问:
Ionic 2 new Row if Index % 3 == 0
ive got a ionic grid with 3 foreach loop's inside eachother
the most outer loop would look like this:

<ion-content padding>
    <ion-grid>
        <ion-row>
            <ion-col>
                <ion-row>
                    <ion-col *ngFor="let field1 of gs.fields; let x = index; trackBy: trackByFn">

                    </ion-col>
                </ion-row>
            </ion-col>
        </ion-row>
    </ion-grid>
</ion-content>```
</div>
</div>
</p>

<p>but i want to get a new row every time x%3 == 0[and if i keep the first  outside of the loop i need x%3 == 0 && x != 0]
i would love to keep everything inside the loop the same and not copy code
<br><strong>Screens at the Bottom</strong><br></p>

<p>my first thought was to do something like:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><ion-content padding>
    <ion-grid>
        <ion-row>
            <ion-col>
                <ion-row>
                    <ion-col *ngFor="let field1 of gs.fields; let x = index; trackBy: trackByFn">
                        <ion-row *ngIf="x%3==0 && x!=0">
                            <!-- More Foreach Loops inside each other-->
                        </ion-row *ngIf="x%3==0 && x!=0">
                    </ion-col>
                </ion-row>
            </ion-col>
        </ion-row>
    </ion-grid>
</ion-content></code>```

x is running in a range from 0 to 8, so </ion-row *ngIf="x%3==0 && x!=0"> as closing tag should be fine because i close the ion-row outside the outter foreach loop. But this isnt loading.

How it is:

How i want it to be:

<ion-content padding>
    <ion-grid>
        <ion-row>
            <ion-col *ngFor="let field1 of gs.fields; let x = index; trackBy: trackByFn">

                    <ion-col *ngFor="let field2 of field1; let y = index; trackBy: trackByFn">
                        <ion-row>
                            <ion-col class="ctr fc tile" *ngFor="let tile of field2; let z = index; trackBy: trackByFn" (click)="playerClick(x,y,z)">
                                {{(tile==0)? ' ': ((tile==1)? 'x' : 'o')}}
                            </ion-col>
                        </ion-row>
                    </ion-col>

                {{(gs.won_fields[x]==1)? 'x' : 'o'}}
            </ion-col>
        </ion-row>
    </ion-grid>
</ion-content>```

答:
ngIf apply for whole element, not just for open or close tag.
You can do like this:

```<code><ion-grid>
    <ion-row>
        <ion-col *ngFor="let item of items; let i = index">
            <ion-row *ngIf="i%3 == 0">
                {{item}}
            </ion-row>
            <div *ngIf="i%3 != 0">
                {{item}}
            </div>
        </ion-col>
    </ion-row>
</ion-grid>
</code>```

Title: Ionic 2 new Row if Index % 3 == 0

Body:
ive got a ionic grid with 3 foreach loop's inside eachother
the most outer loop would look like this:

<ion-content padding>
    <ion-grid>
        <ion-row>
            <ion-col>
                <ion-row>
                    <ion-col *ngFor="let field1 of gs.fields; let x = index; trackBy: trackByFn">

                    </ion-col>
                </ion-row>
            </ion-col>
        </ion-row>
    </ion-grid>
</ion-content>

but i want to get a new row every time x%3 == 0[and if i keep the first  outside of the loop i need x%3 == 0 && x != 0]
i would love to keep everything inside the loop the same and not copy code

Screens at the Bottom

my first thought was to do something like:

<ion-content padding>
    <ion-grid>
        <ion-row>
            <ion-col>
                <ion-row>
                    <ion-col *ngFor="let field1 of gs.fields; let x = index; trackBy: trackByFn">
                        <ion-row *ngIf="x%3==0 && x!=0">

                        </ion-row *ngIf="x%3==0 && x!=0">
                    </ion-col>
                </ion-row>
            </ion-col>
        </ion-row>
    </ion-grid>
</ion-content>

x is running in a range from 0 to 8, so </ion-row *ngIf="x%3==0 && x!=0"> as closing tag should be fine because i close the ion-row outside the outter foreach loop. But this isnt loading.

How it is:

How i want it to be:

<ion-content padding>
    <ion-grid>
        <ion-row>
            <ion-col *ngFor="let field1 of gs.fields; let x = index; trackBy: trackByFn">

                    <ion-col *ngFor="let field2 of field1; let y = index; trackBy: trackByFn">
                        <ion-row>
                            <ion-col class="ctr fc tile" *ngFor="let tile of field2; let z = index; trackBy: trackByFn" (click)="playerClick(x,y,z)">
                                {{(tile==0)? ' ': ((tile==1)? 'x' : 'o')}}
                            </ion-col>
                        </ion-row>
                    </ion-col>

                {{(gs.won_fields[x]==1)? 'x' : 'o'}}
            </ion-col>
        </ion-row>
    </ion-grid>
</ion-content>

Body:
ngIf apply for whole element, not just for open or close tag.
You can do like this:

<ion-grid>
    <ion-row>
        <ion-col *ngFor="let item of items; let i = index">
            <ion-row *ngIf="i%3 == 0">
                {{item}}
            </ion-row>
            <div *ngIf="i%3 != 0">
                {{item}}
            </div>
        </ion-col>
    </ion-row>
</ion-grid>


来源: stackexchange

问:
Redirect in Angular 4.2.2 Programmatically
I'm building a toy app that has a Search page as the default, and then it has an Admin page.  The admin page is called by clicking a button on the Search page.  My code for that process is this:

```<code>  constructor( private searchResultService: SearchService, private router: Router) {
    ....
  }

  goToAdminLogin(ev): void
  {
    this.router.navigate(['adminLogin'])
  }
</code>```

However, on the click of the Button the only thing that changes is the address bar.

In my app.module.ts, I have this:

```<code>RouterModule.forRoot([
  {
    path: 'search',
    redirectTo: '/search',
    pathMatch: 'full'
  },
  {
    path: 'adminLogin',
    component: AdminLoginComponent
  }
])
</code>```

I've checked my console, and I don't see it spewing any error messages.  Does anyone know why my redirect is going nowhere?

Any help is greatly appreciated.

EDIT: Adding the AdminLoginComponent:

My AdminLoginComponent looks like this:

```<code>import {Component, Inject, Input} from '@angular/core';
import {SearchService} from '../services/search.service';
import {SearchResponse} from '../remote/search-response';

@Component({
  selector: 'admin-login-component',
  templateUrl: './admin-login.component.html',
  styleUrls: ['./admin-login.component.css']
})
export class AdminLoginComponent {

  constructor( private searchResultService: SearchService)  {
  }
}
</code>```

My 'admin-login.component.html' is very simple and looks like this:

```<code><div>Hello</div>
</code>```

EDIT: Solution

The solution thanks to Debbie K was to essentially drop my first UI out of my app.component.* and put it in a a sub component, similar to my admin-login setup.  My app.component.html now looks like this:

```<code><router-outlet></router-outlet>
</code>```

答:
Try this:

```<code>this.router.navigate(['/adminLogin'])
</code>```

And set up a hierarchy of router-outlets:

app.component.html

<router-outlet> <-- This one will show anything full page.

home.component.html

<router-outlet> <-- This one will show anything within the header/footer

Does my shorthand here make sense?

ContentLicense: CC BY-SA 3.0

Body:
I'm building a toy app that has a Search page as the default, and then it has an Admin page.  The admin page is called by clicking a button on the Search page.  My code for that process is this:

  constructor( private searchResultService: SearchService, private router: Router) {
    ....
  }

  goToAdminLogin(ev): void
  {
    this.router.navigate(['adminLogin'])
  }

However, on the click of the Button the only thing that changes is the address bar.

In my app.module.ts, I have this:

RouterModule.forRoot([
  {
    path: 'search',
    redirectTo: '/search',
    pathMatch: 'full'
  },
  {
    path: 'adminLogin',
    component: AdminLoginComponent
  }
])

I've checked my console, and I don't see it spewing any error messages.  Does anyone know why my redirect is going nowhere?

Any help is greatly appreciated.

EDIT: Adding the AdminLoginComponent:

My AdminLoginComponent looks like this:

import {Component, Inject, Input} from '@angular/core';
import {SearchService} from '../services/search.service';
import {SearchResponse} from '../remote/search-response';

@Component({
  selector: 'admin-login-component',
  templateUrl: './admin-login.component.html',
  styleUrls: ['./admin-login.component.css']
})
export class AdminLoginComponent {

  constructor( private searchResultService: SearchService)  {
  }
}

My 'admin-login.component.html' is very simple and looks like this:

Hello

EDIT: Solution

The solution thanks to Debbie K was to essentially drop my first UI out of my app.component.* and put it in a a sub component, similar to my admin-login setup.  My app.component.html now looks like this:

<router-outlet></router-outlet>

Body:
Try this:

this.router.navigate(['/adminLogin'])

And set up a hierarchy of router-outlets:

app.component.html

<router-outlet> <-- This one will show anything full page.

home.component.html

<header of menu stuff here>

<router-outlet> <-- This one will show anything within the header/footer

<footer stuff here>

Does my shorthand here make sense?


问:
C on Visual Studio
I'm trying to learn C. As a C# developer, my IDE is Visual Studio. I've heard this is a good environment for C/C++ development. However, it seems no matter what little thing I try to do, intuition fails me. Can someone give good resources for how to either:

learn the ins and out of C in Visual Studio

recommend a better C IDE + compiler

Edit: See also: https://stackoverflow.com/questions/951516/a-good-c-ide

答:
For plain C, I suggest Pelles C. Generates optimized code and supports C99 constructs.

Features:

Support for 32-bit Windows (X86),

64-bit Windows (X64), and Windows Mobile (ARM). Support for the C99 standard.

Integrated source code editor with call tips and symbol browsing. Integrated source-level
debugger. Project management.

Inline assembler for X86 and ARM.

Integrated resource editor. Integrated bitmap, icon and cursor editor. Integrated
animated cursor and video editor.

Integrated hex-dump editor.

Supportfor custom controls in the dialog editor. Support for custom project  wizards.
http://www.smorgasbordet.com/pellesc/

ContentLicense: CC BY-SA 2.5

Title: C on Visual Studio

LastEditorDisplayName: sparkes


问:
RMySQL dbReadTable takes too long
I am using the package RMySQL with DBI package in R.
When I run the code,

```<code>dbReadTable(con, "data")
</code>```

it is taking forever.

I think the table is very big data.
Any ideas on how to speed up this process?

Thanks,

答:
Try to get the database to do as much filtering & processing as possible.  A database has many more ways to optimize operations than R, and isn't constrained by RAM so severely.  It also reduces the amount that has to travel across the network.

Common approaches tactics are

using the WHERE clause to reduce rows

explicitly list (only the necessary) columns, instead of using *

do as much aggregation in SQL as possible (eg, GROUP BY + MAX)

use INSERT queries to write from table to table, so the data doesn't even need to pass through R.

I imagine RMySQL should be faster than the newish odbc package, but it's worth experimenting with.

What's 'forever'?  5 min or 5 hours?  Are things still slow once the data get to R?  If things are still too slow to be feasible, consider escalating to something like sparklyr.

Title: RMySQL dbReadTable takes too long

Body:
I am using the package RMySQL with DBI package in R.
When I run the code,

dbReadTable(con, "data")

it is taking forever.

I think the table is very big data.
Any ideas on how to speed up this process?

Thanks,


问:
LARAVEL webpack
I am using LARAVEL 5.4.

I did versioning of css and js using webpack, which generated mix-manifest.json file in public folder.

While uploading on server , I moved out public folder content to project root folder.

Error - mix manifest does not exist.

Question - how to change manifest path so that it should search manifest.json in root folder.

答:
I have the same issue, but now i think this will help you get ride of that.

but my folder structure a bit different from yours. i had packed the framework in one folder name "framework" and i extracted the public folder to the main directory, in your Cpanel you will have to copy everything inside the laravel public folder and past it direct into the public_HTML. it should look like:

Public_HTML
 - framework (all the laravel file are in this folder)
 - css
 - js
 - images
 - .htaccess
 - favicon.ico
 - index.php
 - mix-manifest.json
 - robots.txt
 - web.config
Note: copy everything in the laravel public folder and past here

now you need to change the index.php file these 2 line

```<code>require __DIR__.'/../bootstrap/autoload.php';

