问:
Implement OnItemLongClickLister in RecyclerView
i am working on one project in which i have used open source code, but at one point i am stuck, in this code i am using RecyclerView in which onRecycleItemClickListener is already implemented but now i need to implement onItemLongClickListener in existing code</p>

```<code>public abstract class BaseRecyclerViewAdapter<T, VH extends BaseClickListenerViewHolder> extends RecyclerView.Adapter<VH> {

private List<T> objectsList;
protected final BaseActivity baseActivity;
protected final LayoutInflater layoutInflater;
protected final Resources resources;
protected QBUser currentQbUser;

// Package private because we need access in BaseViewHolder but not in child classes
OnRecycleItemClickListener<T> onRecycleItemClickListener;
AdapterView.OnItemLongClickListener onItemLongClickListener;

public BaseRecyclerViewAdapter(BaseActivity baseActivity) {
    this.baseActivity = baseActivity;
    this.layoutInflater = LayoutInflater.from(baseActivity);
    resources = baseActivity.getResources();
    objectsList = new ArrayList<>();
}

public BaseRecyclerViewAdapter(BaseActivity baseActivity, List<T> objectsList) {
    this(baseActivity);
    this.objectsList = objectsList;
    currentQbUser = AppSession.getSession().getUser();
}

public void setList(List<T> items) {
    objectsList = items;
    notifyDataSetChanged();
}

public void addItem(T item) {
    objectsList.add(item);
    notifyItemInserted(objectsList.size() - 1);
}

public void addItem(int position, T item) {
    objectsList.add(position, item);
    notifyItemInserted(position);
}

public void addAll(Collection<T> collection) {
    objectsList.addAll(collection);
    notifyItemRangeChanged(objectsList.size() - collection.size(), collection.size());
}

public void removeItem(int position) {
    objectsList.remove(position);
    notifyItemRemoved(position);
}

public void removeItem(T item) {
    int position = objectsList.indexOf(item);
    if (position != -1) {
        objectsList.remove(item);
        notifyItemRemoved(position);
    }
}

public void clear() {
    objectsList.clear();
    notifyDataSetChanged();
}

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

public T getItem(int position) {
    return objectsList.get(position);
}

public List<T> getAllItems() {
    return objectsList;
}

public boolean isEmpty() {
    return objectsList.size() == 0;
}

public void setOnRecycleItemClickListener(OnRecycleItemClickListener<T> onRecycleItemClickListener) {
    this.onRecycleItemClickListener = onRecycleItemClickListener;
}

protected void displayAvatarImage(String uri, ImageView imageView) {
    ImageLoader.getInstance().displayImage(uri, imageView, ImageLoaderUtils.UIL_USER_AVATAR_DISPLAY_OPTIONS);
}
}
</code>```

答:
You can use this class ItemTouchListenerAdapter in your code to easily add support for both item clicks and long-clicks.

Usage:

```<code>recyclerView.addOnItemTouchListener(new ItemTouchListenerAdapter(recyclerView, this));
</code>```

Code:

```<code>public class ItemTouchListenerAdapter extends GestureDetector.SimpleOnGestureListener implements RecyclerView.OnItemTouchListener {

    public interface RecyclerViewOnItemClickListener {
        void onItemClick(RecyclerView parent, View clickedView, int position);

        void onItemLongClick(RecyclerView parent, View clickedView, int position);
    }

    private RecyclerViewOnItemClickListener listener;
    private RecyclerView recyclerView;
    private GestureDetector gestureDetector;

    public ItemTouchListenerAdapter(RecyclerView recyclerView, RecyclerViewOnItemClickListener listener) {
        if (recyclerView == null || listener == null) {
            throw new IllegalArgumentException("RecyclerView and Listener arguments can not be null");
        }
        this.recyclerView = recyclerView;
        this.listener = listener;
        this.gestureDetector = new GestureDetector(recyclerView.getContext(), this);
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
        gestureDetector.onTouchEvent(motionEvent);
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
    }

    @Override
    public void onShowPress(MotionEvent e) {
        View view = getChildViewUnder(e);
        if (view != null) {
            view.setPressed(true);
        }
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        View view = getChildViewUnder(e);
        if (view == null) return false;

        view.setPressed(false);
        int position = recyclerView.getChildPosition(view);
        listener.onItemClick(recyclerView, view, position);
        return true;
    }

    public void onLongPress(MotionEvent e) {
        View view = getChildViewUnder(e);
        if (view == null) return;
        int position = recyclerView.getChildPosition(view);
        listener.onItemLongClick(recyclerView, view, position);
        view.setPressed(false);
    }

    @Nullable
    private View getChildViewUnder(MotionEvent e) {
        return recyclerView.findChildViewUnder(e.getX(), e.getY());
    }
}
</code>```

Body:
i am working on one project in which i have used open source code, but at one point i am stuck, in this code i am using RecyclerView in which onRecycleItemClickListener is already implemented but now i need to implement onItemLongClickListener in existing code

public abstract class BaseRecyclerViewAdapter<T, VH extends BaseClickListenerViewHolder> extends RecyclerView.Adapter<VH> {

private List<T> objectsList;
protected final BaseActivity baseActivity;
protected final LayoutInflater layoutInflater;
protected final Resources resources;
protected QBUser currentQbUser;

// Package private because we need access in BaseViewHolder but not in child classes
OnRecycleItemClickListener<T> onRecycleItemClickListener;
AdapterView.OnItemLongClickListener onItemLongClickListener;

public BaseRecyclerViewAdapter(BaseActivity baseActivity) {
    this.baseActivity = baseActivity;
    this.layoutInflater = LayoutInflater.from(baseActivity);
    resources = baseActivity.getResources();
    objectsList = new ArrayList<>();
}

public BaseRecyclerViewAdapter(BaseActivity baseActivity, List<T> objectsList) {
    this(baseActivity);
    this.objectsList = objectsList;
    currentQbUser = AppSession.getSession().getUser();
}

public void setList(List<T> items) {
    objectsList = items;
    notifyDataSetChanged();
}

public void addItem(T item) {
    objectsList.add(item);
    notifyItemInserted(objectsList.size() - 1);
}

public void addItem(int position, T item) {
    objectsList.add(position, item);
    notifyItemInserted(position);
}

public void addAll(Collection<T> collection) {
    objectsList.addAll(collection);
    notifyItemRangeChanged(objectsList.size() - collection.size(), collection.size());
}

public void removeItem(int position) {
    objectsList.remove(position);
    notifyItemRemoved(position);
}

public void removeItem(T item) {
    int position = objectsList.indexOf(item);
    if (position != -1) {
        objectsList.remove(item);
        notifyItemRemoved(position);
    }
}

public void clear() {
    objectsList.clear();
    notifyDataSetChanged();
}

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

public T getItem(int position) {
    return objectsList.get(position);
}

public List<T> getAllItems() {
    return objectsList;
}

public boolean isEmpty() {
    return objectsList.size() == 0;
}

public void setOnRecycleItemClickListener(OnRecycleItemClickListener<T> onRecycleItemClickListener) {
    this.onRecycleItemClickListener = onRecycleItemClickListener;
}

protected void displayAvatarImage(String uri, ImageView imageView) {
    ImageLoader.getInstance().displayImage(uri, imageView, ImageLoaderUtils.UIL_USER_AVATAR_DISPLAY_OPTIONS);
}
}

Body:
You can use this class ItemTouchListenerAdapter in your code to easily add support for both item clicks and long-clicks.

Usage:

recyclerView.addOnItemTouchListener(new ItemTouchListenerAdapter(recyclerView, this));

Code:

public class ItemTouchListenerAdapter extends GestureDetector.SimpleOnGestureListener implements RecyclerView.OnItemTouchListener {

    public interface RecyclerViewOnItemClickListener {
        void onItemClick(RecyclerView parent, View clickedView, int position);

        void onItemLongClick(RecyclerView parent, View clickedView, int position);
    }

    private RecyclerViewOnItemClickListener listener;
    private RecyclerView recyclerView;
    private GestureDetector gestureDetector;

    public ItemTouchListenerAdapter(RecyclerView recyclerView, RecyclerViewOnItemClickListener listener) {
        if (recyclerView == null || listener == null) {
            throw new IllegalArgumentException("RecyclerView and Listener arguments can not be null");
        }
        this.recyclerView = recyclerView;
        this.listener = listener;
        this.gestureDetector = new GestureDetector(recyclerView.getContext(), this);
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
        gestureDetector.onTouchEvent(motionEvent);
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
    }

    @Override
    public void onShowPress(MotionEvent e) {
        View view = getChildViewUnder(e);
        if (view != null) {
            view.setPressed(true);
        }
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        View view = getChildViewUnder(e);
        if (view == null) return false;

        view.setPressed(false);
        int position = recyclerView.getChildPosition(view);
        listener.onItemClick(recyclerView, view, position);
        return true;
    }

    public void onLongPress(MotionEvent e) {
        View view = getChildViewUnder(e);
        if (view == null) return;
        int position = recyclerView.getChildPosition(view);
        listener.onItemLongClick(recyclerView, view, position);
        view.setPressed(false);
    }

    @Nullable
    private View getChildViewUnder(MotionEvent e) {
        return recyclerView.findChildViewUnder(e.getX(), e.getY());
    }
}


来源: stackexchange

问:
Using C# Pointers
How does c# makes use of pointers? If C# is a managed language and the garbage collector does a good job at preventing memory leaks and freeing up memory properly, then what is the effect of using pointers in c# and how "unsafe" are they?

答: C# supports pointers in a limited way. In C# pointer can only be declared to hold the memory address of value types and arrays. Unlike reference types, pointer types are not tracked by the default garbage collection mechanism. Pointers are also not allowed to point to a reference type or even to a structure type which contains a reference type. So, in pure C#, they have rather limited uses. If used in 'unsafe' code, they would be considered pretty unsafe (of course!).</p>

ContentLicense: CC BY-SA 3.0

Title: Using C# Pointers

ContentLicense: CC BY-SA 2.5


问:
Glob doesn't return results
I'm probably doing something wrong but I can't find what.

Here is the code that works:

```<code>foreach (glob('uploads/'.$userid.'[*') as $file)
{
  echo $file."<br>";
}
</code>```

And here what I am trying to make it work but it doesn't:

```<code>foreach (glob('uploads/'.$userid.'[?]('.$id.')*') as $file)
{
  echo $file."<br>";
}
</code>```

Some file examples:

```<code>uploads/24[3](30) Random name.pdf
uploads/24[1](114) Random name.pdf
uploads/24[2](55) Random name.doc
etc etc
</code>```

Basically: UserID[1-3](ID) name of the file

答:
glob function :

The glob() function searches for all the pathnames matching pattern
  according to the rules used by the libc glob() function, which is
  similar to the rules used by common shells.

you need to escape your brackets and parentheses as follows :

