答:
The error you have mention is normally came when there is mismatch in param mention in function and the passing ones.

According to your code
public function form($id)
$id is required and you are not passing that.

So change your code to

```<code>public function form($id=null)
</code>```

Title: Unable to view Form page in CodeIgniter facing Error

Body:
This is my home.php file in this controller I am facing Fatal error: Uncaught ArgumentCountError:
I have also attached a screenshot, In this screenshot error mentioned, You can easily understand the error through this screenshot, I am newbie in CodeIgniter.
[
I upload only my controller related file.

<?php

class home extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('select');
        $this->load->helper(array('form', 'url', 'html'));
        $this->load->library(array('form_validation', 'session'));
    }

    function records() {
        $ytl['dta'] = $this->users->datas();
        //$this->load->view('info',$ytl);
        //echo "
controller";print_r($ytl);
    }

    function primezone() {
        $ytl['dta'] = $this->users->datas();
        echo "
controller";
        print_r($ytl);
    }

    function form($id) {
        //die($id);
        if ($this->input->post()) {
            //echo"
";print_r( $this->input->post());die;
            $this->form_validation->set_rules('fname', 'First Name', 'required|min_length[5]');
            $this->form_validation->set_rules('lname', 'Last Name', 'required|callback_check_picture[lname]');

            //$this->form_validation->set_rules('email','Email','required');

            $this->form_validation->set_rules('mobile', 'Mobile Number', 'required|callback_valid_phone_number[mobile]');

            $this->form_validation->set_error_delimiters('
', '
');
            if ($this->form_validation->run() == TRUE) {
                $data = [

                    'fname'   => $this->input->post('fname'),
                    'lname'   => $this->input->post('lname'),
                    'email'   => $this->input->post('email'),
                    'mobile'  => $this->input->post('mobile'),
                    'message' => $this->input->post('message'),
                ];
                if (empty($id)) {
                    $ytl = $this->select->insertdata($data);

                } else {
                    $ytl = $this->select->updatedata($data, $id);
                }
                if ($ytl) {
                    $this->session->set_flashdata('message', 'Successfully Added.');
                    redirect('home');
                }
            } else {
                //$this->load->view('form');
            }
        }
        $ytl['dta'] = $this->select->getDataById($id);
        //echo "
";print_r($ytl);die;
        $this->load->view('form', $ytl);
    }

    public function check_picture($a) {
        if ( ! is_numeric($a)) {
            return TRUE;
        } else {
            $this->form_validation->set_message('check_picture', 'Please enter only char value');

            return FALSE;
        }
    }

    function valid_phone_number($value) {
        $value = strlen($value);
        //echo $value;die;
        if ($value == 10) {
            return TRUE;
        } else {
            $this->form_validation->set_message('valid_phone_number', 'Mobile number not in range'); //{10}

            return FALSE;
        }
    }

    public function index() {
        //load the database
        //$this->load->database();
        //load the model
        $this->load->model('select');
        //load the method of model
        $data['h'] = $this->select->select();
        //return the data in view
        $this->load->view('fetch_view', $data);
    }

    public function delete() {
        $this->load->model('select');
        $id = $this->input->get('id');
        if ($this->select->deleteuser($id)) {
            $data['data'] = $this->select->getuser();
            $this->load->view('fetch_view', $data);
        }
    }
}

Body:
The error you have mention is normally came when there is mismatch in param mention in function and the passing ones.

According to your code
public function form($id)
$id is required and you are not passing that.

So change your code to

public function form($id=null)


来源: stackexchange

问:
SQL Query to Get Periodic Summary Report
Consider the Following Table

```<code>ID  |  Name |  Date | Amount
----------
1   |  XYZ|  01 Jan 17 | 40

2   |  ABC |  12 Feb 17 | 130

3   |  DEF| 15 Jan 17 | 70

4   |  XYZ| 14 March 17 | 50
</code>```

etc

I need to get the results like, total amount of less than 10 days of < query parameter && 10 to 30 days from query parameter and more than 30 days of query parameter along with name details, like periodic output how we can get this report.

How I can get this.
Please provide some information to get this.

答:
I'm not 100% sure what you're asking -- in particular when you say "10 days."  10 days of what?  In the example below, I take that to mean time from today, but if you can clarify, perhaps we can refine the example.

```<code>select
  sum (case when current_date - date < 10 then amount else 0 end) as "< 10",
  sum (case when current_date - date between 10 and 30 then amount else 0 end) as "10-30",
  sum (case when current_date - date > 30 then amount else 0 end) as "> 30"
from
  mytable
</code>```

If you didn't mean from today, that's easy enough to parameterize.

ContentLicense: CC BY-SA 3.0

Body:
Consider the Following Table

ID  |  Name |  Date | Amount
----------
1   |  XYZ|  01 Jan 17 | 40

2   |  ABC |  12 Feb 17 | 130

3   |  DEF| 15 Jan 17 | 70

4   |  XYZ| 14 March 17 | 50

etc

I need to get the results like, total amount of less than 10 days of < query parameter && 10 to 30 days from query parameter and more than 30 days of query parameter along with name details, like periodic output how we can get this report.

How I can get this.
Please provide some information to get this.

Body:
I'm not 100% sure what you're asking -- in particular when you say "10 days."  10 days of what?  In the example below, I take that to mean time from today, but if you can clarify, perhaps we can refine the example.

select
  sum (case when current_date - date < 10 then amount else 0 end) as "< 10",
  sum (case when current_date - date between 10 and 30 then amount else 0 end) as "10-30",
  sum (case when current_date - date > 30 then amount else 0 end) as "> 30"
from
  mytable

If you didn't mean from today, that's easy enough to parameterize.


问:
search for exact string value in different json files with exact name
I have a directory structure like the one given below.

```<code>       main folder
      /     |     \
folder1  folder2 folder3 ...
</code>```

and in all of these folders have the same file data21.json

My goal is to search for specific string value (like '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615') in all these .json file and if found in one of them just stop searching, else print false.
I could do this only for one file with this

```<code>    pipeline_id = '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615'
    found = False
    if pipeline_id in open('dir1/data21.json').read():
       found = True
    pprint(found)
</code>```

Just cannot find how to search in all /directory/anydirectory/data21.json

答:
You can also use os.walk -

```<code>import os

BASE_FOLDER = './main'
pipeline_id = '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615'
found = False

    for r,d,f in os.walk(BASE_FOLDER):
        for file_ in f:
            if file_ == 'data21.json':
                if pipeline_id in open(os.path.join(r, file_)).read():
                    found = True
                    break
        if found:
            break

    print(found)
</code>```

Body:
I have a directory structure like the one given below.

       main folder
      /     |     \
folder1  folder2 folder3 ...

and in all of these folders have the same file data21.json

My goal is to search for specific string value (like '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615') in all these .json file and if found in one of them just stop searching, else print false.
I could do this only for one file with this

    pipeline_id = '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615'
    found = False
    if pipeline_id in open('dir1/data21.json').read():
       found = True
    pprint(found)

Just cannot find how to search in all /directory/anydirectory/data21.json

Body:
You can also use os.walk -

import os

BASE_FOLDER = './main'
pipeline_id = '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615'
found = False

    for r,d,f in os.walk(BASE_FOLDER):
        for file_ in f:
            if file_ == 'data21.json':
                if pipeline_id in open(os.path.join(r, file_)).read():
                    found = True
                    break
        if found:
            break

    print(found)


问:
org.springframework.web.servlet.DispatcherServlet noHandlerFound
I get this error when accessing http://api:8080/users which 404's and I get this error in my console:

Sep 23, 2014 5:57:52 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
      WARNING: No mapping found for HTTP request with URI [/users] in DispatcherServlet with name 'dispatcher'

When I access http://localhost:8080/api/users I get a 404 in my browser but no error in my console

applicationContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.api"/>
</beans>
</code>```

dispatcher-servlet.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
    ">

  <context:component-scan base-package="com.api"/>
</beans>
</code>```

web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
</code>```

Users.java:

```<code>package com.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/users")
public class Users {
     @Autowired
     public Users() {

     }

    @RequestMapping(method = RequestMethod.GET)
    public void getUser() {
        System.out.println("\nhere\n");
    }
}
</code>```

If anyone has any clue I'd greatly appreciate it. I've looked up several questions with the same error as I'm getting but common solution was to add     which I have already, so I'm not sure what else to do. Thanks.

EDIT: I've just updated all the code to what the latest reference doc, and I still get the same error.
EDIT: Update to show my current state of files.

答:
A common mistake is this
Make sure the group id in pom.xml is the parent of that mentioned in

```<code>    </context:component-scan>
</code>```

For Example
If  Group Id-com.cavesofprogramming.spring.web then

```<code>    <context:component-scan base- package="com.cavesofprogramming.spring.web.controllers">
</code>```

The effect is that the controller is not found in the maven build and
        as a result the mapping not done to the correct jsp.

ContentLicense: CC BY-SA 4.0

Body:
I get this error when accessing http://api:8080/users which 404's and I get this error in my console:

Sep 23, 2014 5:57:52 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
      WARNING: No mapping found for HTTP request with URI [/users] in DispatcherServlet with name 'dispatcher'

When I access http://localhost:8080/api/users I get a 404 in my browser but no error in my console

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.api"/>
</beans>

dispatcher-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
    ">

  <context:component-scan base-package="com.api"/>
</beans>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>2</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

Users.java:

package com.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/users")
public class Users {
     @Autowired
     public Users() {

     }

    @RequestMapping(method = RequestMethod.GET)
    public void getUser() {
        System.out.println("\nhere\n");
    }
}

If anyone has any clue I'd greatly appreciate it. I've looked up several questions with the same error as I'm getting but common solution was to add     which I have already, so I'm not sure what else to do. Thanks.

EDIT: I've just updated all the code to what the latest reference doc, and I still get the same error.
EDIT: Update to show my current state of files.

Body:
A common mistake is this
Make sure the group id in pom.xml is the parent of that mentioned in

    </context:component-scan>

For Example
If  Group Id-com.cavesofprogramming.spring.web then

    <context:component-scan base- package="com.cavesofprogramming.spring.web.controllers">

The effect is that the controller is not found in the maven build and
        as a result the mapping not done to the correct jsp.


问:
store API response in Angular application
I have an endpoint that returns some site configuration that I want to use in different components.

```<code>  getSiteConfig() {
    return this.http.get('/json/siteConfig')
  }
