问:
Laravel 5.4 - Pagination method works wrong?
I've asked a question about the paginate method from laravel cause I couldn't make it to get the output I needed. I wanted to get all records where the name column contains a specific string.

Anyway, what happens is that I get the whole table content + the links are changing immediately:

The little code snippet ( I've tried many different thinks out )

```<code>$search = $request['search'];
$usergroups = Usergroups::where('name', 'like', '%' . $search . '%')->paginate(3);
</code>```

I'm not so sure but I think in my case there is an problem that doesn't come from my code. If I output $usergroups I get this:

```<code>current_page    1
data:
   // my data
from    1
last_page   2
next_page_url   "http://blabla.de/test?page=2"
path    "http://blabla.de/test"
per_page    3
prev_page_url
to  3
total   5
</code>```

You can clearly see that there is a total of 5 items ( and thats true, I've expected to get 5 items ), and there are 2 pages. Thats also true cause I've set the pagination to paginate(3).

If I output the links in my blade I get something like this:

But if I click on "2" - to get to the last page of that pagination, I don't know why but the links are changing immediately from 1-2 to 1-7.

Without reloading the page or anything.

So before I want to change the pagination link, I get the right amound of items, but if I change to ?page=2, I get all the items in my table. I don't know why but maybe thats a mistake by laravel. I've also tried it with laravel 5.3 ( currently 5.4 ) but got the same problem. If I look into the phpmyadmin query log and manually try the query out, I also get the perfect output. If I use ->get() instead of ->paginate(); I also get the output I want. I have no clue anymore. Maybe anyone knows an answer? Or something I can to? I don't want output my whole table if the user want to search for a specific item

Thanks for any advice and sorry because of my bad english!

search form:

```<code><form id="search" action="{{ route("test") }}" method="get">
                <input type="hidden" name="_token" value="{{ csrf_token() }}">
                <p>
                    <small class="text-muted">Suche durch Stichwörter nach Gruppen!</small>
                </p>
                <input class="form-control searchbar" name="search" type="text"><br>
                <button type="submit" class="btn btn-lg btn-outline"><i class="fa fa-search"></i>Suchen</button>
            </form>
</code>```

route :

```<code>Route::get('test', ['as' => 'test', 'uses' => 'Group\GroupController@test'] );
</code>```

Controller:

```<code>$search = Input::get('search');
$usergroups = Usergroups::where('name', 'like', '%' . $search . '%');
        $usergroups = $usergroups->paginate(3);
        return view('test.test')->with('category_groups', $usergroups);
</code>```

pagination snippet:

```<code>    {{ $usergroups->appends(['search' => request()->query('search')])->links() }}

        <div class="row">
            @foreach($usergroups as $group)
                <div class="col-xs-12 col-sm-6 col-md-4">
                    <div class="group-style">
                        <div class="list-group" style="border: none">
                            <div class="list-group-item">
                                    <h4 class="list-group-item-heading">{{ $group['name'] }}</h4>
                                <p class="list-group-item-text text-center">
                                    {{ $group['description'] }}
                                </p>
                                <br>
                            </div>
                        </div>
                        <div class="list-group">
                            <a target="_blank" href="{{ $group['link'] }}">
                                <div class="list-group-footer">
                                    <i class="fa fa-plus"></i> Beitreten!
                                </div>
                            </a>
                        </div>
                    </div>
                </div>
            @endforeach
        </div>
    {{ $usergroups->appends(['search' => request()->query('search')])->links() }}
</code>```

The URL now looks like:

```<code>http://bla.bla.com/test?search=Test
</code>```

答:
Seems like the search parameter is not added to the links of the paginator and because of that the number of pages increases.

By your code ($search = $request['search']) it's not clear if the parameter is sent by GET or POST, but my assumption is that you send it as POST and that's the reason it's not added to the links.

So, change it to GET and Laravel will take care of the rest for you.

Body:
I've asked a question about the paginate method from laravel cause I couldn't make it to get the output I needed. I wanted to get all records where the name column contains a specific string.

Anyway, what happens is that I get the whole table content + the links are changing immediately:

The little code snippet ( I've tried many different thinks out )

$search = $request['search'];
$usergroups = Usergroups::where('name', 'like', '%' . $search . '%')->paginate(3);

I'm not so sure but I think in my case there is an problem that doesn't come from my code. If I output $usergroups I get this:

current_page    1
data:
   // my data
from    1
last_page   2
next_page_url   "http://blabla.de/test?page=2"
path    "http://blabla.de/test"
per_page    3
prev_page_url
to  3
total   5

You can clearly see that there is a total of 5 items ( and thats true, I've expected to get 5 items ), and there are 2 pages. Thats also true cause I've set the pagination to paginate(3).

If I output the links in my blade I get something like this:

But if I click on "2" - to get to the last page of that pagination, I don't know why but the links are changing immediately from 1-2 to 1-7.

Without reloading the page or anything.

So before I want to change the pagination link, I get the right amound of items, but if I change to ?page=2, I get all the items in my table. I don't know why but maybe thats a mistake by laravel. I've also tried it with laravel 5.3 ( currently 5.4 ) but got the same problem. If I look into the phpmyadmin query log and manually try the query out, I also get the perfect output. If I use ->get() instead of ->paginate(); I also get the output I want. I have no clue anymore. Maybe anyone knows an answer? Or something I can to? I don't want output my whole table if the user want to search for a specific item

Thanks for any advice and sorry because of my bad english!

search form:

<form id="search" action="{{ route("test") }}" method="get">
                <input type="hidden" name="_token" value="{{ csrf_token() }}">

                    Suche durch Stichwörter nach Gruppen!

                <input class="form-control searchbar" name="search" type="text">

                <button type="submit" class="btn btn-lg btn-outline">Suchen</button>
            </form>

route :

Route::get('test', ['as' => 'test', 'uses' => 'Group\GroupController@test'] );

Controller:

$search = Input::get('search');
$usergroups = Usergroups::where('name', 'like', '%' . $search . '%');
        $usergroups = $usergroups->paginate(3);
        return view('test.test')->with('category_groups', $usergroups);

pagination snippet:

    {{ $usergroups->appends(['search' => request()->query('search')])->links() }}

            @foreach($usergroups as $group)

{{ $group['name'] }}

                                    {{ $group['description'] }}

                                     Beitreten!

            @endforeach

    {{ $usergroups->appends(['search' => request()->query('search')])->links() }}

The URL now looks like:

http://bla.bla.com/test?search=Test


来源: stackexchange

问:
Which design pattern will be best for football match app
I am creating web api for application which support football team in collecting statistic data from matches. I am on implementing phase now. And lets say I am thinking what (if it is needed) type of design patter will be best for something like this:

```<code> public class Shot
{
    public int Id { get; set; }
    public int PlayerId { get; set; }
    public string Comment { get; set; }
    public bool OnGoal { get; set; }
    public int GameId { get; set; }

}
</code>```

and

```<code>public class Card
{
    public int Id { get; set; }
    public int PlayerId { get; set; }
    public string Comment { get; set; }
    public bool IsRed{ get; set; }
    public int GameId { get; set; }
}
</code>```

As You can see some properties are same. It should be implemented with interface, inheritance ( f.e. class Action) or maybe I should use one of Design patterns (which one)? What will be best for Entity Framework to avoid problems in later phases?

答:
Well, both your classes represent some kind of game event - shot and card. There could be some other game events, like a free kick, throw in, substitution, penalty, or corner kick. All of these events should have id, game id, player id, timestamp, and probably comment. So your problem is the duplication of data in several classes. It is easily solved with inheritance. No patterns required:

```<code>public abstract class GameEvent
{
    public int Id { get; set; }
    public int GameId { get; set; }
    public int PlayerId { get; set; }
    public TimeSpan Time { get; set; }
    public string Comment { get; set; }
}
</code>```

And various specific events

```<code>public class Shot : GameEvent
{
    public bool OnGoal { get; set; }
}

public class Card : GameEvent
{
    public bool IsRed { get; set; }
}
</code>```

You should also think about saving timestamp of added time because you can get both 46 minutes time span (start of second half) and 45+1 minutes of first half.

ContentLicense: CC BY-SA 3.0

Body:
I am creating web api for application which support football team in collecting statistic data from matches. I am on implementing phase now. And lets say I am thinking what (if it is needed) type of design patter will be best for something like this:

 public class Shot
{
    public int Id { get; set; }
    public int PlayerId { get; set; }
    public string Comment { get; set; }
    public bool OnGoal { get; set; }
    public int GameId { get; set; }

}

and

public class Card
{
    public int Id { get; set; }
    public int PlayerId { get; set; }
    public string Comment { get; set; }
    public bool IsRed{ get; set; }
    public int GameId { get; set; }
}

As You can see some properties are same. It should be implemented with interface, inheritance ( f.e. class Action) or maybe I should use one of Design patterns (which one)? What will be best for Entity Framework to avoid problems in later phases?

Body:
Well, both your classes represent some kind of game event - shot and card. There could be some other game events, like a free kick, throw in, substitution, penalty, or corner kick. All of these events should have id, game id, player id, timestamp, and probably comment. So your problem is the duplication of data in several classes. It is easily solved with inheritance. No patterns required:

public abstract class GameEvent
{
    public int Id { get; set; }
    public int GameId { get; set; }
    public int PlayerId { get; set; }
    public TimeSpan Time { get; set; }
    public string Comment { get; set; }
}

And various specific events

public class Shot : GameEvent
{
    public bool OnGoal { get; set; }
}

public class Card : GameEvent
{
    public bool IsRed { get; set; }
}

You should also think about saving timestamp of added time because you can get both 46 minutes time span (start of second half) and 45+1 minutes of first half.


问:
React server side rendering on API port instead of client
I have a react app I built with an express API to interact with mongoDB. I am now trying to set up server side rendering in my server.js file. I can't figure out why but the server rendered string is only being sent in the browser over my API port localhost:3899/api instead of localhost:3000 where my client is being served.

When I curl http://localhost:3899 I get the html string in my console. When I curl http://localhost:3000 I get the public/index.html skeleton.

I have my client and server directories next to each other at the same level.

node_modules

react-ui

server

...

server.js:

```<code>import express from 'express';
import path from 'path';
import React from 'react';
import 'ignore-styles';
import ReactDOMServer from 'react-dom/server';
import render from './render';
import App from '../react-ui/src/App';
import mongoose from 'mongoose';
import cors from 'cors';
import bodyParser from 'body-parser';
import Appointment from './model/appointments';

//and create our instances
var app = express();
var router = express.Router();

app.use(express.static(path.resolve(__dirname, '../react-ui/build/static')));
//set our port to either a predetermined port number if you have set
//it up, or 3899
var port = process.env.PORT || 3899;
//db config
mongoose.connect('mongodb://josh11:josh11@ds133162.mlab.com:33162/heroku_tl016m5d');
app.use(cors());
//now we should configure the API to use bodyParser and look for
//JSON data in the request body
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

//now we can set the route path & initialize the API
router.get('/', function(request, response) {
  response.render(
    <!doctype html>
    <html>
        <header>
            <title>My Universal App</title>
        </header>
        <body>
            <div id='app'>${ReactDOMServer.renderToString(<App />)}</div>
            <script src='bundle.js'></script>
        </body>
    </html>
  );
});

//Use our router configuration when we call /api
app.use('/api', router);
//starts the server and listens for requests
app.listen(port, function() {
  console.log('api running on port' + port);
});
//adding the /appointments route to our /api router
router.route('/appointments')
  //retrieve all appointments from the database
  .get(function(request, response) {
    //looks at our Appointment Schema
    Appointment.find(function(error, appointments) {
      if (error)
        response.send(error);
      //responds with a json object of our database appointments.
      response.json(appointments)
    });
  })
  //post new appointment to the database
  .post(function(request, response) {
    var appointment = new Appointment();
    //body parser lets us use the req.body
    appointment.appointmentTitle = req.body.appointmentTitle;
    appointment.appointmentDate = req.body.appointmentDate;
    appointment.appointmentTime = req.body.appointmentTime;
    appointment.appointmentDescription = req.body.appointmentDescription;
    appointment.appointmentDestination = req.body.appointmentDestination;
    appointment.appointmentOrigin = req.body.appointmentOrigin;
    appointment.travelMode = req.body.travelMode;
    appointment.save(function(error) {
    if (error)
      response.send(error);
      response.json({ message: 'Appointment successfully added!' });
    });
  });
</code>```

Any guidance would be much appreciated.

答:
To run the application on port defined by environment, try

```<code>PORT=3000 node server.js
</code>```

You have other issue in your code. You have defined the router and mounting the router /api by defining app.use('/api', router). Hence, you are getting 404 whenever you access http://localhost:3000.

To fix the issue, change the router mounting to api.use('/', router).

ContentLicense: CC BY-SA 4.0

Body:
I have a react app I built with an express API to interact with mongoDB. I am now trying to set up server side rendering in my server.js file. I can't figure out why but the server rendered string is only being sent in the browser over my API port localhost:3899/api instead of localhost:3000 where my client is being served.

When I curl http://localhost:3899 I get the html string in my console. When I curl http://localhost:3000 I get the public/index.html skeleton.

I have my client and server directories next to each other at the same level.

node_modules

react-ui

server

...

server.js:

import express from 'express';
import path from 'path';
import React from 'react';
import 'ignore-styles';
import ReactDOMServer from 'react-dom/server';
import render from './render';
import App from '../react-ui/src/App';
import mongoose from 'mongoose';
import cors from 'cors';
import bodyParser from 'body-parser';
import Appointment from './model/appointments';

//and create our instances
var app = express();
var router = express.Router();

app.use(express.static(path.resolve(__dirname, '../react-ui/build/static')));
//set our port to either a predetermined port number if you have set
//it up, or 3899
var port = process.env.PORT || 3899;
//db config
mongoose.connect('mongodb://josh11:josh11@ds133162.mlab.com:33162/heroku_tl016m5d');
app.use(cors());
//now we should configure the API to use bodyParser and look for
//JSON data in the request body
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

//now we can set the route path & initialize the API
router.get('/', function(request, response) {
  response.render(
    <!doctype html>

            <title>My Universal App</title>

${ReactDOMServer.renderToString(<App />)}

  );
});

//Use our router configuration when we call /api
app.use('/api', router);
//starts the server and listens for requests
app.listen(port, function() {
  console.log('api running on port' + port);
});
//adding the /appointments route to our /api router
router.route('/appointments')
  //retrieve all appointments from the database
  .get(function(request, response) {
    //looks at our Appointment Schema
    Appointment.find(function(error, appointments) {
      if (error)
        response.send(error);
      //responds with a json object of our database appointments.
      response.json(appointments)
    });
  })
  //post new appointment to the database
  .post(function(request, response) {
    var appointment = new Appointment();
    //body parser lets us use the req.body
    appointment.appointmentTitle = req.body.appointmentTitle;
    appointment.appointmentDate = req.body.appointmentDate;
    appointment.appointmentTime = req.body.appointmentTime;
    appointment.appointmentDescription = req.body.appointmentDescription;
    appointment.appointmentDestination = req.body.appointmentDestination;
    appointment.appointmentOrigin = req.body.appointmentOrigin;
    appointment.travelMode = req.body.travelMode;
    appointment.save(function(error) {
    if (error)
      response.send(error);
      response.json({ message: 'Appointment successfully added!' });
    });
  });

Any guidance would be much appreciated.

Body:
To run the application on port defined by environment, try

PORT=3000 node server.js

You have other issue in your code. You have defined the router and mounting the router /api by defining app.use('/api', router). Hence, you are getting 404 whenever you access http://localhost:3000.

To fix the issue, change the router mounting to api.use('/', router).


问:
:hover effect on p:after in specific div
I cant seem to properly activate the :hover state for p elements inside a parent div

For all p elements in the parent div there is an :after with 0 width to create an underlining when hovered. I want the width to go from "0" to "2em" when the p is hovered.

I'm not sure how to properly target the p and the :after when hovered.

I though it should look something like below.

HTML

```<code><div class="parent">
    <p>Menu Option A</p>
    <p>Menu Option B</p>
</div>
</code>```

CSS

```<code>.top_menu_wrapper p:after {
  content: "";
  display: block;
  height: 3px;
  width: 0em;
  background: white;
  margin: auto;
  transition: all 0.4s ease;
}
.parent p:hover p:after {
  width: 2em;
}
</code>```

答:
If I understand your structure correctly, you're trying to target the :hover of the :after of any
 tag within the parent class.

To do this, you simply need to combine the two pseudo-selectors as one:

.parent p:hover:after.

The will target any
 child of .parent. If you want to target any
 tag that is a direct child of the .parent class, you can use the greater than symbol (>) as .parent > p:hover:after.

I've added some content to the target selector to help illustrate this.

.parent > p:hover:after {
  width: 2em;
  content: " - Hi there";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
  <p>Menu Option A</p>
  <p>Menu Option B</p>
</div>
<p>Doesn't get the :after effect</p></code>```

Hope this helps! :)

Body:
I cant seem to properly activate the :hover state for p elements inside a parent div

For all p elements in the parent div there is an :after with 0 width to create an underlining when hovered. I want the width to go from "0" to "2em" when the p is hovered.

I'm not sure how to properly target the p and the :after when hovered.

I though it should look something like below.

HTML

Menu Option A

Menu Option B

CSS

.top_menu_wrapper p:after {
  content: "";
  display: block;
  height: 3px;
  width: 0em;
  background: white;
  margin: auto;
  transition: all 0.4s ease;
}
.parent p:hover p:after {
  width: 2em;
}

Body:
If I understand your structure correctly, you're trying to target the :hover of the :after of any <p> tag within the parent class.

To do this, you simply need to combine the two pseudo-selectors as one:

.parent p:hover:after.

The will target any <p> child of .parent. If you want to target any <p> tag that is a direct child of the .parent class, you can use the greater than symbol (>) as .parent > p:hover:after.

I've added some content to the target selector to help illustrate this.

.parent > p:hover:after {
  width: 2em;
  content: " - Hi there";
}

<div class="parent">
  <p>Menu Option A</p>
  <p>Menu Option B</p>
</div>
<p>Doesn't get the :after effect</p>

Hope this helps! :)


问:
opening a javafx FileChooser in the user directory
I am trying to open a javafx FileChooser in the user directory according to an example I found here.

Here is a fragment of the simple code I am using:

```<code>FileChooser fc = new FileChooser();
fc.setTitle("Open Dialog");
String currentDir = System.getProperty("user.dir") + File.separator;
file = new File(currentDir);
fc.setInitialDirectory(file);
</code>```

However, I keep obtaining this warning (complete file paths have been truncated):

```<code>Invalid URL passed to an open/save panel: '/Users/my_user'.  Using 'file://localhost/Users/my_user/<etc>/' instead.
</code>```

I verified that the file object is an existing directory adding these lines:

```<code>System.out.println(file.exists()); //true
System.out.println(file.isDirectory()); //true
</code>```

Then I do not have idea why I am obtaining the warning message.

UPDATE:

This seems to be a bug in JavaFX: https://bugs.openjdk.java.net/browse/JDK-8098160
(you need to create a free Jira account to see the bug report).
This problem happens in OSX, no idea about other platforms.

答:
```<code>@FXML private Label label1; //total file path print
@FXML private Label labelFirst; //file dir path print

private String firstPath; //dir path save

public void method() {
    FileChooser fileChooser = new FileChooser();
    if (firstPath != null) {
        File path = new File(firstPath);
        fileChooser.initialDirectoryProperty().set(path);
    }
    fileChooser.getExtensionFilters().addAll(
            new ExtensionFilter("Text Files", "*.txt"),
            new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"),
            new ExtensionFilter("Audio Files", "*.wav", "*.mp3", "*.aac"),
            new ExtensionFilter("All Files", "*.*") );
    File selectFile = fileChooser.showOpenDialog(OwnStage);
    if (selectFile != null){
        String path = selectFile.getPath();
        int len = path.lastIndexOf("/"); //no detec return -1
        if (len == -1) {
            len = path.lastIndexOf("\\");
        }
        firstPath = path.substring(0, len);
        labelFirst.setText("file path : " + firstPath);
        label1.setText("First File Select: " + path);
    }

  }
</code>```

Body:
I am trying to open a javafx FileChooser in the user directory according to an example I found here.

Here is a fragment of the simple code I am using:

FileChooser fc = new FileChooser();
fc.setTitle("Open Dialog");
String currentDir = System.getProperty("user.dir") + File.separator;
file = new File(currentDir);
fc.setInitialDirectory(file);

However, I keep obtaining this warning (complete file paths have been truncated):

Invalid URL passed to an open/save panel: '/Users/my_user'.  Using 'file://localhost/Users/my_user/<etc>/' instead.

I verified that the file object is an existing directory adding these lines:

System.out.println(file.exists()); //true
System.out.println(file.isDirectory()); //true

Then I do not have idea why I am obtaining the warning message.

UPDATE:

This seems to be a bug in JavaFX: https://bugs.openjdk.java.net/browse/JDK-8098160
(you need to create a free Jira account to see the bug report).
This problem happens in OSX, no idea about other platforms.


问:
Force HTTP://subdomain. and HTTP://domain. to HTTPS (with .htaccess)
I got a quick question on redirecting to HTTPS.

I want

 to
 to

How can I make this possible? The point is, that I got several Domains linking to one Directory and I only want to use one single SSL Certificate.

Thanks to everyone out there who can help me :-)

Kind regards

答:
After hours of searching today I finally found a solution. Maybe it is useful for you so I would like to share:

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.tld [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.domain.tld/$1 [R,L]

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^((?!www\.)[^.]+)\.domain\.tld$
RewriteRule ^ https://%1.domain.tld%{REQUEST_URI} [NE,L,R]
</code>```

:-)

Body:
After hours of searching today I finally found a solution. Maybe it is useful for you so I would like to share:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.tld [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.domain.tld/$1 [R,L]

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^((?!www\.)[^.]+)\.domain\.tld$
RewriteRule ^ https://%1.domain.tld%{REQUEST_URI} [NE,L,R]

:-)


问:
Why this code is not running in emulator even if i have given all the permission in the code?

TelephonyManagerActivity.java

```<code>package com.lovepurohit.project15;

/**
* Program for telephony manager that means to access the details related
* to sim and phone number like IMEI number, Device type and many more
* <p/>
* For this we use TelephonyManagerActivity class which is in the package
* android.telephony.TelephonyManagerActivity;
*/

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

//importing our new package
import android.telephony.TelephonyManager;

import android.widget.TextView;

/**
* Created by Love on 04-07-2017.
*/
public class TelephonyManagerActivity extends AppCompatActivity {
TextView textView;

@Override

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

    //Getting id
    textView = (TextView) findViewById(R.id.textView);

    //Accessing the service for performing operation related to telephony
    TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    /**
     * Getting the phone Type
     * whether phone is cdma or gsm
     */
    int type = tm.getPhoneType();

    //Getting other details like IMEI number and device id and etc
    String IMEINumber = tm.getDeviceId();

    //getting subscriber ID
    String subscriberID = tm.getDeviceId();

    //Getting Sim serial number
    String SIMSerialNumber = tm.getSimSerialNumber();

    //Getting network details
    String networkCountryISO = tm.getNetworkCountryIso();

    //Getting sim country info
    String SIMCountryISO = tm.getSimCountryIso();

    //Getting the software on which app is running
    String softwareVersion = tm.getDeviceSoftwareVersion();

    //Getting the voice mail number on which app is running
    String voiceMailNumber = tm.getVoiceMailNumber();

    String strPhoneType = "";
    switch (type) {
        case (TelephonyManager.PHONE_TYPE_CDMA):
            strPhoneType = "CDMA";
            break;

        case (TelephonyManager.PHONE_TYPE_GSM):
            strPhoneType = "GSM";
            break;

        case (TelephonyManager.PHONE_TYPE_NONE):
            strPhoneType = "NONE";
            break;

    }

    boolean isRoaming = tm.isNetworkRoaming();

    String phoneInfo = "Phone Details: \n";
    phoneInfo += "\n IMEI Number: " + IMEINumber;
    phoneInfo += "\n SubscriberID: " + subscriberID;
    phoneInfo += "\n SIM Serial Number: " + SIMSerialNumber;
    phoneInfo += "\n Network Country ISO: " + networkCountryISO;
    phoneInfo += "\n SIMCountryISO: " + SIMCountryISO;
    phoneInfo += "\n SoftwreVersion: " + softwareVersion;
    phoneInfo += "\n VoiceMailNumber: " + voiceMailNumber;
    phoneInfo += "\n Phone Type: " + strPhoneType;
    phoneInfo += "\n Is Roaming? : " + isRoaming;

    textView.setText(phoneInfo);
}
}
</code>```

AndroidManifest.xml

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

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="adndroid.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <!-- Activity 25th our project -->
    <activity android:name=".SharedPreferences">
        <!-- <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter> -->
    </activity>

    <!-- Activity 26th of our project -->
    <activity android:name=".InternalStorage">
       <!-- <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter> -->
    </activity>

    <!-- Activity 27th of our project -->
    <activity android:name=".TelephonyManagerActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>
</code>```

Do I have to run it on the real device? I have added all the permission but it is not working in the emulator. And I'm using API 23 that is Marshmallow

答:
You can do thing likethis in your onCreateMethod. I am doing it for WRITE_EXTERNAL_STORAGE you can do the same thing for READ_PHONE_STATE</p>

```<code>if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                   if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                       //Show Information about why you need the permission
                       AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                       builder.setTitle("Need Storage Permission");
                       builder.setMessage("We needs storage permission to proceed");
                       builder.setPositiveButton("Allow", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                               ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
                           }
                       });
                       builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                           }
                       });
                       builder.show();
                   } else if (permissionStatus.getBoolean(Manifest.permission.WRITE_EXTERNAL_STORAGE,false)) {
                       //Previously Permission Request was cancelled with 'Dont Ask Again',
                       // Redirect to Settings after showing Information about why you need the permission
                       AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                       builder.setTitle("Storage Permission");
                       builder.setMessage("We need storage permission.");
                       builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                               sentToSettings = true;
                               Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                               Uri uri = Uri.fromParts("package", getPackageName(), null);
                               intent.setData(uri);
                               startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
                               Toast.makeText(getBaseContext(), "Go to Permissions to Grant Storage", Toast.LENGTH_LONG).show();
                           }
                       });
                       builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                           }
                       });
                       builder.show();
                   } else {
                       //just request the permission
                       ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
                   }

                   SharedPreferences.Editor editor = permissionStatus.edit();
                   editor.putBoolean(Manifest.permission.WRITE_EXTERNAL_STORAGE,true);
                   editor.commit();

               } else {
                   //You already have the permission, just go ahead.
                  textView = (TextView) findViewById(R.id.textView);

//Accessing the service for performing operation related to telephony
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

/**
 * Getting the phone Type
 * whether phone is cdma or gsm
 */
int type = tm.getPhoneType();

//Getting other details like IMEI number and device id and etc
String IMEINumber = tm.getDeviceId();

//getting subscriber ID
String subscriberID = tm.getDeviceId();

//Getting Sim serial number
String SIMSerialNumber = tm.getSimSerialNumber();

//Getting network details
String networkCountryISO = tm.getNetworkCountryIso();

//Getting sim country info
String SIMCountryISO = tm.getSimCountryIso();

//Getting the software on which app is running
String softwareVersion = tm.getDeviceSoftwareVersion();

//Getting the voice mail number on which app is running
String voiceMailNumber = tm.getVoiceMailNumber();

String strPhoneType = "";
switch (type) {
    case (TelephonyManager.PHONE_TYPE_CDMA):
        strPhoneType = "CDMA";
        break;

    case (TelephonyManager.PHONE_TYPE_GSM):
        strPhoneType = "GSM";
        break;

    case (TelephonyManager.PHONE_TYPE_NONE):
        strPhoneType = "NONE";
        break;

}

boolean isRoaming = tm.isNetworkRoaming();

 String phoneInfo = "Phone Details: \n";
    phoneInfo += "\n IMEI Number: " + IMEINumber;
    phoneInfo += "\n SubscriberID: " + subscriberID;
    phoneInfo += "\n SIM Serial Number: " + SIMSerialNumber;
    phoneInfo += "\n Network Country ISO: " + networkCountryISO;
    phoneInfo += "\n SIMCountryISO: " + SIMCountryISO;
    phoneInfo += "\n SoftwreVersion: " + softwareVersion;
    phoneInfo += "\n VoiceMailNumber: " + voiceMailNumber;
    phoneInfo += "\n Phone Type: " + strPhoneType;
    phoneInfo += "\n Is Roaming? : " + isRoaming;

    textView.setText(phoneInfo);
                   }

 @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode, resultCode, data);
       if (requestCode == REQUEST_PERMISSION_SETTING) {
           if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
              // Do the exact thing as in else condition above
           }
       }
   }

@Override
   public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
       super.onRequestPermissionsResult(requestCode, permissions, grantResults);
       if (requestCode == EXTERNAL_STORAGE_PERMISSION_CONSTANT) {
           if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               // Do the exact thing as in else condition above
           } else {
               if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                   //Show Information about why you need the permission
                   AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                   builder.setTitle("Need Storage Permission");
                   builder.setMessage("This app needs storage permission");
                   builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialog, int which) {
                           dialog.cancel();

                           ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);

                       }
                   });
                   builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialog, int which) {
                           dialog.cancel();
                       }
                   });
                   builder.show();
               } else {
                   Toast.makeText(getBaseContext(),"Unable to get Permission",Toast.LENGTH_LONG).show();
               }
           }
       }
   }
</code>```

Body:
TelephonyManagerActivity.java

package com.lovepurohit.project15;

/**
* Program for telephony manager that means to access the details related
* to sim and phone number like IMEI number, Device type and many more
*

* For this we use TelephonyManagerActivity class which is in the package
* android.telephony.TelephonyManagerActivity;
*/

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

//importing our new package
import android.telephony.TelephonyManager;

import android.widget.TextView;

/**
* Created by Love on 04-07-2017.
*/
public class TelephonyManagerActivity extends AppCompatActivity {
TextView textView;

@Override

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

    //Getting id
    textView = (TextView) findViewById(R.id.textView);

    //Accessing the service for performing operation related to telephony
    TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

    /**
     * Getting the phone Type
     * whether phone is cdma or gsm
     */
    int type = tm.getPhoneType();

    //Getting other details like IMEI number and device id and etc
    String IMEINumber = tm.getDeviceId();

    //getting subscriber ID
    String subscriberID = tm.getDeviceId();

    //Getting Sim serial number
    String SIMSerialNumber = tm.getSimSerialNumber();

    //Getting network details
    String networkCountryISO = tm.getNetworkCountryIso();

    //Getting sim country info
    String SIMCountryISO = tm.getSimCountryIso();

    //Getting the software on which app is running
    String softwareVersion = tm.getDeviceSoftwareVersion();

    //Getting the voice mail number on which app is running
    String voiceMailNumber = tm.getVoiceMailNumber();

    String strPhoneType = "";
    switch (type) {
        case (TelephonyManager.PHONE_TYPE_CDMA):
            strPhoneType = "CDMA";
            break;

        case (TelephonyManager.PHONE_TYPE_GSM):
            strPhoneType = "GSM";
            break;

        case (TelephonyManager.PHONE_TYPE_NONE):
            strPhoneType = "NONE";
            break;

    }

    boolean isRoaming = tm.isNetworkRoaming();

    String phoneInfo = "Phone Details: \n";
    phoneInfo += "\n IMEI Number: " + IMEINumber;
    phoneInfo += "\n SubscriberID: " + subscriberID;
    phoneInfo += "\n SIM Serial Number: " + SIMSerialNumber;
    phoneInfo += "\n Network Country ISO: " + networkCountryISO;
    phoneInfo += "\n SIMCountryISO: " + SIMCountryISO;
    phoneInfo += "\n SoftwreVersion: " + softwareVersion;
    phoneInfo += "\n VoiceMailNumber: " + voiceMailNumber;
    phoneInfo += "\n Phone Type: " + strPhoneType;
    phoneInfo += "\n Is Roaming? : " + isRoaming;

    textView.setText(phoneInfo);
}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lovepurohit.project15">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="adndroid.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <activity android:name=".SharedPreferences">

    </activity>

    <activity android:name=".InternalStorage">

    </activity>

    <activity android:name=".TelephonyManagerActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

Do I have to run it on the real device? I have added all the permission but it is not working in the emulator. And I'm using API 23 that is Marshmallow

Body:
You can do thing likethis in your onCreateMethod. I am doing it for WRITE_EXTERNAL_STORAGE you can do the same thing for READ_PHONE_STATE

if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                   if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                       //Show Information about why you need the permission
                       AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                       builder.setTitle("Need Storage Permission");
                       builder.setMessage("We needs storage permission to proceed");
                       builder.setPositiveButton("Allow", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                               ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
                           }
                       });
                       builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                           }
                       });
                       builder.show();
                   } else if (permissionStatus.getBoolean(Manifest.permission.WRITE_EXTERNAL_STORAGE,false)) {
                       //Previously Permission Request was cancelled with 'Dont Ask Again',
                       // Redirect to Settings after showing Information about why you need the permission
                       AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                       builder.setTitle("Storage Permission");
                       builder.setMessage("We need storage permission.");
                       builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                               sentToSettings = true;
                               Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                               Uri uri = Uri.fromParts("package", getPackageName(), null);
                               intent.setData(uri);
                               startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
                               Toast.makeText(getBaseContext(), "Go to Permissions to Grant Storage", Toast.LENGTH_LONG).show();
                           }
                       });
                       builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                           @Override
                           public void onClick(DialogInterface dialog, int which) {
                               dialog.cancel();
                           }
                       });
                       builder.show();
                   } else {
                       //just request the permission
                       ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
                   }

                   SharedPreferences.Editor editor = permissionStatus.edit();
                   editor.putBoolean(Manifest.permission.WRITE_EXTERNAL_STORAGE,true);
                   editor.commit();

               } else {
                   //You already have the permission, just go ahead.
                  textView = (TextView) findViewById(R.id.textView);

//Accessing the service for performing operation related to telephony
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

/**
 * Getting the phone Type
 * whether phone is cdma or gsm
 */
int type = tm.getPhoneType();

//Getting other details like IMEI number and device id and etc
String IMEINumber = tm.getDeviceId();

//getting subscriber ID
String subscriberID = tm.getDeviceId();

//Getting Sim serial number
String SIMSerialNumber = tm.getSimSerialNumber();

//Getting network details
String networkCountryISO = tm.getNetworkCountryIso();

//Getting sim country info
String SIMCountryISO = tm.getSimCountryIso();

//Getting the software on which app is running
String softwareVersion = tm.getDeviceSoftwareVersion();

//Getting the voice mail number on which app is running
String voiceMailNumber = tm.getVoiceMailNumber();

String strPhoneType = "";
switch (type) {
    case (TelephonyManager.PHONE_TYPE_CDMA):
        strPhoneType = "CDMA";
        break;

    case (TelephonyManager.PHONE_TYPE_GSM):
        strPhoneType = "GSM";
        break;

    case (TelephonyManager.PHONE_TYPE_NONE):
        strPhoneType = "NONE";
        break;

}

boolean isRoaming = tm.isNetworkRoaming();

 String phoneInfo = "Phone Details: \n";
    phoneInfo += "\n IMEI Number: " + IMEINumber;
    phoneInfo += "\n SubscriberID: " + subscriberID;
    phoneInfo += "\n SIM Serial Number: " + SIMSerialNumber;
    phoneInfo += "\n Network Country ISO: " + networkCountryISO;
    phoneInfo += "\n SIMCountryISO: " + SIMCountryISO;
    phoneInfo += "\n SoftwreVersion: " + softwareVersion;
    phoneInfo += "\n VoiceMailNumber: " + voiceMailNumber;
    phoneInfo += "\n Phone Type: " + strPhoneType;
    phoneInfo += "\n Is Roaming? : " + isRoaming;

    textView.setText(phoneInfo);
                   }

 @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode, resultCode, data);
       if (requestCode == REQUEST_PERMISSION_SETTING) {
           if (ActivityCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
              // Do the exact thing as in else condition above
           }
       }
   }

