问:
How to change menu sandwich to 'X' on mobile screen
I am not a bootstrap or css or front end guy. I been trying to look for help online for two days no luck, I have the following navbar:

```<code><nav class="navbar navbar-default navbar-captum navbar-static-top">
    <div class="container">
        <div class="navbar-header">

            <!-- Collapsed Hamburger -->
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#app-navbar-collapse">
                <span class="sr-only">Toggle Navigation</span>
                <span class="icon-bar top-bar"</span>
                <span class="icon-bar middle-bar"></span>
                <span class="icon-bar bottom-bar"></span>
            </button>

            <!-- Branding Image -->
            <a class="navbar-brand" href="{{ url('/') }}">
                {{--<span class="company-name">{{ config('app.name', 'Laravel') }}</span>/--}}
                <img src="{{asset('/public/images/logo-captum.png')}}" class="logo">
            </a>
        </div>

        <div class="collapse navbar-collapse" id="app-navbar-collapse">

            <!-- User Profile Navbar -->
            <ul class="nav navbar-nav navbar-right navbar-user-profile">

                <!-- Authentication Links -->
                @if (!session()->has('status'))
                    <li><a href="{{ route('login') }}" class="btn btn-default btn-login">Logga in</a></li>

                @else
                    <li>
                        <a href="//captum.provideit.se/kundservice/" target="_blank">
                            <i class="icon-custom icon-custom-message pull-left"></i>
                            Kontakta kundservice
                        </a>
                    </li>

                    <li>
                        <a href="{{ route('profile') }}">
                            <i class="icon-custom icon-custom-lock pull-left"></i>
                            {{ $customer['firstName'].str_repeat(' ',1).$customer['lastName'] }}
                        </a>
                    </li>
                    <li>
                        <a href="{{ route('logout') }}"
                           class="btn btn-default btn-login" style="margin-left: 5px;"
                           onclick="event.preventDefault();document.getElementById('logout-form').submit();">
                            Logga ut
                        </a>

                        <form id="logout-form" action="{{ route('logout') }}" method="POST"
                              style="display: none;">
                            {{ csrf_field() }}
                        </form>
                    </li>
                @endif
            </ul>

        </div>

    </div>
</nav>
</code>```

So when I shrink to phone screen I get a sandwich menu like this

Is there any way to make this menu on mobile look like this :Basically convert sandwich to 'X' and make it menu full screen centered items.

Would be very appreciated if I could get any help

答:
You can just Replace the

```<code><span class="icon-bar top-bar"></span>
<span class="icon-bar middle-bar"></span>
<span class="icon-bar bottom-bar"></span>
</code>```

with a glyphicon:

```<code><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</code>```

Here is a working fiddle example using the bootstrap 3.3.7 navbar example:
https://jsfiddle.net/ozjrhjtj/

Body:
I am not a bootstrap or css or front end guy. I been trying to look for help online for two days no luck, I have the following navbar:

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#app-navbar-collapse">
                Toggle Navigation
                <span class="icon-bar top-bar"

            </button>

                {{--{{ config('app.name', 'Laravel') }}/--}}

                @if (!session()->has('status'))

Logga in

                @else

                            Kontakta kundservice

                            {{ $customer['firstName'].str_repeat(' ',1).$customer['lastName'] }}

                            Logga ut

                        <form id="logout-form" action="{{ route('logout') }}" method="POST"
                              style="display: none;">
                            {{ csrf_field() }}
                        </form>

                @endif

So when I shrink to phone screen I get a sandwich menu like this

Is there any way to make this menu on mobile look like this :Basically convert sandwich to 'X' and make it menu full screen centered items.

Would be very appreciated if I could get any help

Body:
You can just Replace the

<span class="icon-bar top-bar"></span>
<span class="icon-bar middle-bar"></span>
<span class="icon-bar bottom-bar"></span>

with a glyphicon:

<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>

Here is a working fiddle example using the bootstrap 3.3.7 navbar example:
https://jsfiddle.net/ozjrhjtj/


来源: stackexchange

问:
Get list as array from Firebase with angularfire2(v5) and ngrx effects
I have to tell you I'm getting crazy with it. I'm trying to get data from Firebase with AngularFire2(v.5) then work with it on @ngrx/effects and store it on @ngrx/store. Well, as I need the data with the keys, my code of effects looks like this:

spaces.effects.ts

```<code>@Effect()
  getSpaces$ = this.actions$.ofType(SpacesActions.GET_SPACES_REQUEST)
  .switchMap((action: SpacesActions.GetSpacesRequest) => {
    return this.afs.list<Space>('/spaces').snapshotChanges()
      .switchMap(actions => {
      console.log('action is ', actions);
      return actions.map(space => {
      const $key = space.payload.key;
      const data: Space = { $key, ...space.payload.val() };
      console.log('snapshot is: ', data);
      return new SpacesActions.GetSpacesSuccess(data);
      });
    }
  );
</code>```

My "actions" comes with the data and the key, then I get the key for each item because then I could update and delete items easily. My database has 3 items with 3 keys. If I run this code and log it, first I can see all items in 1 array with their payloads and with the second log I see each payload as snapshot.

When I call GetSpacesSuccess, I'd like to send all snapshots I got (with key and item) then store it. The way I'm doing now dispatch this action 3 times and I can see only 2 items on the screen because the first one is overridden by the second one.

So, two questions: Is there any easier way to get the items from firebase with their keys then store them with @ngrx? If not, what am I doing wrong that my first item is being overridden and my action is being dispatched 3 times?

Please, I'm doing my best with it as I'm learning. Thank you!

spaces.reducers.ts

```<code>    case SpacesActions.GET_SPACES_REQUEST:
    return {
      state,
      spaces: null,
      loading: true
  };
    case SpacesActions.GET_SPACES_SUCCESS:
    return {
      ...state,
      ...action.payload,
      spaces: [state, action.payload],
      loading: false
    };
</code>```

spaces.actions.ts

```<code>export class GetSpacesRequest implements Action {
  readonly type = GET_SPACES_REQUEST;

}

export class GetSpacesSuccess implements Action {
  readonly type = GET_SPACES_SUCCESS;

  constructor(public payload: Space) {} <<<<<HERE I'D LIKE TO GET THE FULL ARRAY WITH EACH KEY
}
</code>```

答:
If I understood your question correctly, you would like to store for each Item  also store its key. You are looking for Map.

I would structure your feature as follows.

spaces.actions.ts:

Loading spaces requires no payload, while success has only an array of Space. I think you should build your Map<string,Space> in your reducer (string is your key).

```<code>import { Action } from '@ngrx/store';

/** App Models **/
import { Space } from './space.model';

export const GET_SPACES = '[Spaces] Spaces get';
export const GET_SPACES_SUCCESS = '[Start] Spaces get - Success';

export class GetSpacesAction implements Action {
    readonly type = GET_SPACES;
}

export class GetSpacesActionSuccess implements Action {
    readonly type = GET_SPACES_SUCCESS;
    constructor(public payload: Space[]) {}
}

export type All
    = GetSpacesAction
    | GetSpacesActionSuccess;
</code>```

spaces.effects.ts:

I'm assuming you just need a method to fetch spaces. If you need to do other stuff, just edit this piece of code. spaceService.getSpaces() is supposed to return only an array of Spaces. So, create a new Space model and, on your service, map each json entry to a new Space().

```<code>import { Injectable } from '@angular/core';
import { Actions, Effect } from '@ngrx/effects';

/** rxjs **/
import {map} from 'rxjs/operators/map';
import {mergeMap} from 'rxjs/operators/mergeMap';
import {catchError} from 'rxjs/operators/catchError';

/** ngrx **/
import * as spacesActions from './spaces.actions';

/** App Services **/
import { SpacesService } from './spaces.service';

@Injectable()
export class SpacesEffects {

    @Effect() getSpaces$ = this.actions$
      .ofType(spaceActions.GET_SPACES)
        .pipe(
          mergeMap(() => {
            return this.spaceService.getSpaces()
              .pipe(
                map((spaces) => {
                  return new spacesActions.GetSpacesActionSuccess(spaces);
                }),
                catchError((error: Error) => {
                  // Handle erro here
                })
              );
          })
        )
    ;

    constructor(private spacesService: SpacesService, private actions$: Actions) { }

}
</code>```

spaces.reducer.ts

Here you build your map and you can also create a new action to return, for instance, a space given its key. I dont think you need any loading parameter here, I guess you are using it for some loading handling in your views, just use AsyncPipe in your view and handle a loading animation with an *ngIf checking if there are spaces or not.

```<code>/** ngrx **/
import {createFeatureSelector} from '@ngrx/store';
import {createSelector} from '@ngrx/store';
import * as spacesActions from './spaces.actions';

export type Action = spacesActions.All;

/** App Models **/
import { Space } from './space.model';

export interface SpaceState {
    keySpaces: Map<string, Space>;
    spaces: Space[];
    keys: string[];
}

export const initialState: SpaceState = {
    keySpaces: new Map<string, Space>(),
    spaces: [],
    keys: []
};

// Selectors
export const selectSpace  = createFeatureSelector<SpaceState>('space');
export const getKeySpaces = createSelector(selectSpace, (state: StartState) => {
  return state.keySpaces;
});
export const getSpaces = createSelector(selectSpace, (state: SpaceState) => {
  return state.spaces;
});
export const getKeys = createSelector(selectSpace, (state: SpaceState) => {
  return state.keys;
});

export function spacesReducer(state: SpaceState = initialState, action: Action): SpaceState {
    switch (action.type) {
        case startActions.GET_SPACES_SUCCESS:
            // Since we return this from effect
            const fetchedSpaces = action.payload;
            const fetchedKeys = [];
            const keySpacesMap = new Map<string, Space>();
            fetchedSpaces.forEach( (space: Space) => {
                fetchedkeys = fetchedKeys.concat(space.key);
                keySpacesMap.set(space.key, new Space(space));
            }
            returns {
                ...state,
                keySpaces: keySpacesMap,
                spaces: fetchedSpaces,
                keys: fetchedkeys
            }
        default: {
            return state;
        }
    }
}
</code>```

And, finally, you should be able to get such parameters in your components like:

```<code>. . .

 keySpaces$ = Observable<Map<string, Space>>;
 spaces$ = Observable<Array<Space>>;
 keys$ = Observable<Array<string>>;

 constructor(private _store: Store<AppState>) {
     this.keySpaces$ = this._store.select(getKeySpaces);
     this.space$s = this._store.select(getSpaces);
     this.keys$ = this._store.select(getKeys);
 }

 . . .

 ngOnInit() {
     this._store.dispatch(new spacesActions.GetSpacesAction);
 }

. . .
</code>```

Of course add the new state to AppState:

```<code>. . .

export interface AppState {
  . . .
  space: SpaceState;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have to tell you I'm getting crazy with it. I'm trying to get data from Firebase with AngularFire2(v.5) then work with it on @ngrx/effects and store it on @ngrx/store. Well, as I need the data with the keys, my code of effects looks like this:

spaces.effects.ts

@Effect()
  getSpaces$ = this.actions$.ofType(SpacesActions.GET_SPACES_REQUEST)
  .switchMap((action: SpacesActions.GetSpacesRequest) => {
    return this.afs.list<Space>('/spaces').snapshotChanges()
      .switchMap(actions => {
      console.log('action is ', actions);
      return actions.map(space => {
      const $key = space.payload.key;
      const data: Space = { $key, ...space.payload.val() };
      console.log('snapshot is: ', data);
      return new SpacesActions.GetSpacesSuccess(data);
      });
    }
  );

My "actions" comes with the data and the key, then I get the key for each item because then I could update and delete items easily. My database has 3 items with 3 keys. If I run this code and log it, first I can see all items in 1 array with their payloads and with the second log I see each payload as snapshot.

When I call GetSpacesSuccess, I'd like to send all snapshots I got (with key and item) then store it. The way I'm doing now dispatch this action 3 times and I can see only 2 items on the screen because the first one is overridden by the second one.

So, two questions: Is there any easier way to get the items from firebase with their keys then store them with @ngrx? If not, what am I doing wrong that my first item is being overridden and my action is being dispatched 3 times?

Please, I'm doing my best with it as I'm learning. Thank you!

spaces.reducers.ts

    case SpacesActions.GET_SPACES_REQUEST:
    return {
      state,
      spaces: null,
      loading: true
  };
    case SpacesActions.GET_SPACES_SUCCESS:
    return {
      ...state,
      ...action.payload,
      spaces: [state, action.payload],
      loading: false
    };

spaces.actions.ts

export class GetSpacesRequest implements Action {
  readonly type = GET_SPACES_REQUEST;

}

export class GetSpacesSuccess implements Action {
  readonly type = GET_SPACES_SUCCESS;

  constructor(public payload: Space) {} <<<<<HERE I'D LIKE TO GET THE FULL ARRAY WITH EACH KEY
}

Body:
If I understood your question correctly, you would like to store for each Item  also store its key. You are looking for Map.

I would structure your feature as follows.

spaces.actions.ts:

Loading spaces requires no payload, while success has only an array of Space. I think you should build your Map<string,Space> in your reducer (string is your key).

import { Action } from '@ngrx/store';

/** App Models **/
import { Space } from './space.model';

export const GET_SPACES = '[Spaces] Spaces get';
export const GET_SPACES_SUCCESS = '[Start] Spaces get - Success';

export class GetSpacesAction implements Action {
    readonly type = GET_SPACES;
}

export class GetSpacesActionSuccess implements Action {
    readonly type = GET_SPACES_SUCCESS;
    constructor(public payload: Space[]) {}
}

export type All
    = GetSpacesAction
    | GetSpacesActionSuccess;

spaces.effects.ts:

I'm assuming you just need a method to fetch spaces. If you need to do other stuff, just edit this piece of code. spaceService.getSpaces() is supposed to return only an array of Spaces. So, create a new Space model and, on your service, map each json entry to a new Space().

import { Injectable } from '@angular/core';
import { Actions, Effect } from '@ngrx/effects';

/** rxjs **/
import {map} from 'rxjs/operators/map';
import {mergeMap} from 'rxjs/operators/mergeMap';
import {catchError} from 'rxjs/operators/catchError';

/** ngrx **/
import * as spacesActions from './spaces.actions';

/** App Services **/
import { SpacesService } from './spaces.service';

@Injectable()
export class SpacesEffects {

    @Effect() getSpaces$ = this.actions$
      .ofType(spaceActions.GET_SPACES)
        .pipe(
          mergeMap(() => {
            return this.spaceService.getSpaces()
              .pipe(
                map((spaces) => {
                  return new spacesActions.GetSpacesActionSuccess(spaces);
                }),
                catchError((error: Error) => {
                  // Handle erro here
                })
              );
          })
        )
    ;

    constructor(private spacesService: SpacesService, private actions$: Actions) { }

}

spaces.reducer.ts

Here you build your map and you can also create a new action to return, for instance, a space given its key. I dont think you need any loading parameter here, I guess you are using it for some loading handling in your views, just use AsyncPipe in your view and handle a loading animation with an *ngIf checking if there are spaces or not.

/** ngrx **/
import {createFeatureSelector} from '@ngrx/store';
import {createSelector} from '@ngrx/store';
import * as spacesActions from './spaces.actions';

export type Action = spacesActions.All;

/** App Models **/
import { Space } from './space.model';

export interface SpaceState {
    keySpaces: Map<string, Space>;
    spaces: Space[];
    keys: string[];
}

export const initialState: SpaceState = {
    keySpaces: new Map<string, Space>(),
    spaces: [],
    keys: []
};

// Selectors
export const selectSpace  = createFeatureSelector<SpaceState>('space');
export const getKeySpaces = createSelector(selectSpace, (state: StartState) => {
  return state.keySpaces;
});
export const getSpaces = createSelector(selectSpace, (state: SpaceState) => {
  return state.spaces;
});
export const getKeys = createSelector(selectSpace, (state: SpaceState) => {
  return state.keys;
});

export function spacesReducer(state: SpaceState = initialState, action: Action): SpaceState {
    switch (action.type) {
        case startActions.GET_SPACES_SUCCESS:
            // Since we return this from effect
            const fetchedSpaces = action.payload;
            const fetchedKeys = [];
            const keySpacesMap = new Map<string, Space>();
            fetchedSpaces.forEach( (space: Space) => {
                fetchedkeys = fetchedKeys.concat(space.key);
                keySpacesMap.set(space.key, new Space(space));
            }
            returns {
                ...state,
                keySpaces: keySpacesMap,
                spaces: fetchedSpaces,
                keys: fetchedkeys
            }
        default: {
            return state;
        }
    }
}

And, finally, you should be able to get such parameters in your components like:

. . .

 keySpaces$ = Observable<Map<string, Space>>;
 spaces$ = Observable<Array<Space>>;
 keys$ = Observable<Array<string>>;

 constructor(private _store: Store<AppState>) {
     this.keySpaces$ = this._store.select(getKeySpaces);
     this.space$s = this._store.select(getSpaces);
     this.keys$ = this._store.select(getKeys);
 }

 . . .

 ngOnInit() {
     this._store.dispatch(new spacesActions.GetSpacesAction);
 }

. . .

Of course add the new state to AppState:

. . .

export interface AppState {
  . . .
  space: SpaceState;
}


问:
How to configure ListView to automatically change its height?
I have three ListView widgets in the same LinearLayout. Something like this (I'm omitting XML elements that are not relevant in this example):

```<code><LinearLayout>
    <ListView
      android:layout_width="fill_parent"
      android:layout_height="360dp"/>
    <ListView
      android:layout_width="fill_parent"
      android:layout_height="360dp"/>
    <ListView
      android:layout_width="fill_parent"
      android:layout_height="360dp"/>
</LinearLayout>
</code>```

This forces the list to have a height of 360 dip. Of course, that will be its height even if there are few list items. So, my question is how can make the lists have an automatic height? What I want is that the ListView height takes the exact size of the sum of all its list items.

答:
Instead of editing my previous answer, here's my actual version (after finally the case became the issue and I had to fix it)

```<code>    @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, 0));

    int childHeight = getMeasuredHeight() - (getListPaddingTop() + getListPaddingBottom() +  getVerticalFadingEdgeLength() * 2);

    // on a first run let's have a space for at least one child so it'll trigger remeasurement
    int fullHeight = getListPaddingTop() + getListPaddingBottom() + childHeight*(getCount());

    int newChildHeight = 0;
    for (int x = 0; x<getChildCount(); x++ ){
        View childAt = getChildAt(x);

        if (childAt != null) {
            int height = childAt.getHeight();
            newChildHeight += height;
        }
    }

    //on a second run with actual items - use proper size
    if (newChildHeight != 0)
        fullHeight = getListPaddingTop() + getListPaddingBottom() + newChildHeight;

    setMeasuredDimension(getMeasuredWidth(), fullHeight);
}
</code>```

The trickiest part is that the onMeasure gets called twice, first for approx layout and then after items added for a precise one and both have to return sane results.

ContentLicense: CC BY-SA 2.5

Body:
I have three ListView widgets in the same LinearLayout. Something like this (I'm omitting XML elements that are not relevant in this example):

<LinearLayout>
    <ListView
      android:layout_width="fill_parent"
      android:layout_height="360dp"/>
    <ListView
      android:layout_width="fill_parent"
      android:layout_height="360dp"/>
    <ListView
      android:layout_width="fill_parent"
      android:layout_height="360dp"/>
</LinearLayout>

This forces the list to have a height of 360 dip. Of course, that will be its height even if there are few list items. So, my question is how can make the lists have an automatic height? What I want is that the ListView height takes the exact size of the sum of all its list items.

Body:
Instead of editing my previous answer, here's my actual version (after finally the case became the issue and I had to fix it)

    @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
    super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, 0));

    int childHeight = getMeasuredHeight() - (getListPaddingTop() + getListPaddingBottom() +  getVerticalFadingEdgeLength() * 2);

    // on a first run let's have a space for at least one child so it'll trigger remeasurement
    int fullHeight = getListPaddingTop() + getListPaddingBottom() + childHeight*(getCount());

    int newChildHeight = 0;
    for (int x = 0; x<getChildCount(); x++ ){
        View childAt = getChildAt(x);

        if (childAt != null) {
            int height = childAt.getHeight();
            newChildHeight += height;
        }
    }

    //on a second run with actual items - use proper size
    if (newChildHeight != 0)
        fullHeight = getListPaddingTop() + getListPaddingBottom() + newChildHeight;

    setMeasuredDimension(getMeasuredWidth(), fullHeight);
}

The trickiest part is that the onMeasure gets called twice, first for approx layout and then after items added for a precise one and both have to return sane results.


问:
Why Float error is different in C?
Please see the pictures:

I'm amazing the result is different.

答:
A CGFloat is actually a double on 64 bit platforms. (It was a float on old 32 bit platforms.)

So here you're dividing a double by a double:

```<code>CGFloat price    =    88888736      /     a;
        ^^^^^         ^^^^^^^^            ^
       double        int -> double      double