</code>```

I can call this endpoint like:

```<code>this.siteService.getSiteConfig()
.subscribe(response => {
   this.supportedLangs = response.languages;
   .... etc
})
</code>```

The values from this endpoint are not going to change so I dont really want to use ngrx store. and are needed in different components, so I dont want to make an API call for each component.

What is the best approach to have this config always available for different components to use?

EDIT

I am currently using this method that seems to be working:

in service:

public siteconfig = new BehaviorSubject(null);
getSiteConfig() {

```<code>this.http.get('/json/siteConfig')
.subscribe(response => {
  this.siteconfig.next(response);
})
</code>```

}

And then in the components I use:

```<code>this.storeService.siteconfig.filter(val => val !== null)
.subscribe(res => this.availableLanguages = res.languages);
</code>```

Are there any better solutions?

答:
Did you hear about resolvers ?

You could create a resolver which will send an HTTP request only if its local variable is not already set. For example:

In you routing file :

```<code>const routes: Routes = [
{
    path: 'firstPath',
    component: FirstComponent,
    resolve: {
        VariableName: MyResolverService
    }

},
{
    path: 'secondPath',
    component: SecondComponent,
    resolve: {
        ***VariableName***: MyResolverService
    }
}, ...]
</code>```

This will call your resolver each time you're navigating to the selected path, and call the resolver function before the component is built.

In your resolver:

```<code>    @Injectable()
export class MyResolverService implements Resolve<any> {

    private _supportedLangs: any;

    constructor(private _siteService: SiteService) { }

    resolve (route: ActivatedRouteSnapshot): Observable<any> {
        if (!this._supportedLangs)
           return this._siteService.getSiteConfig().map(result => {
               console.log(result);
               this._supportedLangs = result;
           });
        return this._supportedLangs;
    }
}
</code>```

You can get the value within the components you want like this:

In FirstComponent for example:

```<code>this.supportedLangs = this._route.snapshot.data['***VariableName***'];
</code>```

Body:
I have an endpoint that returns some site configuration that I want to use in different components.

  getSiteConfig() {
    return this.http.get('/json/siteConfig')
  }

I can call this endpoint like:

this.siteService.getSiteConfig()
.subscribe(response => {
   this.supportedLangs = response.languages;
   .... etc
})

The values from this endpoint are not going to change so I dont really want to use ngrx store. and are needed in different components, so I dont want to make an API call for each component.

What is the best approach to have this config always available for different components to use?

EDIT

I am currently using this method that seems to be working:

in service:

public siteconfig = new BehaviorSubject(null);
getSiteConfig() {

this.http.get('/json/siteConfig')
.subscribe(response => {
  this.siteconfig.next(response);
})

}

And then in the components I use:

this.storeService.siteconfig.filter(val => val !== null)
.subscribe(res => this.availableLanguages = res.languages);

Are there any better solutions?

Body:
Did you hear about resolvers ?

You could create a resolver which will send an HTTP request only if its local variable is not already set. For example:

In you routing file :

const routes: Routes = [
{
    path: 'firstPath',
    component: FirstComponent,
    resolve: {
        VariableName: MyResolverService
    }

},
{
    path: 'secondPath',
    component: SecondComponent,
    resolve: {
        ***VariableName***: MyResolverService
    }
}, ...]

This will call your resolver each time you're navigating to the selected path, and call the resolver function before the component is built.

In your resolver:

    @Injectable()
export class MyResolverService implements Resolve<any> {

    private _supportedLangs: any;

    constructor(private _siteService: SiteService) { }

    resolve (route: ActivatedRouteSnapshot): Observable<any> {
        if (!this._supportedLangs)
           return this._siteService.getSiteConfig().map(result => {
               console.log(result);
               this._supportedLangs = result;
           });
        return this._supportedLangs;
    }
}

You can get the value within the components you want like this:

In FirstComponent for example:

this.supportedLangs = this._route.snapshot.data['***VariableName***'];


问:
Send email with PhpMailer without waiting for return
I'm using PhpMailer to send e-mails. It's working fine.

But in some cases I don't want to wait for the send function to return, specially because it can take a while sometimes. I just want to send and finish the funcition right away.

Is it possible to achieve this?

This is a sample code I'm using (nothing different from the basics).

```<code>try {
    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->SMTPDebug = 0;
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = 'tls';
    // ...other options...
    $mail->send();

    return true;
} catch (Exception $e) {
    return $e;
}
</code>```

答: Like jeroen mentioned, you should use queues to achieve this. If you ever configured the cron to work with PHP, this have the similar principle except that it doesn't repeat the same task by schedule but executes any task you provide one-by-one in a queue. You can even give priorities to these tasks. I suggest you to start with beanstalkd. </p>

Body:
I'm using PhpMailer to send e-mails. It's working fine.

But in some cases I don't want to wait for the send function to return, specially because it can take a while sometimes. I just want to send and finish the funcition right away.

Is it possible to achieve this?

This is a sample code I'm using (nothing different from the basics).

try {
    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->SMTPDebug = 0;
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = 'tls';
    // ...other options...
    $mail->send();

    return true;
} catch (Exception $e) {
    return $e;
}


问:
Why is the input displayed after the enter key has been pressed?
```<code>#include <stdio.h>

/* copy input to output */

main()
{
    int c;

    c = getchar();

    while(c != EOF)
        {
        putchar(c);
        c = getchar();
        }

    return 0;
}
</code>```

In the given code, the program displays the input character.
It reads every character one by one (into the variable 'c') and outputs the same read characters simultaneously. The program terminates when the EOF character is given as input.

When I ran the code in my IDE (Code::Blocks 16.01) and input a string,
eg: Hi! My name is C.\n

The output is displayed after '\n' and not simultaneously.
Isn't the output supposed to be as - "HHii!!  MMyy  nnaammee  iiss  CC.."?

Bold letters indicate the output.

答:
Because by default, input from terminal is line-buffered. So your program get a whole line after you press Enter.

To disable buffering in Unix & Linux systems, try this:

```<code>#include <unistd.h>
#include <termios.h>

int disableLineBuffer(void){
    struct termios term, oldterm;
    if (tcgetattr(STDIN_FILENO, &term)) return -1;
    oldterm = term;
    term.c_lflag &= ~(ECHO | ICANON);
    if (tcsetattr(STDIN_FILENO, TCSANOW, &term)) return -1;
    return 0;
}
</code>```

In Windows, go and do this instead:

```<code>#include <windows.h>

BOOL WINAPI DisableLineBuffer(void){
    HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
    DWORD mode;
    if (!GetConsoleMode(hInput, &mode)) return FALSE;
    mode &= ~ENABLE_LINE_INPUT;
    if (!SetConsoleMode(hInput, mode)) return FALSE;
    return TRUE;
}
</code>```

Be sure to revert changes to the console before your program exits, or you may have trouble doing anything else in your terminal.

Body:
#include <stdio.h>

/* copy input to output */

main()
{
    int c;

    c = getchar();

    while(c != EOF)
        {
        putchar(c);
        c = getchar();
        }

    return 0;
}

In the given code, the program displays the input character.
It reads every character one by one (into the variable 'c') and outputs the same read characters simultaneously. The program terminates when the EOF character is given as input.

When I ran the code in my IDE (Code::Blocks 16.01) and input a string,
eg: Hi! My name is C.\n

The output is displayed after '\n' and not simultaneously.
Isn't the output supposed to be as - "HHii!!  MMyy  nnaammee  iiss  CC.."?

Bold letters indicate the output.

Body:
Because by default, input from terminal is line-buffered. So your program get a whole line after you press Enter.

To disable buffering in Unix & Linux systems, try this:

#include <unistd.h>
#include <termios.h>

int disableLineBuffer(void){
    struct termios term, oldterm;
    if (tcgetattr(STDIN_FILENO, &term)) return -1;
    oldterm = term;
    term.c_lflag &= ~(ECHO | ICANON);
    if (tcsetattr(STDIN_FILENO, TCSANOW, &term)) return -1;
    return 0;
}

In Windows, go and do this instead:

#include <windows.h>

BOOL WINAPI DisableLineBuffer(void){
    HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE);
    DWORD mode;
    if (!GetConsoleMode(hInput, &mode)) return FALSE;
    mode &= ~ENABLE_LINE_INPUT;
    if (!SetConsoleMode(hInput, mode)) return FALSE;
    return TRUE;
}

Be sure to revert changes to the console before your program exits, or you may have trouble doing anything else in your terminal.


问:
Enable clean URL in Yii2
How can I enable clean urls in Yii2. I want to remove index.php and '?' from url parameters. Which section needs to be edited in Yii2 for that?</p>

答:
Step-by-step instruction

Step 1

At the root of the project add a .htaccess with the following content:

```<code>Options +FollowSymLinks
IndexIgnore */*
RewriteEngine On
     RewriteCond %{REQUEST_URI} !^/(web)
    RewriteRule ^assets/(.*)$ /web/assets/$1 [L]
    RewriteRule ^css/(.*)$ web/css/$1 [L]
    RewriteRule ^js/(.*)$ web/js/$1 [L]
    RewriteRule ^images/(.*)$ web/images/$1 [L]
    RewriteRule (.*) /web/$1
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /web/index.php
</code>```

Step 2

In the folder /web add a .htaccess file with the following content:

```<code>RewriteEngine On RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . index.php
</code>```

Step 3

In the file /config/web.php in element components of array add folowing code:

```<code>'request' => [
    // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
    'cookieValidationKey' => 'yYy4YYYX8lYyYyQOl8vOcO6ROo7i8twO',
    'baseUrl' => ''
],

//...

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        '' => 'site/index',
        '<controller:\w+>/<action:\w+>/' => '<controller>/<action>',
    ],
],
</code>```

Done..

Title: Enable clean URL in Yii2

Body:
Step-by-step instruction

Step 1

At the root of the project add a .htaccess with the following content:

Options +FollowSymLinks
IndexIgnore */*
RewriteEngine On
     RewriteCond %{REQUEST_URI} !^/(web)
    RewriteRule ^assets/(.*)$ /web/assets/$1 [L]
    RewriteRule ^css/(.*)$ web/css/$1 [L]
    RewriteRule ^js/(.*)$ web/js/$1 [L]
    RewriteRule ^images/(.*)$ web/images/$1 [L]
    RewriteRule (.*) /web/$1
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /web/index.php

