问:
Font change onmouseover onmouseout
what would be the code for this: Insert a link. When mouse is over, the link font turns bold and underlined, when mouse is out, it comes back to the initial form</p>

答:
Only using CSS:</p>

```<code>a:hover {
   font-weight: bold;
   text-decoration: underline;
}
</code>```

Title: Font change onmouseover onmouseout

Body:
Only using CSS:

a:hover {
   font-weight: bold;
   text-decoration: underline;
}


来源: stackexchange

问:
Sequelize, many unique composite keys using same field
If I am designing a table containing the following fields
column_one, column_two, column_three, and I want the combination (column_one:column_two) to be unique, I would do the following:

```<code>column_one: { type: DataTypes.INTEGER, unique: 'composite_one'},
column_one: { type: DataTypes.INTEGER, unique: 'composite_one'},
column_three: { type: DataTypes.INTEGER}
</code>```

What if I need two unique combinations, both including one of the fields? Ex: (column_one:column_two) and (column_one:column_three) must both be unique, though (column_two:column_three) can be repeated

In theory it would be something like:

```<code>column_one: { type: DataTypes.INTEGER, unique: 'composite_one', unique: 'composite_two'},
column_one: { type: DataTypes.INTEGER, unique: 'composite_one'},
column_three: { type: DataTypes.INTEGER, unique: 'composite_two'}
</code>```

This is not a join table, and I do not want to use any raw queries.

Also, column_one must create unique combinations with 2 and 3, but it does not mean that column one, two and three must create a single unique combination.

In case the explanation is not clear, I am giving an example:

```<code>column_one ----- column_two ---- column_three
-11---------------12----------------13-------
-11---------------12----------------14-------
-18---------------12----------------15-------
</code>```

is not a valid set of data, because there are two rows with (column_one: column_two) = (11:12)

But

```<code>column_one ----- column_two ---- column_three
-11---------------12----------------13-------
-11---------------17----------------12-------
-18---------------12----------------15-------
-11---------------12----------------15-------
</code>```

is a valid set of data

答:
Over your migrations, you can use sequelize addConstraint method

From the Docs

```<code> queryInterface.addConstraint('Users', ['email', 'name'], { type: 'unique', name: 'custom_unique_constraint_name' });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If I am designing a table containing the following fields
column_one, column_two, column_three, and I want the combination (column_one:column_two) to be unique, I would do the following:

column_one: { type: DataTypes.INTEGER, unique: 'composite_one'},
column_one: { type: DataTypes.INTEGER, unique: 'composite_one'},
column_three: { type: DataTypes.INTEGER}

What if I need two unique combinations, both including one of the fields? Ex: (column_one:column_two) and (column_one:column_three) must both be unique, though (column_two:column_three) can be repeated

In theory it would be something like:

column_one: { type: DataTypes.INTEGER, unique: 'composite_one', unique: 'composite_two'},
column_one: { type: DataTypes.INTEGER, unique: 'composite_one'},
column_three: { type: DataTypes.INTEGER, unique: 'composite_two'}

This is not a join table, and I do not want to use any raw queries.

Also, column_one must create unique combinations with 2 and 3, but it does not mean that column one, two and three must create a single unique combination.

In case the explanation is not clear, I am giving an example:

column_one ----- column_two ---- column_three
-11---------------12----------------13-------
-11---------------12----------------14-------
-18---------------12----------------15-------

is not a valid set of data, because there are two rows with (column_one: column_two) = (11:12)

But

column_one ----- column_two ---- column_three
-11---------------12----------------13-------
-11---------------17----------------12-------
-18---------------12----------------15-------
-11---------------12----------------15-------

is a valid set of data

Body:
Over your migrations, you can use sequelize addConstraint method

From the Docs

 queryInterface.addConstraint('Users', ['email', 'name'], { type: 'unique', name: 'custom_unique_constraint_name' });


问:
c program to find average
i am a beginner in coding ,i am trying to make a program where i input 'n' number of elements in array and find out what percentage of number are positive,negative and zeros.the output is not what i am expecting it is all 'zeros'.Where i input n=3,so the percentage should be .3,.3,.3 when i input numbers one positive,one negative and one zero.

```<code>#include <math.h>
#include <stdio.h>

int main()
{
    int n;
    float per1, per2, per3;
    scanf("%d", &n);
    int arr[n];
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }

    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;

    for (int i = 0; i <= n - 1; i++)
    {
        if (arr[i] < 0)
        {
            int sum1 = sum1 + 1;
        }
        if (arr[i] > 0)
        {
            sum2 = sum2 + 1;
        }
        else
        {
            sum3 = sum3 + 1;
        }
    }

    per1 = sum1 / n;
    per2 = sum2 / n;
    per3 = sum3 / n;
    printf("%.6f\n%.6f\n%.6f\n", per1, per2, per3);

    return 0;
}
</code>```

output

```<code>3
1
-2
0
0.000000
0.000000
0.000000
</code>```

the last three numbers should be .3,.3,.3 but it is giving zeros.

答:
How do you calculate percentage of some value? Your answers shouldn't be 1,1,1 but 33%, 33%, 33% for input you have. So your code should instead of this

```<code>per1=sum1/n;
</code>```

be like this

```<code>per1=sum1*100.0/n;
</code>```

And you have also got wrong your if conditions. The else part is tied only to second if. So every number less or equal to 0 is counted into sum3 which is not what you probably meant. So your

```<code> if (arr[i] > 0)
</code>```

should have been

```<code> else if (arr[i] > 0)
</code>```

And one last thing. On this line you are creating completely new variable sum1 that will live only to the end of the if statement and thus will not appear in the final calculation. I will leave it to you how to fix it.

```<code>int sum1 = sum1 + 1;
</code>```

I don't know what environment you are using for development, but you should learn how to use debugger from the beginning. You can then peek into flow of your code to see what is going on and when it went wrong. With simple programs like this it is really easy. If you are on Visual Studio, they have really nice debugger integrated. Just set breakpoint and run Debug. If you are on Linux, there is gdb which might come pretty rough for beginners, but there are also graphical tools like ddd.

Title: c program to find average

Body:
i am a beginner in coding ,i am trying to make a program where i input 'n' number of elements in array and find out what percentage of number are positive,negative and zeros.the output is not what i am expecting it is all 'zeros'.Where i input n=3,so the percentage should be .3,.3,.3 when i input numbers one positive,one negative and one zero.

#include <math.h>
#include <stdio.h>

int main()
{
    int n;
    float per1, per2, per3;
    scanf("%d", &n);
    int arr[n];
    for (int i = 0; i < n; i++)
    {
        scanf("%d", &arr[i]);
    }

    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;

    for (int i = 0; i <= n - 1; i++)
    {
        if (arr[i] < 0)
        {
            int sum1 = sum1 + 1;
        }
        if (arr[i] > 0)
        {
            sum2 = sum2 + 1;
        }
        else
        {
            sum3 = sum3 + 1;
        }
    }

    per1 = sum1 / n;
    per2 = sum2 / n;
    per3 = sum3 / n;
    printf("%.6f\n%.6f\n%.6f\n", per1, per2, per3);

    return 0;
}

output

3
1
-2
0
0.000000
0.000000
0.000000

the last three numbers should be .3,.3,.3 but it is giving zeros.

Body:
How do you calculate percentage of some value? Your answers shouldn't be 1,1,1 but 33%, 33%, 33% for input you have. So your code should instead of this

per1=sum1/n;

be like this

per1=sum1*100.0/n;

And you have also got wrong your if conditions. The else part is tied only to second if. So every number less or equal to 0 is counted into sum3 which is not what you probably meant. So your

 if (arr[i] > 0)

should have been

 else if (arr[i] > 0)

And one last thing. On this line you are creating completely new variable sum1 that will live only to the end of the if statement and thus will not appear in the final calculation. I will leave it to you how to fix it.

int sum1 = sum1 + 1;

I don't know what environment you are using for development, but you should learn how to use debugger from the beginning. You can then peek into flow of your code to see what is going on and when it went wrong. With simple programs like this it is really easy. If you are on Visual Studio, they have really nice debugger integrated. Just set breakpoint and run Debug. If you are on Linux, there is gdb which might come pretty rough for beginners, but there are also graphical tools like ddd.


问:
sql missing from clause
```<code>  select m_product.name ,c_bpartner.name  from(
  select count(m_product.name)
  from m_product
  union
  select count(c_bpartner.name)
  from c_bpartner
  ) as total
</code>```

I am getting error.

Error:

missing from-clause entry for table m_product.

Im trying to get the total number of products and bpartner in a table.
Thank you for any help.

```<code> |total number of product|total number of bp|
 |     1000              |   1200           |
 |                       |                  |
</code>```

This is what I'am trying to achieve, I'am doing this using the jasper report.

答:
Try this. You need to alias and group</p>

```<code>select MyCount,Name  from(
  select MyCount=count(m_product.name),Name=m_product.name
  from m_product
  group by m_product.name
  union
  select count(c_bpartner.name) ,c_bpartner.name
  from c_bpartner
  group by c_bpartner.name
  ) as total
</code>```

Title: sql missing from clause

Body:
  select m_product.name ,c_bpartner.name  from(
  select count(m_product.name)
  from m_product
  union
  select count(c_bpartner.name)
  from c_bpartner
  ) as total

I am getting error.

Error:

missing from-clause entry for table m_product.

Im trying to get the total number of products and bpartner in a table.
Thank you for any help.

 |total number of product|total number of bp|
 |     1000              |   1200           |
 |                       |                  |

This is what I'am trying to achieve, I'am doing this using the jasper report.

Body:
Try this. You need to alias and group

select MyCount,Name  from(
  select MyCount=count(m_product.name),Name=m_product.name
  from m_product
  group by m_product.name
  union
  select count(c_bpartner.name) ,c_bpartner.name
  from c_bpartner
  group by c_bpartner.name
  ) as total


问:
invalid method (createTableViewRow) passed to UIModule
i am having this error when i run my app on the device ( iPhone 7 ), but when i run it in the emulator works fine.
Its really strange.

The code is:

```<code>   Ti.API.info( json );
   var renglon = Ti.UI.createTableViewRow({
     id: id,
        width: Ti.UI.FILL,
        height: '80dp',
   });