$app = require_once __DIR__.'/../bootstrap/app.php';
</code>```

to

```<code>require __DIR__.'/framework/bootstrap/autoload.php';

$app = require_once __DIR__.'/framework/bootstrap/app.php';
</code>```

Now we continue to edit and change the Mix function from

file path: framework\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php

```<code>if (! function_exists('mix')) {
    /**
     * Get the path to a versioned Mix file.
     *
     * @param  string  $path
     * @param  string  $manifestDirectory
     * @return \Illuminate\Support\HtmlString
     *
     * @throws \Exception
     */
    function mix($path, $manifestDirectory = '')
    {
        static $manifest;

        if (! starts_with($path, '/')) {
            $path = "/{$path}";
        }

        if ($manifestDirectory && ! starts_with($manifestDirectory, '/')) {
            $manifestDirectory = "/{$manifestDirectory}";
        }

        if (file_exists(public_path($manifestDirectory.'/hot'))) {
            return new HtmlString("//localhost:8080{$path}");
        }

        if (! $manifest) {
            if (! file_exists($manifestPath = public_path($manifestDirectory.'/mix-manifest.json'))) {
                throw new Exception('The Mix manifest does not exist.');
            }

            $manifest = json_decode(file_get_contents($manifestPath), true);
        }

        if (! array_key_exists($path, $manifest)) {
            throw new Exception(
                "Unable to locate Mix file: {$path}. Please check your ".
                'webpack.mix.js output paths and try again.'
            );
        }

        return new HtmlString($manifestDirectory.$manifest[$path]);
    }
}
</code>```

To

```<code>if (! function_exists('mix')) {
    /**
     * Get the path to a versioned Mix file.
     *
     * @param  string  $path
     * @param  string  $manifestDirectory
     * @return \Illuminate\Support\HtmlString
     *
     * @throws \Exception
     */
    function mix($path, $manifestDirectory = '/../..')
    {
        static $manifests = [];

        if (! starts_with($path, '/')) {
            $path = "/{$path}";
        }

        if ($manifestDirectory && ! starts_with($manifestDirectory, '')) {
            $manifestDirectory = "{$manifestDirectory}";
        }

        $manifestKey = $manifestDirectory ? $manifestDirectory : '/';

//        if (file_exists(public_path($manifestDirectory.'/hot'))) {
//            return new HtmlString("//localhost:8080{$path}");
//        }

        if (in_array($manifestKey, $manifests)) {
            $manifest = $manifests[$manifestKey];
        } else {
            if (! file_exists($manifestPath = public_path($manifestDirectory.'/mix-manifest.json'))) {
                throw new Exception('The Mix manifest does not exist.');
            }

            $manifests[$manifestKey] = $manifest = json_decode(
                file_get_contents($manifestPath), true
            );
        }

        if (! array_key_exists($path, $manifest)) {
            throw new Exception(
                "Unable to locate Mix file: {$path}. Please check your ".
                'webpack.mix.js output paths and try again.'
            );
        }

        return new HtmlString($manifestDirectory.$manifest[$path]);
    }
}
</code>```

Hope this help,

Title: LARAVEL webpack

Body:
I have the same issue, but now i think this will help you get ride of that.

but my folder structure a bit different from yours. i had packed the framework in one folder name "framework" and i extracted the public folder to the main directory, in your Cpanel you will have to copy everything inside the laravel public folder and past it direct into the public_HTML. it should look like:

Public_HTML
 - framework (all the laravel file are in this folder)
 - css
 - js
 - images
 - .htaccess
 - favicon.ico
 - index.php
 - mix-manifest.json
 - robots.txt
 - web.config
Note: copy everything in the laravel public folder and past here

now you need to change the index.php file these 2 line

require __DIR__.'/../bootstrap/autoload.php';

$app = require_once __DIR__.'/../bootstrap/app.php';

to

require __DIR__.'/framework/bootstrap/autoload.php';

$app = require_once __DIR__.'/framework/bootstrap/app.php';

Now we continue to edit and change the Mix function from

file path: framework\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php

if (! function_exists('mix')) {
    /**
     * Get the path to a versioned Mix file.
     *
     * @param  string  $path
     * @param  string  $manifestDirectory
     * @return \Illuminate\Support\HtmlString
     *
     * @throws \Exception
     */
    function mix($path, $manifestDirectory = '')
    {
        static $manifest;

        if (! starts_with($path, '/')) {
            $path = "/{$path}";
        }

        if ($manifestDirectory && ! starts_with($manifestDirectory, '/')) {
            $manifestDirectory = "/{$manifestDirectory}";
        }

        if (file_exists(public_path($manifestDirectory.'/hot'))) {
            return new HtmlString("//localhost:8080{$path}");
        }

        if (! $manifest) {
            if (! file_exists($manifestPath = public_path($manifestDirectory.'/mix-manifest.json'))) {
                throw new Exception('The Mix manifest does not exist.');
            }

            $manifest = json_decode(file_get_contents($manifestPath), true);
        }

        if (! array_key_exists($path, $manifest)) {
            throw new Exception(
                "Unable to locate Mix file: {$path}. Please check your ".
                'webpack.mix.js output paths and try again.'
            );
        }

        return new HtmlString($manifestDirectory.$manifest[$path]);
    }
}

To

if (! function_exists('mix')) {
    /**
     * Get the path to a versioned Mix file.
     *
     * @param  string  $path
     * @param  string  $manifestDirectory
     * @return \Illuminate\Support\HtmlString
     *
     * @throws \Exception
     */
    function mix($path, $manifestDirectory = '/../..')
    {
        static $manifests = [];

        if (! starts_with($path, '/')) {
            $path = "/{$path}";
        }

        if ($manifestDirectory && ! starts_with($manifestDirectory, '')) {
            $manifestDirectory = "{$manifestDirectory}";
        }

        $manifestKey = $manifestDirectory ? $manifestDirectory : '/';

//        if (file_exists(public_path($manifestDirectory.'/hot'))) {
//            return new HtmlString("//localhost:8080{$path}");
//        }

        if (in_array($manifestKey, $manifests)) {
            $manifest = $manifests[$manifestKey];
        } else {
            if (! file_exists($manifestPath = public_path($manifestDirectory.'/mix-manifest.json'))) {
                throw new Exception('The Mix manifest does not exist.');
            }

            $manifests[$manifestKey] = $manifest = json_decode(
                file_get_contents($manifestPath), true
            );
        }

        if (! array_key_exists($path, $manifest)) {
            throw new Exception(
                "Unable to locate Mix file: {$path}. Please check your ".
                'webpack.mix.js output paths and try again.'
            );
        }

        return new HtmlString($manifestDirectory.$manifest[$path]);
    }
}

Hope this help,


问:
CookieManager not work on background service when closed from recent list
This method not working on Android when the app is closed from recent list, and all others code is working fine.

```<code>CookieManager.getInstance().getCookie(COOKIES)
</code>```

I am using Services to execute background processes.

答:
Use:

```<code>CookieManager cookieManager = CookieManager.getInstance();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager.createInstance(this);
        }
        cookieManager.setAcceptCookie(true);
</code>```

and will be alright.

Body:
This method not working on Android when the app is closed from recent list, and all others code is working fine.

CookieManager.getInstance().getCookie(COOKIES)

I am using Services to execute background processes.

Body:
Use:

CookieManager cookieManager = CookieManager.getInstance();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            CookieSyncManager.createInstance(this);
        }
        cookieManager.setAcceptCookie(true);

and will be alright.


问:
Django REST Framework Filter Queryset Based On URL
When user visits "baseurl/companies/6/inquiry/", I know that the company_id is 6.

Then user then has the option to create an inquiry with specific products, but should only see the products that belong to company 6.

Here's my viewset:

```<code>class InquiryViewSet(viewsets.ModelViewSet):
    queryset = Inquiry.objects.all()
    serializer_class = InquirySerializer

    def get_serializer(self, *args, **kwargs):
        serializer_class = self.get_serializer_class()
        context = self.get_serializer_context()
        return serializer_class(*args, company_id=self.kwargs['company_id'], context=context, **kwargs)