</code>```

and here you're dividing a double by a float:

```<code>CGFloat price2    =   88888736     /   100.0f;
        ^^^^^^        ^^^^^^^^         ^^^^^^
        double       int -> double      float
</code>```

Change 100.0f to either 100.0 or (CGFloat)100 and you should be fine.

LIVE DEMO

Title: Why Float error is different in C?

Body:
A CGFloat is actually a double on 64 bit platforms. (It was a float on old 32 bit platforms.)

So here you're dividing a double by a double:

CGFloat price    =    88888736      /     a;
        ^^^^^         ^^^^^^^^            ^
       double        int -> double      double

and here you're dividing a double by a float:

CGFloat price2    =   88888736     /   100.0f;
        ^^^^^^        ^^^^^^^^         ^^^^^^
        double       int -> double      float

Change 100.0f to either 100.0 or (CGFloat)100 and you should be fine.

LIVE DEMO


问:
How can I stop Express.js from causing a file to be downloaded in the browser?
In the browser, I'm trying to preview a file (Word document) by using an iframe:

```<code><iframe style="float:right;" src = "/ViewerJS/#../demo/ohm2013.odp" width='400' height='300' allowfullscreen webkitallowfullscreen></iframe>
</code>```

(if it's relevant, this is the library: http://viewerjs.org)

On the server side, I'm retrieving the file from a stream (MongoDB/GridFS) and then piping it to the res object. The relevant code is:

```<code>res.contentType("application/msword");
readstream.pipe(res);
</code>```

On the browser side, this downloads the file locally instead of previewing it.

How can I get the browser to preview my file instead of downloading it?

答:
You can only suggest to the browser what to do with the file; ultimately it's up to the browser and its configuration.

I think the default behavior is to try to show the content inline, but maybe not for certain types; you can explicitly suggest showing it inline by sending the Content-Disposition header in the response with the value inline, using res.set before sending any data:

```<code>res.set("Content-Disposition", "inline");
</code>```

This suggests to the browser that it show the file inline rather than offering to save it. But again, the browser still may to offer to save it instead.

Body:
In the browser, I'm trying to preview a file (Word document) by using an iframe:

(if it's relevant, this is the library: http://viewerjs.org)

On the server side, I'm retrieving the file from a stream (MongoDB/GridFS) and then piping it to the res object. The relevant code is:

res.contentType("application/msword");
readstream.pipe(res);

On the browser side, this downloads the file locally instead of previewing it.

How can I get the browser to preview my file instead of downloading it?

Body:
You can only suggest to the browser what to do with the file; ultimately it's up to the browser and its configuration.

I think the default behavior is to try to show the content inline, but maybe not for certain types; you can explicitly suggest showing it inline by sending the Content-Disposition header in the response with the value inline, using res.set before sending any data:

res.set("Content-Disposition", "inline");

This suggests to the browser that it show the file inline rather than offering to save it. But again, the browser still may to offer to save it instead.


问:
Nesting Excel formulas to extract e-mail address top-level domain
I want to extract the top-level domain from e-mail addresses using Excel formulas.

I tried it first with concatenating RIGHT(..) Formulas and splitting for the dot. Sadly I do not know how to do this recursively with excel formulas, so I swapped to deleting all characters except the last 4. Now the problem is, when I split my formulas into single cells it works perfectly fine. If I try to use them together, I get only the output of the first inner Formula. How do I fix this?

```<code>=RIGHT(B8; LEN(B8)-(LEN(B8)-4))
=RIGHT(BF8;LEN(BF8)-FIND(".";BF8))
</code>```

These are the formulas split into single cells. And here both together

```<code>=RIGHT(RIGHT(B8; LEN(B8)-(LEN(B8)-4));LEN(B8)-FIND(".";B8))
</code>```

I get the same return value as in the first row from this formula

```<code>=RIGHT(B8; LEN(B8)-(LEN(B8)-4))
</code>```

答:
Dot character may appear in left part if e-mail, like: john.johnson@email.com
So, you can't just find "." you need firstly find @, then find dot in right substring.
Tehese are your steps:</p>

```<code>1. =FIND("@"; B8)
find @ character place

2. =RIGHT(B8;LEN(B8) - FIND("@"; B8))
get substring right from @

3. =FIND(".";RIGHT(B8;LEN(B8) - FIND("@"; B8)))
find "." in step 2 substring

4. =RIGHT(RIGHT(B8;LEN(B8) - FIND("@"; B8)); LEN(RIGHT(B8;LEN(B8) - FIND("@"; B8))) - FIND(".";RIGHT(B8;LEN(B8) - FIND("@"; B8))))
get right(step2; len(step2) - step3)
</code>```

Body:
I want to extract the top-level domain from e-mail addresses using Excel formulas.

I tried it first with concatenating RIGHT(..) Formulas and splitting for the dot. Sadly I do not know how to do this recursively with excel formulas, so I swapped to deleting all characters except the last 4. Now the problem is, when I split my formulas into single cells it works perfectly fine. If I try to use them together, I get only the output of the first inner Formula. How do I fix this?

=RIGHT(B8; LEN(B8)-(LEN(B8)-4))
=RIGHT(BF8;LEN(BF8)-FIND(".";BF8))

These are the formulas split into single cells. And here both together

=RIGHT(RIGHT(B8; LEN(B8)-(LEN(B8)-4));LEN(B8)-FIND(".";B8))

I get the same return value as in the first row from this formula

=RIGHT(B8; LEN(B8)-(LEN(B8)-4))

Body:
Dot character may appear in left part if e-mail, like: john.johnson@email.com
So, you can't just find "." you need firstly find @, then find dot in right substring.
Tehese are your steps:

1. =FIND("@"; B8)
find @ character place

2. =RIGHT(B8;LEN(B8) - FIND("@"; B8))
get substring right from @

3. =FIND(".";RIGHT(B8;LEN(B8) - FIND("@"; B8)))
find "." in step 2 substring

4. =RIGHT(RIGHT(B8;LEN(B8) - FIND("@"; B8)); LEN(RIGHT(B8;LEN(B8) - FIND("@"; B8))) - FIND(".";RIGHT(B8;LEN(B8) - FIND("@"; B8))))
get right(step2; len(step2) - step3)


问:
c# WPF remove ListBox Content ScrollBar Gap - Photo included

I have a custom scroll bar template that is set like this:

```<code><ListBox.Resources>
   <Style TargetType="{x:Type ScrollBar}" BasedOn="{StaticResource ScrollBar_New}"/>