Step 2

In the folder /web add a .htaccess file with the following content:

RewriteEngine On RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . index.php

Step 3

In the file /config/web.php in element components of array add folowing code:

'request' => [
    // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
    'cookieValidationKey' => 'yYy4YYYX8lYyYyQOl8vOcO6ROo7i8twO',
    'baseUrl' => ''
],

//...

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        '' => 'site/index',
        '<controller:\w+>/<action:\w+>/' => '<controller>/<action>',
    ],
],

Done..


问:
Showing 5 images in a row (Responsive)
I'm trying to display 5 images in a row using Bootstrap. My current code is below:

```<code><div class="container">
  <div class="row text-center">
    <div class="col-sm-2" *ngFor="let smiley of agtContentService.smileys">
      <figure>
        <img src="{{smiley.image}}" width="150" height="150">
        <figcaption>{{smiley.name}}</figcaption>
      </figure>
    </div>
  </div>
</div>
</code>```

The problem currently is that when the images are displayed they are not centered on the screen. Also, they don't stretch/compress depending on screen size. For iOS it is not responsive at all. Can anyone help? What I'm trying to achieve are the below:

Display 5 images with their captions in a row where they take the whole screen size without overlapping and with some space between them.

If the screen size is much smaller (like a mobile phone) they should become smaller up to a specified minimum size and after that, they start to wrap (for e.g. for really small devices, show the images in a column).

Need to work on Android, iOS, Chrome, Safari and Firefox.

Please help. Thanks.

答:
Give  below css properties to image tag.

```<code>.col-sm-2 img{
width: 100%;
height: auto;
}
</code>```

You can find my example here.
https://jsfiddle.net/sree296/DTcHh/39349/

Title: Showing 5 images in a row (Responsive)

Body:
I'm trying to display 5 images in a row using Bootstrap. My current code is below:

{{smiley.name}}

The problem currently is that when the images are displayed they are not centered on the screen. Also, they don't stretch/compress depending on screen size. For iOS it is not responsive at all. Can anyone help? What I'm trying to achieve are the below:

Display 5 images with their captions in a row where they take the whole screen size without overlapping and with some space between them.

If the screen size is much smaller (like a mobile phone) they should become smaller up to a specified minimum size and after that, they start to wrap (for e.g. for really small devices, show the images in a column).

Need to work on Android, iOS, Chrome, Safari and Firefox.

Please help. Thanks.

Body:
Give  below css properties to image tag.

.col-sm-2 img{
width: 100%;
height: auto;
}

You can find my example here.
https://jsfiddle.net/sree296/DTcHh/39349/


问:
Load an HTML Page Within qTip Tooltip
Im trying to load a simple html page, instead of a youtube video, using the code from this page:

http://craigsworks.com/projects/qtip/demos/content/youtube#

How would i edit this code to just load a page called MyCustomPage.html?

答:
Use

```<code>content: {
    ajax: {
        url : 'a url'
    }
}
</code>```

to load a webpage. Here is the demo.

ContentLicense: CC BY-SA 2.5

Title: Load an HTML Page Within qTip Tooltip

Body:
Use

content: {
    ajax: {
        url : 'a url'
    }
}

to load a webpage. Here is the demo.


问:
UITableView content size not getting proper
I have UITableView for display for chat message list. I am using 5 type of different with dynamic height. Minimum cell height from 20 to maxHeight( approx 1000 px). UITable view cell dynamic height is set by "self.messageTableView.rowHeight = UITableViewAutomaticDimension".

What Should be common estimate row height.

After reload UITableView content size not getting properly. If user scroll then content size increased.

答: It is not enough to just set rowHeight to automatic dimension. You also need to install proper constraints for cell subviews so the cell can calculate its height based on that constraints.</p>


