问:
Elegantly Toggling Many Functions
Let's say I have a handful of functions that do things:

```<code>function doStuff()  { console.log('doing stuff'); }
function doThings() { console.log('doing things'); }
function doIt()     { console.log('doing it'); }
function doThis()   { console.log('doing this'); }
function doThat()   { console.log('doing that'); }
</code>```

And then just as many that disable their behaviors:

```<code>function stopStuff()  { console.log('stopping stuff'); }
function stopThings() { console.log('stopping things'); }
function stopIt()     { console.log('stopping it'); }
function stopThis()   { console.log('stopping this'); }
function stopThat()   { console.log('stopping that'); }
</code>```

Then I put all the 'do' functions in an object so I can dynamically access them by setting what:

```<code>var what = 'things';

var doing = {
    stuff:  function() { doStuff(); },
    things: function() { doThings(); },
    it:     function() { doIt(); },
    this:   function() { doThis(); },
    that:   function() { doThat(); }
};

doing[what](); //console logs 'doing things'
</code>```

Is there a way to go about enabling one do function while iterating through all the non-matching stop functions?

For example, if I do var what = 'this'; doing[what]();, I want it to not only doThis(); but also stopStuff(); stopThings(); stopIt(); stopThat();

I'm having trouble coming up with an elegant method that doesn't involve lengthy if statements or case/switch.

答:
You can use a simple for loop as in the following code

If all your do/stop functions are global - this works

```<code>for(var idx in doing) {
    if(idx == what) {
        doing[idx]();
    }
    else {
       var fn = idx.charAt(0).toUpperCase() + idx.slice(1);
       var fname = "stop"+fn;
       window[fname]();
    }
}
</code>```

Title: Elegantly Toggling Many Functions

Body:
Let's say I have a handful of functions that do things:

function doStuff()  { console.log('doing stuff'); }
function doThings() { console.log('doing things'); }
function doIt()     { console.log('doing it'); }
function doThis()   { console.log('doing this'); }
function doThat()   { console.log('doing that'); }

And then just as many that disable their behaviors:

function stopStuff()  { console.log('stopping stuff'); }
function stopThings() { console.log('stopping things'); }
function stopIt()     { console.log('stopping it'); }
function stopThis()   { console.log('stopping this'); }
function stopThat()   { console.log('stopping that'); }

Then I put all the 'do' functions in an object so I can dynamically access them by setting what:

var what = 'things';

var doing = {
    stuff:  function() { doStuff(); },
    things: function() { doThings(); },
    it:     function() { doIt(); },
    this:   function() { doThis(); },
    that:   function() { doThat(); }
};

doing[what](); //console logs 'doing things'

Is there a way to go about enabling one do function while iterating through all the non-matching stop functions?

For example, if I do var what = 'this'; doing[what]();, I want it to not only doThis(); but also stopStuff(); stopThings(); stopIt(); stopThat();

I'm having trouble coming up with an elegant method that doesn't involve lengthy if statements or case/switch.

Body:
You can use a simple for loop as in the following code

If all your do/stop functions are global - this works

for(var idx in doing) {
    if(idx == what) {
        doing[idx]();
    }
    else {
       var fn = idx.charAt(0).toUpperCase() + idx.slice(1);
       var fname = "stop"+fn;
       window[fname]();
    }
}


来源: stackexchange

问:
RecyclerView: How to clear the recycled views from RecyclerView.RecycledViewPool
Here is the situation: RecyclerView item views have a complex layout.

At some point I modify the layout for RecyclerView items this way:

Ex. Index of modified View inside itemView = 3;

```<code>for (int i=0; i < mRecyclerView.getChildCount(); i++) {

    ViewGroup itemView = ((ViewGroup) mRecyclerView.getChildAt(i));

    itemView.getChildAt(3).getLayoutParams().width = newWidth;
    itemView.getChildAt(3).requestLayout();
}
</code>```

It all works as expected but when I scroll  the RecyclerView there are 2-3 recycled item views that will appear with the old width. Now I'm trying to find how to remove these views from RecycledViewPool or even a better solution: to modify their width too but I can't find a way to get those views.

I tried mRecyclerView.getRecycledViewPool().clear() but the old views keeped reappearing.

答:
```<code>adapter.notifyItemRangeRemoved(0,adapter.getItemCount());
</code>```

Just do this before for loop.

ContentLicense: CC BY-SA 3.0

Body:
Here is the situation: RecyclerView item views have a complex layout.

At some point I modify the layout for RecyclerView items this way:

Ex. Index of modified View inside itemView = 3;

for (int i=0; i < mRecyclerView.getChildCount(); i++) {

    ViewGroup itemView = ((ViewGroup) mRecyclerView.getChildAt(i));

    itemView.getChildAt(3).getLayoutParams().width = newWidth;
    itemView.getChildAt(3).requestLayout();
}

It all works as expected but when I scroll  the RecyclerView there are 2-3 recycled item views that will appear with the old width. Now I'm trying to find how to remove these views from RecycledViewPool or even a better solution: to modify their width too but I can't find a way to get those views.

I tried mRecyclerView.getRecycledViewPool().clear() but the old views keeped reappearing.

Body:
adapter.notifyItemRangeRemoved(0,adapter.getItemCount());

Just do this before for loop.


问:
Geocoding API's response was not valid JSON
I am using Geocoder gem, its working fine. Now I m tried to upgrade with google_premier getting below error

```<code>1.9.2p320 :001 > Geocoder.search("Hyderabad")
Geocoding API's response was not valid JSON.
 => []
</code>```

I am added new file in config/initializers/geocoder.rb, Here is my config setup

```<code>Geocoder::Configuration.lookup = :google_premier
Geocoder::Configuration.api_key = "xxx-key"
</code>```

答: I was also facing the same issue. And my solution may be silly, but it worked for me. My solution was to reinstall the gem.</p>

Body:
I am using Geocoder gem, its working fine. Now I m tried to upgrade with google_premier getting below error

1.9.2p320 :001 > Geocoder.search("Hyderabad")
Geocoding API's response was not valid JSON.
 => []

I am added new file in config/initializers/geocoder.rb, Here is my config setup

Geocoder::Configuration.lookup = :google_premier
Geocoder::Configuration.api_key = "xxx-key"

ContentLicense: CC BY-SA 4.0


问:
Generalizing Concurrent Map Function with Empty Interface In GOlang
So I'm super new to Golang and seeing as the big buzz around the language seems to be concurrency I figured a good way to get my toes wet would be to write a generalized map function. In psudo code:

```<code>map(F funtion,A array){
    return([F(k) for k in A])
}
</code>```

And obviously I want the calculations for each F(k) occur concurrently. For organization I have a main file with my implementation and a supporting file Mr with my required definitions.

```<code>.
├── main.go
└── Mr
    └── Mr.go
</code>```

Main is a simple test implementation which should convert an array of strings to an array of ints where each member of the result is the length of the corresponding string in the input array.

```<code>package main

import(
    "fmt"
    "./Mr"
)

func exfunc(i int, c chan int){
    c<-i
}

func main(){
    data := make(map[int]string)
    data[1]="these"
    data[2]="are"
    data[3]="some"
    data[4]="words"
    data[5]="and a few more..."
    f := func(w string)int{
        return(len(w))
    }
    testMr := Mr.Map(f,data) // this is line 22 (matters later)
    fmt.Println(testMr)
}
</code>```

Which works great with my Mr.Map function given that I specify all the types explicitly.

```<code>package Mr

type result struct{
    key,value int
}

func wrapper(f func(string) int,k int,v string, c chan result){
    c <- result{k,f(v)}
}

func Map(f func(string) int,m map[int]string) map[int]int{
    c := make(chan result)
    ret := make(map[int]int)
    n := 0
    for k := range m{
        go wrapper(f,k,m[k],c)
        n++
    }
    for ;n>0; {
        r := <-c
        ret[r.key]=r.value
        n--
    }
    return(ret)
}
</code>```

However I was hoping that I would be able to generalize this mapping with the empty interface.

```<code>package Mr

type T interface{}

type result struct{
    key,value T
}

func wrapper(f func(T) T,k T,v T, c chan result){
    c <- result{k,f(v)}
}

func Map(f func(T) T,m map[T]T) map[T]T{
    c := make(chan result)
    ret := make(map[T]T)
    n := 0
    for k := range m{
        go wrapper(f,k,m[k],c)
        n++
    }
    for ;n>0; {
        r := <-c
        ret[r.key]=r.value
        n--
    }
    return(ret)
}
</code>```

Unfortunately when I run main with this generalize Mr.Map I get the following error.

```<code># command-line-arguments
./main.go:22: cannot use f (type func(string) int) as type func(Mr.T) Mr.T in argument to Mr.Map
./main.go:22: cannot use data (type map[int]string) as type map[Mr.T]Mr.T in argument to Mr.Map
</code>```

So yeah, obviously I understand what the errors are telling me but it seems wild that I would have to re-write my Map function for each possible combination of key and value types.

Is there a work around here, or is this just the nature of the beast?

答:
The philosophy of Go is not compatible with generalized functions such as is the style with popular dynamic languages. To properly inform the compiler of what you are trying to do, you should express your needed map through an interface or simply by writing it for each type you are using it with.

Mapping requires allocating an array, iterating through a collection, and adding to the array some data element for each element in the collection. If you need a map for a slice of structs, as is common in the application layer, you can express this tersely in Go:

https://play.golang.org/p/pk3Tl_BdlD

Dynamic languages build a "type tree" of "generic" types that allow for terse programming, such as functions like map being called by one symbol over any possible type. This provides a ton of developer productivity because code can be written loosely to allow easy experimentation.

Go is designed for writing semi-permanent software. It performs well because it requires more information to be supplied to the compiler. Map is only about three lines of code, so the cost/benefit of developer productivity v. efficiency lands on the performance side for Go. Functions like map, reduce and filter should be written explicitly as needed.

To evaluate the language, I would encourage you to try to solve a problem with a Go program and see where that takes you.

Body:
So I'm super new to Golang and seeing as the big buzz around the language seems to be concurrency I figured a good way to get my toes wet would be to write a generalized map function. In psudo code:

map(F funtion,A array){
    return([F(k) for k in A])
}

And obviously I want the calculations for each F(k) occur concurrently. For organization I have a main file with my implementation and a supporting file Mr with my required definitions.

.
├── main.go
└── Mr
    └── Mr.go

Main is a simple test implementation which should convert an array of strings to an array of ints where each member of the result is the length of the corresponding string in the input array.

package main