@Override
   public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
       super.onRequestPermissionsResult(requestCode, permissions, grantResults);
       if (requestCode == EXTERNAL_STORAGE_PERMISSION_CONSTANT) {
           if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
               // Do the exact thing as in else condition above
           } else {
               if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                   //Show Information about why you need the permission
                   AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                   builder.setTitle("Need Storage Permission");
                   builder.setMessage("This app needs storage permission");
                   builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialog, int which) {
                           dialog.cancel();

                           ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);

                       }
                   });
                   builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialog, int which) {
                           dialog.cancel();
                       }
                   });
                   builder.show();
               } else {
                   Toast.makeText(getBaseContext(),"Unable to get Permission",Toast.LENGTH_LONG).show();
               }
           }
       }
   }


问:
C# console application passing NameValueCollection from one class to another
I'm learning C# but I'm having trouble with passing the data NameValueCollection from one class to another in my console application, I'm experienced in using java  but from reading about passing by value and passing by reference has me stumped. My demo code below of the two classes is as follows, my helper class.

```<code>namespace ConsoleApplication3
{
    class Helper
    {
        public void Dostuff()
        {
            string name = "valves";
            int num = 5;
            NameValueCollection collection = new NameValueCollection();
            collection.Add("Sam", "Dot Net Perls");
            collection.Add("Bill", "Microsoft");

        }

        public NameValueCollection GetCollection()
        {
            NameValueCollection coll2 = Dostuff.Collection();
            return coll2;
        }
    }
}
</code>```