```<code>foreach (glob('uploads/'.$userid.'\[?\]\(' . $id . '\)*') as $file) {
    echo $file."<br />";
}
</code>```

Title: Glob doesn't return results

Body:
I'm probably doing something wrong but I can't find what.

Here is the code that works:

foreach (glob('uploads/'.$userid.'[*') as $file)
{
  echo $file."
";
}

And here what I am trying to make it work but it doesn't:

foreach (glob('uploads/'.$userid.'[?]('.$id.')*') as $file)
{
  echo $file."
";
}

Some file examples:

uploads/24[3](30) Random name.pdf
uploads/24[1](114) Random name.pdf
uploads/24[2](55) Random name.doc
etc etc

Basically: UserID[1-3](ID) name of the file

Body:
glob function :

The glob() function searches for all the pathnames matching pattern
  according to the rules used by the libc glob() function, which is
  similar to the rules used by common shells.

you need to escape your brackets and parentheses as follows :

foreach (glob('uploads/'.$userid.'\[?\]\(' . $id . '\)*') as $file) {
    echo $file."<br />";
}


问:
I want to make a plot in R with ggplot but it gives me a value
I'm trying to make a barplot with ggplot2. This is the dataset (Error should be in the x, and cantidad as y):

When I run this:

```<code>grafico <- ggplot(tipoerror, aes(x = Error, y = Cantidad))
</code>```

I have no plot in the plots section. I have a new value in the environment instead.

Can you help me to see what I'm doing wrong?

答:
There are several minor/beginners errors (most of them already mentioned in other comments or answers) which add up:

In the call to aes the parameter y = Cantidad is written with a capital C while the image shows the header uses lower case c.

The created ggplot object is missing a layer, i.e, ggplot doesn't know what to plot.

The ggplot object grafico was created but not printed. This is why a new object appears in the Environment pane of RStudio but the plot is not shown in the Plots pane.

Please, try:

```<code>library(ggplot2)
grafico <- ggplot(tipoerror, aes(x = Error, y = cantidad)) +
  geom_col()
grafico
</code>```

to produce this chart:

Data

As the OP failed to provide data in a reproducible format, I had to make up some sample data

```<code>tipoerror <- data.frame(
  Error = c(NA, LETTERS[1:9]),
  cantidad = c(309, 149, 91, 80, 79, 42, 39, 22,  5,  3)
)
</code>```

where the letters replace the error messages.

Body:
I'm trying to make a barplot with ggplot2. This is the dataset (Error should be in the x, and cantidad as y):

When I run this:

grafico <- ggplot(tipoerror, aes(x = Error, y = Cantidad))

I have no plot in the plots section. I have a new value in the environment instead.

Can you help me to see what I'm doing wrong?

Body:
There are several minor/beginners errors (most of them already mentioned in other comments or answers) which add up:

In the call to aes the parameter y = Cantidad is written with a capital C while the image shows the header uses lower case c.

The created ggplot object is missing a layer, i.e, ggplot doesn't know what to plot.

The ggplot object grafico was created but not printed. This is why a new object appears in the Environment pane of RStudio but the plot is not shown in the Plots pane.

Please, try:

library(ggplot2)
grafico <- ggplot(tipoerror, aes(x = Error, y = cantidad)) +
  geom_col()
grafico

to produce this chart:

Data

As the OP failed to provide data in a reproducible format, I had to make up some sample data

tipoerror <- data.frame(
  Error = c(NA, LETTERS[1:9]),
  cantidad = c(309, 149, 91, 80, 79, 42, 39, 22,  5,  3)
)

where the letters replace the error messages.


问:
Integer.toString(int i) vs String.valueOf(int i) in Java
I am wondering why the method String.valueOf(int i) exists ? I am using this method to convert int into String and just discovered the Integer.toString(int i) method.

After looking the implementation of these methods I saw that the first one is calling the second one. As a consequence all my calls to String.valueOf(int i) involve one more call than directly calling Integer.toString(int i)

答:
There have no differences between Integer.toString(5) and String.valueOf(5);

because String.valueOf returns:

```<code>public static String valueOf(int i) {
    return Integer.toString(i);
}
public static String valueOf(float f) {
    return Float.toString(f);
}
</code>```

etc..

ContentLicense: CC BY-SA 4.0

Body:
There have no differences between Integer.toString(5) and String.valueOf(5);

because String.valueOf returns:

public static String valueOf(int i) {
    return Integer.toString(i);
}
public static String valueOf(float f) {
    return Float.toString(f);
}

etc..


问:
Populate select dropdown if returning with errors
As with my text fields, if an error is returned on the view, I want to populate the select elements with the previously submitted data, like: value="{{ old('element_name_here') }}".

Current view:

```<code><select class="form-control" id="input" name="{{ $questionDetail->question_number }}" required="required">
    <option disabled selected value> -- Select an option --</option>
        @foreach($answers as $answer)
            <option value="{{ $answer->value }}">{{ $answer->question }}</option>
        @endforeach
</select>
</code>```

How can I implement it into the above scenario, as there doesn't seem to be a place where I can add a value without overwriting one? Thank you.

答:
```<code><option
    value="{{ $answer->value }}"
    {{ $answer->value == old(questionDetail->question_number) ? 'selected' : '' }}>
        {{ $answer->question }}
</option>
</code>```

You can remove 'selected' from the first option. It will be selected by default because it's the first. if old() exists, then it will do the check.

Body:
As with my text fields, if an error is returned on the view, I want to populate the select elements with the previously submitted data, like: value="{{ old('element_name_here') }}".

Current view:

<select class="form-control" id="input" name="{{ $questionDetail->question_number }}" required="required">
    <option disabled selected value> -- Select an option --</option>
        @foreach($answers as $answer)
            <option value="{{ $answer->value }}">{{ $answer->question }}</option>
        @endforeach
</select>

How can I implement it into the above scenario, as there doesn't seem to be a place where I can add a value without overwriting one? Thank you.

Body:
<option
    value="{{ $answer->value }}"
    {{ $answer->value == old(questionDetail->question_number) ? 'selected' : '' }}>
        {{ $answer->question }}
</option>

You can remove 'selected' from the first option. It will be selected by default because it's the first. if old() exists, then it will do the check.


问:
Random unique string against a blacklist
I want to create a random string of a fixed length (8 chars in my use case) and the generated string has to be case sensitive and unique against a blacklist. I know this sounds like a UUID but I have a specific requirement that prevents me from utilizing them

some characters are disallowed, i.e. I, l and 1 are lookalikes, and O and 0 as well

My initial implementation is solid and solves the task but performs poorly. And by poorly I mean it is doomed to be slower and slower every day.

This is my current implementation I want to optimize:

```<code>private function uuid()
{
    $chars = 'ABCDEFGHJKLMNPQRSTVUWXYZabcdefghijkmnopqrstvuwxyz23456789';

    $uuid = null;
    while (true) {
        $uuid = substr(str_shuffle($chars), 0, 8);

        if (null === DB::table('codes')->select('id')->whereRaw('BINARY uuid = ?', [$uuid])->first())) {
            break;
        }
    }

    return $uuid;
}
</code>```

Please spare me the critique, we live in an agile world and this implementation is functional and is quick to code.

With a small set of data it works beautifully. However if I have 10 million entries in the blacklist and try to create 1000 more it fails flat as it takes 30+ minutes.

A real use case would be to have 10+ million entries in the DB and to attempt to create 20 thousand new unique codes.

I was thinking of pre-seeding all allowed values but this would be insane:
(24+24+8)^8 = 9.6717312e+13

It would be great if the community can point me in the right direction.

Best,
Nikola

答:
Two options:

Just use a hash of something unique, and truncate so it fits in the bandwidth of your identifier.  Hashes sometimes collide, so you will still need to check the database and retry if a code is already in use.

```<code>s = "This is a string that uniquely identifies voucher #1.  Blah blah."
h = hash(s)
guid = truncate(hash)
</code>```

Generate five of the digits from an incrementing counter and three randomly.  A thief will have a worse than 1 in 140,000 chance of guessing a code, depending on your character set.

```<code>u = Db.GetIncrementingCounter()
p = Random.GetCharacters(3)
guid = u + p
</code>```

Body:
I want to create a random string of a fixed length (8 chars in my use case) and the generated string has to be case sensitive and unique against a blacklist. I know this sounds like a UUID but I have a specific requirement that prevents me from utilizing them

some characters are disallowed, i.e. I, l and 1 are lookalikes, and O and 0 as well

My initial implementation is solid and solves the task but performs poorly. And by poorly I mean it is doomed to be slower and slower every day.

This is my current implementation I want to optimize:

private function uuid()
{
    $chars = 'ABCDEFGHJKLMNPQRSTVUWXYZabcdefghijkmnopqrstvuwxyz23456789';

    $uuid = null;
    while (true) {
        $uuid = substr(str_shuffle($chars), 0, 8);

        if (null === DB::table('codes')->select('id')->whereRaw('BINARY uuid = ?', [$uuid])->first())) {
            break;
        }
    }

    return $uuid;
}

Please spare me the critique, we live in an agile world and this implementation is functional and is quick to code.

With a small set of data it works beautifully. However if I have 10 million entries in the blacklist and try to create 1000 more it fails flat as it takes 30+ minutes.

A real use case would be to have 10+ million entries in the DB and to attempt to create 20 thousand new unique codes.

I was thinking of pre-seeding all allowed values but this would be insane:
(24+24+8)^8 = 9.6717312e+13

It would be great if the community can point me in the right direction.

Best,
Nikola

Body:
Two options:

Just use a hash of something unique, and truncate so it fits in the bandwidth of your identifier.  Hashes sometimes collide, so you will still need to check the database and retry if a code is already in use.

s = "This is a string that uniquely identifies voucher #1.  Blah blah."
h = hash(s)
guid = truncate(hash)

Generate five of the digits from an incrementing counter and three randomly.  A thief will have a worse than 1 in 140,000 chance of guessing a code, depending on your character set.

u = Db.GetIncrementingCounter()
p = Random.GetCharacters(3)
guid = u + p


问:
Pandas Dataframe: Split a column into multiple columns
I have a pandas dataframe with columns names as: (columns type as Object)

```<code>1. x_id
2. y_id
3. Sentence1
4. Sentences2
5. Label
</code>```

I want to separate sentences1 and sentence2 into multiple columns in same dataframe.

Here is an example: dataframe names as df

```<code>x_id     y_id     Sentence1          Sentence2          Label
0        2        This is a ball     I hate you         0
1        5        I am a boy         Ahmed Ali          1
2        1        Apple is red       Rose is red        1
3        9        I love you so much Me too             1
</code>```

After splitting the columns[Sentence1,Sentence2] by ' ' Space, dataframe looks like:

