问:
gcc generate compile time error because of unabling to recognize __TIMESTAMP__ and some other defined build variable
I'm working with an existing example on eclipse & GCC based IDE for compiling my application for an embedded EFTPOS devices.
but in the below lines:

```<code>fprintf(stdout, "** Compilation date: %s \n", __TIMESTAMP__);
fprintf(stdout, "**** SDK release: %s \n", __SDK_RELEASE__);
fprintf(stdout, "**** ToolChain release: %s \n", __TOOLCHAIN_RELEASE__);
</code>```

I received these compile time errors which seems compiler is unable to recognized these macros.

```<code>Symbol '__TIMESTAMP__' could not be resolved    main.c
Symbol '__SDK_RELEASE__' could not be resolved  main.c
Symbol '__TOOLCHAIN_RELEASE__' could not be resolved    main.c
</code>```

If I try fprintf(stdout, "** Compilation date: %s \n", __TIME__); it is compiled successfully.
why compiler recognized __TIME__  macro but return error for __TIMESTAMP__ ? also as you can see __SDK_RELEASE__ and __TOOLCHAIN_RELEASE__ are defined in build variables.

EDIT:
Thank for your reply and excuse me for my lacking in provided information.
In C/C++ build ->setting->symbols:

```<code>'__SDK_RELEASE__="${SDK_RELEASE}"'
'__TOOLCHAIN_RELEASE__="${TOOLCHAIN_RELEASE}"'
</code>```

are defined,then __SDK_RELEASE__ and__TOOLCHAIN_RELEASE__ must be valid.Also I mean if __TIME__ macro is valid __TIMESTAMP__ must be do same,but it is not.

答:
You defined SDK_RELEASE and TOOLCHAIN_RELEASE in build variables, so why should they be used with double underscores??..

Change your code to

```<code>fprintf(stdout, "**** SDK release: %s \n", SDK_RELEASE);
fprintf(stdout, "**** ToolChain release: %s \n", TOOLCHAIN_RELEASE);
</code>```

About __TIME__, as you can see, macros are defined since c99 with "double underscores", that is why it works.

Form the C11

6.4.2.2 Predefined identifiers

Semantics

1 The identifier __func__ shall be implicitly declared by the translator as if,
  immediately following the opening brace of each function definition, the declaration

static const char func[] = "function-name";

appeared, where function-name is the name of the lexically-enclosing function.72)

note.72 Since the name __func__ is reserved for any use by the implementation (7.1.3), if any other
  identifier is explicitly declared using the name __func__, the behavior is undefined.

Emphasis mine

6.10.8.1 Mandatory macros

1 The following macro names shall be defined by the implementation:

__DATE__ The date of translation of the preprocessing translation unit: a character
  string literal of the form "Mmm dd yyyy", where the names of the
  months are the same as those generated by the asctime function, and the
  first character of dd is a space character if the value is less than 10. If the
  date of translation is not available, an implementation-defined valid date
  shall be supplied.

__FILE__ The presumed name of the current source file (a character string literal).

__LINE__ The presumed line number (within the current source file) of the current
  source line (an integer constant).

__STDC__ The integer constant 1, intended to indicate a conforming implementation.

__STDC_HOSTED__ The integer constant 1 if the implementation is a hosted
  implementation or the integer constant 0 if it is not.

__STDC_VERSION__ The integer constant 201112L.

__TIME__ The time of translation of the preprocessing translation unit: a character
  string literal of the form "hh:mm:ss" as in the time generated by the
  asctime function. If the time of translation is not available, an
  implementation-defined valid time shall be supplied.

Emphasis mine

7.1.3 Reserved identifiers

1 Each header declares or defines all identifiers listed in its associated subclause, and
  optionally declares or defines identifiers listed in its associated future library directions
  subclause and identifiers which are always reserved either for any use or for use as file
  scope identifiers.

— All identifiers that begin with an underscore and either an uppercase letter or another
  underscore are always reserved for any use.

— All identifiers that begin with an underscore are always reserved for use as identifiers
  with file scope in both the ordinary and tag name spaces.

[...]

Emphasis mine

As you can see the __TIMESTAMP__ define is not in standard, so compilers are free to define or not define it: your current compiler does not.

Body:
I'm working with an existing example on eclipse & GCC based IDE for compiling my application for an embedded EFTPOS devices.
but in the below lines:

fprintf(stdout, "** Compilation date: %s \n", __TIMESTAMP__);
fprintf(stdout, "**** SDK release: %s \n", __SDK_RELEASE__);
fprintf(stdout, "**** ToolChain release: %s \n", __TOOLCHAIN_RELEASE__);

I received these compile time errors which seems compiler is unable to recognized these macros.

Symbol '__TIMESTAMP__' could not be resolved    main.c
Symbol '__SDK_RELEASE__' could not be resolved  main.c
Symbol '__TOOLCHAIN_RELEASE__' could not be resolved    main.c

If I try fprintf(stdout, "** Compilation date: %s \n", __TIME__); it is compiled successfully.
why compiler recognized __TIME__  macro but return error for __TIMESTAMP__ ? also as you can see __SDK_RELEASE__ and __TOOLCHAIN_RELEASE__ are defined in build variables.

EDIT:
Thank for your reply and excuse me for my lacking in provided information.
In C/C++ build ->setting->symbols:

'__SDK_RELEASE__="${SDK_RELEASE}"'
'__TOOLCHAIN_RELEASE__="${TOOLCHAIN_RELEASE}"'

are defined,then __SDK_RELEASE__ and__TOOLCHAIN_RELEASE__ must be valid.Also I mean if __TIME__ macro is valid __TIMESTAMP__ must be do same,but it is not.

Body:
You defined SDK_RELEASE and TOOLCHAIN_RELEASE in build variables, so why should they be used with double underscores??..

Change your code to

fprintf(stdout, "**** SDK release: %s \n", SDK_RELEASE);
fprintf(stdout, "**** ToolChain release: %s \n", TOOLCHAIN_RELEASE);

About __TIME__, as you can see, macros are defined since c99 with "double underscores", that is why it works.

Form the C11

6.4.2.2 Predefined identifiers

Semantics

1 The identifier __func__ shall be implicitly declared by the translator as if,
  immediately following the opening brace of each function definition, the declaration

static const char func[] = "function-name";

appeared, where function-name is the name of the lexically-enclosing function.72)

note.72 Since the name __func__ is reserved for any use by the implementation (7.1.3), if any other
  identifier is explicitly declared using the name __func__, the behavior is undefined.

Emphasis mine

6.10.8.1 Mandatory macros

1 The following macro names shall be defined by the implementation:

__DATE__ The date of translation of the preprocessing translation unit: a character
  string literal of the form "Mmm dd yyyy", where the names of the
  months are the same as those generated by the asctime function, and the
  first character of dd is a space character if the value is less than 10. If the
  date of translation is not available, an implementation-defined valid date
  shall be supplied.

__FILE__ The presumed name of the current source file (a character string literal).

__LINE__ The presumed line number (within the current source file) of the current
  source line (an integer constant).

__STDC__ The integer constant 1, intended to indicate a conforming implementation.

__STDC_HOSTED__ The integer constant 1 if the implementation is a hosted
  implementation or the integer constant 0 if it is not.

__STDC_VERSION__ The integer constant 201112L.

__TIME__ The time of translation of the preprocessing translation unit: a character
  string literal of the form "hh:mm:ss" as in the time generated by the
  asctime function. If the time of translation is not available, an
  implementation-defined valid time shall be supplied.

Emphasis mine

7.1.3 Reserved identifiers

1 Each header declares or defines all identifiers listed in its associated subclause, and
  optionally declares or defines identifiers listed in its associated future library directions
  subclause and identifiers which are always reserved either for any use or for use as file
  scope identifiers.

— All identifiers that begin with an underscore and either an uppercase letter or another
  underscore are always reserved for any use.

— All identifiers that begin with an underscore are always reserved for use as identifiers
  with file scope in both the ordinary and tag name spaces.

[...]

Emphasis mine

As you can see the __TIMESTAMP__ define is not in standard, so compilers are free to define or not define it: your current compiler does not.


来源: stackexchange

问:
How to correctly specify a default value in the Spring @Value annotation?
Initially, I have the following spec:

```<code>@Value("#{props.isFPL}")
private boolean isFPL=false;
</code>```

This works fine correctly getting the value from the property file:

```<code>isFPL = true
</code>```

However, the following expression with default results in the error:

```<code>@Value("#{props.isFPL:false}")
private boolean isFPL=false;
</code>```

Expression parsing failed; nested exception is org.springframework.expression.spel.SpelParseException: EL1041E:(pos 28): After parsing a valid expression, there is still more data in the expression: 'colon(:)'

I also tried to use $ instead of #.

```<code>@Value("${props.isFPL:true}")
private boolean isFPL=false;
</code>```

Then the default value in annotation works fine but I did not get the correct value from the Properties file:

答:
For int type variable:

```<code>@Value("${my.int.config: #{100}}")
int myIntConfig;
</code>```

Note: there is no space before the colon, but an extra space after the colon.

ContentLicense: CC BY-SA 3.0

Body:
Initially, I have the following spec:

@Value("#{props.isFPL}")
private boolean isFPL=false;

This works fine correctly getting the value from the property file:

isFPL = true

However, the following expression with default results in the error:

@Value("#{props.isFPL:false}")
private boolean isFPL=false;

Expression parsing failed; nested exception is org.springframework.expression.spel.SpelParseException: EL1041E:(pos 28): After parsing a valid expression, there is still more data in the expression: 'colon(:)'

I also tried to use $ instead of #.

@Value("${props.isFPL:true}")
private boolean isFPL=false;

Then the default value in annotation works fine but I did not get the correct value from the Properties file:

Body:
For int type variable:

@Value("${my.int.config: #{100}}")
int myIntConfig;

Note: there is no space before the colon, but an extra space after the colon.


问:
ADO .NET blocking despite async calls
I have a WPF application where I am doing some database operations when a user clicks on a button. The button click is bound to a command using the RelayCommand from GalaSoft's MVVM Light.

MySQL is giving me timeouts because of the large amount of data, but the real problem is another. I am doing everything asynchronously, and yet, the application is blocking until the timeout elapses.

I always expect the UI to remain responsive while an asynchronous operation is running. For example if I do a GET request using HttpClient, no matter how long it takes to come back with a response, I can still use the UI.

I am using the Pomelo data provider for MySQL (Pomelo.Data.MySql).

答: It looks like the Pomelo implementation of ExecuteReaderAsync() uses the blocking implementation and wraps it in a TaskCompletionSource.

Title: ADO .NET blocking despite async calls


问:
calling a promise within a promise , with $q.all
I have multiple api requests which can run in parallel.

getlocations, getstates, get territories can make a request in parallel. however once i have the states list from getstates() call, i need to make an api request for each individual state and parse the state object.

Here is the code that i have so far, Is it ok to call a promise within a promise this way ?

```<code>  getAllLocations() {
    //make a promise call for all here .
    var promise = [];
    //first prmise
    promise.push(this.getAllLocations(Id).then(
        (locationsData) => {
            this.locations = locationsData;
        }));
    //second promise
    promise.push(this.getAllStates(Id).then(
        (resp) => {
            this.states = resp.data;
            //for each state , need to make an api call and add to the state info
            angular.forEach(this.states, function(state){
                var nodeId = state.Id;
                this.getStateSummary(nodeId).then((resp) => {
                    state.healthStatus = resp.data.operationalStatus;
                });
            },this)
        }));
    //third promise
    promise.push(this.getAllterritories(Id).then(
        (resp) => {
            this.territories = resp.data;
        }));
    //after all promises parse teh location data
    $q.all(promise).then(() => {
        for (var i = 0; i < this.locations.length; i++) {
            //do something with with location here
        }
        this.gridData = this.locations;
    });
}
</code>```

if not , whats the best way to make teh getStatesummary() call ?

答:
you can use promise chain to send catch promises one after the another

```<code> getAllLocations() {
     //make a promise call for all here .
     var promise = [];
     //first prmise
     this.getAllLocations(Id)
         .then(
             (locationsData) => {
                 this.locations = locationsData;
                 promise.push(this.locations);

                 return this.getAllStates(Id)
             }).then(
             (resp) => {
                 this.states = resp;
                 //for each state , need to make an api call and add to the state info
                 angular.forEach(this.states, function(state) {
                     var nodeId = state.Id;
                     return this.getStateSummary(nodeId);
                 }, this)
                 return this.getAllterritories(Id);
             }).then((resp) => {
             state.healthStatus = resp.data.operationalStatus;
             promise.push(state.healthStatus);
         }).then(
             (resp) => {
                 this.territories = resp.data;
                 promise.push(this.territories);
                 this.callAll(promise)
             })
 }

 callAll(promise) {
     //after all promises parse teh location data
     this.$q.all(promise).then(() => {
         for (var i = 0; i < this.locations.length; i++) {
             //do something with with location here
         }
         this.gridData = this.locations;
     });
 }
</code>```

Body:
I have multiple api requests which can run in parallel.

getlocations, getstates, get territories can make a request in parallel. however once i have the states list from getstates() call, i need to make an api request for each individual state and parse the state object.

Here is the code that i have so far, Is it ok to call a promise within a promise this way ?

  getAllLocations() {
    //make a promise call for all here .
    var promise = [];
    //first prmise
    promise.push(this.getAllLocations(Id).then(
        (locationsData) => {
            this.locations = locationsData;
        }));
    //second promise
    promise.push(this.getAllStates(Id).then(
        (resp) => {
            this.states = resp.data;
            //for each state , need to make an api call and add to the state info
            angular.forEach(this.states, function(state){
                var nodeId = state.Id;
                this.getStateSummary(nodeId).then((resp) => {
                    state.healthStatus = resp.data.operationalStatus;
                });
            },this)
        }));
    //third promise
    promise.push(this.getAllterritories(Id).then(
        (resp) => {
            this.territories = resp.data;
        }));
    //after all promises parse teh location data
    $q.all(promise).then(() => {
        for (var i = 0; i < this.locations.length; i++) {
            //do something with with location here
        }
        this.gridData = this.locations;
    });
}

if not , whats the best way to make teh getStatesummary() call ?

Body:
you can use promise chain to send catch promises one after the another

 getAllLocations() {
     //make a promise call for all here .
     var promise = [];
     //first prmise
     this.getAllLocations(Id)
         .then(
             (locationsData) => {
                 this.locations = locationsData;
                 promise.push(this.locations);

                 return this.getAllStates(Id)
             }).then(
             (resp) => {
                 this.states = resp;
                 //for each state , need to make an api call and add to the state info
                 angular.forEach(this.states, function(state) {
                     var nodeId = state.Id;
                     return this.getStateSummary(nodeId);
                 }, this)
                 return this.getAllterritories(Id);
             }).then((resp) => {
             state.healthStatus = resp.data.operationalStatus;
             promise.push(state.healthStatus);
         }).then(
             (resp) => {
                 this.territories = resp.data;
                 promise.push(this.territories);
                 this.callAll(promise)
             })
 }

 callAll(promise) {
     //after all promises parse teh location data
     this.$q.all(promise).then(() => {
         for (var i = 0; i < this.locations.length; i++) {
             //do something with with location here
         }
         this.gridData = this.locations;
     });
 }


问:
JUnit test — analysing expected Exceptions
In JUnit, I'm currently using annotation to expect an exception in my tests.

Is there a way to analyse this exception? For example, I expect a CriticalServerException, but I also want to verify the content of the getMessage method.

答:
```<code>try
{
    // your code

    fail("Didn't throw expected exception");
}
catch(CriticalServerException e)
{
    assertEquals("Expected message", e.getMessage());
}
</code>```

ContentLicense: CC BY-SA 2.5


问:
Title image alignment in toolbar android
Why image in toolbar not align in center when remove the menu items in android.

If i have hide the menu items the title moved right.that is some spaces added between navigation icon and title.

My code

```<code><android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:contentInsetRight="0dp"
app:contentInsetStartWithNavigation="0dp"
android:background="#FFF">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:id="@+id/pg_title"
android:layout_centerHorizontal="true"
android:src="@drawable/logo"
/>
</LinearLayout>
</android.support.v7.widget.Toolbar>
</code>```

答:
try this add this toolbar in your layout xml file

```<code>   <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.PopupOverlay">

        <include layout="@layout/actionbar_layout" />

    </android.support.v7.widget.Toolbar>
</code>```

create a new actionbar_layout for your toolbar like this

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_bike" />
</LinearLayout>
</code>```

now in your activity file just add below code

```<code>    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("");
</code>```

ask me in case of any query

Body:
Why image in toolbar not align in center when remove the menu items in android.

If i have hide the menu items the title moved right.that is some spaces added between navigation icon and title.

My code

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:contentInsetRight="0dp"
app:contentInsetStartWithNavigation="0dp"
android:background="#FFF">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:id="@+id/pg_title"
android:layout_centerHorizontal="true"
android:src="@drawable/logo"
/>
</LinearLayout>
</android.support.v7.widget.Toolbar>

Body:
try this add this toolbar in your layout xml file

   <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.PopupOverlay">

        <include layout="@layout/actionbar_layout" />

    </android.support.v7.widget.Toolbar>

create a new actionbar_layout for your toolbar like this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_bike" />
</LinearLayout>

now in your activity file just add below code

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("");

ask me in case of any query


问:
In App Purchase Restore isn't working
I followed this link to do In app purchase(http://troybrant.net/blog/2010/01/in-app-purchases-a-full-walkthrough/comment-page-20/#comment-22550). Using Sandbox test User(with US territory) i can purchase the product successfully.i need to restore the product if again i press the Purchase button. how can i know whether the product has already purchased or not? and i need to validate the receipt for auto renewal subscription. how can i do? using objective c.</p>

答:
First, implement a custom payment class conforms protocol SKPaymentTransactionObserver. This class could be used to receive payment information:

.h:

```<code>#import <StoreKit/StoreKit.h>

@interface PaymentObserver : NSObject<SKPaymentTransactionObserver>
+ (instancetype)sharedInstance;
@end
</code>```

.m:

```<code>@implementation PaymentObserver

+ (instancetype)sharedInstance{
    static PaymentObserver * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[PaymentObserver alloc] init];
    });
    return instance;
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
                // Call the appropriate custom method for the transaction state.
            case SKPaymentTransactionStatePurchasing:
                break;
            case SKPaymentTransactionStateDeferred:
                break;
            case SKPaymentTransactionStateFailed:
                break;
            case SKPaymentTransactionStatePurchased:
                break;
            case SKPaymentTransactionStateRestored:
                //Purchased product info goes here. Get more details in transaction object.
                break;
            default:
                break;
        }
    }
}
</code>```

Then, in AppDelegate, use above class to retrieve payment information:

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //......
    [[SKPaymentQueue defaultQueue] addTransactionObserver:[PaymentObserver sharedInstance]];
    //......
}
</code>```

The PaymentObserver class will get the purchased product info from AppStore.

Main procedure is like this. There are more details you are going to handle them.

Title: In App Purchase Restore isn't working

Body:
First, implement a custom payment class conforms protocol SKPaymentTransactionObserver. This class could be used to receive payment information:

.h:

#import <StoreKit/StoreKit.h>