import(
    "fmt"
    "./Mr"
)

func exfunc(i int, c chan int){
    c<-i
}

func main(){
    data := make(map[int]string)
    data[1]="these"
    data[2]="are"
    data[3]="some"
    data[4]="words"
    data[5]="and a few more..."
    f := func(w string)int{
        return(len(w))
    }
    testMr := Mr.Map(f,data) // this is line 22 (matters later)
    fmt.Println(testMr)
}

Which works great with my Mr.Map function given that I specify all the types explicitly.

package Mr

type result struct{
    key,value int
}

func wrapper(f func(string) int,k int,v string, c chan result){
    c <- result{k,f(v)}
}

func Map(f func(string) int,m map[int]string) map[int]int{
    c := make(chan result)
    ret := make(map[int]int)
    n := 0
    for k := range m{
        go wrapper(f,k,m[k],c)
        n++
    }
    for ;n>0; {
        r := <-c
        ret[r.key]=r.value
        n--
    }
    return(ret)
}

However I was hoping that I would be able to generalize this mapping with the empty interface.

package Mr

type T interface{}

type result struct{
    key,value T
}

func wrapper(f func(T) T,k T,v T, c chan result){
    c <- result{k,f(v)}
}

func Map(f func(T) T,m map[T]T) map[T]T{
    c := make(chan result)
    ret := make(map[T]T)
    n := 0
    for k := range m{
        go wrapper(f,k,m[k],c)
        n++
    }
    for ;n>0; {
        r := <-c
        ret[r.key]=r.value
        n--
    }
    return(ret)
}

Unfortunately when I run main with this generalize Mr.Map I get the following error.

# command-line-arguments
./main.go:22: cannot use f (type func(string) int) as type func(Mr.T) Mr.T in argument to Mr.Map
./main.go:22: cannot use data (type map[int]string) as type map[Mr.T]Mr.T in argument to Mr.Map

So yeah, obviously I understand what the errors are telling me but it seems wild that I would have to re-write my Map function for each possible combination of key and value types.

Is there a work around here, or is this just the nature of the beast?


问:
how to resize an image inside a button
I am trying to create a button in which text description comes at bottom and an image at the top.I saw buttons can do the trick by android:drawableTop attribute but I am unable to resize the image

Methods like adjustViewBounds, android:scaleType="fitCenter", fitXY are not working.

Here is my xml code for the button

```<code><Button
            android:text="Start Running"
            android:layout_height="match_parent"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/run"
            android:onClick = "RUN"
            android:scaleType="fitCenter"
            android:drawableTop="@drawable/runner"
            android:layout_marginBottom="3sp"
            android:layout_marginLeft="2sp"
            android:layout_marginRight="3sp"
            android:layout_marginTop="0sp"
            />
</code>```

Please suggest something?

答: Create horizontal LinearLayout with 2 views there - View with your image set as background and TextView with the corresponding text. After that set OnClickListener for this LinearLayout and process it like a regular button.</p>

Title: how to resize an image inside a button

Body:
I am trying to create a button in which text description comes at bottom and an image at the top.I saw buttons can do the trick by android:drawableTop attribute but I am unable to resize the image

Methods like adjustViewBounds, android:scaleType="fitCenter", fitXY are not working.

Here is my xml code for the button

<Button
            android:text="Start Running"
            android:layout_height="match_parent"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/run"
            android:onClick = "RUN"
            android:scaleType="fitCenter"
            android:drawableTop="@drawable/runner"
            android:layout_marginBottom="3sp"
            android:layout_marginLeft="2sp"
            android:layout_marginRight="3sp"
            android:layout_marginTop="0sp"
            />

Please suggest something?


问:
How to find most popular elements in multiple sets
I have a map structured as follows

Map<String, Set<String> myMapOfSets = new HashSet<>():

This map is of size 400. And each of these 400 sets can be of size anywhere between 100 to 10000 elements. Many elements in these sets are repeating. I am looking to find say top 10 elements which are most popular in these 400 sets. How to implement that? Thanks for any help.

答:
Using Java 8 streams:

```<code>Map<String, Set<String>> myMapOfSets = new HashMap<>();
myMapOfSets.put("K1", new HashSet<>(Arrays.asList("A", "B", "C",      "E"     )));
myMapOfSets.put("K2", new HashSet<>(Arrays.asList(     "B", "C", "D",      "F")));
myMapOfSets.put("K3", new HashSet<>(Arrays.asList("A",      "C",      "E", "F")));
myMapOfSets.put("K4", new HashSet<>(Arrays.asList(     "B", "C", "D"          )));
myMapOfSets.put("K5", new HashSet<>(Arrays.asList("A",      "C", "D"          )));
myMapOfSets.put("K6", new HashSet<>(Arrays.asList(     "B", "C", "D", "E", "F")));

List<Entry<String, Long>> result =           // change to List<String> if you only want values
        myMapOfSets.values()
                   .stream()
                   .flatMap(Set::stream)
                   .collect(Collectors.groupingBy(s -> s, Collectors.counting()))
                   .entrySet()
                   .stream()
                   .sorted((e1, e2) -> Long.compare(e2.getValue(), e1.getValue())) // descending
                   .limit(3)                 // change to 10 for your code
                // .map(Map.Entry::getKey)   // uncomment if you only want values
                   .collect(Collectors.toList());
result.forEach(System.out::println);
</code>```

Output

C=6
B=4
D=4
```

Body:
Using Java 8 streams:

Map<String, Set<String>> myMapOfSets = new HashMap<>();
myMapOfSets.put("K1", new HashSet<>(Arrays.asList("A", "B", "C",      "E"     )));
myMapOfSets.put("K2", new HashSet<>(Arrays.asList(     "B", "C", "D",      "F")));
myMapOfSets.put("K3", new HashSet<>(Arrays.asList("A",      "C",      "E", "F")));
myMapOfSets.put("K4", new HashSet<>(Arrays.asList(     "B", "C", "D"          )));
myMapOfSets.put("K5", new HashSet<>(Arrays.asList("A",      "C", "D"          )));
myMapOfSets.put("K6", new HashSet<>(Arrays.asList(     "B", "C", "D", "E", "F")));

List<Entry<String, Long>> result =           // change to List<String> if you only want values
        myMapOfSets.values()
                   .stream()
                   .flatMap(Set::stream)
                   .collect(Collectors.groupingBy(s -> s, Collectors.counting()))
                   .entrySet()
                   .stream()
                   .sorted((e1, e2) -> Long.compare(e2.getValue(), e1.getValue())) // descending
                   .limit(3)                 // change to 10 for your code
                // .map(Map.Entry::getKey)   // uncomment if you only want values
                   .collect(Collectors.toList());
result.forEach(System.out::println);

Output

C=6
B=4
D=4


问:
Wrong order of restored items in RecyclerView
I'm using RecyclerView as a base for my data list and in my adapter the elements are added to the list. The list will always have maximum 10 elements in a specified order. Here is the add method of my adapter:

```<code>void addResult(Result result) {
    int resultPosition = result.getType().getPos();
    boolean inserted = false;

    for (int i = 0; i < results.size(); i++) {
        Result currentField = results.get(i);
        if (currentField.getType().getPos() > resultPosition) {
            results.add(i, result);
            inserted = true;
            notifyItemInserted(i);
            break;
        }
    }

    if (!inserted) {
        results.add(result);
        notifyItemInserted(results.size());
    }
}
</code>```

The list is stored in my fragment to have the data also after a configuration change. Therefore I just use the following method in the adapter:

```<code>    public void setResults(List<Result> results) {
    this.results = results;
}
</code>```

But after a device rotation the items are displayed in the wrong order. Did I forgot something?

EDIT:

This is the rest of my adapter:

```<code>    @Override
public ResultHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);
    return new ResultHolder(view);
}

@Override
public void onBindViewHolder(ResultHolder resultHolder, int position) {
    Result result = results.get(position);
    resultHolder.bindResultData(result);
}

@Override
public int getItemCount() {
    return results.size();
}
</code>```

答:
When you add an item into the middle of the list, the index of all items which is behind the item that you've just added will be updated.

Try this:

```<code>for (int i = 0; i < results.size(); i++) {
    Result currentField = results.get(i);
    if (currentField.getType().getPos() > resultPosition) {
        results.add(i, result);
        inserted = true;
        notifyItemInserted(i);
        notifyItemRangeInserted(i, results.size - i);
        break;
    }
}
</code>```

This could get your stuff done. But using notify in a loop is not a good approach. I suggest doing like this:

```<code>void addResult(Result result) {
    int resultPosition = result.getType().getPos();
    boolean inserted = false;

    for (int i = 0; i < results.size(); i++) {
        Result currentField = results.get(i);
        if (currentField.getType().getPos() > resultPosition) {
            results.add(i, result);
            inserted = true;
            break;
        }
    }

    if (inserted) {
        // I don't know your requirement, so I will use this function
        notifyDataSetChanged();
    } else {
        results.add(result);
        notifyItemInserted(results.size());
    }
}
</code>```

Body:
I'm using RecyclerView as a base for my data list and in my adapter the elements are added to the list. The list will always have maximum 10 elements in a specified order. Here is the add method of my adapter:

void addResult(Result result) {
    int resultPosition = result.getType().getPos();
    boolean inserted = false;

    for (int i = 0; i < results.size(); i++) {
        Result currentField = results.get(i);
        if (currentField.getType().getPos() > resultPosition) {
            results.add(i, result);
            inserted = true;
            notifyItemInserted(i);
            break;
        }
    }

    if (!inserted) {
        results.add(result);
        notifyItemInserted(results.size());
    }
}

The list is stored in my fragment to have the data also after a configuration change. Therefore I just use the following method in the adapter:

    public void setResults(List<Result> results) {
    this.results = results;
}

But after a device rotation the items are displayed in the wrong order. Did I forgot something?

EDIT:

This is the rest of my adapter:

    @Override
public ResultHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);
    return new ResultHolder(view);
}

@Override
public void onBindViewHolder(ResultHolder resultHolder, int position) {
    Result result = results.get(position);
    resultHolder.bindResultData(result);
}

@Override
public int getItemCount() {
    return results.size();
}

Body:
When you add an item into the middle of the list, the index of all items which is behind the item that you've just added will be updated.

Try this:

for (int i = 0; i < results.size(); i++) {
    Result currentField = results.get(i);
    if (currentField.getType().getPos() > resultPosition) {
        results.add(i, result);
        inserted = true;
        notifyItemInserted(i);
        notifyItemRangeInserted(i, results.size - i);
        break;
    }
}

This could get your stuff done. But using notify in a loop is not a good approach. I suggest doing like this:

void addResult(Result result) {
    int resultPosition = result.getType().getPos();
    boolean inserted = false;

    for (int i = 0; i < results.size(); i++) {
        Result currentField = results.get(i);
        if (currentField.getType().getPos() > resultPosition) {
            results.add(i, result);
            inserted = true;
            break;
        }
    }

    if (inserted) {
        // I don't know your requirement, so I will use this function
        notifyDataSetChanged();
    } else {
        results.add(result);
        notifyItemInserted(results.size());
    }
}


问:
How can you make a custom keyboard in Android?
I want to make a custom keyboard. I don't know how to do it using XML and Java. The following picture is a model of the keyboard I want to make. It only needs numbers.

答:
System keyboard

This answer tells how to make a custom system keyboard that can be used in any app that a user has installed on their phone. If you want to make a keyboard that will only be used within your own app, then see my other answer.

The example below will look like this. You can modify it for any keyboard layout.

The following steps show how to create a working custom system keyboard. As much as possible I tried to remove any unnecessary code. If there are other features that you need, I provided links to more help at the end.

1. Start a new Android project

I named my project "Custom Keyboard". Call it whatever you want. There is nothing else special here. I will just leave the MainActivity and "Hello World!" layout as it is.

2. Add the layout files

Add the following two files to your app's res/layout folder:

keyboard_view.xml

key_preview.xml

keyboard_view.xml

This view is like a container that will hold our keyboard. In this example there is only one keyboard, but you could add other keyboards and swap them in and out of this KeyboardView.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.inputmethodservice.KeyboardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:keyPreviewLayout="@layout/key_preview"
    android:layout_alignParentBottom="true">

</android.inputmethodservice.KeyboardView>
</code>```

