问:
Store items in sessionStorage that has ben pushed in another function
I've a slight problem with my code.

I have an array that stores values and i need to store them into sessionStorage.

```<code>document.getElementById("submit-button").addEventListener("click", book, false);

var array = new Array;

function book()
{

 var seat;

 // value in label that is changed everytime i click on a element.
 seat = document.getElementById("label").innerHTML;

 // Put it in a global array
 array.push(seat);
 window.sessionStorage.setItem("items", JSON.stringify(array));

 booked(seat);

}
</code>```

and in load() function:

```<code>function load()
 {
  var storedArray = JSON.parse(window.sessionStorage.getItem("items"));

  for (var i = 0; i < storedArray.length; i++)
  {
    var str1 = "seat";
    var str2 = storedArray[i];

    var number = document.getElementById(str1.concat(str2));
    var context = number.getContext("2d");
    context.fillStyle = 'red';
    context.fillRect(0,0, seat18.width, seat18.height);
  }

 }
</code>```

But my problem is that every time i call book() function, the array resets itself and pushing the new value. And in load() function, the storedArray in only register the newest value from the Array.

First, i want to store every value that is made in book() in global array and get every value in load() from getItem. How can i make that possible?

答:
The sessionStorage can persist only until the current session expires. Use localStorage instead.

Data stored in sessionStorage gets cleared when the page session ends.
  A page session lasts for as long as the browser is open and survives
  over page reloads and restores.

Body:
I've a slight problem with my code.

I have an array that stores values and i need to store them into sessionStorage.

document.getElementById("submit-button").addEventListener("click", book, false);

var array = new Array;

function book()
{

 var seat;

 // value in label that is changed everytime i click on a element.
 seat = document.getElementById("label").innerHTML;

 // Put it in a global array
 array.push(seat);
 window.sessionStorage.setItem("items", JSON.stringify(array));

 booked(seat);

}

and in load() function:

function load()
 {
  var storedArray = JSON.parse(window.sessionStorage.getItem("items"));

  for (var i = 0; i < storedArray.length; i++)
  {
    var str1 = "seat";
    var str2 = storedArray[i];

    var number = document.getElementById(str1.concat(str2));
    var context = number.getContext("2d");
    context.fillStyle = 'red';
    context.fillRect(0,0, seat18.width, seat18.height);
  }

 }

But my problem is that every time i call book() function, the array resets itself and pushing the new value. And in load() function, the storedArray in only register the newest value from the Array.

First, i want to store every value that is made in book() in global array and get every value in load() from getItem. How can i make that possible?


来源: stackexchange

问:
Background of a UIViewController to Grouped table view color
In a UITableView grouped style, the background of the table view is sort of like a grayish texture color. How can I grab that value such that I can set the entire background of a UIViewController to be that color?</p>

答:
If you are developing for the iPhone and iPod touch, UIColor defines a groupTableViewBackgroundColor pattern that you can use:

```<code>[self.view setBackgroundColor:[UIColor groupTableViewBackgroundColor]];
</code>```

You can also find this color in Interface Builder:

This won't be available on the iPad, however. You'll have to grab the image yourself and do a UIColor.colorWithPatternImage: instead.

ContentLicense: CC BY-SA 3.0

Body:
If you are developing for the iPhone and iPod touch, UIColor defines a groupTableViewBackgroundColor pattern that you can use:

[self.view setBackgroundColor:[UIColor groupTableViewBackgroundColor]];

You can also find this color in Interface Builder:

This won't be available on the iPad, however. You'll have to grab the image yourself and do a UIColor.colorWithPatternImage: instead.

ContentLicense: CC BY-SA 2.5


问:
Issue with Delete Action returning HttpNotFound MVC
i have list of user Emails and than i try to make delete method , but i didnt understand why it just returning HttpNotFound , did i miss something!Can anyone direct me in the right direction? thx

Controller:

```<code>public ActionResult Delete(string User)
{

    var db = new DataContext();
    var u = db.PX.Find(User);
    if (u==null)
    {
        return HttpNotFound();
    }
    return View(u);

}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string User)
{
    var db = new DataContext();
    var u = db.PX.Find(User);
    db.PX.Remove(u);
    db.SaveChanges();
    return RedirectToAction("Index");
}
</code>```

View - Index:

```<code><table>
    <thead>
        <tr>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var user in Model)
        {
            <tr>
                <td>

                     <a href="/User/Delete?User=@user.Email">delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>
</code>```

Class :

```<code>public class user
{
    public string Email { get; set; }
    private string password = "";

    } }
}
</code>```

答:
DbSet.Find takes the primary key of the entity (usually a long or Guid). If no entity with this primary key is found, it returns null.

If the user email is not the primary key in the DB, look up the user with SingleOrDefault instead. SingleOrDefault will throw an exception if more than one record matches the given criteria (we want this because the Email is used to identify users uniquely). If no matching record is found, it returns null.

```<code>var u = db.PX.SingleOrDefault(u => u.Email == User);
</code>```

Body:
i have list of user Emails and than i try to make delete method , but i didnt understand why it just returning HttpNotFound , did i miss something!Can anyone direct me in the right direction? thx

Controller:

public ActionResult Delete(string User)
{

    var db = new DataContext();
    var u = db.PX.Find(User);
    if (u==null)
    {
        return HttpNotFound();
    }
    return View(u);

}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string User)
{
    var db = new DataContext();
    var u = db.PX.Find(User);
    db.PX.Remove(u);
    db.SaveChanges();
    return RedirectToAction("Index");
}

View - Index:

            Email

        @foreach (var user in Model)
        {

                     delete

        }

Class :

public class user
{
    public string Email { get; set; }
    private string password = "";

    } }
}

Body:
DbSet.Find takes the primary key of the entity (usually a long or Guid). If no entity with this primary key is found, it returns null.

If the user email is not the primary key in the DB, look up the user with SingleOrDefault instead. SingleOrDefault will throw an exception if more than one record matches the given criteria (we want this because the Email is used to identify users uniquely). If no matching record is found, it returns null.

var u = db.PX.SingleOrDefault(u => u.Email == User);


问:
multiple recyclerviews?
I want to make my homepage with two row  with recyclerview
with data of books and  the events which are display independent of each other how can i accomplish it I want to add event to the my code how can i do it?

MoviesAdapter.java

```<code>public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {

private List<Movie> moviesList;
public Context context;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView title;
    public ImageView thumbnail;

    public MyViewHolder(View view) {
        super(view);
        title = (TextView) view.findViewById(R.id.title);
        thumbnail = (ImageView) view.findViewById(R.id.book);

    }
}//End of MyViewHolder class

public MoviesAdapter(List<Movie> moviesList) {
    this.moviesList = moviesList;
}

//display different items in the data set
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.movie_list_row, parent, false);

    return new MyViewHolder(itemView);
}

//display data at specified location
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {

    holder.title.setText(moviesList.get(position).getTitle());

    holder.thumbnail.setImageResource(moviesList.get(position).getImage());
}

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

I want to make my page like this

答:
I done it with the three recyclerview and their adapter class here is the code of only MainActivity.java and activity.xml

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

    private List<Book> bookList = new ArrayList<>();
    private List<Author> authorList = new ArrayList<>();
    private List<Event> eventList = new ArrayList<>();

    private RecyclerView recyclerView1;
    private RecyclerView recyclerView2;
    private RecyclerView recyclerView3;

    private BookAdapter bAdapter;
    private AuthorAdapter aAdapter;
    private EventAdapter eAdapter;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView1 =  findViewById(R.id.recycler_book);
        bAdapter = new BookAdapter(this,bookList);
        recyclerView1.setHasFixedSize(true);
         RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
        recyclerView1.setLayoutManager(mLayoutManager);
        recyclerView1.setAdapter(bAdapter);
        prepareBookData();

      //second recycler
        recyclerView2 =  findViewById(R.id.recycler_author);
        aAdapter = new AuthorAdapter(this,authorList);
        recyclerView2.setHasFixedSize(true);
        RecyclerView.LayoutManager aLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
        recyclerView2.setLayoutManager(aLayoutManager);
        recyclerView2.setAdapter(aAdapter);
        prepareAuthorData();

        //third recycler
        recyclerView3 = (RecyclerView) findViewById(R.id.recycler_event);
        eAdapter = new EventAdapter(this,eventList);
        recyclerView3.setHasFixedSize(true);
        RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
        //   RecyclerView.LayoutManager eLayoutManager = new GridLayoutManager(this,1,GridLayoutManager.HORIZONTAL,false);
        recyclerView3.setLayoutManager(eLayoutManager);
        recyclerView3.setAdapter(eAdapter);
        prepareEventData();
    }

    private void prepareBookData(){

        int[] drawableArray = {R.drawable.youcanwin, R.drawable.halfgirl};
        String[] nameArray = {"You Can Win", "Half Girlfriend"};
        Book a=new Book(nameArray[0],drawableArray[0]);
        bookList.add(a);

        Book b=new Book(nameArray[1],drawableArray[1]);
        bookList.add(b);

        Book c=new Book(nameArray[0],drawableArray[0]);
        bookList.add(c);

        bAdapter.notifyDataSetChanged();
    }

    private void prepareAuthorData(){

        int[] drawableArray = {R.drawable.youcanwin, R.drawable.halfgirl};
        String[] nameArray = {"You Can Win", "Half Girlfriend"};

        Author a=new Author(nameArray[0],drawableArray[0]);
        authorList.add(a);

        Author b=new Author(nameArray[1],drawableArray[1]);
        authorList.add(b);

        Author c=new Author(nameArray[0],drawableArray[0]);
        authorList.add(c);

        Author d=new Author(nameArray[1],drawableArray[1]);
        authorList.add(d);

        bAdapter.notifyDataSetChanged();
    }

    private void prepareEventData(){

        String[] desArray = {"new","old"};
        String[] nameArray = {"You Can Win", "Half Girlfriend"};

        Event a=new Event(nameArray[0],desArray[0]);
        eventList.add(a);

        Event b=new Event(nameArray[0],desArray[0]);
        eventList.add(b);

        Event c=new Event(nameArray[0],desArray[0]);
        eventList.add(c);

        bAdapter.notifyDataSetChanged();
    }
 }
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView
  xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
tools:context="com.example.hardik.threerecycler.MainActivity"
android:background="#e6edec">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        app:cardCornerRadius="4dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Books"
            android:textSize="20sp"
            android:textStyle="bold" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_book"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_marginTop="20dp" />
    </android.support.v7.widget.CardView>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Authors"
        android:textStyle="bold"
        android:textSize="20sp"
        android:layout_marginTop="10dp"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_author"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_below="@+id/recycler_book"
        android:layout_marginTop="5dp"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Events"
        android:textStyle="bold"
        android:textSize="20sp"
        android:layout_marginTop="10dp"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_event"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_below="@+id/recycler_author"
        android:layout_marginTop="5dp"/>

</LinearLayout>
</code>```