</code>```

Here's my serializer:

```<code>class InquirySerializer(serializers.ModelSerializer):
    def __init__(self, *args, company_id=None, **kwargs):
        super(InquirySerializer, self).__init__(*args, **kwargs)
        company_set = Company.objects.filter(pk=company_id)
        self.fields['company'].queryset = company_set

    company = serializers.HyperlinkedRelatedField(many=False,
                                                  view_name='company-detail',
                                                  queryset=Company.objects.all())
    inquirer = UserPKField(many=False)
    is_anonymous = serializers.BooleanField
    product_rows = CompanyProductField(many=True, company_id= 'Want to access company_id in __init__')

    class Meta:
        model = Inquiry
        fields = ('pk', 'company', 'inquirer_email', 'inquirer', 'is_anonymous', 'inquiry_date', 'product_rows')
        read_only_fields = ('inquirer', 'inquiry_date')
</code>```

And here's the CompanyProductField

```<code>class CompanyProductField(serializers.PrimaryKeyRelatedField):
    def __init__(self, *args, company_id=None, **kwargs):
        super(CompanyProductField, self).__init__(*args, **kwargs)
        self.company_id = company_id

    def get_queryset(self):
        product_query = Q(company__pk=self.company_id)
        return Product.objects.filter(product_query)
</code>```

There has to be a simple way I can access the company_id that's already in InquirySerializer's init method and just pass that on, but I'm stumped.

答:
class InquirySerializer(serializers.ModelSerializer):
    def __init__(self, *args, **kwargs):
        company_id = kwargs.pop('company_id')
        self.company_id = company_id
        super().__init__(*args, **kwargs)

    product_rows = CompanyProductField(many=True)

class CompanyProductField(serializers.PrimaryKeyRelatedField):
    def get_queryset(self):
        return Product.objects.filter(company_id=self.root.company_id)
```

The self.root attribute on the CompanyProductField class will refer to the instance of InquirySerializer in this case.

Body:
When user visits "baseurl/companies/6/inquiry/", I know that the company_id is 6.

Then user then has the option to create an inquiry with specific products, but should only see the products that belong to company 6.

Here's my viewset:

class InquiryViewSet(viewsets.ModelViewSet):
    queryset = Inquiry.objects.all()
    serializer_class = InquirySerializer

    def get_serializer(self, *args, **kwargs):
        serializer_class = self.get_serializer_class()
        context = self.get_serializer_context()
        return serializer_class(*args, company_id=self.kwargs['company_id'], context=context, **kwargs)

Here's my serializer:

class InquirySerializer(serializers.ModelSerializer):
    def __init__(self, *args, company_id=None, **kwargs):
        super(InquirySerializer, self).__init__(*args, **kwargs)
        company_set = Company.objects.filter(pk=company_id)
        self.fields['company'].queryset = company_set

    company = serializers.HyperlinkedRelatedField(many=False,
                                                  view_name='company-detail',
                                                  queryset=Company.objects.all())
    inquirer = UserPKField(many=False)
    is_anonymous = serializers.BooleanField
    product_rows = CompanyProductField(many=True, company_id= 'Want to access company_id in __init__')

    class Meta:
        model = Inquiry
        fields = ('pk', 'company', 'inquirer_email', 'inquirer', 'is_anonymous', 'inquiry_date', 'product_rows')
        read_only_fields = ('inquirer', 'inquiry_date')

And here's the CompanyProductField

class CompanyProductField(serializers.PrimaryKeyRelatedField):
    def __init__(self, *args, company_id=None, **kwargs):
        super(CompanyProductField, self).__init__(*args, **kwargs)
        self.company_id = company_id

    def get_queryset(self):
        product_query = Q(company__pk=self.company_id)
        return Product.objects.filter(product_query)

There has to be a simple way I can access the company_id that's already in InquirySerializer's init method and just pass that on, but I'm stumped.

Body:
class InquirySerializer(serializers.ModelSerializer):
    def __init__(self, *args, **kwargs):
        company_id = kwargs.pop('company_id')
        self.company_id = company_id
        super().__init__(*args, **kwargs)

    product_rows = CompanyProductField(many=True)

class CompanyProductField(serializers.PrimaryKeyRelatedField):
    def get_queryset(self):
        return Product.objects.filter(company_id=self.root.company_id)

The self.root attribute on the CompanyProductField class will refer to the instance of InquirySerializer in this case.