key_preview.xml

The key preview is a layout that pops up when you press a keyboard key. It just shows what key you are pressing (in case your big, fat fingers are covering it). This isn't a multiple choice popup. For that you should check out the Candidates view.

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@android:color/white"
    android:textColor="@android:color/black"
    android:textSize="30sp">
</TextView>
</code>```

3. Add supporting xml files

Create an xml folder in your res folder. (Right click res and choose New > Directory.)

Then add the following two xml files to it. (Right click the xml folder and choose New > XML resource file.)

number_pad.xml

method.xml

number_pad.xml

This is where it starts to get more interesting. This Keyboard defines the layout of the keys.

```<code><?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="20%p"
    android:horizontalGap="5dp"
    android:verticalGap="5dp"
    android:keyHeight="60dp">

    <Row>
        <Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left"/>
        <Key android:codes="50" android:keyLabel="2"/>
        <Key android:codes="51" android:keyLabel="3"/>
        <Key android:codes="52" android:keyLabel="4"/>
        <Key android:codes="53" android:keyLabel="5" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="54" android:keyLabel="6" android:keyEdgeFlags="left"/>
        <Key android:codes="55" android:keyLabel="7"/>
        <Key android:codes="56" android:keyLabel="8"/>
        <Key android:codes="57" android:keyLabel="9"/>
        <Key android:codes="48" android:keyLabel="0" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="-5"
             android:keyLabel="DELETE"
             android:keyWidth="40%p"
             android:keyEdgeFlags="left"
             android:isRepeatable="true"/>
        <Key android:codes="10"
             android:keyLabel="ENTER"
             android:keyWidth="60%p"
             android:keyEdgeFlags="right"/>
    </Row>

</Keyboard>
</code>```

Here are some things to note:

keyWidth: This is the default width of each key. The 20%p means that each key should take up 20% of the width of the parent. It can be overridden by individual keys, though, as you can see happened with the Delete and Enter keys in the third row.

keyHeight: It is hard coded here, but you could use something like @dimen/key_height to set it dynamically for different screen sizes.

Gap: The horizontal and vertical gap tells how much space to leave between keys. Even if you set it to 0px there is still a small gap.

codes: This can be a Unicode or custom code value that determines what happens or what is input when the key is pressed. See keyOutputText if you want to input a longer Unicode string.

keyLabel: This is the text that is displayed on the key.

keyEdgeFlags: This indicates which edge the key should be aligned to.

isRepeatable: If you hold down the key it will keep repeating the input.

method.xml

This file tells the system the input method subtypes that are available. I am just including a minimal version here.

```<code><?xml version="1.0" encoding="utf-8"?>
<input-method
    xmlns:android="http://schemas.android.com/apk/res/android">

    <subtype
        android:imeSubtypeMode="keyboard"/>

</input-method>
</code>```

4. Add the Java code to handle key input

Create a new Java file. Let's call it MyInputMethodService. This file ties everything together. It handles input received from the keyboard and sends it on to whatever view is receiving it (an EditText, for example).

```<code>public class MyInputMethodService extends InputMethodService implements KeyboardView.OnKeyboardActionListener {

    @Override
    public View onCreateInputView() {
        // get the KeyboardView and add our Keyboard layout to it
        KeyboardView keyboardView = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard_view, null);
        Keyboard keyboard = new Keyboard(this, R.xml.number_pad);
        keyboardView.setKeyboard(keyboard);
        keyboardView.setOnKeyboardActionListener(this);
        return keyboardView;
    }

    @Override
    public void onKey(int primaryCode, int[] keyCodes) {

        InputConnection ic = getCurrentInputConnection();
        if (ic == null) return;
        switch (primaryCode) {
            case Keyboard.KEYCODE_DELETE:
                CharSequence selectedText = ic.getSelectedText(0);
                if (TextUtils.isEmpty(selectedText)) {
                    // no selection, so delete previous character
                    ic.deleteSurroundingText(1, 0);
                } else {
                    // delete the selection
                    ic.commitText("", 1);
                }
                break;
            default:
                char code = (char) primaryCode;
                ic.commitText(String.valueOf(code), 1);
        }
    }

    @Override
    public void onPress(int primaryCode) { }

    @Override
    public void onRelease(int primaryCode) { }

    @Override
    public void onText(CharSequence text) { }

    @Override
    public void swipeLeft() { }

    @Override
    public void swipeRight() { }

    @Override
    public void swipeDown() { }

    @Override
    public void swipeUp() { }
}
</code>```

Notes:

The OnKeyboardActionListener listens for keyboard input. It is also requires all those empty methods in this example.

The InputConnection is what is used to send input to another view like an EditText.

5. Update the manifest

I put this last rather than first because it refers to the files we already added above. To register your custom keyboard as a system keyboard, you need to add a service section to your AndroidManifest.xml file. Put it in the application section after activity.

```<code><manifest ...>
    <application ... >
        <activity ... >
            ...
        </activity>

        <service
            android:name=".MyInputMethodService"
            android:label="Keyboard Display Name"
            android:permission="android.permission.BIND_INPUT_METHOD">
            <intent-filter>
                <action android:name="android.view.InputMethod"/>
            </intent-filter>
            <meta-data
                android:name="android.view.im"
                android:resource="@xml/method"/>
        </service>

    </application>