Title: multiple recyclerviews?

Body:
I want to make my homepage with two row  with recyclerview
with data of books and  the events which are display independent of each other how can i accomplish it I want to add event to the my code how can i do it?

MoviesAdapter.java

public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MyViewHolder> {

private List<Movie> moviesList;
public Context context;

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView title;
    public ImageView thumbnail;

    public MyViewHolder(View view) {
        super(view);
        title = (TextView) view.findViewById(R.id.title);
        thumbnail = (ImageView) view.findViewById(R.id.book);

    }
}//End of MyViewHolder class

public MoviesAdapter(List<Movie> moviesList) {
    this.moviesList = moviesList;
}

//display different items in the data set
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.movie_list_row, parent, false);

    return new MyViewHolder(itemView);
}

//display data at specified location
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {

    holder.title.setText(moviesList.get(position).getTitle());

    holder.thumbnail.setImageResource(moviesList.get(position).getImage());
}

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

I want to make my page like this

Body:
I done it with the three recyclerview and their adapter class here is the code of only MainActivity.java and activity.xml

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private List<Book> bookList = new ArrayList<>();
    private List<Author> authorList = new ArrayList<>();
    private List<Event> eventList = new ArrayList<>();

    private RecyclerView recyclerView1;
    private RecyclerView recyclerView2;
    private RecyclerView recyclerView3;

    private BookAdapter bAdapter;
    private AuthorAdapter aAdapter;
    private EventAdapter eAdapter;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView1 =  findViewById(R.id.recycler_book);
        bAdapter = new BookAdapter(this,bookList);
        recyclerView1.setHasFixedSize(true);
         RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
        recyclerView1.setLayoutManager(mLayoutManager);
        recyclerView1.setAdapter(bAdapter);
        prepareBookData();

      //second recycler
        recyclerView2 =  findViewById(R.id.recycler_author);
        aAdapter = new AuthorAdapter(this,authorList);
        recyclerView2.setHasFixedSize(true);
        RecyclerView.LayoutManager aLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
        recyclerView2.setLayoutManager(aLayoutManager);
        recyclerView2.setAdapter(aAdapter);
        prepareAuthorData();

        //third recycler
        recyclerView3 = (RecyclerView) findViewById(R.id.recycler_event);
        eAdapter = new EventAdapter(this,eventList);
        recyclerView3.setHasFixedSize(true);
        RecyclerView.LayoutManager eLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
        //   RecyclerView.LayoutManager eLayoutManager = new GridLayoutManager(this,1,GridLayoutManager.HORIZONTAL,false);
        recyclerView3.setLayoutManager(eLayoutManager);
        recyclerView3.setAdapter(eAdapter);
        prepareEventData();
    }

    private void prepareBookData(){

        int[] drawableArray = {R.drawable.youcanwin, R.drawable.halfgirl};
        String[] nameArray = {"You Can Win", "Half Girlfriend"};
        Book a=new Book(nameArray[0],drawableArray[0]);
        bookList.add(a);

        Book b=new Book(nameArray[1],drawableArray[1]);
        bookList.add(b);

        Book c=new Book(nameArray[0],drawableArray[0]);
        bookList.add(c);

        bAdapter.notifyDataSetChanged();
    }

    private void prepareAuthorData(){

        int[] drawableArray = {R.drawable.youcanwin, R.drawable.halfgirl};
        String[] nameArray = {"You Can Win", "Half Girlfriend"};

        Author a=new Author(nameArray[0],drawableArray[0]);
        authorList.add(a);

        Author b=new Author(nameArray[1],drawableArray[1]);
        authorList.add(b);

        Author c=new Author(nameArray[0],drawableArray[0]);
        authorList.add(c);

        Author d=new Author(nameArray[1],drawableArray[1]);
        authorList.add(d);

        bAdapter.notifyDataSetChanged();
    }

    private void prepareEventData(){

        String[] desArray = {"new","old"};
        String[] nameArray = {"You Can Win", "Half Girlfriend"};

        Event a=new Event(nameArray[0],desArray[0]);
        eventList.add(a);

        Event b=new Event(nameArray[0],desArray[0]);
        eventList.add(b);

        Event c=new Event(nameArray[0],desArray[0]);
        eventList.add(c);

        bAdapter.notifyDataSetChanged();
    }
 }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
  xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
tools:context="com.example.hardik.threerecycler.MainActivity"
android:background="#e6edec">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        app:cardCornerRadius="4dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Books"
            android:textSize="20sp"
            android:textStyle="bold" />

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_book"
            android:layout_width="match_parent"
            android:layout_height="150dp"
            android:layout_marginTop="20dp" />
    </android.support.v7.widget.CardView>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Authors"
        android:textStyle="bold"
        android:textSize="20sp"
        android:layout_marginTop="10dp"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_author"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_below="@+id/recycler_book"
        android:layout_marginTop="5dp"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Events"
        android:textStyle="bold"
        android:textSize="20sp"
        android:layout_marginTop="10dp"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_event"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_below="@+id/recycler_author"
        android:layout_marginTop="5dp"/>

</LinearLayout>

ContentLicense: CC BY-SA 4.0


问:
CakePHP: media views for mp3 files streamed with flash player
I have a page with a audio flash player that streams several mp3 files. This player uses an XML file that has the path of all those files, which are in a audio folder in the webroot directory.

What I don't like is that it's pretty easy for a user to get to the XML file (which is also in the webroot directory) and see the paths of the mp3 files, and then download them instead of just using the flash player.

I've seen that CakePHP has something called Media Views, where you can set a folder outside the webroot and place your files there, so users can't freely access them. The explanation in Cake's website (http://book.cakephp.org/view/1094/Media-Views) is focused on files to download, but I would like to know if I can use the Media Views to stream my mp3 files with the audio player without making them downloadable by the users. OR if there's any other alternative without Media Views that would work as well :)

Thanks so much in advance!

CLARIFICATION

This is the code that I'm using that I would like to change:

- In my controller:

```<code>function index() {}
</code>```

- In my view (index.ctp):

```<code><embed type="application/x-shockwave-flash" flashvars="audioUrl=/audios/01 Track 01.mp3" src="audio-player.swf"></embed>
</code>```

=>How can I change that using Media Views so that my mp3 file is in a folder app/audios instead of app/webroot/audios?

THIS IS WHAT I'VE TRIED:

- In my controller (streams_controller.php):

```<code>function index() {}

function getFile() {

    $this->view = 'Media';

    $params = array(
                    'id' => '01 Track 01.mp3',
                    'name' => '01 Track 01',
                    'download' => false,
                    'extension' => 'mp3',
                    'path' => APP . 'audios' . DS,
                    'cache' => true
                    );

    $this->set($params);
}
</code>```

- In my view (index.ctp):

```<code><embed type="application/x-shockwave-flash" flashvars="audioUrl=/streams/getFile" src="audio-player.swf"></embed>
</code>```

STILL NO LUCK! What am I doing wrong?

答:
Cakephp 3x media files farce to download

if ($this->request->is(['post'])) {
     $data = $this->request->data;

```<code> // $file_name= 'test.mp4';
 $file_name = $data['files'];
 $this->viewClass = 'Media';

  $file_path = WWW_ROOT . 'files/video/' . DS . $file_name;
 //showing the path to the server where the file is to be download
 $this->response->file($file_path, array(
    'download' => true,
    'name' => $file_name,
 ));
 return $this->response;

 exit;
}
</code>```

Body:
I have a page with a audio flash player that streams several mp3 files. This player uses an XML file that has the path of all those files, which are in a audio folder in the webroot directory.

What I don't like is that it's pretty easy for a user to get to the XML file (which is also in the webroot directory) and see the paths of the mp3 files, and then download them instead of just using the flash player.

I've seen that CakePHP has something called Media Views, where you can set a folder outside the webroot and place your files there, so users can't freely access them. The explanation in Cake's website (http://book.cakephp.org/view/1094/Media-Views) is focused on files to download, but I would like to know if I can use the Media Views to stream my mp3 files with the audio player without making them downloadable by the users. OR if there's any other alternative without Media Views that would work as well :)

Thanks so much in advance!

CLARIFICATION

This is the code that I'm using that I would like to change:

- In my controller:

function index() {}

- In my view (index.ctp):

<embed type="application/x-shockwave-flash" flashvars="audioUrl=/audios/01 Track 01.mp3" src="audio-player.swf"></embed>