</code>```

In the emulator works OK, but in the device i got an error, the error appears just after the json is printed in the log.

```<code>[WARN] :   Attempted to load TiUITableViewRowProxy: Could not find class definition.
[ERROR] :  Script Error {
[ERROR] :      column = 2875;
[ERROR] :      line = 1;
[ERROR] :      message = "invalid method (createTableViewRow) passed to  UIModule";
[ERROR] :      sourceURL =    "file:///var/containers/Bundle/Application/B99CA23F-183D-4C5F-A5DC-FA9CFC614186/CarWash.app/src/vistas/personal.js";
[ERROR] :      stack = "[native code]\nagregarRenglonPersonal@file:///var/containers/Bundle/Application/B99CA23F-183D-4C5F-A5DC- FA9CFC614186/CarWash.app/src/vistas/personal.js:1:2875\nonload@file:///var/contain  ers/Bundle/Application/B99CA23F-183D-4C5F-A5DC-  FA9CFC614186/CarWash.app/src/vistas/personal.js:1:3651";
[ERROR] :  }
-- End application log -------------------------------------------------------
</code>```

i'm using:

Titanium appcelerator studio build: 4.9.0.201705302345

SDK: 6.1.0GA

Thanks in advance.

答:
First of all: i do not really like Appcelerator Studio, did you try compiling with the cli? appc run -p ios

If that does not work it would be intresting to see more code than the snippet you posted

Body:
i am having this error when i run my app on the device ( iPhone 7 ), but when i run it in the emulator works fine.
Its really strange.

The code is:

   Ti.API.info( json );
   var renglon = Ti.UI.createTableViewRow({
     id: id,
        width: Ti.UI.FILL,
        height: '80dp',
   });

In the emulator works OK, but in the device i got an error, the error appears just after the json is printed in the log.

[WARN] :   Attempted to load TiUITableViewRowProxy: Could not find class definition.
[ERROR] :  Script Error {
[ERROR] :      column = 2875;
[ERROR] :      line = 1;
[ERROR] :      message = "invalid method (createTableViewRow) passed to  UIModule";
[ERROR] :      sourceURL =    "file:///var/containers/Bundle/Application/B99CA23F-183D-4C5F-A5DC-FA9CFC614186/CarWash.app/src/vistas/personal.js";
[ERROR] :      stack = "[native code]\nagregarRenglonPersonal@file:///var/containers/Bundle/Application/B99CA23F-183D-4C5F-A5DC- FA9CFC614186/CarWash.app/src/vistas/personal.js:1:2875\nonload@file:///var/contain  ers/Bundle/Application/B99CA23F-183D-4C5F-A5DC-  FA9CFC614186/CarWash.app/src/vistas/personal.js:1:3651";
[ERROR] :  }
-- End application log -------------------------------------------------------

i'm using:

Titanium appcelerator studio build: 4.9.0.201705302345

SDK: 6.1.0GA

Thanks in advance.


问:
How to "PERFORM" CTE queries in PL/pgSQL?
I tried to simulate my problem in the code example below. In the code below, I am doing a select * from test in a procedure. As we know, we must use the perform keyword for this. This works great:

```<code>perform * from test;
</code>```

However, if I try to rewrite that simple query as a CTE, I cannot get it working. I am getting a syntax error.

```<code>with test_as_cte as(select * from test) perform * from test_as_cte;
</code>```

Is this possible? What is the correct syntax? I tried several alternatives and going through documentation, but without any success so far.

(Please note that this is just an example to explain my problem. I know the queries do not really make any sense.)

```<code>create table test
(
    key int primary key
);

create function test() returns trigger as
$$
begin
    raise notice 'hello there';
    -- this does work
    perform * from test;
    -- this doesn't work
    with test_as_cte as(select * from test) perform * from test_as_cte;
    return new;
end;
$$
language plpgsql;

create trigger test after insert on test for each row execute procedure test();

insert into test(key) select 1;
</code>```

答:
try:

```<code>perform (with test_as_cte as(select * from test) select * from test_as_cte);
</code>```

I would never think you might need CTE and ignore the result, but if you need, thinking of perform as of "select no return" logic leads to above semantics. or perform * from (CTE) or alike

ContentLicense: CC BY-SA 4.0

Body:
I tried to simulate my problem in the code example below. In the code below, I am doing a select * from test in a procedure. As we know, we must use the perform keyword for this. This works great:

perform * from test;

However, if I try to rewrite that simple query as a CTE, I cannot get it working. I am getting a syntax error.

with test_as_cte as(select * from test) perform * from test_as_cte;

Is this possible? What is the correct syntax? I tried several alternatives and going through documentation, but without any success so far.

(Please note that this is just an example to explain my problem. I know the queries do not really make any sense.)

create table test
(
    key int primary key
);

create function test() returns trigger as
$$
begin
    raise notice 'hello there';
    -- this does work
    perform * from test;
    -- this doesn't work
    with test_as_cte as(select * from test) perform * from test_as_cte;
    return new;
end;
$$
language plpgsql;

create trigger test after insert on test for each row execute procedure test();

insert into test(key) select 1;

Body:
try:

perform (with test_as_cte as(select * from test) select * from test_as_cte);

I would never think you might need CTE and ignore the result, but if you need, thinking of perform as of "select no return" logic leads to above semantics. or perform * from (CTE) or alike


问:
Laravel pass id from blade template to store controller
I am trying to pass id to store controller as I need to save business_id that is being retrieved from another table.  However I get:

Missing argument 2 for App\Http\Controllers\EventController::store()

Here's my view:

```<code>@extends('master') @section('title', 'Live Oldham')
@section('content')
    <div class="col-lg-y col-lg-offset-3">
    <ul class="list-group-list">
        @foreach ($business->businesses as $business)
        <li class="list-group-item">
        <a target="_blank" href="{{ url('business/' . $business->id) }}"> {{($business->name) }}</a><a href="{{ url('events/create/' . $business->id) }}" class="fa fa-plus pull-right" aria-hidden="true"></a>
        </li>
        @endforeach
    </ul>
    </div>