</manifest>
</code>```

That's it! You should be able to run your app now. However, you won't see much until you enable your keyboard in the settings.

6. Enable the keyboard in Settings

Every user who wants to use your keyboard will have to enable it in the Android settings. For detailed instructions on how to do that, see the following link:

How to set the default keyboard on your Android phone

Here is a summary:

Go to Android Settings > Languages and input > Current keyboard > Choose keyboards.

You should see your Custom Keyboard on the list. Enable it.

Go back and choose Current keyboard again. You should see your Custom Keyboard on the list. Choose it.

Now you should be able to use your keyboard anywhere that you can type in Android.

Further study

The keyboard above is usable, but to create a keyboard that other people will want to use you will probably have to add more functionality. Study the links below to learn how.

Creating an Input Method (Android documentation)

SoftKeyboard (source code from Android for a demo custom keyboard)

Building a Custom Android Keyboard (tutorial) (source code)

Create a Custom Keyboard on Android (tutsplus tutorial)

How to create custom keyboard for android (YouTube video: It is soundless but following along is how I first learned how to do this.)

Going On

Don't like how the standard KeyboardView looks and behaves? I certainly don't. It looks like it hasn't been updated since Android 2.0. How about all those custom keyboards in the Play Store? They don't look anything like the ugly keyboard above.

The good news is that you can completely customize your own keyboard's look and behavior. You will need to do the following things:

Create your own custom keyboard view that subclasses ViewGroup. You could fill it with Buttons or even make your own custom key views that subclass View. If you use popup views, then note this.

Add a custom event listener interface in your keyboard. Call its methods for things like onKeyClicked(String text) or onBackspace().

You don't need to add the keyboard_view.xml, key_preview.xml, or number_pad.xml described in the directions above since these are all for the standard KeyboardView. You will handle all these UI aspects in your custom view.

In your MyInputMethodService class, implement the custom keyboard listener that you defined in your keyboard class. This is in place of KeyboardView.OnKeyboardActionListener, which is no longer needed.

In your MyInputMethodService class's onCreateInputView() method, create and return an instance of your custom keyboard. Don't forget to set the keyboard's custom listener to this.

Body:
System keyboard

This answer tells how to make a custom system keyboard that can be used in any app that a user has installed on their phone. If you want to make a keyboard that will only be used within your own app, then see my other answer.

The example below will look like this. You can modify it for any keyboard layout.

The following steps show how to create a working custom system keyboard. As much as possible I tried to remove any unnecessary code. If there are other features that you need, I provided links to more help at the end.

1. Start a new Android project

I named my project "Custom Keyboard". Call it whatever you want. There is nothing else special here. I will just leave the MainActivity and "Hello World!" layout as it is.

2. Add the layout files

Add the following two files to your app's res/layout folder:

keyboard_view.xml

key_preview.xml

keyboard_view.xml

This view is like a container that will hold our keyboard. In this example there is only one keyboard, but you could add other keyboards and swap them in and out of this KeyboardView.

<?xml version="1.0" encoding="utf-8"?>
<android.inputmethodservice.KeyboardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:keyPreviewLayout="@layout/key_preview"
    android:layout_alignParentBottom="true">

</android.inputmethodservice.KeyboardView>

key_preview.xml

The key preview is a layout that pops up when you press a keyboard key. It just shows what key you are pressing (in case your big, fat fingers are covering it). This isn't a multiple choice popup. For that you should check out the Candidates view.

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@android:color/white"
    android:textColor="@android:color/black"
    android:textSize="30sp">
</TextView>

3. Add supporting xml files

Create an xml folder in your res folder. (Right click res and choose New > Directory.)

Then add the following two xml files to it. (Right click the xml folder and choose New > XML resource file.)

number_pad.xml

method.xml

number_pad.xml

This is where it starts to get more interesting. This Keyboard defines the layout of the keys.

<?xml version="1.0" encoding="utf-8"?>
<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyWidth="20%p"
    android:horizontalGap="5dp"
    android:verticalGap="5dp"
    android:keyHeight="60dp">

    <Row>
        <Key android:codes="49" android:keyLabel="1" android:keyEdgeFlags="left"/>
        <Key android:codes="50" android:keyLabel="2"/>
        <Key android:codes="51" android:keyLabel="3"/>
        <Key android:codes="52" android:keyLabel="4"/>
        <Key android:codes="53" android:keyLabel="5" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="54" android:keyLabel="6" android:keyEdgeFlags="left"/>
        <Key android:codes="55" android:keyLabel="7"/>
        <Key android:codes="56" android:keyLabel="8"/>
        <Key android:codes="57" android:keyLabel="9"/>
        <Key android:codes="48" android:keyLabel="0" android:keyEdgeFlags="right"/>
    </Row>

    <Row>
        <Key android:codes="-5"
             android:keyLabel="DELETE"
             android:keyWidth="40%p"
             android:keyEdgeFlags="left"
             android:isRepeatable="true"/>
        <Key android:codes="10"
             android:keyLabel="ENTER"
             android:keyWidth="60%p"
             android:keyEdgeFlags="right"/>
    </Row>

</Keyboard>

Here are some things to note:

keyWidth: This is the default width of each key. The 20%p means that each key should take up 20% of the width of the parent. It can be overridden by individual keys, though, as you can see happened with the Delete and Enter keys in the third row.

keyHeight: It is hard coded here, but you could use something like @dimen/key_height to set it dynamically for different screen sizes.

Gap: The horizontal and vertical gap tells how much space to leave between keys. Even if you set it to 0px there is still a small gap.

codes: This can be a Unicode or custom code value that determines what happens or what is input when the key is pressed. See keyOutputText if you want to input a longer Unicode string.

keyLabel: This is the text that is displayed on the key.

keyEdgeFlags: This indicates which edge the key should be aligned to.

isRepeatable: If you hold down the key it will keep repeating the input.

method.xml

This file tells the system the input method subtypes that are available. I am just including a minimal version here.

<?xml version="1.0" encoding="utf-8"?>
<input-method
    xmlns:android="http://schemas.android.com/apk/res/android">

    <subtype
        android:imeSubtypeMode="keyboard"/>

</input-method>

4. Add the Java code to handle key input

Create a new Java file. Let's call it MyInputMethodService. This file ties everything together. It handles input received from the keyboard and sends it on to whatever view is receiving it (an EditText, for example).

public class MyInputMethodService extends InputMethodService implements KeyboardView.OnKeyboardActionListener {

    @Override
    public View onCreateInputView() {
        // get the KeyboardView and add our Keyboard layout to it
        KeyboardView keyboardView = (KeyboardView) getLayoutInflater().inflate(R.layout.keyboard_view, null);
        Keyboard keyboard = new Keyboard(this, R.xml.number_pad);
        keyboardView.setKeyboard(keyboard);
        keyboardView.setOnKeyboardActionListener(this);
        return keyboardView;
    }

    @Override
    public void onKey(int primaryCode, int[] keyCodes) {

        InputConnection ic = getCurrentInputConnection();
        if (ic == null) return;
        switch (primaryCode) {
            case Keyboard.KEYCODE_DELETE:
                CharSequence selectedText = ic.getSelectedText(0);
                if (TextUtils.isEmpty(selectedText)) {
                    // no selection, so delete previous character
                    ic.deleteSurroundingText(1, 0);
                } else {
                    // delete the selection
                    ic.commitText("", 1);
                }
                break;
            default:
                char code = (char) primaryCode;
                ic.commitText(String.valueOf(code), 1);
        }
    }

    @Override
    public void onPress(int primaryCode) { }

    @Override
    public void onRelease(int primaryCode) { }

    @Override
    public void onText(CharSequence text) { }

    @Override
    public void swipeLeft() { }

    @Override
    public void swipeRight() { }

    @Override
    public void swipeDown() { }

    @Override
    public void swipeUp() { }
}

Notes:

The OnKeyboardActionListener listens for keyboard input. It is also requires all those empty methods in this example.

The InputConnection is what is used to send input to another view like an EditText.

5. Update the manifest

I put this last rather than first because it refers to the files we already added above. To register your custom keyboard as a system keyboard, you need to add a service section to your AndroidManifest.xml file. Put it in the application section after activity.

<manifest ...>
    <application ... >
        <activity ... >
            ...
        </activity>

        <service
            android:name=".MyInputMethodService"
            android:label="Keyboard Display Name"
            android:permission="android.permission.BIND_INPUT_METHOD">
            <intent-filter>
                <action android:name="android.view.InputMethod"/>
            </intent-filter>
            <meta-data
                android:name="android.view.im"
                android:resource="@xml/method"/>
        </service>

    </application>
</manifest>

That's it! You should be able to run your app now. However, you won't see much until you enable your keyboard in the settings.

6. Enable the keyboard in Settings

Every user who wants to use your keyboard will have to enable it in the Android settings. For detailed instructions on how to do that, see the following link:

How to set the default keyboard on your Android phone

Here is a summary:

Go to Android Settings > Languages and input > Current keyboard > Choose keyboards.

You should see your Custom Keyboard on the list. Enable it.

Go back and choose Current keyboard again. You should see your Custom Keyboard on the list. Choose it.

Now you should be able to use your keyboard anywhere that you can type in Android.

Further study

The keyboard above is usable, but to create a keyboard that other people will want to use you will probably have to add more functionality. Study the links below to learn how.

Creating an Input Method (Android documentation)

SoftKeyboard (source code from Android for a demo custom keyboard)

Building a Custom Android Keyboard (tutorial) (source code)

Create a Custom Keyboard on Android (tutsplus tutorial)

How to create custom keyboard for android (YouTube video: It is soundless but following along is how I first learned how to do this.)

Going On

Don't like how the standard KeyboardView looks and behaves? I certainly don't. It looks like it hasn't been updated since Android 2.0. How about all those custom keyboards in the Play Store? They don't look anything like the ugly keyboard above.

The good news is that you can completely customize your own keyboard's look and behavior. You will need to do the following things:

Create your own custom keyboard view that subclasses ViewGroup. You could fill it with Buttons or even make your own custom key views that subclass View. If you use popup views, then note this.

Add a custom event listener interface in your keyboard. Call its methods for things like onKeyClicked(String text) or onBackspace().

You don't need to add the keyboard_view.xml, key_preview.xml, or number_pad.xml described in the directions above since these are all for the standard KeyboardView. You will handle all these UI aspects in your custom view.

In your MyInputMethodService class, implement the custom keyboard listener that you defined in your keyboard class. This is in place of KeyboardView.OnKeyboardActionListener, which is no longer needed.

In your MyInputMethodService class's onCreateInputView() method, create and return an instance of your custom keyboard. Don't forget to set the keyboard's custom listener to this.


问:
How to join two mysql tables in my Django application
I have two tables in my MySQL database:

First Table: For Subscribers (id, name, area, subscriberNumber, phoneNumber)

Second Table: For Monthly Payment (id, subscriberNumber, month, year, amount, discount, fine, billNumber)

I have a HTML page where the list of the Subscriber. Whenever the admin clicks on one of the subscriber the detail of the user is shown.But currently I can only show the user detail(from the first table). I want the page to show the list of payments he/she has done throughout the year(from the second table). I want to join the tables and show the details of both the table in one HTML page.

This is the code to display the data of the first table in views.py

```<code>@login_required
def userDetail(request, id=None):
    instance = get_object_or_404(Subscribers.objects.using('db2'), id=id)
    context = {
        "Name": instance.name,
        "instance": instance,
    }
    return render(request, 'userDetail.html', context)
</code>```

How do I show the payments done by the user on the same page as their details are in?

Models.py

```<code>from __future__ import unicode_literals
from django.db import models
from django.core.urlresolvers import reverse

class Subscribers(models.Model):
    name = models.CharField(max_length=120)
    area = models.CharField(max_length=30)
    phoneNumber = models.CharField(max_length=10)
    installationCost = models.CharField(max_length=10)
    subsNumber = models.CharField(max_length=100)

    def get_absolute_url(self):
        return reverse("userDetail", kwargs={"id": self.id})

class Payments(models.Model):
    month = models.CharField(max_length=120)
    year = models.CharField(max_length=4)
    amount = models.CharField(max_length=10)
    discount = models.CharField(max_length=10)
    fine = models.CharField(max_length=10)
    billNumber = models.CharField(max_length=100)
    subsNumber = models.CharField(max_length=100)

    def get_absolute_url(self):
        return reverse("userDetail", kwargs={"id": self.id})
</code>```

答:
To show the payment of a user you can use:</p>

```<code>instance = get_object_or_404(Subscribers.objects.using('db2'), id=id)
try:
    payment_info = Payments.objects.using('db2').get(subsNumber=instance.subsNumber)
except Payments.DoesNotExist:
    payment_info = None