=>How can I change that using Media Views so that my mp3 file is in a folder app/audios instead of app/webroot/audios?

THIS IS WHAT I'VE TRIED:

- In my controller (streams_controller.php):

function index() {}

function getFile() {

    $this->view = 'Media';

    $params = array(
                    'id' => '01 Track 01.mp3',
                    'name' => '01 Track 01',
                    'download' => false,
                    'extension' => 'mp3',
                    'path' => APP . 'audios' . DS,
                    'cache' => true
                    );

    $this->set($params);
}

- In my view (index.ctp):

<embed type="application/x-shockwave-flash" flashvars="audioUrl=/streams/getFile" src="audio-player.swf"></embed>

STILL NO LUCK! What am I doing wrong?

Body:
Cakephp 3x media files farce to download

if ($this->request->is(['post'])) {
     $data = $this->request->data;

 // $file_name= 'test.mp4';
 $file_name = $data['files'];
 $this->viewClass = 'Media';

  $file_path = WWW_ROOT . 'files/video/' . DS . $file_name;
 //showing the path to the server where the file is to be download
 $this->response->file($file_path, array(
    'download' => true,
    'name' => $file_name,
 ));
 return $this->response;

 exit;
}


问:
Generic lambda and its argument as constant expression
The following code is accepted by GCC 7.2 and clang 5.0.0, but is rejected by Microsoft VS 2017 15.5.0 Preview 5 and Intel C++ compiler 19:

```<code>struct S { };

constexpr int f(S)
{
    return 0;
}

int main()
{
    auto lambda = [](auto x)
    {
        constexpr int e = f(x);
    };

    lambda(S{});
}
</code>```

Microsoft:

```<code><source>(12): error C2131: expression did not evaluate to a constant
</code>```

Intel:

```<code><source>(12): error: expression must have a constant value
    constexpr int e = f(x);
                      ^
<source>(12): note: the value of parameter "x" (declared at line 10) cannot be used as a constant
    constexpr int e = f(x);
                        ^
</code>```

If I replace f(x) with f(decltype(x){}), both Microsoft and Intel do not complain. I understand that x is not a constant expression, but it is not used inside f. This is probably why GCC and clang do not complain.

I guess that Microsoft and Intel compilers are correct in rejecting this code. What do you think?

答:
This is not a gcc/clang bug. The same behavior can be reproduced in C++11 with a template function:

```<code>template <typename T>
void foo(T x)
{
    constexpr int e = f(x);
}

int main()
{
    foo(S{});
}
</code>```

on godbolt.org

The question is, given...

```<code>template <typename T>
void foo(T x)
{
    constexpr int e = f(x);
}
</code>```

...is f(x) a constant expression?

From [expr.const]:

An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:

invocation of a function other than a constexpr constructor for a literal class, a constexpr function, or an implicit invocation of a trivial destructor

S{} and 0 are constant expressions because it doesn't violate any of the rules in [expr.const]. f(x) is a constant expression because it's an invocation to a constexpr function.

Unless I am missing something, gcc and clang are correct here.

Body:
The following code is accepted by GCC 7.2 and clang 5.0.0, but is rejected by Microsoft VS 2017 15.5.0 Preview 5 and Intel C++ compiler 19:

struct S { };

constexpr int f(S)
{
    return 0;
}

int main()
{
    auto lambda = [](auto x)
    {
        constexpr int e = f(x);
    };

    lambda(S{});
}

Microsoft:

<source>(12): error C2131: expression did not evaluate to a constant

Intel:

<source>(12): error: expression must have a constant value
    constexpr int e = f(x);
                      ^
<source>(12): note: the value of parameter "x" (declared at line 10) cannot be used as a constant
    constexpr int e = f(x);
                        ^

If I replace f(x) with f(decltype(x){}), both Microsoft and Intel do not complain. I understand that x is not a constant expression, but it is not used inside f. This is probably why GCC and clang do not complain.

I guess that Microsoft and Intel compilers are correct in rejecting this code. What do you think?

Body:
This is not a gcc/clang bug. The same behavior can be reproduced in C++11 with a template function:

template <typename T>
void foo(T x)
{
    constexpr int e = f(x);
}

int main()
{
    foo(S{});
}

on godbolt.org

The question is, given...

template <typename T>
void foo(T x)
{
    constexpr int e = f(x);
}

...is f(x) a constant expression?

From [expr.const]:

An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:

invocation of a function other than a constexpr constructor for a literal class, a constexpr function, or an implicit invocation of a trivial destructor

S{} and 0 are constant expressions because it doesn't violate any of the rules in [expr.const]. f(x) is a constant expression because it's an invocation to a constexpr function.

Unless I am missing something, gcc and clang are correct here.


问:
Why LinkedHashSet has boolean accessOrder set to false
In Java LinkedHashSet is created with backing HashSet creating LinkedHashMap with following LinkedHashMap constructor

```<code>map = new LinkedHashMap<>(initialCapacity, loadFactor);
</code>```

Now in LinkedHashMap, the above constructor in turn calls

```<code> public LinkedHashMap(int initialCapacity, float loadFactor) {
    super(initialCapacity, loadFactor);
    accessOrder = false;
}
</code>```

so is there any way to have a LinkedHashSet with accessOrder set to true?
This can help create LRU cache implementation with LinkedHashSet.

答:
As you can see from the source code, a LinkedHashSet is backed by a LinkedHashMap with the accessOrder set to false.

Furthermore, there is no public constructor for LinkedHashSet to change the access order from insertion order to access order.

You could try this (just an example):

```<code>LinkedHashSet<E> set = (LinkedHashSet<E>) Collections.newSetFromMap(new LinkedHashMap<>(16, 0.75f, true));
</code>```

Body:
In Java LinkedHashSet is created with backing HashSet creating LinkedHashMap with following LinkedHashMap constructor

map = new LinkedHashMap<>(initialCapacity, loadFactor);

Now in LinkedHashMap, the above constructor in turn calls

 public LinkedHashMap(int initialCapacity, float loadFactor) {
    super(initialCapacity, loadFactor);
    accessOrder = false;
}

so is there any way to have a LinkedHashSet with accessOrder set to true?
This can help create LRU cache implementation with LinkedHashSet.

Body:
As you can see from the source code, a LinkedHashSet is backed by a LinkedHashMap with the accessOrder set to false.

Furthermore, there is no public constructor for LinkedHashSet to change the access order from insertion order to access order.

You could try this (just an example):

LinkedHashSet<E> set = (LinkedHashSet<E>) Collections.newSetFromMap(new LinkedHashMap<>(16, 0.75f, true));


问:
Combining elements in a list in Python where sequence matters
I have a 2d list

```<code>a = [[[6, 7], [7, 4]],
    [[4, 7], [7, 8], [8, 15]],
    [[3, 19], [15, 3], [19, 12]]]
</code>```

Figures are the node names in a TSP ([6,7] means go from 6 to 7). Each row in a corresponds to a tour in specific day. I need to make another 2d list which sequences are considered: Below is what I need:

```<code>FinalTours = [[6,7,4],
              [4,7,8,15],
              [15,3,19,12]]
</code>```

Any suggestions?
I tried the code below but it only works for the first day (first row of a)

```<code>FinalTours = [[] for i in range(T)]
for t in range(T):
    for i in AllTour[t]:
        if t == 0:
            Wakeup = 6
            if i[0] == Wakeup:
                Tour =[]
                Tour.append(Wakeup)
                Tour.append(i[1])
            else:
                if i[0] == Tour[-1]:
                    Tour.append(i[1])
                    FinalTours[t] = Tour

        else:
            Wakeup = Tour[-1]
            if i[0] == Wakeup:
                Tour =[]
                Tour.append(Wakeup)
                Tour.append(i[1])
            else:
                if i[0] == Tour[-1]:
                    Tour.append(i[1])
                    FinalTours[t] = Tour
</code>```

答:
Naive approach brute-forcing a path from a list, using itertools.permutations

```<code>from itertools import permutations

def is_path(lst):
    # check if [[a, b], [b, c], [c, d], ...] holds
    return all(x[1] == y[0] for x, y in zip(lst, lst[1:]))

def make_path(lst):
    # find lst permutation that is a path
    for p in permutations(lst, len(lst)):
        if is_path(p):
            return p
    raise ValueError('No Path possible')

def flatten_path(lst):
    # turn [[a, b], [b, c]] into [a, b, c]
    return lst[0][:1] + [x[1] for x in lst]

a = [[[6, 7], [7, 4]],
    [[4, 7], [7, 8], [8, 15]],
    [[3, 19], [15, 3], [19, 12]]]

paths = [flatten_path(make_path(x)) for x in a]
# [[6, 7, 4], [4, 7, 8, 15], [15, 3, 19, 12]]
</code>```

Body:
I have a 2d list

a = [[[6, 7], [7, 4]],
    [[4, 7], [7, 8], [8, 15]],
    [[3, 19], [15, 3], [19, 12]]]

Figures are the node names in a TSP ([6,7] means go from 6 to 7). Each row in a corresponds to a tour in specific day. I need to make another 2d list which sequences are considered: Below is what I need:

FinalTours = [[6,7,4],
              [4,7,8,15],
              [15,3,19,12]]

Any suggestions?
I tried the code below but it only works for the first day (first row of a)

FinalTours = [[] for i in range(T)]
for t in range(T):
    for i in AllTour[t]:
        if t == 0:
            Wakeup = 6
            if i[0] == Wakeup:
                Tour =[]
                Tour.append(Wakeup)
                Tour.append(i[1])
            else:
                if i[0] == Tour[-1]:
                    Tour.append(i[1])
                    FinalTours[t] = Tour

        else:
            Wakeup = Tour[-1]
            if i[0] == Wakeup:
                Tour =[]
                Tour.append(Wakeup)
                Tour.append(i[1])
            else:
                if i[0] == Tour[-1]:
                    Tour.append(i[1])
                    FinalTours[t] = Tour