</ListBox.Resources>
</code>```

I am trying to move those buttons closer to the scroll bar and not sure if there is a setting I am missing someplace. Do I need to also modify the listbox control style? I am still new to WPF and not sure if there is something I am missing here. I have already tried <Setter Property="Width" Value="10"/> to see if that that alters it, but it does not.

Style Used:

```<code>    <Style x:Key="ScrollThumbs" TargetType="{x:Type Thumb}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Thumb}">
                    <Grid x:Name="Grid">
                        <Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="Auto" Height="Auto" Fill="Transparent" />
                        <Border x:Name="Rectangle1" CornerRadius="5" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="Auto" Height="Auto"
                                Background="{TemplateBinding Background}" />
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="Tag" Value="Horizontal">
                            <Setter TargetName="Rectangle1" Property="Width" Value="Auto" />
                            <Setter TargetName="Rectangle1" Property="Height" Value="7" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <!--ScrollBars-->
    <Style x:Key="ScrollBar_Rounded" TargetType="{x:Type ScrollBar}">
        <Setter Property="Stylus.IsFlicksEnabled" Value="false" />
        <Setter Property="Foreground" Value="#FFFCC515" />
        <Setter Property="Background" Value="Transparent" />
        <Setter Property="Width" Value="8" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ScrollBar}">
                    <Grid x:Name="GridRoot" Width="8" Background="{TemplateBinding Background}">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="0.00001*" />
                        </Grid.RowDefinitions>

                        <Track x:Name="PART_Track" Grid.Row="0" IsDirectionReversed="true" Focusable="false">
                            <Track.Thumb>
                                <Thumb x:Name="Thumb" Background="{TemplateBinding Foreground}" Style="{DynamicResource ScrollThumbs}" />
                            </Track.Thumb>
                            <Track.IncreaseRepeatButton>
                                <RepeatButton x:Name="PageUp" Command="ScrollBar.PageDownCommand" Opacity="0" Focusable="false" />
                            </Track.IncreaseRepeatButton>
                            <Track.DecreaseRepeatButton>
                                <RepeatButton x:Name="PageDown" Command="ScrollBar.PageUpCommand" Opacity="0" Focusable="false" />
                            </Track.DecreaseRepeatButton>
                        </Track>
                    </Grid>

                    <ControlTemplate.Triggers>
                        <Trigger SourceName="Thumb" Property="IsMouseOver" Value="true">
                            <Setter Value="{DynamicResource ButtonSelectBrush}" TargetName="Thumb" Property="Background" />
                        </Trigger>
                        <Trigger SourceName="Thumb" Property="IsDragging" Value="true">
                            <Setter Value="{DynamicResource DarkBrush}" TargetName="Thumb" Property="Background" />
                        </Trigger>

                        <Trigger Property="IsEnabled" Value="false">
                            <Setter TargetName="Thumb" Property="Visibility" Value="Collapsed" />
                        </Trigger>
                        <Trigger Property="Orientation" Value="Horizontal">
                            <Setter TargetName="GridRoot" Property="LayoutTransform">
                                <Setter.Value>
                                    <RotateTransform Angle="-90" />
                                </Setter.Value>
                            </Setter>
                            <Setter TargetName="PART_Track" Property="LayoutTransform">
                                <Setter.Value>
                                    <RotateTransform Angle="-90" />
                                </Setter.Value>
                            </Setter>
                            <Setter Property="Width" Value="Auto" />
                            <Setter Property="Height" Value="8" />
                            <Setter TargetName="Thumb" Property="Tag" Value="Horizontal" />
                            <Setter TargetName="PageDown" Property="Command" Value="ScrollBar.PageLeftCommand" />
                            <Setter TargetName="PageUp" Property="Command" Value="ScrollBar.PageRightCommand" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</code>```

答:
Ok after a little bit of testing i've come to my conclusion. In your style there are several things that affect the width of the scrollbar. To avoid to mess up the everything hardconding width

```<code>        <Style x:Key="ScrollThumbs" TargetType="{x:Type Thumb}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Thumb}">
                        <Grid x:Name="Grid">
                            <Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="Auto" Height="Auto" Fill="Transparent" />
                            <Border Margin="3" x:Name="Rectangle1" CornerRadius="5" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="Auto" Height="Auto"
                            Background="{TemplateBinding Background}" />
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="Tag" Value="Horizontal">
                                <Setter TargetName="Rectangle1" Property="Width" Value="Auto" />
                                <Setter TargetName="Rectangle1" Property="Height" Value="Auto" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <!--ScrollBars-->
        <Style x:Key="ScrollBar_Rounded" TargetType="{x:Type ScrollBar}">
            <Setter Property="Stylus.IsFlicksEnabled" Value="false" />
            <Setter Property="Foreground" Value="#FFFCC515" />
            <Setter Property="Background" Value="Transparent" />
            <Setter Property="Width" Value="8" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ScrollBar}">
                        <Grid x:Name="GridRoot" Width="Auto" Background="{TemplateBinding Background}">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="0.00001*" />
                            </Grid.RowDefinitions>

                            <Track x:Name="PART_Track" Grid.Row="0" IsDirectionReversed="true" Focusable="false">
                                <Track.Thumb>
                                    <Thumb x:Name="Thumb" Background="{TemplateBinding Foreground}" Style="{DynamicResource ScrollThumbs}" />
                                </Track.Thumb>
                                <Track.IncreaseRepeatButton>
                                    <RepeatButton x:Name="PageUp" Command="ScrollBar.PageDownCommand" Opacity="0" Focusable="false" />
                                </Track.IncreaseRepeatButton>
                                <Track.DecreaseRepeatButton>
                                    <RepeatButton x:Name="PageDown" Command="ScrollBar.PageUpCommand" Opacity="0" Focusable="false" />
                                </Track.DecreaseRepeatButton>
                            </Track>
                        </Grid>

                        <ControlTemplate.Triggers>
                            <Trigger SourceName="Thumb" Property="IsMouseOver" Value="true">
                                <Setter Value="{DynamicResource ButtonSelectBrush}" TargetName="Thumb" Property="Background" />
                            </Trigger>
                            <Trigger SourceName="Thumb" Property="IsDragging" Value="true">
                                <Setter Value="{DynamicResource DarkBrush}" TargetName="Thumb" Property="Background" />
                            </Trigger>

                            <Trigger Property="IsEnabled" Value="false">
                                <Setter TargetName="Thumb" Property="Visibility" Value="Collapsed" />
                            </Trigger>
                            <Trigger Property="Orientation" Value="Horizontal">
                                <Setter TargetName="GridRoot" Property="LayoutTransform">
                                    <Setter.Value>
                                        <RotateTransform Angle="-90" />
                                    </Setter.Value>
                                </Setter>
                                <Setter TargetName="PART_Track" Property="LayoutTransform">
                                    <Setter.Value>
                                        <RotateTransform Angle="-90" />
                                    </Setter.Value>
                                </Setter>
                                <Setter Property="Width" Value="Auto" />
                                <Setter Property="Height" Value="8" />
                                <Setter TargetName="Thumb" Property="Tag" Value="Horizontal" />
                                <Setter TargetName="PageDown" Property="Command" Value="ScrollBar.PageLeftCommand" />
                                <Setter TargetName="PageUp" Property="Command" Value="ScrollBar.PageRightCommand" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