问:
Elegant way to combine multiple collections of elements?
Say I have an arbitrary number of collections, each containing objects of the same type (for example, List<int> foo and List<int> bar). If these collections were themselves in a collection (e.g., of type List<List<int>>, I could use SelectMany to combine them all into one collection.

However, if these collections are not already in the same collection, it's my impression that I'd have to write a method like this:

```<code>public static IEnumerable<T> Combine<T>(params ICollection<T>[] toCombine)
{
   return toCombine.SelectMany(x => x);
}
</code>```

Which I'd then call like this:

```<code>var combined = Combine(foo, bar);
</code>```

Is there a clean, elegant way to combine (any number of) collections without having to write a utility method like Combine above? It seems simple enough that there should be a way to do it in LINQ, but perhaps not.

答:
Given that you're starting with a bunch of separate collections, I think your solution is rather elegant.  You're going to have to do something to stitch them together.

It would be more convenient syntactically to make an extension method out of your Combine method, which would make it available anywhere you go.

Body:
Say I have an arbitrary number of collections, each containing objects of the same type (for example, List<int> foo and List<int> bar). If these collections were themselves in a collection (e.g., of type List<List<int>>, I could use SelectMany to combine them all into one collection.

However, if these collections are not already in the same collection, it's my impression that I'd have to write a method like this:

public static IEnumerable<T> Combine<T>(params ICollection<T>[] toCombine)
{
   return toCombine.SelectMany(x => x);
}

Which I'd then call like this:

var combined = Combine(foo, bar);

Is there a clean, elegant way to combine (any number of) collections without having to write a utility method like Combine above? It seems simple enough that there should be a way to do it in LINQ, but perhaps not.


问:
Can't center image in the second row
I have one row of three images. They are displaying equally spaced and centered as needed. But then I have a row beneath that of one image and I can't get it to move to align centered of the first row.

I've tried all of the suggestions I could find, like margin:0 auto; width:90%, but that image in the second row stays aligned left.

Would someone please point out my mistake? Here is the jsfiddle and here's the code I am using.

.banner_set {
  width: 100%;
  overflow: hidden
}

.nav-align {
  display: -webkit-flex;
  display: flex;
  -webkit-reorder-direction: row-reverse;
  width: 100%;
  height: auto;
  list-style: none;
}

.nav-items {
  /* width: 33%; */
  margin: 24px;
  flex: 1;
  /* NEW */
  box-shadow: 2px 4px 6px rgba(0, 0, 0, 0.5)
}

.nav-items-wide {
  width: 100% margin: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="banner_set">
  <ul class="nav navbar-nav nav-align">
    <li class="nav-items">

        <img src="http://www.exampe.com/images/img1.jpg" class="img-responsive" width="80" height="40">
    </li>
    <li class="nav-items">

        <img src="images/img2.jpg" class="img-responsive" width="80" height="40">
    </li>
    <li class="nav-items">

        <img src="http://www.exampe.com/images/img3.jpg" class="img-responsive" width="80" height="40">
    </li>
  </ul>
</div>

<div class="banner_set">
  <ul class="nav navbar-nav nav-align">
    <li class="nav-items-wide">
      href="http://www.example.com/b4">
        <img src="http://www.exampe.com/images/img4.jpg" class="img-responsive" width="125" height="40">
    </li>
  </ul>
</div></code>```

答:
Add justify-content: space-around; or justify-content: center; for class nav-align.

.banner_set {
  width: 100%;
  overflow: hidden
}

.nav-align {
  display: -webkit-flex;
  display: flex;
  -webkit-reorder-direction: row-reverse;
  width: 100%;
  height: auto;
  list-style: none;
  justify-content: space-around;
}

.nav-items {
  /* width: 33%; */
  margin: 24px;
  flex: 1;
  /* NEW */
  box-shadow: 2px 4px 6px rgba(0, 0, 0, 0.5)
}

.nav-items-wide {
  width: 100% margin: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="banner_set">
  <ul class="nav navbar-nav nav-align">
    <li class="nav-items">

        <img src="http://www.exampe.com/images/img1.jpg" class="img-responsive" width="80" height="40">
    </li>
    <li class="nav-items">

        <img src="images/img2.jpg" class="img-responsive" width="80" height="40">
    </li>
    <li class="nav-items">

        <img src="http://www.exampe.com/images/img3.jpg" class="img-responsive" width="80" height="40">
    </li>
  </ul>
</div>

<div class="banner_set">
  <ul class="nav navbar-nav nav-align">
    <li class="nav-items-wide">
      href="http://www.example.com/b4">
        <img src="http://www.exampe.com/images/img4.jpg" class="img-responsive" width="125" height="40">
    </li>
  </ul>
</div></code>```

Title: Can't center image in the second row

Body:
Add justify-content: space-around; or justify-content: center; for class nav-align.

.banner_set {
  width: 100%;
  overflow: hidden
}

.nav-align {
  display: -webkit-flex;
  display: flex;
  -webkit-reorder-direction: row-reverse;
  width: 100%;
  height: auto;
  list-style: none;
  justify-content: space-around;
}

.nav-items {
  /* width: 33%; */
  margin: 24px;
  flex: 1;
  /* NEW */
  box-shadow: 2px 4px 6px rgba(0, 0, 0, 0.5)
}

.nav-items-wide {
  width: 100% margin: 0px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="banner_set">
  <ul class="nav navbar-nav nav-align">
    <li class="nav-items">
      <a href="http://www.example.com/b1">
        <img src="http://www.exampe.com/images/img1.jpg" class="img-responsive" width="80" height="40"></a>
    </li>
    <li class="nav-items">
      <a href="http://www.example.com/b2">
        <img src="images/img2.jpg" class="img-responsive" width="80" height="40"></a>
    </li>
    <li class="nav-items">
      <a href="http://www.example.com/b3">
        <img src="http://www.exampe.com/images/img3.jpg" class="img-responsive" width="80" height="40">
    </li>
  </ul>
</div>

<div class="banner_set">
  <ul class="nav navbar-nav nav-align">
    <li class="nav-items-wide">
      <a href="http://www.example.com/b4">
        <img src="http://www.exampe.com/images/img4.jpg" class="img-responsive" width="125" height="40"></a>
    </li>
  </ul>
</div>


问:
How to multiply each number in array by 2 in ruby
I have an array with characters, numbers and float values.

```<code> a[] = {'a',2,2.5}
</code>```

I have to multiply each integer and float by 2 and no operation should be done on character.

My solution -

```<code>def self.double_numbers(input)
        input.map do |input_element|
            if input_element.is_a? Integer
                input_element.to_i * 2
            elsif input_element.is_a? Float
                input_element.to_Float * 2
            end
        end
    end
</code>```

It is not working, for input

```<code>   a[] = {'a',2,2.5}
</code>```

It is returning

0 4 4

答:
You could use map and over each element in the array check if is Numeric, and if so, then multiply it by 2, then you can compact your result for nil values:

```<code>p ['a', 2, 2.5].map{|e| e * 2 if e.is_a? Numeric}.compact
# => [4, 5.0]
</code>```

If you want to leave the elements which won't be applied the *2 operation, then:

```<code>p ['a', 2, 2.5].map{|e| e.is_a?(Numeric) ? e * 2 : e}
</code>```

Also you could use grep to simplify the checking, and then map your only-numeric values:

```<code>p ['a', 2, 2.5].grep(Numeric).map{|e| e*2}
# => [4, 5.0]
</code>```

I don't know the side effects of doing this, but looks good (of course if the output won't be only Numeric objects):

```<code>class Numeric
  def duplicate
    self * 2
  end
end

p ['a', 2, 2.5].grep(Numeric).map(&:duplicate)
</code>```

Or also:

```<code>p ['a', 2, 2.5].grep(Numeric).map(&2.method(:*))
# [4, 5.0]
</code>```

Body:
I have an array with characters, numbers and float values.

 a[] = {'a',2,2.5}

I have to multiply each integer and float by 2 and no operation should be done on character.

My solution -

def self.double_numbers(input)
        input.map do |input_element|
            if input_element.is_a? Integer
                input_element.to_i * 2
            elsif input_element.is_a? Float
                input_element.to_Float * 2
            end
        end
    end

It is not working, for input

   a[] = {'a',2,2.5}

It is returning

0 4 4

Body:
You could use map and over each element in the array check if is Numeric, and if so, then multiply it by 2, then you can compact your result for nil values:

p ['a', 2, 2.5].map{|e| e * 2 if e.is_a? Numeric}.compact
# => [4, 5.0]

If you want to leave the elements which won't be applied the *2 operation, then:

p ['a', 2, 2.5].map{|e| e.is_a?(Numeric) ? e * 2 : e}

Also you could use grep to simplify the checking, and then map your only-numeric values:

p ['a', 2, 2.5].grep(Numeric).map{|e| e*2}
# => [4, 5.0]

I don't know the side effects of doing this, but looks good (of course if the output won't be only Numeric objects):

class Numeric
  def duplicate
    self * 2
  end
end

p ['a', 2, 2.5].grep(Numeric).map(&:duplicate)

Or also:

p ['a', 2, 2.5].grep(Numeric).map(&2.method(:*))
# [4, 5.0]


问:
How to run war file on machine of client from another country without having error related to clock/ signature?
I have eclispe maven project based on Azure services. I want to run it on client's machine who is from another country, so have different time zone.

When I install eclipse on their machine and run all the services, those works fine. But when I added war to apache folder , after running it, it's giving error like :

```<code>Make sure the value of Authorization header is formed correctly including the signature.
at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:)
</code>```

I came to this link and I think I am having almost same type of error :

StorageException for azure blob with java

Please tell me how to solve this and how to make clock 'slow' as mentioned in the answer of provided link.

Here is the code : (See the code in else loop from first method. It's blob related code.)

```<code>@Override
    public JSONObject syncFiles(JSONObject jsonInput) throws InvalidKeyException, URISyntaxException {
        if (jsonInput.containsKey("accountName")) {
            CloudFileClient fileClient = null;
            String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="
                    + jsonInput.get("accountName") + ";" + "AccountKey=" + jsonInput.get("accountKey");
            System.out.println(storageConnectionString);
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
            JSONObject jsonOutput = new JSONObject();
            ArrayList fileList = new ArrayList<>();
            try {
                // fileClient =
                // FileClientProvider.getFileClientReference(jsonOutput);
                fileClient = storageAccount.createCloudFileClient();
                String directoryName = jsonInput.get("directoryStructure").toString();

                String[] directoryNameArray = directoryName.split("\\s*/\\s*");
                System.out.println(directoryNameArray.length);

                CloudFileShare share = fileClient.getShareReference(directoryNameArray[0].toLowerCase()
                        .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                if (share.createIfNotExists()) {
                    System.out.println("New share created named as " + directoryNameArray[0].toLowerCase()
                            .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                }
                CloudFileDirectory rootDir = share.getRootDirectoryReference();
                for (int i = 0; i < directoryNameArray.length; i++) {
                    String directoryToCreate = directoryNameArray[i];
                    CloudFileDirectory directory = rootDir.getDirectoryReference(directoryToCreate);

                    String directoryNameToListFiles = directory.getName();
                    if (i == directoryNameArray.length - 1) {
                        for (ListFileItem fileItem : directory.listFilesAndDirectories()) {
                            boolean isDirectory;
                            if (isDirectory = fileItem.getClass() == CloudFileDirectory.class) {
                                System.out.println("Directory Exists Here");
                            } else {
                                System.out.println("Name with files :" + fileItem.getUri().toString());
                                String downloadLocation = "/home/zcon/AzureDownloadedFiles";
                                String fileName[] = fileItem.getUri().toString().split("\\s*/\\s*");
                                for (int j = 0; j < fileName.length; j++) {
                                    if (j == fileName.length - 1) {
                                        String fileNameWithExtension = fileName[j];
                                        File f = new File(downloadLocation + "/" + fileNameWithExtension);
                                        String DownloadTo = f.toString();
                                        f.createNewFile();
                                        CloudFile cloudFile = directory
                                                .getFileReference(fileNameWithExtension.replaceAll("%20", " "));
                                        System.out.println("fileName===========" + fileNameWithExtension);
                                        String tokenKey = testFileSAS(share, cloudFile);
                                        cloudFile.downloadToFile(DownloadTo);
                                        fileList.add(fileItem.getUri().toString() + "?" + tokenKey);
                                        f.delete();
                                    }
                                }
                            }
                        }
                    }
                    rootDir = directory;
                }
                ArrayList fileNamesList = new ArrayList<>();
                for (int i = 0; i < fileList.size(); i++) {
                    String fileName[] = fileList.get(i).toString().split("\\s*/\\s*");
                    for (int j = 0; j < fileName.length; j++) {
                        if (j == fileName.length - 1) {
                            String fileNameReturn = fileName[j];
                            String[] fileNameReturnArray = fileNameReturn.split("\\.");
                            fileNamesList.add(fileNameReturnArray[0].replace("%20", " "));
                        }
                    }
                }
                jsonOutput.put("fileNamesList", fileNamesList);
                jsonOutput.put("fileList", fileList);
                jsonOutput.put("status", "successful");
            } catch (Exception e) {
                System.out.println("Exception is " + e.toString());
                jsonOutput.put("status", "unsuccessful");
                jsonOutput.put("exception", e.toString());
                e.printStackTrace();
            }
            return jsonOutput;
        } else {

            CloudBlobClient blobClient = null;
            String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="
                    + jsonInput.get("blobAccountName") + ";" + "AccountKey=" + jsonInput.get("blobAccountKey");
            System.out.println(storageConnectionString);
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
            JSONObject jsonOutput = new JSONObject();
            ArrayList fileList = new ArrayList<>();
            ArrayList fileNamesList = new ArrayList<>();
            ArrayList blobItemList = new ArrayList<>();

            try {
                blobClient = storageAccount.createCloudBlobClient();
                String directoryName = jsonInput.get("directoryStructure").toString();
                String[] directoryNameArray = directoryName.split("\\s*/\\s*");
                CloudBlobContainer container = blobClient.getContainerReference(directoryNameArray[0].toLowerCase()
                        .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                if (container.createIfNotExists()) {
                    System.out.println("New share created named as " + directoryNameArray[0].toLowerCase()
                            .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                }
                // CloudBlockBlob blob =
                // container.getBlockBlobReference(jsonInput.get("directoryStructure")+"/"+jsonInput.get("fileToCopy"));
                CloudBlobDirectory directoryOfFile = container
                        .getDirectoryReference(jsonInput.get("directoryStructure").toString());
                for (ListBlobItem blobItem : directoryOfFile.listBlobs()) {
                    // System.out.println(blobItem.getUri());
                    // fileList.add(blobItem.getUri());
                    blobItemList.add(blobItem);

                }

                for(int  q= 0; q<blobItemList.size(); q++){
                    if(blobItemList.get(q).getClass()==CloudBlobDirectory.class)
                    {
                        blobItemList.remove(q);
                    }
                }
                System.out.println(blobItemList);
                for (int l = 0; l < blobItemList.size(); l++) {
                    CloudBlob blob = (CloudBlob) blobItemList.get(l);
                    if (blob.getUri().toString().contains("Temp.txt")) {
                        System.out.println("Temp file was skipped");
                    } else {
                        String tokenKey = testBlobSaS(blob, container);
                        fileList.add(blob.getUri().toString() + "?" + tokenKey);
                    }
                }
                System.out.println("size of blobItemList is=============" + blobItemList.size());

                for (int k = 0; k < fileList.size(); k++) {
                    String fileItem = fileList.get(k).toString();
                    String fileName[] = fileItem.split("\\s*/\\s*");

                    for (int j = 0; j < fileName.length; j++) {
                        if (j == fileName.length - 1) {
                            String fileNameWithExtension = fileName[j];
                            String[] parts = fileNameWithExtension.split("\\?");
                            System.out.println("fileName===========" + fileNameWithExtension);
                            fileNamesList.add(parts[0].replace("%20", " "));
                        }
                    }
                }
                jsonOutput.put("fileList", fileList);
                jsonOutput.put("fileNamesList", fileNamesList);
                jsonOutput.put("status", "successful");
                System.out.println(fileList);
                return jsonOutput;
            } catch (Exception e) {
                System.out.println("Exception is " + e.toString());
                jsonOutput.put("status", "unsuccessful");
                jsonOutput.put("exception", e.toString());
                e.printStackTrace();
            }
            return jsonOutput;
        }

    }
</code>```

Method to create BlobSAS :

```<code>@Test
    // @Category(SlowTests.class)
    public String testBlobSaS(CloudBlob blob, CloudBlobContainer container) throws InvalidKeyException,
            IllegalArgumentException, StorageException, URISyntaxException, InterruptedException {
        SharedAccessBlobPolicy sp = createSharedAccessBlobPolicy(
                EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.LIST), 100);
        BlobContainerPermissions perms = new BlobContainerPermissions();

        perms.getSharedAccessPolicies().put("readperm", sp);
        container.uploadPermissions(perms);
        // Thread.sleep(30000);
        String sas = blob.generateSharedAccessSignature(sp, null);

        CloudBlockBlob sasBlob = new CloudBlockBlob(
                new URI(blob.getUri().toString() + "?" + blob.generateSharedAccessSignature(null, "readperm")));
        sasBlob.download(new ByteArrayOutputStream());

        // do not give the client and check that the new blob's client has the
        // correct perms
        CloudBlob blobFromUri = new CloudBlockBlob(
                PathUtility.addToQuery(blob.getStorageUri(), blob.generateSharedAccessSignature(null, "readperm")));
        assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
                blobFromUri.getServiceClient().getCredentials().getClass().toString());

        // create credentials from sas
        StorageCredentials creds = new StorageCredentialsSharedAccessSignature(
                blob.generateSharedAccessSignature(null, "readperm"));
        CloudBlobClient bClient = new CloudBlobClient(sasBlob.getServiceClient().getStorageUri(), creds);

        CloudBlockBlob blobFromClient = bClient.getContainerReference(blob.getContainer().getName())
                .getBlockBlobReference(blob.getName());
        assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
                blobFromClient.getServiceClient().getCredentials().getClass().toString());
        assertEquals(bClient, blobFromClient.getServiceClient());
        return sas;

    }
</code>```

Method to create shared access blob policy :

```<code>private final static SharedAccessBlobPolicy createSharedAccessBlobPolicy(EnumSet<SharedAccessBlobPermissions> sap,
            int expireTimeInSeconds) {

        Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        cal.setTime(new Date());
        cal.add(Calendar.YEAR, expireTimeInSeconds);
        SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
        policy.setPermissions(sap);
        policy.setSharedAccessExpiryTime(cal.getTime());
        return policy;

    }
</code>```

What changes I should make here?

答:
I have faced similar problem before. What you need to do is , make your code comfortable for all the time zones like GMT,IST,EST etc. Because when you upload war in server of another country, your code must be 'clever' enough to understand time zone of that country !

So here is what you can do :

Step 1:

In third part of your code , try replaceing "UTC" by your client machine's timezone like GMT,EST etc.

If that works (and I am pretty much sure that it will work fine) , go for

Step 2:

First of all we will code something that gives you current time zone in String  like "Indian Standard Time" or "European Standard Time" etc.

Then, we will pick only first letters from all words and make a String like "IST" or "EST".

At last, we will pass this String at place where you wrote "UTC" in third part of your code.

So, here is the code :

```<code>private final static SharedAccessBlobPolicy createSharedAccessBlobPolicy(EnumSet<SharedAccessBlobPermissions> sap,
            int expireTimeInSeconds) {
        Calendar now = Calendar.getInstance();
        TimeZone timeZone = now.getTimeZone();
        System.out.println("Current TimeZone is : " + timeZone.getDisplayName());
        String x = timeZone.getDisplayName();
        String[] myName = x.split(" ");
        String s = "";
        ArrayList zoneArray = new ArrayList<>();
        char zone = 0;
        for (int i = 0; i < myName.length; i++) {
            s = myName[i];
            System.out.print(s.charAt(0));
            zone = s.charAt(0);
            zoneArray.add(zone);
        }
        String timeZoneCurrent = s;
        String timeZoneDynamic = zoneArray.toString().replace(",", "").replace(" ", "").replace("[", "").replace("]",
                "");
        System.out.println("Value of S==========" + timeZoneDynamic);
        Calendar cal = new GregorianCalendar(TimeZone.getTimeZone(timeZoneDynamic));
        cal.setTime(new Date());
        cal.add(Calendar.YEAR, expireTimeInSeconds);
        SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
        policy.setPermissions(sap);
        policy.setSharedAccessExpiryTime(cal.getTime());
        return policy;
    }
</code>```

In this, timeZoneDynamic has values like "IST" , "GMT" etc. This logic must work. If have any error, post it in edit. Hope that will work.

Body:
I have eclispe maven project based on Azure services. I want to run it on client's machine who is from another country, so have different time zone.

When I install eclipse on their machine and run all the services, those works fine. But when I added war to apache folder , after running it, it's giving error like :

Make sure the value of Authorization header is formed correctly including the signature.
at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:)

I came to this link and I think I am having almost same type of error :

StorageException for azure blob with java

Please tell me how to solve this and how to make clock 'slow' as mentioned in the answer of provided link.

Here is the code : (See the code in else loop from first method. It's blob related code.)

@Override
    public JSONObject syncFiles(JSONObject jsonInput) throws InvalidKeyException, URISyntaxException {
        if (jsonInput.containsKey("accountName")) {
            CloudFileClient fileClient = null;
            String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="
                    + jsonInput.get("accountName") + ";" + "AccountKey=" + jsonInput.get("accountKey");
            System.out.println(storageConnectionString);
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
            JSONObject jsonOutput = new JSONObject();
            ArrayList fileList = new ArrayList<>();
            try {
                // fileClient =
                // FileClientProvider.getFileClientReference(jsonOutput);
                fileClient = storageAccount.createCloudFileClient();
                String directoryName = jsonInput.get("directoryStructure").toString();

                String[] directoryNameArray = directoryName.split("\\s*/\\s*");
                System.out.println(directoryNameArray.length);

                CloudFileShare share = fileClient.getShareReference(directoryNameArray[0].toLowerCase()
                        .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                if (share.createIfNotExists()) {
                    System.out.println("New share created named as " + directoryNameArray[0].toLowerCase()
                            .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                }
                CloudFileDirectory rootDir = share.getRootDirectoryReference();
                for (int i = 0; i < directoryNameArray.length; i++) {
                    String directoryToCreate = directoryNameArray[i];
                    CloudFileDirectory directory = rootDir.getDirectoryReference(directoryToCreate);

                    String directoryNameToListFiles = directory.getName();
                    if (i == directoryNameArray.length - 1) {
                        for (ListFileItem fileItem : directory.listFilesAndDirectories()) {
                            boolean isDirectory;
                            if (isDirectory = fileItem.getClass() == CloudFileDirectory.class) {
                                System.out.println("Directory Exists Here");
                            } else {
                                System.out.println("Name with files :" + fileItem.getUri().toString());
                                String downloadLocation = "/home/zcon/AzureDownloadedFiles";
                                String fileName[] = fileItem.getUri().toString().split("\\s*/\\s*");
                                for (int j = 0; j < fileName.length; j++) {
                                    if (j == fileName.length - 1) {
                                        String fileNameWithExtension = fileName[j];
                                        File f = new File(downloadLocation + "/" + fileNameWithExtension);
                                        String DownloadTo = f.toString();
                                        f.createNewFile();
                                        CloudFile cloudFile = directory
                                                .getFileReference(fileNameWithExtension.replaceAll("%20", " "));
                                        System.out.println("fileName===========" + fileNameWithExtension);
                                        String tokenKey = testFileSAS(share, cloudFile);
                                        cloudFile.downloadToFile(DownloadTo);
                                        fileList.add(fileItem.getUri().toString() + "?" + tokenKey);
                                        f.delete();
                                    }
                                }
                            }
                        }
                    }
                    rootDir = directory;
                }
                ArrayList fileNamesList = new ArrayList<>();
                for (int i = 0; i < fileList.size(); i++) {
                    String fileName[] = fileList.get(i).toString().split("\\s*/\\s*");
                    for (int j = 0; j < fileName.length; j++) {
                        if (j == fileName.length - 1) {
                            String fileNameReturn = fileName[j];
                            String[] fileNameReturnArray = fileNameReturn.split("\\.");
                            fileNamesList.add(fileNameReturnArray[0].replace("%20", " "));
                        }
                    }
                }
                jsonOutput.put("fileNamesList", fileNamesList);
                jsonOutput.put("fileList", fileList);
                jsonOutput.put("status", "successful");
            } catch (Exception e) {
                System.out.println("Exception is " + e.toString());
                jsonOutput.put("status", "unsuccessful");
                jsonOutput.put("exception", e.toString());
                e.printStackTrace();
            }
            return jsonOutput;
        } else {

            CloudBlobClient blobClient = null;
            String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName="
                    + jsonInput.get("blobAccountName") + ";" + "AccountKey=" + jsonInput.get("blobAccountKey");
            System.out.println(storageConnectionString);
            CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);
            JSONObject jsonOutput = new JSONObject();
            ArrayList fileList = new ArrayList<>();
            ArrayList fileNamesList = new ArrayList<>();
            ArrayList blobItemList = new ArrayList<>();

            try {
                blobClient = storageAccount.createCloudBlobClient();
                String directoryName = jsonInput.get("directoryStructure").toString();
                String[] directoryNameArray = directoryName.split("\\s*/\\s*");
                CloudBlobContainer container = blobClient.getContainerReference(directoryNameArray[0].toLowerCase()
                        .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                if (container.createIfNotExists()) {
                    System.out.println("New share created named as " + directoryNameArray[0].toLowerCase()
                            .replaceAll("[-+.^:,!@#$%&*()_~`]", "").replaceAll("\\s+", ""));
                }
                // CloudBlockBlob blob =
                // container.getBlockBlobReference(jsonInput.get("directoryStructure")+"/"+jsonInput.get("fileToCopy"));
                CloudBlobDirectory directoryOfFile = container
                        .getDirectoryReference(jsonInput.get("directoryStructure").toString());
                for (ListBlobItem blobItem : directoryOfFile.listBlobs()) {
                    // System.out.println(blobItem.getUri());
                    // fileList.add(blobItem.getUri());
                    blobItemList.add(blobItem);

                }

                for(int  q= 0; q<blobItemList.size(); q++){
                    if(blobItemList.get(q).getClass()==CloudBlobDirectory.class)
                    {
                        blobItemList.remove(q);
                    }
                }
                System.out.println(blobItemList);
                for (int l = 0; l < blobItemList.size(); l++) {
                    CloudBlob blob = (CloudBlob) blobItemList.get(l);
                    if (blob.getUri().toString().contains("Temp.txt")) {
                        System.out.println("Temp file was skipped");
                    } else {
                        String tokenKey = testBlobSaS(blob, container);
                        fileList.add(blob.getUri().toString() + "?" + tokenKey);
                    }
                }
                System.out.println("size of blobItemList is=============" + blobItemList.size());

                for (int k = 0; k < fileList.size(); k++) {
                    String fileItem = fileList.get(k).toString();
                    String fileName[] = fileItem.split("\\s*/\\s*");

                    for (int j = 0; j < fileName.length; j++) {
                        if (j == fileName.length - 1) {
                            String fileNameWithExtension = fileName[j];
                            String[] parts = fileNameWithExtension.split("\\?");
                            System.out.println("fileName===========" + fileNameWithExtension);
                            fileNamesList.add(parts[0].replace("%20", " "));
                        }
                    }
                }
                jsonOutput.put("fileList", fileList);
                jsonOutput.put("fileNamesList", fileNamesList);
                jsonOutput.put("status", "successful");
                System.out.println(fileList);
                return jsonOutput;
            } catch (Exception e) {
                System.out.println("Exception is " + e.toString());
                jsonOutput.put("status", "unsuccessful");
                jsonOutput.put("exception", e.toString());
                e.printStackTrace();
            }
            return jsonOutput;
        }

    }

Method to create BlobSAS :

@Test
    // @Category(SlowTests.class)
    public String testBlobSaS(CloudBlob blob, CloudBlobContainer container) throws InvalidKeyException,
            IllegalArgumentException, StorageException, URISyntaxException, InterruptedException {
        SharedAccessBlobPolicy sp = createSharedAccessBlobPolicy(
                EnumSet.of(SharedAccessBlobPermissions.READ, SharedAccessBlobPermissions.LIST), 100);
        BlobContainerPermissions perms = new BlobContainerPermissions();

        perms.getSharedAccessPolicies().put("readperm", sp);
        container.uploadPermissions(perms);
        // Thread.sleep(30000);
        String sas = blob.generateSharedAccessSignature(sp, null);

        CloudBlockBlob sasBlob = new CloudBlockBlob(
                new URI(blob.getUri().toString() + "?" + blob.generateSharedAccessSignature(null, "readperm")));
        sasBlob.download(new ByteArrayOutputStream());

        // do not give the client and check that the new blob's client has the
        // correct perms
        CloudBlob blobFromUri = new CloudBlockBlob(
                PathUtility.addToQuery(blob.getStorageUri(), blob.generateSharedAccessSignature(null, "readperm")));
        assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
                blobFromUri.getServiceClient().getCredentials().getClass().toString());

        // create credentials from sas
        StorageCredentials creds = new StorageCredentialsSharedAccessSignature(
                blob.generateSharedAccessSignature(null, "readperm"));
        CloudBlobClient bClient = new CloudBlobClient(sasBlob.getServiceClient().getStorageUri(), creds);

        CloudBlockBlob blobFromClient = bClient.getContainerReference(blob.getContainer().getName())
                .getBlockBlobReference(blob.getName());
        assertEquals(StorageCredentialsSharedAccessSignature.class.toString(),
                blobFromClient.getServiceClient().getCredentials().getClass().toString());
        assertEquals(bClient, blobFromClient.getServiceClient());
        return sas;

    }

Method to create shared access blob policy :

private final static SharedAccessBlobPolicy createSharedAccessBlobPolicy(EnumSet<SharedAccessBlobPermissions> sap,
            int expireTimeInSeconds) {

        Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        cal.setTime(new Date());
        cal.add(Calendar.YEAR, expireTimeInSeconds);
        SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
        policy.setPermissions(sap);
        policy.setSharedAccessExpiryTime(cal.getTime());
        return policy;

    }

What changes I should make here?

Body:
I have faced similar problem before. What you need to do is , make your code comfortable for all the time zones like GMT,IST,EST etc. Because when you upload war in server of another country, your code must be 'clever' enough to understand time zone of that country !

So here is what you can do :

Step 1:

In third part of your code , try replaceing "UTC" by your client machine's timezone like GMT,EST etc.

If that works (and I am pretty much sure that it will work fine) , go for

Step 2:

First of all we will code something that gives you current time zone in String  like "Indian Standard Time" or "European Standard Time" etc.

Then, we will pick only first letters from all words and make a String like "IST" or "EST".

At last, we will pass this String at place where you wrote "UTC" in third part of your code.

So, here is the code :

private final static SharedAccessBlobPolicy createSharedAccessBlobPolicy(EnumSet<SharedAccessBlobPermissions> sap,
            int expireTimeInSeconds) {
        Calendar now = Calendar.getInstance();
        TimeZone timeZone = now.getTimeZone();
        System.out.println("Current TimeZone is : " + timeZone.getDisplayName());
        String x = timeZone.getDisplayName();
        String[] myName = x.split(" ");
        String s = "";
        ArrayList zoneArray = new ArrayList<>();
        char zone = 0;
        for (int i = 0; i < myName.length; i++) {
            s = myName[i];
            System.out.print(s.charAt(0));
            zone = s.charAt(0);
            zoneArray.add(zone);
        }
        String timeZoneCurrent = s;
        String timeZoneDynamic = zoneArray.toString().replace(",", "").replace(" ", "").replace("[", "").replace("]",
                "");
        System.out.println("Value of S==========" + timeZoneDynamic);
        Calendar cal = new GregorianCalendar(TimeZone.getTimeZone(timeZoneDynamic));
        cal.setTime(new Date());
        cal.add(Calendar.YEAR, expireTimeInSeconds);
        SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
        policy.setPermissions(sap);
        policy.setSharedAccessExpiryTime(cal.getTime());
        return policy;
    }

In this, timeZoneDynamic has values like "IST" , "GMT" etc. This logic must work. If have any error, post it in edit. Hope that will work.


答:
Just add justify-content: center to .nav-align.

https://jsfiddle.net/60yqwufm/1/

Title: Can't center image in the second row

Body:
I have one row of three images. They are displaying equally spaced and centered as needed. But then I have a row beneath that of one image and I can't get it to move to align centered of the first row.

I've tried all of the suggestions I could find, like margin:0 auto; width:90%, but that image in the second row stays aligned left.

Would someone please point out my mistake? Here is the jsfiddle and here's the code I am using.

.banner_set {
  width: 100%;
  overflow: hidden
}

.nav-align {
  display: -webkit-flex;
  display: flex;
  -webkit-reorder-direction: row-reverse;
  width: 100%;
  height: auto;
  list-style: none;
}

.nav-items {
  /* width: 33%; */
  margin: 24px;
  flex: 1;
  /* NEW */
  box-shadow: 2px 4px 6px rgba(0, 0, 0, 0.5)
}

.nav-items-wide {
  width: 100% margin: 0px;
}


问:
xlwings: set foreground text color from Python
I'm using xlwings on a Mac and would like to set the foreground color of text in a cell from Python. I see that range.color will change background color which I could use but it has an additional problem that the cell borders are overwritten by the new BG color.

Is there any way to change foreground text color from Python and/or prevent the cell borders being overwritten by a new BG color?

答:
The new API is :</p>

```<code>Range("A1").api.Font.ColorIndex = 3
</code>```

Body:
The new API is :

Range("A1").api.Font.ColorIndex = 3


问:
Overlap of Group Barcharts in matplotlib
Dataset:

Code to plot:

```<code>import numpy as np
import matplotlib.pyplot as plt

# data to plot
n_groups = 6
GreenTaxi = pivot_df['GreenTaxi'].tolist()
YellowTaxi = pivot_df['YellowTaxi'].tolist()
Uber = pivot_df['Uber'].tolist()

# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8

rects1 = plt.bar(index, GreenTaxi, bar_width,
                 alpha=opacity,
                 color='b',
                 label='GreenTaxi')

rects2 = plt.bar(index + bar_width, YellowTaxi, bar_width,
                 alpha=opacity,
                 color='g',
                 label='YellowTaxi')

rects3 = plt.bar(index + bar_width, Uber, bar_width,
                 alpha=opacity,
                 color='r',
                 label='Uber')

plt.xlabel('Month')
plt.ylabel('Ride Counts')
plt.title('Rides By Month')
plt.figure(figsize=(5,5))
plt.xticks(index + bar_width,pivot_df['MonthName'].tolist() )
plt.legend()
plt.show()
</code>```

Output:

The green and red bar charts are overlapping and more over MonthName does not come in the x label ,only  numerics are coming . Could you please advise on th eissue.

答:
```<code>import pandas as pd
import numpy as np

df=pd.DataFrame(10*np.random.rand(4,3),index=["Jan","Feb","March","April"],columns=["Uber","T1", "T2"])

df.plot(kind='bar',rot=0)
</code>```

Body:
Dataset:

Code to plot:

import numpy as np
import matplotlib.pyplot as plt

# data to plot
n_groups = 6
GreenTaxi = pivot_df['GreenTaxi'].tolist()
YellowTaxi = pivot_df['YellowTaxi'].tolist()
Uber = pivot_df['Uber'].tolist()

# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8

rects1 = plt.bar(index, GreenTaxi, bar_width,
                 alpha=opacity,
                 color='b',
                 label='GreenTaxi')

rects2 = plt.bar(index + bar_width, YellowTaxi, bar_width,
                 alpha=opacity,
                 color='g',
                 label='YellowTaxi')

rects3 = plt.bar(index + bar_width, Uber, bar_width,
                 alpha=opacity,
                 color='r',
                 label='Uber')

plt.xlabel('Month')
plt.ylabel('Ride Counts')
plt.title('Rides By Month')
plt.figure(figsize=(5,5))
plt.xticks(index + bar_width,pivot_df['MonthName'].tolist() )
plt.legend()
plt.show()

Output:

The green and red bar charts are overlapping and more over MonthName does not come in the x label ,only  numerics are coming . Could you please advise on th eissue.


问:
How to convert Json type with array to .net object?
I have JSON string:
// the coverage value is an array.

```<code>  string jsonData = @"{
""plans"":
[
{
""plan_code"":""UL500"",
    ""plan_name"":""Unlimited 500M"",
    ""days"":1,
    ""limit"":500,
    ""coverage"":
[
{
""country"":""SE"",
},
{
""country"":""BZ""
}
]
},
{
""plan_code"":""UL1GB"",
    ""plan_name"":""Unlimited 1GB"",
    ""days"":1,
    ""limit"":1024,
    ""coverage"":
[
{
""country"":""SG"",
},
{
""country"":""JP""
}
]
}
]
}
";
</code>```

and i'm parse by JsonConvert.DeserializeObject as sample code below:

```<code> try
    {
        var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
        HttpResponseMessage response = await client.PostAsync("", content);
        var result = await response.Content.ReadAsStringAsync();
        var tempRecords = JsonConvert.DeserializeObject<List<plan>>(result);
    }
</code>```

and then i'm get an error message:
    "Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[DAL.plan]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'plans', line 1, position 9."

please show me a right way for this issue.

答:
The whole string represents an object with a property called "plans" that refers to your array. The string itself is not the array, so if you're trying to deserialize it as a List<T>, that's not going to work. You need to handle the fact that your desired array is wrapped by a JSON object.

This is a similar problem that I think explains it well.

Body:
I have JSON string:
// the coverage value is an array.

  string jsonData = @"{
""plans"":
[
{
""plan_code"":""UL500"",
    ""plan_name"":""Unlimited 500M"",
    ""days"":1,
    ""limit"":500,
    ""coverage"":
[
{
""country"":""SE"",
},
{
""country"":""BZ""
}
]
},
{
""plan_code"":""UL1GB"",
    ""plan_name"":""Unlimited 1GB"",
    ""days"":1,
    ""limit"":1024,
    ""coverage"":
[
{
""country"":""SG"",
},
{
""country"":""JP""
}
]
}
]
}
";

and i'm parse by JsonConvert.DeserializeObject as sample code below:

 try
    {
        var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
        HttpResponseMessage response = await client.PostAsync("", content);
        var result = await response.Content.ReadAsStringAsync();
        var tempRecords = JsonConvert.DeserializeObject<List<plan>>(result);
    }

and then i'm get an error message:
    "Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[DAL.plan]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'plans', line 1, position 9."

please show me a right way for this issue.


问:
About resolving Resource Leaks
I'm a newbee to spring framework and I encounted some errors when I was compiling the "HelloSpring" code on tutorialscom. Throughout the code there is only one warning in the main class:

```<code>package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        HelloWorld  HW = (HelloWorld)context.getBean("Hello Spring");
        HW.getMsg();
    }
}
</code>```

Eclipse warns me "Resource Leak: 'context' is never close", but for ApplicationContext class I dont know how to close it. Can anyone help me with it?

The errors are:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    at org.springframework.context.support.AbstractApplicationContext.<init>(AbstractApplicationContext.java:164)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.<init>(AbstractRefreshableApplicationContext.java:89)
    at org.springframework.context.support.AbstractRefreshableConfigApplicationContext.<init>(AbstractRefreshableConfigApplicationContext.java:58)
    at org.springframework.context.support.AbstractXmlApplicationContext.<init>(AbstractXmlApplicationContext.java:61)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:136)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.tutorialspoint.MainApp.main(MainApp.java:10)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 7 more
</code>```

BTW my java version is the latest 1.80, idk if this matters.
Thank you!

答:
If you're starting off, find something better than tutorialspoint. There are many tutorials written by Spring guys, and here's their getting started

No one uses XML config anymore, unless you're 97 years old and against annotations. Use annotations.

You don't need a try-finally to close the ApplicationContext. Try-with-resources was introduced in Java 7 in 2011, about the same time people stopped using XML for Spring config.

I was gonna suggest you use Spring Boot and make life easier for yourself, but Boot does many things under the hood that you perhaps would like to learn the hard way.

Title: About resolving Resource Leaks

Body:
I'm a newbee to spring framework and I encounted some errors when I was compiling the "HelloSpring" code on tutorialscom. Throughout the code there is only one warning in the main class:

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        HelloWorld  HW = (HelloWorld)context.getBean("Hello Spring");
        HW.getMsg();
    }
}

Eclipse warns me "Resource Leak: 'context' is never close", but for ApplicationContext class I dont know how to close it. Can anyone help me with it?

The errors are:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    at org.springframework.context.support.AbstractApplicationContext.<init>(AbstractApplicationContext.java:164)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.<init>(AbstractRefreshableApplicationContext.java:89)
    at org.springframework.context.support.AbstractRefreshableConfigApplicationContext.<init>(AbstractRefreshableConfigApplicationContext.java:58)
    at org.springframework.context.support.AbstractXmlApplicationContext.<init>(AbstractXmlApplicationContext.java:61)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:136)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.tutorialspoint.MainApp.main(MainApp.java:10)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 7 more

BTW my java version is the latest 1.80, idk if this matters.
Thank you!


问:
How do I limit decimal places to only two numbers when paste number into input box using angularjs?
I have input box accepting decimal numbers with having decimal points limit upto 2 places. Also I am not allowing input to enter more than two decimal places.

eg. 9999.99

But now the problem is when I am copy some number i.e. 999999.9999 and paste it into input box I want result i.e. 999999.99

Meaning I want to truncate rest of the decimal places and don't want rounding as well.

How can I achieve this using angularjs?

答:
You can use ngPattern directive.

```<code><input type="text" ng-pattern="/^[0-9]+(?:\.[0-9][0-9])?$/">
</code>```

This regex would enforce exactly two places (no more or less). Just change the regex to get whichever desired behavior you want.

Body:
You can use ngPattern directive.

<input type="text" ng-pattern="/^[0-9]+(?:\.[0-9][0-9])?$/">

This regex would enforce exactly two places (no more or less). Just change the regex to get whichever desired behavior you want.


问:
Direction of Dependencies in Angular Modules
What is the recommended approach and trade offs for splitting a large app into modules?

In particular, I would try to avoid circular dependencies, and I would try to ensure that components and services should be declared once in a single module only.

What is the effect if these practices are not followed?

If module A, the root module, imports modules B and C, and a service S is provided in both module B and C, would there be two instances of service S existing at runtime.

What would happens if module B provides one implementation of S whilst module C provides another implementation. Would that work, or would we have a last-in-wins situation where the first service registration gets overwritten by the second.

答:
As @HarryNinh and @DeborahK suggested, the official docs is the best article I found about splitting your modules. This is just a prescribed way of splitting your modules and feel free to deviate from it if there is a need.
I have the same problem before and I ended up splitting the modules in this way. (This is heavily influenced from the official docs and from my own experience)

The AppModule or root module - This is the module that angular loads first. I try to make this as small as possible and import other modules from here such as SharedModule and CoreModule.

Shared Module - This module is where you put modules that you are going to need in a lot of places. For example if you often find that you always need to use FormsModule you put it here. Another example from my experience is that I lazy loaded some of my components as much as possible and I found myself repeating the imports like FormsModule. Another example is if you are using UI frameworks such as angular/material or ng-bootstrap, you should put it in SharedModule to prevent repeating the same imports from your lazy loaded modules. Feel free to import this from your FeatureModules. I know you might be wondering if there is a duplication of imports of modules. Well taken from official docs

What if I import the same module twice?

That's not a problem. When three modules all import Module 'A',
Angular evaluates Module 'A' once, the first time it encounters it,
and doesn't do so again.

Core Module -  This is where you put your providers for services that you need a single instance. Ideal candidate is if you have an AuthService, or some data service. This should only be imported once in your AppModule.

Feature Module - this is where you put your components and services with related functionalities. Usually you import this from your AppModule, but personally I tend not to because I want to lazy load as much as possible.

Hope this helps.


问:
Save data in python
I'm a little stuck here. I'm running a twitter api request loop and I need to store these tweets in a csv file. I'm doing something like:

```<code>for tweet in tweepy.Cursor(api.search,q=search+ lang="en").items(num_tweets):
    data = tweet.text
    print (tweet.text)
</code>```

My question is what's the easiest way to save tweets in this format:

```<code>["Hello world. I love Reddit!", "Lorem ipsum dolor sit amaet."]
</code>```

答:
Simple way to achieve what you want.

```<code>import csv

with open('filename', 'w') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    for tweet in tweepy.Cursor(api.search, q=search+ lang="en").items(num_tweets):
        data = tweet.text
        wr.writerow(tweet.text)
</code>```

You can check what csv.QUOTE_ALL does.

Title: Save data in python

Body:
I'm a little stuck here. I'm running a twitter api request loop and I need to store these tweets in a csv file. I'm doing something like:

for tweet in tweepy.Cursor(api.search,q=search+ lang="en").items(num_tweets):
    data = tweet.text
    print (tweet.text)

My question is what's the easiest way to save tweets in this format:

["Hello world. I love Reddit!", "Lorem ipsum dolor sit amaet."]

Body:
Simple way to achieve what you want.

import csv

with open('filename', 'w') as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    for tweet in tweepy.Cursor(api.search, q=search+ lang="en").items(num_tweets):
        data = tweet.text
        wr.writerow(tweet.text)

You can check what csv.QUOTE_ALL does.


问:
I need to set next button as disabled till any radio button got selected
In my use case i need to set Next button from a popup is disabled in default till any one of the radio button got selected.

Need to achieve this in Ember.Js

My hbs code (for that popup):

```<code>{{! To list all accounts in popup }}
<div id="listAllAccounts" class="modal animated fadeInUp modal-pop downloadAsPopup">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true" {{action 'clearModal'}}>×</button>
        <h4 class="modal-title">List of accounts</h4>
      </div>
      <div class="modal-body">
        <div class="textGroup">
          <h2 class="primaryTitle">Select an account.</h2>
        </div>
        <div class="modalTableHolder">
          <table class="primaryListTable" id="AccountsInfo">
            <thead>
              <td class="tablestyle5">Account ID</td>
              <td class="tablestyle5">Account Name</td>
            </thead>
            <tbody>
              {{#each model.integration as |list index|}}
                <tr>
                  <td class="tablestyle5"><input type="radio" name="accounts" class="messageCheckbox mt6 mR5" data-acc-name={{list.ACCOUNT_NAME}} value={{list.ACCOUNT_ID}}>{{list.ACCOUNT_ID}}</td>
                  <td class="tablestyle5">{{list.ACCOUNT_NAME}}</td>
                </tr>
              {{/each}}
            </tbody>
          </table>
        </div>
      </div>
      <div class="modal-footer">
        <div class="text-right">
          <button type="button" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" {{action 'clearModal'}}>Cancel</button>
          <button type="button" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" {{action 'showContainerPopup' 'clearModal'}}>Next</button>
        </div>
      </div>
    </div>
  </div>
</div>
{{! To list all accounts in popup Ends }}
</code>```

JS code:

```<code>Ember.run.scheduleOnce('afterRender', this, function() {
          new URI(Abc, this.get('currentOrg.ABC_ID'), Project, this.get('defaultProject.PROJECT_ID'), Integration)
          .addQueryParam('email', this.get(email))
          .GETS()
          .then(function(res) {
            if(res.length !== 0){
              var sett = projectObj.get("INTEGRATION");
              self.set("model.integration", res);    //this is where i set data to that popup
              common.hideModal("loadingPopup");
              common.showModal("listAllAccounts");
            } else {
              common.hideModal("loadingPopup");
              options.content = i18n("enable.integration.noaccount.error");
              options.type = 'warning';
              dialog.showCard(options);
            }
          });
</code>```

This is the popup. I need to disable the next button until anyone selects any one radio button. If radio button is checked i need to enable next option.

答:
First you can disable your button using

```<code>disabled="disabled"
</code>```

when pop is appear and add extra class for next button btn-next.

And check if radio button is checked or not to enable your button.

```<code> $(document).on('click',"input:radio[name='accounts']",function () {
        if ($(this).is(':checked')) {
            $(".btn-next").prop("disabled", false);
        }
    });
</code>```

Body:
In my use case i need to set Next button from a popup is disabled in default till any one of the radio button got selected.

Need to achieve this in Ember.Js

My hbs code (for that popup):

{{! To list all accounts in popup }}

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true" {{action 'clearModal'}}>×</button>

List of accounts

Select an account.

              Account ID
              Account Name

              {{#each model.integration as |list index|}}

                  <input type="radio" name="accounts" class="messageCheckbox mt6 mR5" data-acc-name={{list.ACCOUNT_NAME}} value={{list.ACCOUNT_ID}}>{{list.ACCOUNT_ID}}
                  {{list.ACCOUNT_NAME}}

              {{/each}}

          <button type="button" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" {{action 'clearModal'}}>Cancel</button>
          <button type="button" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" {{action 'showContainerPopup' 'clearModal'}}>Next</button>

{{! To list all accounts in popup Ends }}

JS code:

Ember.run.scheduleOnce('afterRender', this, function() {
          new URI(Abc, this.get('currentOrg.ABC_ID'), Project, this.get('defaultProject.PROJECT_ID'), Integration)
          .addQueryParam('email', this.get(email))
          .GETS()
          .then(function(res) {
            if(res.length !== 0){
              var sett = projectObj.get("INTEGRATION");
              self.set("model.integration", res);    //this is where i set data to that popup
              common.hideModal("loadingPopup");
              common.showModal("listAllAccounts");
            } else {
              common.hideModal("loadingPopup");
              options.content = i18n("enable.integration.noaccount.error");
              options.type = 'warning';
              dialog.showCard(options);
            }
          });

This is the popup. I need to disable the next button until anyone selects any one radio button. If radio button is checked i need to enable next option.

Body:
First you can disable your button using

disabled="disabled"

when pop is appear and add extra class for next button btn-next.

And check if radio button is checked or not to enable your button.

 $(document).on('click',"input:radio[name='accounts']",function () {
        if ($(this).is(':checked')) {
            $(".btn-next").prop("disabled", false);
        }
    });


问:
AJAX, response headers are not sent by PHP script!
I'm banging my head for some hours now. I have a select option that it updates a database using AJAX (at least it's trying to!). What happens is while running the PHP script directly with params required the database gets updated but not when running indirectly through AJAX, instead I get 3 times the alert("There was a problem in the returned data:\n"); and then it gets updated. JavaScript is on  and not in an external file. Here it goes:

JavaScript:

```<code>function updateHub(){
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }else{
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function(){
       if (xmlhttp.readyState==4 && xmlhttp.status==200){
           document.getElementById("hubinfo").innerHTML=xmlhttp.responseText;
       }else{
           alert("There was a problem in the returned data:\n");
       }
    }
    var prefHub = document.getElementById("prefHub");
    var hubID = prefHub.options[prefHub.selectedIndex].value;
    xmlhttp.open("GET","updateHub.php?hubID="+hubID,true);
    xmlhttp.send();
}
</code>```

updateHub.php:

```<code>session_start();
include '../../../common/config.php';
$hubID = '';
if(isset($_POST['hubID'])){
    $hubID = strip_tags(mysql_real_escape_string(trim($_POST['hubID'])));
}elseif(isset($_GET['hubID'])){
    $hubID = strip_tags(mysql_real_escape_string(trim($_GET['hubID'])));
}
mysql_query("UPDATE prefs set hubID='$hubID' where userID = '".$_SESSION['userID']."'") or die(mysql_error());
if(mysql_affected_rows()){
    echo "Updated";
}else{
    echo 'Error';
}
return $hubID;
</code>```

and the HTML:

```<code><form action="" method="post" onsubmit="updateHub();">
    <select name="prefHub" id="prefHub">
        <option value="43">opt1</option>
        <option value="64">opt2</option>
        <option value="30">opt2</option>
     </select>
     <input type="submit" name="update" value="Update Hub"/>
</form>
<div id="hubinfo"></div>
</code>```

答:
I moved

```<code>var prefHub = document.getElementById("prefHub");
var hubID = prefHub.options[prefHub.selectedIndex].value;
</code>```

right after

```<code>function updateHub()
{
</code>```

and removed

```<code>else{
         alert("There was a problem in the returned data:\n");
    }
</code>```

and it's now working properly but I don't understand why.Is anyone able to explain it?

andreas explained why.

Body:
I'm banging my head for some hours now. I have a select option that it updates a database using AJAX (at least it's trying to!). What happens is while running the PHP script directly with params required the database gets updated but not when running indirectly through AJAX, instead I get 3 times the alert("There was a problem in the returned data:\n"); and then it gets updated. JavaScript is on  and not in an external file. Here it goes:

JavaScript:

function updateHub(){
    if (window.XMLHttpRequest){
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }else{
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function(){
       if (xmlhttp.readyState==4 && xmlhttp.status==200){
           document.getElementById("hubinfo").innerHTML=xmlhttp.responseText;
       }else{
           alert("There was a problem in the returned data:\n");
       }
    }
    var prefHub = document.getElementById("prefHub");
    var hubID = prefHub.options[prefHub.selectedIndex].value;
    xmlhttp.open("GET","updateHub.php?hubID="+hubID,true);
    xmlhttp.send();
}

updateHub.php:

session_start();
include '../../../common/config.php';
$hubID = '';
if(isset($_POST['hubID'])){
    $hubID = strip_tags(mysql_real_escape_string(trim($_POST['hubID'])));
}elseif(isset($_GET['hubID'])){
    $hubID = strip_tags(mysql_real_escape_string(trim($_GET['hubID'])));
}
mysql_query("UPDATE prefs set hubID='$hubID' where userID = '".$_SESSION['userID']."'") or die(mysql_error());
if(mysql_affected_rows()){
    echo "Updated";
}else{
    echo 'Error';
}
return $hubID;

and the HTML:

<form action="" method="post" onsubmit="updateHub();">
    <select name="prefHub" id="prefHub">
        <option value="43">opt1</option>
        <option value="64">opt2</option>
        <option value="30">opt2</option>
     </select>
     <input type="submit" name="update" value="Update Hub"/>
</form>

Body:
I moved

var prefHub = document.getElementById("prefHub");
var hubID = prefHub.options[prefHub.selectedIndex].value;

right after

function updateHub()
{

and removed

else{
         alert("There was a problem in the returned data:\n");
    }

and it's now working properly but I don't understand why.Is anyone able to explain it?

andreas explained why.


问:
how do i change an image if i click on a button in Swift?
I am new to swift. I have a button and 3 images that are saved in the array. What I want is to change the images by clicking on the button. </p>

```<code>let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]
@IBAction func carbsButton(_ sender: Any) {

}
</code>```

答:
```<code>let image = UIImage(named: circleArray[0]) // circleArray[1], circleArray[2]
</code>```

in your action function set button image

```<code>button.setImage(image, for: .normal)
</code>```

Body:
I am new to swift. I have a button and 3 images that are saved in the array. What I want is to change the images by clicking on the button.

let circleArray = ["circle-gray-big","circle-green-big","circle-red-big"]
@IBAction func carbsButton(_ sender: Any) {

}

Body:
let image = UIImage(named: circleArray[0]) // circleArray[1], circleArray[2]

in your action function set button image

button.setImage(image, for: .normal)


问:
Attach dynamically loaded javascript event handler to dynamically loaded HTML
I have a site which loads content through AJAX. I need to attach onclick handler to some div which was dynamically loaded. It works fine if my event handler is already defined in my main javascript file (whether I attach it through markup via attribute onclick="myFunc" on by more pedantic addEventListener ).

However, I would like this event handler to be defined in a  is before or after the
.

I tried to attach it at the end of the XmlHttpRequest:

```<code>contentDiv.innerHTML = xhr.responseText;
var handlerName = getItFrom(xhr.responseText);
var clickFn = window[handlerName];
loadedDiv.addEventListener('click', clickFn);
</code>```

Doesn't work neither: handlerName is correct, but clickFn remains undefined...

I prefer a pure js answer but jquery is ok if I can easily translate it.

答:
If getItFrom(xhr.responseText); returns a function defined in the global scope try to add quotes like this:

var clickFn = window['handlerName'];

Because console says:

```<code>var luck = function(){}; window[luck];
> undefined
var luck = function(){}; window['luck'];
> function luck()
</code>```

Body:
I have a site which loads content through AJAX. I need to attach onclick handler to some div which was dynamically loaded. It works fine if my event handler is already defined in my main javascript file (whether I attach it through markup via attribute onclick="myFunc" on by more pedantic addEventListener ).

However, I would like this event handler to be defined in a  is before or after the
.

I tried to attach it at the end of the XmlHttpRequest:

contentDiv.innerHTML = xhr.responseText;
var handlerName = getItFrom(xhr.responseText);
var clickFn = window[handlerName];
loadedDiv.addEventListener('click', clickFn);

Doesn't work neither: handlerName is correct, but clickFn remains undefined...

I prefer a pure js answer but jquery is ok if I can easily translate it.

Body:
If getItFrom(xhr.responseText); returns a function defined in the global scope try to add quotes like this:

var clickFn = window['handlerName'];

Because console says:

var luck = function(){}; window[luck];
> undefined
var luck = function(){}; window['luck'];
> function luck()