```<code>x_id     y_id     1     2     3    4     5      6      7     8      Label
0        2        This  is    a    ball  NONE   I      hate  you    0
1        5        I     am    a    boy   NONE   Ahmed  Ali   NONE   1
2        1        Apple is    red  NONE  NONE   Rose   is    red    1
3        9        I     love  you  so    much   Me     too   NONE   1
</code>```

How to split the columns like this in python? How to do this using pandas dataframe?

答:
Here is how to do it for the sentences in the column Sentence1. The idea is identical for the Sentence2 column.

```<code>splits = df.Sentence1.str.split(' ')
longest = splits.apply(len).max()
</code>```

Note that longest is the length of the longest sentence. Now make the Null columns:

```<code>for j in range(1,longest+1):
    df[str(j)] = np.nan
</code>```

And finally, go through the splitted values and assign them:

```<code>for j in splits.values:
    for k in range(1,longest+1):
        try:
            df.loc[str(j), k] = j[k]
        except:
            pass
</code>```

`

Body:
I have a pandas dataframe with columns names as: (columns type as Object)

1. x_id
2. y_id
3. Sentence1
4. Sentences2
5. Label

I want to separate sentences1 and sentence2 into multiple columns in same dataframe.

Here is an example: dataframe names as df

x_id     y_id     Sentence1          Sentence2          Label
0        2        This is a ball     I hate you         0
1        5        I am a boy         Ahmed Ali          1
2        1        Apple is red       Rose is red        1
3        9        I love you so much Me too             1

After splitting the columns[Sentence1,Sentence2] by ' ' Space, dataframe looks like:

x_id     y_id     1     2     3    4     5      6      7     8      Label
0        2        This  is    a    ball  NONE   I      hate  you    0
1        5        I     am    a    boy   NONE   Ahmed  Ali   NONE   1
2        1        Apple is    red  NONE  NONE   Rose   is    red    1
3        9        I     love  you  so    much   Me     too   NONE   1

How to split the columns like this in python? How to do this using pandas dataframe?

Body:
Here is how to do it for the sentences in the column Sentence1. The idea is identical for the Sentence2 column.

splits = df.Sentence1.str.split(' ')
longest = splits.apply(len).max()

Note that longest is the length of the longest sentence. Now make the Null columns:

for j in range(1,longest+1):
    df[str(j)] = np.nan

And finally, go through the splitted values and assign them:

for j in splits.values:
    for k in range(1,longest+1):
        try:
            df.loc[str(j), k] = j[k]
        except:
            pass

`


答:
You need to mark previous value as selected so something like this should work:

```<code><select class="form-control" id="input" name="{{ $questionDetail->question_number }}" required="required">
    <option disabled @if(!old($questionDetail->question_number)) selected @endif value> -- Select an option --</option>
        @foreach($answers as $answer)
            <option value="{{ $answer->value }}" @if(old($questionDetail->question_number) == $answer->value) selected @endif>{{ $answer->question }}</option>
        @endforeach
</select>
</code>```

Probably when working a lot with forms it's a good idea to use https://laravelcollective.com/docs/5.3/html (branch 5.4)

Title: Populate select dropdown if returning with errors

Body:
You need to mark previous value as selected so something like this should work:

<select class="form-control" id="input" name="{{ $questionDetail->question_number }}" required="required">
    <option disabled @if(!old($questionDetail->question_number)) selected @endif value> -- Select an option --</option>
        @foreach($answers as $answer)
            <option value="{{ $answer->value }}" @if(old($questionDetail->question_number) == $answer->value) selected @endif>{{ $answer->question }}</option>
        @endforeach
</select>

Probably when working a lot with forms it's a good idea to use https://laravelcollective.com/docs/5.3/html (branch 5.4)


问:
AngularJS - Uncaught Error: [$injector:modulerr] when trying to combine modules
I'm trying learn angular by using multiple modules for a html page. One module for routing and the others for displaying content.

For example, here i have 3 modules in app.js. I have routeApp for the routes, comentUpp for displaying content. and combineApp to combine everything.

var routeApp = angular.module('routeApp',['ngRoute']);
routeApp.config(function($routeProvider){
  $routeProvider
    .when('/', {
      templateUrl : 'views/comment.php',
    });
});
var commentUpp = angular.module('commentUpp',['mainCtrl', 'commentService']);
var combineApp = angular.module('combineApp',['routeApp','commentUpp'])```
</div>
</div>
</p>

<p>and in index.php i have it like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><!DOCTYPE html>
    <html ng-app="combineApp" >
    <head>
      <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
      <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />

      <!-- SPELLS -->
      <!-- load angular and angular route via CDN -->
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular.min.js"></script>
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-resource.min.js"></script>
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.3/angular-route.min.js"> </script>
     <script src="js/app.js"></script>

      <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    </head>
    <body  >

        <!-- HEADER AND NAVBAR -->
        <header>
            <nav class="navbar navbar-default">
            <div class="container">
                <div class="navbar-header">
                    Angular Routing Example
                </div>

                <ul class="nav navbar-nav navbar-right">
                    <li><i class="fa fa-home"></i> Home</li>
                    <li><i class="fa fa-shield"></i> About</li>
                    <li><i class="fa fa-comment"></i> Contact</li>
                </ul>
            </div>
            </nav>
        </header>

        <!-- MAIN CONTENT AND INJECTED VIEWS -->
        <div id="main" >
          <div ng-view></div>

        </div>

    </body>
    </html></code>```

As you can see i'm trying to inject comment.php into index.php.
below is my comment.php

Laravel and Angular Single Page Application

Commenting System

      <form ng-submit="submitComment()">

              <input type="text" class="form-control input-sm" name="author" ng-model="commentData.author" placeholder="Name">

              <input type="text" class="form-control input-lg" name="comment" ng-model="commentData.text" placeholder="Say what you have to say">

              <button type="submit" class="btn btn-primary btn-lg">Submit</button>

      </form>

Comment #{{ comment.id }} by {{ comment.author }}

{{ comment.text }}

Delete

```

for some reason it shows

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.3/$injector/modulerr?p0=combineApp&p1=Error…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.3%2Fangular.min.js%3A22%3A179)

any idea on how to fix this? thanks

答:
You don't need a separate Module to have mainCtrl and commentService injected, you need to inject the commentService to your mainCtrl,

```<code> var commentUpp = angular.module('commentUpp',[]);
</code>```

then

```<code>var combineApp = angular.module('combineApp',['routeApp','commentUpp'])
</code>```

Body:
I'm trying learn angular by using multiple modules for a html page. One module for routing and the others for displaying content.

For example, here i have 3 modules in app.js. I have routeApp for the routes, comentUpp for displaying content. and combineApp to combine everything.

var routeApp = angular.module('routeApp',['ngRoute']);
routeApp.config(function($routeProvider){
  $routeProvider
    .when('/', {
      templateUrl : 'views/comment.php',
    });
});
var commentUpp = angular.module('commentUpp',['mainCtrl', 'commentService']);
var combineApp = angular.module('combineApp',['routeApp','commentUpp'])

and in index.php i have it like this:

<!DOCTYPE html>

      <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
      <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />

                    Angular Routing Example

 Home

 About

 Contact

As you can see i'm trying to inject comment.php into index.php.
below is my comment.php

Laravel and Angular Single Page Application

Commenting System

      <form ng-submit="submitComment()">

              <input type="text" class="form-control input-sm" name="author" ng-model="commentData.author" placeholder="Name">

              <input type="text" class="form-control input-lg" name="comment" ng-model="commentData.text" placeholder="Say what you have to say">

              <button type="submit" class="btn btn-primary btn-lg">Submit</button>

      </form>

Comment #{{ comment.id }} by {{ comment.author }}

{{ comment.text }}

Delete

for some reason it shows

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.3/$injector/modulerr?p0=combineApp&p1=Error…ogleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.6.3%2Fangular.min.js%3A22%3A179)

any idea on how to fix this? thanks

Body:
You don't need a separate Module to have mainCtrl and commentService injected, you need to inject the commentService to your mainCtrl,

 var commentUpp = angular.module('commentUpp',[]);

then

var combineApp = angular.module('combineApp',['routeApp','commentUpp'])


问:
Don't re-add mapview after is loaded in viewdidload
I have created function caricamappa() to loading map view with my mapbox map, and into Custompointannotation there is a control for add and remove annotation with Bool control, with a button i want to caricamappa() add and remove annotation with force Bool and its work but i don't want to re-add subview(mapview) into my app, is it possible to refresh a view without adding another and hide/show annotation? thanks</p>

```<code>func carica_mappa() {
    // Fill in the next line with your style URL from Mapbox Studio.
    let styleURL = NSURL(string: "mapbox:***")
    let mapView = MGLMapView(frame: view.bounds,
                             styleURL: styleURL as URL?)
    mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    // Set the map’s center coordinate and zoom level.
    mapView.setCenter(CLLocationCoordinate2D(latitude: 44.370417,
                                             longitude: 7.411713),
                      zoomLevel: 13, animated: false)
    view.addSubview(mapView)

    mapView.userTrackingMode = .followWithHeading
    // Set the delegate property of our map view to `self` after instantiating it.
    mapView.delegate = self

    let uno = CustomPointAnnotation(coordinate: CLLocationCoordinate2DMake(44.376362, 7.396907),
                                    title: "**",
                                    subtitle: "**",
                                    controllo: visible)
    // Set the custom `image` and `reuseIdentifier` properties, later used in the `mapView:imageForAnnotation:` delegate method.
    uno.reuseIdentifier = "montagna"
    uno.image = UIImage(named: "montagna")
    if uno.controllo == true {
        mapView.addAnnotation(uno)

    }
    else {
        mapView.removeAnnotation(uno)
    }
}
    func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? {
        if let point = annotation as? CustomPointAnnotation,
            let image = point.image,
            let reuseIdentifier = point.reuseIdentifier {

            if let annotationImage = mapView.dequeueReusableAnnotationImage(withIdentifier: reuseIdentifier) {
                // The annotatation image has already been cached, just reuse it.
                return annotationImage
            } else {
                // Create a new annotation image.
                return MGLAnnotationImage(image: image, reuseIdentifier: reuseIdentifier)
            }
        }

        // Fallback to the default marker image.
        return nil
    }

    func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
        // Always allow callouts to popup when annotations are tapped.
        return true
    }

override func viewDidLoad() {
    super.viewDidLoad()
    carica_mappa()
  }