context = {
    "Name": instance.name,
    "instance": instance,
    "payment": payment_info
}
</code>```

Body:
I have two tables in my MySQL database:

First Table: For Subscribers (id, name, area, subscriberNumber, phoneNumber)

Second Table: For Monthly Payment (id, subscriberNumber, month, year, amount, discount, fine, billNumber)

I have a HTML page where the list of the Subscriber. Whenever the admin clicks on one of the subscriber the detail of the user is shown.But currently I can only show the user detail(from the first table). I want the page to show the list of payments he/she has done throughout the year(from the second table). I want to join the tables and show the details of both the table in one HTML page.

This is the code to display the data of the first table in views.py

@login_required
def userDetail(request, id=None):
    instance = get_object_or_404(Subscribers.objects.using('db2'), id=id)
    context = {
        "Name": instance.name,
        "instance": instance,
    }
    return render(request, 'userDetail.html', context)

How do I show the payments done by the user on the same page as their details are in?

Models.py

from __future__ import unicode_literals
from django.db import models
from django.core.urlresolvers import reverse

class Subscribers(models.Model):
    name = models.CharField(max_length=120)
    area = models.CharField(max_length=30)
    phoneNumber = models.CharField(max_length=10)
    installationCost = models.CharField(max_length=10)
    subsNumber = models.CharField(max_length=100)

    def get_absolute_url(self):
        return reverse("userDetail", kwargs={"id": self.id})

class Payments(models.Model):
    month = models.CharField(max_length=120)
    year = models.CharField(max_length=4)
    amount = models.CharField(max_length=10)
    discount = models.CharField(max_length=10)
    fine = models.CharField(max_length=10)
    billNumber = models.CharField(max_length=100)
    subsNumber = models.CharField(max_length=100)

    def get_absolute_url(self):
        return reverse("userDetail", kwargs={"id": self.id})

Body:
To show the payment of a user you can use:

instance = get_object_or_404(Subscribers.objects.using('db2'), id=id)
try:
    payment_info = Payments.objects.using('db2').get(subsNumber=instance.subsNumber)
except Payments.DoesNotExist:
    payment_info = None
context = {
    "Name": instance.name,
    "instance": instance,
    "payment": payment_info
}


问:
Combine results from two tables into one recordset
I have two tables items and content.

```<code> items:|ID|menu|img
</code>```

table

```<code> itemcontent |ID|parent|title|content
</code>```

content holds is paired to items by parent holding the title and content

i want to search all the items and also print out those records wich do not have a title present in the itemcontent table
whereby the titles will be printed as "Empty".
so printing out the output would look something like:

```
title: test1 and ID: items.ID=1
title: Empty and ID: items.ID=2
title: Empty and ID: items.ID=3
title: test2 and ID: items.ID=4
title: Empty and ID: items.ID=5
etc...
```

I tried the following and then some but to no avail:

```<code>SELECT items.*, itemcontent.title, itemcontent.content
FROM items, itemcontent
WHERE itemcontent.title LIKE '%$search%'
     AND itemcontent.parent = items.ID
order by title ASC
</code>```

A little help would be much appreciated

答: Just to be sure you might want to ORDER BY itemcontent.title and not just title or select itemcontent.title AS title? Do you have a field called title in the items table?</p>

ContentLicense: CC BY-SA 2.5

Body:
I have two tables items and content.

 items:|ID|menu|img

table

 itemcontent |ID|parent|title|content

content holds is paired to items by parent holding the title and content

i want to search all the items and also print out those records wich do not have a title present in the itemcontent table
whereby the titles will be printed as "Empty".
so printing out the output would look something like:

title: test1 and ID: items.ID=1
title: Empty and ID: items.ID=2
title: Empty and ID: items.ID=3
title: test2 and ID: items.ID=4
title: Empty and ID: items.ID=5
etc...

I tried the following and then some but to no avail:

SELECT items.*, itemcontent.title, itemcontent.content
FROM items, itemcontent
WHERE itemcontent.title LIKE '%$search%'
     AND itemcontent.parent = items.ID
order by title ASC

A little help would be much appreciated


问:
angular 2 ui-router: change data in parent state
I have a project using Angular 2 and UI-ROUTER (not NgRoute).

It has:

    a parent state 'parent', controlling the view of Header and Control as shown in the picture below,

    two child states 'childA' and 'childB', controlling the view of child

On entering any of a child state say 'childAState', I need to pass some text like 'childA', to the header view that controlled by parent state. How can I do it? How to pass data to parent state when entering a child state?

This 'childA' text is not related to any component, but related to the child state it's entering. ( So I don't think I should pass it through component tree.)

I defined the states like this:

```<code>export const parentState = {
    name: 'parent',
    url: '',
    redirectTo: 'childA',
    views: {
        'header': {
            component: HeaderComponent
        },
        'control-panel': {
            component: ControlComponent
        }
    }
};
export const childAState = {
    name: 'childA',
    parent: 'parent',
    url: '/childA',
    views: {
        'child@': {
            component: LayerAComponent
        }
    }
};
export const childBState = {
    name: 'childB',
    parent: 'parent',
    url: '/childB',
    views: {
        'child@': {
            component: LayerBComponent
        }
    }
};
</code>```

Thanks!

答:
Put data on your states' data property, like this example:

```<code>export const childAState = {
    name: 'childA',
    parent: 'parent',
    url: '/childA',
    data: {
        childData: 'childA'
    },
    views: {
        'child@': {
            component: LayerAComponent
        }
    }
};
</code>```

In your HeaderComponent you can listen to state changes, either using a Transition Hook or the router.globals.success$ observable.

```<code>import { TransitionService } from '@uirouter/angular';

@Component({})
class HeaderComponent {
  private unsub: Function;
  constructor(public transService: TransitionService) {}

  ngOnInit() {
    this.unsub = this.transService.onSuccess({}, transition => {
      const to = transition.to(); // The state that was just activated
      if (to.data && to.data.childData) {
        // do something
      }
    });
  }

  ngOnDestroy() {
    this.unsub();
  }
}
</code>```

or

```<code>import { UIRouter } from '@uirouter/angular';

@Component({})
class HeaderComponent {
  private sub: Subscription;
  constructor(public router: UIRouter) {}

  ngOnInit() {
    this.sub = router.globals.success$.subscribe({}, transition => {
      const to = transition.to(); // The state that was just activated
      if (to.data && to.data.childData) {
        // do something
      }
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}
</code>```

Body:
I have a project using Angular 2 and UI-ROUTER (not NgRoute).

It has:

    a parent state 'parent', controlling the view of Header and Control as shown in the picture below,

    two child states 'childA' and 'childB', controlling the view of child

On entering any of a child state say 'childAState', I need to pass some text like 'childA', to the header view that controlled by parent state. How can I do it? How to pass data to parent state when entering a child state?

This 'childA' text is not related to any component, but related to the child state it's entering. ( So I don't think I should pass it through component tree.)

I defined the states like this:

export const parentState = {
    name: 'parent',
    url: '',
    redirectTo: 'childA',
    views: {
        'header': {
            component: HeaderComponent
        },
        'control-panel': {
            component: ControlComponent
        }
    }
};
export const childAState = {
    name: 'childA',
    parent: 'parent',
    url: '/childA',
    views: {
        'child@': {
            component: LayerAComponent
        }
    }
};
export const childBState = {
    name: 'childB',
    parent: 'parent',
    url: '/childB',
    views: {
        'child@': {
            component: LayerBComponent
        }
    }
};

Thanks!

Body:
Put data on your states' data property, like this example:

export const childAState = {
    name: 'childA',
    parent: 'parent',
    url: '/childA',
    data: {
        childData: 'childA'
    },
    views: {
        'child@': {
            component: LayerAComponent
        }
    }
};

In your HeaderComponent you can listen to state changes, either using a Transition Hook or the router.globals.success$ observable.

import { TransitionService } from '@uirouter/angular';

@Component({})
class HeaderComponent {
  private unsub: Function;
  constructor(public transService: TransitionService) {}

  ngOnInit() {
    this.unsub = this.transService.onSuccess({}, transition => {
      const to = transition.to(); // The state that was just activated
      if (to.data && to.data.childData) {
        // do something
      }
    });
  }

  ngOnDestroy() {
    this.unsub();
  }
}

or

import { UIRouter } from '@uirouter/angular';

@Component({})
class HeaderComponent {
  private sub: Subscription;
  constructor(public router: UIRouter) {}

  ngOnInit() {
    this.sub = router.globals.success$.subscribe({}, transition => {
      const to = transition.to(); // The state that was just activated
      if (to.data && to.data.childData) {
        // do something
      }
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}


问:
Send SMS with Twilio in Swift
I try to use Twilio as an service provider but they have no examples for Swift that I understand.

My task is to send SMS to a number using Twilio API with Swift.

I have a Twilio.com account - and that one is working. But how do I do this in Swift code in a easy manner.

Twilio does provide a library - but that is meant for C# not for Swift (and using a bridging header seems too complicated!)

Here is the C# example, I need a easy Swift example.

```<code>// Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio;
class Example
{
  static void Main(string[] args)
  {
    // Find your Account Sid and Auth Token at twilio.com/user/account
    string AccountSid = "AC5ef8732a3c49700934481addd5ce1659";
    string AuthToken = "{{ auth_token }}";
    var twilio = new TwilioRestClient(AccountSid, AuthToken);

    var message = twilio.SendMessage("+14158141829", "+15558675309", "Jenny please?! I love you <3", new string[] {"http://www.example.com/hearts.png"});

    Console.WriteLine(message.Sid);
  }
}
</code>```

答:
Swift 3 version:</p>

```<code>func sendSMS()
{
    print("Starting...")
    let twilioSID = "ENRET YOUR SID"
    let twilioSecret = "YOUR TOKEN"
    //Note replace + = %2B , for To and From phone number
    let fromNumber = "%29999999"// actual number is +9999999
    let toNumber = "%29999999"// actual number is +9999999
    let message = "Your verification code is 2212 for signup with"

    // Build the request
    let request = NSMutableURLRequest(url: URL(string:"https://\(twilioSID):\(twilioSecret)@api.twilio.com/2010-04-01/Accounts/\(twilioSID)/SMS/Messages")!)
    request.httpMethod = "POST"
    request.httpBody = "From=\(fromNumber)&To=\(toNumber)&Body=\(message)".data(using: .utf8)

    // Build the completion block and send the request
    URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
        print("Finished")
        if let data = data, let responseDetails = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
            // Success
            print("Response: \(responseDetails)")
        } else {
            // Failure
            print("Error: \(error)")
        }
    }).resume()
}
</code>```

Title: Send SMS with Twilio in Swift

Body:
I try to use Twilio as an service provider but they have no examples for Swift that I understand.

My task is to send SMS to a number using Twilio API with Swift.

I have a Twilio.com account - and that one is working. But how do I do this in Swift code in a easy manner.

Twilio does provide a library - but that is meant for C# not for Swift (and using a bridging header seems too complicated!)

Here is the C# example, I need a easy Swift example.

// Download the twilio-csharp library from twilio.com/docs/csharp/install
using System;
using Twilio;
class Example
{
  static void Main(string[] args)
  {
    // Find your Account Sid and Auth Token at twilio.com/user/account
    string AccountSid = "AC5ef8732a3c49700934481addd5ce1659";
    string AuthToken = "{{ auth_token }}";
    var twilio = new TwilioRestClient(AccountSid, AuthToken);

    var message = twilio.SendMessage("+14158141829", "+15558675309", "Jenny please?! I love you <3", new string[] {"http://www.example.com/hearts.png"});

    Console.WriteLine(message.Sid);
  }
}

Body:
Swift 3 version:

func sendSMS()
{
    print("Starting...")
    let twilioSID = "ENRET YOUR SID"
    let twilioSecret = "YOUR TOKEN"
    //Note replace + = %2B , for To and From phone number
    let fromNumber = "%29999999"// actual number is +9999999
    let toNumber = "%29999999"// actual number is +9999999
    let message = "Your verification code is 2212 for signup with"

    // Build the request
    let request = NSMutableURLRequest(url: URL(string:"https://\(twilioSID):\(twilioSecret)@api.twilio.com/2010-04-01/Accounts/\(twilioSID)/SMS/Messages")!)
    request.httpMethod = "POST"
    request.httpBody = "From=\(fromNumber)&To=\(toNumber)&Body=\(message)".data(using: .utf8)

    // Build the completion block and send the request
    URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
        print("Finished")
        if let data = data, let responseDetails = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
            // Success
            print("Response: \(responseDetails)")
        } else {
            // Failure
            print("Error: \(error)")
        }
    }).resume()
}


问:
How to vertically center elements in Bulma?
How can I vertically center this
 to that red colored section which is enclosing it?

And should I remove or add some classes here to improve this code? Please suggest me. Thanks!

I am new to CSS framework, never tried Bootstrap and instead opted for Bulma.

```<code><section id="eyes" class="section">
    <div class="container">
        <div class="columns is-vcentered">
            <div class="column">
                <h1>Eyes on what matters</h1>
                <p>Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.</p>
            </div>
            <div class="column">
                <img class="image" src="img/roll.jpg" alt="">
            </div>
        </div>
    </div>