@endsection
</code>```

Controller:

```<code>class EventController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $id = Auth::id();
        $business = User::where('id', $id)
            ->with('businesses')
            ->first();
        return view('events.viewEvent', compact('business'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        return view('events.addEvent')
            ->with('Business', Business::find($id));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, $id)
    {
        $event = new Event;
        $event->startdate = $request->input('startdate');
        $event->enddate = $request->input('enddate');
        $event->title = $request->input('title');
        $event->frequency = $request->input('frequency');
        $event->description = $request->input('description');
        $event->business_id = $id;
        $event->save();
    }
</code>```

form:

```<code>@extends('master') @section('title', 'Live Oldham')
@section('content')
<div class="container">
<!-- Alert Messages -->
@if (session('message'))
@if (session('message')=="success")
    <div class="alert alert-success">
        Event Created
    </div>
@else
    <div class="alert alert-danger">
       There has been a fatal error! Apologies, we are working to fix it!
    </div>
@endif
@endif
<!-- JQuery UI init -->
<script>
  $( function() {
    $( document ).tooltip();
  } );
</script>
 <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                <div class="panel-heading">Create Event</div>
                    <div class="panel-body">
                        <form class="form-horizontal" role="form" method="POST" action="{{ action('EventController@store') }}">
                        {{ csrf_field() }}
                        <div class="form-group{{ $errors->has('title') ? ' has-error' : '' }}">
                        <div style="display:none;" class="title_message form-control alert-warning"></div>
                            <label for="title" class="col-md-4 control-label">Event Title</label>
                        <div class="col-md-6">
                        <input id="title" type="text" class="form-control" placeholder="Event title"
                        title="What is the event title?" name="title" value="{{ old('title') }}">
                            @if ($errors->has('title'))
                                <span class="help-block">
                            <strong>{{ $errors->first('title') }}</strong>
                                </span>
                            @endif
                            </div>
                        </div>
                        <div class="form-group{{ $errors->has('frequency') ? ' has-error' : '' }}">
                        <div style="display:none ;" class="frequency_message form-control alert-warning"></div>
                            <label id="frequency2" for="frequency" class="col-md-4 control-label">Frequency</label>
                        <div class="col-md-6">
                        <select class="form-control" name="frequency" id="frequency">
                            <option selected disabled>Choose event frequency...</option>
                            <option value="One">One-time Event</option>
                            <option value="Daily">Daily</option>
                            <option value="Weekly">Weekly</option>
                            <option value="Monthly">Monthly</option>
                            <option value="Yearly">Yearly</option>
                        </select>
                                @if ($errors->has('frequency'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('frequency') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        <div class="form-group{{ $errors->has('startdate') ? ' has-error' : '' }}">
                        <div style="display:none ;" class="startdate_message form-control alert-warning"></div>
                            <label id="startdate2" for="startdate" class="col-md-4 control-label">Event Start Date</label>
                        <div class="col-md-6">
                            <input id="startdate" type="date" class="form-control" placeholder="Start Date"
                            title="When does the event start?" name="startdate" value="{{ old('startdate') }}">
                                @if ($errors->has('startdate'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('email') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        <div class="form-group{{ $errors->has('enddate') ? ' has-error' : '' }}">
                        <div style="display:none ;" class="enddate_message form-control alert-warning"></div>
                            <label id="address3" for="enddate" class="col-md-4 control-label">Event End Date</label>
                        <div class="col-md-6">
                            <input id="enddate" type="date" class="form-control" placeholder="End Date"
                            title="When does the event end?" name="enddate" value="{{ old('enddate') }}">
                                @if ($errors->has('enddate'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('enddate') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        <div class="form-group{{ $errors->has('description') ? ' has-error' : '' }}">
                        <div style="display:none ;" class="description_message form-control alert-warning"></div>
                            <label id="description2" for="description" class="col-md-4 control-label">Event Description</label>
                        <div class="col-md-6">
                            <textarea id="description" type="text" class="form-control" placeholder="Event description"
                            title="Here goes event description" name="description" value="{{ old('description') }}">
                            </textarea>
                                @if ($errors->has('description'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('description') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" id="submit" class="btn btn-success">
                                    Add Event
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

@endsection
</code>```

答:
You can pass the id to the form action</p>

```<code><form method="POST" action="{{ action('EventController@store', $business->id) }}" class="form-horizontal" role="form">
...
</form>
</code>```

Body:
I am trying to pass id to store controller as I need to save business_id that is being retrieved from another table.  However I get:

Missing argument 2 for App\Http\Controllers\EventController::store()

Here's my view:

@extends('master') @section('title', 'Live Oldham')
@section('content')

        @foreach ($business->businesses as $business)

        id) }}"> {{($business->name) }}id) }}" class="fa fa-plus pull-right" aria-hidden="true">

        @endforeach

@endsection

Controller:

class EventController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $id = Auth::id();
        $business = User::where('id', $id)
            ->with('businesses')
            ->first();
        return view('events.viewEvent', compact('business'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        return view('events.addEvent')
            ->with('Business', Business::find($id));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, $id)
    {
        $event = new Event;
        $event->startdate = $request->input('startdate');
        $event->enddate = $request->input('enddate');
        $event->title = $request->input('title');
        $event->frequency = $request->input('frequency');
        $event->description = $request->input('description');
        $event->business_id = $id;
        $event->save();
    }

form:

@extends('master') @section('title', 'Live Oldham')
@section('content')

@if (session('message'))
@if (session('message')=="success")

        Event Created

@else

       There has been a fatal error! Apologies, we are working to fix it!

@endif
@endif

Create Event

                        <form class="form-horizontal" role="form" method="POST" action="{{ action('EventController@store') }}">
                        {{ csrf_field() }}

has('title') ? ' has-error' : '' }}">

                            Event Title

                        <input id="title" type="text" class="form-control" placeholder="Event title"
                        title="What is the event title?" name="title" value="{{ old('title') }}">
                            @if ($errors->has('title'))

                            {{ $errors->first('title') }}

                            @endif

has('frequency') ? ' has-error' : '' }}">

                            Frequency

                        <select class="form-control" name="frequency" id="frequency">
                            <option selected disabled>Choose event frequency...</option>
                            <option value="One">One-time Event</option>
                            <option value="Daily">Daily</option>
                            <option value="Weekly">Weekly</option>
                            <option value="Monthly">Monthly</option>
                            <option value="Yearly">Yearly</option>
                        </select>
                                @if ($errors->has('frequency'))

                                        {{ $errors->first('frequency') }}

                                @endif

has('startdate') ? ' has-error' : '' }}">

                            Event Start Date

                            <input id="startdate" type="date" class="form-control" placeholder="Start Date"
                            title="When does the event start?" name="startdate" value="{{ old('startdate') }}">
                                @if ($errors->has('startdate'))

                                        {{ $errors->first('email') }}

                                @endif

has('enddate') ? ' has-error' : '' }}">

                            Event End Date

                            <input id="enddate" type="date" class="form-control" placeholder="End Date"
                            title="When does the event end?" name="enddate" value="{{ old('enddate') }}">
                                @if ($errors->has('enddate'))

                                        {{ $errors->first('enddate') }}

                                @endif

has('description') ? ' has-error' : '' }}">

                            Event Description

                            <textarea id="description" type="text" class="form-control" placeholder="Event description"
                            title="Here goes event description" name="description" value="{{ old('description') }}">
                            </textarea>
                                @if ($errors->has('description'))

                                        {{ $errors->first('description') }}

                                @endif

                                <button type="submit" id="submit" class="btn btn-success">
                                    Add Event
                                </button>

                    </form>

@endsection

Body:
You can pass the id to the form action

<form method="POST" action="{{ action('EventController@store', $business->id) }}" class="form-horizontal" role="form">
...
</form>


问:
how do you translate your toast?
hi my toast needs to translate to France or English depending on what you select as your language, in the login screen you can select your languages </p>

答:
Create strings.xml file depends on language.
Read:
stackoverflow.com/a/41907754/1636478
Developer Guide</p>

Title: how do you translate your toast?


答:
Put your texts for the default language in res/values/strings.xml .
and create res/values-fr/strings.xml where you put the translations for french and repeat for each language.

Your application will be shown in the correct language depending in the phone language setting.

Title: how do you translate your toast?

Body: hi my toast needs to translate to France or English depending on what you select as your language, in the login screen you can select your languages


问:
redefinition of unused function in python
I have 2 python files in the same folder utils.py and preprocessing.py.

I have two functions defined in utils.py file: preprocess_text, text2seq_generator

I need to use these functions in preprocessing.py. But I'm getting unable to import and warning saying redefinition of unused preprocess_text from line 19

Code:

utils.py

```<code>from __future__ import print_function
from collections import defaultdict
from collections import Counter
from string import punctuation
#import pdb

def filter_text(text):
    return ''.join([c for c in text if c not in punctuation]).lower()

def preprocess_text(file_path_src, file_path_tar, max_feats):
    f_src = open(file_path_src)
    f_tar = open(file_path_tar)
    vocab = defaultdict(int)
    freq_src = defaultdict(int)
    freq_tar = defaultdict(int)
    sents_src = [line.rstrip() for line in f_src.readlines()]
    sents_tar = [line.rstrip() for line in f_tar.readlines()]

    for sent in sents_src:
        sent = filter_text(sent)
        for word in sent.split():
            freq_src[word] += 1

   for sent in sents_tar:
       for word in sent.split():
           freq_tar[word] += 1

   freq_sorted_src = Counter(freq_src)
   freq_sorted_src = freq_sorted_src.most_common(max_feats)
   freq_sorted_tar = Counter(freq_tar)
   freq_sorted_tar = freq_sorted_tar.most_common(max_feats)

   freq_words_src = map(lambda x:x[0], freq_sorted_src)
   freq_words_tar = map(lambda x:x[0], freq_sorted_tar)

   vocab_src = dict({v:k for k, v in enumerate(freq_words_src)})
   vocab_tar = dict({v:k for k, v in enumerate(freq_words_tar)})

   vocab_src["UNK"] = max_feats
   vocab_src["<s>"] = max_feats + 1
   vocab_src["</s>"] = max_feats + 2

   vocab_tar["UNK"] = max_feats
   vocab_tar["<s>"] = max_feats + 1
   vocab_tar["</s>"] = max_feats + 2
   #pdb.set_trace()
   return vocab_src, vocab_tar, sents_src, sents_tar

def text2seq_generator(vocab_src, vocab_tar, sents_src, sents_tar):
    unk_key = vocab_src["UNK"]
    for sent_src, sent_tar in zip(sents_src, sents_tar):
        seq_src = map(lambda x:vocab_src.get(x, unk_key), filter_text(sent_src).split())
        seq_tar = map(lambda x:vocab_tar.get(x, unk_key), sent_tar.split())
        #pdb.set_trace()
        yield seq_src, seq_tar

 #vs, vt, ss, st = preprocess_text('../data/training.hi-en.en', '../data/training.hi-en.hi', 5000)
 #for x,y in text2seq_generator(vs, vt, ss, st):
 #print(y)
</code>```

preprocessing.py file:

```<code>  from keras.preprocessing.text import Tokenizer
  from keras.preprocessing.sequence import pad_sequences
  import codecs
  import pdb
  import numpy as np
  from utils import preprocess_text,text2seq_generator
</code>```

Error :

```<code>  from keras.preprocessing.text import Tokenizer
  from keras.preprocessing.sequence import pad_sequences
  import codecs
  import pdb
  import numpy as np
  from utils import preprocess_text

  Traceback (most recent call last):

   File "<ipython-input-8-335a30ab7871>", line 6, in <module>
from utils import preprocess_text

  ImportError: cannot import name 'preprocess_text'
</code>```

warning:

```<code>   redefinition of unused preprocess_text from line 19
</code>```

答:
It seems you have another package called utils somewhere in your PYTHONPATH that conflicts with your current file.

You can explicitly load your module from its path with the importlib module.

Add these lines to preprocessing.py (python 3.3 and 3.4):

```<code>from importlib.machinery import SourceFileLoader

utils = SourceFileLoader("utils", "/path/to/utils.py").load_module()
utils.preprocess_text(...)
</code>```

For python3.5+, you should use:

```<code>import importlib.util
spec = importlib.util.spec_from_file_location("utils", "/path/to/utils.py")
utils = importlib.util.module_from_spec(spec)
spec.loader.exec_module(utils)
utils.preprocess_text(...)
</code>```

Body:
I have 2 python files in the same folder utils.py and preprocessing.py.

I have two functions defined in utils.py file: preprocess_text, text2seq_generator

I need to use these functions in preprocessing.py. But I'm getting unable to import and warning saying redefinition of unused preprocess_text from line 19

Code:

utils.py

from __future__ import print_function
from collections import defaultdict
from collections import Counter
from string import punctuation
#import pdb

def filter_text(text):
    return ''.join([c for c in text if c not in punctuation]).lower()

def preprocess_text(file_path_src, file_path_tar, max_feats):
    f_src = open(file_path_src)
    f_tar = open(file_path_tar)
    vocab = defaultdict(int)
    freq_src = defaultdict(int)
    freq_tar = defaultdict(int)
    sents_src = [line.rstrip() for line in f_src.readlines()]
    sents_tar = [line.rstrip() for line in f_tar.readlines()]

    for sent in sents_src:
        sent = filter_text(sent)
        for word in sent.split():
            freq_src[word] += 1

   for sent in sents_tar:
       for word in sent.split():
           freq_tar[word] += 1

   freq_sorted_src = Counter(freq_src)
   freq_sorted_src = freq_sorted_src.most_common(max_feats)
   freq_sorted_tar = Counter(freq_tar)
   freq_sorted_tar = freq_sorted_tar.most_common(max_feats)

   freq_words_src = map(lambda x:x[0], freq_sorted_src)
   freq_words_tar = map(lambda x:x[0], freq_sorted_tar)

   vocab_src = dict({v:k for k, v in enumerate(freq_words_src)})
   vocab_tar = dict({v:k for k, v in enumerate(freq_words_tar)})

   vocab_src["UNK"] = max_feats
   vocab_src["<s>"] = max_feats + 1
   vocab_src["</s>"] = max_feats + 2

   vocab_tar["UNK"] = max_feats
   vocab_tar["<s>"] = max_feats + 1
   vocab_tar["</s>"] = max_feats + 2
   #pdb.set_trace()
   return vocab_src, vocab_tar, sents_src, sents_tar

def text2seq_generator(vocab_src, vocab_tar, sents_src, sents_tar):
    unk_key = vocab_src["UNK"]
    for sent_src, sent_tar in zip(sents_src, sents_tar):
        seq_src = map(lambda x:vocab_src.get(x, unk_key), filter_text(sent_src).split())
        seq_tar = map(lambda x:vocab_tar.get(x, unk_key), sent_tar.split())
        #pdb.set_trace()
        yield seq_src, seq_tar

 #vs, vt, ss, st = preprocess_text('../data/training.hi-en.en', '../data/training.hi-en.hi', 5000)
 #for x,y in text2seq_generator(vs, vt, ss, st):
 #print(y)

preprocessing.py file:

  from keras.preprocessing.text import Tokenizer
  from keras.preprocessing.sequence import pad_sequences
  import codecs
  import pdb
  import numpy as np
  from utils import preprocess_text,text2seq_generator

Error :

  from keras.preprocessing.text import Tokenizer
  from keras.preprocessing.sequence import pad_sequences
  import codecs
  import pdb
  import numpy as np
  from utils import preprocess_text

  Traceback (most recent call last):

   File "<ipython-input-8-335a30ab7871>", line 6, in <module>
from utils import preprocess_text

  ImportError: cannot import name 'preprocess_text'

warning:

   redefinition of unused preprocess_text from line 19

Body:
It seems you have another package called utils somewhere in your PYTHONPATH that conflicts with your current file.

You can explicitly load your module from its path with the importlib module.

Add these lines to preprocessing.py (python 3.3 and 3.4):

from importlib.machinery import SourceFileLoader

utils = SourceFileLoader("utils", "/path/to/utils.py").load_module()
utils.preprocess_text(...)

For python3.5+, you should use:

import importlib.util
spec = importlib.util.spec_from_file_location("utils", "/path/to/utils.py")
utils = importlib.util.module_from_spec(spec)
spec.loader.exec_module(utils)
utils.preprocess_text(...)


问:
getting null pointer exception when running the simulator of the restaurant app in eclipse
I'm getting the following error when trying to run the restaurant app in eclipse:

java.lang.NullPointerException
    at com.myrestaurant.app.ui.MainMenuForm.lambda$0(MainMenuForm.java:73)
    at com.codename1.ui.util.EventDispatcher.fireSelectionSync(EventDispatcher.java:321)
    at com.codename1.ui.util.EventDispatcher.fireSelectionEvent(EventDispatcher.java:402)
    at com.codename1.ui.list.DefaultListModel.setSelectedIndex(DefaultListModel.java:181)
    at com.codename1.ui.List.initComponentImpl(List.java:329)
    at com.codename1.ui.Container.initComponentImpl(Container.java:979)
    at com.codename1.ui.Container.insertComponentAtImpl(Container.java:715)
    at com.codename1.ui.Container.insertComponentAt(Container.java:687)
    at com.codename1.ui.Container.addComponent(Container.java:641)
    at com.codename1.ui.Form.addComponent(Form.java:1207)
    at com.codename1.ui.Container.add(Container.java:281)
    at com.myrestaurant.app.ui.BaseForm.init(BaseForm.java:102)
    at com.myrestaurant.app.ui.BaseForm.(BaseForm.java:34)
    at com.myrestaurant.app.ui.MainMenuForm.(MainMenuForm.java:43)
    at com.myrestaurant.app.ui.BaseForm.showMainMenuForm(BaseForm.java:156)
    at com.myrestaurant.app.MyRestaurant.start(MyRestaurant.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.codename1.impl.javase.Executor$1$1.run(Executor.java:123)
    at com.codename1.ui.Display.processSerialCalls(Display.java:1154)
    at com.codename1.ui.Display.mainEDTLoop(Display.java:971)
    at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
    at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

Any help please?

The method is the following:

```<code>@Override
protected List<String> createCategoryList() {
    if(Restaurant.getInstance().
                menu.get().
                categories.size() == 0) {
        categoryModel = new DefaultListModel<>("Loading...");
    } else {
        categoryModel = new DefaultListModel<>(
                Restaurant.getInstance().
                    menu.get().
                    categories.asList());
    }
    List<String> l = new List<String>(categoryModel) {
        @Override
        protected boolean shouldRenderSelection() {
            return true;
        }
    };
    ((DefaultListCellRenderer<String>)l.getRenderer()).setAlwaysRenderSelection(true);
    l.setIgnoreFocusComponentWhenUnfocused(false);
    l.setOrientation(List.HORIZONTAL);
    l.setFixedSelection(List.FIXED_CENTER);
    l.addSelectionListener((i, ii) -> {
        if(currentCategory != l.getSelectedItem()) {
            currentCategory = l.getSelectedItem();
            for(Component c : dishesContainer) {
                Dish d = (Dish)c.getClientProperty("dish");
                ***boolean hidden = d.category.get().equals(currentCategory);***
                c.setHidden(hidden);
                c.setVisible(!hidden);
            }
            dishesContainer.animateLayout(150);
        }
    });
    return l;
}
</code>```

答:
Remove the "***" characters in the list listener ...
Seems that one of this variable is null :

currentCategory

dishesContainer

d

d.category

Body:
I'm getting the following error when trying to run the restaurant app in eclipse:

java.lang.NullPointerException
    at com.myrestaurant.app.ui.MainMenuForm.lambda$0(MainMenuForm.java:73)
    at com.codename1.ui.util.EventDispatcher.fireSelectionSync(EventDispatcher.java:321)
    at com.codename1.ui.util.EventDispatcher.fireSelectionEvent(EventDispatcher.java:402)
    at com.codename1.ui.list.DefaultListModel.setSelectedIndex(DefaultListModel.java:181)
    at com.codename1.ui.List.initComponentImpl(List.java:329)
    at com.codename1.ui.Container.initComponentImpl(Container.java:979)
    at com.codename1.ui.Container.insertComponentAtImpl(Container.java:715)
    at com.codename1.ui.Container.insertComponentAt(Container.java:687)
    at com.codename1.ui.Container.addComponent(Container.java:641)
    at com.codename1.ui.Form.addComponent(Form.java:1207)
    at com.codename1.ui.Container.add(Container.java:281)
    at com.myrestaurant.app.ui.BaseForm.init(BaseForm.java:102)
    at com.myrestaurant.app.ui.BaseForm.(BaseForm.java:34)
    at com.myrestaurant.app.ui.MainMenuForm.(MainMenuForm.java:43)
    at com.myrestaurant.app.ui.BaseForm.showMainMenuForm(BaseForm.java:156)
    at com.myrestaurant.app.MyRestaurant.start(MyRestaurant.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.codename1.impl.javase.Executor$1$1.run(Executor.java:123)
    at com.codename1.ui.Display.processSerialCalls(Display.java:1154)
    at com.codename1.ui.Display.mainEDTLoop(Display.java:971)
    at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
    at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)

Any help please?

The method is the following:

@Override
protected List<String> createCategoryList() {
    if(Restaurant.getInstance().
                menu.get().
                categories.size() == 0) {
        categoryModel = new DefaultListModel<>("Loading...");
    } else {
        categoryModel = new DefaultListModel<>(
                Restaurant.getInstance().
                    menu.get().
                    categories.asList());
    }
    List<String> l = new List<String>(categoryModel) {
        @Override
        protected boolean shouldRenderSelection() {
            return true;
        }
    };
    ((DefaultListCellRenderer<String>)l.getRenderer()).setAlwaysRenderSelection(true);
    l.setIgnoreFocusComponentWhenUnfocused(false);
    l.setOrientation(List.HORIZONTAL);
    l.setFixedSelection(List.FIXED_CENTER);
    l.addSelectionListener((i, ii) -> {
        if(currentCategory != l.getSelectedItem()) {
            currentCategory = l.getSelectedItem();
            for(Component c : dishesContainer) {
                Dish d = (Dish)c.getClientProperty("dish");
                ***boolean hidden = d.category.get().equals(currentCategory);***
                c.setHidden(hidden);
                c.setVisible(!hidden);
            }
            dishesContainer.animateLayout(150);
        }
    });
    return l;
}


问:
csv string comparison not working
I'm checking if a string appears in an array filled with fgetcsv(), I've checked the content and the string it's contained at the array but in_array() returns false

```<code>function checkFieldCSV($index,$code){
    $codes  = array();
    if (($handle = fopen("./csv/file.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) {
            array_push($codes, explode(';', $data[0])[$index] );
        }
        fclose($handle);
    }
    $codes = removeCommas($codes);
    var_dump($codes);
    var_dump($code);
    return in_array($code, $codes);
}
</code>```

Output:

```<code>bool(false)
</code>```

答:
I think you try to search in a two dimensional array.

```<code>array_push($codes, explode(';', $data[0])[$index] );
</code>```

this will result in $codes[0][0...n] so in array wont work.

try the following

```<code>$found = false;
foreach($codes as $key=>$value){
   $found = in_array($code, $value);
}
return $found;
</code>```

Code is not tested, let me know if this has helped you.

Title: csv string comparison not working

Body:
I'm checking if a string appears in an array filled with fgetcsv(), I've checked the content and the string it's contained at the array but in_array() returns false

function checkFieldCSV($index,$code){
    $codes  = array();
    if (($handle = fopen("./csv/file.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) {
            array_push($codes, explode(';', $data[0])[$index] );
        }
        fclose($handle);
    }
    $codes = removeCommas($codes);
    var_dump($codes);
    var_dump($code);
    return in_array($code, $codes);
}

Output:

bool(false)

Body:
I think you try to search in a two dimensional array.

array_push($codes, explode(';', $data[0])[$index] );

this will result in $codes[0][0...n] so in array wont work.

try the following

$found = false;
foreach($codes as $key=>$value){
   $found = in_array($code, $value);
}
return $found;

Code is not tested, let me know if this has helped you.


问:
Multiple timerTask
In My app I want to do some operations on every 3mins, 5mins, 10 mins. In android is there any API
to do it in single Timer/thread. What is the best way to that ? </p>

答:
The proper way to create Timers in Android is to use Handler, as suggested here. You could create one Handler task for every interval you need.

One thing to notice is that if you need long intervals (like 3 or 5 minutes you've mentioned), your application may not running for so long. In that a case you can use and AlarmManager.

ContentLicense: CC BY-SA 2.5

Title: Multiple timerTask


问:
Maven dependency plugin adds artifact named directory
I want to copy files from some artifact. but it always adds a directory with the name of that artifact.

the pom of the artifact to copy from:

```<code><groupId>some.group</groupId>
<artifactId>scheduler-common-test-resources</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>Scheduler common test resources</name>
<description>A scheduler test resources</description>
<packaging>pom</packaging>
.
.
.
 <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.2.1</version>
            <configuration>
                <descriptors>
                    <descriptor>lib/assembly.xml</descriptor>
                </descriptors>
                <appendAssemblyId>false</appendAssemblyId>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
</code>```

the assembly file:

```<code><assembly>
<id>json</id>
<formats>
    <format>tar.gz</format>
</formats>
<fileSets>
    <fileSet>
        <directory>resources/db</directory>
        <outputDirectory>/</outputDirectory>
        <includes>
            <include>alterTables.sql</include>
            <include>createTables.sql</include>
            <include>insertsIntoReminders.sql</include>
        </includes>
        <excludes>
            <exclude>pom.xml</exclude>
        </excludes>
    </fileSet>
</fileSets>
</code>```

the item to be copied in the artifact pom:

```<code> <artifactItem>
                                <groupId>some.group</groupId>
                                <artifactId>scheduler-common-test-resources</artifactId>
                                <version>1.0.0-SNAPSHOT</version>
                                <outputDirectory>${project.build.directory}/test-classes/db/</outputDirectory>
                                <type>tar.gz</type>
                                <overWrite>false</overWrite>
                            </artifactItem>
</code>```

result:

its get copied to test-classes/db/scheduler-common-test-resources-1.0.0-SNAPSHOT/

how can i remove the directory with the artifact name?

答:
The assembly-plugin will by default add a baseDirectory, which will, also by default, be ${project.build.finalName}.

In your case, you just have to indicate the plugin that you don't need that directory by adding:

```<code><includeBaseDirectory>false</includeBaseDirectory>
</code>```

in the assembly descriptor (assembly.xmlfor you). See assembly descriptor documentation.

Body:
I want to copy files from some artifact. but it always adds a directory with the name of that artifact.

the pom of the artifact to copy from:

<groupId>some.group</groupId>
<artifactId>scheduler-common-test-resources</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>Scheduler common test resources</name>
<description>A scheduler test resources</description>
<packaging>pom</packaging>
.
.
.
 <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.2.1</version>
            <configuration>
                <descriptors>
                    <descriptor>lib/assembly.xml</descriptor>
                </descriptors>
                <appendAssemblyId>false</appendAssemblyId>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

the assembly file:

<assembly>
<id>json</id>
<formats>
    <format>tar.gz</format>
</formats>
<fileSets>
    <fileSet>
        <directory>resources/db</directory>
        <outputDirectory>/</outputDirectory>
        <includes>
            <include>alterTables.sql</include>
            <include>createTables.sql</include>
            <include>insertsIntoReminders.sql</include>
        </includes>
        <excludes>
            <exclude>pom.xml</exclude>
        </excludes>
    </fileSet>
</fileSets>

the item to be copied in the artifact pom:

 <artifactItem>
                                <groupId>some.group</groupId>
                                <artifactId>scheduler-common-test-resources</artifactId>
                                <version>1.0.0-SNAPSHOT</version>
                                <outputDirectory>${project.build.directory}/test-classes/db/</outputDirectory>
                                <type>tar.gz</type>
                                <overWrite>false</overWrite>
                            </artifactItem>

result:

its get copied to test-classes/db/scheduler-common-test-resources-1.0.0-SNAPSHOT/

how can i remove the directory with the artifact name?

Body:
The assembly-plugin will by default add a baseDirectory, which will, also by default, be ${project.build.finalName}.

In your case, you just have to indicate the plugin that you don't need that directory by adding:

<includeBaseDirectory>false</includeBaseDirectory>

in the assembly descriptor (assembly.xmlfor you). See assembly descriptor documentation.


问:
How can i get subscribe to only last data?
i am doing system of searching in my App. And i subscribe on EventBusEvent

```<code>addSubscription(TheApplication.getEventBus().observe(UpdateSearchResults.class).subscribe(event ->
        getViewModel().setParameter(event.getText())
    ));
</code>```

Event:

```<code>public class UpdateSearchResults
{
    public UpdateSearchResults(String text)
    {
        this.text = text;
    }

    public String getText()
    {
        return text;
    }

    private String text;
}
</code>```

And each time when user input new symbol. I send event like this:

```<code>TheApplication.getEventBus().post(new UpdateSearchResults(newText));
</code>```

Can i with help rxJava handle only  last data?

Example: user is input string fast: "Example" and after input symbol "e" subscription will work. But for other symbols subscription will not work.

What kind of solutions to the problem exist?

答:
There's a method debounce() which can be used to delay an emission of an item until a timeout occurred after the original event.

This means: as long as the user types, new events will be emitted and thus the old ones being dropped. When the user stops typing, the timeout will be reached and the last event emitted to the subscriber.

Body:
i am doing system of searching in my App. And i subscribe on EventBusEvent

addSubscription(TheApplication.getEventBus().observe(UpdateSearchResults.class).subscribe(event ->
        getViewModel().setParameter(event.getText())
    ));

Event:

public class UpdateSearchResults
{
    public UpdateSearchResults(String text)
    {
        this.text = text;
    }

    public String getText()
    {
        return text;
    }

    private String text;
}

And each time when user input new symbol. I send event like this:

TheApplication.getEventBus().post(new UpdateSearchResults(newText));

Can i with help rxJava handle only  last data?

Example: user is input string fast: "Example" and after input symbol "e" subscription will work. But for other symbols subscription will not work.

What kind of solutions to the problem exist?


问:
Unique values of two columns for pandas dataframe
Suppose I have pandas data frame with 2 columns:

```<code>df: Col1  Col2
      1     1
      1     2
      1     2
      1     2
      3     4
      3     4
</code>```

Then I want to keep only the unique couple values (col1, col2) of these two columns and give their frequncy:

```<code>df2: Col1  Col2  Freq
      1     1     1
      1     2     3
      3     4     2
</code>```

I think to use df['Col1', 'Col2'].value_counts() but it works only for one column.
Does it exist a function to deal with many columns?

答:
You could try

```<code>df.groupby(['Col1', 'Col2']).size()
</code>```

for a different visual output in comparison to jez's answer, you can extend that solution with

```<code>pd.DataFrame(df.groupby(['Col1', 'Col2']).size().rename('Freq'))
</code>```

gives

```<code>           Freq
Col1 Col2
1    1        1
     2        3
3    4        2
</code>```

Body:
Suppose I have pandas data frame with 2 columns:

df: Col1  Col2
      1     1
      1     2
      1     2
      1     2
      3     4
      3     4

Then I want to keep only the unique couple values (col1, col2) of these two columns and give their frequncy:

df2: Col1  Col2  Freq
      1     1     1
      1     2     3
      3     4     2

I think to use df['Col1', 'Col2'].value_counts() but it works only for one column.
Does it exist a function to deal with many columns?

Body:
You could try

df.groupby(['Col1', 'Col2']).size()

for a different visual output in comparison to jez's answer, you can extend that solution with

pd.DataFrame(df.groupby(['Col1', 'Col2']).size().rename('Freq'))

gives

           Freq
Col1 Col2
1    1        1
     2        3
3    4        2


问:
AutoMapper throwing "No default constructor" during validation
I have classes to map, but they don't have default constructors, and I don't want them to have. This is because I only map to/from already existing objects.

```<code>public class Order
{
    public string OrderName { get; set; }
    public Order(string name)
    {
        this.OrderName = name;
    }
}

public class OrderProcessor
{
    private IService service;
    public string OrderName { get; set; }

    public OrderProcessor(IService service)
    {
        this.service = service;
        Mapper.Initialize(config => config.CreateMap<Order, OrderProcessor>());
    }

    public void Init()
    {
        var order = this.service.GetOrder();

        // this works
        Mapper.Map(order, this);

        // this fails
        Mapper.Configuration.AssertConfigurationIsValid();
    }
}
</code>```

AutoMapper.AutoMapperConfigurationException :  Unmapped members were
  found. Review the types and members below. Add a custom mapping
  expression, ignore, add a custom resolver, or modify the
  source/destination type For no matching constructor, add a no-arg
  ctor, add optional arguments, or map all of the constructor parameters

Order -> OrderProcessor (Destination member list)

No available constructor.

at Test() in Tests.cs:line

How to make configuration assert pass and why it fails when I don't want to create new objects?

答:
I also stumbled onto this problem after recently upgrading from Automapper 4.x to 6.x.

You need to tell AutoMapper that you don't intend to have it construct the destination type by calling CreateMap<TSource, TDest>().DisableCtorValidation().

As per the method documentation:

```<code>    // Summary:
    //     Disable constructor validation. During mapping this map is used
    //     against an existing destination object and never constructed itself.
    //
</code>```

Body:
I have classes to map, but they don't have default constructors, and I don't want them to have. This is because I only map to/from already existing objects.

public class Order
{
    public string OrderName { get; set; }
    public Order(string name)
    {
        this.OrderName = name;
    }
}

public class OrderProcessor
{
    private IService service;
    public string OrderName { get; set; }

    public OrderProcessor(IService service)
    {
        this.service = service;
        Mapper.Initialize(config => config.CreateMap<Order, OrderProcessor>());
    }

    public void Init()
    {
        var order = this.service.GetOrder();

        // this works
        Mapper.Map(order, this);

        // this fails
        Mapper.Configuration.AssertConfigurationIsValid();
    }
}

AutoMapper.AutoMapperConfigurationException :  Unmapped members were
  found. Review the types and members below. Add a custom mapping
  expression, ignore, add a custom resolver, or modify the
  source/destination type For no matching constructor, add a no-arg
  ctor, add optional arguments, or map all of the constructor parameters

Order -> OrderProcessor (Destination member list)

No available constructor.

at Test() in Tests.cs:line

How to make configuration assert pass and why it fails when I don't want to create new objects?

Body:
I also stumbled onto this problem after recently upgrading from Automapper 4.x to 6.x.

You need to tell AutoMapper that you don't intend to have it construct the destination type by calling CreateMap<TSource, TDest>().DisableCtorValidation().

As per the method documentation:

    // Summary:
    //     Disable constructor validation. During mapping this map is used
    //     against an existing destination object and never constructed itself.
    //


问:
Fetch the current location of the user
What changes do I need to make in my code to make it fetch the current location of the user rather than predefined latitudes and longitudes?

Here is my code:

```<code>package com.example.safwan.mypersonal;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                                             .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // Add a marker in Sydney and move the camera
        LatLng cannaughtplace = new LatLng(28.6315,77.2167);
        mMap.addMarker(new MarkerOptions()
            .position(cannaughtplace)
            .title("Marker in Cannught place"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(cannaughtplace));
    }
}
</code>```

答:
```<code>  locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    try {
        location = locationManager.getLastKnownLocation(provider);
    }
    catch (Exception e)
    {

    }
    if(location==null) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

    if (location != null) {
        double lat = location.getLatitude();
        double longg = location.getLongitude();
        mMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(lat,longg) , 14.0f) );
        startService(new Intent(MainActivity.this, MyService.class));
        ismarkervisible = true;
    } else {
        Toast.makeText(MainActivity.this, "Device Failed To Fetch Lat Long", Toast.LENGTH_LONG).show();
    }
</code>```

Title: Fetch the current location of the user

Body:
What changes do I need to make in my code to make it fetch the current location of the user rather than predefined latitudes and longitudes?

Here is my code:

package com.example.safwan.mypersonal;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                                             .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // Add a marker in Sydney and move the camera
        LatLng cannaughtplace = new LatLng(28.6315,77.2167);
        mMap.addMarker(new MarkerOptions()
            .position(cannaughtplace)
            .title("Marker in Cannught place"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(cannaughtplace));
    }
}


问:
Removing columns from a txt file
I'm a beginner in Python and I'm a bit stuck on a trivial problem. I would like to remove some columns and strings from a text file. It is tab separated.
The first file is called A.txt

```<code>chr1_1792868_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->S:225) C   T   C/C C/C C/C C/C C/C C/T 234 233 232 219 233 221 234 233 232 219 233 23  0   0   0   0   0   198
</code>```

And the output file (let's call it B.txt) should be like :

```<code>1   1792868 Bcin01g04980    C   T   C/C C/C C/C C/C C/C C/T 234 233 232 219 233 221 234 233 232 219 233 23  0   0   0   0   0   198
</code>```

So it would be to perform different operations:

Remove the "chr" and "_" strings of the first column

Split the 1 after "chr" and the number after in 2 different columns

Remove all the columns 3 and 4

I tried so far to do :

```<code>with  open ('A.txt', 'r') as mutmut_mutants:
        dble_mut = csv.reader(mutmut_mutants, delimiter='\t')
        with open('B.txt', 'w+') as mutants_coo:
            mut_coo= csv.writer(mutants_coo)
            for i in dble_mut:
                del i[2]
                del i[3]
                mut_coov.writerow( i )
</code>```

But, big surprise, it's not working. And I'm not splitting the first string in 2 columns. Anyone has an idea on how to proceed?

Thanks a lot!

答:
So thanks to the code provided above (thank @Ajax1234 and @doctorlove ), I managed to have what I want in a list. I have some trouble saving it properly into a file. I want it to be tab delimited and with each element of the list as a new line.
The code is

```<code>f = open('mutmut_mutants.txt').readlines()

f = [i.strip('\n').split() for i in f]

new_data = []

for i in f:
    data1 = i[0].split("_")
    new = data1[0][-1]+" "+data1[1]+" "

    new += i[1]+" "

    new += ' '.join(i[4:])

    new_data.append(new)
print new_data

outfile = open("test.txt", "w")
print >> outfile, "\t".join(str(i) for i in new_data)
outfile.close()
</code>```

My new_data list looks like that :

['1 1792868 Bcin01g04980 C T C/C C/C C/C C/C C/C C/T 234 233 232 219 233 221 234 233 232 219 233 23 0 0 0 0 0 198', '1 1792869 Bcin01g04980 C T C/C C/T C/T C/T C/T C/T 240 236 233 220 232 220 240 96 66 80 30 25 0 140 166 140 202 194', '2 19718 Bcin02g00005 C A C/A C/A C/A C/A C/A C/A 86 51 78 84 87 108 63 38 58 60 63 86 22 13 20 24 24 22','....','....','...']

And the output in the text file looks ok except that there's not new line at the end of each element of the list :

1 1792868 Bcin01g04980 C T C/C C/C C/C C/C C/C C/T 234 233 232 219 233 221 234 233 232 219 233 23 0 0 0 0 0 198   1 1792869 Bcin01g04980 ...

Thanks for your help!

Title: Removing columns from a txt file

Body:
I'm a beginner in Python and I'm a bit stuck on a trivial problem. I would like to remove some columns and strings from a text file. It is tab separated.
The first file is called A.txt

chr1_1792868_SNP    Bcin01g04980    NON_SYNONYMOUS  NON_SYNONYMOUS[T](gene:Bcin01g04980|transcript:Bcin01g04980.1|P->S:225) C   T   C/C C/C C/C C/C C/C C/T 234 233 232 219 233 221 234 233 232 219 233 23  0   0   0   0   0   198

And the output file (let's call it B.txt) should be like :

1   1792868 Bcin01g04980    C   T   C/C C/C C/C C/C C/C C/T 234 233 232 219 233 221 234 233 232 219 233 23  0   0   0   0   0   198

So it would be to perform different operations:

Remove the "chr" and "_" strings of the first column

Split the 1 after "chr" and the number after in 2 different columns

Remove all the columns 3 and 4

I tried so far to do :

with  open ('A.txt', 'r') as mutmut_mutants:
        dble_mut = csv.reader(mutmut_mutants, delimiter='\t')
        with open('B.txt', 'w+') as mutants_coo:
            mut_coo= csv.writer(mutants_coo)
            for i in dble_mut:
                del i[2]
                del i[3]
                mut_coov.writerow( i )

But, big surprise, it's not working. And I'm not splitting the first string in 2 columns. Anyone has an idea on how to proceed?

Thanks a lot!

Body:
So thanks to the code provided above (thank @Ajax1234 and @doctorlove ), I managed to have what I want in a list. I have some trouble saving it properly into a file. I want it to be tab delimited and with each element of the list as a new line.
The code is

f = open('mutmut_mutants.txt').readlines()

f = [i.strip('\n').split() for i in f]

new_data = []

for i in f:
    data1 = i[0].split("_")
    new = data1[0][-1]+" "+data1[1]+" "

    new += i[1]+" "

    new += ' '.join(i[4:])

    new_data.append(new)
print new_data

outfile = open("test.txt", "w")
print >> outfile, "\t".join(str(i) for i in new_data)
outfile.close()

My new_data list looks like that :

['1 1792868 Bcin01g04980 C T C/C C/C C/C C/C C/C C/T 234 233 232 219 233 221 234 233 232 219 233 23 0 0 0 0 0 198', '1 1792869 Bcin01g04980 C T C/C C/T C/T C/T C/T C/T 240 236 233 220 232 220 240 96 66 80 30 25 0 140 166 140 202 194', '2 19718 Bcin02g00005 C A C/A C/A C/A C/A C/A C/A 86 51 78 84 87 108 63 38 58 60 63 86 22 13 20 24 24 22','....','....','...']

And the output in the text file looks ok except that there's not new line at the end of each element of the list :

1 1792868 Bcin01g04980 C T C/C C/C C/C C/C C/C C/T 234 233 232 219 233 221 234 233 232 219 233 23 0 0 0 0 0 198   1 1792869 Bcin01g04980 ...

Thanks for your help!


问:
How to handle windows file upload using Selenium WebDriver?
I have seen lots of questions and solutions on File upload using Selenium WebDriver on Stack Overflow. But none of them are working for following scenario.

Someone has given a solution as following

```<code>// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");
</code>```

But still I can't find window handle. How can I work on that?

I am looking for a solution for the scenario above.

Please check this on any of the following websites.

```<code>http://www.uploadify.com/demos/
http://www.zamzar.com/
</code>```

答:
Use AutoIt Script To Handle File Upload In Selenium Webdriver. It's working fine for the above scenario.

```<code>Runtime.getRuntime().exec("E:\\AutoIT\\FileUpload.exe");
</code>```

Please use below link for further assistance:
http://www.guru99.com/use-autoit-selenium.html

Body:
I have seen lots of questions and solutions on File upload using Selenium WebDriver on Stack Overflow. But none of them are working for following scenario.

Someone has given a solution as following

// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");

But still I can't find window handle. How can I work on that?

I am looking for a solution for the scenario above.

Please check this on any of the following websites.

http://www.uploadify.com/demos/
http://www.zamzar.com/

Body:
Use AutoIt Script To Handle File Upload In Selenium Webdriver. It's working fine for the above scenario.

Runtime.getRuntime().exec("E:\\AutoIT\\FileUpload.exe");

Please use below link for further assistance:
http://www.guru99.com/use-autoit-selenium.html


问:
Pandas - OR condition in joining 2 datasets
Pretty New to Pandas

I have 2 datasets , example data :

```<code>C1 C2 C3 C4
A ANN BXX 9
B YYY NNN 10
C UUU DAF 11

C7 C8 C9
N PP   C
B KK  68
F UUU  A
</code>```

Desired output :

```<code>A ANN UUU
B YYY KK
C UUU PP
</code>```

I need to join datasets in following fasion of sql query :

```<code>select C1 , C2,C8 from tab1 A, tab2  B where  (A.C1 = B.C7 or A.C1 = B.C9);
</code>```

In short I need to merge 2 datsets either if C1 = C7 or C1 = C9. I understand how to join with one condition.

Something like :

```<code>OuT = pd.merge(tab1 , tab2 , left_on = 'C1', right_on =['C7' OR 'C9'], how = 'inner')
</code>```

答:
I think you need reshape tab2 by melt and then merge:

```<code>tab2 = tab2.melt('C8', value_name='C1').drop('variable', axis=1)
#older pandas versions
#tab2 = pd.melt(tab2, id_vars='C8', value_name='C1').drop('variable', axis=1)

print (tab2)
    C8  C1
0   PP   N
1   KK   B
2  UUU   F
3   PP   C
4   KK  68
5  UUU   A

#inner join by default, so can omit how='inner'
OuT = pd.merge(tab1 , tab2 , on = 'C1')
print (OuT)
  C1   C2   C3  C4   C8
0  A  ANN  BXX   9  UUU
1  B  YYY  NNN  10   KK
2  C  UUU  DAF  11   PP
</code>```

and then if need filter columns:

```<code>OuT = pd.merge(tab1 , tab2 , on = 'C1')[['C1','C2','C8']]
print (OuT)
   C1   C2   C8
0  A  ANN  UUU
1  B  YYY   KK
2  C  UUU   PP
</code>```

Body:
Pretty New to Pandas

I have 2 datasets , example data :

C1 C2 C3 C4
A ANN BXX 9
B YYY NNN 10
C UUU DAF 11

C7 C8 C9
N PP   C
B KK  68
F UUU  A

Desired output :

A ANN UUU
B YYY KK
C UUU PP

I need to join datasets in following fasion of sql query :

select C1 , C2,C8 from tab1 A, tab2  B where  (A.C1 = B.C7 or A.C1 = B.C9);

In short I need to merge 2 datsets either if C1 = C7 or C1 = C9. I understand how to join with one condition.

Something like :

OuT = pd.merge(tab1 , tab2 , left_on = 'C1', right_on =['C7' OR 'C9'], how = 'inner')

Body:
I think you need reshape tab2 by melt and then merge:

tab2 = tab2.melt('C8', value_name='C1').drop('variable', axis=1)
#older pandas versions
#tab2 = pd.melt(tab2, id_vars='C8', value_name='C1').drop('variable', axis=1)

print (tab2)
    C8  C1
0   PP   N
1   KK   B
2  UUU   F
3   PP   C
4   KK  68
5  UUU   A

#inner join by default, so can omit how='inner'
OuT = pd.merge(tab1 , tab2 , on = 'C1')
print (OuT)
  C1   C2   C3  C4   C8
0  A  ANN  BXX   9  UUU
1  B  YYY  NNN  10   KK
2  C  UUU  DAF  11   PP

and then if need filter columns:

OuT = pd.merge(tab1 , tab2 , on = 'C1')[['C1','C2','C8']]
print (OuT)
   C1   C2   C8
0  A  ANN  UUU
1  B  YYY   KK
2  C  UUU   PP


问:
Can the controls in the toolbox be used in both Winform and WPF application?
If not, how can I know which controls are used in winforms, which controls are used in WPF?</p>

答:
If you develop a WinForms application, WPF controls are not shown in your toolbox, and vice versa.

If you want to use a WinForms control in a WPF application anyway, there's the WindowsFormsHost WPF control for that.

For hosting a WPF control in a Windows Forms app, you can use the System.Windows.Forms.Integration.ElementHost control.


问:
How to default select2 in angularJS
Instead using ui-select, I'm using jQuery select2 in AngularJS. I created custom directive for select2, for ng-model. I get the value from ng-model. But when I update the select2 on default, it doesn't work. I'm using select2 v4.0.3.

Directive

```<code>App.directive('jsSelect2', function ($timeout) {
    return {
        link: function (scope, element, attrs) {
            jQuery(element).select2();

            scope.$watch(attrs.ngModel, function(){
                $timeout(function(){
                    element.trigger('change.select2');
                },100);
            });

        }
    };
});
</code>```

HTML

```<code><select id="update_created_by" data-js-select2="" name="update_created_by"
   data-placeholder="To Who" ng-model="anc.update_created_by"
   ng-options="c.name for c in anc_staffs"
   required="required" class="form-control">
</select>
</code>```

Controller

```<code>$scope.anc_staffs = [{id:1, name:'abel'},{id:2, name:'john'}];
jQuery("#update_created_by").val(1); // Doesn't work, show empty
jQuery("#update_created_by").val(1).trigger('change.select2'); // Doesn't work, show empty
</code>```

答:
Check this working code.

just add below code.

```<code>$scope.anc = {};
$scope.anc.update_created_by = $scope.anc_staffs[0];
</code>```

        <title></title>

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />

            <select id="update_created_by" data-js-select2="" name="update_created_by"
                data-placeholder="To Who" ng-model="anc.update_created_by"
                ng-options="c.name for c in anc_staffs"
                required="required" class="form-control">
            </select>

    ```

Title: How to default select2 in angularJS

Body:
Instead using ui-select, I'm using jQuery select2 in AngularJS. I created custom directive for select2, for ng-model. I get the value from ng-model. But when I update the select2 on default, it doesn't work. I'm using select2 v4.0.3.

Directive

App.directive('jsSelect2', function ($timeout) {
    return {
        link: function (scope, element, attrs) {
            jQuery(element).select2();

            scope.$watch(attrs.ngModel, function(){
                $timeout(function(){
                    element.trigger('change.select2');
                },100);
            });

        }
    };
});

HTML

<select id="update_created_by" data-js-select2="" name="update_created_by"
   data-placeholder="To Who" ng-model="anc.update_created_by"
   ng-options="c.name for c in anc_staffs"
   required="required" class="form-control">
</select>

Controller

$scope.anc_staffs = [{id:1, name:'abel'},{id:2, name:'john'}];
jQuery("#update_created_by").val(1); // Doesn't work, show empty
jQuery("#update_created_by").val(1).trigger('change.select2'); // Doesn't work, show empty

Body:
Check this working code.

just add below code.

$scope.anc = {};
$scope.anc.update_created_by = $scope.anc_staffs[0];

     <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />
        <style>
            .select2-container {
                width: 100px !important;
            }
        </style>
        <script>
            var app = angular.module('plunker', []);

            app.controller('MainCtrl', function ($scope) {
                $scope.anc_staffs = [{ id: 1, name: 'abel' }, { id: 2, name: 'john' }];
                $scope.anc = {};
                $scope.anc.update_created_by = $scope.anc_staffs[0];
            });
            app.directive('jsSelect2', function ($timeout) {
                return {
                    link: function (scope, element, attrs) {
                        jQuery(element).select2();

                        scope.$watch(attrs.ngModel, function () {
                            $timeout(function () {
                                element.trigger('change.select2');
                            }, 100);
                        });

                    }
                };
            });

        </script>
     </head>
    <body>
        <div ng-app="plunker" ng-controller="MainCtrl">
            <select id="update_created_by" data-js-select2="" name="update_created_by"
                data-placeholder="To Who" ng-model="anc.update_created_by"
                ng-options="c.name for c in anc_staffs"
                required="required" class="form-control">
            </select>
        </div>
    </body>
    </html>


问:
Template Parse error in HTML code
I'm getting these errors when I run my Ionic 2 HTML code :
Template parse errors: Unexpected closing tag "form" " Submit [ERROR ->]
Unexpected closing tag "ion-content"" Home Page</button> --> [ERROR ->] "

Here is my HTML code :

```<code><ion-content>
    <ion-title (click)="showAlert()">
        Sign Up
    </ion-title>
    <form #userForm = "ngForm" (ngSubmit)="onSubmit(userForm.value)">
        <div>
          <ion-label color="primary">Enter Username</ion-label>
          <ion-input type="text" required #usernameRef="ngModel"  class="form-control" placeholder="Username" ngModel></ion-input>
          <div [hidden]=" usernameRef.valid || usernameRef.pristine ">
           Please enter username
          </div>
        </div>
        <div>
          <ion-label color="primary">Enter Password</ion-label>
          <ion-input type="text" required #passRef="ngModel"  class="form-control" placeholder="Password" ngModel></ion-input>
          <div [hidden]=" passRef.valid || passRef.pristine ">
           Please enter password
          </div>
        </div>
        <div>
           <ion-label color="primary">Re-enter Password</ion-label>
          <ion-input type="text" required #repassRef="ngModel"  class="form-control" placeholder="Re-enter Password" ngModel></ion-input>
          <div [hidden]=" repassRef.valid || repassRef.pristine ">
           Please re-enter password
          </div>
        </div>
        <div>
           <ion-label color="primary">Enter Email Address</ion-label>
          <ion-input type="text" required #emailRef="ngModel"  class="form-control" placeholder="example@email.com" ngModel></ion-input>
          <div [hidden]=" emailRef.valid || emailRef.pristine ">
           Please enter email
          </div>
        </div>
        <div>
           <ion-label color="primary">Enter Phone Number</ion-label>
          <ion-input type="text" required #numRef="ngModel"  class="form-control" placeholder="+91-7022-51-074" ngModel></ion-input>
          <div [hidden]=" numRef.valid || numRef.pristine ">
           Please enter phone number
          </div>
        </div>
           <ion-label color="primary">Enter Country</ion-label>
          <ion-input type="text" required #conRef="ngModel"  class="form-control" placeholder="United States" ngModel></ion-input>
          <div [hidden]=" conRef.valid || conRef.pristine ">
           Please enter country
          </div>
        <div>
        <button type="submit">Submit</button>
    </form>
     <button ion-button (click)="goBack()">Home Page</button>
</ion-content>
</code>```

Why am I getting that error ? How do I fix it?

答:
Enjoy! you forgot a div tag and add a div for a closing div</p>

```<code><ion-content>
    <ion-title (click)="showAlert()">
        Sign Up
    </ion-title>
    <form #userForm = "ngForm" (ngSubmit)="onSubmit(userForm.value)">
        <div>
          <ion-label color="primary">Enter Username</ion-label>
          <ion-input type="text" required #usernameRef="ngModel"  class="form-control" placeholder="Username" ngModel></ion-input>
          <div [hidden]=" usernameRef.valid || usernameRef.pristine ">
           Please enter username
          </div>
        </div>
        <div>
          <ion-label color="primary">Enter Password</ion-label>
          <ion-input type="text" required #passRef="ngModel"  class="form-control" placeholder="Password" ngModel></ion-input>
          <div [hidden]=" passRef.valid || passRef.pristine ">
           Please enter password
          </div>
        </div>
        <div>
           <ion-label color="primary">Re-enter Password</ion-label>
          <ion-input type="text" required #repassRef="ngModel"  class="form-control" placeholder="Re-enter Password" ngModel></ion-input>
          <div [hidden]=" repassRef.valid || repassRef.pristine ">
           Please re-enter password
          </div>
        </div>
        <div>
           <ion-label color="primary">Enter Email Address</ion-label>
          <ion-input type="text" required #emailRef="ngModel"  class="form-control" placeholder="example@email.com" ngModel></ion-input>
          <div [hidden]=" emailRef.valid || emailRef.pristine ">
           Please enter email
          </div>
        </div>
        <div>
           <ion-label color="primary">Enter Phone Number</ion-label>
          <ion-input type="text" required #numRef="ngModel"  class="form-control" placeholder="+91-7022-51-074" ngModel></ion-input>
          <div [hidden]=" numRef.valid || numRef.pristine ">
           Please enter phone number
          </div>
        </div>
        <div>
           <ion-label color="primary">Enter Country</ion-label>
          <ion-input type="text" required #conRef="ngModel"  class="form-control" placeholder="United States" ngModel></ion-input>
          <div [hidden]=" conRef.valid || conRef.pristine ">
           Please enter country
          </div>
        </div>
        <button type="submit">Submit</button>
    </form>
     <button ion-button (click)="goBack()">Home Page</button>
</ion-content>
</code>```

Title: Template Parse error in HTML code

Body:
I'm getting these errors when I run my Ionic 2 HTML code :
Template parse errors: Unexpected closing tag "form" " Submit [ERROR ->]
Unexpected closing tag "ion-content"" Home Page</button> --> [ERROR ->] "

Here is my HTML code :

<ion-content>
    <ion-title (click)="showAlert()">
        Sign Up
    </ion-title>
    <form #userForm = "ngForm" (ngSubmit)="onSubmit(userForm.value)">

          <ion-label color="primary">Enter Username</ion-label>
          <ion-input type="text" required #usernameRef="ngModel"  class="form-control" placeholder="Username" ngModel></ion-input>

           Please enter username

          <ion-label color="primary">Enter Password</ion-label>
          <ion-input type="text" required #passRef="ngModel"  class="form-control" placeholder="Password" ngModel></ion-input>

           Please enter password

           <ion-label color="primary">Re-enter Password</ion-label>
          <ion-input type="text" required #repassRef="ngModel"  class="form-control" placeholder="Re-enter Password" ngModel></ion-input>

           Please re-enter password

           <ion-label color="primary">Enter Email Address</ion-label>
          <ion-input type="text" required #emailRef="ngModel"  class="form-control" placeholder="example@email.com" ngModel></ion-input>

           Please enter email

           <ion-label color="primary">Enter Phone Number</ion-label>
          <ion-input type="text" required #numRef="ngModel"  class="form-control" placeholder="+91-7022-51-074" ngModel></ion-input>

           Please enter phone number

           <ion-label color="primary">Enter Country</ion-label>
          <ion-input type="text" required #conRef="ngModel"  class="form-control" placeholder="United States" ngModel></ion-input>

           Please enter country

        <button type="submit">Submit</button>
    </form>
     <button ion-button (click)="goBack()">Home Page</button>
</ion-content>

Why am I getting that error ? How do I fix it?

Body:
Enjoy! you forgot a div tag and add a div for a closing div

<ion-content>
    <ion-title (click)="showAlert()">
        Sign Up
    </ion-title>
    <form #userForm = "ngForm" (ngSubmit)="onSubmit(userForm.value)">
        <div>
          <ion-label color="primary">Enter Username</ion-label>
          <ion-input type="text" required #usernameRef="ngModel"  class="form-control" placeholder="Username" ngModel></ion-input>
          <div [hidden]=" usernameRef.valid || usernameRef.pristine ">
           Please enter username
          </div>
        </div>
        <div>
          <ion-label color="primary">Enter Password</ion-label>
          <ion-input type="text" required #passRef="ngModel"  class="form-control" placeholder="Password" ngModel></ion-input>
          <div [hidden]=" passRef.valid || passRef.pristine ">
           Please enter password
          </div>
        </div>
        <div>
           <ion-label color="primary">Re-enter Password</ion-label>
          <ion-input type="text" required #repassRef="ngModel"  class="form-control" placeholder="Re-enter Password" ngModel></ion-input>
          <div [hidden]=" repassRef.valid || repassRef.pristine ">
           Please re-enter password
          </div>
        </div>
        <div>
           <ion-label color="primary">Enter Email Address</ion-label>
          <ion-input type="text" required #emailRef="ngModel"  class="form-control" placeholder="example@email.com" ngModel></ion-input>
          <div [hidden]=" emailRef.valid || emailRef.pristine ">
           Please enter email
          </div>
        </div>
        <div>
           <ion-label color="primary">Enter Phone Number</ion-label>
          <ion-input type="text" required #numRef="ngModel"  class="form-control" placeholder="+91-7022-51-074" ngModel></ion-input>
          <div [hidden]=" numRef.valid || numRef.pristine ">
           Please enter phone number
          </div>
        </div>
        <div>
           <ion-label color="primary">Enter Country</ion-label>
          <ion-input type="text" required #conRef="ngModel"  class="form-control" placeholder="United States" ngModel></ion-input>
          <div [hidden]=" conRef.valid || conRef.pristine ">
           Please enter country
          </div>
        </div>
        <button type="submit">Submit</button>
    </form>
     <button ion-button (click)="goBack()">Home Page</button>
</ion-content>


问:
EF6: Adding multiple data to db or bulk operation
see my code how i am adding multiple data in db.

```<code>List<Employee> oEmp = new List<Employee>
{
    new Employee{Name="New employee2", Salary=5000},
    new Employee{Name="New employee3", Salary=6000},
    new Employee{Name="New employee4", Salary=7000}
};

using (var ctx = new TestEFContext())
{
    foreach (Employee emp in oEmp)
    {
        ctx.Employees.Add(emp);
    }
    ctx.SaveChanges();
}
</code>```

just curious to know how EF6 insert multiple data? does it insert multiple data into db in one go or add data one by one internally?

does the above code can be consider as bulk insert or bulk insert is fully different?

i saw people use many different extension to do bulk insert with EF. here are one link https://stackoverflow.com/a/43979807/6188148

so i have two questions in this post. please answer two question in details.

1) HOW EF insert mutiple data in db.....in one go or something different happen behind the curtain?

2) the way i am inserting multiple data in table....will it be consider bulk insert or bulk insert is different one?

thanks

答:
Disclaimer: I'm the owner of the project Entity Framework Extensions

HOW EF insert mutiple data in db.....in one go or something different happen behind the curtain?

EF perform a database round-trip for every entity you insert.

So if you insert 5000 entities, 5000 database round-trip will be performed.

It's always the same strategy used no matter the number of entities used.

the way i am inserting multiple data in table....will it be consider
  bulk insert or bulk insert is different one?

Bulk Insert library is completely different. They read the model and use SqlBulkCopy under the hood to perform Bulk Insert.

Your code will make a database round-trip for every entity which is INSANELY slow when thousands of entities are involved.

Should I use AddRange instead of Add?

Yes, when adding multiple entities, AddRange will only detect change once which dramatically improve the performance to add entities in the context.

Body:
see my code how i am adding multiple data in db.

List<Employee> oEmp = new List<Employee>
{
    new Employee{Name="New employee2", Salary=5000},
    new Employee{Name="New employee3", Salary=6000},
    new Employee{Name="New employee4", Salary=7000}
};

using (var ctx = new TestEFContext())
{
    foreach (Employee emp in oEmp)
    {
        ctx.Employees.Add(emp);
    }
    ctx.SaveChanges();
}

just curious to know how EF6 insert multiple data? does it insert multiple data into db in one go or add data one by one internally?

does the above code can be consider as bulk insert or bulk insert is fully different?

i saw people use many different extension to do bulk insert with EF. here are one link https://stackoverflow.com/a/43979807/6188148

so i have two questions in this post. please answer two question in details.

1) HOW EF insert mutiple data in db.....in one go or something different happen behind the curtain?

2) the way i am inserting multiple data in table....will it be consider bulk insert or bulk insert is different one?

thanks


问:
php pconnect vs connect
If I have a script which inserts data then exits,
the script will be opened by 100 users at the same time or within 2 mins.

(Actually I'm doing email tracking.)

So pconnect is better, or connect is better to reduce the resource?

I have close when after insert.

答:
mysql_pconnect() : is permanent connection with database. you cant lose your connection while such kind of operation.

mysql_connect() : is for connect database with normal way using some time due to large number of operation you might lose your connection.

I suggest mysql_pconnect() for database connection.

Title: php pconnect vs connect


问:
String not Added to Observable Collection Xamarin Forms
I have created an observable collection that is updating correctly. But is only updating one of the strings in the observable collection. I have thrown a debug point in loop that is doing this and the list of strings is showing as having two items but only one of them gets added to the observable collection.

The function that sets the observable collection:

```<code>public async Task GetNotificationData()
    {
       List<string> intermediary =  _database.getMessages();

        foreach (var variable in intermediary)
        {
            DataBaseList = new ObservableCollection<string> { variable };
        }
        _DataBaseList = DataBaseList;
    }
</code>```

and the function (getMessages) that returns the data from an SQLite database:

```<code>   public List<string> getMessages()
    {

        var DataBaseSelection =  _connection.Query<MessageTable>("Select * From [MessageTable]");
        List<string> dataList = new List<string>();

        for (var i=0;i<DataBaseSelection.Count;i++)
        {
            dataList.Add(DataBaseSelection[i].message);
        }
        return dataList;

    }
</code>```

And for completeness the Xaml:

```<code><ListView
    x:Name="notificationList"
    ItemsSource="{Binding DataBaseList}">
</ListView>
</code>```

Just to be clear this is showing one of the strings in the list on the front end but not the other, like its skipping the second string in the list.
The first string in the list is "test" the second one is called "test2" but only test is showing in the list view.

Any insights?

答:
Sorry for the poor english.

In this piece of code that sets the observable collection, you are overwriting the content of DataBaseList in each iteration, and in the end you are setting just the last result of this to the observable collection _DataBaseList.

```<code>foreach (var variable in intermediary)
{
    DataBaseList = new ObservableCollection<string> { variable };
}
_DataBaseList = DataBaseList;
</code>```

What I suggest you do:
- Initialize your observable collection at the constructor;
- To fill it, use:

```<code>_DataBaseList.Clear();
foreach(var variable in intermediary)
{
    _DatabaseList.Add(variable);
}
</code>```

And this must works. Check it out.

Body:
I have created an observable collection that is updating correctly. But is only updating one of the strings in the observable collection. I have thrown a debug point in loop that is doing this and the list of strings is showing as having two items but only one of them gets added to the observable collection.

The function that sets the observable collection:

public async Task GetNotificationData()
    {
       List<string> intermediary =  _database.getMessages();

        foreach (var variable in intermediary)
        {
            DataBaseList = new ObservableCollection<string> { variable };
        }
        _DataBaseList = DataBaseList;
    }

and the function (getMessages) that returns the data from an SQLite database:

   public List<string> getMessages()
    {

        var DataBaseSelection =  _connection.Query<MessageTable>("Select * From [MessageTable]");
        List<string> dataList = new List<string>();

        for (var i=0;i<DataBaseSelection.Count;i++)
        {
            dataList.Add(DataBaseSelection[i].message);
        }
        return dataList;

    }

And for completeness the Xaml:

<ListView
    x:Name="notificationList"
    ItemsSource="{Binding DataBaseList}">
</ListView>

Just to be clear this is showing one of the strings in the list on the front end but not the other, like its skipping the second string in the list.
The first string in the list is "test" the second one is called "test2" but only test is showing in the list view.

Any insights?

Body:
Sorry for the poor english.

In this piece of code that sets the observable collection, you are overwriting the content of DataBaseList in each iteration, and in the end you are setting just the last result of this to the observable collection _DataBaseList.

foreach (var variable in intermediary)
{
    DataBaseList = new ObservableCollection<string> { variable };
}
_DataBaseList = DataBaseList;

What I suggest you do:
- Initialize your observable collection at the constructor;
- To fill it, use:

_DataBaseList.Clear();
foreach(var variable in intermediary)
{
    _DatabaseList.Add(variable);
}

And this must works. Check it out.