</code>```

答:
My advice is to split the code to setup the map and the one to add the CustomAnnotationView. CaricaMappa() should only be used to add the map to its superview and called in viewDidLoad(). The code to setup the CustomAnnotation should be in its own method and you can call it on button tap. So you would have something like:  </p>

```<code>func carica_mappa() {
    // Fill in the next line with your style URL from Mapbox Studio.
    let styleURL = NSURL(string: "mapbox:***")
    let mapView = MGLMapView(frame: view.bounds,
                             styleURL: styleURL as URL?)
    mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    // Set the map’s center coordinate and zoom level.
    mapView.setCenter(CLLocationCoordinate2D(latitude: 44.370417,
                                             longitude: 7.411713),
                      zoomLevel: 13, animated: false)
    view.addSubview(mapView)

    mapView.userTrackingMode = .followWithHeading
    // Set the delegate property of our map view to `self` after instantiating it.
    mapView.delegate = self
}

    @IBaction func didPressButton(sender: UIButton) {

          let uno = CustomPointAnnotation(coordinate: CLLocationCoordinate2DMake(44.376362, 7.396907),
                                        title: "**",
                                        subtitle: "**",
                                        controllo: visible)
        // Set the custom `image` and `reuseIdentifier` properties, later used in the `mapView:imageForAnnotation:` delegate method.
        uno.reuseIdentifier = "montagna"
        uno.image = UIImage(named: "montagna")
        if uno.controllo == true {
            mapView.addAnnotation(uno)

        }
        else {
//You might want to check if the annotation exist in the map first.
            mapView.removeAnnotation(uno)
        }
    }
</code>```

Body:
I have created function caricamappa() to loading map view with my mapbox map, and into Custompointannotation there is a control for add and remove annotation with Bool control, with a button i want to caricamappa() add and remove annotation with force Bool and its work but i don't want to re-add subview(mapview) into my app, is it possible to refresh a view without adding another and hide/show annotation? thanks

func carica_mappa() {
    // Fill in the next line with your style URL from Mapbox Studio.
    let styleURL = NSURL(string: "mapbox:***")
    let mapView = MGLMapView(frame: view.bounds,
                             styleURL: styleURL as URL?)
    mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    // Set the map’s center coordinate and zoom level.
    mapView.setCenter(CLLocationCoordinate2D(latitude: 44.370417,
                                             longitude: 7.411713),
                      zoomLevel: 13, animated: false)
    view.addSubview(mapView)

    mapView.userTrackingMode = .followWithHeading
    // Set the delegate property of our map view to `self` after instantiating it.
    mapView.delegate = self

    let uno = CustomPointAnnotation(coordinate: CLLocationCoordinate2DMake(44.376362, 7.396907),
                                    title: "**",
                                    subtitle: "**",
                                    controllo: visible)
    // Set the custom `image` and `reuseIdentifier` properties, later used in the `mapView:imageForAnnotation:` delegate method.
    uno.reuseIdentifier = "montagna"
    uno.image = UIImage(named: "montagna")
    if uno.controllo == true {
        mapView.addAnnotation(uno)

    }
    else {
        mapView.removeAnnotation(uno)
    }
}
    func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? {
        if let point = annotation as? CustomPointAnnotation,
            let image = point.image,
            let reuseIdentifier = point.reuseIdentifier {

            if let annotationImage = mapView.dequeueReusableAnnotationImage(withIdentifier: reuseIdentifier) {
                // The annotatation image has already been cached, just reuse it.
                return annotationImage
            } else {
                // Create a new annotation image.
                return MGLAnnotationImage(image: image, reuseIdentifier: reuseIdentifier)
            }
        }

        // Fallback to the default marker image.
        return nil
    }

    func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
        // Always allow callouts to popup when annotations are tapped.
        return true
    }

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

Body:
My advice is to split the code to setup the map and the one to add the CustomAnnotationView. CaricaMappa() should only be used to add the map to its superview and called in viewDidLoad(). The code to setup the CustomAnnotation should be in its own method and you can call it on button tap. So you would have something like:

func carica_mappa() {
    // Fill in the next line with your style URL from Mapbox Studio.
    let styleURL = NSURL(string: "mapbox:***")
    let mapView = MGLMapView(frame: view.bounds,
                             styleURL: styleURL as URL?)
    mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    // Set the map’s center coordinate and zoom level.
    mapView.setCenter(CLLocationCoordinate2D(latitude: 44.370417,
                                             longitude: 7.411713),
                      zoomLevel: 13, animated: false)
    view.addSubview(mapView)

    mapView.userTrackingMode = .followWithHeading
    // Set the delegate property of our map view to `self` after instantiating it.
    mapView.delegate = self
}

    @IBaction func didPressButton(sender: UIButton) {

          let uno = CustomPointAnnotation(coordinate: CLLocationCoordinate2DMake(44.376362, 7.396907),
                                        title: "**",
                                        subtitle: "**",
                                        controllo: visible)
        // Set the custom `image` and `reuseIdentifier` properties, later used in the `mapView:imageForAnnotation:` delegate method.
        uno.reuseIdentifier = "montagna"
        uno.image = UIImage(named: "montagna")
        if uno.controllo == true {
            mapView.addAnnotation(uno)

        }
        else {
//You might want to check if the annotation exist in the map first.
            mapView.removeAnnotation(uno)
        }
    }


问:
Angular2 push values to array on checkbox selected
I have a set of checkboxes as following:

            <input type="checkbox" id="checkbox-1" name="hobbies" value="sport"
            class="mdl-checkbox__input">
            Sports

            <input type="checkbox" id="checkbox-2" name="hobbies" value="reading" class="mdl-checkbox__input">
            Reading

            <input type="checkbox" id="checkbox-3" name="hobbies" value="singing"
            class="mdl-checkbox__input">
            Singing

            <input type="checkbox" id="checkbox-4" name="hobbies" value="travelling"
            class="mdl-checkbox__input">
            Travelling

            <input type="checkbox" id="checkbox-5" name="hobbies" value="movies"
            class="mdl-checkbox__input">
            Movies

            <input type="checkbox" id="checkbox-6" name="hobbies" value="cooking"
            class="mdl-checkbox__input">
            Cooking

```

<p>In my component I have an array:</p>

<pre class="lang-html prettyprint-override"><code>hobbies: string[];

constructor(){
  this.hobbies=[];
}
</code>```

I would like to collect all the values which user has checked the checkbox in this array i.e. hobbies=['sport', 'reading'..]. How can I do that?

答:
I would just use ngModel:

```<code>hobbies = {};

constructor() {
}

getHobbies() {
    return Object.entries(this.hobbies).filter(arr => arr[1]).map(arr => arr[0]);
}
</code>```

And in the view:

```<code>  <label><input type="checkbox" [(ngModel)]="hobbies['sport']"/>Sport</label>
  <label><input type="checkbox" [(ngModel)]="hobbies['cooking']"/>Cooking</label>
  <label><input type="checkbox" [(ngModel)]="hobbies['cinema']"/>Cinema</label>

  <br>
  Hobbies:
  <ul>
    <li *ngFor="let hobby of getHobbies()">{{ hobby }}</li>
  </ul>
</code>```

Here's a plunkr illustrating it.

Body:
I have a set of checkboxes as following:

            <input type="checkbox" id="checkbox-1" name="hobbies" value="sport"
            class="mdl-checkbox__input">
            Sports

            <input type="checkbox" id="checkbox-2" name="hobbies" value="reading" class="mdl-checkbox__input">
            Reading

            <input type="checkbox" id="checkbox-3" name="hobbies" value="singing"
            class="mdl-checkbox__input">
            Singing

            <input type="checkbox" id="checkbox-4" name="hobbies" value="travelling"
            class="mdl-checkbox__input">
            Travelling

            <input type="checkbox" id="checkbox-5" name="hobbies" value="movies"
            class="mdl-checkbox__input">
            Movies

            <input type="checkbox" id="checkbox-6" name="hobbies" value="cooking"
            class="mdl-checkbox__input">
            Cooking

In my component I have an array:

hobbies: string[];

constructor(){
  this.hobbies=[];
}

I would like to collect all the values which user has checked the checkbox in this array i.e. hobbies=['sport', 'reading'..]. How can I do that?

Body:
I would just use ngModel:

hobbies = {};

constructor() {
}

getHobbies() {
    return Object.entries(this.hobbies).filter(arr => arr[1]).map(arr => arr[0]);
}

And in the view:

  <label><input type="checkbox" [(ngModel)]="hobbies['sport']"/>Sport</label>
  <label><input type="checkbox" [(ngModel)]="hobbies['cooking']"/>Cooking</label>
  <label><input type="checkbox" [(ngModel)]="hobbies['cinema']"/>Cinema</label>

  <br>
  Hobbies:
  <ul>
    <li *ngFor="let hobby of getHobbies()">{{ hobby }}</li>
  </ul>

Here's a plunkr illustrating it.


问:
Functional way to take element in a list until a limit in Scala
The aim of the method is to take elements in a list until a limit is reached.

e.g.

I've come up with 2 different implementations

```<code>def take(l: List[Int], limit: Int): List[Int] = {
  var sum = 0
  l.takeWhile { e =>
    sum += e
    sum <= limit
  }
}
</code>```

It is straightforward, but a mutable state is used.

```<code>def take(l: List[Int], limit: Int): List[Int] = {
  val summed = l.toStream.scanLeft(0) { case (e, sum) => sum + e }
  l.take(summed.indexWhere(_ > limit) - 1)
}
</code>```

It seems cleaner, but it's more verbose and perhaps less memory efficient because a stream is needed.

Is there a better way ?

答:
A functional way is to use recursive function and make sure it is stack safe.

If you just use basic scala:

```<code>    import scala.annotation.tailrec
    def take(l: List[Int], limit: Int) : List[Int] = {
      @tailrec
      def takeHelper(l:List[Int], limit:Int, r:List[Int]):List[Int] =
        l match {
            case h::t if (h <= limit ) =>  takeHelper(t, limit-h, r:+h)
            case _ =>  r
      }
      takeHelper(l, limit, Nil)
    }
</code>```

If you can use scalaz Trampoline, it is a bit nicer:

```<code>import scalaz._
import scalaz.Scalaz._
import Free._
 def take(l: List[Int], limit: Int): Trampoline[List[Int]] = {

    l match {
      case h :: t if (h <= limit) => suspend(take(t, limit - h)).map(h :: _)

     case _                      => return_(Nil)
    }
  }
  println(take(List(1, 2, 3, 4, 0, 0, 1), 10).run)
  println(take(List.fill(10000)(1), 100000000).run)