问:
Wordpress xmlrpc page returns non xml data for non browser applications
I am using python (http://python-wordpress-xmlrpc.readthedocs.io/en/latest/) to connect to wordpress to post contents.

I have a few wordpress sites to which I connect using sitename.com/xmlrpc.php

However one of my sites recently started reporting a problem while connection mentioning not a valid xml. When I view the page in browser I see the usual "XML-RPC server accepts POST requests only." but when I connect using python I see the following message:

funct ion toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))}) ;return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].cons tructor==Array?arguments[0]:arguments,e="",f=0;fd[f]?"0":"" )+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c 63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("c299 e542498206cd9cff8fd57dfc56df");document.cookie="__test="+toHex(slowAES.decrypt(c ,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://targetDomainNameHere.com/xmlrpc.php?i=1";This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support

I searched for the file aes.js, no luck.
How to get this working ? How do I remove this? I am using the latest version of Wordpress as of 07.NOV.2017

答:
You can try to pass "User-Agent" header in the request. Generally the Java or Python library would use their version in the User-Agent allowing the word-press server to block.

Over-riding User-Agent header with browser-like value can help get data for some word-press servers. Value can look like: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36


问:
cordova no sound on bluetooth speakers
I am working on an android   (and IOS) application, the application plays audio messages without problem. My problem is as follow:
if the mobile is already connected to bluetooth (bluetooth enabled and connected), if then I launch my application and I play an audio file in this case I hear nothing neither on the telephine nor on the bluetooth speaker.

But, if I launch my application and then I activate the bluetooth,then play the audio file, there is no problem, the sound goes out well on my bluetooth speakers.

The solution I used for now is that when I launch my application I disable completely the bluetooth and then I restart it on the onDeviceready (using a plugin cordova) it works fin like that  but it is not ideal as solution, it is very annoying for the users that the bluetooth disconnect and reconnect especially when it is the bluetooth of the car.

Does anyone have the same problem and can you help me find another solution.

I use the latest versions of Cordova (7.0.1), android (6.2.3) ...
and I use the plugova cordova-plugin-bluetoothle to restart bluetooth (disable then enable after the launch of the application)

Any Idea please?

答:
Exact same problem here! I'm working on a musical webapp for Android (6.4.0) and iOS (4.5.3) built with Cordova (7.1.0). I use the webaudio API to play sounds. Everything works great on every platforms except in this specific case:

If the bluetooth is enabled and connected before I launch my App there is no sounds at all playing. This problem occurs only on Android. On some model/type of Android devices it works, on some others it doesn't... Example:

Samsung J3 (Android v5.1.1) = no sounds playing

LENOVO TB2 (Android v5.1.1) = no sounds playing

HUAWEI VTR (Android v7.0) = no sounds playing

LG G6 (Android v7.0) = it works like a charm!

Unfortunately I didn't find any 'clean' solutions yet. I do the same than yours (BT=bluetooth):

force to disable BT if this one is connected,

reload the entire page,

re-connect the BT.

The only hint I found during my tests is about an attribute into the AudioContext object. The AudioContext object has a attribute called baseLatency. The official DOC isn't really clear about it:

This represents the number of seconds of processing latency incurred by the AudioContext passing the audio from the AudioDestinationNode to the audio subsystem [...]

What I understood is that this property give you an estimation (in seconds) of the time/delay needed by AudioContext to bring a sound to his destination...

Right after the AudioContext has been initialized in your code, you can ask for this baseLatency (read-only property):

```<code>var context = new AudioContext();
console.log(context.baseLatency);// 0.008 for example
</code>```

What I noticed during my tests, is that this baseLatency is always higher than 0.2 everytime the problem occurs.

Example with bluetooth DISabled:

```<code>// baseLatency on computer = 0.008
// baseLatency on iOS devices = 0.05
// baseLatency on Android devices = 0.05
</code>```

Example with bluetooth ENabled:

```<code>// baseLatency on computer = 0.008 (same)
// baseLatency on iOS devices = 0.05 (same)
// baseLatency on (some) Android devices = 0.2 (HIGHER)
</code>```

Well, I did this test hundreds times, each times the same result. If BT is enabled before you launch the App on some Androids devices, the baseLatency will be higher than 0.2 meaning the AudioContext won't be able to play any sounds in your app. This is not a solution I know, but that can helps a little by letting you know for sure if the App will play sounds or not.

I tried to re-initialize the AudioContext object, but this doesn't works at all... the baseLatency stay the same even if you reconstruct the AudioContext object.

I hope this tiny hint could help us to find a solution!

Title: cordova no sound on bluetooth speakers

Body:
Exact same problem here! I'm working on a musical webapp for Android (6.4.0) and iOS (4.5.3) built with Cordova (7.1.0). I use the webaudio API to play sounds. Everything works great on every platforms except in this specific case:

If the bluetooth is enabled and connected before I launch my App there is no sounds at all playing. This problem occurs only on Android. On some model/type of Android devices it works, on some others it doesn't... Example:

Samsung J3 (Android v5.1.1) = no sounds playing

LENOVO TB2 (Android v5.1.1) = no sounds playing

HUAWEI VTR (Android v7.0) = no sounds playing

LG G6 (Android v7.0) = it works like a charm!

Unfortunately I didn't find any 'clean' solutions yet. I do the same than yours (BT=bluetooth):

force to disable BT if this one is connected,

reload the entire page,

re-connect the BT.

The only hint I found during my tests is about an attribute into the AudioContext object. The AudioContext object has a attribute called baseLatency. The official DOC isn't really clear about it:

This represents the number of seconds of processing latency incurred by the AudioContext passing the audio from the AudioDestinationNode to the audio subsystem [...]

What I understood is that this property give you an estimation (in seconds) of the time/delay needed by AudioContext to bring a sound to his destination...

Right after the AudioContext has been initialized in your code, you can ask for this baseLatency (read-only property):

var context = new AudioContext();
console.log(context.baseLatency);// 0.008 for example

What I noticed during my tests, is that this baseLatency is always higher than 0.2 everytime the problem occurs.

Example with bluetooth DISabled:

// baseLatency on computer = 0.008
// baseLatency on iOS devices = 0.05
// baseLatency on Android devices = 0.05

Example with bluetooth ENabled:

// baseLatency on computer = 0.008 (same)
// baseLatency on iOS devices = 0.05 (same)
// baseLatency on (some) Android devices = 0.2 (HIGHER)

Well, I did this test hundreds times, each times the same result. If BT is enabled before you launch the App on some Androids devices, the baseLatency will be higher than 0.2 meaning the AudioContext won't be able to play any sounds in your app. This is not a solution I know, but that can helps a little by letting you know for sure if the App will play sounds or not.

I tried to re-initialize the AudioContext object, but this doesn't works at all... the baseLatency stay the same even if you reconstruct the AudioContext object.

I hope this tiny hint could help us to find a solution!


问:
How to add scroll in modalpanel?
I have a modal panel which contains the dynamically included page. The page contains search form. After click the search button it shows the contents.

Intially the page height is less than 300px. After search the page height is more than 600px. So i cannot set the height statically. At that time of search the modalpanel partial contents are hide in the browser. So i need to put the scrollbar when the page is larger than browser.

How can i achieve that?

答:
define

```<code><style>
.scroll_div{
 overflow: scroll;
 width:100%;
 height:100%;
}
</style>
</code>```

and apply

```<code><rich:modalPanel id="panel" width="350" height="100">
 <div class="scroll_div">
</code>```

Source :http://community.jboss.org/message/66213

Or

override the css modal panel

```<code>.rich-mpnl-panel {
    position: inherit;
}
</code>```

Title: How to add scroll in modalpanel?

Body:
define

<style>
.scroll_div{
 overflow: scroll;
 width:100%;
 height:100%;
}
</style>

and apply

<rich:modalPanel id="panel" width="350" height="100">
 <div class="scroll_div">

Source :http://community.jboss.org/message/66213

Or

override the css modal panel

.rich-mpnl-panel {
    position: inherit;
}


问:
After kill(getpid(), sig), is the signal guaranteed to be delivered before the next statement?
Assuming that you're in a single-threaded process, and that the relevant signal is not blocked or ignored, is it guaranteed that:

```<code>kill(getpid(), sig);
</code>```

will result in the signal being delivered before the next line of code is executed?

In particular, if the signal is one for which there is no handler and whole default action is to terminate the process (e.g. SIGTERM, SIGALRM), is it guaranteed that the next line of code won't be executed?

I had always assumed that (at least on Linux) the answer was "yes", because I thought that before returning from any syscall the kernel would always check to see if there were any pending signals and deliver them if so.  But I think I have observed that (when run on a heavily-loaded, multi-core system) this is not always the case, though this is very hard to reproduce and so I'd appreciate confirmation that I'm not seeing things.

[This question is very similar to Is a signal sent with kill to a parent thread guaranteed to be processed before the next statement? except that that question was asking about multi-threaded processes (for which the answer is definitely "no"), whereas this question is about single-threaded processes.]

答:
Yes. If you're in a single threaded process, POSIX gives guarantees you this.

If the value of pid causes sig to be generated for the sending
  process, and if sig is not blocked for the calling thread and if no
  other thread has sig unblocked or is waiting in a sigwait() function
  for sig, either sig or at least one pending unblocked signal shall be
  delivered to the sending thread before kill() returns.

Body:
Assuming that you're in a single-threaded process, and that the relevant signal is not blocked or ignored, is it guaranteed that:

kill(getpid(), sig);

will result in the signal being delivered before the next line of code is executed?

In particular, if the signal is one for which there is no handler and whole default action is to terminate the process (e.g. SIGTERM, SIGALRM), is it guaranteed that the next line of code won't be executed?

I had always assumed that (at least on Linux) the answer was "yes", because I thought that before returning from any syscall the kernel would always check to see if there were any pending signals and deliver them if so.  But I think I have observed that (when run on a heavily-loaded, multi-core system) this is not always the case, though this is very hard to reproduce and so I'd appreciate confirmation that I'm not seeing things.

[This question is very similar to Is a signal sent with kill to a parent thread guaranteed to be processed before the next statement? except that that question was asking about multi-threaded processes (for which the answer is definitely "no"), whereas this question is about single-threaded processes.]


问:
Bind two lists to combobox, one only for suggestions
I'm creating a program for birthday notification and also editor to add celebrants into "database". Editor works with 3 comboboxes - one for day, month and year.

Current situation is that user can use numeric keyboard to set day and year, but in case of month he must write name of the month or select one item from the roll menu with mouse.

An ideal situation would be that user could use only tab (that is solved by TabIndex) and numeric keyboard - suggestion behind month combobox would be based on two (somehow connected) lists - months names (Jan, Feb, ...) AND months numbers (1, 2, ...) - while the only one (the named) would be visible - so that user would have an opportunity to write either "j" or "1" to select "January" item.
Is that possible?

My current Combobox settings are:

AutoCompleteMode: SuggestAppend

AutoCompleteSource: ListItems

DropDownStyle: DropDownList

Items: Names of months (January - December)

Thanks in advance for any advice.

答:
Personally, I don't think I would expect a listbox to respond to two lists. If I saw a list of months as text, I would not expect to be able to select them by number. But it's entirely possible that's just me :-)

Assuming you've already considered alternatives, such as a calendar control, you could try trapping the KeyDown event on the combobox something like this?

```<code>private string keysTyped = string.Empty;

private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
  KeysConverter conv = new KeysConverter();

  this.keysTyped+=conv.ConvertToString(e.KeyCode).Replace("NumPad", "");

  int numTyped;
  while (int.TryParse(this.keysTyped, out numTyped))
  {
    if (numTyped <= 12)
    {
      this.comboBox1.SelectedIndex = numTyped - 1;
      break;
    }
    this.keysTyped = this.keysTyped.Substring(1);
  }
}
</code>```

This seems to work with the minimal testing I've done, and I think it answers the question, but it does feel a little convoluted, which generally makes me question whether I'm trying to do something I shouldn't. But if it's what you need...

Note that the reason it's complicated is because it is designed so that it will accept two digits rather than just the one. There is more than one way to do this, but the above seems simplest. So if you type "1" then "2", it will select December.

Body:
Personally, I don't think I would expect a listbox to respond to two lists. If I saw a list of months as text, I would not expect to be able to select them by number. But it's entirely possible that's just me :-)

Assuming you've already considered alternatives, such as a calendar control, you could try trapping the KeyDown event on the combobox something like this?

private string keysTyped = string.Empty;

private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
  KeysConverter conv = new KeysConverter();

  this.keysTyped+=conv.ConvertToString(e.KeyCode).Replace("NumPad", "");

  int numTyped;
  while (int.TryParse(this.keysTyped, out numTyped))
  {
    if (numTyped <= 12)
    {
      this.comboBox1.SelectedIndex = numTyped - 1;
      break;
    }
    this.keysTyped = this.keysTyped.Substring(1);
  }
}

This seems to work with the minimal testing I've done, and I think it answers the question, but it does feel a little convoluted, which generally makes me question whether I'm trying to do something I shouldn't. But if it's what you need...

Note that the reason it's complicated is because it is designed so that it will accept two digits rather than just the one. There is more than one way to do this, but the above seems simplest. So if you type "1" then "2", it will select December.


问:
Execute Invantive SQL on Exact Online from Visual Basic for Applications (VBA)
I want to run some Invantive SQL statements from within VBA code on Excel on an Exact Online data source.

I can use a UDF function call like:

```<code>I_SQL_SELECT_SCALAR("select fullname from me")
</code>```

in an Excel sheet.

How can I retrieve the full name from within VBA?

答:
First, you must reference the functions from Visual Basic Editor -> Tools menu -> References:

Then use code such as the following to retrieve a scalar value:

```<code>Option Explicit

Sub RunSql()
On Error GoTo Catch
Dim result As Variant
'
' Get full name of current user.
'
If Not I_INTEGRATION_ACTIVE() Then
MsgBox "VBA integration not available. Please use the Tools menu to activate it."
End If

result = InvantiveControlUDFs.I_SQL_SELECT_SCALAR("fullname", "Me")
MsgBox ("Result is '" & result & "'.")
'
' Retrieve scalar value: =I_SQL_SELECT_SCALAR(fieldName;tableName;whereClause;orderByClause;postFix;valueNoValue;valueTooManyValues;process)
' Retrieve table: =I_SQL_SELECT_TABLE(sqlStatement;errorOnMoreRows;errorOnMoreColumns;addHeaderRow;process)
' Normally disabled: =I_SQL_SCALAR(process;sql)
'

Finally:
    Exit Sub
Catch:
    HandleError "RunSql"
End Sub
</code>```

Or to retrieve a result set (normally used in a matrix formula):

```<code>Option Explicit

Sub RunSqlTable()
On Error GoTo Catch
Dim result() As Variant
'
' Get list of GLAccounts.
'
If Not I_INTEGRATION_ACTIVE() Then
MsgBox "VBA integration not available. Please use the Tools menu to activate it."
End If

result = InvantiveControlUDFs.I_SQL_SELECT_TABLE("select * from exactonlinerest..glaccounts")
Finally:
    Exit Sub
Catch:
    HandleError "RunSqlTable"
End Sub
</code>```

The use of I_SQL_SELECT_TABLE is only available in releases from October 2017 and newer.

Body:
I want to run some Invantive SQL statements from within VBA code on Excel on an Exact Online data source.

I can use a UDF function call like:

I_SQL_SELECT_SCALAR("select fullname from me")

in an Excel sheet.

How can I retrieve the full name from within VBA?

Body:
First, you must reference the functions from Visual Basic Editor -> Tools menu -> References:

Then use code such as the following to retrieve a scalar value:

Option Explicit

Sub RunSql()
On Error GoTo Catch
Dim result As Variant
'
' Get full name of current user.
'
If Not I_INTEGRATION_ACTIVE() Then
MsgBox "VBA integration not available. Please use the Tools menu to activate it."
End If

result = InvantiveControlUDFs.I_SQL_SELECT_SCALAR("fullname", "Me")
MsgBox ("Result is '" & result & "'.")
'
' Retrieve scalar value: =I_SQL_SELECT_SCALAR(fieldName;tableName;whereClause;orderByClause;postFix;valueNoValue;valueTooManyValues;process)
' Retrieve table: =I_SQL_SELECT_TABLE(sqlStatement;errorOnMoreRows;errorOnMoreColumns;addHeaderRow;process)
' Normally disabled: =I_SQL_SCALAR(process;sql)
'

Finally:
    Exit Sub
Catch:
    HandleError "RunSql"
End Sub

Or to retrieve a result set (normally used in a matrix formula):

Option Explicit

Sub RunSqlTable()
On Error GoTo Catch
Dim result() As Variant
'
' Get list of GLAccounts.
'
If Not I_INTEGRATION_ACTIVE() Then
MsgBox "VBA integration not available. Please use the Tools menu to activate it."
End If

result = InvantiveControlUDFs.I_SQL_SELECT_TABLE("select * from exactonlinerest..glaccounts")
Finally:
    Exit Sub
Catch:
    HandleError "RunSqlTable"
End Sub

The use of I_SQL_SELECT_TABLE is only available in releases from October 2017 and newer.


问:
ASP.Net MVC returning values from List of Checkboxes
I have a model with a property that is a List. MyObjects simply has an id, a description and a selected boolean property.

I have managed to display the items as checkboxes on my view. I did this via:

```<code> <%foreach (var cat in Model.DefaultCategories)
      {%>
    <tr>
        <td>
        <%=cat.Category %>

        </td>
        <td>
           <%=Html.CheckBoxFor(x=>cat.Selected) %>
        </td>
    </tr>
    <%
        }%>
</table>
</code>```

However, there is a problem. They all end up, when rendered, with the same names. Here's a portion of my list:

```<code>        <tr>
        <td>
        Medical

        </td>
        <td>
           <input id="cat_Selected" name="cat.Selected" type="checkbox" value="true" /><input name="cat.Selected" type="hidden" value="false" />
        </td>

    </tr>

    <tr>
        <td>
        Salary

        </td>
        <td>
           <input checked="checked" id="cat_Selected" name="cat.Selected" type="checkbox" value="true" /><input name="cat.Selected" type="hidden" value="false" />
        </td>
    </tr>
</code>```

They have all been named "cat.Selected".

How can I resolve this?

And then, when I submit, I need to iterate through them. With different names, I assume I can get them in my HttpPost method:

```<code>        [HttpPost]
    public ActionResult Modify(int id, FormCollection formValues)
    {
        PayeeDto p = new PayeeDto { Name = Request.Form["name"], PayeeId = id };

        Services.PayeeServices.Save(p);
        return RedirectToAction("Index");
    }
</code>```

The FormCollection will have the different names? At the moment, it just has the single 'cat.selected' item.

答:
I would recommend you using Editor Templates and stop writing loops in your views. They will take care of generating the proper names so that binding works. Example:

In your main view:

```<code><table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Selected</th>
        </tr>
    </thead>
    <tbody>
        <%: Html.EditorFor(x => x.DefaultCategories) %>
    </tbody>
</table>
</code>```

and then inside an editor template strongly typed to a Category (~/Views/Home/EditorTemplates/Category.ascx). Also if you want to get the corresponding Name back in your controller action you need to include it (probably as hidden field). Another technique involves adding only the id and then fetching back the relevant information from the database in your controller action:

```<code><%@ Control
    Language="C#"
    Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.Category>" %>

<tr>
    <td><%: Model.Name %></td>
    <td>
        <!-- include the category name as hidden field so that
             we can fetch it back in the controller action
        -->
        <%: Html.HiddenFor(x => x.Name) %>
        <%: Html.CheckBoxListFor(x => x.Selected) %>
    </td>
</tr>
</code>```

Now the naming convention is important here. If the DefaultCategories property on your view model is an IEnumerable<Category>, then the editor template needs to be called Category.ascx and placed in ~/Views/Home/EditorTemplates/Category.ascx or if it will be reused between multiple controllers in ~/Views/Shared/EditorTemplates/Category.ascx.

Also your controller action you are submitting to should use a view model as parameter:

```<code>[HttpPost]
public ActionResult Modify(MyViewModel model)
{
    PayeeDto = Mapper.Map<MyViewModel, PayeeDto>(model);
    Services.PayeeServices.Save(p);
    return RedirectToAction("Index");
}
</code>```

Body:
I have a model with a property that is a List. MyObjects simply has an id, a description and a selected boolean property.

I have managed to display the items as checkboxes on my view. I did this via:

 <%foreach (var cat in Model.DefaultCategories)
      {%>

        <%=cat.Category %>

           <%=Html.CheckBoxFor(x=>cat.Selected) %>

    <%
        }%>

However, there is a problem. They all end up, when rendered, with the same names. Here's a portion of my list:

        Medical

           <input id="cat_Selected" name="cat.Selected" type="checkbox" value="true" /><input name="cat.Selected" type="hidden" value="false" />

        Salary

           <input checked="checked" id="cat_Selected" name="cat.Selected" type="checkbox" value="true" /><input name="cat.Selected" type="hidden" value="false" />

They have all been named "cat.Selected".

How can I resolve this?

And then, when I submit, I need to iterate through them. With different names, I assume I can get them in my HttpPost method:

        [HttpPost]
    public ActionResult Modify(int id, FormCollection formValues)
    {
        PayeeDto p = new PayeeDto { Name = Request.Form["name"], PayeeId = id };

        Services.PayeeServices.Save(p);
        return RedirectToAction("Index");
    }

The FormCollection will have the different names? At the moment, it just has the single 'cat.selected' item.

Body:
I would recommend you using Editor Templates and stop writing loops in your views. They will take care of generating the proper names so that binding works. Example:

In your main view:

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Selected</th>
        </tr>
    </thead>
    <tbody>
        <%: Html.EditorFor(x => x.DefaultCategories) %>
    </tbody>
</table>

and then inside an editor template strongly typed to a Category (~/Views/Home/EditorTemplates/Category.ascx). Also if you want to get the corresponding Name back in your controller action you need to include it (probably as hidden field). Another technique involves adding only the id and then fetching back the relevant information from the database in your controller action:

<%@ Control
    Language="C#"
    Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.Category>" %>

<tr>
    <td><%: Model.Name %></td>
    <td>
        <!-- include the category name as hidden field so that
             we can fetch it back in the controller action
        -->
        <%: Html.HiddenFor(x => x.Name) %>
        <%: Html.CheckBoxListFor(x => x.Selected) %>
    </td>
</tr>

Now the naming convention is important here. If the DefaultCategories property on your view model is an IEnumerable<Category>, then the editor template needs to be called Category.ascx and placed in ~/Views/Home/EditorTemplates/Category.ascx or if it will be reused between multiple controllers in ~/Views/Shared/EditorTemplates/Category.ascx.

Also your controller action you are submitting to should use a view model as parameter:

[HttpPost]
public ActionResult Modify(MyViewModel model)
{
    PayeeDto = Mapper.Map<MyViewModel, PayeeDto>(model);
    Services.PayeeServices.Save(p);
    return RedirectToAction("Index");
}


问:
How to save a file upload to MongoDb in a form along with other data using formidable?
I am trying to save form data to MongoDb, which also includes an image file upload. I use Jquery form serialize to send this data to the server. The rest of the data gets saved to the database, but not the image. I guess it needs some special treatment. How can I do that? NOTE: I want to be able to send it along with all form data

This is my html part:

```<code><!-- SIGNUP for USERS and ADMIN -->
    <div id="pageSignup" class="page popup">
        <div class="wrapper">
            <h3>SIGNUP</h3>
            <form class="form" id="frmSignup">
                <input type="text" id="txtEmailorPhoneNumber" name="txtEmailorPhoneNumber" placeholder="Mobile number or Email" required>
                <input type="text" name="txtName" placeholder="Name" required>
                <input type="text" name="txtLastName" placeholder="Lastname" required>
                <input type="password" name="txtPassword" placeholder="Password" required>
                <div class="lblFileUpload">
                    <p>Select your picture:</p>
                    <input type="file" name="fileUserImage" required>
                </div>
                <button type="button" class="btnShowPage btnForm" id="btnSignupForm">Signup</button>
                <div class="lblFormExtention">
                    <p class="pyesAccount">Already have an account?</p>
                    <button type="button" class="btnShowPage" id="btnLogin" data-showThisPage="pageLogin">Login</button>
                </div>
            </form>
            <h3 class="lblErrorMessage" id="lblSignupErrorMessage"></h3>
        </div>
    </div>
</code>```

This is the jquery serialize part:

```<code>$('#btnSignupForm').click(function () {
        console.log('btn signup user clicked')
        var oForm = $("#frmSignup").serialize()
        console.log("oForm", oForm)
        var sUrl = 'save-user/'
        console.log("sUrl ", sUrl);
        $.post(sUrl, oForm, function (uData) {
            console.log('SUCCESS')
        })
    })
</code>```

This is my server.js:

```<code>var express = require('express')
var app = express()
var formidable = require('express-formidable');
app.use(formidable());
app.use(express.static(__dirname + '/public'));
var fs = require('fs')
var mongo = require('mongodb').MongoClient
global.db = null
var sDatabasePath = 'mongodb://localhost:27017/webshop'
global.mongoId = require('mongodb').ObjectID

/**************************************************/

var user = require(__dirname + '/user.js')

/**************************************************/

app.get('/shopaholic', (req, res) => { res.sendFile(__dirname + '/shopaholic.html') })

mongo.connect(sDatabasePath, (err, db) => {
    if (err) {
        console.log('ERROR 003 -> Cannot connect to the database')
        return false
    }
    global.db = db
    console.log('OK 002 -> Connected to the database')
    return true
})

/**************************************************/

app.post('/save-user', (req, res) => {
    //var sName = req.fields.userName
    //console.log("sName ", sName)
    user.saveUser(req.fields, (err, jResult) => {
        if (err) {
            console.log(jResult)
            res.send('ERROR')
            return
        }
        console.log(jResult)
        res.send('OK')
        return
    })
})

/**************************************************/

app.listen(3000, (err) => {
    if (err) {
        console.log('ERROR 001 -> Cannot listen to port 3000')
        return false
    }
    console.log('OK 000 -> Server listening to port 3000')
})
</code>```

And finally my user.js:

```<code>var user = {}

/**************************************************/

user.saveUser = (jUserData, fcallback) => {
    var jUser = { "userName": jUserData.txtEmailorPhoneNumber, "firstName": jUserData.txtName, "lastName": jUserData.txtLastName, "password": jUserData.txtPassword, "image": jUserData.fileUserImage }
    global.db.collection('users').insertOne(jUser, (err, jResult) => {
        if (err) {
            var jError = { "status": "error", "message": "ERROR -> user.js -> 001" }
            console.log(jError)
            return fcallback(true, jError)

        }
        var jOk = { "status": "ok", "message": "user.js -> saved -> 000" }
        console.log(jOk)
        return fcallback(false, jOk)
    })
}

/**************************************************/

module.exports = user
</code>```

答: I would suggest that you use multer module for handling your file uploads and only save image's path/url in your mongodb database and let me know if you face any issues with this approach. I will be happy to help.

Body:
I am trying to save form data to MongoDb, which also includes an image file upload. I use Jquery form serialize to send this data to the server. The rest of the data gets saved to the database, but not the image. I guess it needs some special treatment. How can I do that? NOTE: I want to be able to send it along with all form data

This is my html part:

SIGNUP

            <form class="form" id="frmSignup">
                <input type="text" id="txtEmailorPhoneNumber" name="txtEmailorPhoneNumber" placeholder="Mobile number or Email" required>
                <input type="text" name="txtName" placeholder="Name" required>
                <input type="text" name="txtLastName" placeholder="Lastname" required>
                <input type="password" name="txtPassword" placeholder="Password" required>

Select your picture:

                    <input type="file" name="fileUserImage" required>

                <button type="button" class="btnShowPage btnForm" id="btnSignupForm">Signup</button>

Already have an account?

                    <button type="button" class="btnShowPage" id="btnLogin" data-showThisPage="pageLogin">Login</button>

            </form>

This is the jquery serialize part:

$('#btnSignupForm').click(function () {
        console.log('btn signup user clicked')
        var oForm = $("#frmSignup").serialize()
        console.log("oForm", oForm)
        var sUrl = 'save-user/'
        console.log("sUrl ", sUrl);
        $.post(sUrl, oForm, function (uData) {
            console.log('SUCCESS')
        })
    })

This is my server.js:

var express = require('express')
var app = express()
var formidable = require('express-formidable');
app.use(formidable());
app.use(express.static(__dirname + '/public'));
var fs = require('fs')
var mongo = require('mongodb').MongoClient
global.db = null
var sDatabasePath = 'mongodb://localhost:27017/webshop'
global.mongoId = require('mongodb').ObjectID

/**************************************************/

var user = require(__dirname + '/user.js')

/**************************************************/

app.get('/shopaholic', (req, res) => { res.sendFile(__dirname + '/shopaholic.html') })

mongo.connect(sDatabasePath, (err, db) => {
    if (err) {
        console.log('ERROR 003 -> Cannot connect to the database')
        return false
    }
    global.db = db
    console.log('OK 002 -> Connected to the database')
    return true
})

/**************************************************/

app.post('/save-user', (req, res) => {
    //var sName = req.fields.userName
    //console.log("sName ", sName)
    user.saveUser(req.fields, (err, jResult) => {
        if (err) {
            console.log(jResult)
            res.send('ERROR')
            return
        }
        console.log(jResult)
        res.send('OK')
        return
    })
})

/**************************************************/

app.listen(3000, (err) => {
    if (err) {
        console.log('ERROR 001 -> Cannot listen to port 3000')
        return false
    }
    console.log('OK 000 -> Server listening to port 3000')
})

And finally my user.js:

var user = {}

/**************************************************/

user.saveUser = (jUserData, fcallback) => {
    var jUser = { "userName": jUserData.txtEmailorPhoneNumber, "firstName": jUserData.txtName, "lastName": jUserData.txtLastName, "password": jUserData.txtPassword, "image": jUserData.fileUserImage }
    global.db.collection('users').insertOne(jUser, (err, jResult) => {
        if (err) {
            var jError = { "status": "error", "message": "ERROR -> user.js -> 001" }
            console.log(jError)
            return fcallback(true, jError)

        }
        var jOk = { "status": "ok", "message": "user.js -> saved -> 000" }
        console.log(jOk)
        return fcallback(false, jOk)
    })
}

/**************************************************/

module.exports = user


问:
Loop through One2Many records Odoo 10
I am trying to loop through my One2Many records to avoid duplication.

```<code>class sales_target(models.Model):
    _name = 'sales.target'
    _description = 'Sales Target'

    name = fields.Char(string='Name',required=True)
    from_date = fields.Date(string='From Date',required=True)
    to_date = fields.Date(string='To Date',required=True)
    sales_team = fields.Many2one('crm.team',required=True)
    sales_record_ids = fields.One2many('sales.target.record','sales_target_rec_id',string='Sales Record')

    @api.one
    def check_duplication(self,result):
        count = 0
        if self.sales_record_ids:
            for record in self.sales_record_ids:
                if result.id == record.sales_person_p_id:
                    count = 1
        if count == 0:
            self.write({'sales_record_ids':[(0,0,{'sales_person':result.name})]})

    @api.one
    def get_sales_person(self):
        for res in self.sales_team.member_ids:
            self.check_duplication(res)
</code>```

The other class is as:

```<code>class sales_target_record(models.Model):
    _name = 'sales.target.record'

    sales_target_rec_id = fields.Many2one("sales.target")
    sales_person = fields.Char(string='Sales Person',readonly=True,required=True)
    sales_person_p_id = fields.Char(compute='get_value',store=True)

 @api.onchange('sales_person')
    @api.depends('sales_person')
    def get_value(self):
        res = self.env['res.partner'].search([('name','=',self.sales_person)])
        self.sales_person_p_id = res[0].id
</code>```

Now when I am hitting the button i still have duplicate records. However I tried to compare with name and things work good but I cannot compare with names since its not correct because names can be same but id cannot. That function was as:

```<code> @api.one
 def check_duplication(self,result):
     count = 0
     if self.sales_record_ids:
         for record in self.sales_record_ids:
             if result.name == record.sales_person:
                 count = 1
     if count == 0:
         self.write({'sales_record_ids':[(0,0,{'sales_person':result.name})]})
</code>```

Hope for guidance on this.

答:
Can you try like this</p>

```<code>@api.multi
def check_duplication(self,result):
    if self.sales_record_ids:
       for record in self.sales_record_ids:
           if not result.name == record.sales_person:
              self.write({'sales_record_ids':[(0,0,{'sales_person':result.name})]})
</code>```

Title: Loop through One2Many records Odoo 10

Body:
I am trying to loop through my One2Many records to avoid duplication.

class sales_target(models.Model):
    _name = 'sales.target'
    _description = 'Sales Target'

    name = fields.Char(string='Name',required=True)
    from_date = fields.Date(string='From Date',required=True)
    to_date = fields.Date(string='To Date',required=True)
    sales_team = fields.Many2one('crm.team',required=True)
    sales_record_ids = fields.One2many('sales.target.record','sales_target_rec_id',string='Sales Record')

    @api.one
    def check_duplication(self,result):
        count = 0
        if self.sales_record_ids:
            for record in self.sales_record_ids:
                if result.id == record.sales_person_p_id:
                    count = 1
        if count == 0:
            self.write({'sales_record_ids':[(0,0,{'sales_person':result.name})]})

    @api.one
    def get_sales_person(self):
        for res in self.sales_team.member_ids:
            self.check_duplication(res)

The other class is as:

class sales_target_record(models.Model):
    _name = 'sales.target.record'

    sales_target_rec_id = fields.Many2one("sales.target")
    sales_person = fields.Char(string='Sales Person',readonly=True,required=True)
    sales_person_p_id = fields.Char(compute='get_value',store=True)

 @api.onchange('sales_person')
    @api.depends('sales_person')
    def get_value(self):
        res = self.env['res.partner'].search([('name','=',self.sales_person)])
        self.sales_person_p_id = res[0].id

Now when I am hitting the button i still have duplicate records. However I tried to compare with name and things work good but I cannot compare with names since its not correct because names can be same but id cannot. That function was as:

 @api.one
 def check_duplication(self,result):
     count = 0
     if self.sales_record_ids:
         for record in self.sales_record_ids:
             if result.name == record.sales_person:
                 count = 1
     if count == 0:
         self.write({'sales_record_ids':[(0,0,{'sales_person':result.name})]})

Hope for guidance on this.

Body:
Can you try like this

@api.multi
def check_duplication(self,result):
    if self.sales_record_ids:
       for record in self.sales_record_ids:
           if not result.name == record.sales_person:
              self.write({'sales_record_ids':[(0,0,{'sales_person':result.name})]})


问:
null reference exception
i get a system null reference exception error that displays as follows.

Am performing validation on 4 "dropdownlists". what could i have done wrong?

code behind below.

```<code>  protected void addExhibitButton_Click(object sender, EventArgs e)
    {

        if (Page.IsValid)
        {
            DateTime exhibitDate = DateTime.Now;
            int caseid = Convert.ToInt32(DropDownListcaseid.SelectedItem.Text);
            string exhibittype = exhibitTypeDropDownList.Text.ToString();
            string storedloc = storedLocationDropDownList.Text.ToString();
            string offid = DropDownList1.SelectedItem.Text.ToString();
            string status = "Pending";
            Stream imgStream = exhibitImageFileUpload.PostedFile.InputStream;
            int imgLen = exhibitImageFileUpload.PostedFile.ContentLength;
            byte[] imgBinaryData = new byte[imgLen];
            int n = imgStream.Read(imgBinaryData,0,imgLen);
            try
            {
                SqlConnection connections = new SqlConnection(strConn);
                SqlCommand command = new SqlCommand("INSERT INTO Exhibits (CaseID, ExhibitType, ExhibitImage, DateReceived, StoredLocation, InvestigationStatus, OfficerID, SuspectID, InvestigatorID, ManagerID, AdminID ) VALUES (@CaseID, @ExhibitType, @ExhibitImage, @DateReceived, @StoredLocation, @InvestigationStatus, @OfficerID, @SuspectID, @InvestigatorID, @ManagerID, @AdminID)", connections);

                SqlParameter param0 = new SqlParameter("@CaseID", SqlDbType.Int);
                param0.Value = caseid;
                command.Parameters.Add(param0);

                SqlParameter param1 = new SqlParameter("@ExhibitType", SqlDbType.NText);
                param1.Value = exhibittype;
                command.Parameters.Add(param1);

                SqlParameter param2 = new SqlParameter("@ExhibitImage", SqlDbType.Image);
                param2.Value = imgBinaryData;
                command.Parameters.Add(param2);

                SqlParameter param3 = new SqlParameter("@DateReceived", SqlDbType.SmallDateTime);
                param3.Value = exhibitDate;
                command.Parameters.Add(param3);

                SqlParameter param4 = new SqlParameter("@StoredLocation", SqlDbType.NText);
                param4.Value = storedloc;
                command.Parameters.Add(param4);

                SqlParameter param5 = new SqlParameter("@InvestigationStatus", SqlDbType.VarChar, 50);
                param5.Value = status;
                command.Parameters.Add(param5);

                SqlParameter param6 = new SqlParameter("@OfficerID", SqlDbType.NChar, 10);
                param6.Value = offid;
                command.Parameters.Add(param6);

                SqlParameter param7 = new SqlParameter("@SuspectID", SqlDbType.NChar, 10);
                param7.Value = DBNull.Value;
                command.Parameters.Add(param7);

                SqlParameter param8 = new SqlParameter("@InvestigatorID", SqlDbType.NChar, 10);
                param8.Value = DBNull.Value;
                command.Parameters.Add(param8);

                SqlParameter param9 = new SqlParameter("@ManagerID", SqlDbType.NChar, 10);
                param9.Value = DBNull.Value;
                command.Parameters.Add(param9);

                SqlParameter param10 = new SqlParameter("@AdminID", SqlDbType.NChar, 10);
                param10.Value = adminID;
                command.Parameters.Add(param10);

                connections.Open();
                int numRowsAffected = command.ExecuteNonQuery();
                connections.Close();

                if (numRowsAffected != 0)
                {

                    DropDownListcaseid.ClearSelection();
                    exhibitTypeDropDownList.Text = null;
                    storedLocationDropDownList.Text = null;
                    DropDownList1.ClearSelection();
                    messageLabel.Text = "Rows Inserted successfully";
                    messageLabel.Visible = true;
                }
                else
                {
                    messageLabel.Text = "An error occured while inserting columns.";
                    messageLabel.Visible = true;

                }
            }
            catch (Exception ex)
            {
                string script = "<script>alert('" + ex.Message + "');</script>";
            }

        }

    }
</code>```

Image of page being run below

I applied validation items to all drop down lists except the one with the browse button(which offcourse is not a dropdown item). clearly according to my knowledge i havent left out any field.so what could be the cause?

答: It seems that in at least one dropdownlist you have not selected anything, causing the SelectedItem property to return null. Change your code to check if the property is null before trying to access it's Text property.

Title: null reference exception

Body:
i get a system null reference exception error that displays as follows.

Am performing validation on 4 "dropdownlists". what could i have done wrong?

code behind below.

  protected void addExhibitButton_Click(object sender, EventArgs e)
    {

        if (Page.IsValid)
        {
            DateTime exhibitDate = DateTime.Now;
            int caseid = Convert.ToInt32(DropDownListcaseid.SelectedItem.Text);
            string exhibittype = exhibitTypeDropDownList.Text.ToString();
            string storedloc = storedLocationDropDownList.Text.ToString();
            string offid = DropDownList1.SelectedItem.Text.ToString();
            string status = "Pending";
            Stream imgStream = exhibitImageFileUpload.PostedFile.InputStream;
            int imgLen = exhibitImageFileUpload.PostedFile.ContentLength;
            byte[] imgBinaryData = new byte[imgLen];
            int n = imgStream.Read(imgBinaryData,0,imgLen);
            try
            {
                SqlConnection connections = new SqlConnection(strConn);
                SqlCommand command = new SqlCommand("INSERT INTO Exhibits (CaseID, ExhibitType, ExhibitImage, DateReceived, StoredLocation, InvestigationStatus, OfficerID, SuspectID, InvestigatorID, ManagerID, AdminID ) VALUES (@CaseID, @ExhibitType, @ExhibitImage, @DateReceived, @StoredLocation, @InvestigationStatus, @OfficerID, @SuspectID, @InvestigatorID, @ManagerID, @AdminID)", connections);

                SqlParameter param0 = new SqlParameter("@CaseID", SqlDbType.Int);
                param0.Value = caseid;
                command.Parameters.Add(param0);

                SqlParameter param1 = new SqlParameter("@ExhibitType", SqlDbType.NText);
                param1.Value = exhibittype;
                command.Parameters.Add(param1);

                SqlParameter param2 = new SqlParameter("@ExhibitImage", SqlDbType.Image);
                param2.Value = imgBinaryData;
                command.Parameters.Add(param2);

                SqlParameter param3 = new SqlParameter("@DateReceived", SqlDbType.SmallDateTime);
                param3.Value = exhibitDate;
                command.Parameters.Add(param3);

                SqlParameter param4 = new SqlParameter("@StoredLocation", SqlDbType.NText);
                param4.Value = storedloc;
                command.Parameters.Add(param4);

                SqlParameter param5 = new SqlParameter("@InvestigationStatus", SqlDbType.VarChar, 50);
                param5.Value = status;
                command.Parameters.Add(param5);

                SqlParameter param6 = new SqlParameter("@OfficerID", SqlDbType.NChar, 10);
                param6.Value = offid;
                command.Parameters.Add(param6);

                SqlParameter param7 = new SqlParameter("@SuspectID", SqlDbType.NChar, 10);
                param7.Value = DBNull.Value;
                command.Parameters.Add(param7);

                SqlParameter param8 = new SqlParameter("@InvestigatorID", SqlDbType.NChar, 10);
                param8.Value = DBNull.Value;
                command.Parameters.Add(param8);

                SqlParameter param9 = new SqlParameter("@ManagerID", SqlDbType.NChar, 10);
                param9.Value = DBNull.Value;
                command.Parameters.Add(param9);

                SqlParameter param10 = new SqlParameter("@AdminID", SqlDbType.NChar, 10);
                param10.Value = adminID;
                command.Parameters.Add(param10);

                connections.Open();
                int numRowsAffected = command.ExecuteNonQuery();
                connections.Close();

                if (numRowsAffected != 0)
                {

                    DropDownListcaseid.ClearSelection();
                    exhibitTypeDropDownList.Text = null;
                    storedLocationDropDownList.Text = null;
                    DropDownList1.ClearSelection();
                    messageLabel.Text = "Rows Inserted successfully";
                    messageLabel.Visible = true;
                }
                else
                {
                    messageLabel.Text = "An error occured while inserting columns.";
                    messageLabel.Visible = true;

                }
            }
            catch (Exception ex)
            {
                string script = "";
            }

        }

    }

Image of page being run below

I applied validation items to all drop down lists except the one with the browse button(which offcourse is not a dropdown item). clearly according to my knowledge i havent left out any field.so what could be the cause?


问:
Bottom bar navigation and Navigation drawer in same app
I'm using roughike bottom bar navigation in my app.now i,m trying to add navigation drawer also, and use both in my app.when i run my code logcat showing bellow error.how can i fix this?

Log cat error

FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.app.testfragments/com.android.app.testfragments.MainActivity}: android.view.InflateException: Binary XML file line #59: Error inflating class com.roughike.bottombar.BottomBar