</section>
</code>```

In CSS apart from coloring elements, I've only done this:

```<code>section {
    height: 70vh;
}
</code>```

答:
The columns are not vertically centered because you have used a height for the section. Use padding to increase the height.

Remove the class .section (in Bulma)

```<code>.section {
  background-color: white;
  padding: 3rem 1.5rem;
}
</code>```

and use your own padding.

Example

.red-bg {
  background: red;
}

.orange-bg {
  background: orange;
}

section {
  padding: 100px 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.3/css/bulma.css" rel="stylesheet" />
<section class="red-bg">
  <div class="container">
    <div class="columns is-vcentered">
      <div class="column">
        <h1>Eyes on what matters</h1>
        <p>Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.</p>
      </div>
      <div class="column">
        <img class="image" src="http://placehold.it/400x300" alt="">
      </div>
    </div>
  </div>
</section>
<section class="orange-bg">
  <div class="container">
    <div class="columns is-vcentered">
      <div class="column">
        <img class="image" src="http://placehold.it/400x300" alt="">
      </div>
      <div class="column">
        <h1>Eyes on what matters</h1>
        <p>Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.</p>
      </div>
    </div>
  </div>
</section>
<section class="red-bg">
  <div class="container">
    <div class="columns is-vcentered">
      <div class="column">
        <h1>Eyes on what matters</h1>
        <p>Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.</p>
      </div>
      <div class="column">
        <img class="image" src="http://placehold.it/400x300" alt="">
      </div>
    </div>
  </div>
</section></code>```

POSTSCRIPT

You can use .columns is-vcentered two times. In that case you can set an height for the section.

section {
  height: 70vh;
  padding: 15px;
}

.red-bg {
  background: red;
}

.orange-bg {
  background: orange;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.3/css/bulma.css" rel="stylesheet" />
<section class="columns is-vcentered is-centered red-bg">
  <div class="container">
    <div class="columns is-vcentered is-centered">
      <div class="column">
        <h1>Eyes on what matters</h1>
        <p>Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.</p>
      </div>
      <div class="column">
        <img class="image" src="http://placehold.it/400x300" alt="">
      </div>
    </div>
  </div>
</section>
<section class="columns is-vcentered orange-bg">
  <div class="container">
    <div class="columns is-vcentered">
      <div class="column">
        <img class="image" src="http://placehold.it/400x300" alt="">
      </div>
      <div class="column">
        <h1>Eyes on what matters</h1>
        <p>Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.</p>
      </div>
    </div>
  </div>
</section>
<section class="columns is-vcentered red-bg">
  <div class="container">
    <div class="columns is-vcentered">
      <div class="column">
        <h1>Eyes on what matters</h1>
        <p>Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.</p>
      </div>
      <div class="column">
        <img class="image" src="http://placehold.it/400x300" alt="">
      </div>
    </div>
  </div>
</section></code>```

Body:
How can I vertically center this
 to that red colored section which is enclosing it?

And should I remove or add some classes here to improve this code? Please suggest me. Thanks!

I am new to CSS framework, never tried Bootstrap and instead opted for Bulma.

Eyes on what matters

Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.

In CSS apart from coloring elements, I've only done this:

section {
    height: 70vh;
}

Body:
The columns are not vertically centered because you have used a height for the section. Use padding to increase the height.

Remove the class .section (in Bulma)

.section {
  background-color: white;
  padding: 3rem 1.5rem;
}

and use your own padding.

Example

.red-bg {
  background: red;
}

.orange-bg {
  background: orange;
}

section {
  padding: 100px 15px;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.3/css/bulma.css" rel="stylesheet" />
<section class="red-bg">
  <div class="container">
    <div class="columns is-vcentered">
      <div class="column">
        <h1>Eyes on what matters</h1>
        <p>Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.</p>
      </div>
      <div class="column">
        <img class="image" src="http://placehold.it/400x300" alt="">
      </div>
    </div>
  </div>
</section>
<section class="orange-bg">
  <div class="container">
    <div class="columns is-vcentered">
      <div class="column">
        <img class="image" src="http://placehold.it/400x300" alt="">
      </div>
      <div class="column">
        <h1>Eyes on what matters</h1>
        <p>Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.</p>
      </div>
    </div>
  </div>
</section>
<section class="red-bg">
  <div class="container">
    <div class="columns is-vcentered">
      <div class="column">
        <h1>Eyes on what matters</h1>
        <p>Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.</p>
      </div>
      <div class="column">
        <img class="image" src="http://placehold.it/400x300" alt="">
      </div>
    </div>
  </div>
</section>

POSTSCRIPT

You can use .columns is-vcentered two times. In that case you can set an height for the section.

section {
  height: 70vh;
  padding: 15px;
}

.red-bg {
  background: red;
}

.orange-bg {
  background: orange;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.3/css/bulma.css" rel="stylesheet" />
<section class="columns is-vcentered is-centered red-bg">
  <div class="container">
    <div class="columns is-vcentered is-centered">
      <div class="column">
        <h1>Eyes on what matters</h1>
        <p>Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.</p>
      </div>
      <div class="column">
        <img class="image" src="http://placehold.it/400x300" alt="">
      </div>
    </div>
  </div>
</section>
<section class="columns is-vcentered orange-bg">
  <div class="container">
    <div class="columns is-vcentered">
      <div class="column">
        <img class="image" src="http://placehold.it/400x300" alt="">
      </div>
      <div class="column">
        <h1>Eyes on what matters</h1>
        <p>Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.</p>
      </div>
    </div>
  </div>
</section>
<section class="columns is-vcentered red-bg">
  <div class="container">
    <div class="columns is-vcentered">
      <div class="column">
        <h1>Eyes on what matters</h1>
        <p>Backtick is made to look minimal, so you can focus on your code, always. From UI to linter errors, everything is kept non-obtrusive.</p>
      </div>
      <div class="column">
        <img class="image" src="http://placehold.it/400x300" alt="">
      </div>
    </div>
  </div>
</section>


问:
Cannot Open CSV File Swift
I am trying to create a simple CVS file in document directory on iPad or temp directory. This code is as follows:

```<code> let fileName = "test.csv"

        _ = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
</code>```

I am then trying to modify the file using CSV.swift library from github like this:

```<code>let stream = OutputStream(toFileAtPath: "test.csv", append: false)!

        let csv = try! CSVWriter(stream: stream) // Error at this line

        try! csv.write(row: headerarray)
        try! csv.write(row: dataarray)

        csv.stream.close()
</code>```

For some reason I am getting error saying CSV.CSVError.cannotOpenFile: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-802.0.53/src/swift/stdlib/public/core/ErrorType.swift

It doesn't look like I am creating the .csv file correctly.

答:
You are throwing away the path to the Temporary Directory in the second line. That is your problem. So instead of adding fileName inside the Temporary Directory, you are trying to add it to the root of your hard disk. I doubt you have permissions for this and therefore fail to create the file. Try building up the full pathname like I do in the first line of the function below.

Here is a function that writes a String to a file in the Temporary Directory using streams.

```<code>func streamTextToFile(_ text: String) {
  let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("test.csv")
  guard let stream = OutputStream(toFileAtPath: url.path, append: false) else { return }
  let data = [UInt8](text.utf8)
  stream.open()
  stream.write(data, maxLength: data.count)
  stream.close()
}
</code>```

Here is some sample output.

Title: Cannot Open CSV File Swift

Body:
I am trying to create a simple CVS file in document directory on iPad or temp directory. This code is as follows:

 let fileName = "test.csv"

        _ = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)

I am then trying to modify the file using CSV.swift library from github like this:

let stream = OutputStream(toFileAtPath: "test.csv", append: false)!

        let csv = try! CSVWriter(stream: stream) // Error at this line

        try! csv.write(row: headerarray)
        try! csv.write(row: dataarray)

        csv.stream.close()

For some reason I am getting error saying CSV.CSVError.cannotOpenFile: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-802.0.53/src/swift/stdlib/public/core/ErrorType.swift

It doesn't look like I am creating the .csv file correctly.

Body:
You are throwing away the path to the Temporary Directory in the second line. That is your problem. So instead of adding fileName inside the Temporary Directory, you are trying to add it to the root of your hard disk. I doubt you have permissions for this and therefore fail to create the file. Try building up the full pathname like I do in the first line of the function below.

Here is a function that writes a String to a file in the Temporary Directory using streams.

func streamTextToFile(_ text: String) {
  let url = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("test.csv")
  guard let stream = OutputStream(toFileAtPath: url.path, append: false) else { return }
  let data = [UInt8](text.utf8)
  stream.open()
  stream.write(data, maxLength: data.count)
  stream.close()
}

Here is some sample output.


问:
php array to string conversion odbc_exec count
i'm still new towards php but after searching through multiple topics i can't seem to figure this one out.

```<code>$query2 = "SELECT COUNT(MAP_CODE2) FROM TCODE_MAPPING WHERE MAP_CODE2 = 'ABC123'";
$result2 = odbc_exec($connect,$query2);
echo $result2;
</code>```

i have a query above that i'd like to use to get the total number of rows within the query that i've set, however for some reason i keep getting hit by the error

Array to string conversion in /var/www/html/xxx.php on line 85

Would highly appreciate if anyone could help out on what i'm doing wrong. Thank you!

答:
What is happening here is you are echoing an array object type that is also a resource type and php echo only string and other primitive type variables.

so you need to use a loop to access the row or to get row count and access row just use a foreach($results as $result)

to get row count visit this sqlsrv-num-rows . on this official php link you can get more example how to fetch data.

Body:
i'm still new towards php but after searching through multiple topics i can't seem to figure this one out.

$query2 = "SELECT COUNT(MAP_CODE2) FROM TCODE_MAPPING WHERE MAP_CODE2 = 'ABC123'";
$result2 = odbc_exec($connect,$query2);
echo $result2;

i have a query above that i'd like to use to get the total number of rows within the query that i've set, however for some reason i keep getting hit by the error

Array to string conversion in /var/www/html/xxx.php on line 85

Would highly appreciate if anyone could help out on what i'm doing wrong. Thank you!


问:
Set timezone for MYSQL NOW()
On my server i keep a log of operations and this is tracked using the timestamp generated by MYSQL NOW() function.But the problem is that the timestamp generated is in UTC and i want the NOW() function to generate the timestamp corresponding to my local time for Asia/Kolkata. I tried the SET timezone but it is not working

```<code>$queryt="SET time_zone='Asia/Kolkata'";
mysqli_query($mysqli, $queryt))
</code>```

What am i doing wrong?

答:
Try this:</p>

```<code>SET GLOBAL time_zone = "Asia/Kolkata";
SET time_zone = "+05:30";
SET @@session.time_zone = "+05:30";
</code>```

Title: Set timezone for MYSQL NOW()

Body:
On my server i keep a log of operations and this is tracked using the timestamp generated by MYSQL NOW() function.But the problem is that the timestamp generated is in UTC and i want the NOW() function to generate the timestamp corresponding to my local time for Asia/Kolkata. I tried the SET timezone but it is not working

$queryt="SET time_zone='Asia/Kolkata'";
mysqli_query($mysqli, $queryt))

What am i doing wrong?

Body:
Try this:

SET GLOBAL time_zone = "Asia/Kolkata";
SET time_zone = "+05:30";
SET @@session.time_zone = "+05:30";


问:
Context-free grammar and Reversal
I'm designing a context-free grammar to generate this language:

```<code>{ w in {a,b}* | w is of the form uvu^R, where u and v are any strings in {a,b}* }
</code>```

I would define the first two strings as:

```<code>U -> aU | bU | _
V -> aV | bV | _
</code>```

And then combine those:

```<code>S -> UV
</code>```

But how do I express the reversal as context-free grammar?

答:
You need to make use of the context-free-ness of the grammar (what you're presenting so far is just a regular grammar):

```<code>U-> aUa | bUb | a | b | _
</code>```

Will match things like "ababa" and "aabaa", but not "aabba".

I'll leave it to you to alter this to your needs - but keep in mind that your specified language has the possibility of u being the empty string, hence it generates all strings in {a,b}*.

Title: Context-free grammar and Reversal

Body:
I'm designing a context-free grammar to generate this language:

{ w in {a,b}* | w is of the form uvu^R, where u and v are any strings in {a,b}* }

I would define the first two strings as:

U -> aU | bU | _
V -> aV | bV | _

And then combine those:

S -> UV

But how do I express the reversal as context-free grammar?

Body:
You need to make use of the context-free-ness of the grammar (what you're presenting so far is just a regular grammar):

U-> aUa | bUb | a | b | _

Will match things like "ababa" and "aabaa", but not "aabba".

I'll leave it to you to alter this to your needs - but keep in mind that your specified language has the possibility of u being the empty string, hence it generates all strings in {a,b}*.


答:
Problem is:-

You are trying to echo a result-set object of array type.

Solution (check the code comments):-

```<code>$query2 = "SELECT COUNT(MAP_CODE2) AS MYCOUNT FROM TCODE_MAPPING WHERE MAP_CODE2 = 'ABC123'"; // given a name to the count