</code>```

Body:
The aim of the method is to take elements in a list until a limit is reached.

e.g.

I've come up with 2 different implementations

def take(l: List[Int], limit: Int): List[Int] = {
  var sum = 0
  l.takeWhile { e =>
    sum += e
    sum <= limit
  }
}

It is straightforward, but a mutable state is used.

def take(l: List[Int], limit: Int): List[Int] = {
  val summed = l.toStream.scanLeft(0) { case (e, sum) => sum + e }
  l.take(summed.indexWhere(_ > limit) - 1)
}

It seems cleaner, but it's more verbose and perhaps less memory efficient because a stream is needed.

Is there a better way ?

Body:
A functional way is to use recursive function and make sure it is stack safe.

If you just use basic scala:

    import scala.annotation.tailrec
    def take(l: List[Int], limit: Int) : List[Int] = {
      @tailrec
      def takeHelper(l:List[Int], limit:Int, r:List[Int]):List[Int] =
        l match {
            case h::t if (h <= limit ) =>  takeHelper(t, limit-h, r:+h)
            case _ =>  r
      }
      takeHelper(l, limit, Nil)
    }

If you can use scalaz Trampoline, it is a bit nicer:

import scalaz._
import scalaz.Scalaz._
import Free._
 def take(l: List[Int], limit: Int): Trampoline[List[Int]] = {

    l match {
      case h :: t if (h <= limit) => suspend(take(t, limit - h)).map(h :: _)

     case _                      => return_(Nil)
    }
  }
  println(take(List(1, 2, 3, 4, 0, 0, 1), 10).run)
  println(take(List.fill(10000)(1), 100000000).run)


问:
MongoDb: Combine two find operations together
When I search for documents containing title 'Apple' as such:

db.getCollection('items').find({title: {$regex: 'Apple'}})

The documents with title containing 'Apple' are returned as expected

When I search for documents where priceA is less than priceB as such:

db.getCollection('items').find({"$where":"this.priceA < this.priceB"})

The documents where priceA is less than priceB are returned as expected.

However, when I try to do both together as such:

db.getCollection('items').find({title: {$regex: 'Apple'}},
  {"$where":"this.priceA < this.priceB"})

Only the _id field is returned, and it's really all the documents in my collection and the two filters above are not applied at all:

How do I apply both filters?

答:
Your query is wrong try this. You are passing the second condition wrong in projection method check this out for more details

Mongodb find() method takes 3 arguments

condition:{title: {$regex: 'Apple'},"$where":"this.priceA < this.priceB"}

Projection:

By default t you wont specify any thing in projection it will return you the entire document but if you want only specific details you can pass it like {name:1,email:1}

Options:
sample example is{sort:1,limit:1}

```<code>  db.getCollection('items').find({title: {$regex: 'Apple'},"$where":"this.priceA < this.priceB"}, {})
</code>```

Body:
Your query is wrong try this. You are passing the second condition wrong in projection method check this out for more details

Mongodb find() method takes 3 arguments

condition:{title: {$regex: 'Apple'},"$where":"this.priceA < this.priceB"}

Projection:

By default t you wont specify any thing in projection it will return you the entire document but if you want only specific details you can pass it like {name:1,email:1}

Options:
sample example is{sort:1,limit:1}

  db.getCollection('items').find({title: {$regex: 'Apple'},"$where":"this.priceA < this.priceB"}, {})


问:
AngularJS: How to create routes with ui-router for my application
I have a problem with my a tag - I have a page that present data according to the GET vars.

For example - /foo.php?opt=1 will show table of cities that each one will go to -  /foo.php?city=4 that have table of schools that go to /foo.php?school=4 that show table of students etc..

The problem is that the first time it works - when I choose city it will show me the list of schools and change the url, but when I choose school, it changes the URL but I still see the city table, and only if I press F5 it will show me table students.

This is the code:

odinvite.php:

```<code><?php
if (isset($_GET['city']))
{
    include "odbycity.php";
}
else if (isset($_GET['school']))
{
    include "odbyschool.php";
}
else
{
    include "odshowcities.php";
}
?>
</code>```

odshowcities.php:

```<code><div ng-controller="allcities">

    <button class="btn btn-info" ng-repeat="x in names">
        <a href="/odinvite.php?city={{x.areaid}}">
        {{x.areaname}}</a>
    </button>

</div>
</code>```

odbyschool.php:

```<code><div ng-controller="odbycity">
    <button class="btn btn-info" ng-repeat="x in names">
        <a href="/odinvite.php?school={{x.schoolid}}">
        {{x.school_name}}</a>
    </button>
</div>
</code>```

MyAngular.js:

```<code>var myApp = angular.module('myApp',[]);

myApp.config(function( $locationProvider) {

    $locationProvider.html5Mode(true);
});

myApp.controller ('allcities', function ($scope, $http)
{
    $http.get("fetch_json_sql.php?option=1")
        .then(function (response)
        {
            $scope.names = response.data.result;
        });
    console.log($scope.names);
});

myApp.controller ('odbycity', function ($scope, $http, $location)
{
    $scope.cityid=$location.search().city;
    console.log($scope.cityid);
    $http.get("fetch_json_sql.php?option=2&cityid="+$scope.cityid)
        .then(function (response)
        {
            $scope.names = response.data.result;
        });

});

myApp.controller ('odbyschool', function ($scope, $http ,$location)
{
    $scope.schoolid = $location.search().school;
    console.log($scope.schoolid);
    $http.get("fetch_json_sql.php?option=4&schoolid="+$scope.schoolid)
        .then(function (response)
        {
            $scope.names = response.data.result;
        });

});
</code>```

What can be the problem?

I tried to make 100% change of the URL - link and it didn't work. just changed the URL without redirect.

Thanks!

答:
You should stop rendering your templates with a backend. AngularJS is for SPA. If you need data provided by a backend try to implement an API e.g. a RESTful API. you need to configure your routes for example like in this runnable demo plnkr. It uses ui-router. Please note, this is just a demo. You should be able to put your logic into that prototype. I prepared all routes you need by using some dummy data. Just include your existing API in the controllers and you should be fine.</p>

```<code>var myApp = angular.module("myApp", ['ui.router']);

myApp.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.when("", "/main");

    $stateProvider
        .state("main", {
            url: "/main",
            templateUrl: "main.html"
        })
        .state("main.listSchools", {
            url: "/listSchools/:schoolId",
            templateUrl: "schools.html"
        })
        .state("main.listAreas", {
            url: "/listAreas/:areaId",
            templateUrl: "areas.html"
        });
});

myApp.controller('mainMenuController', function ($scope) {
    $scope.schools = [{
      schoolid: 1,
      name: 'Test School 1'
    },{
      schoolid: 5,
      name: 'Test School 5'
    },{
      schoolid: 11,
      name: 'Test School 11'
    }];
    $scope.areas = [{
      areaid: 3,
      name: 'Test area 3'
    },{
      areaid: 7,
      name: 'Test area 7'
    },{
      areaid: 19,
      name: 'Test area 7'
    }];
});

myApp.controller('listSchoolController', function ($scope, $state) {
  $scope.schoolId = $state.params.schoolId;
});

myApp.controller('listAreaController', function ($scope, $state) {
  $scope.areaId = $state.params.areaId;
});
</code>```

Body:
I have a problem with my a tag - I have a page that present data according to the GET vars.

For example - /foo.php?opt=1 will show table of cities that each one will go to -  /foo.php?city=4 that have table of schools that go to /foo.php?school=4 that show table of students etc..

The problem is that the first time it works - when I choose city it will show me the list of schools and change the url, but when I choose school, it changes the URL but I still see the city table, and only if I press F5 it will show me table students.

This is the code:

odinvite.php:

<?php
if (isset($_GET['city']))
{
    include "odbycity.php";
}
else if (isset($_GET['school']))
{
    include "odbyschool.php";
}
else
{
    include "odshowcities.php";
}
?>

odshowcities.php:

    <button class="btn btn-info" ng-repeat="x in names">

        {{x.areaname}}
    </button>

odbyschool.php:

    <button class="btn btn-info" ng-repeat="x in names">

        {{x.school_name}}
    </button>

MyAngular.js:

var myApp = angular.module('myApp',[]);

myApp.config(function( $locationProvider) {

    $locationProvider.html5Mode(true);
});

myApp.controller ('allcities', function ($scope, $http)
{
    $http.get("fetch_json_sql.php?option=1")
        .then(function (response)
        {
            $scope.names = response.data.result;
        });
    console.log($scope.names);
});

myApp.controller ('odbycity', function ($scope, $http, $location)
{
    $scope.cityid=$location.search().city;
    console.log($scope.cityid);
    $http.get("fetch_json_sql.php?option=2&cityid="+$scope.cityid)
        .then(function (response)
        {
            $scope.names = response.data.result;
        });

});

myApp.controller ('odbyschool', function ($scope, $http ,$location)
{
    $scope.schoolid = $location.search().school;
    console.log($scope.schoolid);
    $http.get("fetch_json_sql.php?option=4&schoolid="+$scope.schoolid)
        .then(function (response)
        {
            $scope.names = response.data.result;
        });

});

What can be the problem?

I tried to make 100% change of the URL - link and it didn't work. just changed the URL without redirect.

Thanks!

Body:
You should stop rendering your templates with a backend. AngularJS is for SPA. If you need data provided by a backend try to implement an API e.g. a RESTful API. you need to configure your routes for example like in this runnable demo plnkr. It uses ui-router. Please note, this is just a demo. You should be able to put your logic into that prototype. I prepared all routes you need by using some dummy data. Just include your existing API in the controllers and you should be fine.

var myApp = angular.module("myApp", ['ui.router']);

myApp.config(function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.when("", "/main");

    $stateProvider
        .state("main", {
            url: "/main",
            templateUrl: "main.html"
        })
        .state("main.listSchools", {
            url: "/listSchools/:schoolId",
            templateUrl: "schools.html"
        })
        .state("main.listAreas", {
            url: "/listAreas/:areaId",
            templateUrl: "areas.html"
        });
});

myApp.controller('mainMenuController', function ($scope) {
    $scope.schools = [{
      schoolid: 1,
      name: 'Test School 1'
    },{
      schoolid: 5,
      name: 'Test School 5'
    },{
      schoolid: 11,
      name: 'Test School 11'
    }];
    $scope.areas = [{
      areaid: 3,
      name: 'Test area 3'
    },{
      areaid: 7,
      name: 'Test area 7'
    },{
      areaid: 19,
      name: 'Test area 7'
    }];
});

myApp.controller('listSchoolController', function ($scope, $state) {
  $scope.schoolId = $state.params.schoolId;
});

myApp.controller('listAreaController', function ($scope, $state) {
  $scope.areaId = $state.params.areaId;
});


问:
Ruby: Avoiding infinite loop in an array that doubles each number
So there is an infinte loop here, but I'm not seeing it.

```<code># Return an array that doubles each number
numbers = [1, 2, 3, 4]
numbers.each do |number|
  numbers << number * 2
end
puts numbers
</code>```

I understand there are shorter ways to do this, but I am learning so it's all written out more explicitly.

答:
You cant see the process since this infinity lasts forever and never reaches your puts numbers statement. Thats why you cant see it in the console.

Try something like:

```<code>numbers = [1, 2, 3, 4]
numbers.each do |number|
  numbers << number * 2
  puts numbers