Body:
Naive approach brute-forcing a path from a list, using itertools.permutations

from itertools import permutations

def is_path(lst):
    # check if [[a, b], [b, c], [c, d], ...] holds
    return all(x[1] == y[0] for x, y in zip(lst, lst[1:]))

def make_path(lst):
    # find lst permutation that is a path
    for p in permutations(lst, len(lst)):
        if is_path(p):
            return p
    raise ValueError('No Path possible')

def flatten_path(lst):
    # turn [[a, b], [b, c]] into [a, b, c]
    return lst[0][:1] + [x[1] for x in lst]

a = [[[6, 7], [7, 4]],
    [[4, 7], [7, 8], [8, 15]],
    [[3, 19], [15, 3], [19, 12]]]

paths = [flatten_path(make_path(x)) for x in a]
# [[6, 7, 4], [4, 7, 8, 15], [15, 3, 19, 12]]


问:
Where is an array initialized by an initializer list stored?
Given this piece of code:

```<code>(void)someFunction(void) {
    int array[] = {1,2,3,4,5,6,7,8,9,10};
}
</code>```

Where are the values of the array stored?

Stack?

Heap?

Together with those string literals. (Is it called High Frequency Heap?)

Somewhere else?

I'm asking because I'm unsure regarding this question:

Create an array of integers property in objective-c

答:
The array itself will be on the stack.  There will be a bit of code on entry to the function that copies the values which are stored in some unnamed array in a global/static memory area  into the local array on the stack.  It's likely that the unnamed global/static array with the initial values is in the same general memory area as string literals.

Note however, that none of this is required by the standard - but it's pretty much how any compiler will implement it.  A smart enough compiler might notice that the values are simply incremented integer values and might gen up a loop to init the local array,