@interface PaymentObserver : NSObject<SKPaymentTransactionObserver>
+ (instancetype)sharedInstance;
@end

.m:

@implementation PaymentObserver

+ (instancetype)sharedInstance{
    static PaymentObserver * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[PaymentObserver alloc] init];
    });
    return instance;
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
    for (SKPaymentTransaction *transaction in transactions) {
        switch (transaction.transactionState) {
                // Call the appropriate custom method for the transaction state.
            case SKPaymentTransactionStatePurchasing:
                break;
            case SKPaymentTransactionStateDeferred:
                break;
            case SKPaymentTransactionStateFailed:
                break;
            case SKPaymentTransactionStatePurchased:
                break;
            case SKPaymentTransactionStateRestored:
                //Purchased product info goes here. Get more details in transaction object.
                break;
            default:
                break;
        }
    }
}

Then, in AppDelegate, use above class to retrieve payment information:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    //......
    [[SKPaymentQueue defaultQueue] addTransactionObserver:[PaymentObserver sharedInstance]];
    //......
}

The PaymentObserver class will get the purchased product info from AppStore.

Main procedure is like this. There are more details you are going to handle them.


问:
which javascript chart library should use for interactive chart
I know this question has been asked extensively,so now I confused between options. I want to create application which use populate charts on browser. chart should be interactive and it's conventional chart (pie,bar etc). I liked to go to for D3 but it seems I may fall short on time basis to learn that. so I checked on other libraries like google chart,DC,morris,C3,nvd3,ember chart where DC,C3,nvd3 are create on top of D3. google chart may be restricted due to security reasons. so which library should I prefer? should I go for google one if no security measures are there or any alternative are there?please help me out because as I am digging more,more I am getting confused and I am running out of time to create PoCs for this libraries</p>

答:
Try to explore this list: https://en.wikipedia.org/wiki/Comparison_of_JavaScript_charting_frameworks

If your project is non-profit, I'd suggest AnyChart because then you'll be able to use it for free. It has a lot of chart types, ways to work with data, customization options, and ready-to-use samples, as well as comprehensive documentation and API reference.


问:
Autogrow textarea height 0px?
After init i have this:

```<code>  ngAfterViewInit(){
        this.autogrow();
    }
</code>```

My function is this:

```<code> autogrow(){
        let elements = (<HTMLScriptElement[]><any>document.querySelectorAll('.textarea'));
            elements.forEach(function(elem,index) {
                elem.style.height = (elem.scrollHeight) + 'px';
            });
    }
</code>```

But problem is that i get height 0px for every textarea. Any suggestion how can i fix that?

答:
Why dont you set the height in the html using

```<code><textarea
  [style.height]="YourGetterWhichReturnsHeightInString"
</textarea>
</code>```

Getter returns the scrollHeight

Title: Autogrow textarea height 0px?

Body:
After init i have this:

  ngAfterViewInit(){
        this.autogrow();
    }

My function is this:

 autogrow(){
        let elements = (<HTMLScriptElement[]><any>document.querySelectorAll('.textarea'));
            elements.forEach(function(elem,index) {
                elem.style.height = (elem.scrollHeight) + 'px';
            });
    }

But problem is that i get height 0px for every textarea. Any suggestion how can i fix that?

Body:
Why dont you set the height in the html using

<textarea
  [style.height]="YourGetterWhichReturnsHeightInString"
</textarea>

Getter returns the scrollHeight


问:
How to have an IIS Application run a simple command?
So, let's say you have a website in IIS called Test. I want to be able to add an Application that simply runs foo.exe /runfoo when a user visits the page. Let's say I don't care about performance, "clean code", running the command too often, etc. This is for a proof-of-concept / part of a bigger toolkit.

What I have tried and have working is that I can deploy a full C# Web App with all the DLLs/other junk, and have it create a Process and run it. I don't want to have to do that. The ideal scenario is that I would create an Application under an existing website which has a separate app pool (that I can change), and within that I could modify the web.config or something to do with the app pool to have it run a command. A simple Application, with a single folder, with minimal files in it.

Some requirements:

The command can run regularly rather than only when a user visits a page, but that's not as preferable.

The command must be able to take arguments.

Minimal files needed in the Application directory.

I've looked through all of the existing options I could find, and none of them stuck out to me as something that'd be useful for this except the "Process Orphaning" in the App Pool settings. Is there a way to trigger this by visiting the page (without deploying a full-fledged web app)?

答:
Edit:

Looks like this is a research work doing on offensive security technique and what this requirements from IIS

The command can run regularly rather than only when a user visits a
page, but that's not as preferable.

The command must be able to take
arguments.

Minimal files needed in the Application directory.

You can run an exe as CGI executable in IIS as explained here . This article talks about passing query string value . Also explore fastCGI as well for an improvement on CGI

Edit 2:Adding another option

You can also simply put a simple aspx and it's code behind in a IIS
  website's content and can access that aspx page. No Compilation,No
  deployment,no bin directory etc.All you need is two files

Create two files default.aspx and Default.aspx.cs inside your IIS website

Here's the code

Default.aspx

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>
</code>```

and Default.aspx.cs file

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
            Process process = new Process();
            process.StartInfo.FileName = "echo.exe";
            process.Start();
    }
}
</code>```

Body:
Edit:

Looks like this is a research work doing on offensive security technique and what this requirements from IIS

The command can run regularly rather than only when a user visits a
page, but that's not as preferable.

The command must be able to take
arguments.

Minimal files needed in the Application directory.

You can run an exe as CGI executable in IIS as explained here . This article talks about passing query string value . Also explore fastCGI as well for an improvement on CGI

Edit 2:Adding another option

You can also simply put a simple aspx and it's code behind in a IIS
  website's content and can access that aspx page. No Compilation,No
  deployment,no bin directory etc.All you need is two files

Create two files default.aspx and Default.aspx.cs inside your IIS website

Here's the code

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>

and Default.aspx.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
            Process process = new Process();
            process.StartInfo.FileName = "echo.exe";
            process.Start();
    }
}


问:
Catch HttpException in time when file upload exceeds size
so i am making a file upload. I have, in my web.config:

<httpRuntime executionTimeout="300" maxRequestLength="5120"/>

so the file can't exceed 5MB.

My server side code looks something like:

protected void button_Click(object sender, EventArgs e) {

      try
      {

```<code>    if (fupCV.FileName != "") {
     DirectoryInfo di = new DirectoryInfo(Server.MapPath("CVs"));
     if (!di.Exists)
         di.Create();
     fupCV.SaveAs(di.FullName + "/" + fupCV.FileName);
     //afterwards code
    }
}
catch (HttpException ex) {
    Response.Write(ex.Message);
}
</code>```

}

and i can't catch the exception, i still get "Server Error in '/' Application."

Thanx for the help

答:
That's because the request never reach your code, IIS never passes the request to your code because it is to big.

I guess the only thing you can do is to upload via ajax and control the error code returned from your server.

Body:
so i am making a file upload. I have, in my web.config:

<httpRuntime executionTimeout="300" maxRequestLength="5120"/>

so the file can't exceed 5MB.

My server side code looks something like:

protected void button_Click(object sender, EventArgs e) {

      try
      {

    if (fupCV.FileName != "") {
     DirectoryInfo di = new DirectoryInfo(Server.MapPath("CVs"));
     if (!di.Exists)
         di.Create();
     fupCV.SaveAs(di.FullName + "/" + fupCV.FileName);
     //afterwards code
    }
}
catch (HttpException ex) {
    Response.Write(ex.Message);
}

}

and i can't catch the exception, i still get "Server Error in '/' Application."

Thanx for the help


问:
Prefetch data with React Router 4
I'm trying to migrate to v4 of React Router and I'm stuck with the prefetch data. The latests versions we used to have match function.

One of the returning parameters was renderProps but now I can't use match so I don't know how to prefetch data. The documentation shows how to load data but doesn't works for me because I'm using the new version of react-router-redux to sync the store.

Here's the code the client:

```<code>return (
  <MuiThemeProvider muiTheme={letgoMuiTheme}>
    <Provider store={store}>
      <IntlProvider>
        { routes(history, store) }
      </IntlProvider>
  </Provider>
</MuiThemeProvider>
);
</code>```

Routes:

```<code>export default function routes(history) {
  return (
    <ConnectedRouter history={history}>
      <Switch>
        <Route exact path="/" component={App} />
        <Route path="/:lang/chat" component={Chat} />
        ...
        <Route path="*" component={NotFound} status={404} />
      </Switch>
    </ConnectedRouter>
  );
}
</code>```

Server:

```<code>if (context.url) {
  res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else {
  const render = () => {
    const body = renderToString(
      <StaticRouter
        location={req.url}
        context={context}
      >
        <MuiThemeProvider muiTheme={muiTheme}>
          <Provider store={store}>
            <IntlProvider>
              { routes(history, store) }
            </IntlProvider>
          </Provider>
        </MuiThemeProvider>,
      </StaticRouter>
    );

    res.setHeader('content-language', locale);
    res.render('index', {
      head,
      body,
      locale,
      state: stringState,
      ...
    });
  };

  Promise.all(
    prefetchData(renderProps, store),
  )
  .then(render)
  .catch(prefetchError => next(prefetchError));
}
</code>```

That's my old server file:

```<code>    match({ history, routes, location: req.url }, (error, redirectLocation, renderProps) => {
      if (error) {
        throw error;
      } else if (redirectLocation) {
        res.redirect(302, redirectLocation.pathname + redirectLocation.search);
      } else if (renderProps) {
        // Render react components once store is initializaed and return HTTP response
        const render = () => {
          const body = renderToString(
            <MuiThemeProvider muiTheme={muiTheme}>
              <Provider store={store}>
                <IntlProvider>
                  <RouterContext {...renderProps} />
                </IntlProvider>
              </Provider>
            </MuiThemeProvider>,
          );

          res.setHeader('content-language', locale);
          res.render('index', {
            head,
            newrelicScript,
            body,
            locale,
            state: stringState,
            ...
          });
        };

        // Fetch components data and render HTML (no matter the fetch results
        // we need to render something)
        Promise.all(
          prefetchData(renderProps, store),
        )
        .then(render)
        .catch(prefetchError => next(prefetchError));
      } else {
        logger.warning('Ops !!! We should never arrive here :(');
        next();
      }
    });
</code>```

And prefetch data:

```<code>export const prefetchData = (renderProps, store) => {
  const { components, params } = renderProps;
  const { dispatch } = store;
  const state = store.getState();
  const extractWrappedComponent = (component) => {
    if (component.WrappedComponent) {
      return extractWrappedComponent(component.WrappedComponent);
    }
    return component;
  };

  return components
    .filter(component => component !== undefined)
    // Get component, be aware if they are wrapped by redux connect or intl.
    .map(component => extractWrappedComponent(component))
    // Get the fetchData method of each component
    .map(component => component.fetchData)
    .filter(fetchData => fetchData !== undefined)
    // Invoke each fetchData to initialize the redux state.
    .map(fetchData => fetchData(state, dispatch, params));
};
</code>```

答:
After looking into it, I found a solution that works for me. This is the helper (before was prefetchData). matchPath is from react-router-dom.

```<code>export const getRouteData = (routesArray, url, store) => {
  const { dispatch } = store;
  const state = store.getState();
  const extractWrappedComponent = (component) => {
    if (component.WrappedComponent) {
      return extractWrappedComponent(component.WrappedComponent);
    }
    return component;
  };

  return routesArray.map((route) => {
    const component = route.component;
    const extractedComponent = extractWrappedComponent(component);
    const match = matchPath(url, { path: route.path, exact: route.exact, strict: false });

    if (match) {
      if (extractedComponent.fetchData !== undefined) {
        extractedComponent.fetchData(state, dispatch, match.params);
      }
    }
  });
}
</code>```

Then I call it:

```<code>getRouteData(routes, req.url, store);
</code>```

Were routes is a static routes:

```<code>export const routes = [
  {
    path: '/',
    component: App
  },
  {
    path: '/:lang/chat',
    component: Chat
  }
  ...
</code>```

My server file now does not have match. Instead:

```<code>if (context.url) {
  res.redirect(302, context.url);
} else {
  const render = () => {
    const body = renderApp(req, muiTheme, store, history, context);

    res.render('index', {
      head,
      body,
      locale,
      ...
    });
  };

  Promise.all(
    getRouteData(routes, req.url, store),
  )
  .then(render)
  .catch(prefetchError => next(prefetchError));
</code>```

RenderApp file (Client has to be the same without StaticRouter):

```<code>const renderApp = (req, muiTheme, store, history, context) => {
  const app = (
    <MuiThemeProvider muiTheme={muiTheme}>
      <Provider store={store}>
        <IntlProvider>
          <StaticRouter
            location={req.url}
            context={context}
          >
            { appRoutes(history) }
          </StaticRouter>
        </IntlProvider>
      </Provider>
    </MuiThemeProvider>
  );

  return renderToString(app);
};
</code>```

appRoutes file:

```<code>export default function appRoutes(history) {
  return (
    <ConnectedRouter history={history}>
      <div>
        {routes.map((route, key) => (
          <Route key={key} {...route} />
        ))}
      </div>
    </ConnectedRouter>
  );
}
</code>```

Title: Prefetch data with React Router 4

Body:
I'm trying to migrate to v4 of React Router and I'm stuck with the prefetch data. The latests versions we used to have match function.

One of the returning parameters was renderProps but now I can't use match so I don't know how to prefetch data. The documentation shows how to load data but doesn't works for me because I'm using the new version of react-router-redux to sync the store.

Here's the code the client:

return (
  <MuiThemeProvider muiTheme={letgoMuiTheme}>
    <Provider store={store}>
      <IntlProvider>
        { routes(history, store) }
      </IntlProvider>
  </Provider>
</MuiThemeProvider>
);

Routes:

export default function routes(history) {
  return (
    <ConnectedRouter history={history}>
      <Switch>
        <Route exact path="/" component={App} />
        <Route path="/:lang/chat" component={Chat} />
        ...
        <Route path="*" component={NotFound} status={404} />
      </Switch>
    </ConnectedRouter>
  );
}

Server:

if (context.url) {
  res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else {
  const render = () => {
    const body = renderToString(
      <StaticRouter
        location={req.url}
        context={context}
      >
        <MuiThemeProvider muiTheme={muiTheme}>
          <Provider store={store}>
            <IntlProvider>
              { routes(history, store) }
            </IntlProvider>
          </Provider>
        </MuiThemeProvider>,
      </StaticRouter>
    );

    res.setHeader('content-language', locale);
    res.render('index', {
      head,
      body,
      locale,
      state: stringState,
      ...
    });
  };

  Promise.all(
    prefetchData(renderProps, store),
  )
  .then(render)
  .catch(prefetchError => next(prefetchError));
}

That's my old server file:

    match({ history, routes, location: req.url }, (error, redirectLocation, renderProps) => {
      if (error) {
        throw error;
      } else if (redirectLocation) {
        res.redirect(302, redirectLocation.pathname + redirectLocation.search);
      } else if (renderProps) {
        // Render react components once store is initializaed and return HTTP response
        const render = () => {
          const body = renderToString(
            <MuiThemeProvider muiTheme={muiTheme}>
              <Provider store={store}>
                <IntlProvider>
                  <RouterContext {...renderProps} />
                </IntlProvider>
              </Provider>
            </MuiThemeProvider>,
          );

          res.setHeader('content-language', locale);
          res.render('index', {
            head,
            newrelicScript,
            body,
            locale,
            state: stringState,
            ...
          });
        };

        // Fetch components data and render HTML (no matter the fetch results
        // we need to render something)
        Promise.all(
          prefetchData(renderProps, store),
        )
        .then(render)
        .catch(prefetchError => next(prefetchError));
      } else {
        logger.warning('Ops !!! We should never arrive here :(');
        next();
      }
    });

And prefetch data:

export const prefetchData = (renderProps, store) => {
  const { components, params } = renderProps;
  const { dispatch } = store;
  const state = store.getState();
  const extractWrappedComponent = (component) => {
    if (component.WrappedComponent) {
      return extractWrappedComponent(component.WrappedComponent);
    }
    return component;
  };

  return components
    .filter(component => component !== undefined)
    // Get component, be aware if they are wrapped by redux connect or intl.
    .map(component => extractWrappedComponent(component))
    // Get the fetchData method of each component
    .map(component => component.fetchData)
    .filter(fetchData => fetchData !== undefined)
    // Invoke each fetchData to initialize the redux state.
    .map(fetchData => fetchData(state, dispatch, params));
};

Body:
After looking into it, I found a solution that works for me. This is the helper (before was prefetchData). matchPath is from react-router-dom.

export const getRouteData = (routesArray, url, store) => {
  const { dispatch } = store;
  const state = store.getState();
  const extractWrappedComponent = (component) => {
    if (component.WrappedComponent) {
      return extractWrappedComponent(component.WrappedComponent);
    }
    return component;
  };

  return routesArray.map((route) => {
    const component = route.component;
    const extractedComponent = extractWrappedComponent(component);
    const match = matchPath(url, { path: route.path, exact: route.exact, strict: false });

    if (match) {
      if (extractedComponent.fetchData !== undefined) {
        extractedComponent.fetchData(state, dispatch, match.params);
      }
    }
  });
}

Then I call it:

getRouteData(routes, req.url, store);

Were routes is a static routes:

export const routes = [
  {
    path: '/',
    component: App
  },
  {
    path: '/:lang/chat',
    component: Chat
  }
  ...

My server file now does not have match. Instead:

if (context.url) {
  res.redirect(302, context.url);
} else {
  const render = () => {
    const body = renderApp(req, muiTheme, store, history, context);

    res.render('index', {
      head,
      body,
      locale,
      ...
    });
  };

  Promise.all(
    getRouteData(routes, req.url, store),
  )
  .then(render)
  .catch(prefetchError => next(prefetchError));

RenderApp file (Client has to be the same without StaticRouter):

const renderApp = (req, muiTheme, store, history, context) => {
  const app = (
    <MuiThemeProvider muiTheme={muiTheme}>
      <Provider store={store}>
        <IntlProvider>
          <StaticRouter
            location={req.url}
            context={context}
          >
            { appRoutes(history) }
          </StaticRouter>
        </IntlProvider>
      </Provider>
    </MuiThemeProvider>
  );

  return renderToString(app);
};

appRoutes file:

export default function appRoutes(history) {
  return (
    <ConnectedRouter history={history}>
      <div>
        {routes.map((route, key) => (
          <Route key={key} {...route} />
        ))}
      </div>
    </ConnectedRouter>
  );
}


问:
Client-side js: check file encoding
I have to validate on client side that my downloading file is UTF-8 encoded. How can I do it?
Maybe something with FileReader.readAsArrayBuffer()

答:
try this:

reader.readAsText(file, 'ISO-8859-1');

may be it will help to you.

Title: Client-side js: check file encoding


问:
Global connection already exists issue node.js
I have connected MSSQl with node.js using below code

```<code>           var sql = require('mssql')
            var config ={
            server:'xxxx',
            database:'xxxx',
            user:'xxx',
            password:'xxx',
            port:'xx'
            };
            sql.connect(dbconfig, function (err) {

                if (err) console.log(err);

                  var sqlquery='';
                const request = new sql.Request();
                if(condition)
        {
            //query to the database and get the repo value
                sqlquery='select * from verylargetable';
                request.query(sqlquery, function (err, result) {
                    if (err) console.log(err)
                   var repo=result.recordset[0].Repo;

         //query to the database and get the comm value
                  sqlquery="select commit from verylargetable where Repo='"+repo+"'";
                request.query(sqlquery, function (err, result) {
                    if (err) console.log(err)
                  var comm=result.recordset[0].Comm;
                 if (result.recordset.length  > 0)
        {
//query to the database and update the table
         sqlquery="UPDATE verylargetable set Repo='"+repo+"', WHERE Comm='"+comm+"'";
        request.query(sqlquery, function (err,result){
                 if (err) console.log(err)
                   console.log("record(s) updated");
               });
              }
           });
         });
        }
        else
        {
        //query to the database and get the repo value
                sqlquery='select * from verylargetable';
                request.query(sqlquery, function (err, result) {
                    if (err) console.log(err)
                   var repo=result.recordset[0].Repo;
    //query to the databaseto insert new record
        sqlquery ="INSERT INTO verylargetable VALUES("+repo+"','"+comm+"',1)";
    request.query(sqlquery, function (err, result) {
            if (err) console.log(err)
           });
        });
       }
    });
</code>```

Based on some conditions have to execute queries. while executing, these queries are updated properly.but sometimes facing below issue

global connection already exists. call sql.close() first.

when i used sql.close() at the end i couldn't initialize connection next time.

Facing connection is closed issue.

I have separate method for database changes.I need to establish the connection at the start of the method and have to close at the end.In between have to execute all the queries.
please let me know how to open and close the connection properly?

答:
I was facing the same issue and solved it with below implementation,
For handling global connection already exists. call sql.close() first  we need to create a connection pool for mssql npm version 4.0.4

```<code>const config = {
user: '**',
password: '**',
server: '** or localhost',
database: '**',
pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
}}
router.get('/SQLConnection1', function (req, res, next) {
const pool1 = new sql.ConnectionPool(config, err => {
    // ... error checks

    // Query

    pool1.request() // or: new sql.Request(pool1)
        .query('SELECT ID,Name  from Avatar', (err, result) => {
            // ... error checks

            console.dir(result)
            res.json({'Result': result})
        })
})
pool1.on('error', err => {
    // ... error handler
    console.log('Error ' + err);
})
</code>```

});

Body:
I have connected MSSQl with node.js using below code

           var sql = require('mssql')
            var config ={
            server:'xxxx',
            database:'xxxx',
            user:'xxx',
            password:'xxx',
            port:'xx'
            };
            sql.connect(dbconfig, function (err) {

                if (err) console.log(err);

                  var sqlquery='';
                const request = new sql.Request();
                if(condition)
        {
            //query to the database and get the repo value
                sqlquery='select * from verylargetable';
                request.query(sqlquery, function (err, result) {
                    if (err) console.log(err)
                   var repo=result.recordset[0].Repo;

         //query to the database and get the comm value
                  sqlquery="select commit from verylargetable where Repo='"+repo+"'";
                request.query(sqlquery, function (err, result) {
                    if (err) console.log(err)
                  var comm=result.recordset[0].Comm;
                 if (result.recordset.length  > 0)
        {
//query to the database and update the table
         sqlquery="UPDATE verylargetable set Repo='"+repo+"', WHERE Comm='"+comm+"'";
        request.query(sqlquery, function (err,result){
                 if (err) console.log(err)
                   console.log("record(s) updated");
               });
              }
           });
         });
        }
        else
        {
        //query to the database and get the repo value
                sqlquery='select * from verylargetable';
                request.query(sqlquery, function (err, result) {
                    if (err) console.log(err)
                   var repo=result.recordset[0].Repo;
    //query to the databaseto insert new record
        sqlquery ="INSERT INTO verylargetable VALUES("+repo+"','"+comm+"',1)";
    request.query(sqlquery, function (err, result) {
            if (err) console.log(err)
           });
        });
       }
    });

Based on some conditions have to execute queries. while executing, these queries are updated properly.but sometimes facing below issue

global connection already exists. call sql.close() first.

when i used sql.close() at the end i couldn't initialize connection next time.

Facing connection is closed issue.

I have separate method for database changes.I need to establish the connection at the start of the method and have to close at the end.In between have to execute all the queries.
please let me know how to open and close the connection properly?

Body:
I was facing the same issue and solved it with below implementation,
For handling global connection already exists. call sql.close() first  we need to create a connection pool for mssql npm version 4.0.4

const config = {
user: '**',
password: '**',
server: '** or localhost',
database: '**',
pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
}}
router.get('/SQLConnection1', function (req, res, next) {
const pool1 = new sql.ConnectionPool(config, err => {
    // ... error checks

    // Query

    pool1.request() // or: new sql.Request(pool1)
        .query('SELECT ID,Name  from Avatar', (err, result) => {
            // ... error checks

            console.dir(result)
            res.json({'Result': result})
        })
})
pool1.on('error', err => {
    // ... error handler
    console.log('Error ' + err);
})

});


问:
NullPointerException when Creating an Array of objects
I have been trying to create an array of a class containing two values, but when I try to apply a value to the array I get a NullPointerException.

```<code>public class ResultList {
    public String name;
    public Object value;
}
</code>```

```<code>public class Test {
    public static void main(String[] args){
        ResultList[] boll = new ResultList[5];
        boll[0].name = "iiii";
    }
}
</code>```

Why am I getting this exception and how can I fix it?

答:
```<code>ResultList p[] = new ResultList[2];
</code>```

<p>By writing this you just allocate space for a array of 2 elements.
You should initialize the reference variable by doing this: </p>

```<code>for(int i = 0; i < 2; i++){
    p[i] = new ResultList();
 }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have been trying to create an array of a class containing two values, but when I try to apply a value to the array I get a NullPointerException.

public class ResultList {
    public String name;
    public Object value;
}

public class Test {
    public static void main(String[] args){
        ResultList[] boll = new ResultList[5];
        boll[0].name = "iiii";
    }
}

Why am I getting this exception and how can I fix it?

Body:
ResultList p[] = new ResultList[2];

By writing this you just allocate space for a array of 2 elements.
You should initialize the reference variable by doing this:

for(int i = 0; i < 2; i++){
    p[i] = new ResultList();
 }


问:
Show audio files from document directory in tableview and play audio files on selecting row in swift 3
I am saving audio recordings files in iPhone document directory and shows save files in tableview, but on selecting saved audio files could not play.</p>

答:
i used collection view for that you can simply replace did select method of  collection view with tableView </p>

```<code>import UIKit
import AVFoundation

let reuseIdentifier = "recordingCell"

class RecordingsCollectionViewController: UICollectionViewController {

    var recordings = [URL]()
    var player:AVAudioPlayer!

    override func viewDidLoad() {
        super.viewDidLoad()
        listRecordings()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.recordings.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! RecordingCollectionViewCell

        cell.label.text = recordings[(indexPath as NSIndexPath).row].lastPathComponent

        return cell
    }

    // MARK: UICollectionViewDelegate

    override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
        return true
    }

    override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        return true
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        print("selected \(recordings[(indexPath as NSIndexPath).row].lastPathComponent)")
        play(recordings[(indexPath as NSIndexPath).row])

    }

    func play(_ url:URL) {
        print("playing \(url)")

        do {
            self.player = try AVAudioPlayer(contentsOf: url)
            player.prepareToPlay()
            player.volume = 1.0
            player.play()
        } catch let error as NSError {
            self.player = nil
            print(error.localizedDescription)
        } catch {
            print("AVAudioPlayer init failed")
        }

    }
    func listRecordings() {

        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        do {
            let urls = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
            self.recordings = urls.filter( { (name: URL) -> Bool in
                return name.lastPathComponent.hasSuffix("m4a")
            })

        } catch let error as NSError {
            print(error.localizedDescription)
        } catch {
            print("something went wrong listing recordings")
        }

    }
}