</code>```

Shortly What i did was to :

Change the setter of the Height Property for Rectangle 1 to auto (this cause to have horizonatal and vertical scrollbar to look the same)

Set GridRoot Width to auto In the ScrollBar_Rounded style (this cause the scrollbar to get all the available space)

Use a margin in the Rectangle1 to the desired space (this will help you to decide how much space should be displayed between your scrollbars and the content of the listbox)

Body:
I have a custom scroll bar template that is set like this:

<ListBox.Resources>

Body:
Ok after a little bit of testing i've come to my conclusion. In your style there are several things that affect the width of the scrollbar. To avoid to mess up the everything hardconding width

        <Style x:Key="ScrollThumbs" TargetType="{x:Type Thumb}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Thumb}">
                        <Grid x:Name="Grid">
                            <Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="Auto" Height="Auto" Fill="Transparent" />
                            <Border Margin="3" x:Name="Rectangle1" CornerRadius="5" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Width="Auto" Height="Auto"
                            Background="{TemplateBinding Background}" />
                        </Grid>
                        <ControlTemplate.Triggers>
                            <Trigger Property="Tag" Value="Horizontal">
                                <Setter TargetName="Rectangle1" Property="Width" Value="Auto" />
                                <Setter TargetName="Rectangle1" Property="Height" Value="Auto" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <!--ScrollBars-->
        <Style x:Key="ScrollBar_Rounded" TargetType="{x:Type ScrollBar}">
            <Setter Property="Stylus.IsFlicksEnabled" Value="false" />
            <Setter Property="Foreground" Value="#FFFCC515" />
            <Setter Property="Background" Value="Transparent" />
            <Setter Property="Width" Value="8" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ScrollBar}">
                        <Grid x:Name="GridRoot" Width="Auto" Background="{TemplateBinding Background}">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="0.00001*" />
                            </Grid.RowDefinitions>

                            <Track x:Name="PART_Track" Grid.Row="0" IsDirectionReversed="true" Focusable="false">
                                <Track.Thumb>
                                    <Thumb x:Name="Thumb" Background="{TemplateBinding Foreground}" Style="{DynamicResource ScrollThumbs}" />
                                </Track.Thumb>
                                <Track.IncreaseRepeatButton>
                                    <RepeatButton x:Name="PageUp" Command="ScrollBar.PageDownCommand" Opacity="0" Focusable="false" />
                                </Track.IncreaseRepeatButton>
                                <Track.DecreaseRepeatButton>
                                    <RepeatButton x:Name="PageDown" Command="ScrollBar.PageUpCommand" Opacity="0" Focusable="false" />
                                </Track.DecreaseRepeatButton>
                            </Track>
                        </Grid>

                        <ControlTemplate.Triggers>
                            <Trigger SourceName="Thumb" Property="IsMouseOver" Value="true">
                                <Setter Value="{DynamicResource ButtonSelectBrush}" TargetName="Thumb" Property="Background" />
                            </Trigger>
                            <Trigger SourceName="Thumb" Property="IsDragging" Value="true">
                                <Setter Value="{DynamicResource DarkBrush}" TargetName="Thumb" Property="Background" />
                            </Trigger>

                            <Trigger Property="IsEnabled" Value="false">
                                <Setter TargetName="Thumb" Property="Visibility" Value="Collapsed" />
                            </Trigger>
                            <Trigger Property="Orientation" Value="Horizontal">
                                <Setter TargetName="GridRoot" Property="LayoutTransform">
                                    <Setter.Value>
                                        <RotateTransform Angle="-90" />
                                    </Setter.Value>
                                </Setter>
                                <Setter TargetName="PART_Track" Property="LayoutTransform">
                                    <Setter.Value>
                                        <RotateTransform Angle="-90" />
                                    </Setter.Value>
                                </Setter>
                                <Setter Property="Width" Value="Auto" />
                                <Setter Property="Height" Value="8" />
                                <Setter TargetName="Thumb" Property="Tag" Value="Horizontal" />
                                <Setter TargetName="PageDown" Property="Command" Value="ScrollBar.PageLeftCommand" />
                                <Setter TargetName="PageUp" Property="Command" Value="ScrollBar.PageRightCommand" />
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

Shortly What i did was to :

Change the setter of the Height Property for Rectangle 1 to auto (this cause to have horizonatal and vertical scrollbar to look the same)

Set GridRoot Width to auto In the ScrollBar_Rounded style (this cause the scrollbar to get all the available space)

Use a margin in the Rectangle1 to the desired space (this will help you to decide how much space should be displayed between your scrollbars and the content of the listbox)


问:
Android Appium Chrome Button Does not clicks or Taps?
I was able to click on links and texts but I cannot click on Button using Chrome with Android Appium

```<code>public void testcheck() {
    System.out.println("Select");
    //<a id="vivKo" href="javascript:void(0);" class="btn btn- green vivKo at_vivKo">
    //<span class="text">vivKo</span>
  //  <i class="fa fa-chevron-right"></i>  </a>
    //driver.findElementByXPath("//span[contains(., \"" + vivKo + "\")]").click();
    WebElement vova = (WebElement) driver.findElementByXPath("//*[@id=vivKo']");
    TouchAction ta = new TouchAction(driver);
    ta.longPress(vova);
    //WebElement vova = (WebElement) driver.findElementByXPath("//*[@id='vivKo']");
    driver.findElement(By.xpath("//*[@id='vivKo']")).click();
    WebElement elementToClick = driver.findElement(By.xpath("//*[@id='vivKo']"));
    Actions actions = new Actions(driver);
    new WebDriverWait(driver, 60).until(ExpectedConditions.visibilityOf(vova));
    actions.moveToElement(elementToClick).click().build().perform();
</code>```

Error: FAILED: testcheck

```<code>org.openqa.selenium.WebDriverException: unknown error: Element is not clickable at point (180, 630)
(Session info: chrome=62.0.3202.84)
(Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.12.6 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 237 milliseconds
Build info: version: '2.52.0', revision: '4c2593cfc3689a7fcd7be52549167e5ccc93ad28', time: '2016-02-11 11:22:43'
System info: host: 'AMAC02T90QRGTFM', ip: '192.168.14.180', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6', java.version: '1.8.0_144'
Driver info: io.appium.java_client.android.AndroidDriver
Capabilities [{deviceScreenSize=1440x2960, networkConnectionEnabled=true, warnings={}, databaseEnabled=false, deviceName=9887fc35525a485333, platform=LINUX, deviceUDID=9887fc35525a485333, desired={platformVersion=7.0, browserName=Chrome, platformName=Android, deviceName=Vovchik}, platformVersion=7.0, webStorageEnabled=false, locationContextEnabled=false, takesScreenshot=true, browserName=Chrome, javascriptEnabled=true, deviceModel=SM-G950U, platformName=Android, deviceManufacturer=samsung}]
Session ID: 10923751-6fb6-48d1-b61d-50be29f84770
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at
</code>```

答:
If you know there is an element that not displayed on screen but still possible to get it via driver, you can swipe up (e.g. 100 px) before you try to click it.

```<code>int x = element.getLocation().getX();
int y = element.getLocation().getY();
new TouchAction(driver)
  .press(x, y)
  .waitAction(ofMillis(500))
  .moveTo(x, y+100)
  .release()
  .perform();
</code>```

Of course, you can calculate more accurate px shift taking in account screen size.

Body:
I was able to click on links and texts but I cannot click on Button using Chrome with Android Appium

public void testcheck() {
    System.out.println("Select");
    //
    //vivKo
  //
    //driver.findElementByXPath("//span[contains(., \"" + vivKo + "\")]").click();
    WebElement vova = (WebElement) driver.findElementByXPath("//*[@id=vivKo']");
    TouchAction ta = new TouchAction(driver);
    ta.longPress(vova);
    //WebElement vova = (WebElement) driver.findElementByXPath("//*[@id='vivKo']");
    driver.findElement(By.xpath("//*[@id='vivKo']")).click();
    WebElement elementToClick = driver.findElement(By.xpath("//*[@id='vivKo']"));
    Actions actions = new Actions(driver);
    new WebDriverWait(driver, 60).until(ExpectedConditions.visibilityOf(vova));
    actions.moveToElement(elementToClick).click().build().perform();

Error: FAILED: testcheck

org.openqa.selenium.WebDriverException: unknown error: Element is not clickable at point (180, 630)
(Session info: chrome=62.0.3202.84)
(Driver info: chromedriver=2.30.477690 (c53f4ad87510ee97b5c3425a14c0e79780cdf262),platform=Mac OS X 10.12.6 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 237 milliseconds
Build info: version: '2.52.0', revision: '4c2593cfc3689a7fcd7be52549167e5ccc93ad28', time: '2016-02-11 11:22:43'
System info: host: 'AMAC02T90QRGTFM', ip: '192.168.14.180', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.12.6', java.version: '1.8.0_144'
Driver info: io.appium.java_client.android.AndroidDriver
Capabilities [{deviceScreenSize=1440x2960, networkConnectionEnabled=true, warnings={}, databaseEnabled=false, deviceName=9887fc35525a485333, platform=LINUX, deviceUDID=9887fc35525a485333, desired={platformVersion=7.0, browserName=Chrome, platformName=Android, deviceName=Vovchik}, platformVersion=7.0, webStorageEnabled=false, locationContextEnabled=false, takesScreenshot=true, browserName=Chrome, javascriptEnabled=true, deviceModel=SM-G950U, platformName=Android, deviceManufacturer=samsung}]
Session ID: 10923751-6fb6-48d1-b61d-50be29f84770
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at

Body:
If you know there is an element that not displayed on screen but still possible to get it via driver, you can swipe up (e.g. 100 px) before you try to click it.

int x = element.getLocation().getX();
int y = element.getLocation().getY();
new TouchAction(driver)
  .press(x, y)
  .waitAction(ofMillis(500))
  .moveTo(x, y+100)
  .release()
  .perform();

Of course, you can calculate more accurate px shift taking in account screen size.


问:
Swift convert NSMutableArray in string format to NSMutableArray
Hey guys so I create a NSMutableArray send it to my mysql server convert it to base64, then when the app reads the data, it decodes the base64 code into a string format. Now im trying to convert the string back into an NSMutableArray. I cant seem to get it work heres the code that converts it to a string. </p>

```<code>let string = String(data: (Data(base64Encoded:((data?.value(forKey: "14112017") as! NSArray)[0] as! NSDictionary)["data"] as! String)!), encoding: .utf8)!
</code>```

答:
So the answer to my question ended up converting my array to a JSONstring first which I did by using:

```<code>let jsonData: Data? = try? JSONSerialization.data(withJSONObject: UniversalArray)
let jsonString = String(data: jsonData!, encoding: .utf8)
</code>```

then when retreiving it I get back my jsonString, however it has "\" which I replace using:

```<code>let cleanJsonString = myData.replacingOccurrences(of: "\\", with: "")
</code>```

then to finally finish it off I just send this cleanJsonString to this function:

```<code>func convertToDictionary(text: String) -> Any? {

    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: [])
        } catch {
            print(error.localizedDescription)
        }
    }

    return nil

}
</code>```

when calling this function I used this:

```<code> let array = convertToDictionary(text: myMutableArray) as? [AnyObject]
</code>```

Thanks everyone for the amazing support, heres the answer to this bogus mess I created.

Body:
Hey guys so I create a NSMutableArray send it to my mysql server convert it to base64, then when the app reads the data, it decodes the base64 code into a string format. Now im trying to convert the string back into an NSMutableArray. I cant seem to get it work heres the code that converts it to a string.

let string = String(data: (Data(base64Encoded:((data?.value(forKey: "14112017") as! NSArray)[0] as! NSDictionary)["data"] as! String)!), encoding: .utf8)!

Body:
So the answer to my question ended up converting my array to a JSONstring first which I did by using:

let jsonData: Data? = try? JSONSerialization.data(withJSONObject: UniversalArray)
let jsonString = String(data: jsonData!, encoding: .utf8)

then when retreiving it I get back my jsonString, however it has "\" which I replace using:

let cleanJsonString = myData.replacingOccurrences(of: "\\", with: "")

then to finally finish it off I just send this cleanJsonString to this function:

func convertToDictionary(text: String) -> Any? {

    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: [])
        } catch {
            print(error.localizedDescription)
        }
    }

    return nil

}

when calling this function I used this:

 let array = convertToDictionary(text: myMutableArray) as? [AnyObject]

Thanks everyone for the amazing support, heres the answer to this bogus mess I created.


问:
mvn install jar-with-dependencies
Is there a way to do an install on a jar-with-dependencies created using maven-assembly-plugin?</p>

答: Is mvn install not doing this?

Title: mvn install jar-with-dependencies

Body: Is mvn install not doing this?


问:
unable to connect any of the specified MySQL host c# application from windows pc trying to connect mysql server on Ubuntu 16.04 server
I have C# application installed all my LAN PC having windows 10 OS, and my central server has Ubuntu 16.04 installed on which mysql server is installed and my C# application communicate to the central server, it's working well some time, but some time it gives "unable to connect any of the specified MySQL host.

I have changed mysql configuration file as:
bind-address to "my server ip address" and also check it by "0.0.0.0",
make #skip-networking comment,
open 3306 port,
allowed 3306 port in firewall,
increase max_connections,
grant user to access from % address,

And in my c# application i used standard way of connection string

It was working very well before when my server was on windows,
It is working very well without any error from my website

答:
Check connection string. Some times it's matter for Mysql (with spaces!):</p>

```<code>Server=server_host_name; Port=port_number; Database=myDataBase; Uid=user_name; Pwd=passwoed;
</code>```

Body:
Check connection string. Some times it's matter for Mysql (with spaces!):

Server=server_host_name; Port=port_number; Database=myDataBase; Uid=user_name; Pwd=passwoed;


答:
if you are using jquery (you can do this animation also without it) in your project you can try this way by adding a class to the button and managing the animation with css.

var button = document.getElementById('theButton');
button.addEventListener('click', function() {
    button.classList.toggle('active'); // or whatever your active class is
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navbar-toggle {
  padding: 6px;
}

.navbar-toggle .icon-bar{
  width: 28px;
  height: 2px;
  background: gray;
  margin-bottom: 6px;
  display: block;
  transition-duration: 0.5s;
  opacity: 1;
}

.navbar-toggle .icon-bar:last-of-type{
  margin-bottom: 0;
}

.navbar-toggle.active .icon-bar.top-bar{
  transform: rotate(45deg) translate(6px, 6px)
}
.navbar-toggle.active .icon-bar.middle-bar{
  opacity: 0;
}
.navbar-toggle.active .icon-bar.bottom-bar{
  transform: rotate(-45deg) translate(5px, -5px)
}</code>```

<button id="theButton" type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse">

            </button>```

UPDATE

I removed jquery from the script and toggled the class with pure javascript.

Title: How to change menu sandwich to 'X' on mobile screen

Body:
I am not a bootstrap or css or front end guy. I been trying to look for help online for two days no luck, I have the following navbar:

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                    data-target="#app-navbar-collapse">
                Toggle Navigation
                <span class="icon-bar top-bar"

            </button>

                {{--{{ config('app.name', 'Laravel') }}/--}}

                @if (!session()->has('status'))

Logga in

                @else

                            Kontakta kundservice

                            {{ $customer['firstName'].str_repeat(' ',1).$customer['lastName'] }}

                            Logga ut

                        <form id="logout-form" action="{{ route('logout') }}" method="POST"
                              style="display: none;">
                            {{ csrf_field() }}
                        </form>

                @endif

So when I shrink to phone screen I get a sandwich menu like this

Is there any way to make this menu on mobile look like this :Basically convert sandwich to 'X' and make it menu full screen centered items.

Would be very appreciated if I could get any help

Body:
if you are using jquery (you can do this animation also without it) in your project you can try this way by adding a class to the button and managing the animation with css.

var button = document.getElementById('theButton');
button.addEventListener('click', function() {
    button.classList.toggle('active'); // or whatever your active class is
});

.navbar-toggle {
  padding: 6px;
}

.navbar-toggle .icon-bar{
  width: 28px;
  height: 2px;
  background: gray;
  margin-bottom: 6px;
  display: block;
  transition-duration: 0.5s;
  opacity: 1;
}

.navbar-toggle .icon-bar:last-of-type{
  margin-bottom: 0;
}

.navbar-toggle.active .icon-bar.top-bar{
  transform: rotate(45deg) translate(6px, 6px)
}
.navbar-toggle.active .icon-bar.middle-bar{
  opacity: 0;
}
.navbar-toggle.active .icon-bar.bottom-bar{
  transform: rotate(-45deg) translate(5px, -5px)
}

<button id="theButton" type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse">
                <span class="icon-bar top-bar"></span>
                <span class="icon-bar middle-bar"></span>
                <span class="icon-bar bottom-bar"></span>
            </button>

UPDATE

I removed jquery from the script and toggled the class with pure javascript.


问:
Items of feature_columns must be a _FeatureColumn
I am getting this error:

ValueError: Items of feature_columns must be a _FeatureColumn. Given
  (type ): Index(['CreditScore',
  'Age', 'Tenure', 'Balance', 'NumOfProducts', 'HasCrCard',
         'IsActiveMember', 'EstimatedSalary', 'Exited'],
        dtype='object').

I am using tensorFlow lib. I want to get prediction results but I can not run m.train(input_fn=get_input_fn ,steps=5000) code. I always got the same error whatever I did. I used these  input functions in the following but nothing changed.

```<code>def input_fn_train():
     x=tf.constant(df_train.astype(np.float64)),
     y=tf.constant(df_train[LABEL].astype(np.float64))
     return x, y