(this answer assumes C/C++ - I don't know if Objective-C would change any of this).

OwnerDisplayName: gs

Body:
Given this piece of code:

(void)someFunction(void) {
    int array[] = {1,2,3,4,5,6,7,8,9,10};
}

Where are the values of the array stored?

Stack?

Heap?

Together with those string literals. (Is it called High Frequency Heap?)

Somewhere else?

I'm asking because I'm unsure regarding this question:

Create an array of integers property in objective-c

OwnerDisplayName: Michael Burr


问:
Unusual formatting for date and times: wish to convert to datetime objects
I have a .csv file with three columns, one representing date, one time, and a third associated values. The columns are as shown:

```<code>date        time        value
02112017    143335      1.79
03112017    153540      0.86
04112017    164015      2.79
05112017    135150      3.50
</code>```

After uploading the .csv file into Python and querying data types, "date" and "time" are integer values and "value" are float values.

I would like to combine the "date" and "time" columns into a single column of datetime objects, that I can then plot against "value" column to make a timeseries. As such:

```<code>date        time       datetime
02112017    143335     02-11-2017 14:33:35
</code>```

I've tried to concatenate these values and then use pd.to_datetime to convert them to datetime objects, but get a series of error messages thrown up - including the message:

```<code>ValueError: unconverted data remains: 00
</code>```

If anyone could shine a light on what I'm missing, I'd be grateful!

Body:
I have a .csv file with three columns, one representing date, one time, and a third associated values. The columns are as shown:

date        time        value
02112017    143335      1.79
03112017    153540      0.86
04112017    164015      2.79
05112017    135150      3.50

After uploading the .csv file into Python and querying data types, "date" and "time" are integer values and "value" are float values.

I would like to combine the "date" and "time" columns into a single column of datetime objects, that I can then plot against "value" column to make a timeseries. As such:

date        time       datetime
02112017    143335     02-11-2017 14:33:35

I've tried to concatenate these values and then use pd.to_datetime to convert them to datetime objects, but get a series of error messages thrown up - including the message:

ValueError: unconverted data remains: 00

If anyone could shine a light on what I'm missing, I'd be grateful!

Body:
First join columns and then use to_datetime:

s = df['date'] + ' ' + df['time'].astype(str)
df['datetime'] = pd.to_datetime(s, format='%d%m%Y %H%M%S')
print (df)
       date    time value            datetime
0  02112017  143335  1.79 2017-11-02 14:33:35
1  03112017  153540  0.86 2017-11-03 15:35:40
2  04112017  164015  2.79 2017-11-04 16:40:15
3  05112017  135150  3.50 2017-11-05 13:51:50


问:
git pre-commit hook file
I tried to add the pre-commit hook file gitlab server side. I know pre-commit hook is client side hook. I just want to add the pre-commit hook file in all the project's .git/hooks folder.

What I tried:-
I edited all the pre-commit.sample file in my gitlab server machine and created the new project. But I did not found that edited sample hook file in my local (windows) after cloned the repo.

Is there any way to add the pre-commit hook in all the project's git folder by server side? Because we have more than 500 projects.

答:
This is the fundamental trade-off with client-side hooks: they can't be centrally configured.

You could add the hook script(s) you want to the work tree, along with a script that you run in the root of the work tree to copy the scripts into .git/hooks.  Then if individual users want the hooks, they can run the script.  (Assuming they don't have some exotic setup where .git isn't in the root of the work tree.)

But no, you can't make it automatic that cloning your repo causes arbitrary code you selected to be run at times of your specification on someone else's computer.

Title: git pre-commit hook file


问:
Two for-each loops in a recursive function to traverse a file system
I'm not looking to get someone to do my assignment for me. I'm just not too sure about what its asking when it comes to the recursive part of the assignment.

This is a recursive function to open the directory and open the files of the computer:

```<code>For each ChildContainer item in dir
Create an OrderedList of names
For each ChildData item of the ChildContainer
Add the ChildData name to the OrderedList of names
</code>```

Why are there two for each statements in the recursive part of the instructions?

答:
okies,

Firstly this should not be StackOverflow as it's not a programming question it's a programming theory question that should be asked on https://softwareengineering.stackexchange.com/

I think you're missing the point of recursive functions/methods here. The whole point of a recursive function is that it does the nesting for you so you should not need to nest a foreach inside another foreach the function will do that for you.

This is an outline of how to do it, however, i will not provide code as you have said this is an assignment. I don't support plagiarism.

```<code>PlaceToStore = array of array of dir path (string);

function scanPath(pathToOpen, PlaceToStore){
    where dirHandle equals directory reader
    where childrenArray = dirHandle->getChilden
    foreach child in childrenArray do
        if(child is directory) then
            scanPath(child->path, PlaceToStore[child->path]
        else
             placeToStore[child->path] = child->path
       end if
   endforeach
}
</code>```

you should not need a double for each your childData is another directory or file

now this example is a quick outline of a messy way to do it but it shows how recursion should be done in an example that easy to understand.

Body:
I'm not looking to get someone to do my assignment for me. I'm just not too sure about what its asking when it comes to the recursive part of the assignment.

This is a recursive function to open the directory and open the files of the computer:

For each ChildContainer item in dir
Create an OrderedList of names
For each ChildData item of the ChildContainer
Add the ChildData name to the OrderedList of names

Why are there two for each statements in the recursive part of the instructions?

Body:
okies,

Firstly this should not be StackOverflow as it's not a programming question it's a programming theory question that should be asked on https://softwareengineering.stackexchange.com/

I think you're missing the point of recursive functions/methods here. The whole point of a recursive function is that it does the nesting for you so you should not need to nest a foreach inside another foreach the function will do that for you.

This is an outline of how to do it, however, i will not provide code as you have said this is an assignment. I don't support plagiarism.

PlaceToStore = array of array of dir path (string);

function scanPath(pathToOpen, PlaceToStore){
    where dirHandle equals directory reader
    where childrenArray = dirHandle->getChilden
    foreach child in childrenArray do
        if(child is directory) then
            scanPath(child->path, PlaceToStore[child->path]
        else
             placeToStore[child->path] = child->path
       end if
   endforeach
}

you should not need a double for each your childData is another directory or file

now this example is a quick outline of a messy way to do it but it shows how recursion should be done in an example that easy to understand.


问:
IIS Express 502 error in vs 2017
When I create new .NET Core 2.0 project in Visual Studio 2017, I am getting an error when I try to run IIS Express:

"Unable to start process C:\Program Files\dotnet\dotnet.exe. The web server request failed with status code 502, Bad Gateway"

I try:

Visual Studio restart

Machine restart

.Net SDK reinstall

Run Visual Studio as admin

Clean project (delete .vs, bin and obj folders)

答:
Can you elaborate the issue, are you able to run dotnet core application with default template.

Add Current logged in user in IIS_Users Group and try to run the application.

Title: IIS Express 502 error in vs 2017


问:
C palindrome program - undefined reference to main
I wrote an function, which checks, if string of char is palindrome or not.

```<code>//pan.c

#include <stdbool.h>
#include "funs.h"
#include <stdio.h>
#include <string.h>

bool palindrom(char napis[])
{
    int begin, middle, end, length = 0;

    while(napis[length] != '\0')
      length++;

    end = length - 1;
    middle = length;

    for (begin = 0; begin < middle; begin++)
      {
        if(napis[begin] != napis[end])
        {
          return false;
          break;
        }
        end--;
      }
      if(begin == middle)
        return true;
}
</code>```

I also created funs.h

```<code>//funs.h
#include <stdbool.h>
bool palindrom();
</code>```

Now, I'm trying to use this function in my main function

```<code>#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include "funs.h"

int main()
{
    char text[100];
    bool result;

    printf("Enter an char: ");
    scanf("%s", text);
    result = palindrom(text);
    if(result)
    {
        printf("Brawo!\n");
    }
    else
    {
        printf("Gówno!\n");
    }
    return 0;
}
</code>```

I also created makefile:

```<code># Makefile

all: main

main: main.o pan.o
    clang -o main main.o pan.o

main.o: main.c
    clang -c main.c

pan.o: pan.c
    clang -c pan.c

clean:
rm -f main *.o *~
</code>```

Everything seems fine and works in single file, but when I try to compile them separately they "don't see" each other. Makefile also seems to work badly, but I can't see any mistakes. Can you help me fix it?

答:
When I try "make" command it returns "makefile:15: *** missing separator. Stop." comment and do nothing.

Did you actually look at line 15 of your makefile?  Notice that it's flush against the margin instead of indented by a tab character.

When I'm compiling pan.c with "clang pan.c -Wall --pedantic -std=c11 -o pan" command: 1 warning generated. /usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/../../../x86_64-linux-gnu/crt1.o: In function _start': (.text+0x20): undefined reference to main'

Indeed, your pan.c does not have a main() function.  So don't try to compile it by itself.  How about

clang main.c pan.c -Wall --pedantic -std=c11 -o pan

Body:
I wrote an function, which checks, if string of char is palindrome or not.

//pan.c

#include <stdbool.h>
#include "funs.h"
#include <stdio.h>
#include <string.h>

bool palindrom(char napis[])
{
    int begin, middle, end, length = 0;

    while(napis[length] != '\0')
      length++;

    end = length - 1;
    middle = length;

    for (begin = 0; begin < middle; begin++)
      {
        if(napis[begin] != napis[end])
        {
          return false;
          break;
        }
        end--;
      }
      if(begin == middle)
        return true;
}

I also created funs.h

//funs.h
#include <stdbool.h>
bool palindrom();

Now, I'm trying to use this function in my main function

#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include "funs.h"

int main()
{
    char text[100];
    bool result;

    printf("Enter an char: ");
    scanf("%s", text);
    result = palindrom(text);
    if(result)
    {
        printf("Brawo!\n");
    }
    else
    {
        printf("Gówno!\n");
    }
    return 0;
}

I also created makefile:

# Makefile

all: main

main: main.o pan.o
    clang -o main main.o pan.o

main.o: main.c
    clang -c main.c

pan.o: pan.c
    clang -c pan.c

clean:
rm -f main *.o *~

Everything seems fine and works in single file, but when I try to compile them separately they "don't see" each other. Makefile also seems to work badly, but I can't see any mistakes. Can you help me fix it?


问:
how to select the checkboxes automatically as per the values in an array?
I have some checkboxes like this in my form...

```<code><label><input type="checkbox" name="project_dept[]" id="project_dept1" value="1">Development</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept2" value="2">Designing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept3" value="3">Testing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept4" value="4">Finance</label>
</code>```

Now, in javascript I have a string in a format of comma separated values like,

```<code>var projDepts = "1,2,3,4";
</code>```

after using the split function of javascript i have converted it to an array.

Now, my question is I want to select all those checkboxes as per the values in the array. I have tried something but its not working for me,

```<code>var projDepts = "1,2,3,4";
var projDeptArray = projDepts.split(',');
var project_depts = document.getElementsByName("prdept[]");
for (var i = 0; i < projDeptArray.length; i++) {
  for (var j = 0; j < project_depts.length; j++) {
    if (projDeptArray[i] == project_depts[j]) {
      $(project_depts[i]).prop("checked", true)
    }
  }
}
</code>```

This code is not working and none of the checkboxes got checked, I know I am getting somewhere wrong. Please someone help me to a solution for this.

答:
Map that split string to id selectors and pass to jQuery as a one liner

var projDepts = "1,3,4";
var checkboxSelectors = projDepts.split(",").map(s => '#project_dept' +s).join() ;
$(checkboxSelectors).prop('checked', true);

console.log(checkboxSelectors )```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label> <input type="checkbox" name="project_dept[]" id="project_dept1" value="1">Development</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept2" value="2">Designing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept3" value="3">Testing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept4" value="4">Finance</label></code>```

Or another way using prop(propertyName, function)

var projDepts = "1,3,4",
  projDeptArray = projDepts.split(',');

$(':checkbox[name="project_dept[]"]').prop('checked', function() {
  return projDeptArray.includes(this.value)
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label> <input type="checkbox" name="project_dept[]" id="project_dept1" value="1">Development</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept2" value="2">Designing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept3" value="3">Testing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept4" value="4">Finance</label></code>```

Body:
I have some checkboxes like this in my form...

<input type="checkbox" name="project_dept[]" id="project_dept1" value="1">Development
 <input type="checkbox" name="project_dept[]" id="project_dept2" value="2">Designing
 <input type="checkbox" name="project_dept[]" id="project_dept3" value="3">Testing
 <input type="checkbox" name="project_dept[]" id="project_dept4" value="4">Finance

Now, in javascript I have a string in a format of comma separated values like,

var projDepts = "1,2,3,4";

after using the split function of javascript i have converted it to an array.

Now, my question is I want to select all those checkboxes as per the values in the array. I have tried something but its not working for me,

var projDepts = "1,2,3,4";
var projDeptArray = projDepts.split(',');
var project_depts = document.getElementsByName("prdept[]");
for (var i = 0; i < projDeptArray.length; i++) {
  for (var j = 0; j < project_depts.length; j++) {
    if (projDeptArray[i] == project_depts[j]) {
      $(project_depts[i]).prop("checked", true)
    }
  }
}

This code is not working and none of the checkboxes got checked, I know I am getting somewhere wrong. Please someone help me to a solution for this.

Body:
Map that split string to id selectors and pass to jQuery as a one liner

var projDepts = "1,3,4";
var checkboxSelectors = projDepts.split(",").map(s => '#project_dept' +s).join() ;
$(checkboxSelectors).prop('checked', true);

console.log(checkboxSelectors )

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label> <input type="checkbox" name="project_dept[]" id="project_dept1" value="1">Development</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept2" value="2">Designing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept3" value="3">Testing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept4" value="4">Finance</label>

Or another way using prop(propertyName, function)

var projDepts = "1,3,4",
  projDeptArray = projDepts.split(',');

$(':checkbox[name="project_dept[]"]').prop('checked', function() {
  return projDeptArray.includes(this.value)
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label> <input type="checkbox" name="project_dept[]" id="project_dept1" value="1">Development</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept2" value="2">Designing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept3" value="3">Testing</label>
<label> <input type="checkbox" name="project_dept[]" id="project_dept4" value="4">Finance</label>


问:
How to check if task<List<userMethod>> is empty
App.Database.query(UserName.Text, Password.Text) return listAsync but even there is no user is displayed YES !!

```<code>private async void Button_Clicked_1(object sender, EventArgs e)
{
    if(App.Database.query(txtUserName.Text, txtPassword.Text) == null )
    {
        await DisplayAlert("Alert", " No user", "OK");
    }
    else
    {
        await DisplayAlert("Alert", "Yes user", "OK");
    }
}
</code>```

答:
If it is return Task<IList<T>>, and async, you will need to await it and check for empty list.

```<code>...
var users = await App.Database.query(txtUserName.Text, txtPassword.Text);
if(!users.Any())
...
</code>```

Body:
App.Database.query(UserName.Text, Password.Text) return listAsync but even there is no user is displayed YES !!

private async void Button_Clicked_1(object sender, EventArgs e)
{
    if(App.Database.query(txtUserName.Text, txtPassword.Text) == null )
    {
        await DisplayAlert("Alert", " No user", "OK");
    }
    else
    {
        await DisplayAlert("Alert", "Yes user", "OK");
    }
}

Body:
If it is return Task<IList<T>>, and async, you will need to await it and check for empty list.

...
var users = await App.Database.query(txtUserName.Text, txtPassword.Text);
if(!users.Any())
...


答:
Consider updating your controller to the following, which simplifies the query to the PX table and ensures that you grab the appropriate value:

```<code>public ActionResult Delete(string User)
{

    var db = new DataContext();
    var u = db.PX.Where(x=> x.Email == User).FirstOrDefault();  //This line updated
    db.PX.Remove(u);
    db.SaveChanges();
    return RedirectToAction("Index");

}
</code>```

EDIT to reflect comment

In your Delete(string User) method, you are trying to return the Delete view, but really you want to reroute to the Index view.

Title: Issue with Delete Action returning HttpNotFound MVC

Body:
i have list of user Emails and than i try to make delete method , but i didnt understand why it just returning HttpNotFound , did i miss something!Can anyone direct me in the right direction? thx

Controller:

public ActionResult Delete(string User)
{

    var db = new DataContext();
    var u = db.PX.Find(User);
    if (u==null)
    {
        return HttpNotFound();
    }
    return View(u);

}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string User)
{
    var db = new DataContext();
    var u = db.PX.Find(User);
    db.PX.Remove(u);
    db.SaveChanges();
    return RedirectToAction("Index");
}

View - Index:

            Email

        @foreach (var user in Model)
        {

                     delete

        }

Class :

public class user
{
    public string Email { get; set; }
    private string password = "";

    } }
}

Body:
Consider updating your controller to the following, which simplifies the query to the PX table and ensures that you grab the appropriate value:

public ActionResult Delete(string User)
{

    var db = new DataContext();
    var u = db.PX.Where(x=> x.Email == User).FirstOrDefault();  //This line updated
    db.PX.Remove(u);
    db.SaveChanges();
    return RedirectToAction("Index");

}

EDIT to reflect comment

In your Delete(string User) method, you are trying to return the Delete view, but really you want to reroute to the Index view.


问:
Automatic update a Windows application
How do I develop my Windows application so it will auto update on the client machine, like Firefox, Skype, etc.?

Is there any simple approach or any open source library which help me to do it just following some steps or a few lines of code?

答: You can use wyUpdate or .NET Application Updater Component</p>

Title: Automatic update a Windows application


问:
react-day-picker setState delayed to display on console

After the first date selection the selected date is not displayed on console and delayed and only set on state on the next selection.

This is the link to my code.
go to sample code

Am i missing something? I expect it to display on console on the first selection.

答:
setState is asynchronous.

If you call setState and immediately use this.state, chances are it will not be updated yet.

If you want to set the state and immediately act on that change, you can pass in a callback function.

So, in your case his code will work:

```<code>handleFromChange(from) {
    this.setState({ from }, () => console.log(this.state));
}
</code>```

Docs:

setState() does not immediately mutate this.state but creates a
  pending state transition. Accessing this.state after calling this
  method can potentially return the existing value. There is no
  guarantee of synchronous operation of calls to setState and calls may
  be batched for performance gains.

Body:
setState is asynchronous.

If you call setState and immediately use this.state, chances are it will not be updated yet.

If you want to set the state and immediately act on that change, you can pass in a callback function.

So, in your case his code will work:

handleFromChange(from) {
    this.setState({ from }, () => console.log(this.state));
}

Docs:

setState() does not immediately mutate this.state but creates a
  pending state transition. Accessing this.state after calling this
  method can potentially return the existing value. There is no
  guarantee of synchronous operation of calls to setState and calls may
  be batched for performance gains.


问:
Is there a way to dump a stack trace without throwing an exception in java?
I am thinking of creating a debug tool for my Java application.

I am wondering if it is possible to get a stack trace, just like Exception.printStackTrace() but without actually throwing an exception?

My goal is to, in any given method, dump a stack to see who the method caller is.

答:
Java 9 introduced the StackWalker and supporting classes for walking the stack.

Here are a few snippets from the Javadoc:

The walk method opens a sequential stream of StackFrames for the current thread and then applies the given function to walk the StackFrame stream. The stream reports stack frame elements in order, from the top most frame that represents the execution point at which the stack was generated to the bottom most frame. The StackFrame stream is closed when the walk method returns. If an attempt is made to reuse the closed stream, IllegalStateException will be thrown.

...

To snapshot the top 10 stack frames of the current thread,

```<code>List<StackFrame> stack = StackWalker.getInstance().walk(s ->
 s.limit(10).collect(Collectors.toList()));
</code>```

Body:
Java 9 introduced the StackWalker and supporting classes for walking the stack.

Here are a few snippets from the Javadoc:

The walk method opens a sequential stream of StackFrames for the current thread and then applies the given function to walk the StackFrame stream. The stream reports stack frame elements in order, from the top most frame that represents the execution point at which the stack was generated to the bottom most frame. The StackFrame stream is closed when the walk method returns. If an attempt is made to reuse the closed stream, IllegalStateException will be thrown.

...

To snapshot the top 10 stack frames of the current thread,

List<StackFrame> stack = StackWalker.getInstance().walk(s ->
 s.limit(10).collect(Collectors.toList()));


问:
ToolStripMenuSeparator prevents Disable/Enable programmatically of ToolStripMenuItems
I am using this part of code below to disable some ToolStripMenuItems whose tag is M2 for example. The problem is that code works, untill it "meets" the first ToolStripMenuSeparator. Even if ToolStripMenuItems under ToolStripMenuSeparator have M2 as tag, remain enabled. If I manually remove the ToolStripMenuSeparator everything is okay!!! There is any difference in case we have a separator between menu items?

```<code>Dim MenuItem As ToolStripMenuItem
    For Each MenuItem In MainForm_MenuStrip.Items
        If (MenuItem.GetType() Is GetType(ToolStripMenuItem)) Then
            Dim MenuSubItem As ToolStripMenuItem
            For Each MenuSubItem In MenuItem.DropDownItems
                If (MenuSubItem.GetType() Is GetType(ToolStripMenuItem)) And MenuSubItem.Tag = "M2" Then
                    MenuSubItem.Enabled = False
                End If
            Next
        End If
    Next
</code>```

答:
The main problem is that ToolStripSeparator can not be casted to ToolStripMenuItem.
So the following line will throw an InvalidCastException as soon as the loop reaches the ToolStripSeparator:

```<code>For Each MenuSubItem In MenuItem.DropDownItems
</code>```

If you cast to ToolStripItem instead it will work fine.
Furthermore you should define MenuItem as Object instead, otherwise your code will fail as soon as there's a ToolStripTextbox or ToolStripCombobox in the menu. Also the GetType-parts can be replaced with TypeOf.

```<code>For Each MenuItem As Object In Mainform_MenuStrip.Items
    If TypeOf MenuItem Is ToolStripMenuItem Then
        For Each MenuSubItem As ToolStripItem In MenuItem.DropDownItems
            If TypeOf MenuSubItem Is ToolStripMenuItem AndAlso MenuSubItem.Tag = "M2" Then
                MenuSubItem.Enabled = False
            End If
        Next
    End If
Next
</code>```

This example uses late-binding.

Following will also work with Option Strict On:

```<code>For Each MenuItem As ToolStripItem In Mainform_MenuStrip.Items
    If TypeOf MenuItem Is ToolStripMenuItem Then
        For Each MenuSubItem As ToolStripItem In DirectCast(MenuItem, ToolStripMenuItem).DropDownItems
            If TypeOf MenuSubItem Is ToolStripMenuItem AndAlso CStr(MenuSubItem.Tag) = "M2" Then
                MenuSubItem.Enabled = False
            End If
        Next
    End If
Next
</code>```

Body:
I am using this part of code below to disable some ToolStripMenuItems whose tag is M2 for example. The problem is that code works, untill it "meets" the first ToolStripMenuSeparator. Even if ToolStripMenuItems under ToolStripMenuSeparator have M2 as tag, remain enabled. If I manually remove the ToolStripMenuSeparator everything is okay!!! There is any difference in case we have a separator between menu items?

Dim MenuItem As ToolStripMenuItem
    For Each MenuItem In MainForm_MenuStrip.Items
        If (MenuItem.GetType() Is GetType(ToolStripMenuItem)) Then
            Dim MenuSubItem As ToolStripMenuItem
            For Each MenuSubItem In MenuItem.DropDownItems
                If (MenuSubItem.GetType() Is GetType(ToolStripMenuItem)) And MenuSubItem.Tag = "M2" Then
                    MenuSubItem.Enabled = False
                End If
            Next
        End If
    Next

Body:
The main problem is that ToolStripSeparator can not be casted to ToolStripMenuItem.
So the following line will throw an InvalidCastException as soon as the loop reaches the ToolStripSeparator:

For Each MenuSubItem In MenuItem.DropDownItems

If you cast to ToolStripItem instead it will work fine.
Furthermore you should define MenuItem as Object instead, otherwise your code will fail as soon as there's a ToolStripTextbox or ToolStripCombobox in the menu. Also the GetType-parts can be replaced with TypeOf.

For Each MenuItem As Object In Mainform_MenuStrip.Items
    If TypeOf MenuItem Is ToolStripMenuItem Then
        For Each MenuSubItem As ToolStripItem In MenuItem.DropDownItems
            If TypeOf MenuSubItem Is ToolStripMenuItem AndAlso MenuSubItem.Tag = "M2" Then
                MenuSubItem.Enabled = False
            End If
        Next
    End If
Next

This example uses late-binding.

Following will also work with Option Strict On:

For Each MenuItem As ToolStripItem In Mainform_MenuStrip.Items
    If TypeOf MenuItem Is ToolStripMenuItem Then
        For Each MenuSubItem As ToolStripItem In DirectCast(MenuItem, ToolStripMenuItem).DropDownItems
            If TypeOf MenuSubItem Is ToolStripMenuItem AndAlso CStr(MenuSubItem.Tag) = "M2" Then
                MenuSubItem.Enabled = False
            End If
        Next
    End If
Next


问:
Node.js POST method error 404
I built an index.js file which sends SMS based on body input while posting with Postman. The code is working and looks like this (I have hidden my apiKey and apiSecret for this preview)

```<code>const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const Nexmo = require('nexmo');
const nexmo = new Nexmo({
   apiKey: 'hidden.apiKey',
   apiSecret: 'hidden.apiSecret'
   });

app.post('/send', (req, res) => {
// Sending SMS via Nexmo
nexmo.message.sendSms(
    '4542542445', req.body.toNumber, req.body.message, {type: 'unicode'},
  (err, responseData) => {if (responseData) {console.log(responseData)}}
);
});
const server = app.listen(3000);
console.log("starting server")
</code>```

It woks fine and I receive an SMS message when I run the file, and a post to the route using Postman.

I am trying to implement the same in my bigger project, where I have separate client and server folders representing my frontend and backend.

When I add the code to my app.js file, I run into Status code 404 not found error. Here is the code of my app.js:

```<code>const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const {sequelize} = require('./models')
const config = require('./config/config')
const Nexmo = require('nexmo')

const app = express()

app.use(morgan('combined'))

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false}))

app.use(cors())

require('./routes')(app)

sequelize.sync()
.then(() => {
    app.listen(config.port)
    console.log(`Server started on port ${config.port}`)
})

const nexmo = new Nexmo({
apiKey: 'hidden.apiKey',
apiSecret: 'hidden.apiSecret'
}, {debug: true})

app.post('/send', (req, res) => {
// Sending SMS via Nexmo
nexmo.message.sendSms(
    '4542542445', req.body.toNumber, req.body.message, {type: 'unicode'},
  (err, responseData) => {if (responseData) {console.log(responseData)}}
);
  });
</code>```

I am asking for help to try figure out what is wrong and why it does not hit the route, instead returning status code 404.

I can share my github or we can talk on discord: soko#8667

I appreciate your thoughts and help.

答:
I managed to make it work.

I was adding new route while my server was running.

I restarted my PC and ran server and client again and it seems work.

Title: Node.js POST method error 404

Body:
I built an index.js file which sends SMS based on body input while posting with Postman. The code is working and looks like this (I have hidden my apiKey and apiSecret for this preview)

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const Nexmo = require('nexmo');
const nexmo = new Nexmo({
   apiKey: 'hidden.apiKey',
   apiSecret: 'hidden.apiSecret'
   });

app.post('/send', (req, res) => {
// Sending SMS via Nexmo
nexmo.message.sendSms(
    '4542542445', req.body.toNumber, req.body.message, {type: 'unicode'},
  (err, responseData) => {if (responseData) {console.log(responseData)}}
);
});
const server = app.listen(3000);
console.log("starting server")

It woks fine and I receive an SMS message when I run the file, and a post to the route using Postman.

I am trying to implement the same in my bigger project, where I have separate client and server folders representing my frontend and backend.

When I add the code to my app.js file, I run into Status code 404 not found error. Here is the code of my app.js:

const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const morgan = require('morgan')
const {sequelize} = require('./models')
const config = require('./config/config')
const Nexmo = require('nexmo')

const app = express()

app.use(morgan('combined'))

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false}))