$result2 = odbc_exec($connect,$query2); //prepare and execute query

while (odbc_fetch_row($result2)) { //iterate over result-set object

  echo odbc_result($result, "MYCOUNT"), "\n"; // echo count

}
</code>```

Title: php array to string conversion odbc_exec count

Body:
Problem is:-

You are trying to echo a result-set object of array type.

Solution (check the code comments):-

$query2 = "SELECT COUNT(MAP_CODE2) AS MYCOUNT FROM TCODE_MAPPING WHERE MAP_CODE2 = 'ABC123'"; // given a name to the count

$result2 = odbc_exec($connect,$query2); //prepare and execute query

while (odbc_fetch_row($result2)) { //iterate over result-set object

  echo odbc_result($result, "MYCOUNT"), "\n"; // echo count

}


问:
How to sort songs from raw folder in my own order using arraylist
I am new to android development and I would like to sorts the songs in my own order which are in raw folder.I am using array list.Thanks you. </p>

答:
Try this</p>

```<code>private List<File> getFilesList(File dir, String fileExt) {
    ArrayList<File> fileList = new ArrayList<File>();
    File[] files = dir.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            fileList.addAll(getListFiles(file));
        } else {
            if(file.getName().endsWith(fileExt)){
                fileList.add(file);
            }
        }
    }
    return fileList;
}

// get files list
List<File> files = getFilesList(new File("your folder path", ".mp3"));

// sort files in list based on filename
Collections.sort(files, new Comparator<File>() {
    @Override
    public int compare(File file1, File file2)
    {
        return  file1.getName().compareTo(file2.getName());
    }
});
</code>```

Body:
Try this

private List<File> getFilesList(File dir, String fileExt) {
    ArrayList<File> fileList = new ArrayList<File>();
    File[] files = dir.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            fileList.addAll(getListFiles(file));
        } else {
            if(file.getName().endsWith(fileExt)){
                fileList.add(file);
            }
        }
    }
    return fileList;
}

// get files list
List<File> files = getFilesList(new File("your folder path", ".mp3"));

// sort files in list based on filename
Collections.sort(files, new Comparator<File>() {
    @Override
    public int compare(File file1, File file2)
    {
        return  file1.getName().compareTo(file2.getName());
    }
});


问:
Confirmation instruction on other email with devise
I have two email fields in my model :email and :representative_email I want to send confirmation instructions email on :representative_email (if present or not nil) rather than :email how can I do it with efficiently. And I still want to login with my :email field.</p>

答:
I needed to override headers_for method for devise within mailer

```<code>class DeviseCustomMailer < Devise::Mailer
  helper :application # gives access to all helpers defined within `application_helper`.
  include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`
  default template_path: 'devise/mailer'
  def headers_for(action, opts)
    headers = {
      subject: subject_for(action),
      to: resource.notification_email_for(action), #I changed this line
      from: mailer_sender(devise_mapping),
      reply_to: mailer_reply_to(devise_mapping),
      template_path: template_paths,
      template_name: action
    }.merge(opts)

    @email = headers[:to]
    headers
  end
end
</code>```

and in my user.rb

```<code>def notification_email_for(action)
  (self.company? && self.authorised_representative && action == :confirmation_instructions) ? self.representative_email : self.email
end
</code>```

and in my config/initializers/devise.rb

```<code>config.mailer = 'DeviseCustomMailer'
</code>```

that's it

Body:
I needed to override headers_for method for devise within mailer

class DeviseCustomMailer < Devise::Mailer
  helper :application # gives access to all helpers defined within `application_helper`.
  include Devise::Controllers::UrlHelpers # Optional. eg. `confirmation_url`
  default template_path: 'devise/mailer'
  def headers_for(action, opts)
    headers = {
      subject: subject_for(action),
      to: resource.notification_email_for(action), #I changed this line
      from: mailer_sender(devise_mapping),
      reply_to: mailer_reply_to(devise_mapping),
      template_path: template_paths,
      template_name: action
    }.merge(opts)

    @email = headers[:to]
    headers
  end
end

and in my user.rb

def notification_email_for(action)
  (self.company? && self.authorised_representative && action == :confirmation_instructions) ? self.representative_email : self.email
end

and in my config/initializers/devise.rb

config.mailer = 'DeviseCustomMailer'

that's it


问:
When using Google Invisible Captcha automatic html form validation and required attribute does not work. Why?
I am trying to implement the new Google Invisible Recaptcha and for some reason yet unknown to me the automatic html form validation and the required attributes does not seem to be working after along with the Recaptcha. I am guessing it is because of the onSubmit() function callback. Can someone let me know how to fix this issue? Thanks in advance.

Below is my implementation of a form with Google Invisible Recaptcha. The data-sitekey has been intentionally removed.

<form id="contactForm" action="#" method="POST">

Leave a Message

  Name
  <input type="text" name="Name" id="inputName" placeholder="Name" required>

  Email
  <input type="email" name="Email" id="inputEmail" placeholder="Email Id" required>

  Message
  <input type="text" name="Message" id="inputMessage" placeholder="Message" required>

  <button class="g-recaptcha" type="submit" data-sitekey="//site-key" data-badge="bottomleft" data-callback='onSubmit'>Submit</button>
  <button type="reset">Reset</button>
</form>

```

答:
Create a callback function which sets the onclick property of the submit button to onSubmit function and then triggers a click. </p>

```<code> <script>
 function callBack(){
  document.getElementById('submit-button').addEventListener('click',onSubmit);
  document.getElementById('submit-button').click();
 }

 function onSubmit() {
 //validation code here
  document.getElementById("contactForm").submit();
 }