</code>```

and

```<code>def get_input_fn(data_set, num_epochs=None, shuffle=False):
     return tf.estimator.inputs.pandas_input_fn(
      x=pd.DataFrame({k: data_set[k].values for k in data_set.columns}),
      y=pd.Series(data_set[LABEL].values), num_epochs=num_epochs,
                  shuffle=shuffle)
</code>```

I can not understand what should I do. What the error is about? I've been googling but never found useful thing. How can I handle this error. The code is below. Thanks!

```<code>import pandas as pd
import tensorflow as tf
import numpy as np
import tempfile

COLS= ["RowNumber","CustomerId","Surname","CreditScore","Geography",
"Gender","Age","Tenure","Balance","NumOfProducts","HasCrCard",
"IsActiveMember","EstimatedSalary","Exited"]

FEATURES = ["CreditScore","Age","Tenure","Balance","NumOfProducts",
       "HasCrCard","IsActiveMember", "EstimatedSalary"]

LABEL="Exited"

df_train = pd.read_csv("Churn_Modelling.csv", skipinitialspace=True,
header=0)
df_test = pd.read_csv("Churn_Modelling.csv", skipinitialspace=True,
header=0)
test_label = df_test[LABEL].astype(float)
df_test.drop("Surname", axis = 1, inplace=True)
df_test.drop("RowNumber", axis = 1, inplace=True)
df_test.drop("CustomerId", axis = 1, inplace=True)
df_train.drop("CustomerId", axis = 1, inplace=True)
df_train.drop("Surname", axis = 1, inplace=True)
df_train.drop("RowNumber", axis = 1, inplace=True)
df_train.drop("Geography", axis = 1, inplace=True)
df_train.drop("Gender", axis = 1, inplace=True)

def get_input_fn():
    return {'x': tf.constant(df_train[FEATURES].as_matrix(), tf.float32,
           df_train.shape),
           'y': tf.constant(df_train[LABEL].as_matrix(), tf.float32,
            df_train.shape)
           }

 df=df_train.select_dtypes(exclude=['object'])
 numeric_cols=df.columns

 m = tf.estimator.LinearClassifier(model_dir=model_dir, feature_columns=
[numeric_cols])

 m.train(input_fn=get_input_fn ,steps=5000)
 results = m.evaluate(input_fn= get_input_fn(df_test, num_epochs=1,
 shuffle=False),steps=None)

 y = m.predict(input_fn=get_input_fn(df_test, num_epochs=1, shuffle=False))
 pred = list(y)

 rowNumber=0
 for i in pred:
     print(str(rowNumber)+': '+str(pred[i]))
     rowNumber=rowNumber+1
</code>```

答:
It is working clearly.</p>

```<code>import pandas as pd
import tensorflow as tf
import tempfile
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import f1_score
from sklearn.metrics import recall_score

def split_data(data, rate, label):
    data = data.dropna()

    train_data, test_data = train_test_split(data, test_size=rate)

    train_label = train_data[label]
    train_data = train_data.drop(label, 1)

    test_label = test_data[label]
    test_data = test_data.drop(label, 1)
    return train_data, train_label, test_data, test_label

LABEL = "Exited"

data = pd.read_csv("Churn_Modelling.csv", skipinitialspace=True,
    header=0)

data.drop("Surname", axis=1, inplace=True)
data.drop("RowNumber", axis=1, inplace=True)
data.drop("CustomerId", axis=1, inplace=True)
data.drop("Geography", axis=1, inplace=True)
data.drop("Gender", axis=1, inplace=True)
x_train, y_train, x_test, y_test = split_data(data, 0.20, LABEL)

def get_input_fn_train():
    input_fn = tf.estimator.inputs.pandas_input_fn(
        x=x_train,
        y=y_train,
        shuffle=False
    )
    return input_fn

def get_input_fn_test():
    input_fn = tf.estimator.inputs.pandas_input_fn(
        x=x_test,
        y=y_test,
        shuffle=False
    )
    return input_fn

feature_columns = tf.contrib.learn.infer_real_valued_columns_from_input_fn
(get_input_fn_train())

model_dir = tempfile.mkdtemp()
m = tf.estimator.LinearClassifier(model_dir=model_dir,
feature_columns=feature_columns)

# train data
m.train(input_fn=get_input_fn_train(), steps=5000)

# you can get accuracy, accuracy_baseline, auc, auc_precision_recall,
#average_loss, global_step, label/mean, lossprediction/mean

results = m.evaluate(input_fn=get_input_fn_test(), steps=None)

print("model directory = %s" % model_dir)
for key in sorted(results):
    print("%s: %s" % (key, results[key]))

# get prediction results
y = m.predict(input_fn=get_input_fn_test())
predictions = list(y)
pred1=pd.DataFrame(data=predictions)
prediction=pd.DataFrame(data=pred1['class_ids'])
pred=[]
for row in prediction["class_ids"]:
    pred.append(row[0])

rowNumber = 0
for i in pred:
    print(str(rowNumber) + ': ' + str(i))
    rowNumber = rowNumber + 1

def calculate(prediction, LABEL):
    arr = {"accuracy": accuracy_score(prediction, LABEL),
           "report": classification_report(prediction, LABEL),
           "Confusion_Matrix": confusion_matrix(prediction, LABEL),
           "F1 score": f1_score(prediction, LABEL),
           "Recall Score": recall_score(prediction, LABEL),
           "cohen_kappa": cohen_kappa_score(prediction, LABEL)
           }
    return arr

pred2 = pd.DataFrame(data=pred)