And here is my program class

```<code>namespace ConsoleApplication3
{
    class Program
    {
        public void Main(string[] args)
        {
            Helper h1 = new ConsoleApplication3.Helper();
            NameValueCollection newcollection = h1.GetCollection();
            RandomInbuiltMethod(newcollection);
        }

    }
}
</code>```

I'm not handling the passing of the NameValueCollection data properly and I don't want to make the helper methods static, Is there a way to do this, I'm sure I'm over creating the complexity and using to much resources for the Helper class, can anyone show me how to solve this.

答:
Probably you want to return the collection created in the DoStuff method of the Helper class

```<code>class Helper
{
    private NameValueCollection Dostuff()
    {
        string name = "valves";
        int num = 5;
        NameValueCollection collection = new NameValueCollection();
        collection.Add("Sam", "Dot Net Perls");
        collection.Add("Bill", "Microsoft");
        return collection;
    }

    public NameValueCollection GetCollection()
    {
        return Dostuff();
    }
}
</code>```

Now, your main method will retrieve the collection with the values added inside the DoStuff method

Body:
I'm learning C# but I'm having trouble with passing the data NameValueCollection from one class to another in my console application, I'm experienced in using java  but from reading about passing by value and passing by reference has me stumped. My demo code below of the two classes is as follows, my helper class.