extension RecordingsCollectionViewController: FileManagerDelegate {

    func fileManager(_ fileManager: FileManager, shouldMoveItemAt srcURL: URL, to dstURL: URL) -> Bool {

        print("should move \(srcURL) to \(dstURL)")
        return true
    }

}
</code>```

Body:
i used collection view for that you can simply replace did select method of  collection view with tableView

import UIKit
import AVFoundation

let reuseIdentifier = "recordingCell"

class RecordingsCollectionViewController: UICollectionViewController {

    var recordings = [URL]()
    var player:AVAudioPlayer!

    override func viewDidLoad() {
        super.viewDidLoad()
        listRecordings()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.recordings.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! RecordingCollectionViewCell

        cell.label.text = recordings[(indexPath as NSIndexPath).row].lastPathComponent

        return cell
    }

    // MARK: UICollectionViewDelegate

    override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
        return true
    }

    override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        return true
    }

    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        print("selected \(recordings[(indexPath as NSIndexPath).row].lastPathComponent)")
        play(recordings[(indexPath as NSIndexPath).row])

    }

    func play(_ url:URL) {
        print("playing \(url)")

        do {
            self.player = try AVAudioPlayer(contentsOf: url)
            player.prepareToPlay()
            player.volume = 1.0
            player.play()
        } catch let error as NSError {
            self.player = nil
            print(error.localizedDescription)
        } catch {
            print("AVAudioPlayer init failed")
        }

    }
    func listRecordings() {

        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        do {
            let urls = try FileManager.default.contentsOfDirectory(at: documentsDirectory, includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
            self.recordings = urls.filter( { (name: URL) -> Bool in
                return name.lastPathComponent.hasSuffix("m4a")
            })

        } catch let error as NSError {
            print(error.localizedDescription)
        } catch {
            print("something went wrong listing recordings")
        }

    }
}

extension RecordingsCollectionViewController: FileManagerDelegate {

    func fileManager(_ fileManager: FileManager, shouldMoveItemAt srcURL: URL, to dstURL: URL) -> Bool {

        print("should move \(srcURL) to \(dstURL)")
        return true
    }

}


问:
Jquery .click function not working on chrome but fine on firefox
I found same question also posted on stackoverflow but i didn't get right answer so i posted its again what is the reason jquery click function working on firefox but not working on chrome
Jquery

```<code>$("#companypancard").click(function(){

            $(".nav a.active").removeClass("active");
            $("#registrationandlicenses").addClass("active");
            $("#sab2d").hide();

            $("#header-box-content").hide();
            $(".entire-box-content").show();
            $(".line, .back").show();

            $(".h1-content").html("Company Pancard");
            $(".p-discription").html("PAN is mandatory for every organization for financial transition and open a bank account.");
        });
        $("#registrationandlicenses").mouseenter(function(){$("#sab2d").show();});
        $("#sab2d").mouseleave(function(){$("#sab2d").hide();});