print(calculate(pred2.round(), y_test))
</code>```

Body:
I am getting this error:

ValueError: Items of feature_columns must be a _FeatureColumn. Given
  (type ): Index(['CreditScore',
  'Age', 'Tenure', 'Balance', 'NumOfProducts', 'HasCrCard',
         'IsActiveMember', 'EstimatedSalary', 'Exited'],
        dtype='object').

I am using tensorFlow lib. I want to get prediction results but I can not run m.train(input_fn=get_input_fn ,steps=5000) code. I always got the same error whatever I did. I used these  input functions in the following but nothing changed.

def input_fn_train():
     x=tf.constant(df_train.astype(np.float64)),
     y=tf.constant(df_train[LABEL].astype(np.float64))
     return x, y

and

def get_input_fn(data_set, num_epochs=None, shuffle=False):
     return tf.estimator.inputs.pandas_input_fn(
      x=pd.DataFrame({k: data_set[k].values for k in data_set.columns}),
      y=pd.Series(data_set[LABEL].values), num_epochs=num_epochs,
                  shuffle=shuffle)

I can not understand what should I do. What the error is about? I've been googling but never found useful thing. How can I handle this error. The code is below. Thanks!

import pandas as pd
import tensorflow as tf
import numpy as np
import tempfile

COLS= ["RowNumber","CustomerId","Surname","CreditScore","Geography",
"Gender","Age","Tenure","Balance","NumOfProducts","HasCrCard",
"IsActiveMember","EstimatedSalary","Exited"]

FEATURES = ["CreditScore","Age","Tenure","Balance","NumOfProducts",
       "HasCrCard","IsActiveMember", "EstimatedSalary"]

LABEL="Exited"

df_train = pd.read_csv("Churn_Modelling.csv", skipinitialspace=True,
header=0)
df_test = pd.read_csv("Churn_Modelling.csv", skipinitialspace=True,
header=0)
test_label = df_test[LABEL].astype(float)
df_test.drop("Surname", axis = 1, inplace=True)
df_test.drop("RowNumber", axis = 1, inplace=True)
df_test.drop("CustomerId", axis = 1, inplace=True)
df_train.drop("CustomerId", axis = 1, inplace=True)
df_train.drop("Surname", axis = 1, inplace=True)
df_train.drop("RowNumber", axis = 1, inplace=True)
df_train.drop("Geography", axis = 1, inplace=True)
df_train.drop("Gender", axis = 1, inplace=True)

def get_input_fn():
    return {'x': tf.constant(df_train[FEATURES].as_matrix(), tf.float32,
           df_train.shape),
           'y': tf.constant(df_train[LABEL].as_matrix(), tf.float32,
            df_train.shape)
           }

 df=df_train.select_dtypes(exclude=['object'])
 numeric_cols=df.columns

 m = tf.estimator.LinearClassifier(model_dir=model_dir, feature_columns=
[numeric_cols])

 m.train(input_fn=get_input_fn ,steps=5000)
 results = m.evaluate(input_fn= get_input_fn(df_test, num_epochs=1,
 shuffle=False),steps=None)

 y = m.predict(input_fn=get_input_fn(df_test, num_epochs=1, shuffle=False))
 pred = list(y)

 rowNumber=0
 for i in pred:
     print(str(rowNumber)+': '+str(pred[i]))
     rowNumber=rowNumber+1

Body:
It is working clearly.

import pandas as pd
import tensorflow as tf
import tempfile
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import cohen_kappa_score
from sklearn.metrics import f1_score
from sklearn.metrics import recall_score

def split_data(data, rate, label):
    data = data.dropna()

    train_data, test_data = train_test_split(data, test_size=rate)

    train_label = train_data[label]
    train_data = train_data.drop(label, 1)

    test_label = test_data[label]
    test_data = test_data.drop(label, 1)
    return train_data, train_label, test_data, test_label

LABEL = "Exited"

data = pd.read_csv("Churn_Modelling.csv", skipinitialspace=True,
    header=0)

data.drop("Surname", axis=1, inplace=True)
data.drop("RowNumber", axis=1, inplace=True)
data.drop("CustomerId", axis=1, inplace=True)
data.drop("Geography", axis=1, inplace=True)
data.drop("Gender", axis=1, inplace=True)
x_train, y_train, x_test, y_test = split_data(data, 0.20, LABEL)

def get_input_fn_train():
    input_fn = tf.estimator.inputs.pandas_input_fn(
        x=x_train,
        y=y_train,
        shuffle=False
    )
    return input_fn

def get_input_fn_test():
    input_fn = tf.estimator.inputs.pandas_input_fn(
        x=x_test,
        y=y_test,
        shuffle=False
    )
    return input_fn

feature_columns = tf.contrib.learn.infer_real_valued_columns_from_input_fn
(get_input_fn_train())

model_dir = tempfile.mkdtemp()
m = tf.estimator.LinearClassifier(model_dir=model_dir,
feature_columns=feature_columns)

# train data
m.train(input_fn=get_input_fn_train(), steps=5000)

# you can get accuracy, accuracy_baseline, auc, auc_precision_recall,
#average_loss, global_step, label/mean, lossprediction/mean

results = m.evaluate(input_fn=get_input_fn_test(), steps=None)

print("model directory = %s" % model_dir)
for key in sorted(results):
    print("%s: %s" % (key, results[key]))

# get prediction results
y = m.predict(input_fn=get_input_fn_test())
predictions = list(y)
pred1=pd.DataFrame(data=predictions)
prediction=pd.DataFrame(data=pred1['class_ids'])
pred=[]
for row in prediction["class_ids"]:
    pred.append(row[0])

rowNumber = 0
for i in pred:
    print(str(rowNumber) + ': ' + str(i))
    rowNumber = rowNumber + 1

def calculate(prediction, LABEL):
    arr = {"accuracy": accuracy_score(prediction, LABEL),
           "report": classification_report(prediction, LABEL),
           "Confusion_Matrix": confusion_matrix(prediction, LABEL),
           "F1 score": f1_score(prediction, LABEL),
           "Recall Score": recall_score(prediction, LABEL),
           "cohen_kappa": cohen_kappa_score(prediction, LABEL)
           }
    return arr

pred2 = pd.DataFrame(data=pred)

print(calculate(pred2.round(), y_test))


问:
setText on button from another activity android
I have a problem, I want to click on the list, calling a new activity and rename the button to another name.

I tried several things, nothing worked, can someone please help me?

My class EditarTimes:

```private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
        t = times.get(pos);

        <strike>CadastroTimes cad = new CadastroTimes();</strike>
        <strike>CadastroTimes.salvar.setText("Alterar");</strike>
        Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
        startActivity(intent);

    }

};```

public class CadastroTimes extends AppCompatActivity {

    private Time t;
    private timeDatabase db;
    private EditText edID;
    private EditText edNome;
    public Button salvar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cadastro_times);

        edID = (EditText) findViewById(R.id.edID);
        edNome = (EditText) findViewById(R.id.edNome);
        db = new timeDatabase(getApplicationContext());
        salvar = (Button) findViewById(R.id.btnCadastrar);
        salvar.setText("Cadastrar");
        String newString;
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            if(extras == null) {
                newString= null;
            } else {
                newString= extras.getString("Alterar");
            }
        } else {
            newString= (String) savedInstanceState.getSerializable("Alterar");
        }

        //button in CadastroTimes activity to have that String as text
        System.out.println(newString + " AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
        salvar.setText(newString);
    }

    public void salvarTime(View v) {
        t = new Time();
        t.setNome(edNome.getText().toString());

        if (salvar.getText().equals("Alterar")) {
            db.atualizar(t);
            exibirMensagem("Time atualizado com sucesso!");
        } else {
            db.salvar(t);
            exibirMensagem("Time cadastrado com sucesso!");
        }

        Intent intent = new Intent(this, EditarTimes.class);
        startActivity(intent);

    }

    private void limparDados() {
        edID.setText("");
        edNome.setText("");
        edNome.requestFocus();
    }

    private void exibirMensagem(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

}
```
<pre class="lang-java prettyprint-override"><code>public class EditarTimes extends AppCompatActivity {

    private Time t;
    private List<Time> times;
    private timeDatabase db;
    private ListView lvTimes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editar_times);

        lvTimes = (ListView) findViewById(R.id.lvTimes);
        lvTimes.setOnItemClickListener(selecionarTime);
        lvTimes.setOnItemLongClickListener(excluirTime);
        times = new ArrayList<Time>();
        db = new timeDatabase(getApplicationContext());
        atualizarLista();
    }

    private void excluirTime(final int idTime) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Excluir time?")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setMessage("Deseja excluir esse time?")
                .setCancelable(false)
                .setPositiveButton(getString(R.string.sim),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                if (db.deletar(idTime)) {
                                    atualizarLista();
                                    exibirMensagem(getString(R.string.msgExclusao));
                                } else {
                                    exibirMensagem(getString(R.string.msgFalhaExclusao));
                                }

                            }
                        })
                .setNegativeButton(getString(R.string.nao),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
        builder.create();
        builder.show();

        atualizarLista();

    }

    private void atualizarLista() {

        times = db.listAll();
        if (times != null) {
            if (times.size() > 0) {
                TimeListAdapter tla = new TimeListAdapter(
                        getApplicationContext(), times);
                lvTimes.setAdapter(tla);
            }

        }

    }

    private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
            t = times.get(pos);

            Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
            String strName = "Alterar";
            intent.putExtra("Alterar", strName);
            startActivity(intent);
        }

    };

    private AdapterView.OnItemLongClickListener excluirTime = new AdapterView.OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       int pos, long arg3) {
            excluirTime(times.get(pos).getId());
            return true;
        }

    };

    private void exibirMensagem(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

    public void telaCadastrar(View view) {
        Intent intent = new Intent(this, CadastroTimes.class);
        startActivity(intent);
    }

    public void botaoSair(View view) {
        Intent intent = new Intent(this, TelaInicial.class);
        startActivity(intent);
    }
}
</code>```

答:
1: Use intent.putExtra() to share a value from one activity another activity, as:

In ActivityOne.class :

```<code>startActivity(
    Intent(
        applicationContext,
        ActivityTwo::class.java
    ).putExtra(
        "key",
        "value"
    )
)
</code>```

In ActivityTwo.class :

```<code>var value = ""
if (intent.hasExtra("key")
    value = intent.getStringExtra("key")
</code>```

2: Modify button text programatically as:

```<code>btn_object.text = value
</code>```

Hope this will help you

ContentLicense: CC BY-SA 4.0

Body:
I have a problem, I want to click on the list, calling a new activity and rename the button to another name.

I tried several things, nothing worked, can someone please help me?

My class EditarTimes:

private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {

    public void onItemClick(AdapterView arg0, View arg1, int pos, long id) {
        t = times.get(pos);

        CadastroTimes cad = new CadastroTimes();
        CadastroTimes.salvar.setText("Alterar");
        Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
        startActivity(intent);

    }

};

public class CadastroTimes extends AppCompatActivity {

    private Time t;
    private timeDatabase db;
    private EditText edID;
    private EditText edNome;
    public Button salvar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cadastro_times);

        edID = (EditText) findViewById(R.id.edID);
        edNome = (EditText) findViewById(R.id.edNome);
        db = new timeDatabase(getApplicationContext());
        salvar = (Button) findViewById(R.id.btnCadastrar);
        salvar.setText("Cadastrar");
        String newString;
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            if(extras == null) {
                newString= null;
            } else {
                newString= extras.getString("Alterar");
            }
        } else {
            newString= (String) savedInstanceState.getSerializable("Alterar");
        }

        //button in CadastroTimes activity to have that String as text
        System.out.println(newString + " AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
        salvar.setText(newString);
    }

    public void salvarTime(View v) {
        t = new Time();
        t.setNome(edNome.getText().toString());

        if (salvar.getText().equals("Alterar")) {
            db.atualizar(t);
            exibirMensagem("Time atualizado com sucesso!");
        } else {
            db.salvar(t);
            exibirMensagem("Time cadastrado com sucesso!");
        }

        Intent intent = new Intent(this, EditarTimes.class);
        startActivity(intent);

    }

    private void limparDados() {
        edID.setText("");
        edNome.setText("");
        edNome.requestFocus();
    }

    private void exibirMensagem(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

}

public class EditarTimes extends AppCompatActivity {

    private Time t;
    private List<Time> times;
    private timeDatabase db;
    private ListView lvTimes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editar_times);

        lvTimes = (ListView) findViewById(R.id.lvTimes);
        lvTimes.setOnItemClickListener(selecionarTime);
        lvTimes.setOnItemLongClickListener(excluirTime);
        times = new ArrayList<Time>();
        db = new timeDatabase(getApplicationContext());
        atualizarLista();
    }

    private void excluirTime(final int idTime) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Excluir time?")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setMessage("Deseja excluir esse time?")
                .setCancelable(false)
                .setPositiveButton(getString(R.string.sim),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                if (db.deletar(idTime)) {
                                    atualizarLista();
                                    exibirMensagem(getString(R.string.msgExclusao));
                                } else {
                                    exibirMensagem(getString(R.string.msgFalhaExclusao));
                                }

                            }
                        })
                .setNegativeButton(getString(R.string.nao),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
        builder.create();
        builder.show();

        atualizarLista();

    }

    private void atualizarLista() {

        times = db.listAll();
        if (times != null) {
            if (times.size() > 0) {
                TimeListAdapter tla = new TimeListAdapter(
                        getApplicationContext(), times);
                lvTimes.setAdapter(tla);
            }

        }

    }

    private AdapterView.OnItemClickListener selecionarTime = new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long id) {
            t = times.get(pos);

            Intent intent = new Intent(EditarTimes.this, CadastroTimes.class);
            String strName = "Alterar";
            intent.putExtra("Alterar", strName);
            startActivity(intent);
        }

    };

    private AdapterView.OnItemLongClickListener excluirTime = new AdapterView.OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                       int pos, long arg3) {
            excluirTime(times.get(pos).getId());
            return true;
        }

    };

    private void exibirMensagem(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
    }

    public void telaCadastrar(View view) {
        Intent intent = new Intent(this, CadastroTimes.class);
        startActivity(intent);
    }

    public void botaoSair(View view) {
        Intent intent = new Intent(this, TelaInicial.class);
        startActivity(intent);
    }
}

Body:
1: Use intent.putExtra() to share a value from one activity another activity, as:

In ActivityOne.class :

startActivity(
    Intent(
        applicationContext,
        ActivityTwo::class.java
    ).putExtra(
        "key",
        "value"
    )
)

In ActivityTwo.class :

var value = ""
if (intent.hasExtra("key")
    value = intent.getStringExtra("key")

2: Modify button text programatically as:

btn_object.text = value

Hope this will help you


问:
AJAX not working on IE and EDGE
I made an application using ajax in some points, and I figured out that it wasn't working on IE and EDGE.
On the examples bellow, I'm trying to generate a PDF from one html page.
Here's my code

```<code>$(document).ready(function() {
  try {
  var url_string = window.location.href;
  var url = new URL(url_string);
  var token = url.searchParams.get("token");

  if (url_string.includes('/quiz/show_report')) {
    $.ajax({
      cache: false,
      type: "POST",
      url: '/chart.js?token=' + token
    });
  }
 } catch (e) {}
});
</code>```

on the document, I'm calling

```<code>$.ajax({
  cache: false,
  type: "POST",
  url: '/download_pdf?token=' + token,
  data: {
    natural_chart: $('#natural-chart').attr('data-image'),
    humanities_chart: $('#humanities-chart').attr('data-image'),
    language_codes_chart: $('#language-codes-chart').attr('data-image'),
    mathematics_technology_chart: $('#mathematics-technology-chart').attr('data-image')
  }
}).success(function(e) {
  window.location = '/download?token=' + token;
});
</code>```

What I tryed:
Using cache false
Forcing ie compatibility mode with that metatag:

<meta http-equiv="X-UA-Compatible" content="IE=7" />

and that:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" >

and all that other compatible meta tags. I Tryed also that ones

<meta content="no-cache" http-equiv="Cache-Control">
<meta content="no-cache" http-equiv="Pragma">

We updated the jquery version to the newer one (3.2.1),

Anyone has any idea what I might do to fix it?

Thank you in advance

答: Do you have any information about why it can not work at EDGE? As I know, EDGE did not support "searchParams" right now. </p>

Title: AJAX not working on IE and EDGE

Body:
I made an application using ajax in some points, and I figured out that it wasn't working on IE and EDGE.
On the examples bellow, I'm trying to generate a PDF from one html page.
Here's my code

$(document).ready(function() {
  try {
  var url_string = window.location.href;
  var url = new URL(url_string);
  var token = url.searchParams.get("token");

  if (url_string.includes('/quiz/show_report')) {
    $.ajax({
      cache: false,
      type: "POST",
      url: '/chart.js?token=' + token
    });
  }
 } catch (e) {}
});

on the document, I'm calling

$.ajax({
  cache: false,
  type: "POST",
  url: '/download_pdf?token=' + token,
  data: {
    natural_chart: $('#natural-chart').attr('data-image'),
    humanities_chart: $('#humanities-chart').attr('data-image'),
    language_codes_chart: $('#language-codes-chart').attr('data-image'),
    mathematics_technology_chart: $('#mathematics-technology-chart').attr('data-image')
  }
}).success(function(e) {
  window.location = '/download?token=' + token;
});

What I tryed:
Using cache false
Forcing ie compatibility mode with that metatag:

<meta http-equiv="X-UA-Compatible" content="IE=7" />

and that:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9" >

and all that other compatible meta tags. I Tryed also that ones

<meta content="no-cache" http-equiv="Cache-Control">
<meta content="no-cache" http-equiv="Pragma">

We updated the jquery version to the newer one (3.2.1),

Anyone has any idea what I might do to fix it?

Thank you in advance


问:
How do I watch a file for changes?
I have a log file being written by another process which I want to watch for changes. Each time a change occurs I'd like to read the new data in to do some processing on it.

What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the win32file.FindNextChangeNotification function but have no idea how to ask it to watch a specific file.

If anyone's done anything like this I'd be really grateful to hear how...

[Edit] I should have mentioned that I was after a solution that doesn't require polling.

[Edit] Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.

答:
It should not work on windows (maybe with cygwin ?), but for unix user, you should use the "fcntl" system call. Here is an example in Python. It's mostly the same code if you need to write it in C (same function names)</p>

```<code>import time
import fcntl
import os
import signal

FNAME = "/HOME/TOTO/FILETOWATCH"

def handler(signum, frame):
    print "File %s modified" % (FNAME,)

signal.signal(signal.SIGIO, handler)
fd = os.open(FNAME,  os.O_RDONLY)
fcntl.fcntl(fd, fcntl.F_SETSIG, 0)
fcntl.fcntl(fd, fcntl.F_NOTIFY,
            fcntl.DN_MODIFY | fcntl.DN_CREATE | fcntl.DN_MULTISHOT)

while True:
    time.sleep(10000)
</code>```

OwnerDisplayName: Jon Cage

Title: How do I watch a file for changes?

LastEditorDisplayName: Jon Cage

Body:
It should not work on windows (maybe with cygwin ?), but for unix user, you should use the "fcntl" system call. Here is an example in Python. It's mostly the same code if you need to write it in C (same function names)

import time
import fcntl
import os
import signal

FNAME = "/HOME/TOTO/FILETOWATCH"

def handler(signum, frame):
    print "File %s modified" % (FNAME,)

signal.signal(signal.SIGIO, handler)
fd = os.open(FNAME,  os.O_RDONLY)
fcntl.fcntl(fd, fcntl.F_SETSIG, 0)
fcntl.fcntl(fd, fcntl.F_NOTIFY,
            fcntl.DN_MODIFY | fcntl.DN_CREATE | fcntl.DN_MULTISHOT)

while True:
    time.sleep(10000)

OwnerDisplayName: Maxime Biais


问:
thymeleaf - is there a way to pass a String that can't be edited or removed from an input element?
I have a requirement to build a String id using another as part of it.

I know I could pass to the page a model.addAttribute("parentId", parentId); and display as

```<code><div>
    <span th:text="${parentId}"/><input id="id" type="text" th:field="${id}" />
</div>
</code>```

But I was hoping to get it all inside the <input /> element as a placeholder and making the $[parentId} text impossible to be removed and edited.

Is there a way to do it using only Thymeleaf and NO JavaScript?

UPDATE

As requested, an example for this would be something like this:

parentId could be any String, for instance, "abc".

the parentId value would be passed to the screen and the input would have a fixed value of "abc:" that would allow changes and any value could be inserted in the input field, so the resulting id would be something like abc:xpto.

答:
I don't think it's possible to do this on the view side.
What you could do is managing the value of parentId and id on the controller side.

So, while maintaining your view with a span to show the parentId and the input for the id, and assuming your input is inside a form, in the controller you might have something like this:

```<code>@RequestMapping(value = "/submitId", method = RequestMethod.POST)
public void manageId(String id) {
    id = parentId + id;
    //work with the complete id
}
</code>```

Where parentId is the same variable you previously sent to the Model.

After that you can do whatever you need to do with the new id value, from saving the value to DB to showing it in another view.

Body:
I have a requirement to build a String id using another as part of it.

I know I could pass to the page a model.addAttribute("parentId", parentId); and display as

    <input id="id" type="text" th:field="${id}" />

But I was hoping to get it all inside the <input /> element as a placeholder and making the $[parentId} text impossible to be removed and edited.

Is there a way to do it using only Thymeleaf and NO JavaScript?

UPDATE

As requested, an example for this would be something like this:

parentId could be any String, for instance, "abc".

the parentId value would be passed to the screen and the input would have a fixed value of "abc:" that would allow changes and any value could be inserted in the input field, so the resulting id would be something like abc:xpto.

Body:
I don't think it's possible to do this on the view side.
What you could do is managing the value of parentId and id on the controller side.

So, while maintaining your view with a span to show the parentId and the input for the id, and assuming your input is inside a form, in the controller you might have something like this:

@RequestMapping(value = "/submitId", method = RequestMethod.POST)
public void manageId(String id) {
    id = parentId + id;
    //work with the complete id
}

Where parentId is the same variable you previously sent to the Model.

After that you can do whatever you need to do with the new id value, from saving the value to DB to showing it in another view.


问:
iOS - How can I get the IndexPath of the last item in a tableview?
I would like to automatically scroll to the end of a table view.

```<code>[tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
</code>```

Given that I know how many item are in the tableview using:

```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
</code>```

How can I get the IndexPath * to the last item in this tableView? This is needed so that I can provide it as an argument to scrollToRowAtIndexPath:atScrollPosition:animated

Thanks!

答:
Try this code:</p>

```<code>//   get number of section
let indexOfLastSection = self.yourTableView.numberOfSections - 1

// Then get the number of rows in the last section

if indexOfLastSection >= 0{
    let indexOfLastRow = self.yourTableView.numberOfRows(inSection: indexOfLastSection) - 1
    if indexOfLastRow >= 0{
        let pathToLastRow = IndexPath.init(row: indexOfLastRow, section: indexOfLastSection)
    }
}
</code>```

Body:
I would like to automatically scroll to the end of a table view.

[tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];

Given that I know how many item are in the tableview using:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

How can I get the IndexPath * to the last item in this tableView? This is needed so that I can provide it as an argument to scrollToRowAtIndexPath:atScrollPosition:animated

Thanks!

Body:
Try this code:

//   get number of section
let indexOfLastSection = self.yourTableView.numberOfSections - 1

// Then get the number of rows in the last section

if indexOfLastSection >= 0{
    let indexOfLastRow = self.yourTableView.numberOfRows(inSection: indexOfLastSection) - 1
    if indexOfLastRow >= 0{
        let pathToLastRow = IndexPath.init(row: indexOfLastRow, section: indexOfLastSection)
    }
}