namespace ConsoleApplication3
{
    class Helper
    {
        public void Dostuff()
        {
            string name = "valves";
            int num = 5;
            NameValueCollection collection = new NameValueCollection();
            collection.Add("Sam", "Dot Net Perls");
            collection.Add("Bill", "Microsoft");

        }

        public NameValueCollection GetCollection()
        {
            NameValueCollection coll2 = Dostuff.Collection();
            return coll2;
        }
    }
}

And here is my program class

namespace ConsoleApplication3
{
    class Program
    {
        public void Main(string[] args)
        {
            Helper h1 = new ConsoleApplication3.Helper();
            NameValueCollection newcollection = h1.GetCollection();
            RandomInbuiltMethod(newcollection);
        }

    }
}

I'm not handling the passing of the NameValueCollection data properly and I don't want to make the helper methods static, Is there a way to do this, I'm sure I'm over creating the complexity and using to much resources for the Helper class, can anyone show me how to solve this.

Body:
Probably you want to return the collection created in the DoStuff method of the Helper class

class Helper
{
    private NameValueCollection Dostuff()
    {
        string name = "valves";
        int num = 5;
        NameValueCollection collection = new NameValueCollection();
        collection.Add("Sam", "Dot Net Perls");
        collection.Add("Bill", "Microsoft");
        return collection;
    }