end
</code>```

To see your pc going mad :)

Body:
So there is an infinte loop here, but I'm not seeing it.

# Return an array that doubles each number
numbers = [1, 2, 3, 4]
numbers.each do |number|
  numbers << number * 2
end
puts numbers

I understand there are shorter ways to do this, but I am learning so it's all written out more explicitly.

Body:
You cant see the process since this infinity lasts forever and never reaches your puts numbers statement. Thats why you cant see it in the console.

Try something like:

numbers = [1, 2, 3, 4]
numbers.each do |number|
  numbers << number * 2
  puts numbers
end

To see your pc going mad :)


问:
How to search string in NSArray of NSObject Swift 3.0?
I am working on UiSearchbar,where if an user type some string, i have to show him the related suggestions. Right now the array is containing data in format like below:

```<code>"Name: Optional(\"2.1 - Classroom\")",
"Name: Optional(\"2.11 - Classroom\")",
"Name: Optional(\"2.22 - Classroom\")",
"Name: Optional(\"2.13 - Classroom\")",
"Name: Optional(\"2.34 - Classroom\")",
"Name: Optional(\"2.55 - Classroom\")"
</code>```

What I want to do is, when an user type 2.1 then i want to suggest him all the names start with 2.1 . I have tried all the suggestions i got from internet. However, i am new to iOS so i can't figure out that how i can do this.
This is my code :

```<code>func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String){
    if searchText.characters.count == 0{
        isSearch = false;
        self.resulttableview.reloadData()
    }else{
        let filtered  = list.filter(){
            return ($0 as AnyObject).contains(searchText) // 2.1 or searchtext
        }
        print(filtered)
    }
}
</code>```

For assigning the array

```<code>func itemsDownloaded(items: NSArray){
    list = items
    self.resulttableview.reloadData()
}
</code>```

And this code is for retrieving data from JSON and store in mutable array :

```<code>func downloadItems(){
    let url = NSURL(string: urlPath)!

    var session: URLSession!
    let configuration = URLSessionConfiguration.default

    session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    let task = session.dataTask(with: url as URL)

    task.resume()
}

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data){
    self.data.append(data);
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?){
    if error != nil{
        print("Failed to download data")
    }else{
        print("Data downloaded")
        self.parseJSON()
    }
}

func parseJSON(){
    var jsonResult: NSMutableArray = NSMutableArray()

    do{
        let jsonResults = try JSONSerialization.jsonObject(with: self.data as Data , options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray
        jsonResult = jsonResults.mutableCopy() as! NSMutableArray
    }catch let error as NSError{
        print(error)
    }

    var jsonElement = NSDictionary()
    let locations: NSMutableArray = NSMutableArray()

    for i in 0 ..< jsonResult.count{
        jsonElement = jsonResult[i] as! NSDictionary
        let location = roommodel()

        if let name = jsonElement["name"] as? String{
            location.name = name
        }

        locations.add(location)
    }

    DispatchQueue.main.async{
        self.delegate.itemsDownloaded(items: locations)
    }

}
</code>```

Thanks in advance

答:
First of all, don't use NSArray and NSMutableArray in Swift code.

For example, location should be declared as:

```<code>var locations: [roommodel] = []
</code>```

and list as

```<code>var list: [roommodel] = []
</code>```

(and you should name classes with camelcase RoomModel).

Then the filtering can be simplified to:

```<code>let filtered = list.filter {
    return ($0.name ?? "").hasPrefix(searchText)
}
</code>```

or, for "contains" search:

```<code>let filtered = list.filter {
    return ($0.name ?? "").range(of: searchText) != nil
}
</code>```

with more complex options:

```<code>let filtered = list.filter {
    return ($0.name ?? "").range(of: searchText, options: [.caseInsensitive, .diacriticsInsensitive]) != nil
}
</code>```

Body:
I am working on UiSearchbar,where if an user type some string, i have to show him the related suggestions. Right now the array is containing data in format like below:

"Name: Optional(\"2.1 - Classroom\")",
"Name: Optional(\"2.11 - Classroom\")",
"Name: Optional(\"2.22 - Classroom\")",
"Name: Optional(\"2.13 - Classroom\")",
"Name: Optional(\"2.34 - Classroom\")",
"Name: Optional(\"2.55 - Classroom\")"

What I want to do is, when an user type 2.1 then i want to suggest him all the names start with 2.1 . I have tried all the suggestions i got from internet. However, i am new to iOS so i can't figure out that how i can do this.
This is my code :

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String){
    if searchText.characters.count == 0{
        isSearch = false;
        self.resulttableview.reloadData()
    }else{
        let filtered  = list.filter(){
            return ($0 as AnyObject).contains(searchText) // 2.1 or searchtext
        }
        print(filtered)
    }
}

For assigning the array

func itemsDownloaded(items: NSArray){
    list = items
    self.resulttableview.reloadData()
}

And this code is for retrieving data from JSON and store in mutable array :

func downloadItems(){
    let url = NSURL(string: urlPath)!

    var session: URLSession!
    let configuration = URLSessionConfiguration.default

    session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    let task = session.dataTask(with: url as URL)

    task.resume()
}

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data){
    self.data.append(data);
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?){
    if error != nil{
        print("Failed to download data")
    }else{
        print("Data downloaded")
        self.parseJSON()
    }
}

func parseJSON(){
    var jsonResult: NSMutableArray = NSMutableArray()

    do{
        let jsonResults = try JSONSerialization.jsonObject(with: self.data as Data , options: JSONSerialization.ReadingOptions.allowFragments) as! NSArray
        jsonResult = jsonResults.mutableCopy() as! NSMutableArray
    }catch let error as NSError{
        print(error)
    }

    var jsonElement = NSDictionary()
    let locations: NSMutableArray = NSMutableArray()

    for i in 0 ..< jsonResult.count{
        jsonElement = jsonResult[i] as! NSDictionary
        let location = roommodel()

        if let name = jsonElement["name"] as? String{
            location.name = name
        }

        locations.add(location)
    }

    DispatchQueue.main.async{
        self.delegate.itemsDownloaded(items: locations)
    }

}

Thanks in advance

Body:
First of all, don't use NSArray and NSMutableArray in Swift code.

For example, location should be declared as:

var locations: [roommodel] = []

and list as

var list: [roommodel] = []

(and you should name classes with camelcase RoomModel).

Then the filtering can be simplified to:

let filtered = list.filter {
    return ($0.name ?? "").hasPrefix(searchText)
}

or, for "contains" search:

let filtered = list.filter {
    return ($0.name ?? "").range(of: searchText) != nil
}

with more complex options:

let filtered = list.filter {
    return ($0.name ?? "").range(of: searchText, options: [.caseInsensitive, .diacriticsInsensitive]) != nil
}


问:
Gray scaling the entire view
I am working on a swift based application which shows some events. Each event has time limit after which event expires.

I want to make the event screen grayscale after event expiration for which I have tried things like:

Mask view

```<code>        if let maskImage = UIImage(named: "MaskImage"){
        myView.maskView = UIImageView(image: maskImage)
    }
</code>```

above solution not worked from me as my event screen contains colored images as well

Recursively fetched all subviews and tried to set their backgroundColor but not worked

Changing alpha value of all subViews which shows more faded white color

Query: My event screen has many colorful images and some colorful labels, how can I make all these in grayscale?

Any help would be appreciated.

答:
After some research I've achieved gray scaling effect over entire view something like this:

```<code>/**
     To convert an image to grayscale

     - parameter image: The UIImage to be converted

     - returns: The UIImage after conversion
     */
    static func convertToGrayScale(_ image: UIImage?) -> UIImage? {
        if image == nil {
            return nil
        }
        let imageRect:CGRect = CGRect(x: 0, y: 0, width: image!.size.width, height: image!.size.height)
        let colorSpace = CGColorSpaceCreateDeviceGray()
        let width = image!.size.width
        let height = image!.size.height

        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
        let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)

        context?.draw(image!.cgImage!, in: imageRect)
        let imageRef = context?.makeImage()
        let newImage = UIImage(cgImage: imageRef!)

        return newImage
    }
</code>```

Here above method will work for all coloured images in presented view and the same can be used for myView.maskView = UIImageView(image: maskImage).

This will grayscale your entire view and while gray scaling only labels and texts I used this:

```<code>// Convert to grayscale
    func convertToGrayScaleColor() -> UIColor? {
        if self == UIColor.clear {
            return UIColor.clear
        }
        var fRed : CGFloat = 0
        var fGreen : CGFloat = 0
        var fBlue : CGFloat = 0
        var fAlpha: CGFloat = 0
        if self.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
            if fRed == 0 && fGreen == 0 && fBlue == 0{
                return  UIColor.gray
            }else{
                let grayScaleColor = (fRed + fGreen + fBlue)/3
                return UIColor(red: grayScaleColor, green: grayScaleColor, blue: grayScaleColor, alpha: fAlpha)
            }
        } else {
            print("Could not extract RGBA components, so rolling back to default UIColor.grayColor()")
            return UIColor.gray
        }
    }