app.use(cors())

require('./routes')(app)

sequelize.sync()
.then(() => {
    app.listen(config.port)
    console.log(`Server started on port ${config.port}`)
})

const nexmo = new Nexmo({
apiKey: 'hidden.apiKey',
apiSecret: 'hidden.apiSecret'
}, {debug: true})

app.post('/send', (req, res) => {
// Sending SMS via Nexmo
nexmo.message.sendSms(
    '4542542445', req.body.toNumber, req.body.message, {type: 'unicode'},
  (err, responseData) => {if (responseData) {console.log(responseData)}}
);
  });

I am asking for help to try figure out what is wrong and why it does not hit the route, instead returning status code 404.

I can share my github or we can talk on discord: soko#8667

I appreciate your thoughts and help.


问:
Concat two json fields in one column in POSTGRESQL 9.6
Hello here is my query :

```<code>SELECT id,objecttype,(content->>'ip' || content->>'mask') as content,  FROM public."Route"
</code>```

I'd like to concat these two json fields (ip,mask) but with a space betwen them. I tried to use concat function, it works but I don't have the space between.

This is the error generate from the query above :

```<code>ERROR:  operator does not exist: text ->> unknown
LINE 1: SELECT id,objecttype,(content->>'ip' || content->>'ip') as c...
</code>```