Activity_main.xml

```<code><android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
<LinearLayout
            android:id="@+id/container_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
 <include
                android:id="@+id/toolbar"
                layout="@layout/toolbar" />
        </LinearLayout>
<FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
</LinearLayout>
 <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#FFFFFF"
        android:choiceMode="singleChoice"
        android:divider="@android:color/darker_gray"
        android:dividerHeight="1dp" />
<FrameLayout
        android:id="@+id/contentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottomBar" />
<com.roughike.bottombar.BottomBar
        android:id="@+id/bottomBar"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        app:bb_tabXmlResource="@xml/bottombar_tabs" />
</android.support.v4.widget.DrawerLayout>
</code>```

答:
may be your library not installed properly

You can use bottom navigation bar activity provided by Android Studio

Body:
I'm using roughike bottom bar navigation in my app.now i,m trying to add navigation drawer also, and use both in my app.when i run my code logcat showing bellow error.how can i fix this?

Log cat error

FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.app.testfragments/com.android.app.testfragments.MainActivity}: android.view.InflateException: Binary XML file line #59: Error inflating class com.roughike.bottombar.BottomBar

Activity_main.xml

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
<LinearLayout
            android:id="@+id/container_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
 <include
                android:id="@+id/toolbar"
                layout="@layout/toolbar" />
        </LinearLayout>
<FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
</LinearLayout>
 <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#FFFFFF"
        android:choiceMode="singleChoice"
        android:divider="@android:color/darker_gray"
        android:dividerHeight="1dp" />
<FrameLayout
        android:id="@+id/contentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottomBar" />
<com.roughike.bottombar.BottomBar
        android:id="@+id/bottomBar"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        app:bb_tabXmlResource="@xml/bottombar_tabs" />
</android.support.v4.widget.DrawerLayout>


问:
jQuery each "sleep" with callback inside
I have an each() with inside a function with callback.
I would like that each() will be synchronous by callback.
I post here my example

function insRow(rif, callback){
    setTimeout(function() {
      $(rif+" tr:nth-child(2)");
      var newtr=$(rif+" tr:nth-child(2)").clone();
      $(".insTo").append(newtr);
      $(rif+" tr:nth-child(2) td:nth-child(1)").text("O");
      $(rif+" tr:nth-child(2) td:nth-child(3)").text("O");
      $(rif+" tr:nth-child(2) td:nth-child(5)").text("O");
      if (callback) { callback(true); }
    },1000);
}

var go=true;
$(".insFrom tr:not(:first-child)").each(function(){
    if(go){
        go=false;
        $(".middle tr:nth-child(2) td:nth-child(1)").text($(this).find("td:nth-child(1)").text());
        $(".middle tr:nth-child(2) td:nth-child(3)").text($(this).find("td:nth-child(2)").text());
        $(".middle tr:nth-child(2) td:nth-child(5)").text($(this).find("td:nth-child(3)").text());
        insRow(".middle", function(callback){
          if(callback){
            go=true;
          }
        });
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>table td{
  border:1px solid black;
  min-width:50px;
  text-align:center;
}</code>```

A	B	C	D	E

A	B	C	D	E

O/td>X	O	Y	O

A	C	E

1	2	3

4	5	6

7	8	9

```

My code is more complicated than this and I must to pass data from "insFrom" to "middle" and than combined to "insTo". Now my result is only the first row combined, but I want to have all combined.

答:
You probably need to await the loop (this is new cool js stuff [ won't work in old browsers]):

```<code>//we need to define a block of async code
(async function (){
  //.forEach won't work, we need a real array and a real for loop
  for(const el of $(".insFrom tr:not(:first-child)").toArray()){

    $(".middle tr:nth-child(2) td:nth-child(1)").text($(el).find("td:nth-child(1)").text());
    $(".middle tr:nth-child(2) td:nth-child(3)").text($(el).find("td:nth-child(2)").text());
    $(".middle tr:nth-child(2) td:nth-child(5)").text($(el).find("td:nth-child(3)").text());

    //now the real magic:
    //the code halts here, and resumes when the callback gets called
    await new Promise(callback => insRow(".middle", callback));
  }
})();//the async code block is called emmidiately
</code>```

Or you need some callback hell:

```<code>var els = $(".insFrom tr:not(:first-child)");
//an IIFE, used as an entry point for continuing
(function next(i){
    //if index is out of scope terminate
    if(i >= els.length) return;
    var el = els[i];

    $(".middle tr:nth-child(2) td:nth-child(1)").text($(el).find("td:nth-child(1)").text());
    $(".middle tr:nth-child(2) td:nth-child(3)").text($(el).find("td:nth-child(2)").text());
    $(".middle tr:nth-child(2) td:nth-child(5)").text($(el).find("td:nth-child(3)").text());
    insRow(".middle", function(callback){
      if(callback){
        next(i+1);//proceed with the next element
      }
    });
})(0);//start immediately at index 0
</code>```

Body:
I have an each() with inside a function with callback.
I would like that each() will be synchronous by callback.
I post here my example

function insRow(rif, callback){
    setTimeout(function() {
      $(rif+" tr:nth-child(2)");
      var newtr=$(rif+" tr:nth-child(2)").clone();
      $(".insTo").append(newtr);
      $(rif+" tr:nth-child(2) td:nth-child(1)").text("O");
      $(rif+" tr:nth-child(2) td:nth-child(3)").text("O");
      $(rif+" tr:nth-child(2) td:nth-child(5)").text("O");
      if (callback) { callback(true); }
    },1000);
}

var go=true;
$(".insFrom tr:not(:first-child)").each(function(){
    if(go){
        go=false;
        $(".middle tr:nth-child(2) td:nth-child(1)").text($(this).find("td:nth-child(1)").text());
        $(".middle tr:nth-child(2) td:nth-child(3)").text($(this).find("td:nth-child(2)").text());
        $(".middle tr:nth-child(2) td:nth-child(5)").text($(this).find("td:nth-child(3)").text());
        insRow(".middle", function(callback){
          if(callback){
            go=true;
          }
        });
    }
});

table td{
  border:1px solid black;
  min-width:50px;
  text-align:center;
}

A	B	C	D	E

A	B	C	D	E

O/td>X	O	Y	O

A	C	E

1	2	3

4	5	6

7	8	9

My code is more complicated than this and I must to pass data from "insFrom" to "middle" and than combined to "insTo". Now my result is only the first row combined, but I want to have all combined.

Body:
You probably need to await the loop (this is new cool js stuff [ won't work in old browsers]):

//we need to define a block of async code
(async function (){
  //.forEach won't work, we need a real array and a real for loop
  for(const el of $(".insFrom tr:not(:first-child)").toArray()){

    $(".middle tr:nth-child(2) td:nth-child(1)").text($(el).find("td:nth-child(1)").text());
    $(".middle tr:nth-child(2) td:nth-child(3)").text($(el).find("td:nth-child(2)").text());
    $(".middle tr:nth-child(2) td:nth-child(5)").text($(el).find("td:nth-child(3)").text());

    //now the real magic:
    //the code halts here, and resumes when the callback gets called
    await new Promise(callback => insRow(".middle", callback));
  }
})();//the async code block is called emmidiately

Or you need some callback hell:

var els = $(".insFrom tr:not(:first-child)");
//an IIFE, used as an entry point for continuing
(function next(i){
    //if index is out of scope terminate
    if(i >= els.length) return;
    var el = els[i];

    $(".middle tr:nth-child(2) td:nth-child(1)").text($(el).find("td:nth-child(1)").text());
    $(".middle tr:nth-child(2) td:nth-child(3)").text($(el).find("td:nth-child(2)").text());
    $(".middle tr:nth-child(2) td:nth-child(5)").text($(el).find("td:nth-child(3)").text());
    insRow(".middle", function(callback){
      if(callback){
        next(i+1);//proceed with the next element
      }
    });
})(0);//start immediately at index 0


问:
Parse JSON with special characters into Array in PHP
```<code>{
    "api_response": "{\"LeadRefNumber\":\"23223222433534543554\",\"ApplicationNumber\":\"2323343434234234\",\"StatusCode\":\"3456\",\"ProcessingStatus\":\"111\",\"CreditLimit\":\"5454554\",\"Messages\":{\"Message\":\"test.\"}}"
}
</code>```

NOTE: The above is the json encoded one, but couldn't access it as array even if the json is decoded with json_decode().

答:
```<code>$creditLimit = {"api_response":"{\"LeadRefNumber\":\"3434343345435453\",\"ApplicationNumber\":\"5345345345345534\",\"StatusCode\":\"13420\",\"ProcessingStatus\":\"145\",\"CreditLimit\":\"4500000\",\"Messages\":{\"Message\":\"Test\"}}"};

$arrCreditLimit = json_decode($creditLimit['api_response'], true);

print_r("CreditLimit".$arrCreditLimit['CreditLimit']);
</code>```

Output:

CreditLimit: 4500000

Found the solution by the above way.

Body:
{
    "api_response": "{\"LeadRefNumber\":\"23223222433534543554\",\"ApplicationNumber\":\"2323343434234234\",\"StatusCode\":\"3456\",\"ProcessingStatus\":\"111\",\"CreditLimit\":\"5454554\",\"Messages\":{\"Message\":\"test.\"}}"
}

NOTE: The above is the json encoded one, but couldn't access it as array even if the json is decoded with json_decode().

Body:
$creditLimit = {"api_response":"{\"LeadRefNumber\":\"3434343345435453\",\"ApplicationNumber\":\"5345345345345534\",\"StatusCode\":\"13420\",\"ProcessingStatus\":\"145\",\"CreditLimit\":\"4500000\",\"Messages\":{\"Message\":\"Test\"}}"};

$arrCreditLimit = json_decode($creditLimit['api_response'], true);

print_r("CreditLimit".$arrCreditLimit['CreditLimit']);

Output:

CreditLimit: 4500000

Found the solution by the above way.


问:
Angular 2 Router - change just named outlet
I have a primary router outlet and a named outlet.  The primary outlet contains a child router outlet.  When I try to change just the named outlet, it fails - I get routed to the default primary route and nothing happens in the named outlet.

AppRouter (primary/AppModule):

```<code>{ path: 'dashboard', component: DashboardComponent },
{ path: 'person/:id', component: PersonProfileComponent }
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{ path: '**', redirectTo: 'dashboard', pathMatch: 'full' }
</code>```

Child Router (separate module) :

```<code>{
        path: 'person/:id',
        component: PersonProfileComponent,
        children: [
            { path: 'people', component: PersonPeopleComponent },
            {
                path:'person-edit',
                component: PersonEditPanelComponent,
                outlet:'taskPane'
            },
}
</code>```

From the PersonPeopleComponent (url of #/person/8/people - which matches person/:id in the primary outlet and people in the child outlet), I have the following RouterLink:

```<code><a [routerLink]="[{outlets:{taskPane : ['person-edit']} }]">Click Me!</a>
</code>```

where taskPane is the named outlet.

What I would expect to happen is that the PersonEditPanelComponent would show in the taskPane named outlet, and the PersonProfileComponent and the PersonPeopleComponent would remain unchanged in the primary and child outlets.  Instead, what I see is the Dashboard route (my fallback route) gets loaded into the primary outlet and the taskPane outlet is empty.  No error is recorded in the console.

The href on my link ends up as something like #/person/8/(people//taskPane:person-edit) which doesn't work  (I've tried many different permutations on the router link so that is an example of just one invalid URL).  The URL needs to be #/person/8/people(taskPane:person-edit) which does work (I tested it manually) but I can't figure out how to set the RouterLink to generate that URL.

I think that the routes are configured correctly because the URL works when I hardcode it, which means then that the problem is in the RouterLink.

Any clues as to what I'm doing wrong?

Thanks.

答:
Got it.  Adding an empty string for the relative part of the routerLink worked:

Click Me!

```<code>                  ^^
</code>```

Body:
I have a primary router outlet and a named outlet.  The primary outlet contains a child router outlet.  When I try to change just the named outlet, it fails - I get routed to the default primary route and nothing happens in the named outlet.

AppRouter (primary/AppModule):

{ path: 'dashboard', component: DashboardComponent },
{ path: 'person/:id', component: PersonProfileComponent }
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{ path: '**', redirectTo: 'dashboard', pathMatch: 'full' }

Child Router (separate module) :

{
        path: 'person/:id',
        component: PersonProfileComponent,
        children: [
            { path: 'people', component: PersonPeopleComponent },
            {
                path:'person-edit',
                component: PersonEditPanelComponent,
                outlet:'taskPane'
            },
}

From the PersonPeopleComponent (url of #/person/8/people - which matches person/:id in the primary outlet and people in the child outlet), I have the following RouterLink:

Click Me!

where taskPane is the named outlet.

What I would expect to happen is that the PersonEditPanelComponent would show in the taskPane named outlet, and the PersonProfileComponent and the PersonPeopleComponent would remain unchanged in the primary and child outlets.  Instead, what I see is the Dashboard route (my fallback route) gets loaded into the primary outlet and the taskPane outlet is empty.  No error is recorded in the console.

The href on my link ends up as something like #/person/8/(people//taskPane:person-edit) which doesn't work  (I've tried many different permutations on the router link so that is an example of just one invalid URL).  The URL needs to be #/person/8/people(taskPane:person-edit) which does work (I tested it manually) but I can't figure out how to set the RouterLink to generate that URL.

I think that the routes are configured correctly because the URL works when I hardcode it, which means then that the problem is in the RouterLink.

Any clues as to what I'm doing wrong?

Thanks.

Body:
Got it.  Adding an empty string for the relative part of the routerLink worked:

<a [routerLink]="['', {outlets: {taskPane: 'person-edit'} }]">Click Me!</a>

                  ^^