    public NameValueCollection GetCollection()
    {
        return Dostuff();
    }
}

Now, your main method will retrieve the collection with the values added inside the DoStuff method


答:
Make sure you are appending the query strings to your pagination links

Eg:

```<code>$users->appends(['search' => $searchTerm])->links()
</code>```

Edit:

Instead of :

```<code> {{ $usergroups->links() }}
</code>```

Append your query strings, like this :

```<code> {{ $usergroups->appends(['search' => request()->query('search')])->links() }}
</code>```

Title: Laravel 5.4 - Pagination method works wrong?

Body:
Make sure you are appending the query strings to your pagination links

Eg:

$users->appends(['search' => $searchTerm])->links()

Edit:

Instead of :

 {{ $usergroups->links() }}

Append your query strings, like this :

 {{ $usergroups->appends(['search' => request()->query('search')])->links() }}


问:
Is it possible to make a property of type class A, inside of class A?
So lets say that I have a class named A. Class A has several basic properties, however one of it's properties is supposed to be of type Class A. Here is an example of what I am talking about:

```<code>class A {
public:
    int a;
    bool b;
    A c;
};
</code>```

However, when I try to build this, I get the error "incomplete type is not allowed", which I am assuming has to do with the fact that property c does not have a definition for A yet, but even if I put:

```<code>class A;
</code>```

before I construct class A, however I still get the error "incomplete type is not allowed". If anyone knows how to create a property of type class A inside of class A, I would appreciate your help.
Thanks

Edit: I do not believe this post is a duplicate because I am trying to find out How you can create a property of type class A inside class A, instead of simply "why you can't create an instance of itself..."

答:
Yeah this is not possible, you have to declare it as a pointer like so:

```<code>class A {
public:
   int a;
   bool b;
   A* c;
};
</code>```

Then you can just allocate c on the heap.
The reason is that the compiler cannot know the size of A. Think like a compiler. Could you figure out the size of A? Well maybe 4 bytes for member a. Then maybe a byte for b. And for c, we have to look inside the class definition of A. Well the size of A is therefore 4 bytes for member...
You see where this is going to?

Body:
So lets say that I have a class named A. Class A has several basic properties, however one of it's properties is supposed to be of type Class A. Here is an example of what I am talking about:

class A {
public:
    int a;
    bool b;
    A c;
};

However, when I try to build this, I get the error "incomplete type is not allowed", which I am assuming has to do with the fact that property c does not have a definition for A yet, but even if I put:

class A;

before I construct class A, however I still get the error "incomplete type is not allowed". If anyone knows how to create a property of type class A inside of class A, I would appreciate your help.
Thanks

Edit: I do not believe this post is a duplicate because I am trying to find out How you can create a property of type class A inside class A, instead of simply "why you can't create an instance of itself..."

Body:
Yeah this is not possible, you have to declare it as a pointer like so:

class A {
public:
   int a;
   bool b;
   A* c;
};

Then you can just allocate c on the heap.
The reason is that the compiler cannot know the size of A. Think like a compiler. Could you figure out the size of A? Well maybe 4 bytes for member a. Then maybe a byte for b. And for c, we have to look inside the class definition of A. Well the size of A is therefore 4 bytes for member...
You see where this is going to?


问:
How to put some delay in calling an activity from another activity?
I have an application in which I'm receiving a sms containing his location.On receiving sms it calls another activity to start and passes that location to that activity to plot it on the map.Before calling the second activity it shows a toast like notification on the screen but somehoe due to calling second activity that toast doesn't come up.My question is how can we delay the calling of second activity from this activity ?</p>

答:
An example would be the following:</p>

```<code>Handler TimeDelay=new Handler();
                if(previous=="geofence"){

                    tts.speak(previous,TextToSpeech.QUEUE_ADD,null, null);
                    Runnable r = new Runnable() {
                        @Override
                        public void run() {
                            /*
                            Intent intent = new Intent(
                                    MyBroadcastMessageReceiver.class.getName());
                            intent.putExtra("some additional data", choice);
                            someActivity.sendBroadcast(intent);*/
                            tts.speak(previous,TextToSpeech.QUEUE_ADD,null, null);
                        }
                    };
                    TimeDelay.postDelayed(r, 150000);
</code>```

Body:
An example would be the following:

Handler TimeDelay=new Handler();
                if(previous=="geofence"){

                    tts.speak(previous,TextToSpeech.QUEUE_ADD,null, null);
                    Runnable r = new Runnable() {
                        @Override
                        public void run() {
                            /*
                            Intent intent = new Intent(
                                    MyBroadcastMessageReceiver.class.getName());
                            intent.putExtra("some additional data", choice);
                            someActivity.sendBroadcast(intent);*/
                            tts.speak(previous,TextToSpeech.QUEUE_ADD,null, null);
                        }
                    };
                    TimeDelay.postDelayed(r, 150000);


问:
Highlight first character of every line using css or JS
I have requirement to highlight first character in each and every line, as example image below, all the content is in single paragraph, based on resolution change also it should behave same,

I have tried with flex box, and first child using script also, I could not able to find solution

Any help will be appreciated.

答:
Try this:

p::first-letter {
  font-weight: bold;
  color: #8A2BE2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Hi there</p>
<p>Color first!</p></code>```

EDIT:
Ok, since you need this per each line in one paragrpah, you'll have to this with a script.

var allLines = document.querySelector("p").innerHTML.split("\n");
allLines = allLines.filter(function(x){return x !== ""}).map(function(x){
return "" + x.charAt(0) + "" + x.substr(1);
}).join("
");
document.querySelector("p").innerHTML = allLines;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>span {
  color: red;
}</code>```

TEXT
SOME MORE TEXT

```

Body:
Try this:

p::first-letter {
  font-weight: bold;
  color: #8A2BE2;
}

<p>Hi there</p>
<p>Color first!</p>

EDIT:
Ok, since you need this per each line in one paragrpah, you'll have to this with a script.

var allLines = document.querySelector("p").innerHTML.split("\n");
allLines = allLines.filter(function(x){return x !== ""}).map(function(x){
return "<span>" + x.charAt(0) + "</span>" + x.substr(1);
}).join("<br/>");
document.querySelector("p").innerHTML = allLines;

span {
  color: red;
}

<p>
TEXT
SOME MORE TEXT
</p>


问:
rails escape_javascript in .net
For rails developer please check my last paragraph.

Is there an equivalent of escape_javascript in rails for .net specifically .net mvc2?
I am going to return some JavaScript which needs to be escaped since I am getting the code from another view using RenderPartialViewToString http://craftycodeblog.com/2010/05/15/asp-net-mvc-render-partial-view-to-string/

You can see what escape_javascript does here Why escape_javascript before rendering a partial? if your not familiar with its functionality.

Rails developers:
It feels like this function should be easy to implement or port for rails so can someone explain what it does more than just escaping qoutes?

答: If you go here, and click on the show source link, you can see the source to the method.  It is just a Regex.Replace() call.</p>

ContentLicense: CC BY-SA 2.5

Title: rails escape_javascript in .net


问:
Is gRPC(HTTP/2) faster than REST with HTTP/2?
The goal is to introduce a transport and application layer protocol that is better in its latency and network throughput. Currently, the application uses REST with HTTP/1.1 and we experience a high latency. I need to resolve this latency problem and I am open to use either gRPC(HTTP/2) or REST/HTTP2.

HTTP/2:

Multiplexed

Single TCP Connection

Binary instead of textual

Header compression

Server Push

I am aware of all the above advantages. Question No. 1: If I use REST with HTTP/2, I am sure, I will get a significant performance improvement when compared to REST with HTTP/1.1, but how does this compare with gRPC(HTTP/2)?

I am also aware that gRPC uses proto buffer, which is the best binary serialization technique for transmission of structured data on the wire. Proto buffer also helps in developing an language agnostic approach. I agree with that and I can implement the same feature in REST using graphQL. But my concern is over serialization: Question No. 2: When HTTP/2 implements this binary feature, does using proto buffer give an added advantage on top of HTTP/2?

Question No. 3: In terms of streaming, bi-directional use-cases, how does gRPC(HTTP/2) compare with (REST and HTTP/2)?

There are so many blogs/videos out in the internet that compares gRPC(HTTP/2) with (REST and HTTP/1.1) like this. As stated earlier, I would like to know the differences, benefits on comparing GRPC(HTTP/2) and (REST with HTTP/2).

答:
I am not an expert on this by any means and I have no data to back any of this up.

The "binary feature" you're talking about is the binary representation of HTTP/2 frames. The content itself (a JSON payload) will still be UTF-8. You can compress that JSON and set Content-Encoding: gzip, just like HTTP/1.

But gRPC does gzip compression as well. So really, we're talking about the difference between gzip-compressed JSON vs gzip-compressed protobufs.

As you can imagine, compressed protobufs should beat compressed JSON in every way, or else protobufs have failed at their goal.

Besides the ubiquity of JSON vs protobufs, the only downside I can see to using protobufs is that you need the .proto to decode them, say in a tcpdump situation.


问:
Vanilla JS .style working but jQuery .css is not?
If i were to comment out the jquery .style and replace it with the currently commented line the code works fine. I do not understand the issue as they both accomplish the same thing. This might be a conceptual issue more than a coding one but I am not sure. Any help would be appreciated. </p>

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="css/index.css" type="text/css">
</head>
<body>

  <div id="header">

    <div id="navimg-holder">
        <img src="images/navimg.jpg" alt="">
    </div>

    <div id="navlist">

        <div class="navelm">
            <a href=""> <p> Home </p> </a>
        </div>
        <div class="navelm">
            <a href=""> <p> Contant </p> </a>
        </div>
        <div class="navelm">
            <a href=""> <p> Experience </p> </a>
        </div>
        <div class="navelm">
            <a href=""> <p> Interests </p> </a>
        </div>

    </div>

    <div id="logo-holder">

    </div>
    <div id="socialmedia-div">

        <div class="socialmedia-holder">
            <a href="https://facebook.com"> <img src="images/social1.jpg" alt="" > </a>
        </div>

        <div class="socialmedia-holder" id="second-socialmedia">
            <a href="https://twitter.com"> <img src="images/social2.jpg" alt="" id="twitter"> </a>
        </div>

        <div class="socialmedia-holder" id="third-socialmedia">
            <a href="https://www.instagram.com"> <img src="images/social3.jpg" alt="" id="insta"> </a>
        </div>

    </div>

  </div>

  <div id="content1">

  </div>

<script src="js/jquery-3.2.1.js"></script>
<script src="js/index.js"></script>
<script>document.write('<script src="http://' + (location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1"></' + 'script>')</script>
</body>
</html>

/*    * * * * * * * * * * * * * * CSS * * * * * * * *  * * *   */

 #navlist
{
    position: absolute;
    height: 200px;
    width: 200px;
    margin-top: 140px;
    z-index: 1;
}

.navelm
{
    position: relative;
    border:1px solid black;
    height: 20%;
    width: 100%;
    margin-top: 5%;
}

.navelm a
{
    text-decoration: none;
}

.navelm p
{
    color:white;
    text-align: center;
    font-family: Palatino;
}

/*  * * * * * * * * * * *  JAVASCRIPT * * * * * * */

$("#navimg-holder img").click(showMenu);

function showMenu()
{
    $('.navelm').each(function()
        {
            this.css("background-color","white");
           /* this.style.backgroundColor = "white";  */
        });

}
</code>```

答:
this is a JavaScript DOM object. this has no method .css to it. You need to wrap it in your jQuery object.

```<code>$(this).css("background-color","white");
</code>```

For that to work.

Body:
If i were to comment out the jquery .style and replace it with the currently commented line the code works fine. I do not understand the issue as they both accomplish the same thing. This might be a conceptual issue more than a coding one but I am not sure. Any help would be appreciated.

<!DOCTYPE html>

    <title></title>
    <link rel="stylesheet" href="css/index.css" type="text/css">

 Home

 Contant

 Experience

 Interests

/*    * * * * * * * * * * * * * * CSS * * * * * * * *  * * *   */

 #navlist
{
    position: absolute;
    height: 200px;
    width: 200px;
    margin-top: 140px;
    z-index: 1;
}

.navelm
{
    position: relative;
    border:1px solid black;
    height: 20%;
    width: 100%;
    margin-top: 5%;
}

.navelm a
{
    text-decoration: none;
}

.navelm p
{
    color:white;
    text-align: center;
    font-family: Palatino;
}

/*  * * * * * * * * * * *  JAVASCRIPT * * * * * * */

$("#navimg-holder img").click(showMenu);

function showMenu()
{
    $('.navelm').each(function()
        {
            this.css("background-color","white");
           /* this.style.backgroundColor = "white";  */
        });

}

Body:
this is a JavaScript DOM object. this has no method .css to it. You need to wrap it in your jQuery object.

$(this).css("background-color","white");

For that to work.


问:
Remove a specific string only if it's in the very end of a code
I'm parsing a html file to extract part of its text to create an epub. The problem is that in the text extracted sometimes the last paragraph is an empty one that I would like to remove. So... how can I remove this blank paragraph (and any additional blank spaces after that) with the condition that there's no additional text later on in any other line of code?

For example:

```<code><p> </p>
<p>“Lorem ipsum dolor sit amet, consectetur adipiscing elit.”</p>
<p>Sed ut perspiciatis unde omnis iste natus error...</p>
<p> </p>
<p>“Lorem ipsum dolor sit amet.”</p>
<p>Omnis iste natus error sit voluptatem.</p>
<p> </p>
</code>```

So, what can I do to remove only this last instance of

 (and any additional blank spaces/newlines after that) from the code above?

I have tried using this negative lookahead

\s*?(?!
) on perl-regex to exclude later paragraphs from the search, but it still finds the previous instances of

 and I only need to remove this paragraph when it's the last one in the file.

Thank you in advance!

EDIT-1:

To be clear, I want this:

```<code><p> </p>
<p>“Lorem ipsum dolor sit amet, consectetur adipiscing elit.”</p>
<p>Sed ut perspiciatis unde omnis iste natus error...</p>
<p> </p>
<p>“Lorem ipsum dolor sit amet.”</p>
<p>Omnis iste natus error sit voluptatem.</p>
<p> </p>
</code>```

to become this:

```<code><p> </p>
<p>“Lorem ipsum dolor sit amet, consectetur adipiscing elit.”</p>
<p>Sed ut perspiciatis unde omnis iste natus error...</p>
<p> </p>
<p>“Lorem ipsum dolor sit amet.”</p>
<p>Omnis iste natus error sit voluptatem.</p>
</code>```

i.e. I want to remove the

 only in the last line (where there's no other text after it), so I want to know which perl-regex search I should use to find only this particular instance of this string so I can replace it with nothing and with that remove it from the code.

EDIT-2.:

Based on a suggestion by ikegami, I used \s*(?>

\s*)(?!
)\s* as the search string to find only the last blank paragraph (

)of the html code to be removed. What really made the difference in his answer seems to have been the use of an atomic grouping (?>...). Without it, I was picking other instances of the same string from other lines of the code that I didn't want. Not sure why (really not an expert on regex), but that's what I got from my tests.

I'm just using some basic find/replace operations of perl-regex in an ebook editor to clean the code, so I'm not sure about how it will behave under other circumstances. Anyway, I appreciate the other attempts of helping me, some of which were even too technical for me to grasp and I hope this answer will help someone in the future with a similar problem. Thank you again!

答:
Short answer: use the $ anchor.

Long answer:

```<code>#!/usr/bin/env perl

use strict;
use warnings;

my $fn = $ARGV[0] or die 'filename required!';

# Not certain what encoding your file is in
open (my $fh, '< :encoding(UTF-8)', $fn)
    or die "could not open file '$fn': $!";

# slurp entire file
my $content = do{ local $/; <$fh>; };
close $fh;

# If it ends with the blank paragraph followed by newline/tab/space,
# overwrite the file
if ( $content =~ s /<p> <\/p>[\n\s\t\r]*$// ){
    open (my $fh, '> :encoding(UTF-8)', $fn)
        or die "could not open file '$fn' to write: $!";
    print $fh $content;
    close $fh;
}
</code>```

Body:
I'm parsing a html file to extract part of its text to create an epub. The problem is that in the text extracted sometimes the last paragraph is an empty one that I would like to remove. So... how can I remove this blank paragraph (and any additional blank spaces after that) with the condition that there's no additional text later on in any other line of code?

For example:

“Lorem ipsum dolor sit amet, consectetur adipiscing elit.”

Sed ut perspiciatis unde omnis iste natus error...

“Lorem ipsum dolor sit amet.”

Omnis iste natus error sit voluptatem.

So, what can I do to remove only this last instance of

 (and any additional blank spaces/newlines after that) from the code above?

I have tried using this negative lookahead

\s*?(?!
) on perl-regex to exclude later paragraphs from the search, but it still finds the previous instances of

 and I only need to remove this paragraph when it's the last one in the file.

Thank you in advance!

EDIT-1:

To be clear, I want this:

“Lorem ipsum dolor sit amet, consectetur adipiscing elit.”

Sed ut perspiciatis unde omnis iste natus error...

“Lorem ipsum dolor sit amet.”

Omnis iste natus error sit voluptatem.

to become this:

“Lorem ipsum dolor sit amet, consectetur adipiscing elit.”

Sed ut perspiciatis unde omnis iste natus error...

“Lorem ipsum dolor sit amet.”

Omnis iste natus error sit voluptatem.

i.e. I want to remove the

 only in the last line (where there's no other text after it), so I want to know which perl-regex search I should use to find only this particular instance of this string so I can replace it with nothing and with that remove it from the code.

EDIT-2.:

Based on a suggestion by ikegami, I used \s*(?>

\s*)(?!
)\s* as the search string to find only the last blank paragraph (

)of the html code to be removed. What really made the difference in his answer seems to have been the use of an atomic grouping (?>...). Without it, I was picking other instances of the same string from other lines of the code that I didn't want. Not sure why (really not an expert on regex), but that's what I got from my tests.

I'm just using some basic find/replace operations of perl-regex in an ebook editor to clean the code, so I'm not sure about how it will behave under other circumstances. Anyway, I appreciate the other attempts of helping me, some of which were even too technical for me to grasp and I hope this answer will help someone in the future with a similar problem. Thank you again!

Body:
Short answer: use the $ anchor.

Long answer:

#!/usr/bin/env perl

use strict;
use warnings;

my $fn = $ARGV[0] or die 'filename required!';

# Not certain what encoding your file is in
open (my $fh, '< :encoding(UTF-8)', $fn)
    or die "could not open file '$fn': $!";

# slurp entire file
my $content = do{ local $/; <$fh>; };
close $fh;

# If it ends with the blank paragraph followed by newline/tab/space,
# overwrite the file
if ( $content =~ s /<p>&nbsp;<\/p>[\n\s\t\r]*$// ){
    open (my $fh, '> :encoding(UTF-8)', $fn)
        or die "could not open file '$fn' to write: $!";
    print $fh $content;
    close $fh;
}


问:
DocuSign SDK Assembly Dependency Versions
I am integrating the DocuSign SDK into my application (from the github page here: https://github.com/docusign/docusign-csharp-client) and can see it has two dependencies:
- Netwtonsoft.JSON
- RestSharp

However, it seems the included dependency assemblies are not the same versions that were used to create the DocuSign SDK assembly.
The included NewtonSoft.JSON assembly is v8, but the SDK uses v7.
The included RestSharp assembly is 105.2.3, but the SDK uses v105.1.0.0

Is it possible to get an updated SDK with the correct dependencies?

答:
Dependencies For the DocuSign Nuget package 2.1.4

Newtonsoft.Json (>= 8.0.3)

RestSharpSigned (>= 105.2.2)

Source code is also referring to the same versions. See here


问:
Octet-stream data URI ignoring  'download' attribute
I have a download button on my page that looks like this:

```<code><a download="test.jpg" href="data:application/octet-stream;base64,/9j/4AAQSkZ...">Download</a>
</code>```

The href attribute is populated by JavaScript, and on my test server it functions exactly as I'd expect it to: it prompts a 'Save As' dialogue box with the filename "test.jpg".

However, when I use the exact same code on a different, live server, the filename is dropped.

In Chrome it saves as 'download', without a file extension

In Firefox it saves as a seemingly random string, again without a file extension

Any ideas what could be causing this difference in behaviour across the two servers?

答: This is a security measure applies when saving off-site downloads. since the prototcols don't match (data vs http), it's considered a different site, and a default names gets applies. Use URL.createObjectURL instead of base64 to feed the download's href. you can get a dataURL to Blob routine in my downlod.js library, then feed the Blob to createObjectURL().</p>

Title: Octet-stream data URI ignoring <a> 'download' attribute

Body:
I have a download button on my page that looks like this:

Download

The href attribute is populated by JavaScript, and on my test server it functions exactly as I'd expect it to: it prompts a 'Save As' dialogue box with the filename "test.jpg".

However, when I use the exact same code on a different, live server, the filename is dropped.

In Chrome it saves as 'download', without a file extension

In Firefox it saves as a seemingly random string, again without a file extension

Any ideas what could be causing this difference in behaviour across the two servers?


问:
Wordpress sub-menu Jquery does not work
I'm building my website based on Wordpress and have added a mobile menu. Now I'm hanging on the problem the submenu does not collapse when I click on the menu item.

The regular name of the submenu in Wordpress is .sub-menu, when there are more sub-menu's the menu collapse when I click on the menu item which has the submenu but all the sub-menu's collapse while I only want the one which is clicked to be collapsed.

Read about the (this) function but can't get it to work.

Any suggestions of what I'm doing wrong?

My default code which makes every submenu visible when click on menu item:

```<code>(function($){
jQuery(document).ready(function() {
    jQuery('#mobilenav .menu-item-has-children').click(function(){
         jQuery('#mobilenav .sub-menu').toggleClass('openup1');
    });
});

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

The code I have made but which is not working:

```<code>(function($){
jQuery(document).ready(function() {

    jQuery('#mobilenav .menu-item-has-children').click(function(){
            jQuery(this).closest('#mobilenav .sub-menu').toggleClass('openup1');
        });

});

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

Title: Wordpress sub-menu Jquery does not work

Body:
I'm building my website based on Wordpress and have added a mobile menu. Now I'm hanging on the problem the submenu does not collapse when I click on the menu item.

The regular name of the submenu in Wordpress is .sub-menu, when there are more sub-menu's the menu collapse when I click on the menu item which has the submenu but all the sub-menu's collapse while I only want the one which is clicked to be collapsed.

Read about the (this) function but can't get it to work.

Any suggestions of what I'm doing wrong?

My default code which makes every submenu visible when click on menu item:

(function($){
jQuery(document).ready(function() {
    jQuery('#mobilenav .menu-item-has-children').click(function(){
         jQuery('#mobilenav .sub-menu').toggleClass('openup1');
    });
});

})(jQuery);

The code I have made but which is not working:

(function($){
jQuery(document).ready(function() {

    jQuery('#mobilenav .menu-item-has-children').click(function(){
            jQuery(this).closest('#mobilenav .sub-menu').toggleClass('openup1');
        });

});

})(jQuery);

Body: jQuery(this).children('.sub-menu').first().toggleClass('openup1');


问:
Get cookie by name
I have a getter to get the value from a cookie.

Now I have 2 cookies by the name shares= and by the name obligations= .

I want to make this getter only to get the values from the obligations cookie.

How do I do this? So the for splits the data into separate values and puts it in an array.

```<code> function getCookie1() {
    // What do I have to add here to look only in the "obligations=" cookie?
    // Because now it searches all the cookies.

    var elements = document.cookie.split('=');
    var obligations= elements[1].split('%');
    for (var i = 0; i < obligations.length - 1; i++) {
        var tmp = obligations[i].split('$');
        addProduct1(tmp[0], tmp[1], tmp[2], tmp[3]);
    }
 }
</code>```

答:
Simple function for Get cookie with cookie name:</p>

```<code>function getCookie(cn) {
    var name = cn+"=";
    var allCookie = decodeURIComponent(document.cookie).split(';');
    var cval = [];
    for(var i=0; i < allCookie.length; i++) {
        if (allCookie[i].trim().indexOf(name) == 0) {
            cval = allCookie[i].trim().split("=");
        }
    }
    return (cval.length > 0) ? cval[1] : "";
}
</code>```

Title: Get cookie by name

Body:
I have a getter to get the value from a cookie.

Now I have 2 cookies by the name shares= and by the name obligations= .

I want to make this getter only to get the values from the obligations cookie.

How do I do this? So the for splits the data into separate values and puts it in an array.

 function getCookie1() {
    // What do I have to add here to look only in the "obligations=" cookie?
    // Because now it searches all the cookies.

    var elements = document.cookie.split('=');
    var obligations= elements[1].split('%');
    for (var i = 0; i < obligations.length - 1; i++) {
        var tmp = obligations[i].split('$');
        addProduct1(tmp[0], tmp[1], tmp[2], tmp[3]);
    }
 }

Body:
Simple function for Get cookie with cookie name:

function getCookie(cn) {
    var name = cn+"=";
    var allCookie = decodeURIComponent(document.cookie).split(';');
    var cval = [];
    for(var i=0; i < allCookie.length; i++) {
        if (allCookie[i].trim().indexOf(name) == 0) {
            cval = allCookie[i].trim().split("=");
        }
    }
    return (cval.length > 0) ? cval[1] : "";
}


问:
Laravel follower/following relationships
I am trying to make a simple follower/following system in laravel, nothing special, just click a button to follow or unfollow, and display the followers or the people following you.

My trouble is I can't figure out how to make the relationships between the models.

These are the migrations:

-User migration:

```<code>Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('email');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('password');
        $table->string('gender');
        $table->date('dob');
        $table->rememberToken();
    });
</code>```

-Followers migration:

```<code>Schema::create('followers', function (Blueprint $table) {

        $table->increments('id');
        $table->integer('follower_id')->unsigned();
        $table->integer('following_id')->unsigned();
        $table->timestamps();
    });
}
</code>```

And here are the models:

-User model:

```<code>   class User extends Model implements Authenticatable
{
    use \Illuminate\Auth\Authenticatable;
    public function posts()
    {
        return $this->hasMany('App\Post');
    }

    public function followers()
    {
        return $this->hasMany('App\Followers');
    }

}
</code>```

-And the followers model is basically empty, this is where I got stuck

I tried something like this:

```<code>class Followers extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}
</code>```

but it didn't work.

Also, I'd like to ask if you could tell me how to write the "follow" and "display followers/following" functions. I've read every tutorial I could find but to no use. I can't seem to understand.

答:
You need to realize that the "follower" is also a App\User. So you only need one model App\User with these two methods:

```<code>// users that are followed by this user
public function following() {
    return $this->belongsToMany(User::class, 'followers', 'follower_id', 'following_id');
}

// users that follow this user
public function followers() {
    return $this->belongsToMany(User::class, 'followers', 'following_id', 'follower_id');
}
</code>```

User $a wants to follow user $b:

```<code>$a->following()->attach($b);
</code>```

User $a wants to stop following user $b:

```<code>$a->following()->detach($b);
</code>```

Get all followers of user $a:

```<code>$a_followers = $a->followers()->get();
</code>```

Body:
I am trying to make a simple follower/following system in laravel, nothing special, just click a button to follow or unfollow, and display the followers or the people following you.

My trouble is I can't figure out how to make the relationships between the models.

These are the migrations:

-User migration:

Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('email');
        $table->string('first_name');
        $table->string('last_name');
        $table->string('password');
        $table->string('gender');
        $table->date('dob');
        $table->rememberToken();
    });

-Followers migration:

Schema::create('followers', function (Blueprint $table) {

        $table->increments('id');
        $table->integer('follower_id')->unsigned();
        $table->integer('following_id')->unsigned();
        $table->timestamps();
    });
}

And here are the models:

-User model:

   class User extends Model implements Authenticatable
{
    use \Illuminate\Auth\Authenticatable;
    public function posts()
    {
        return $this->hasMany('App\Post');
    }

    public function followers()
    {
        return $this->hasMany('App\Followers');
    }

}

-And the followers model is basically empty, this is where I got stuck

I tried something like this:

class Followers extends Model
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

but it didn't work.

Also, I'd like to ask if you could tell me how to write the "follow" and "display followers/following" functions. I've read every tutorial I could find but to no use. I can't seem to understand.

Body:
You need to realize that the "follower" is also a App\User. So you only need one model App\User with these two methods:

// users that are followed by this user
public function following() {
    return $this->belongsToMany(User::class, 'followers', 'follower_id', 'following_id');
}

// users that follow this user
public function followers() {
    return $this->belongsToMany(User::class, 'followers', 'following_id', 'follower_id');
}

User $a wants to follow user $b:

$a->following()->attach($b);

User $a wants to stop following user $b:

$a->following()->detach($b);

Get all followers of user $a:

$a_followers = $a->followers()->get();


问:
Use match from file in string
I have a list of user ids in a file and I'm trying to generate some sql from the file.

```<code>cat users.json | awk '/UID/{print "INSERT IGNORE INTO potential_problem_users VALUES ("$2");" }'
</code>```

But it's not doing what I expected it to do:

```<code>);SERT IGNORE INTO potential_problem_users VALUES ("1"
);SERT IGNORE INTO potential_problem_users VALUES ("2"
</code>```

The query I am trying for is:

```<code>INSERT IGNORE INTO potential_problem_users VALUES ([userID]);
</code>```

example json if it helps:

```<code>{
  "results": [
    {
      "UID": "abc"
    },
    {
      "UID": "124"
    }
  ],
  "objectsCount": 5,
  "totalCount": 10966,
  "statusCode": 200,
  "errorCode": 0,
  "statusReason": "OK"
}
</code>```

Am I using the right tool? If I am, what am I doing wrong?

答:
users.json contains carriage returns (aka \rs aka control-Ms), run dos2unix or similar on it first then re-run your awk script (or run any other script) on it and then let us know if you still have a problem.

Almost every time you find characters you expect to see at the end of a line showing up at the start instead the problem is control-Ms.

Title: Use match from file in string

Body:
I have a list of user ids in a file and I'm trying to generate some sql from the file.

cat users.json | awk '/UID/{print "INSERT IGNORE INTO potential_problem_users VALUES ("$2");" }'

But it's not doing what I expected it to do:

);SERT IGNORE INTO potential_problem_users VALUES ("1"
);SERT IGNORE INTO potential_problem_users VALUES ("2"

The query I am trying for is:

INSERT IGNORE INTO potential_problem_users VALUES ([userID]);

example json if it helps:

{
  "results": [
    {
      "UID": "abc"
    },
    {
      "UID": "124"
    }
  ],
  "objectsCount": 5,
  "totalCount": 10966,
  "statusCode": 200,
  "errorCode": 0,
  "statusReason": "OK"
}

Am I using the right tool? If I am, what am I doing wrong?


问:
Django Testing - loading data into the database before loading the apps
I'm currently writting some tests for a Django app (+ REST framework), and having some issues loading the test data into the database.

Let me explain with some (very simplified) code :

I have a django view which is something like :

view.py

```<code>from myapp.models import Item
from myapp.utils import MyClass

# need to initialize with the set of items
item_set = {item.name for item in Item.objects.all()}
my_class_object = MyClass(item_set)

class MyView(APIView):
    def post(selfself, request):
        result = my_class_object.process(request.data)
        return Response(result)
</code>```

So basically I need to initialize a class with some data from the database, and I then use this class in my view to process the data received by the endpoint.

Now the test :

my_test.py

```<code>from rest_framework.test import APILiveServerTestCase
from myapp.models import Item

class MyTest(APILiveServerTestCase):

    def setUp(self):
        self.URL = '/some_url_linking_to_myview/'

        # load some data
        Item.objects.create(name="first item")
        Item.objects.create(name="second item")

    def test_myview_return_correct_result(self):
        post_data = {"foo"}
        response = self.client.post(self.URL,
                                    data=post_data,
                                    format='json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data, {"my_expected_result"})
</code>```

When running the test, what currently happens is that view.py is loaded before the setUp() method get excecuted, so when I instantiate the class with these two lines :

```<code>item_set = {item.name for item in Item.objects.all()}
my_class_object = MyClass(item_set)
</code>```

the database is still empty.

I'm wondering if there is a way to either get the data into the database before view.py get executed, or maybe somehow force reloading the app after setUp(), or instantiate my class somewhere else so it gets called after loading the data ?

thanks !

答:
I think you are looking for setUpTestData().

Here is roughly how I set this up if I am going to use a significant amount of data:

tests.py

```<code>from django.test import TestCase
from .tests.test_data import base_data

class MyClassTest(TestCase):

    @classmethod
    def setUpTestData(cls):
        base_data.base_data(cls)
</code>```

base_data.py

```<code>from .models import MyClass

def base_data(cls):
    cls.MyClass1 = MyClass.objects.create(
       name="first_name"
    )
    cls.MyClass2 = MyClass.objects.create(
       name="second_name"
    )
</code>```

Of course, you can do everything directly in the setUpTestData() function, if you would rather have your test data sitting up top.

Body:
I'm currently writting some tests for a Django app (+ REST framework), and having some issues loading the test data into the database.

Let me explain with some (very simplified) code :

I have a django view which is something like :

view.py

from myapp.models import Item
from myapp.utils import MyClass

# need to initialize with the set of items
item_set = {item.name for item in Item.objects.all()}
my_class_object = MyClass(item_set)

class MyView(APIView):
    def post(selfself, request):
        result = my_class_object.process(request.data)
        return Response(result)

So basically I need to initialize a class with some data from the database, and I then use this class in my view to process the data received by the endpoint.

Now the test :

my_test.py

from rest_framework.test import APILiveServerTestCase
from myapp.models import Item

class MyTest(APILiveServerTestCase):

    def setUp(self):
        self.URL = '/some_url_linking_to_myview/'

        # load some data
        Item.objects.create(name="first item")
        Item.objects.create(name="second item")

    def test_myview_return_correct_result(self):
        post_data = {"foo"}
        response = self.client.post(self.URL,
                                    data=post_data,
                                    format='json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data, {"my_expected_result"})

When running the test, what currently happens is that view.py is loaded before the setUp() method get excecuted, so when I instantiate the class with these two lines :

item_set = {item.name for item in Item.objects.all()}
my_class_object = MyClass(item_set)

the database is still empty.

I'm wondering if there is a way to either get the data into the database before view.py get executed, or maybe somehow force reloading the app after setUp(), or instantiate my class somewhere else so it gets called after loading the data ?

thanks !

Body:
I think you are looking for setUpTestData().

Here is roughly how I set this up if I am going to use a significant amount of data:

tests.py

from django.test import TestCase
from .tests.test_data import base_data

class MyClassTest(TestCase):

    @classmethod
    def setUpTestData(cls):
        base_data.base_data(cls)

base_data.py

from .models import MyClass

def base_data(cls):
    cls.MyClass1 = MyClass.objects.create(
       name="first_name"
    )
    cls.MyClass2 = MyClass.objects.create(
       name="second_name"
    )

Of course, you can do everything directly in the setUpTestData() function, if you would rather have your test data sitting up top.


问:
javascript : how can i get array in different ways?
hi i have a little problem with my javascript
can i make the simple way to execute content of array with different character of word?
for example :

```<code>var word = new Array();
word [0] = "is";
word [1] = "am";
.
.
.
.
word [100] = "when";
</code>```

var word should be access with 3 ways,in order to reduce process to execute arrays..

```<code>first : " "+ word +" ";
second : " "+ word;
third : word +" ";
</code>```

-thank you for helping-

答:
I'm not exactly sure what you are chasing (fill me in and I'll update), but I'd like to point out a far better way of filling in that array literal...

```<code>var word = [
   'is',
   'am'
];
</code>```

You can see the index is calculated automatically, and you are not required to repeat the var name for each member definition.

Update

Maybe you want something you can call and get the next array member each time. This should do it...

```<code>function getNextMember(array, startIndex) {
   startIndex = startIndex || 0;

   return function() {
      startIndex++;
      return array[startIndex];
   };

};

var getNextWord = getNextMember(word);

alert(getNextWord() + ' ' + getNextWord());
</code>```

See it on jsFiddle.

And of course, if you are feeling naughty, you could add that function to Array's prototype.

Body:
hi i have a little problem with my javascript
can i make the simple way to execute content of array with different character of word?
for example :

var word = new Array();
word [0] = "is";
word [1] = "am";
.
.
.
.
word [100] = "when";

var word should be access with 3 ways,in order to reduce process to execute arrays..

first : " "+ word +" ";
second : " "+ word;
third : word +" ";

-thank you for helping-

Body:
I'm not exactly sure what you are chasing (fill me in and I'll update), but I'd like to point out a far better way of filling in that array literal...

var word = [
   'is',
   'am'
];

You can see the index is calculated automatically, and you are not required to repeat the var name for each member definition.

Update

Maybe you want something you can call and get the next array member each time. This should do it...

function getNextMember(array, startIndex) {
   startIndex = startIndex || 0;

   return function() {
      startIndex++;
      return array[startIndex];
   };

};

var getNextWord = getNextMember(word);

alert(getNextWord() + ' ' + getNextWord());

See it on jsFiddle.

And of course, if you are feeling naughty, you could add that function to Array's prototype.