The query works well with only one field, but I need two have the concatenation between these fields with a space between them.

Thanks

答:
You can use cast :

```<code>SELECT id,
       objecttype,
       (cast(content->>'ip' as text) || ' ' || cast(content->>'mask' as text)) as content
FROM public."Route"
</code>```

Body:
Hello here is my query :

SELECT id,objecttype,(content->>'ip' || content->>'mask') as content,  FROM public."Route"

I'd like to concat these two json fields (ip,mask) but with a space betwen them. I tried to use concat function, it works but I don't have the space between.

This is the error generate from the query above :

ERROR:  operator does not exist: text ->> unknown
LINE 1: SELECT id,objecttype,(content->>'ip' || content->>'ip') as c...

The query works well with only one field, but I need two have the concatenation between these fields with a space between them.

Thanks

Body:
You can use cast :

SELECT id,
       objecttype,
       (cast(content->>'ip' as text) || ' ' || cast(content->>'mask' as text)) as content
FROM public."Route"


问:
Customized strikethrough on title
I'm creating a website to school project and i want to put a strikethrough behind my title like in this image. I want that green lines behind text

I am working with HTML and CSS , someone know the code to get that beautiful strikethrough?

答:
Short example including overlaying both strikes should be

p {font-size: 130px; color: #f00;}
span {position: relative;}
span:before, span:after {content: ''; background: rgba(0,0,0,.5); border-radius: 20px; position: absolute; top: calc(50% - 20px); width: 56%; height: 40px; z-index: -1}
span:before {left: 0;}
span:after {right: 0;}

span.left:before {width: 100%;}
span.left:after {width: 100px; left: 0;}

span.longer:before {width: 60%; left: 8%}
span.longer:after {width: 43%; left: 47%;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
    <span>TEXT</span> <br>
    <span>WITH</span> <br>
    <span>STRIKE</span><br>
    <span class="left">LEFT</span>
    <span class="longer">OTHER</span>
</p></code>```

Using classes you can make overlays with different widths, etc. The basic idea  is obvious.

Title: Customized strikethrough on title

Body:
Short example including overlaying both strikes should be

p {font-size: 130px; color: #f00;}
span {position: relative;}
span:before, span:after {content: ''; background: rgba(0,0,0,.5); border-radius: 20px; position: absolute; top: calc(50% - 20px); width: 56%; height: 40px; z-index: -1}
span:before {left: 0;}
span:after {right: 0;}

span.left:before {width: 100%;}
span.left:after {width: 100px; left: 0;}

span.longer:before {width: 60%; left: 8%}
span.longer:after {width: 43%; left: 47%;}

<p>
    <span>TEXT</span> <br>
    <span>WITH</span> <br>
    <span>STRIKE</span><br>
    <span class="left">LEFT</span>
    <span class="longer">OTHER</span>
</p>

Using classes you can make overlays with different widths, etc. The basic idea  is obvious.


问:
PHP Facebook or twitter-like news feed
Hey guys, I'm creating a website and I'm wondering if any of you know how I can create a PHP facebook-like news feed or one similar to twitter. I prefer facebook's, so if you know of a way or you know of a helpful tutorial, that would greatly help. Thank you.</p>

答: You can check news every 10 seconds via javascript. And then, javascript runs generate.php . Generate.php generates a feed (i.e. xml feed)

Title: PHP Facebook or twitter-like news feed


问:
JNI function returning illegal UTF characters at android
Im trying to return string from JNI to android but its returning illegal UTF characters like this:

```<code>JNI DETECTED ERROR IN APPLICATION: input is not valid Modified UTF-8:
illegal start byte 0x80
04-12 16:08:09.899 18210-18372 A/art:art/runtime/runtime.cc:427]
string: '���� ���!��"��,"���"���#���$��%���
%��`&��'��H(���)��D*���*��X+��,���,���-��4.��|.��P/��t/���/��01��x1��
2��D2���2���3���4���5��06���6��9���9��;���;��H<��=��0=���=���>��8?��
</code>```

Here is the code which I am using:

```<code>JNIEXPORT jbyteArray Java_pakdata_com_qurantextc_MainActivity_get(
    JNIEnv *pEnv,
    jobject this,
    jint pageNo, jint lang) {

char* buffer=(char*)malloc(10000);  // this buffer contains the ayat
register unsigned int pageNumber = pageNo - 1;

char * header=(char*)malloc(1000);
sprintf(header,"[{\"OFFSET\":%d,\"DATA\":\"",pageNumber+1);
strcpy(buffer,header);

// to get the last ayat of the page
// this loop will fetch all ayats of the page

for (int i = start_ayat; i <= end_ayat; i++) {

sprintf(buffer+strlen(buffer),"<div class=\\\"qr0\\\" data-ayat=\\\"%d\\\" id=\"%d\\\"><span>",i+1,i+1);
get(lang, i, buffer + strlen(buffer)); // len is equal to length of buffer (   strlen()  )
        strcpy(buffer+strlen(buffer),"<\\/span><\\/div>");

}
  // char* footer;
sprintf(buffer+strlen(buffer),"<div class=\\\"pagebreak\">%d<a id=\\\"%d\\\"next\\\"href=\\\"\\/page\\/%d\\\"></a><\\/div <\\/div>\"}]",pageNumber+1,pageNumber+1,pageNumber+1);

__android_log_print(ANDROID_LOG_DEBUG, "LOG_TAG","string: '%s'" , buffer);
int l = strlen(buffer);
char c[l];
strcpy(c,replace(buffer,"\r","<br>"));

jbyteArray ret = (*pEnv)->NewByteArray(pEnv,l);
(*pEnv)->SetByteArrayRegion (pEnv,ret, 0, l, c);
const char * errorKind = NULL;
uint8_t utf8 = checkUtfytes(c, &errorKind);
if  (errorKind != NULL) {
    free(buffer);
    return ret;

} else {
    free(buffer);
    return ret;
}
</code>```

I have tried using this too:

```<code>return = (*pEnv)->NewStringUTF(pEnv,buffer)
</code>```

but it still contain illegal UTF characters..

Here is my android side code

```<code>byte[] ss = get(a, pos);
s= new String(ss,"UTF-8");
</code>```

Still getting illegal UTF character error.
I have tried encoding on java side but its no help either,
I am posting here because all other methods that are written here i have already tried but it didn't worked.

PLEASE HELP!!!

答: May be I am late but your code seems to be correct but according to JNI documentation they doesn't support these characters. You have to handle it from server side. Hope it helps.</p>

Body:
Im trying to return string from JNI to android but its returning illegal UTF characters like this:

JNI DETECTED ERROR IN APPLICATION: input is not valid Modified UTF-8:
illegal start byte 0x80
04-12 16:08:09.899 18210-18372 A/art:art/runtime/runtime.cc:427]
string: '���� ���!��"��,"���"���#���$��%���
%��`&��'��H(���)��D*���*��X+��,���,���-��4.��|.��P/��t/���/��01��x1��
2��D2���2���3���4���5��06���6��9���9��;���;��H<��=��0=���=���>��8?��

Here is the code which I am using:

JNIEXPORT jbyteArray Java_pakdata_com_qurantextc_MainActivity_get(
    JNIEnv *pEnv,
    jobject this,
    jint pageNo, jint lang) {

char* buffer=(char*)malloc(10000);  // this buffer contains the ayat
register unsigned int pageNumber = pageNo - 1;

char * header=(char*)malloc(1000);
sprintf(header,"[{\"OFFSET\":%d,\"DATA\":\"",pageNumber+1);
strcpy(buffer,header);

// to get the last ayat of the page
// this loop will fetch all ayats of the page

for (int i = start_ayat; i <= end_ayat; i++) {

sprintf(buffer+strlen(buffer),"
",i+1,i+1);
get(lang, i, buffer + strlen(buffer)); // len is equal to length of buffer (   strlen()  )
        strcpy(buffer+strlen(buffer),"<\\/span><\\/div>");

}
  // char* footer;
sprintf(buffer+strlen(buffer),"
%d<\\/div <\\/div>\"}]",pageNumber+1,pageNumber+1,pageNumber+1);

__android_log_print(ANDROID_LOG_DEBUG, "LOG_TAG","string: '%s'" , buffer);
int l = strlen(buffer);
char c[l];
strcpy(c,replace(buffer,"\r","
"));

jbyteArray ret = (*pEnv)->NewByteArray(pEnv,l);
(*pEnv)->SetByteArrayRegion (pEnv,ret, 0, l, c);
const char * errorKind = NULL;
uint8_t utf8 = checkUtfytes(c, &errorKind);
if  (errorKind != NULL) {
    free(buffer);
    return ret;

} else {
    free(buffer);
    return ret;
}

I have tried using this too:

return = (*pEnv)->NewStringUTF(pEnv,buffer)

but it still contain illegal UTF characters..

Here is my android side code

byte[] ss = get(a, pos);
s= new String(ss,"UTF-8");

Still getting illegal UTF character error.
I have tried encoding on java side but its no help either,
I am posting here because all other methods that are written here i have already tried but it didn't worked.

PLEASE HELP!!!


问:
How to make Material Design Menu (mat-menu) hide on mouseleave
I succeeded in making the menu appear on mouseenter. What I want to do now is make it disappear on the mouseleave event of the menu itself. Any ideas on how to make this possible?

```<code>    <button mat-button [mat-menu-trigger-for]="menu"
     #menuTrigger="matMenuTrigger" (mouseenter)="menuTrigger.openMenu()">
        TRIGGER BUTTON
    </button>
    <mat-menu #menu="matMenu" [overlapTrigger]="false"
     (mouseleave)="menuTrigger.closeMenu()">
         <button mat-menu-item [routerLink]="['sources']">
              <mat-icon>view_headline</mat-icon>
              MENU CHOICE
        </button>
    </mat-menu>