</code>```

EDIT

JSFiddle Is created here

**my code is working on js fiddle but when i upload on server not working on chrome but working on firefox..my 3rd tab is register your business its all sub menu working same code i use on next tab registration and licenses (first submenu) company pan card not working... **

答:
https://jsfiddle.net/o2gxgz9r/9480/

https://jsfiddle.net/o2gxgz9r/9481/

```<code>$(document).on('click', '#companypancard',function(){

});
$("#companypancard").click(function(){

});
</code>```

Both scenario are working in chrome. So check whether your jquery has loaded properly in your page and check your chrome version was supported to your jquery.

Again also you got an error .you just put your code in jsfiddle and send link.

Body:
I found same question also posted on stackoverflow but i didn't get right answer so i posted its again what is the reason jquery click function working on firefox but not working on chrome
Jquery

$("#companypancard").click(function(){

            $(".nav a.active").removeClass("active");
            $("#registrationandlicenses").addClass("active");
            $("#sab2d").hide();

            $("#header-box-content").hide();
            $(".entire-box-content").show();
            $(".line, .back").show();

            $(".h1-content").html("Company Pancard");
            $(".p-discription").html("PAN is mandatory for every organization for financial transition and open a bank account.");
        });
        $("#registrationandlicenses").mouseenter(function(){$("#sab2d").show();});
        $("#sab2d").mouseleave(function(){$("#sab2d").hide();});

EDIT

JSFiddle Is created here

**my code is working on js fiddle but when i upload on server not working on chrome but working on firefox..my 3rd tab is register your business its all sub menu working same code i use on next tab registration and licenses (first submenu) company pan card not working... **

Body:
https://jsfiddle.net/o2gxgz9r/9480/

https://jsfiddle.net/o2gxgz9r/9481/

$(document).on('click', '#companypancard',function(){

});
$("#companypancard").click(function(){

});

Both scenario are working in chrome. So check whether your jquery has loaded properly in your page and check your chrome version was supported to your jquery.

Again also you got an error .you just put your code in jsfiddle and send link.


问:
How to hide Ejabberd data from port scannig
I have ejabberd 16 running on ubuntu 16.04. I have secured the ejabberd with TLS encryption. But on port scanning I am able to see the stream_id, protocol, protocol version etc. Is there any way to hide that ? I tried disabling mod_version but there is no use. Can anyone point me in the right direction?

答: There is nothing to hide: stream id is a random number and version is always 1.0. The only problem might be a host name, but in recent versions ejabberd doesn't advertise it when generating an error for malformed XML.


问:
Disable boostrap toggle collapse for one class and enable it for another
I have a boostrap collapse button that looks like this:

```<code><button type="button" class="btn btn-info" data-toggle="collapse" data-target="#<?php echo $row['pid']; ?>">View more info</button>
    <div id="<?php echo $row['pid']; ?>" class="collapse">
        <?php
        //php code that display more info goes here
        }
        echo '</div>';
  ?>
</code>```

when user click this button, more information about the picture will be revealed. Because each picture has unique information, the div id and data-target of this button has to be the id of the picture in the database, otherwise no accurate information can be displayed.
However, I also have a like button, when a user clicked it, he will "liked" the picture, and it goes like this :

```<code><button type="button" class="like" id="<?php echo $row['pid']; ?>">Like <span><?php echo likes($row['pid']); ?></span></button>
</code>```

the id of the like button also has to be identical to the id of the picture in the database, because in the javascript code I use this id to know which picture's like button is being clicked, and then I can add the number of likes for that picture.

The problem is, both the like button and the collapse button have the same id(the id of the picture). When I clicked the collapse button, instead of showing more information about the picture, the number of likes is being hidden.  I tried to disabled boostrap collapse based on classes by the following code :

```<code><script>

    $('.like').bootstrapToggle('off');
   $('.collapse').bootstrapToggle('on');

</script>
</code>```

but it's not working. If I delete the "like" button everything will work smoothly, but after adding the like button, the collapse button would hide the like button when it's clicked. What can I do to not the the collapse button interfere with the likes button?

答:
So here is an example where you use the same id :

ABCD1234

on both elements but on the like button you apply it as a data attribute. When the button is clicked, you retrieve the id via the data attribute and then use it as a selector to update the like count on the appropriate matching collapsed content based on that id.

HTML

```<code><button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#ABCD1234" aria-expanded="false" aria-controls="collapseExample">
  Button with data-target
</button>
<div class="collapse" id="ABCD1234">
  <div class="well">
    <span>100</span> likes
  </div>
</div>

<br>
<button type="button" class="like" data-id="ABCD1234">Like <span>ABCD1234</span></button>
</code>```

JS

```<code>$('.like').click(function(){
  var thisID = '#' + $(this).data('id');
  var $count = $('span', thisID);
  var number = parseInt($count.text());
  $count.text(number+1);
});
</code>```

https://codepen.io/partypete25/pen/XgqBZX

Body:
I have a boostrap collapse button that looks like this:

<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#<?php echo $row['pid']; ?>">View more info</button>
    <div id="<?php echo $row['pid']; ?>" class="collapse">
        <?php
        //php code that display more info goes here
        }
        echo '
';
  ?>

when user click this button, more information about the picture will be revealed. Because each picture has unique information, the div id and data-target of this button has to be the id of the picture in the database, otherwise no accurate information can be displayed.
However, I also have a like button, when a user clicked it, he will "liked" the picture, and it goes like this :

<button type="button" class="like" id="<?php echo $row['pid']; ?>">Like <?php echo likes($row['pid']); ?></button>

the id of the like button also has to be identical to the id of the picture in the database, because in the javascript code I use this id to know which picture's like button is being clicked, and then I can add the number of likes for that picture.

The problem is, both the like button and the collapse button have the same id(the id of the picture). When I clicked the collapse button, instead of showing more information about the picture, the number of likes is being hidden.  I tried to disabled boostrap collapse based on classes by the following code :

but it's not working. If I delete the "like" button everything will work smoothly, but after adding the like button, the collapse button would hide the like button when it's clicked. What can I do to not the the collapse button interfere with the likes button?

Body:
So here is an example where you use the same id :

ABCD1234

on both elements but on the like button you apply it as a data attribute. When the button is clicked, you retrieve the id via the data attribute and then use it as a selector to update the like count on the appropriate matching collapsed content based on that id.

HTML

<button class="btn btn-primary" type="button" data-toggle="collapse" data-target="#ABCD1234" aria-expanded="false" aria-controls="collapseExample">
  Button with data-target
</button>
<div class="collapse" id="ABCD1234">
  <div class="well">
    <span>100</span> likes
  </div>
</div>

<br>
<button type="button" class="like" data-id="ABCD1234">Like <span>ABCD1234</span></button>

JS

$('.like').click(function(){
  var thisID = '#' + $(this).data('id');
  var $count = $('span', thisID);
  var number = parseInt($count.text());
  $count.text(number+1);
});

https://codepen.io/partypete25/pen/XgqBZX


问:
Custom Post Type taxonomy page still showing all posts
I have a sub-navigation for custom post type 'Projects' taxonomy called "Type":

```<code>        <?php $args = array( 'post_type' => 'projects');
        $the_query = new WP_Query( $args ); ?>
            <?php if ( $the_query->have_posts() ) : ?>
            <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
            <?php   $terms = get_terms('type');
            $currentterm = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
                echo '<ul class="sub-nav-menu">';
                foreach ($terms as $term) {
                    $class = $currentterm->slug == $term->slug ? 'live' : '' ;
                    echo '<li><a href="'.get_term_link($term).'" class="'. $class .'">'.$term->name.'</a></li>';
                    }
                echo '</ul>'; ?>
            <?php endwhile; ?>
            <?php endif; ?>
</code>```

When clicking on taxonomy it takes you to the taxonomy page taxonomy-type.php.

Although this page is still showing all the custom post types not just the ones for the current taxonomy page.

```<code><?php $args = array( 'post_type' => 'projects');
                    $the_query = new WP_Query( $args ); ?>
            <?php if ( $the_query->have_posts() ) : ?>
            <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
            <?php   $terms = get_terms('type'); ?>
            <a href="<?php the_permalink() ?>">
                <h3><?php the_title(); ?></h3>
            </a>
    <?php wp_reset_postdata(); ?>
    <?php endwhile; ?>