</script>
</code>```

<p>Set this callback function to the data-callback property </p>

```<code><button id='submit-button' class="g-recaptcha" type="submit" data-sitekey="//site-key" data-badge="bottomleft" data-callback='callBack'>Submit</button>
</code>```

Body:
Create a callback function which sets the onclick property of the submit button to onSubmit function and then triggers a click.

 <script>
 function callBack(){
  document.getElementById('submit-button').addEventListener('click',onSubmit);
  document.getElementById('submit-button').click();
 }

 function onSubmit() {
 //validation code here
  document.getElementById("contactForm").submit();
 }
</script>

Set this callback function to the data-callback property

<button id='submit-button' class="g-recaptcha" type="submit" data-sitekey="//site-key" data-badge="bottomleft" data-callback='callBack'>Submit</button>


问:
Is it possible to reference a VSTS Build variable directly into a Xamarin project code?
Currently exploring an option to configure app secret in VSTS build variable and then reference the build variable within in the xamarin.Android project. Is that even possible? I know that we can use a script to update the project from the build variable. But looking for a simple and direct approach. The idea is to have different app secret for different build configuration. </p>

<p>Anyone have any experience in this area? </p>

答:
Yes, you can use build variable to replace the secret you defined in your Xamarin.android code (assume the secret is stored in MainActivity.cs).

Option 1: use Replace Tokens extension task

Add a variable (such as password) in Variables Tab, and set the value as what you want to use in your code.

Add the Replace Tokens task in your build definition.

Root directory: where your MainActivity.cs stored in or the parent directory.

Target files: **\ MainActivity.cs

Empty value: password

Change the secret setting as secret="#{password}#"; in your code. The task will replace the part start with #{ and end with }#.

Option 2: use PowerShell task

Assume the secret defined in your code as secret="password";.

Add a variable (such as token) in variables Tab, and set the value as what you want to replace.

Add PowerShell task in your build definition.

Type: inline Script

Inline Script:

$path="$(Build.SourcesDirectory)\project\project\ MainActivity.cs"
(Get-Content $path) -replace "password",$(token) | out-file $path

For MAC, you can use the shell script as below:

cd /to/the/path/the/file/exist
find . -type f -name "MainActivity.cs" | xargs sed -i '' 's/password/$(token)/g'

Body:
Currently exploring an option to configure app secret in VSTS build variable and then reference the build variable within in the xamarin.Android project. Is that even possible? I know that we can use a script to update the project from the build variable. But looking for a simple and direct approach. The idea is to have different app secret for different build configuration.

Anyone have any experience in this area?


问:
Change ArrayList to three dots for an input
I have a method that has as a signature, let's say method(Object... args)
And one of my other methods creates an ArrayList<Object> list.

What should I do so I can use method(list)?
I have tried to do method(Arrays.asList(list)) but it has not worked

答:
You can use List.toArray() like

```<code>method(list.toArray());
</code>```

Also, the three dots means it is a varargs or variadic function.

Body:
You can use List.toArray() like

method(list.toArray());

Also, the three dots means it is a varargs or variadic function.


问:
Keep db column comment when renaming a column
When I add a new column, I can add a db comment as follows.

```<code>add_column :foo_tables, :bar_column, :boolean, comment: 'comment'
</code>```

However, when I change column name, the comment is gone and it seems there is no way to add it again...
I tried following patterns, but none of them worked :(

```<code># migration succeeds, but comment is gone
rename_column :foo_tables, :bar_column, :bar_new_column

# migration fails (rename_column does not take :comment as arg)
rename_column :foo_tables, :bar_column, :bar_new_column, comment: 'comment'

# migration fails (change_column does not take :comment as arg)
rename_column :foo_tables, :bar_column, :bar_new_column
change_column :foo_tables, comment: 'new_comment'
</code>```

Is there any way to keep comment after renaming a column?

答:
You will have to change the bottom portion of your code to:

```<code>rename_column :foo_tables, :bar_column, :bar_new_column
change_column :foo_tables, :bar_new_column, :string, comment: 'new_comment'
</code>```

If you look at the migration docs you can see that rename_column takes only 3 arguments:

rename_column(table_name, column_name, new_column_name)

In your migration you can rename the column and then add the comment.

Body:
When I add a new column, I can add a db comment as follows.

add_column :foo_tables, :bar_column, :boolean, comment: 'comment'

However, when I change column name, the comment is gone and it seems there is no way to add it again...
I tried following patterns, but none of them worked :(

# migration succeeds, but comment is gone
rename_column :foo_tables, :bar_column, :bar_new_column

# migration fails (rename_column does not take :comment as arg)
rename_column :foo_tables, :bar_column, :bar_new_column, comment: 'comment'

# migration fails (change_column does not take :comment as arg)
rename_column :foo_tables, :bar_column, :bar_new_column
change_column :foo_tables, comment: 'new_comment'

Is there any way to keep comment after renaming a column?

Body:
You will have to change the bottom portion of your code to:

rename_column :foo_tables, :bar_column, :bar_new_column
change_column :foo_tables, :bar_new_column, :string, comment: 'new_comment'

If you look at the migration docs you can see that rename_column takes only 3 arguments:

rename_column(table_name, column_name, new_column_name)

In your migration you can rename the column and then add the comment.


问:
iOS dragging UIImageView
Ok, so I have always wondered how do I actually pick up an image view and drag it. I was planning when I drag an image view and when user places it to correct location it locks there. I really don't have idea how to do this and it has bothered me for sometime.

Thanks so much in advance!

答:
I already worked with this, but the user can drag imageview freely with position that they want. and this is my custom class with swift

```<code>class DraggableImageView: UIImageView {
      var beganPoint: CGPoint? = nil
      var originCenter: CGPoint? = nil
      override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
           if let position = touches.first?.location(in: superview){
                beganPoint = position
                originCenter = center
           }
      }
      override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
      }
      override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
           if let position = touches.first?.location(in: superview){
                let newPosition = CGPoint(x: position.x - (beganPoint?.x)!, y: position.y - (beganPoint?.y)!)
                center = CGPoint(x: (originCenter?.x)! + newPosition.x, y: (originCenter?.y)! + newPosition.y)
           }
      }
}
</code>```

Just user this custom class with your UIImageView

Title: iOS dragging UIImageView

Body:
I already worked with this, but the user can drag imageview freely with position that they want. and this is my custom class with swift

class DraggableImageView: UIImageView {
      var beganPoint: CGPoint? = nil
      var originCenter: CGPoint? = nil
      override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
           if let position = touches.first?.location(in: superview){
                beganPoint = position
                originCenter = center
           }
      }
      override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
      }
      override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
           if let position = touches.first?.location(in: superview){
                let newPosition = CGPoint(x: position.x - (beganPoint?.x)!, y: position.y - (beganPoint?.y)!)
                center = CGPoint(x: (originCenter?.x)! + newPosition.x, y: (originCenter?.y)! + newPosition.y)
           }
      }
}

Just user this custom class with your UIImageView


问:
How to customize/style woocommerce account page
As you can see here: https://wildlatina.com/my-account/

the white body is not inside the page and there is not margin padding for the login form? what did I do to mess this up? I'm a beginner when it comes to editing with css so please go easy on me. Just would like the account page to look nice.

答:
hi please login to your cpanel or ftp then open your theme style.css

find the css rule below

```<code>.full-width-content .container.grid-container {
  max-width: 100%;
}
</code>```

and comment the rule like this

```<code>.full-width-content .container.grid-container {
  /*max-width: 100%;*/
}
</code>```

and it will look like this

Body:
hi please login to your cpanel or ftp then open your theme style.css

find the css rule below

.full-width-content .container.grid-container {
  max-width: 100%;
}

and comment the rule like this

.full-width-content .container.grid-container {
  /*max-width: 100%;*/
}

and it will look like this


问:
How to Find All TRUE Conditions and Concatenate Corresponding Variables into New Variable?
```<code>a = 4
b = 5
c = 7

if (a >= 4){
    text1 = “a is high”;
}
if (b >= 8){
    text2 = “b is high”;
}
if (c >= 6){
    text3 = “c is high”;
}
</code>```

In C or C++, how would I find which of these statements are true (a & c) and create a new variable that concatenates their accompanying variables containing text to produce a result like “a is high and c is high”? The next time the code executes it may find that only a is high, or whatever the case may be.  How would I go about doing this?

答:
create a temporary variable as result.</p>

```<code>a = 4
b = 5
c = 7
result="";

if (a >= 4){
    result += “a is high”;
}
if (b >= 8){
    if(result==""){
        result += “b is high”;
    }else{
        result += “and b is high”;
    }
}
if (c <= 6){
    if(result==""){
        result += “c is high”;
    }else{
        result += “and c is high”;
    }
}
text1=result
</code>```

Body:
a = 4
b = 5
c = 7

if (a >= 4){
    text1 = “a is high”;
}
if (b >= 8){
    text2 = “b is high”;
}
if (c >= 6){
    text3 = “c is high”;
}

In C or C++, how would I find which of these statements are true (a & c) and create a new variable that concatenates their accompanying variables containing text to produce a result like “a is high and c is high”? The next time the code executes it may find that only a is high, or whatever the case may be.  How would I go about doing this?

Body:
create a temporary variable as result.

a = 4
b = 5
c = 7
result="";

if (a >= 4){
    result += “a is high”;
}
if (b >= 8){
    if(result==""){
        result += “b is high”;
    }else{
        result += “and b is high”;
    }
}
if (c <= 6){
    if(result==""){
        result += “c is high”;
    }else{
        result += “and c is high”;
    }
}
text1=result


问:
A problem connecting to a MySQL DB using JDBC
Here's how I'm trying to connect:

```<code>try {
   Class.forName("com.mysql.jdbc.Driver").newInstance();
   } catch (Exception e) {
      throw new DbConnectionException();
   }
   try {
      connection = DriverManager.getConnection(url,username,password);
   } catch (SQLException e) {
      e.printStackTrace();
      throw new DbConnectionException();
   }
</code>```

I'm 100% sure that the url, username, password strings are correct. I've already connected successfully using an external tool (MySQL query browser).
This is the error I receive:

com.mysql.jdbc.CommunicationsException:
  Communications link failure due to
  underlying exception:

** BEGIN NESTED EXCEPTION **

java.net.SocketException MESSAGE:
  java.net.ConnectException: Connection
  refused

...

答:
did you run the mysql browser from the same machine where the code is running?  What I am getting at is the permissions in mysql can be host-specific, and depending on how you set them up you might not be able to connect from the machine where the code is running.

Also, you  might want to double check the url, name, pword again, perhaps with log statements or a debugger to make sure there are no typos, trailing whitespaces, etc...

Body:
Here's how I'm trying to connect:

try {
   Class.forName("com.mysql.jdbc.Driver").newInstance();
   } catch (Exception e) {
      throw new DbConnectionException();
   }
   try {
      connection = DriverManager.getConnection(url,username,password);
   } catch (SQLException e) {
      e.printStackTrace();
      throw new DbConnectionException();
   }

I'm 100% sure that the url, username, password strings are correct. I've already connected successfully using an external tool (MySQL query browser).
This is the error I receive:

com.mysql.jdbc.CommunicationsException:
  Communications link failure due to
  underlying exception:

** BEGIN NESTED EXCEPTION **

java.net.SocketException MESSAGE:
  java.net.ConnectException: Connection
  refused

...