</code>```

答:
You can do this by wrapping the menu buttons in a  element:

HTML:

```<code><button mat-button
  [matMenuTriggerFor]="menu"
  (mouseenter)="openMyMenu()">
  Trigger
</button>
<mat-menu #menu="matMenu" overlapTrigger="false">
  <span (mouseleave)="closeMyMenu()">
    <button mat-menu-item>Item 1</button>
    <button mat-menu-item>Item 2</button>
  </span>
</mat-menu>
</code>```

Component:

```<code>export class MenuOverviewExample {
  @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;

  openMyMenu() {
    this.trigger.openMenu();
  }
  closeMyMenu() {
    this.trigger.closeMenu();
  }
}
</code>```

Demo (V5):

StackBlitz

Material V6:

StackBlitz

Body:
I succeeded in making the menu appear on mouseenter. What I want to do now is make it disappear on the mouseleave event of the menu itself. Any ideas on how to make this possible?

    <button mat-button [mat-menu-trigger-for]="menu"
     #menuTrigger="matMenuTrigger" (mouseenter)="menuTrigger.openMenu()">
        TRIGGER BUTTON
    </button>
    <mat-menu #menu="matMenu" [overlapTrigger]="false"
     (mouseleave)="menuTrigger.closeMenu()">
         <button mat-menu-item [routerLink]="['sources']">
              <mat-icon>view_headline</mat-icon>
              MENU CHOICE
        </button>
    </mat-menu>

Body:
You can do this by wrapping the menu buttons in a <span> element:

HTML:

<button mat-button
  [matMenuTriggerFor]="menu"
  (mouseenter)="openMyMenu()">
  Trigger
</button>
<mat-menu #menu="matMenu" overlapTrigger="false">
  <span (mouseleave)="closeMyMenu()">
    <button mat-menu-item>Item 1</button>
    <button mat-menu-item>Item 2</button>
  </span>
</mat-menu>

Component:

export class MenuOverviewExample {
  @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;

  openMyMenu() {
    this.trigger.openMenu();
  }
  closeMyMenu() {
    this.trigger.closeMenu();
  }
}

Demo (V5):

StackBlitz

Material V6:

StackBlitz


问:
Yii2 RESTful: Content Negotiation languages not work
I implemented a structure of API Rest with the models in Yii2. Everything works great for actions (index, create, update etc ...) and methods (GET, POST, PUT etc ..) but I have a problem with the ContentNegotiator class.
Specifically, if I pass as a parameter of GET the language in which the response is to be translated, this is ignored.
According to the documentation for setting the language of response we need to set allowed languages of ContentNegotiator (look at my behaviors()) and make a request like this:

http://localhost/api/v1/users?_lang=it-IT

But the response continues to be in English. Why??? Nothing against the English =)

This is my ActiveController child class that extend from yii\rest\Controller.

```<code>use yii\rest\ActiveController;
use yii\filters\VerbFilter;

class AActiveController extends ActiveController
{
    public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors['verbFilter'] = [
            'class' => VerbFilter::className(),
            'actions' => $this->verbs(),
        ];
        $behaviors['contentNegotiator']['languages'] = [
            'en-EN',
            'it-IT',
            'de-DE',
            'ru-RU',
        ];

        return $behaviors;
    }
...
</code>```

N.B.: I debug through yii\filters\ContentNegotiator class of the framework and at this point the app language is set correctly but the response is always in English.

negotiate() public method

```<code>public function negotiate()
{
    $request = $this->request ?: Yii::$app->getRequest();
    $response = $this->response ?: Yii::$app->getResponse();
    if (!empty($this->formats)) {
        $this->negotiateContentType($request, $response);
    }
    if (!empty($this->languages)) {
        Yii::$app->language = $this->negotiateLanguage($request);
    }
    debug(Yii::$app->language); // result OK!: it-IT
}
</code>```

答:
Looks like some build-in errors not translated, for example yii\rest\Action:103 throws throw new NotFoundHttpException("Object not found: $id") its not translated. You have different ways to solve this problem:

Good way. Extend this Action and throw correct exception with translate

Bad way. Edit framework file itself.

Best way. Create patch to framework and send to maintainers.

For more information about i18n see documentation.

Body:
I implemented a structure of API Rest with the models in Yii2. Everything works great for actions (index, create, update etc ...) and methods (GET, POST, PUT etc ..) but I have a problem with the ContentNegotiator class.
Specifically, if I pass as a parameter of GET the language in which the response is to be translated, this is ignored.
According to the documentation for setting the language of response we need to set allowed languages of ContentNegotiator (look at my behaviors()) and make a request like this:

http://localhost/api/v1/users?_lang=it-IT

But the response continues to be in English. Why??? Nothing against the English =)

This is my ActiveController child class that extend from yii\rest\Controller.

use yii\rest\ActiveController;
use yii\filters\VerbFilter;

class AActiveController extends ActiveController
{
    public function behaviors()
    {
        $behaviors = parent::behaviors();

        $behaviors['verbFilter'] = [
            'class' => VerbFilter::className(),
            'actions' => $this->verbs(),
        ];
        $behaviors['contentNegotiator']['languages'] = [
            'en-EN',
            'it-IT',
            'de-DE',
            'ru-RU',
        ];

        return $behaviors;
    }
...

N.B.: I debug through yii\filters\ContentNegotiator class of the framework and at this point the app language is set correctly but the response is always in English.

negotiate() public method

public function negotiate()
{
    $request = $this->request ?: Yii::$app->getRequest();
    $response = $this->response ?: Yii::$app->getResponse();
    if (!empty($this->formats)) {
        $this->negotiateContentType($request, $response);
    }
    if (!empty($this->languages)) {
        Yii::$app->language = $this->negotiateLanguage($request);
    }
    debug(Yii::$app->language); // result OK!: it-IT
}


问:
What is hasProtectedContent for AVAsset
I notice this property hasProtectedContent in the AVAsset which is very vaguely defined.

Assets containing protected content may not be playable without successful authorization, even if the value of the playable property is YES. [doc]

Can someone elaborate what is protected content property means and when it will be true? Is it always required (or good practice) to check for this value before attempting to play the video?

答:
I am not sure what it means for third party sources, but this property is used to detect whether an asset is DRM protected or not. In my case, I use it to check if a chosen song from user's music library is DRM protected or not as the songs from Apple Music (subscription) are DRM protected. hasProtectedContent is true for such songs and false for the ones which are DRM-free. Such DRM-protected songs cannot be played by AVPlayer and only by MPMusicPlayer.

If you are interested in detecting whether an asset is DRM protected or in playing such assets the right way, you can read my detailed answer here: https://stackoverflow.com/a/47694472/4331787

Title: What is hasProtectedContent for AVAsset