<?php endif; ?>
</code>```

How should I modify the loop to filter only the current taxonomy posts of the 'Type' taxonomy?

答:
you can get post list by taxonomy in taxonomy-{post_type}.php In this file by default gt list of post for specified taxonomy.

Create like this file in current active theme folder and use below code,

```<code><?php
if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        //
        // Post Content here
        //
    } // end while
} // end if
?>
</code>```

Body:
I have a sub-navigation for custom post type 'Projects' taxonomy called "Type":

        <?php $args = array( 'post_type' => 'projects');
        $the_query = new WP_Query( $args ); ?>
            <?php if ( $the_query->have_posts() ) : ?>
            <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
            <?php   $terms = get_terms('type');
            $currentterm = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
                echo '
';
                foreach ($terms as $term) {
                    $class = $currentterm->slug == $term->slug ? 'live' : '' ;
                    echo '
'.$term->name.'
';
                    }
                echo '
'; ?>
            <?php endwhile; ?>
            <?php endif; ?>

When clicking on taxonomy it takes you to the taxonomy page taxonomy-type.php.

Although this page is still showing all the custom post types not just the ones for the current taxonomy page.

<?php $args = array( 'post_type' => 'projects');
                    $the_query = new WP_Query( $args ); ?>
            <?php if ( $the_query->have_posts() ) : ?>
            <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
            <?php   $terms = get_terms('type'); ?>
            <a href="<?php the_permalink() ?>">

<?php the_title(); ?>

    <?php wp_reset_postdata(); ?>
    <?php endwhile; ?>
<?php endif; ?>

How should I modify the loop to filter only the current taxonomy posts of the 'Type' taxonomy?

Body:
you can get post list by taxonomy in taxonomy-{post_type}.php In this file by default gt list of post for specified taxonomy.

Create like this file in current active theme folder and use below code,

<?php
if ( have_posts() ) {
    while ( have_posts() ) {
        the_post();
        //
        // Post Content here
        //
    } // end while
} // end if
?>


问:
Toggle two divs query
Hi i would like to toggle two divs. I made it basic way but i really want to write it this way and i have no idea what is wrong with this. Could someone help me with it ? </p>

```<code>    (function($) {

    var showAll = function() {
        this.$button = this.find('.btn-all-events');
        this.$all = this.find('.all-events');
        this.$recent = this.find('.recent-events');

        this.initEvents();
    };

    showAll.prototype = {
        initEvents: function() {

            if (this.$all) {
                this.$button.on('click', this.showEvents.bind(this));
            }
        },

        showEvents: function() {
            this.$recent.hide();
            this.$all.show();
        }
    };

    this.toggle = new showAll($(this));
})(jQuery);
</code>```

答:
Toggle div simply using jquery . You can check here https://jsfiddle.net/surendra786/os09Lhfw/

```<code>html --
   <div class="main">
    <div class="first">Divdfasdfasdfsd</div>
    <div class="second hide">afsdfasfasdfasdfsdf</div>
   </div>
  <a class="toggle">toggle</a>

css--

<style>
 .hide {
display:none;
 }
</style>

 js---

 $('.toggle').click(function(){
if($('.first').hasClass('hide')){
$('.first').removeClass('hide');
} else {
$('.first').addClass('hide');
}
if($('.second').hasClass('hide')){
$('.second').removeClass('hide');
 } else {
$('.second').addClass('hide');
 }
});
</code>```

try this it should work, please up if working

Title: Toggle two divs query

Body:
Hi i would like to toggle two divs. I made it basic way but i really want to write it this way and i have no idea what is wrong with this. Could someone help me with it ?

    (function($) {

    var showAll = function() {
        this.$button = this.find('.btn-all-events');
        this.$all = this.find('.all-events');
        this.$recent = this.find('.recent-events');

        this.initEvents();
    };

    showAll.prototype = {
        initEvents: function() {

            if (this.$all) {
                this.$button.on('click', this.showEvents.bind(this));
            }
        },

        showEvents: function() {
            this.$recent.hide();
            this.$all.show();
        }
    };

    this.toggle = new showAll($(this));
})(jQuery);

Body:
Toggle div simply using jquery . You can check here https://jsfiddle.net/surendra786/os09Lhfw/

html --
   <div class="main">
    <div class="first">Divdfasdfasdfsd</div>
    <div class="second hide">afsdfasfasdfasdfsdf</div>
   </div>
  <a class="toggle">toggle</a>

css--

<style>
 .hide {
display:none;
 }
</style>

 js---

 $('.toggle').click(function(){
if($('.first').hasClass('hide')){
$('.first').removeClass('hide');
} else {
$('.first').addClass('hide');
}
if($('.second').hasClass('hide')){
$('.second').removeClass('hide');
 } else {
$('.second').addClass('hide');
 }
});

try this it should work, please up if working


问:
Angular 1.4.8 :angular module/ng-app error
I have written few very simple lines of code using angular 1.4.8 and I was getting

Error: [$injector:nomod] Module 'a' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

Followed this link as I am also using the same version of angular.
Angular js 1.4.8 Injection module error

```<code><div ng-app='a'>
<div ng-controller="myctrl as ctrl">
<input type="text" ng-model="ctrl.name"/>
<input type="submit" ng-click="call();"/>
</div>
</div>
</code>```

```<code>var a=angular.module('a',[]);
a.controller("myctrl",['$scope',function($scope){

var ctrl=this;

$scope.call=function(){
alert(ctrl.name);
};

}]);
</code>```

here is link to my fiddle.
https://jsfiddle.net/rakotkar/mumv3uwf/4/

答:
Just assign $scope to ctrl object instead of this key word like var ctrl=$scope;

code :

```<code>var a=angular.module('a',[]);
a.controller("myctrl",['$scope',function($scope){
var ctrl=$scope;
$scope.call=function(){
alert(ctrl.name);
};
}]);
</code>```

And you should define the angular reference inside the head tag

Finally remove ctrl ( no need to use ) alias in ng-controller attribute

code :

```<code><div ng-app='a'>
<div ng-controller="myctrl">
<input type="text" ng-model="name"/>
<input type="submit" ng-click="call();"/>
</div>
</div>
</code>```

Working demo

Body:
I have written few very simple lines of code using angular 1.4.8 and I was getting

Error: [$injector:nomod] Module 'a' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

Followed this link as I am also using the same version of angular.
Angular js 1.4.8 Injection module error

<input type="text" ng-model="ctrl.name"/>
<input type="submit" ng-click="call();"/>

var a=angular.module('a',[]);
a.controller("myctrl",['$scope',function($scope){

var ctrl=this;

$scope.call=function(){
alert(ctrl.name);
};

}]);

here is link to my fiddle.
https://jsfiddle.net/rakotkar/mumv3uwf/4/

Body:
Just assign $scope to ctrl object instead of this key word like var ctrl=$scope;

code :

var a=angular.module('a',[]);
a.controller("myctrl",['$scope',function($scope){
var ctrl=$scope;
$scope.call=function(){
alert(ctrl.name);
};
}]);

And you should define the angular reference inside the head tag

Finally remove ctrl ( no need to use ) alias in ng-controller attribute

code :

<div ng-app='a'>
<div ng-controller="myctrl">
<input type="text" ng-model="name"/>
<input type="submit" ng-click="call();"/>
</div>
</div>

Working demo


问:
Pure CSS, div hover can affect more than one element
I can change the size of a div element when is hover another div element, like this example.
https://jsfiddle.net/9510a6kj/

```<code> .left, .right{
        float:left;
    }

    .left{
        background: red;
        width: 200px;
        height: 300px;
        transition: width 1s ;
    }

    .right{
        background: blue;
        width: 300px;
        height: 300px;
        transition: width 1s;
    }

    .left:hover{
        width: 300px;
    }

    .left:hover + .right{
        width: 100px;
    }
    </style>
</code>```

But it's possible to change the size of two different div elements when is hover the first element.

For example on mouse hover div "a", change size of div "b" and div "c".

Thank you.

答:
It all depends on what relationship is between those elements.

1. If they are siblings and one after the other use + also for the c div . See below

div {
  height: 50px;
  width: 50px;
  border: 1px solid black
}

.a:hover + .b {
  background: blue;
}

.a:hover + .b + .c {
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a">
  a
</div>
<div class="b">
  b
</div>
<div class="c">
  c
</div></code>```

2. If they are siblings and both b and c are after a , but not one after the other, use ~

div {
  height: 50px;
  width: 50px;
  border: 1px solid black
}

.a:hover ~ .b {
  background: blue;
}