</code>```

Above method is a part extension UIColor. Above code is written in Swift 3.0 using xcode 8.1

Please feel free to drop a comment if concerned or confused about anything in the answer.

Title: Gray scaling the entire view

Body:
I am working on a swift based application which shows some events. Each event has time limit after which event expires.

I want to make the event screen grayscale after event expiration for which I have tried things like:

Mask view

        if let maskImage = UIImage(named: "MaskImage"){
        myView.maskView = UIImageView(image: maskImage)
    }

above solution not worked from me as my event screen contains colored images as well

Recursively fetched all subviews and tried to set their backgroundColor but not worked

Changing alpha value of all subViews which shows more faded white color

Query: My event screen has many colorful images and some colorful labels, how can I make all these in grayscale?

Any help would be appreciated.

Body:
After some research I've achieved gray scaling effect over entire view something like this:

/**
     To convert an image to grayscale

     - parameter image: The UIImage to be converted

     - returns: The UIImage after conversion
     */
    static func convertToGrayScale(_ image: UIImage?) -> UIImage? {
        if image == nil {
            return nil
        }
        let imageRect:CGRect = CGRect(x: 0, y: 0, width: image!.size.width, height: image!.size.height)
        let colorSpace = CGColorSpaceCreateDeviceGray()
        let width = image!.size.width
        let height = image!.size.height

        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
        let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)

        context?.draw(image!.cgImage!, in: imageRect)
        let imageRef = context?.makeImage()
        let newImage = UIImage(cgImage: imageRef!)

        return newImage
    }

Here above method will work for all coloured images in presented view and the same can be used for myView.maskView = UIImageView(image: maskImage).

This will grayscale your entire view and while gray scaling only labels and texts I used this:

// Convert to grayscale
    func convertToGrayScaleColor() -> UIColor? {
        if self == UIColor.clear {
            return UIColor.clear
        }
        var fRed : CGFloat = 0
        var fGreen : CGFloat = 0
        var fBlue : CGFloat = 0
        var fAlpha: CGFloat = 0
        if self.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha) {
            if fRed == 0 && fGreen == 0 && fBlue == 0{
                return  UIColor.gray
            }else{
                let grayScaleColor = (fRed + fGreen + fBlue)/3
                return UIColor(red: grayScaleColor, green: grayScaleColor, blue: grayScaleColor, alpha: fAlpha)
            }
        } else {
            print("Could not extract RGBA components, so rolling back to default UIColor.grayColor()")
            return UIColor.gray
        }
    }

Above method is a part extension UIColor. Above code is written in Swift 3.0 using xcode 8.1

Please feel free to drop a comment if concerned or confused about anything in the answer.


问:
How to separate variables to other files and access
I'm new in swift and IOS, I have no idea to separate the variable(mylessons) to other file(.swift) or (.json) to achieve MVC. Anyone can teach me? Thanks a lot</p>

```<code>class LessonsTableViewController: UITableViewController {

var mylessons = [["title":"Posture", "subtitle":"Set up your body",
"bgimage":"Ln1", "lesimage":"Posture_pic", "lestitle":"So starting from
the head and moving down:", "lescontent":"1) The top back part of your
head should be pointing up.."], ..]

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 150
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
..
}
</code>```

答:
Referring to your given code snippet, for achieving MVC, you should create a model for the lesson -which contains the desired properties-, thus, mylessons array should contains objects of lesson.

If you want to separate the layers in different files (which is a good idea), you might want to create a file -Lesson.swift for example-, which contains your model, as follows:

Lesson.swift:

```<code>// Note that I decalred it as 'struct'
// instead of 'class' do what is suitable
// for your requirements...
struct Lesson {
    var title:String?
    var subtitle: String?
    var bgImage: String?
    var lesImage: String?
    var lesTitle: String?
}
</code>```

ViewController:

```<code>// note that myLessons data type is: '[Lesson]'
var myLessons =  [Lesson(title: "Posture",
                         subtitle: "Set up your body",
                         bgImage: "Ln1",
                         lesImage: "Posture_pic",
                         lesTitle: "So starting from the head and moving down",
                         lesContent: "1) The top back part of your head should be pointing up..")]
</code>```

Remark: if you are implementing tableView:cellForRowAtIndexPath:, you should access the lesson for each row like this:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //....

    let currentLesson = myLessons[indexPath.row]

    // ...
}
</code>```

Also:

It would be nice if you are able to convert the given dictionary to a lesson object, actually it is possible, by adding the following Dictionary Extension:

```<code>extension Dictionary where Key: ExpressibleByStringLiteral, Value: ExpressibleByStringLiteral {
    func toLesson() -> Lesson {
        var lessonToRetrun = Lesson()

        if let title = self["title"] as? String {
            lessonToRetrun.title = title
        }

        if let subtitle = self["subtitle"] as? String {
            lessonToRetrun.subtitle = subtitle
        }

        if let bgimage = self["bgimage"] as? String {
            lessonToRetrun.bgImage = bgimage
        }

        if let lesimage = self["lesimage"] as? String {
            lessonToRetrun.lesImage = lesimage
        }

        if let lestitle = self["lestitle"] as? String {
            lessonToRetrun.lesTitle = lestitle
        }

        if let lescontent = self["lescontent"] as? String {
            lessonToRetrun.lesContent = lescontent
        }

        return lessonToRetrun
    }
}
</code>```

you will be able to do:

```<code>let lessonDict = ["title":"Posture",
                  "subtitle":"Set up your body",
                  "bgimage":"Ln1", "lesimage":"Posture_pic",
                  "lestitle":"So starting from the head and moving down:",
                  "lescontent":"1) The top back part of your head should be pointing up.."]

let convertedLesson = lessonDict.toLesson()

print(convertedLesson)
// Lesson(title: Optional("Posture"), subtitle: Optional("Set up your body"), bgImage: Optional("Ln1"), lesImage: Optional("Posture_pic"), lesTitle: Optional("So starting from the head and moving down:"), lesContent: Optional("1) The top back part of your head should be pointing up.."))
</code>```

but you have to be pretty sure that the keys are identical.

Hope this helped.

Body:
I'm new in swift and IOS, I have no idea to separate the variable(mylessons) to other file(.swift) or (.json) to achieve MVC. Anyone can teach me? Thanks a lot

class LessonsTableViewController: UITableViewController {

var mylessons = [["title":"Posture", "subtitle":"Set up your body",
"bgimage":"Ln1", "lesimage":"Posture_pic", "lestitle":"So starting from
the head and moving down:", "lescontent":"1) The top back part of your
head should be pointing up.."], ..]

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 150
}

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
..
}

Body:
Referring to your given code snippet, for achieving MVC, you should create a model for the lesson -which contains the desired properties-, thus, mylessons array should contains objects of lesson.

If you want to separate the layers in different files (which is a good idea), you might want to create a file -Lesson.swift for example-, which contains your model, as follows:

Lesson.swift:

// Note that I decalred it as 'struct'
// instead of 'class' do what is suitable
// for your requirements...
struct Lesson {
    var title:String?
    var subtitle: String?
    var bgImage: String?
    var lesImage: String?
    var lesTitle: String?
}

ViewController:

// note that myLessons data type is: '[Lesson]'
var myLessons =  [Lesson(title: "Posture",
                         subtitle: "Set up your body",
                         bgImage: "Ln1",
                         lesImage: "Posture_pic",
                         lesTitle: "So starting from the head and moving down",
                         lesContent: "1) The top back part of your head should be pointing up..")]

Remark: if you are implementing tableView:cellForRowAtIndexPath:, you should access the lesson for each row like this:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    //....

    let currentLesson = myLessons[indexPath.row]

    // ...
}

Also:

It would be nice if you are able to convert the given dictionary to a lesson object, actually it is possible, by adding the following Dictionary Extension:

extension Dictionary where Key: ExpressibleByStringLiteral, Value: ExpressibleByStringLiteral {
    func toLesson() -> Lesson {
        var lessonToRetrun = Lesson()

        if let title = self["title"] as? String {
            lessonToRetrun.title = title
        }

        if let subtitle = self["subtitle"] as? String {
            lessonToRetrun.subtitle = subtitle
        }

        if let bgimage = self["bgimage"] as? String {
            lessonToRetrun.bgImage = bgimage
        }

        if let lesimage = self["lesimage"] as? String {
            lessonToRetrun.lesImage = lesimage
        }

        if let lestitle = self["lestitle"] as? String {
            lessonToRetrun.lesTitle = lestitle
        }

        if let lescontent = self["lescontent"] as? String {
            lessonToRetrun.lesContent = lescontent
        }

        return lessonToRetrun
    }
}

you will be able to do:

let lessonDict = ["title":"Posture",
                  "subtitle":"Set up your body",
                  "bgimage":"Ln1", "lesimage":"Posture_pic",
                  "lestitle":"So starting from the head and moving down:",
                  "lescontent":"1) The top back part of your head should be pointing up.."]

let convertedLesson = lessonDict.toLesson()

print(convertedLesson)
// Lesson(title: Optional("Posture"), subtitle: Optional("Set up your body"), bgImage: Optional("Ln1"), lesImage: Optional("Posture_pic"), lesTitle: Optional("So starting from the head and moving down:"), lesContent: Optional("1) The top back part of your head should be pointing up.."))

but you have to be pretty sure that the keys are identical.

Hope this helped.


问:
Kotlin anonymous function use case?
Based on my understanding, anonymous function in Kotlin allow you to specify return type. In addition to that, return statement inside anonymous will exit only the function block, while in lambda it will exit the enclosing function.

Still, I can't imagine what would be the real world use case of anonymous function in Kotlin that lambda syntax cannot provide?

Kotlin Higher Order Function and Lambda

答:
The use case is that sometimes we may wish to be explicit about the return type. In those cases, we can use so called an anonymous function. Example:

```<code>fun(a: String, b: String): String = a + b
</code>```

Or better return control like:

```<code>fun(): Int {
    try {
        // some code
        return result
    } catch (e: SomeException) {
        // handler
        return badResult
        }
}
</code>```

Title: Kotlin anonymous function use case?

Body:
The use case is that sometimes we may wish to be explicit about the return type. In those cases, we can use so called an anonymous function. Example:

fun(a: String, b: String): String = a + b

Or better return control like:

fun(): Int {
    try {
        // some code
        return result
    } catch (e: SomeException) {
        // handler
        return badResult
        }
}


问:
Using C# Pointers
How does c# makes use of pointers? If C# is a managed language and the garbage collector does a good job at preventing memory leaks and freeing up memory properly, then what is the effect of using pointers in c# and how "unsafe" are they?

答:
When using pointers in C# (inside unsafe code blocks), the memory is not managed by the Framework. You are responsible for managing your own memory and cleaning up after yourself.

...therefore, I would consider if fairly "unsafe".

Title: Using C# Pointers


问:
Horizontal Div Scroll
I'm quite new to Jquery, I'm trying to implement horizontal scrolling on a div using the scrollLeft property, I'm not getting any error messages and nothing seems to be working, could someone explain why? Thanks in advance
this is my code:

```
<pre class="snippet-code-css lang-css prettyprint-override"><code><style>
        #container{
            max-width: 938px;
            height: 500px;
            border: 2px solid black;
            margin-left: auto;
            margin-right: auto;
            overflow: scroll;
            /*display: table;*/
        }
        .picsdiv{
            display: table-cell;
            min-width: 286px;
            padding-right: 80px;
            height: 508px;
            border: 2px solid pink;

        }

        .prev, .next {
          cursor: pointer;
          position: absolute;
          top: 250px;
          width: auto;
          margin-top: -22px;
          padding: 16px;
          color: white;
          font-weight: bold;
          font-size: 18px;
          transition: 0.6s ease;
          border-radius: 0 3px 3px 0;
            border: 2px solid pink;
        }

        .next {
          right: 170px;
          border-radius: 3px 0 0 3px;
        }
        .prev{
            left: 170px;
        }

        .prev:hover, .next:hover {
          background-color: rgba(0,0,0,0.8);
        }
    </style></code>```

       ❮
      ❯

```

答: I just added a seperate script tag for the Jquery code and used the first one to only refer to the library and it now works. Thanks for all your help</p>

Title: Horizontal Div Scroll

Body:
I'm quite new to Jquery, I'm trying to implement horizontal scrolling on a div using the scrollLeft property, I'm not getting any error messages and nothing seems to be working, could someone explain why? Thanks in advance
this is my code:

       ❮
      ❯


问:
How to call for a Maven goal within an Ant script?
Is it possible to call or execute a Maven goal within an Ant script?

Say I have an ant target called 'distribute' and inside which I need to call a maven 'compile' goal from another pom.xml.

答:
From Thiagoh answer, I have to add this to make it work.</p>

```<code> <condition property="isWindows">
                    <os family="windows" />
 </condition>

 <condition property="isLinux">
                    <os family="unix" />
 </condition>