.a:hover ~ .c {
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a">
  a
</div>
<div>

</div>
<div class="b">
  b
</div>
<div>

</div>
<div class="c">
  c
</div></code>```

3. if b and c are after a but not right after, but c is right after b you can use ~ together with +

div {
  height: 50px;
  width: 50px;
  border: 1px solid black
}

.a:hover ~ .b {
  background: blue;
}

.a:hover ~ .b + .c {
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a">
  a
</div>
<div>

</div>
<div class="b">
  b
</div>
<div class="c">
  c
</div></code>```

if they are children you can use a:hover b,a:hover c or > ( direct child) and then you can add the above sibling selectors.

As i said, there are many possibilities. It all depends on the structure. BUT you can only do this with CSS if b and c come after a in the dom tree.

Body:
I can change the size of a div element when is hover another div element, like this example.
https://jsfiddle.net/9510a6kj/

 .left, .right{
        float:left;
    }

    .left{
        background: red;
        width: 200px;
        height: 300px;
        transition: width 1s ;
    }

    .right{
        background: blue;
        width: 300px;
        height: 300px;
        transition: width 1s;
    }

    .left:hover{
        width: 300px;
    }

    .left:hover + .right{
        width: 100px;
    }
    </style>

But it's possible to change the size of two different div elements when is hover the first element.

For example on mouse hover div "a", change size of div "b" and div "c".

Thank you.

Body:
It all depends on what relationship is between those elements.

1. If they are siblings and one after the other use + also for the c div . See below

div {
  height: 50px;
  width: 50px;
  border: 1px solid black
}

.a:hover + .b {
  background: blue;
}

.a:hover + .b + .c {
  background: red;
}

<div class="a">
  a
</div>
<div class="b">
  b
</div>
<div class="c">
  c
</div>

2. If they are siblings and both b and c are after a , but not one after the other, use ~

div {
  height: 50px;
  width: 50px;
  border: 1px solid black
}

.a:hover ~ .b {
  background: blue;
}

.a:hover ~ .c {
  background: red;
}

<div class="a">
  a
</div>
<div>

</div>
<div class="b">
  b
</div>
<div>

</div>
<div class="c">
  c
</div>

3. if b and c are after a but not right after, but c is right after b you can use ~ together with +

div {
  height: 50px;
  width: 50px;
  border: 1px solid black
}

.a:hover ~ .b {
  background: blue;
}

.a:hover ~ .b + .c {
  background: red;
}

<div class="a">
  a
</div>
<div>

</div>
<div class="b">
  b
</div>
<div class="c">
  c
</div>

if they are children you can use a:hover b,a:hover c or > ( direct child) and then you can add the above sibling selectors.

As i said, there are many possibilities. It all depends on the structure. BUT you can only do this with CSS if b and c come after a in the dom tree.


问:
assign a command to a variable containing file paths
I've been searching an answer regarding commands assignated to variables in shell but without success. My script looks for a folder named 2015may that has a file 4444444.xml. The command find /path/zipfolders -name "*${array[$((i+1))]}*" -exec grep -l "${array[$i]}" {} + displays the following output using these parameters ["2015may","44444444"]: path/filename_2015may.zip. The problem is that this command returns '' when assinging it to $command. I think I have a syntax mistake when assingning it to $command. I will appreciate your help to solving this issue.

Script

```<code>command=$(find /path/zipfolders -name "*${array[$((i+1))]}*" -exec grep -l "${array[$i]}" {} +)
echo "$command"
</code>```

Actual Output

```<code>find /path/zipfolders -name "*${array[$((i+1))]}*" -exec grep -l "${array[$i]}" {} +
++ find /path/zipfolders -name '*2015may*' -exec grep -l 44444444 '{}' +
+ command=
+ echo ''
</code>```

Desired Output

path/filename_2015may.zip

答:
For assigning the command output to a shell variable, enclose the command in backticks(``). So your command will look like this:</p>

```<code>    command=`(find /path/zipfolders -name "*${array[$((i+1))]}*" -exec grep -l "${array[$i]}" {} +)`
    echo $command
</code>```

Body:
I've been searching an answer regarding commands assignated to variables in shell but without success. My script looks for a folder named 2015may that has a file 4444444.xml. The command find /path/zipfolders -name "*${array[$((i+1))]}*" -exec grep -l "${array[$i]}" {} + displays the following output using these parameters ["2015may","44444444"]: path/filename_2015may.zip. The problem is that this command returns '' when assinging it to $command. I think I have a syntax mistake when assingning it to $command. I will appreciate your help to solving this issue.

Script

command=$(find /path/zipfolders -name "*${array[$((i+1))]}*" -exec grep -l "${array[$i]}" {} +)
echo "$command"

Actual Output

find /path/zipfolders -name "*${array[$((i+1))]}*" -exec grep -l "${array[$i]}" {} +
++ find /path/zipfolders -name '*2015may*' -exec grep -l 44444444 '{}' +
+ command=
+ echo ''

Desired Output

path/filename_2015may.zip

Body:
For assigning the command output to a shell variable, enclose the command in backticks(``). So your command will look like this:

    command=`(find /path/zipfolders -name "*${array[$((i+1))]}*" -exec grep -l "${array[$i]}" {} +)`
    echo $command


问:
Remove form from DOM using JavaScript
I have three radio buttons.. each radio buttons on click have an independent form that appears. I need to remove form from DOM when i click on a radio button.  and there are a third one not ready yet. When i click on the first radio button only its form appears, the other two are removed from DOM. Same for other.
I don't have a good idea about JavaScript.

Html:

```<code>   <div class="page-header">
    <h1>Backtesting{% if form.instance.pk %}: {{form.instance.title}} {% endif %}</h1>
    </div>

   <div class="row">
    <div class='col-md-9'>
               <form action="{% url "backtest" %}" method='POST' role='form' id='form'>
                  {% csrf_token %}

                <div id="tabs">

                 <input type="radio" name="tabs" value="first" id="toggle-tab1"  checked="checked" />
                 <label for="toggle-tab1">Long</label>

                 <input type="radio" name="tabs" value="second" id="toggle-tab2"     />
                 <label for="toggle-tab2">Short</label>

                 <input type="radio" name="tabs" value="third" id="toggle-tab3"   />
                 <label for="toggle-tab3">Long and Short</label>
                 <div id="tab1" class="tab"  >

                     {% include 'tags/parameters_form.html' %}
                         <br />

                            {% if user.is_authenticated %}
                            <input type='submit' id='run' value='Run' class='btn btn-default'>

                            {% if user.profile.is_active %}
                    Name: {{ form.title }} <input type='submit' name='save' value='Save' class='btn btn-default'>
                {% else %}
                    <p>
                    Expired account! you need to reactivate in order to save parameters.
                    </p>
                {% endif %}
            {% else %}
                                     Please <a href="{% url 'auth_login' %}">login</a> in order to Run backtesting!
                 </br>
                 Our system needs your email in order to notify you once one or more of your simulations are done. This is a safer way for you to keep track of your previous simulations (/jobs).

                              {% endif %}

                 </div>
                 <div id="tab2" class="tab"  >

                   {% include 'tags/parameters_backtest_form.html' %}
                            <br />

                            {% if user.is_authenticated %}
                            <input type='submit' id='run' value='Run' class='btn btn-default'>

                {% if user.profile.is_active %}
                    Name: {{ form.title }} <input type='submit' name='save' value='Save' class='btn btn-default'>
                {% else %}
                    <p>
                    Expired account! you need to reactivate in order to save parameters.
                    </p>
                {% endif %}
            {% else %}
                                     Please <a href="{% url 'auth_login' %}">login</a> in order to Run backtesting!
                 </br>
                 Our system needs your email in order to notify you once one or more of your simulations are done. This is a safer way for you to keep track of your previous simulations (/jobs).

                              {% endif %}

                 </div>
                    </div>
           </form>

         </div>

     </div>
{% endblock %}
</code>```

答:
Problem is resolved with :</p>

```<code>                 <input type="radio" name="tabs"  value="first" id="toggle-tab1"  {% if strategy == 'l' %} checked="checked"{% endif %} />
                 <label for="toggle-tab1">Long</label>

                 <input type="radio" name="tabs"   value="second" id="toggle-tab2" {% if strategy == 's' %} checked="checked" {% endif %}  />
                 <label for="toggle-tab2">Short</label>

                 <div id="tab1" class="tab"  >

        <form action="{% url "backtest" %}" method='POST' role='form' id='form'>
             {% csrf_token %}
             <input type="hidden" name="tabs"  value="first" id="toggle-tab1"  checked="checked" />
</code>```

Title: Remove form from DOM using JavaScript

Body:
I have three radio buttons.. each radio buttons on click have an independent form that appears. I need to remove form from DOM when i click on a radio button.  and there are a third one not ready yet. When i click on the first radio button only its form appears, the other two are removed from DOM. Same for other.
I don't have a good idea about JavaScript.

Html:

Backtesting{% if form.instance.pk %}: {{form.instance.title}} {% endif %}

               <form action="{% url "backtest" %}" method='POST' role='form' id='form'>
                  {% csrf_token %}

                 <input type="radio" name="tabs" value="first" id="toggle-tab1"  checked="checked" />
                 Long

                 <input type="radio" name="tabs" value="second" id="toggle-tab2"     />
                 Short

                 <input type="radio" name="tabs" value="third" id="toggle-tab3"   />
                 Long and Short

                     {% include 'tags/parameters_form.html' %}

                            {% if user.is_authenticated %}
                            <input type='submit' id='run' value='Run' class='btn btn-default'>

                            {% if user.profile.is_active %}
                    Name: {{ form.title }} <input type='submit' name='save' value='Save' class='btn btn-default'>
                {% else %}

                    Expired account! you need to reactivate in order to save parameters.

                {% endif %}
            {% else %}
                                     Please login in order to Run backtesting!

                 Our system needs your email in order to notify you once one or more of your simulations are done. This is a safer way for you to keep track of your previous simulations (/jobs).

                              {% endif %}

                   {% include 'tags/parameters_backtest_form.html' %}

                            {% if user.is_authenticated %}
                            <input type='submit' id='run' value='Run' class='btn btn-default'>

                {% if user.profile.is_active %}
                    Name: {{ form.title }} <input type='submit' name='save' value='Save' class='btn btn-default'>
                {% else %}

                    Expired account! you need to reactivate in order to save parameters.

                {% endif %}
            {% else %}
                                     Please login in order to Run backtesting!

                 Our system needs your email in order to notify you once one or more of your simulations are done. This is a safer way for you to keep track of your previous simulations (/jobs).

                              {% endif %}

           </form>

{% endblock %}

Body:
Problem is resolved with :

                 <input type="radio" name="tabs"  value="first" id="toggle-tab1"  {% if strategy == 'l' %} checked="checked"{% endif %} />
                 <label for="toggle-tab1">Long</label>

                 <input type="radio" name="tabs"   value="second" id="toggle-tab2" {% if strategy == 's' %} checked="checked" {% endif %}  />
                 <label for="toggle-tab2">Short</label>

                 <div id="tab1" class="tab"  >

        <form action="{% url "backtest" %}" method='POST' role='form' id='form'>
             {% csrf_token %}
             <input type="hidden" name="tabs"  value="first" id="toggle-tab1"  checked="checked" />