<target name="mvn_windows_setup" if="isWindows">
    <property name="mvn.executable" value="cmd" />
    <property name="mvn.args" value="/c" />
</target>

<target name="mvn_unix_setup" if="isLinux">
    <property name="mvn.executable" value="sh" />
    <property name="mvn.args" value="-c" />
</target>

<target name="run-mvn-goals" depends="mvn_windows_setup, mvn_unix_setup">

    <exec dir="${basedir}" executable="${mvn.executable}">
        <arg line="${mvn.args} 'mvn ${p_goals}'" />
    </exec>

</target>
</code>```

Body:
From Thiagoh answer, I have to add this to make it work.

 <condition property="isWindows">
                    <os family="windows" />
 </condition>

 <condition property="isLinux">
                    <os family="unix" />
 </condition>

<target name="mvn_windows_setup" if="isWindows">
    <property name="mvn.executable" value="cmd" />
    <property name="mvn.args" value="/c" />
</target>

<target name="mvn_unix_setup" if="isLinux">
    <property name="mvn.executable" value="sh" />
    <property name="mvn.args" value="-c" />
</target>

<target name="run-mvn-goals" depends="mvn_windows_setup, mvn_unix_setup">

    <exec dir="${basedir}" executable="${mvn.executable}">
        <arg line="${mvn.args} 'mvn ${p_goals}'" />
    </exec>

</target>


问:
Android request ACCESS_NOTIFICATION_POLICY and mute phone
I am a beginner Android developer and I have an interesting question at hand. I am trying to mute the phone with

```<code>AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
</code>```

But I am getting the following error

```<code>java.lang.SecurityException: Not allowed to change Do Not Disturb state
</code>```

Now I do not understand this, as I am using EasyPermissions (https://github.com/googlesamples/easypermissions) and requesting the permission

```<code>Manifest.permission.ACCESS_NOTIFICATION_POLICY
</code>```

But it does not ask me to allow anything on app startup. I figured this is because ACCESS_NOTIFICATION_POLICY is a non dangerous permission and thus granted at installation time, for which I also added it to my manifest.xml as thus

```<code><uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
</code>```

But it is still not working, my app is crashing because it throws the "Not allowed to change to Do Not Disturb state" error. Wierdly I found that I can request to go to the "Do Not Disturb access" screen with the following code

```<code>Intent intent = new Intent(
                    android.provider.Settings
                            .ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
 startActivity(intent);
</code>```

What am I doing wrong here? Why cannot I request this permissions as a normal permission? Do I really have to go through the intent to allow my app to mute the phone?

答:
I will post an answer on how I managed to solve this issue for androids over 23 and under 23 with a startActivityForResult callback

the requestMutePhonePermsAndMutePhone() function is called in the main actions onCreate function.

Mind you the code is very much intrusive, since the Settings menu is permacalled until you accept the Do Not Disturb permissions, but one can easily accomodate this code for their personal needs and maybe build a question prompt, etc...

```<code>private void requestMutePhonePermsAndMutePhone() {
    try {
        if (Build.VERSION.SDK_INT < 23) {
            AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
            audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        } else if( Build.VERSION.SDK_INT >= 23 ) {
            this.requestDoNotDisturbPermissionOrSetDoNotDisturbApi23AndUp();
        }
    } catch ( SecurityException e ) {

    }
}

private void requestDoNotDisturbPermissionOrSetDoNotDisturbApi23AndUp() {
    //TO SUPPRESS API ERROR MESSAGES IN THIS FUNCTION, since Ive no time to figrure our Android SDK suppress stuff
    if( Build.VERSION.SDK_INT < 23 ) {
        return;
    }

    NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    if ( notificationManager.isNotificationPolicyAccessGranted()) {
        AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
        audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
    } else{
        // Ask the user to grant access
        Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
        startActivityForResult( intent, MainActivity.ON_DO_NOT_DISTURB_CALLBACK_CODE );
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == MainActivity.ON_DO_NOT_DISTURB_CALLBACK_CODE ) {
        this.requestDoNotDisturbPermissionOrSetDoNotDisturbApi23AndUp();
    }
}
</code>```

Body:
I am a beginner Android developer and I have an interesting question at hand. I am trying to mute the phone with

AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);

But I am getting the following error

java.lang.SecurityException: Not allowed to change Do Not Disturb state

Now I do not understand this, as I am using EasyPermissions (https://github.com/googlesamples/easypermissions) and requesting the permission

Manifest.permission.ACCESS_NOTIFICATION_POLICY

But it does not ask me to allow anything on app startup. I figured this is because ACCESS_NOTIFICATION_POLICY is a non dangerous permission and thus granted at installation time, for which I also added it to my manifest.xml as thus

<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />

But it is still not working, my app is crashing because it throws the "Not allowed to change to Do Not Disturb state" error. Wierdly I found that I can request to go to the "Do Not Disturb access" screen with the following code

Intent intent = new Intent(
                    android.provider.Settings
                            .ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
 startActivity(intent);

What am I doing wrong here? Why cannot I request this permissions as a normal permission? Do I really have to go through the intent to allow my app to mute the phone?

Body:
I will post an answer on how I managed to solve this issue for androids over 23 and under 23 with a startActivityForResult callback

the requestMutePhonePermsAndMutePhone() function is called in the main actions onCreate function.

Mind you the code is very much intrusive, since the Settings menu is permacalled until you accept the Do Not Disturb permissions, but one can easily accomodate this code for their personal needs and maybe build a question prompt, etc...

private void requestMutePhonePermsAndMutePhone() {
    try {
        if (Build.VERSION.SDK_INT < 23) {
            AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
            audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        } else if( Build.VERSION.SDK_INT >= 23 ) {
            this.requestDoNotDisturbPermissionOrSetDoNotDisturbApi23AndUp();
        }
    } catch ( SecurityException e ) {

    }
}

private void requestDoNotDisturbPermissionOrSetDoNotDisturbApi23AndUp() {
    //TO SUPPRESS API ERROR MESSAGES IN THIS FUNCTION, since Ive no time to figrure our Android SDK suppress stuff
    if( Build.VERSION.SDK_INT < 23 ) {
        return;
    }

    NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    if ( notificationManager.isNotificationPolicyAccessGranted()) {
        AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
        audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
    } else{
        // Ask the user to grant access
        Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
        startActivityForResult( intent, MainActivity.ON_DO_NOT_DISTURB_CALLBACK_CODE );
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == MainActivity.ON_DO_NOT_DISTURB_CALLBACK_CODE ) {
        this.requestDoNotDisturbPermissionOrSetDoNotDisturbApi23AndUp();
    }
}


问:
Win32 equivalent of opendir
Would anyone know what the Win32 equivalent of opendir is (or if it even exists) ?
Obviously I could use FindFirstFile(Ex) with FindNextFile, but appending * to the path seems like such a hackish way to do it.</p>

答: I believe you can use CreateFile with FILE_FLAG_BACKUP_SEMANTICS and then BackupRead to read directory data, but I'm not sure what format the data is actually in. Also, you would need to be running as a user with the SE_BACKUP_NAME privilege enabled, so this is not really suitable in a general purpose application.

OwnerDisplayName: Frans-Willem

Title: Win32 equivalent of opendir

OwnerDisplayName: Greg Hewgill


问:
How to know menu open or not in swrevealviewcontroller in swift 2.0
I have made one app in ios. I have use swrevealviewcontroller for menu.I need keyboard disapper when menu open or not. So how to recognize menu is open or not?</p>

答:
Swift 3

Add SWRevealViewControllerDelegate to your controller

Set revealViewControllerDelegate to self in viewDidLoad()

```<code>self.revealViewController().delegate = self
</code>```

Implement this Func with (didMoveTo) or the one with (willMoveTo) in your viewController

```<code>func revealController(_ revealController: SWRevealViewController!, didMoveTo position: FrontViewPosition) {

    switch position {

    case FrontViewPosition.leftSideMostRemoved:
        print("LeftSideMostRemoved")
        // Left most position, front view is presented left-offseted by rightViewRevealWidth+rigthViewRevealOverdraw

    case FrontViewPosition.leftSideMost:
        print("LeftSideMost")
        // Left position, front view is presented left-offseted by rightViewRevealWidth

    case FrontViewPosition.leftSide:
        print("LeftSide")

        // Center position, rear view is hidden behind front controller
    case FrontViewPosition.left:
        print("Left")
        //Closed
        //0 rotation

        // Right possition, front view is presented right-offseted by rearViewRevealWidth
    case FrontViewPosition.right:
        print("Right")
        //Opened
        //rotated

        // Right most possition, front view is presented right-offseted by rearViewRevealWidth+rearViewRevealOverdraw

    case FrontViewPosition.rightMost:
        print("RightMost")
        // Front controller is removed from view. Animated transitioning from this state will cause the same
        // effect than animating from FrontViewPositionRightMost. Use this instead of FrontViewPositionRightMost when
        // you intent to remove the front controller view from the view hierarchy.

    case FrontViewPosition.rightMostRemoved:
        print("RightMostRemoved")

    }

}
</code>```

Body:
Swift 3

Add SWRevealViewControllerDelegate to your controller

Set revealViewControllerDelegate to self in viewDidLoad()

self.revealViewController().delegate = self

Implement this Func with (didMoveTo) or the one with (willMoveTo) in your viewController

func revealController(_ revealController: SWRevealViewController!, didMoveTo position: FrontViewPosition) {

    switch position {

    case FrontViewPosition.leftSideMostRemoved:
        print("LeftSideMostRemoved")
        // Left most position, front view is presented left-offseted by rightViewRevealWidth+rigthViewRevealOverdraw

    case FrontViewPosition.leftSideMost:
        print("LeftSideMost")
        // Left position, front view is presented left-offseted by rightViewRevealWidth

    case FrontViewPosition.leftSide:
        print("LeftSide")

        // Center position, rear view is hidden behind front controller
    case FrontViewPosition.left:
        print("Left")
        //Closed
        //0 rotation

        // Right possition, front view is presented right-offseted by rearViewRevealWidth
    case FrontViewPosition.right:
        print("Right")
        //Opened
        //rotated

        // Right most possition, front view is presented right-offseted by rearViewRevealWidth+rearViewRevealOverdraw

    case FrontViewPosition.rightMost:
        print("RightMost")
        // Front controller is removed from view. Animated transitioning from this state will cause the same
        // effect than animating from FrontViewPositionRightMost. Use this instead of FrontViewPositionRightMost when
        // you intent to remove the front controller view from the view hierarchy.

    case FrontViewPosition.rightMostRemoved:
        print("RightMostRemoved")

    }

}