问:
Is there more efficient way to check the number of cases in every brach in variable?
For 100 000 000 rows it costs 5 sec. It is too much. Do ya know how to improve this code to get the checking faster?</p>

```<code> #a variable to check
xVar <- as.factor(sample(x=c("transp","bud","wolny","pref",
                                      "inny"), size=100000000, replace=T))

#a trigger, if a variable has less then 1000 number of cases in any branch then the variable warn will fill with a comunicat
sen <- 10000

#function to improve
check <- function(xVar, sen){
  if (min(table(xVar)) < sen){
    warn <- "Variable has very low number in some branches - IV can be spoiled"
  }else{
    warn <- ""
  }
}

#go
start <- Sys.time()
check(xVar, sen)
stop <- Sys.time()
stop - start
</code>```

答:
We can use tabulate to improve the speed

```<code>check <- function(xVar, sen){
  if (min(tabulate(xVar)) < sen){
   warn <- "Variable has very low number in some branches - IV can be spoiled"
  }else{
    warn <- ""
  }
}

start <- Sys.time()
check(xVar, sen)
stop <- Sys.time()
stop - start
#Time difference of 0.272254 secs
</code>```

With OP's function, the difference of stop and start is

```<code>stop - start
#Time difference of 5.077512 secs
</code>```

data

```<code>set.seed(24)
xVar <- as.factor(sample(x=c("transp","bud","wolny","pref",
                                  "inny"), size=100000000, replace=T))
sen <- 10000
</code>```

Body:
For 100 000 000 rows it costs 5 sec. It is too much. Do ya know how to improve this code to get the checking faster?

 #a variable to check
xVar <- as.factor(sample(x=c("transp","bud","wolny","pref",
                                      "inny"), size=100000000, replace=T))

#a trigger, if a variable has less then 1000 number of cases in any branch then the variable warn will fill with a comunicat
sen <- 10000

#function to improve
check <- function(xVar, sen){
  if (min(table(xVar)) < sen){
    warn <- "Variable has very low number in some branches - IV can be spoiled"
  }else{
    warn <- ""
  }
}

#go
start <- Sys.time()
check(xVar, sen)
stop <- Sys.time()
stop - start

Body:
We can use tabulate to improve the speed

check <- function(xVar, sen){
  if (min(tabulate(xVar)) < sen){
   warn <- "Variable has very low number in some branches - IV can be spoiled"
  }else{
    warn <- ""
  }
}

start <- Sys.time()
check(xVar, sen)
stop <- Sys.time()
stop - start
#Time difference of 0.272254 secs

With OP's function, the difference of stop and start is

stop - start
#Time difference of 5.077512 secs

data

set.seed(24)
xVar <- as.factor(sample(x=c("transp","bud","wolny","pref",
                                  "inny"), size=100000000, replace=T))
sen <- 10000


来源: stackexchange

问:
how to disable voice input key in android keypad
i need a code to disable/hide the voice input key in android keyboard.
thanks</p>

答: @tim You can add android:inputType="text|textVisiblePassword|textMultiLine" to EditText in your xml. This piece of code hides the voice input but auto-suggestion will be closed at the same time.

ContentLicense: CC BY-SA 3.0


问:
Codeigniter file upload displaying error
Controller code

```<code>        $config['upload_path']          = './uploads/'.$random;
        $config['allowed_types']        = 'gif|jpg|png';
        $config['max_size']             = 100;
        $config['max_width']            = 1024;
        $config['max_height']           = 768;

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload('imageupload'))
        {
            $error = array('error' => $this->upload->display_errors());
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());
        }
        print_r($data);
</code>```

HTML code:

```<code><form role="form" enctype="multipart/form-data" accept-charset="utf-8" name="formname" id="formname"  method="post" action="http://www.example.com/Property/post">
    <input type="file" class="default" id="imageupload1" name="imageupload[]">
</form>
</code>```

Whenever I am uploading file it displaying warning is_uploaded_file() expects parameter 1 to be string, array given. How can I resolve it?

答:
Probably your input name should be without brackets:</p>

```<code><input type="file" class="default" id="imageupload1" name="imageupload">
</code>```

Body:
Controller code

        $config['upload_path']          = './uploads/'.$random;
        $config['allowed_types']        = 'gif|jpg|png';
        $config['max_size']             = 100;
        $config['max_width']            = 1024;
        $config['max_height']           = 768;

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload('imageupload'))
        {
            $error = array('error' => $this->upload->display_errors());
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());
        }
        print_r($data);

HTML code:

<form role="form" enctype="multipart/form-data" accept-charset="utf-8" name="formname" id="formname"  method="post" action="http://www.example.com/Property/post">
    <input type="file" class="default" id="imageupload1" name="imageupload[]">
</form>

Whenever I am uploading file it displaying warning is_uploaded_file() expects parameter 1 to be string, array given. How can I resolve it?

Body:
Probably your input name should be without brackets:

<input type="file" class="default" id="imageupload1" name="imageupload">


问:
Array Size Not Defined? C++
Dumb question. but can you do this.
(these are global variables by the way)

```<code>int size;
double Values[size];
</code>```

If Im getting the SIZE from a file?

I know you probably can't, but maybe theirs some way to readjust the size based on the number I read in from the file (like say I read in 7, I know Values will have to be of Size 7).

The compiler complains, but Im wondering if their is some workaround. (these have to stay as global variables btw.

答:
No, you can only specify array sizes like this using constant integral expressions.  Meaning known at compile-time.

You probably shouldn't be doing this, anyway.  Instead, you should be using a vector.

If for whatever reason you can't use a vector (which I would seriously doubt), then your next option would be to use dynamically-allocated arrays.  But please, for the love of all that is good int he world, use a smart pointer if you do this.

ContentLicense: CC BY-SA 2.5

Title: Array Size Not Defined? C++

Body:
Dumb question. but can you do this.
(these are global variables by the way)

int size;
double Values[size];

If Im getting the SIZE from a file?

I know you probably can't, but maybe theirs some way to readjust the size based on the number I read in from the file (like say I read in 7, I know Values will have to be of Size 7).

The compiler complains, but Im wondering if their is some workaround. (these have to stay as global variables btw.


问:
Get featured image with custom size outside wordpress
I have WordPress blog which is hosted as a sub directory of a web application. The WordPress installation is untouched and modifications are done in the theme level. The web application home page needs to display the recent blog posts. So I have the following code for displaying the recent posts:

```<code>    $array = array();

    $query = "SELECT * FROM wp_posts WHERE post_status=:publish AND post_type=:post_type";
    $stmt = $this->dbj->prepare($query);
    $stmt->execute(array(
        ':publish' => 'publish',
        ':post_type' => 'post'
    ));

    if ($stmt->rowCount() > 0) {
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $id = $row["ID"];
            if ($row["post_name"] == '') {
                $slug = $row["ID"];
            } else {
                $slug = $row["post_name"];
            }
            $content1 = strip_tags($row["post_content"]);

            $image_prepare = $this->dbj->prepare('SELECT
    wp_postmeta.meta_id,
    wp_postmeta.post_id,
    wp_postmeta.meta_key,
    wp_postmeta.meta_value
FROM
    wp_postmeta
INNER JOIN wp_posts ON wp_posts.ID = wp_postmeta.post_id
WHERE
    wp_postmeta.meta_key = :meta_key
AND wp_posts.post_parent = :pid');

            $image_prepare->execute(
                array(
                    ':pid' => $id,
                    ':meta_key' => '_wp_attached_file'
                )
            );

            $image_fetch = $image_prepare->fetchAll();

            foreach ($image_fetch as $image_row) {
                $image_name = $row['post_title'];
                $image_path = $image_row['meta_value'];
            }

            if (strlen($content1) > 200) {
                $content = substr($content1, 0, 200) . '...';
            } else {
                $content = nl2br($content1);
            }

            $array[] = array(
                'image_path' => $image_path,
                'image_name' => $image_name,
                'slug' => $row["post_name"],
                'content' => $content,
                'title' => $row['post_title']
            );
        }
    return $array;
    }
</code>```

I am getting the full size image url. I have done resizing in my functions.php file in theme:

```<code>add_theme_support('post-thumbnails');

add_image_size('home-size', 214, 300);
add_image_size('home-featured', 300, 300);
add_image_size('jobs-thumb', 50, 75);
</code>```

The problem is that resized images in uploads directory does not always have image-name-300x300.jpg for home-featured. Instead it have random value for height depending on the image's ratio in file name(Ex: image-name-300x220.jpg). And I have regenerated the thumbnails again but still same file name. How do I get 'home-featured' for above solution?

答:
Wordpress keeps serialized data of generated images in postmeta table with _wp_attachment_metadata as a meta_key.

In your case, if you don't need full size images for your code, change _wp_attached_file to _wp_attachment_metadata.

```<code>$image_prepare->execute(
    array(
        ':pid' => $id,
        ':meta_key' => '_wp_attached_file'
    )
);

$image_fetch = $image_prepare->fetchAll();

foreach ($image_fetch as $image_row) {
    $image_name = $row['post_title'];
    $image_meta = unserialize($image_row['meta_value']);
    $image_path = $image_meta['sizes']['home-featured']['file'];
}
</code>```

$image_meta will be similar to:

```<code>array (
    'width' => 720,
    'height' => 960,
    'file' => '2017/03/image.jpg',
    'sizes' =>
        array (
            'thumbnail' =>
                array (
                    'file' => 'image-150x150.jpg',
                    'width' => 150,
                    'height' => 150,
                    'mime-type' => 'image/jpeg',
                ),
            'medium' =>
                array (
                    'file' => 'image-225x300.jpg',
                    'width' => 225,
                    'height' => 300,
                    'mime-type' => 'image/jpeg',
                ),
            'twentyseventeen-thumbnail-avatar' =>
                array (
                    'file' => 'image-100x100.jpg',
                    'width' => 100,
                    'height' => 100,
                    'mime-type' => 'image/jpeg',
                ),
        ),
</code>```

Body:
I have WordPress blog which is hosted as a sub directory of a web application. The WordPress installation is untouched and modifications are done in the theme level. The web application home page needs to display the recent blog posts. So I have the following code for displaying the recent posts:

    $array = array();

    $query = "SELECT * FROM wp_posts WHERE post_status=:publish AND post_type=:post_type";
    $stmt = $this->dbj->prepare($query);
    $stmt->execute(array(
        ':publish' => 'publish',
        ':post_type' => 'post'
    ));

    if ($stmt->rowCount() > 0) {
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $id = $row["ID"];
            if ($row["post_name"] == '') {
                $slug = $row["ID"];
            } else {
                $slug = $row["post_name"];
            }
            $content1 = strip_tags($row["post_content"]);

            $image_prepare = $this->dbj->prepare('SELECT
    wp_postmeta.meta_id,
    wp_postmeta.post_id,
    wp_postmeta.meta_key,
    wp_postmeta.meta_value
FROM
    wp_postmeta
INNER JOIN wp_posts ON wp_posts.ID = wp_postmeta.post_id
WHERE
    wp_postmeta.meta_key = :meta_key
AND wp_posts.post_parent = :pid');

            $image_prepare->execute(
                array(
                    ':pid' => $id,
                    ':meta_key' => '_wp_attached_file'
                )
            );

            $image_fetch = $image_prepare->fetchAll();

            foreach ($image_fetch as $image_row) {
                $image_name = $row['post_title'];
                $image_path = $image_row['meta_value'];
            }

            if (strlen($content1) > 200) {
                $content = substr($content1, 0, 200) . '...';
            } else {
                $content = nl2br($content1);
            }

            $array[] = array(
                'image_path' => $image_path,
                'image_name' => $image_name,
                'slug' => $row["post_name"],
                'content' => $content,
                'title' => $row['post_title']
            );
        }
    return $array;
    }

I am getting the full size image url. I have done resizing in my functions.php file in theme:

add_theme_support('post-thumbnails');

add_image_size('home-size', 214, 300);
add_image_size('home-featured', 300, 300);
add_image_size('jobs-thumb', 50, 75);

The problem is that resized images in uploads directory does not always have image-name-300x300.jpg for home-featured. Instead it have random value for height depending on the image's ratio in file name(Ex: image-name-300x220.jpg). And I have regenerated the thumbnails again but still same file name. How do I get 'home-featured' for above solution?

Body:
Wordpress keeps serialized data of generated images in postmeta table with _wp_attachment_metadata as a meta_key.

In your case, if you don't need full size images for your code, change _wp_attached_file to _wp_attachment_metadata.

$image_prepare->execute(
    array(
        ':pid' => $id,
        ':meta_key' => '_wp_attached_file'
    )
);

$image_fetch = $image_prepare->fetchAll();

foreach ($image_fetch as $image_row) {
    $image_name = $row['post_title'];
    $image_meta = unserialize($image_row['meta_value']);
    $image_path = $image_meta['sizes']['home-featured']['file'];
}

$image_meta will be similar to:

array (
    'width' => 720,
    'height' => 960,
    'file' => '2017/03/image.jpg',
    'sizes' =>
        array (
            'thumbnail' =>
                array (
                    'file' => 'image-150x150.jpg',
                    'width' => 150,
                    'height' => 150,
                    'mime-type' => 'image/jpeg',
                ),
            'medium' =>
                array (
                    'file' => 'image-225x300.jpg',
                    'width' => 225,
                    'height' => 300,
                    'mime-type' => 'image/jpeg',
                ),
            'twentyseventeen-thumbnail-avatar' =>
                array (
                    'file' => 'image-100x100.jpg',
                    'width' => 100,
                    'height' => 100,
                    'mime-type' => 'image/jpeg',
                ),
        ),


问:
How to scale video to be as large as possible so that the background area is completely covered by the background video
I want to create a background video using HTML5 so it will scale as large as possible so that the background area is completely covered by the background video, something similarly to the background-size: cover;, but to the video.

I want it to be as cross-platform/browser as possible.

EDIT

I meant background-size: cover;

Sorry for that :/

答:
You can easily do this using the transform property. It adjusts the video at the center of the screen and the width properties fill the screen with the entire video.</p>

```<code>video {
 position: fixed;
 top: 50%;
 left: 50%;
 min-width: 100%;
 min-height: 100%;
 width: auto;
 height: auto;
 z-index: -100;
 transform: translateX(-50%) translateY(-50%);
 background-size: cover;
}
</code>```

Body:
You can easily do this using the transform property. It adjusts the video at the center of the screen and the width properties fill the screen with the entire video.

video {
 position: fixed;
 top: 50%;
 left: 50%;
 min-width: 100%;
 min-height: 100%;
 width: auto;
 height: auto;
 z-index: -100;
 transform: translateX(-50%) translateY(-50%);
 background-size: cover;
}


问:
coverage on virtualenv includes tests of python standard libraries
I am trying to run test coverage of my code. Tests are located inside tests folder of my project. Without coverage I ran:

```<code>python -m unittest discover tests -vb
</code>```

and ran all tests inside test directory. I tried using coverage report running

```<code>coverage run -m unittest discover test -vb
</code>```

and then

```<code>coverage html
</code>```

but the html report contains modules that are from the standard library or third party libraries that are included inside site-packages directory of my virtualenv. I thought coverage excluded this by default. How can I run coverage correctly to exclude everything outside my code? Shoulde I use the --source flag and set it to the root of my project e.g

```<code> coverage run --source=<project_root> -m unittest discover test -vb
</code>```

答:
I think your expectation is correct: by default you should not get stats for the python installed library. I'm running your command on a test of mine and only get coverage for my modules. With flag -L I get coverage for python installed modules. Is it possible you have a custom installation of coverage? Or the flag is somehow set in your configuration? What version of coverage do you use? From the history of versions, it seems the default for this option may be true for versions older than v3.0b.
If you run without -m unittest discover (simply execute one of the tests), do you still get the same?
You could try --debug=sys in case it produces useful info.</p>

Body:
I am trying to run test coverage of my code. Tests are located inside tests folder of my project. Without coverage I ran:

python -m unittest discover tests -vb

and ran all tests inside test directory. I tried using coverage report running

coverage run -m unittest discover test -vb

and then

coverage html

but the html report contains modules that are from the standard library or third party libraries that are included inside site-packages directory of my virtualenv. I thought coverage excluded this by default. How can I run coverage correctly to exclude everything outside my code? Shoulde I use the --source flag and set it to the root of my project e.g

 coverage run --source=<project_root> -m unittest discover test -vb


问:
How to fetch HTTP parameters in java transformer in MULE ESB
I am bit new at Mule ESB and Anypoint Studio so I am trying to figure out how to fetch HTTP query parameters in a java transformer class.

I have tried

```<code>String firstname = message.getInboundProperty("fname");
String lastName = message.getInboundProperty("lname");
</code>```

even went with

```<code>Map<String, String> queryParams = message.getInboundProperty("http.query.params");
String firstname = queryParams.get("fname");
String lastname = queryParams.get("lname");
</code>```

but they return null values, I have even tried to use Callable Interface but I think it only possible to use it if it's a JAVA Component.

Do please let me know,

Thanks.

答:
If you want to use in a Java transformer, you can follow the following example :-

```<code>public class MyCustomTransformer extends AbstractMessageTransformer {
 @Override
 public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {

     Map<String, String> queryParams = message.getInboundProperty("http.query.params");
     String fname=queryParams.get("fname");
     System.out.println("fname: "+fname);
     String lname=queryParams.get("lname");
     System.out.println("lname: "+lname);
     return message;

 }
}
</code>```

And Mule flow will be :-

```<code> <http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/>

 <flow name="Testlow">
   <http:listener config-ref="HTTP_Listener_Configuration" path="/test" doc:name="HTTP"/>
  <custom-transformer class="MyCustomTransformer" doc:name="Java"/>
 </flow>
</code>```

Now if you hit the url with query parameter for example:- http://localhost:8081/test?fname=anirban&lname=sen

You will get the following result in your console:-

Body:
I am bit new at Mule ESB and Anypoint Studio so I am trying to figure out how to fetch HTTP query parameters in a java transformer class.

I have tried

String firstname = message.getInboundProperty("fname");
String lastName = message.getInboundProperty("lname");

even went with

Map<String, String> queryParams = message.getInboundProperty("http.query.params");
String firstname = queryParams.get("fname");
String lastname = queryParams.get("lname");

but they return null values, I have even tried to use Callable Interface but I think it only possible to use it if it's a JAVA Component.

Do please let me know,

Thanks.

Body:
If you want to use in a Java transformer, you can follow the following example :-

public class MyCustomTransformer extends AbstractMessageTransformer {
 @Override
 public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {

     Map<String, String> queryParams = message.getInboundProperty("http.query.params");
     String fname=queryParams.get("fname");
     System.out.println("fname: "+fname);
     String lname=queryParams.get("lname");
     System.out.println("lname: "+lname);
     return message;

 }
}

And Mule flow will be :-

 <http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/>

 <flow name="Testlow">
   <http:listener config-ref="HTTP_Listener_Configuration" path="/test" doc:name="HTTP"/>
  <custom-transformer class="MyCustomTransformer" doc:name="Java"/>
 </flow>

Now if you hit the url with query parameter for example:- http://localhost:8081/test?fname=anirban&lname=sen

You will get the following result in your console:-


问:
Dependency Injection with .NETCore for DAL and connection string
I am new to the DI patterns with .NETCore, and I am having trouble getting my connection strings to my DAL.

I followed the advice given in this thread via the accepted answer, and subsequent comments.

This is my base class

```<code>public class BaseRepository : IRepository<IDataModel>
{
    private readonly IConfiguration config;

    public BaseRepository(IConfiguration config)
    {
        this.config = config;
    }

    public string GetSQLConnectionString()
    {
        return config["Data:DefaultConnetion:ConnectionString"];
    }
</code>```

This is a snippet of a repository class inheriting the base class

```<code>public class PrivacyLevelRepository : BaseRepository, IRepository<PrivacyLevelDM>
{
    public PrivacyLevelRepository(IConfiguration config) : base(config) { }
    public void Add(PrivacyLevelDM dataModel)
    {
         ...
    }
}
</code>```

This is in my startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddScoped<IRepository<IDataModel>>(c => new BaseRepository(Configuration));
    }
</code>```

However, In my service layer, the instantiation of the repository class is still asking for the (IConfiguration config) to be passed as a parameter.

```<code> PrivacyLevelRepository repo = new PrivacyLevelRepository();
</code>```

How do I get the IConfiguration loaded directly to my DAL, without having to pass it from Controller > BLL > DAL.  This seems extremely inefficient, and incorrect.  As the DAL should be determining the connection for an object, not the controller or service layer.  They should be agnostic of the datasource, no?

I figure this is something simple, that I am just not seeing within the DI/IoC paradigm, but I cannot figure it out.

Edit: I am not using Entity Framework, but a custom Data layer.

Thanx for any help.

答:
You could follow the options pattern with the configuration framework. This allows you to define a custom type that hold your configuration settings (statically typed) while being restricted to only your actual relevant configuration.

You can use it like this:

```<code>public void ConfigureServices(IServiceCollection services)
{
    // register the `Data:DefaultConnection` configuration section as
    // a configuration for the `DatabaseOptions` type
    services.Configure<DatabaseOptions>(Configuration.GetSection("Data:DefaultConnection"));

    // register your database repository
    // note that we don’t use a custom factory where we create the object ourselves
    services.AddScoped<IRepository<IDataModel>, BaseRepository>();
}
</code>```

This assumes a type DatabaseOptions like this:

```<code>public class DatabaseOptions
{
    public string ConnectionString { get; set; }
}
</code>```

Then, you can just have the DatabaseOptions injected into your BaseRepository:

```<code>public class BaseRepository
{
    private readonly DatabaseOptions _options;

    public BaseRepository(IOptions<DatabaseOptions> databaseOptions)
    {
         _options = databaseOptions.Value;
    }
}
</code>```

Of course, if you have subtypes of that BaseRepository, you need to register those as well and pass the options to the base class:

```<code>// register the repository as well in the `ConfigureServices` method
services.AddScoped<PrivacyLevelRepository>();
</code>```

```<code>public class PrivacyLevelRepository : BaseRepository, IRepository<PrivacyLevelDM>
{
    public PrivacyLevelRepository(IOptions<DatabaseOptions> databaseOptions)
        : base(databaseOptions)
    { }
}
</code>```

I am instantiating and using the repo like I always have. I am not sure how to use a class that I don't instantiate. How do i let this object know it depends on the PrivacyLevelRepository?

```<code>PrivacyLevelRepository repo = new PrivacyLevelRepository();
returnValue = repo.GetAllByDomainID(DomainID).ToList();
return returnValue;
</code>```

You do not appear to understand the idea behind dependency injection yet. Dependency injection with its underlying principle Inversion of Control is simply said about avoiding the use of new to create objects. Instead of actively depending on an implementation (in your example the PrivacyLevelRepository), you are giving up the responsibility and just depend on the outer system to provide you with the dependencies you need.

So instead of creating a new PrivacyLevelRepository, you inject an instance that is created by something somewhere else. That looses coupling on the implementation of your dependency. A very practical example of this is how PrivacyLevelRepository depends on IOptions<DatabaseOptions>. You, as a consumer of that repository, should not need to care to know how to get such an object to be able to create the repository instance. You shouldn’t even need to know how to create a repository instance in the first place.

So your consumer of PrivacyLevelRepository should follow the same idea as the repository itself: The repository does not know how to get those database options; it just depends on the constructing entity to pass such an object on. And your consumer, I assume a controller, should do the same:

```<code>public class MyController
{
    private readonly PrivacyLevelRepository _privacyLevelRepository;

    public MyController(PrivacyLevelRepository privacyLevelRepository)
    {
         // instead of *creating* a repository, we just expect to get one
         _privacyLevelRepository = privacyLevelRepository;
    }

    public IActionResult SomeRoute()
    {
         var domainId = "whatever";
         var data = _privacyLevelRepository.GetAllByDomainID(domainId).ToList();
         return View(data);
    }
}
</code>```

Of course, something has to create the dependencies at some point. But if you embrace dependency injection completely—which ASP.NET Core not only makes very easy but also actively requires you to do so in order to work completely—then you don’t need to care about that part. You just register the types in the ConfigureServices method and then expect the dependencies to be fulfilled where you need them.

For more information, you should definitely check out the dependency injection chapter of the documentation.

Body:
I am new to the DI patterns with .NETCore, and I am having trouble getting my connection strings to my DAL.

I followed the advice given in this thread via the accepted answer, and subsequent comments.

This is my base class

public class BaseRepository : IRepository<IDataModel>
{
    private readonly IConfiguration config;

    public BaseRepository(IConfiguration config)
    {
        this.config = config;
    }

    public string GetSQLConnectionString()
    {
        return config["Data:DefaultConnetion:ConnectionString"];
    }

This is a snippet of a repository class inheriting the base class

public class PrivacyLevelRepository : BaseRepository, IRepository<PrivacyLevelDM>
{
    public PrivacyLevelRepository(IConfiguration config) : base(config) { }
    public void Add(PrivacyLevelDM dataModel)
    {
         ...
    }
}

This is in my startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddScoped<IRepository<IDataModel>>(c => new BaseRepository(Configuration));
    }

However, In my service layer, the instantiation of the repository class is still asking for the (IConfiguration config) to be passed as a parameter.

 PrivacyLevelRepository repo = new PrivacyLevelRepository();

How do I get the IConfiguration loaded directly to my DAL, without having to pass it from Controller > BLL > DAL.  This seems extremely inefficient, and incorrect.  As the DAL should be determining the connection for an object, not the controller or service layer.  They should be agnostic of the datasource, no?

I figure this is something simple, that I am just not seeing within the DI/IoC paradigm, but I cannot figure it out.

Edit: I am not using Entity Framework, but a custom Data layer.

Thanx for any help.

Body:
You could follow the options pattern with the configuration framework. This allows you to define a custom type that hold your configuration settings (statically typed) while being restricted to only your actual relevant configuration.

You can use it like this:

public void ConfigureServices(IServiceCollection services)
{
    // register the `Data:DefaultConnection` configuration section as
    // a configuration for the `DatabaseOptions` type
    services.Configure<DatabaseOptions>(Configuration.GetSection("Data:DefaultConnection"));

    // register your database repository
    // note that we don’t use a custom factory where we create the object ourselves
    services.AddScoped<IRepository<IDataModel>, BaseRepository>();
}

This assumes a type DatabaseOptions like this:

public class DatabaseOptions
{
    public string ConnectionString { get; set; }
}

Then, you can just have the DatabaseOptions injected into your BaseRepository:

public class BaseRepository
{
    private readonly DatabaseOptions _options;

    public BaseRepository(IOptions<DatabaseOptions> databaseOptions)
    {
         _options = databaseOptions.Value;
    }
}

Of course, if you have subtypes of that BaseRepository, you need to register those as well and pass the options to the base class:

// register the repository as well in the `ConfigureServices` method
services.AddScoped<PrivacyLevelRepository>();

public class PrivacyLevelRepository : BaseRepository, IRepository<PrivacyLevelDM>
{
    public PrivacyLevelRepository(IOptions<DatabaseOptions> databaseOptions)
        : base(databaseOptions)
    { }
}

I am instantiating and using the repo like I always have. I am not sure how to use a class that I don't instantiate. How do i let this object know it depends on the PrivacyLevelRepository?

PrivacyLevelRepository repo = new PrivacyLevelRepository();
returnValue = repo.GetAllByDomainID(DomainID).ToList();
return returnValue;

You do not appear to understand the idea behind dependency injection yet. Dependency injection with its underlying principle Inversion of Control is simply said about avoiding the use of new to create objects. Instead of actively depending on an implementation (in your example the PrivacyLevelRepository), you are giving up the responsibility and just depend on the outer system to provide you with the dependencies you need.

So instead of creating a new PrivacyLevelRepository, you inject an instance that is created by something somewhere else. That looses coupling on the implementation of your dependency. A very practical example of this is how PrivacyLevelRepository depends on IOptions<DatabaseOptions>. You, as a consumer of that repository, should not need to care to know how to get such an object to be able to create the repository instance. You shouldn’t even need to know how to create a repository instance in the first place.

So your consumer of PrivacyLevelRepository should follow the same idea as the repository itself: The repository does not know how to get those database options; it just depends on the constructing entity to pass such an object on. And your consumer, I assume a controller, should do the same:

public class MyController
{
    private readonly PrivacyLevelRepository _privacyLevelRepository;

    public MyController(PrivacyLevelRepository privacyLevelRepository)
    {
         // instead of *creating* a repository, we just expect to get one
         _privacyLevelRepository = privacyLevelRepository;
    }

    public IActionResult SomeRoute()
    {
         var domainId = "whatever";
         var data = _privacyLevelRepository.GetAllByDomainID(domainId).ToList();
         return View(data);
    }
}

Of course, something has to create the dependencies at some point. But if you embrace dependency injection completely—which ASP.NET Core not only makes very easy but also actively requires you to do so in order to work completely—then you don’t need to care about that part. You just register the types in the ConfigureServices method and then expect the dependencies to be fulfilled where you need them.

For more information, you should definitely check out the dependency injection chapter of the documentation.


问:
Call a soap webservice in android
I need to make a call to a soap webservice in an android device. I have been reading a lot of articles in stackoverflow and on other pages, watching videos... But I've tried everythin and I can't make it work in my android device, and I can't test in on an emulator, because my computer can't handle any of them, so I don't know if the error is on the code or if it's a problem of my android device.

The layout xml are only an EditText, a Button, and a TextView.

In this link you can see the request xml I need to send to the webservice (should I use SOAP 1.1 or SOAP 1.2 ?)
http://www.webservicex.net/globalweather.asmx?op=GetCitiesByCountry

This is my actual code, and I have tried many other ways, and none of them have worked for me. Any help? (url, namespace, soap_action and method_name values are okey, aren't they?)

```<code>package com.example.doazdoas.webservice_prueba;

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;

    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;

    import android.os.AsyncTask;
    import android.widget.Toast;

    import static android.content.ContentValues.TAG;

   public class MainActivity extends Activity{
    private TextView textResult;
    private Button buttonSend;

    String NAMESPACE = "http://www.webserviceX.NET/";
    String METHOD_NAME = "GetCitiesByCountry";
    String SOAP_ACTION = NAMESPACE + METHOD_NAME;
    String URL = "http://www.webservicex.net/globalweather.asmx?WSDL";

    private Object resultsRequestSOAP = null;

    HttpTransportSE androidHttpTransport;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textResult = (TextView)findViewById(R.id.textResultado);
        buttonSend = (Button)findViewById(R.id.buttonEnviar);
        //setContentView(tv);
    }

    public void onClickEnviar(View view){
        AsyncCallWS task = new AsyncCallWS();
        task.execute();
    }

    private class AsyncCallWS extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute");
        }

        @Override
        protected Void doInBackground(Void... params) {
            Log.i(TAG, "doInBackground");
            sendRequest();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            Log.i(TAG, "onPostExecute");
            Log.d("dump Request: " ,androidHttpTransport.requestDump);
            Log.d("dump response: " ,androidHttpTransport.responseDump);
        }

    }

    public void sendRequest(){
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        //SoapObject
        request.addProperty("@CountryName", "SPAIN");
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);

        androidHttpTransport = new HttpTransportSE(URL);
        try
        {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            resultsRequestSOAP =  envelope.getResponse();
            String[] results = (String[])  resultsRequestSOAP;
            textResult.setText( results[0]);
        }
        catch (Exception aE)
        {
            aE.printStackTrace ();
        }
    }
}
</code>```

答:
You can do any UI related operations in doInBackGround, So move them in onPostExecute methnod.

Because doInBackGround is not a UI thread. Please read AsyncTask Document carefully. Whatever is the data you are returning from doInBackGround, it is being taken as input to onPostExecute.

So change your code as follows,

```<code>    private class AsyncCallWS extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        Log.i(TAG, "onPreExecute");
    }

    @Override
    protected String[] doInBackground(Void... params) {
        Log.i(TAG, "doInBackground");
        String[] data = sendRequest();
        return data;
    }

    @Override
    protected void onPostExecute(String[] result) {
        Log.i(TAG, "onPostExecute");
        if(result != null && result.length > 0){
             textResult.setText( results[0]);
        }
    }

}

private String[] sendRequest(){
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    //SoapObject
    request.addProperty("@CountryName", "SPAIN");
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);

    androidHttpTransport = new HttpTransportSE(URL);
    try
    {
        androidHttpTransport.call(SOAP_ACTION, envelope);
        resultsRequestSOAP =  envelope.getResponse();
        String[] results = (String[])  resultsRequestSOAP;
    }
    catch (Exception aE)
    {
        aE.printStackTrace ();
    }
}
</code>```

Title: Call a soap webservice in android

Body:
I need to make a call to a soap webservice in an android device. I have been reading a lot of articles in stackoverflow and on other pages, watching videos... But I've tried everythin and I can't make it work in my android device, and I can't test in on an emulator, because my computer can't handle any of them, so I don't know if the error is on the code or if it's a problem of my android device.

The layout xml are only an EditText, a Button, and a TextView.

In this link you can see the request xml I need to send to the webservice (should I use SOAP 1.1 or SOAP 1.2 ?)
http://www.webservicex.net/globalweather.asmx?op=GetCitiesByCountry

This is my actual code, and I have tried many other ways, and none of them have worked for me. Any help? (url, namespace, soap_action and method_name values are okey, aren't they?)

package com.example.doazdoas.webservice_prueba;

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.TextView;

    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.HttpTransportSE;

    import android.os.AsyncTask;
    import android.widget.Toast;

    import static android.content.ContentValues.TAG;

   public class MainActivity extends Activity{
    private TextView textResult;
    private Button buttonSend;

    String NAMESPACE = "http://www.webserviceX.NET/";
    String METHOD_NAME = "GetCitiesByCountry";
    String SOAP_ACTION = NAMESPACE + METHOD_NAME;
    String URL = "http://www.webservicex.net/globalweather.asmx?WSDL";

    private Object resultsRequestSOAP = null;

    HttpTransportSE androidHttpTransport;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textResult = (TextView)findViewById(R.id.textResultado);
        buttonSend = (Button)findViewById(R.id.buttonEnviar);
        //setContentView(tv);
    }

    public void onClickEnviar(View view){
        AsyncCallWS task = new AsyncCallWS();
        task.execute();
    }

    private class AsyncCallWS extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute");
        }

        @Override
        protected Void doInBackground(Void... params) {
            Log.i(TAG, "doInBackground");
            sendRequest();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            Log.i(TAG, "onPostExecute");
            Log.d("dump Request: " ,androidHttpTransport.requestDump);
            Log.d("dump response: " ,androidHttpTransport.responseDump);
        }

    }

    public void sendRequest(){
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        //SoapObject
        request.addProperty("@CountryName", "SPAIN");
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.setOutputSoapObject(request);

        androidHttpTransport = new HttpTransportSE(URL);
        try
        {
            androidHttpTransport.call(SOAP_ACTION, envelope);
            resultsRequestSOAP =  envelope.getResponse();
            String[] results = (String[])  resultsRequestSOAP;
            textResult.setText( results[0]);
        }
        catch (Exception aE)
        {
            aE.printStackTrace ();
        }
    }
}

Body:
You can do any UI related operations in doInBackGround, So move them in onPostExecute methnod.

Because doInBackGround is not a UI thread. Please read AsyncTask Document carefully. Whatever is the data you are returning from doInBackGround, it is being taken as input to onPostExecute.

So change your code as follows,

    private class AsyncCallWS extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        Log.i(TAG, "onPreExecute");
    }

    @Override
    protected String[] doInBackground(Void... params) {
        Log.i(TAG, "doInBackground");
        String[] data = sendRequest();
        return data;
    }

    @Override
    protected void onPostExecute(String[] result) {
        Log.i(TAG, "onPostExecute");
        if(result != null && result.length > 0){
             textResult.setText( results[0]);
        }
    }

}

private String[] sendRequest(){
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    //SoapObject
    request.addProperty("@CountryName", "SPAIN");
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.setOutputSoapObject(request);

    androidHttpTransport = new HttpTransportSE(URL);
    try
    {
        androidHttpTransport.call(SOAP_ACTION, envelope);
        resultsRequestSOAP =  envelope.getResponse();
        String[] results = (String[])  resultsRequestSOAP;
    }
    catch (Exception aE)
    {
        aE.printStackTrace ();
    }
}


问:
Spring OAuth2 Redis Client Details
I have a working example of oauth2 and rest with inmemory authentication and authorization for the client and owner of the resource.

I want to use Redis and is a bit confused on how to it set it up.

How to adjust my code below to be able to persist data in Redis (e.g token, refresh_token and other client details)

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Value("${spring.oauth2.realm.id}")
    private String REALM;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private UserApprovalHandler userApprovalHandler;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client001")
                .authorizedGrantTypes("client_credentials", "password")
                .authorities("ROLE_ADMIN", "ROLE_TRUSTED_CLIENT")
                .scopes("read", "write", "trust")
                .secret("secret")
                .accessTokenValiditySeconds(120)
                .refreshTokenValiditySeconds(600);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .userApprovalHandler(userApprovalHandler)
                .authenticationManager(authenticationManager);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.realm(REALM + "/client");
    }

}```
</div>
</div>
</p>

<p><strong>[Updated]</strong></p>

<p>I was able to store the tokens to <strong>Redis</strong> by utilizing <strong>RedisTokenStore</strong>. To do so, in your <strong>OAuth2SecurityConfiguration</strong> replace the following lines:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>@Bean
public TokenStore tokenStore() {
    return new InMemoryTokenStore();
}</code>```

with...

@Bean
public TokenStore tokenStore(final RedisConnectionFactory factory) {
    return new RedisTokenStore(factory);
}```
</div>
</div>
</p>

<p>Now a new problem was encountered, in <strong><code>AuthorizationServerConfiguration#configure(final ClientDetailsServiceConfigurer clients);</code></strong>. Is there a support for <strong>redis</strong>?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>@Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
      clients.inMemory()
        .withClient("client001")
        .secret("secret")
        .authorizedGrantTypes("client_credentials", "password")
        .authorities("ROLE_ADMIN", "ROLE_TRUSTED_CLIENT")
        .scopes("read", "write", "trust")
        .accessTokenValiditySeconds(60)
        .refreshTokenValiditySeconds(120);
    }</code>```

When I peeked at ClientDetailsServiceConfigurer it only supports inMemory() and jdbc(). I was planning to use withClientDetails() to support redis. Is there a RedisClientDetailsService or something of the like?

Any comments and suggestion for its implementation is greatly appreciated.

答:
I was able to store the client details to Redis.

These are the steps that I made:

Create the following classes:

RedisClientDetailsServiceBuilder.java

RedisClientDetailsService.java

RedisClientDetailsService

public class RedisClientDetailsService implements ClientDetailsService {

    private PasswordEncoder passwordEncoder = NoOpPasswordEncoder.getInstance();

    private Map<String, ClientDetails> clientDetailsStore = new HashMap<String, ClientDetails>();

    public ClientDetails loadClientByClientId(final String clientId) throws ClientRegistrationException {
        final ClientDetails details = clientDetailsStore.get(clientId);
        if (details == null) {
            throw new NoSuchClientException("No client with requested id: " + clientId);
        }
        return details;
    }

    public void setClientDetailsStore(final Map<String, ? extends ClientDetails> clientDetailsStore) {
        this.clientDetailsStore = new HashMap<String, ClientDetails>(clientDetailsStore);
    }

    /**
     * @param passwordEncoder the password encoder to set
     */
    public void setPasswordEncoder(final PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }
}```
</div>
</div>
</p>

<p><strong>RedisClientDetailsServiceBuilder</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>public class RedisClientDetailsServiceBuilder extends ClientDetailsServiceBuilder<RedisClientDetailsServiceBuilder> {

    private Map<String, ClientDetails> clientDetails = new HashMap<String, ClientDetails>();

    private PasswordEncoder passwordEncoder; // for writing client secrets

    public RedisClientDetailsServiceBuilder passwordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
        return this;
    }

    @Override
    protected void addClient(
            final String clientId,
            final ClientDetails build) {

        clientDetails.put(clientId, build);
    }

    @Override
    protected ClientDetailsService performBuild() {
        final RedisClientDetailsService redisClientDetailsService = new RedisClientDetailsService();
        if (passwordEncoder != null) {
            // This is used to encode secrets as they are added to the database (if it isn't set then the user has top
            // pass in pre-encoded secrets)
            redisClientDetailsService.setPasswordEncoder(passwordEncoder);
        }

        redisClientDetailsService.setClientDetailsStore(clientDetails);
        return redisClientDetailsService;
    }

}</code>```

Then on AuthorizationServerConfiguration#configure(), set client builder with the builder we made.

@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
    final RedisClientDetailsServiceBuilder builder = new RedisClientDetailsServiceBuilder();
    clients.setBuilder(builder);

    // @formatter:off
    builder.withClient("client001")
          .secret("secret")
          .authorizedGrantTypes("client_credentials", "password")
          .authorities("ROLE_ADMIN", "ROLE_TRUSTED_CLIENT")
          .scopes("read", "write", "trust")
          .accessTokenValiditySeconds(120)
          .refreshTokenValiditySeconds(400)
    // @formatter:on
}```

Title: Spring OAuth2 Redis Client Details

Body:
I have a working example of oauth2 and rest with inmemory authentication and authorization for the client and owner of the resource.

I want to use Redis and is a bit confused on how to it set it up.

How to adjust my code below to be able to persist data in Redis (e.g token, refresh_token and other client details)

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Value("${spring.oauth2.realm.id}")
    private String REALM;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private UserApprovalHandler userApprovalHandler;

    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client001")
                .authorizedGrantTypes("client_credentials", "password")
                .authorities("ROLE_ADMIN", "ROLE_TRUSTED_CLIENT")
                .scopes("read", "write", "trust")
                .secret("secret")
                .accessTokenValiditySeconds(120)
                .refreshTokenValiditySeconds(600);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .userApprovalHandler(userApprovalHandler)
                .authenticationManager(authenticationManager);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.realm(REALM + "/client");
    }

}

[Updated]

I was able to store the tokens to Redis by utilizing RedisTokenStore. To do so, in your OAuth2SecurityConfiguration replace the following lines:

@Bean
public TokenStore tokenStore() {
    return new InMemoryTokenStore();
}

with...

@Bean
public TokenStore tokenStore(final RedisConnectionFactory factory) {
    return new RedisTokenStore(factory);
}

Now a new problem was encountered, in AuthorizationServerConfiguration#configure(final ClientDetailsServiceConfigurer clients);. Is there a support for redis?

@Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
      clients.inMemory()
        .withClient("client001")
        .secret("secret")
        .authorizedGrantTypes("client_credentials", "password")
        .authorities("ROLE_ADMIN", "ROLE_TRUSTED_CLIENT")
        .scopes("read", "write", "trust")
        .accessTokenValiditySeconds(60)
        .refreshTokenValiditySeconds(120);
    }

When I peeked at ClientDetailsServiceConfigurer it only supports inMemory() and jdbc(). I was planning to use withClientDetails() to support redis. Is there a RedisClientDetailsService or something of the like?

Any comments and suggestion for its implementation is greatly appreciated.

Body:
I was able to store the client details to Redis.

These are the steps that I made:

Create the following classes:

RedisClientDetailsServiceBuilder.java

RedisClientDetailsService.java

RedisClientDetailsService

public class RedisClientDetailsService implements ClientDetailsService {

    private PasswordEncoder passwordEncoder = NoOpPasswordEncoder.getInstance();

    private Map<String, ClientDetails> clientDetailsStore = new HashMap<String, ClientDetails>();

    public ClientDetails loadClientByClientId(final String clientId) throws ClientRegistrationException {
        final ClientDetails details = clientDetailsStore.get(clientId);
        if (details == null) {
            throw new NoSuchClientException("No client with requested id: " + clientId);
        }
        return details;
    }

    public void setClientDetailsStore(final Map<String, ? extends ClientDetails> clientDetailsStore) {
        this.clientDetailsStore = new HashMap<String, ClientDetails>(clientDetailsStore);
    }

    /**
     * @param passwordEncoder the password encoder to set
     */
    public void setPasswordEncoder(final PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }
}

RedisClientDetailsServiceBuilder

public class RedisClientDetailsServiceBuilder extends ClientDetailsServiceBuilder<RedisClientDetailsServiceBuilder> {

    private Map<String, ClientDetails> clientDetails = new HashMap<String, ClientDetails>();

    private PasswordEncoder passwordEncoder; // for writing client secrets

    public RedisClientDetailsServiceBuilder passwordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
        return this;
    }

    @Override
    protected void addClient(
            final String clientId,
            final ClientDetails build) {

        clientDetails.put(clientId, build);
    }

    @Override
    protected ClientDetailsService performBuild() {
        final RedisClientDetailsService redisClientDetailsService = new RedisClientDetailsService();
        if (passwordEncoder != null) {
            // This is used to encode secrets as they are added to the database (if it isn't set then the user has top
            // pass in pre-encoded secrets)
            redisClientDetailsService.setPasswordEncoder(passwordEncoder);
        }

        redisClientDetailsService.setClientDetailsStore(clientDetails);
        return redisClientDetailsService;
    }

}

Then on AuthorizationServerConfiguration#configure(), set client builder with the builder we made.

@Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
    final RedisClientDetailsServiceBuilder builder = new RedisClientDetailsServiceBuilder();
    clients.setBuilder(builder);

    // @formatter:off
    builder.withClient("client001")
          .secret("secret")
          .authorizedGrantTypes("client_credentials", "password")
          .authorities("ROLE_ADMIN", "ROLE_TRUSTED_CLIENT")
          .scopes("read", "write", "trust")
          .accessTokenValiditySeconds(120)
          .refreshTokenValiditySeconds(400)
    // @formatter:on
}


问:
WordPress: Non-existent pages are being loaded
I believe a hacker modified the website 'http://bbltechnical.co.uk/' so that loads of dating website show up in Google search results for the website. I have looked for those posts/pages via the dashboard and database, and the don't seem to be anywhere.

(I warn further click-through links on the following page contain explicit content)

Example spam page: http://bbltechnical.co.uk/online-uk-dating/

You can see I have changed the theme of the actual website, yet the theme hasn't changed on the spam pages. Using Wappalyzer I have found the WordPress versions differ. Also the two images in the body text of that page do not exist on the FTP. So I have concluded it is another WordPress set up, sharing the same domain name.

I have cleared the database, flushed out the DNS records, and even spoken to GoDaddy about it. It is such a weird behaviour.

This is the .htaccess file:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

答:
I found it was a modification of 'wp-blog-header.php', at the root of the site, which edited the HTTP header to pull in data from another website.

I used a malware scanner plugin to scan for any changes to the core WordPress files.

Thanks to uvishere's suggestion, I used the plugin 'Sucuri Security' to scan for the changes. Another option is the plugin 'Wordfence'.

Body:
I believe a hacker modified the website 'http://bbltechnical.co.uk/' so that loads of dating website show up in Google search results for the website. I have looked for those posts/pages via the dashboard and database, and the don't seem to be anywhere.

(I warn further click-through links on the following page contain explicit content)

Example spam page: http://bbltechnical.co.uk/online-uk-dating/

You can see I have changed the theme of the actual website, yet the theme hasn't changed on the spam pages. Using Wappalyzer I have found the WordPress versions differ. Also the two images in the body text of that page do not exist on the FTP. So I have concluded it is another WordPress set up, sharing the same domain name.

I have cleared the database, flushed out the DNS records, and even spoken to GoDaddy about it. It is such a weird behaviour.

This is the .htaccess file:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress


问:
With angular component and ui-router, can a single controller have multiple templates?
In a component I would like to associate templates to CRUD actions, but use a single controller that handles data for all all of them. Does this make sense with angular components, or should I use several components ?
How would the ui-router state configuration look like ?

EDIT:
Components have templates, and ui-router states too. I am confused about the articulation of those 2 concepts.

EDIT 2:
trying to clarify my understanding so far :

component are controller + template + bindings. Controller can be omitted.

states are url + template + controller or url + component. Controller can be omitted.

So it seems that components are taking away some of the responsabilities that use to belong to ui-router.

My goal here:

```<code> - url1 --> controller foo + template x;
 - url2 --> controller foo + template y;
 - url3 --> controller foo + template z;
</code>```

should I do :

components:

```<code>component x --> controller foo + template x;
component y --> controller foo + template y;
component z --> controller foo + template z;
</code>```

and then routing:

```<code>url 1 --> component x
url 2 --> component y
url 3 --> component z
</code>```

?

EDIT 3:
quote from https://docs.angularjs.org/guide/component :

"In a component-based application, every view is a component"

quote from https://ui-router.github.io/guide/ng1/route-to-component :

"The component model enforces separation of concerns and encapsulation by using an isolate scope. Data from parent scopes can no longer be directly accessed. Instead, it needs to be explicitly wired in"

答:
Your state provider will look like this

JS code

```<code>        $stateProvider
      .state('report', {
        views: {
          'filters': {
            templateUrl: 'report-filters.html',
            controller: 'ctrl'
          },
          'tabledata': {
            templateUrl: 'report-table.html',
            controller: 'ctrl'
          },
          'graph': {
            templateUrl: 'report-graph.html',
            controller: 'ctrl'
          }
        }
      })
</code>```

in single state you can load multiple views

HTML

```<code>  <body>
    <div ui-view="filters"></div>
    <div ui-view="tabledata"></div>
    <div ui-view="graph"></div>
  </body>
</code>```

refer multiple views

Body:
In a component I would like to associate templates to CRUD actions, but use a single controller that handles data for all all of them. Does this make sense with angular components, or should I use several components ?
How would the ui-router state configuration look like ?

EDIT:
Components have templates, and ui-router states too. I am confused about the articulation of those 2 concepts.

EDIT 2:
trying to clarify my understanding so far :

component are controller + template + bindings. Controller can be omitted.

states are url + template + controller or url + component. Controller can be omitted.

So it seems that components are taking away some of the responsabilities that use to belong to ui-router.

My goal here:

 - url1 --> controller foo + template x;
 - url2 --> controller foo + template y;
 - url3 --> controller foo + template z;

should I do :

components:

component x --> controller foo + template x;
component y --> controller foo + template y;
component z --> controller foo + template z;

and then routing:

url 1 --> component x
url 2 --> component y
url 3 --> component z

?

EDIT 3:
quote from https://docs.angularjs.org/guide/component :

"In a component-based application, every view is a component"

quote from https://ui-router.github.io/guide/ng1/route-to-component :

"The component model enforces separation of concerns and encapsulation by using an isolate scope. Data from parent scopes can no longer be directly accessed. Instead, it needs to be explicitly wired in"

Body:
Your state provider will look like this

JS code

        $stateProvider
      .state('report', {
        views: {
          'filters': {
            templateUrl: 'report-filters.html',
            controller: 'ctrl'
          },
          'tabledata': {
            templateUrl: 'report-table.html',
            controller: 'ctrl'
          },
          'graph': {
            templateUrl: 'report-graph.html',
            controller: 'ctrl'
          }
        }
      })

in single state you can load multiple views

HTML

  <body>
    <div ui-view="filters"></div>
    <div ui-view="tabledata"></div>
    <div ui-view="graph"></div>
  </body>

refer multiple views


问:
Wiremock Stand alone - How to manipulate response with request data
I was trying to implement mocking of POST REST call using Wiremock Standalone server. I am faced with a challenge like this, suppose the post body contains an "name" field and its value, the same value should be returned in the response of that POST call. My json file looks like this:

```<code>{
"priority": 1,
"request": {
    "method": "POST",
    "urlPath": "/primeSlots",
    "bodyPatterns" : [ {
        "matchesJsonPath" : "{ \"things\": [ { \"name\": \"794363\" }]
 }"
    } ]
 },
 "response": {
    "status": 200,
    "body": "{{$.things.name.value}}",
    "transformers": ["response-template"]
 }
}
</code>```

so, I need to get the value , that is 794363,but using above approach not able to get it in the post response body.

I tried this too:

```<code>{
 "request": {
    "method": "POST",
    "urlPath": "/transform",
    "bodyPatterns": [
        {
            "matchesJsonPath" : "$.things[?(@.name =~ /[0-9]+/i)]"
        }
    ]
  },
  "response": {
    "status": 200,
    "body": "{\"responseName\": \"
   {{request.body.things.name.value}}\"}",
    "headers": {
        "Content-Type": "application/json"
    },
    "transformers": ["body-transformer"]
  }
 }
</code>```

So my question is, even if i use a regEx, which matches with any number that comes in the request, how to give back the same number in the response using Wiremock standalone json file?
Thanks.

答:
Unfortunately WireMock's response templating transformer doesn't currently break out the request body into a Map as would be necessary for what you're trying to do. The request body is just a single string.

The simplest way for you to enable this would probably be to write a Handlebars helper that implements JSONPath or some other mechanism for querying a JSON document, then registering this with the templating transformer when you initialise WireMock.

At some point I'll write handlebars helpers to do this kind of thing for XML and JSON, but that won't be for a while.

Body:
I was trying to implement mocking of POST REST call using Wiremock Standalone server. I am faced with a challenge like this, suppose the post body contains an "name" field and its value, the same value should be returned in the response of that POST call. My json file looks like this:

{
"priority": 1,
"request": {
    "method": "POST",
    "urlPath": "/primeSlots",
    "bodyPatterns" : [ {
        "matchesJsonPath" : "{ \"things\": [ { \"name\": \"794363\" }]
 }"
    } ]
 },
 "response": {
    "status": 200,
    "body": "{{$.things.name.value}}",
    "transformers": ["response-template"]
 }
}

so, I need to get the value , that is 794363,but using above approach not able to get it in the post response body.

I tried this too:

{
 "request": {
    "method": "POST",
    "urlPath": "/transform",
    "bodyPatterns": [
        {
            "matchesJsonPath" : "$.things[?(@.name =~ /[0-9]+/i)]"
        }
    ]
  },
  "response": {
    "status": 200,
    "body": "{\"responseName\": \"
   {{request.body.things.name.value}}\"}",
    "headers": {
        "Content-Type": "application/json"
    },
    "transformers": ["body-transformer"]
  }
 }

So my question is, even if i use a regEx, which matches with any number that comes in the request, how to give back the same number in the response using Wiremock standalone json file?
Thanks.


问:
Directly convert splat to set
I'm using the below code to generate a set from a range:

```<code>my_set = *(1..10).to_set
 # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</code>```

As you can see, instead of getting a set, I get an array.

The statement works if I split it into two lines:

```<code>my_set = *(1..10)
my_set = my_set.to_set
 # => #<Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}>
</code>```

How can I get it to work as expected in one line?

答:
Set.new works as well with ranges:

```<code>Set.new(1..10)
 => #<Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}>
</code>```

Just for fun, if you want to use splat operator (*):

```<code>my_set = (_ = *(1..10)).to_set
=> #<Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}>
</code>```

Note, that you should use assignment if you want to splat range.

Title: Directly convert splat to set

Body:
I'm using the below code to generate a set from a range:

my_set = *(1..10).to_set
 # => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

As you can see, instead of getting a set, I get an array.

The statement works if I split it into two lines:

my_set = *(1..10)
my_set = my_set.to_set
 # => #<Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}>

How can I get it to work as expected in one line?

Body:
Set.new works as well with ranges:

Set.new(1..10)
 => #<Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}>

Just for fun, if you want to use splat operator (*):

my_set = (_ = *(1..10)).to_set
=> #<Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}>

Note, that you should use assignment if you want to splat range.


问:
AJAX: Submitting a form without refreshing the page
I have a form similar to the following:

```<code><form method="post" action="mail.php" id="myForm">
   <input type="text" name="fname">
   <input type="text" name="lname">
   <input type="text" name="email">
    <input type="submit">
</form>
</code>```

I am new to AJAX and what I am trying to accomplish is when the user clicks the submit button, I would like for the mail.php script to run behind the scenes without refreshing the page.

I tried something like the code below, however, it still seems to submit the form as it did before and not like I need it to (behind the scenes):

```<code>$.post('mail.php', $('#myForm').serialize());
</code>```

If possible, I would like to get help implementing this using AJAX,

Many thanks in advance

答:
You need to prevent default action if you are using input type as submit <input type="submit" name="submit" value="Submit">.

By putting $("form").submit(...) you're attaching the submit handler, this will submit form (this is default action).

If don't want this default action use preventDefault() method.

If you are using other than submit, no need to prevent default.

```<code> $("form").submit(function(e) {
    e.preventDefault();
    $.ajax({
      type: 'POST',
      url: 'save.asmx/saveData',
      dataType: 'json',
      contentType:"application/json;charset=utf-8",
      data: $('form').serialize(),
      async:false,
      success: function() {
        alert("success");
      }
      error: function(request,error) {
        console.log("error");
      }
</code>```

Body:
I have a form similar to the following:

<form method="post" action="mail.php" id="myForm">
   <input type="text" name="fname">
   <input type="text" name="lname">
   <input type="text" name="email">
    <input type="submit">
</form>

I am new to AJAX and what I am trying to accomplish is when the user clicks the submit button, I would like for the mail.php script to run behind the scenes without refreshing the page.

I tried something like the code below, however, it still seems to submit the form as it did before and not like I need it to (behind the scenes):

$.post('mail.php', $('#myForm').serialize());

If possible, I would like to get help implementing this using AJAX,

Many thanks in advance

Body:
You need to prevent default action if you are using input type as submit <input type="submit" name="submit" value="Submit">.

By putting $("form").submit(...) you're attaching the submit handler, this will submit form (this is default action).

If don't want this default action use preventDefault() method.

If you are using other than submit, no need to prevent default.

 $("form").submit(function(e) {
    e.preventDefault();
    $.ajax({
      type: 'POST',
      url: 'save.asmx/saveData',
      dataType: 'json',
      contentType:"application/json;charset=utf-8",
      data: $('form').serialize(),
      async:false,
      success: function() {
        alert("success");
      }
      error: function(request,error) {
        console.log("error");
      }


答:
You already had a set. Splatting it (*) gave you the array. Just don't splat:

```<code>my_set = (1..10).to_set # => #<Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}>
</code>```

Title: Directly convert splat to set

Body:
You already had a set. Splatting it (*) gave you the array. Just don't splat:

my_set = (1..10).to_set # => #<Set: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}>


问:
Android Signed APK showing as Unsigned APK when trying to upload to production
I signed my APK in Android Studio 2.3 (build->generate signed APK). When I'm trying to upload it to Google Play store it is showing the error that I've uploaded unsigned APK. Could anyone answer why it is happening and how to solve it?</p>

答:
Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files.

While generating signed apk there are two checkbox .

V1 (Jar Signature)

V2 (Full apk Signature)

There are three choices available to us:

select V1 (For older version of signing) - apk gets uploaded successfully

select V2 (For newer version of signing) - Please note that selecting this alone will not work.

select V1 and V2 (For older and newer version) - apk gets uploaded successfully

Why selecting V2 alone does not work ?

Because APK Signature Scheme v2 was introduced in Android 7.0 (Nougat). To make a APK installable on Android 6.0 (Marshmallow) and older devices, the APK should be signed using JAR signing before being signed with the v2 scheme.

For more information jump here


问:
Database design for a social networking site
What are the Tables that would be present in a social networking site (ex: Twitter).

I have a users table as of now. How to keep track of followers and people I do follow?

Should I maintain a separate table for followers and people I follow?

What are the columns which would be there in those tables?

Please don't think this as Subjective/Off topic. As I am a beginner, I thought experts can guide me to get a good DB design?

答: you can use this Messenger Database Design Concept: Messenger DB

ContentLicense: CC BY-SA 4.0


问:
Server returned HTTP response code: 415 Unsupported media type
I have a rest web service like below.

```<code>@POST
@Path("/startProcess")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String startProcess(InputParams inputParams, @Context HttpServletRequest request, @Context HttpServletResponse response) {
   ProjectBean projBean = new ProjectBean();
   Helper.loadProjectBean(inputParams, projBean);
   return "1";
}
</code>```

Now I am trying to consume it with below main program.

```<code>public static void main(String[] args) throws Exception {
    StringBuffer response = new StringBuffer();
    String taigaServiceUrl = "http://localhost:8181/restServer/rest/TestWebService/startProcess/";
    URL url = new URL(taigaServiceUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "application/json");
    String userpass = "admin" + ":" + "admin";
    String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
    conn.setRequestProperty("Authorization", basicAuth);
    InputParams inputParams = new InputParams();
    inputParams.setXXX("xxxx");
    inputParams.setYYYY("123456");
    inputParams.setZZZZ("ZZZZ");
    String json = new Gson().toJson(inputParams);
    DataOutputStream os = new DataOutputStream (conn.getOutputStream());
    os.write(json.getBytes());
    os.flush();
    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
    String inputLine;
    while ((inputLine = br.readLine()) != null) {
        response.append(inputLine);
    }
    br.close();
}
</code>```

But every time I am getting below error.

```<code>Exception in thread "main" java.io.IOException: Server returned HTTP response code: 415 for URL: http://localhost:8181/restServer/rest/TestWebService/startProcess/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at scm.controllers.Test.main(Test.java:64)
</code>```

As per error the media type is unsupported. In my rest webservice I am consuming JSON and in my main program I am sending JSON. Then where it is breaking?

答:
This is the issue with your @Produces and @Consumes.
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
As per the annotation, your endpoint receives JSON and result would be TEXT.

But in your client program, you have mentioned content type as json.
conn.setRequestProperty("Content-Type", "application/json");

Hence client expects a json, where as its not.

Change this as
conn.setRequestProperty("Content-Type", "text/plain");

would work.

Body:
I have a rest web service like below.

@POST
@Path("/startProcess")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String startProcess(InputParams inputParams, @Context HttpServletRequest request, @Context HttpServletResponse response) {
   ProjectBean projBean = new ProjectBean();
   Helper.loadProjectBean(inputParams, projBean);
   return "1";
}

Now I am trying to consume it with below main program.

public static void main(String[] args) throws Exception {
    StringBuffer response = new StringBuffer();
    String taigaServiceUrl = "http://localhost:8181/restServer/rest/TestWebService/startProcess/";
    URL url = new URL(taigaServiceUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "application/json");
    String userpass = "admin" + ":" + "admin";
    String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
    conn.setRequestProperty("Authorization", basicAuth);
    InputParams inputParams = new InputParams();
    inputParams.setXXX("xxxx");
    inputParams.setYYYY("123456");
    inputParams.setZZZZ("ZZZZ");
    String json = new Gson().toJson(inputParams);
    DataOutputStream os = new DataOutputStream (conn.getOutputStream());
    os.write(json.getBytes());
    os.flush();
    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
    String inputLine;
    while ((inputLine = br.readLine()) != null) {
        response.append(inputLine);
    }
    br.close();
}

But every time I am getting below error.

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 415 for URL: http://localhost:8181/restServer/rest/TestWebService/startProcess/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at scm.controllers.Test.main(Test.java:64)

As per error the media type is unsupported. In my rest webservice I am consuming JSON and in my main program I am sending JSON. Then where it is breaking?


问:
MongoDB: Updating arrays of sub documents after document deletion
I have an API in which I am deleting 'course' documents in the following way:

```<code>module.exports.deleteCourse = function(req, res){
  var courseid = req.params.courseid;
  if(courseid){
    Course.findByIdAndRemove(courseid, function(err, course){
      if(err){
        sendJSONResponse(res, 404, err);
        return;
      }
      sendJSONResponse(res, 204, null)
    });
  } else{
      sendJSONResponse(res, 404, {"message":"NoId"});
    }
  };
</code>```

This is successful in deleting the course from the database, as is shown when attempting to find it by id.

The issue is that in user documents:

```<code>    var instructorSchema = new mongoose.Schema({
   name: {type: String,
         unique: true,
         required: true},
   password: {type: String,
            required: true},
   courses: [course.schema]
});
</code>```

If the document was pushed to the courses array it remains after the deletion method.

So my question. Is there a relatively painless way to keep this document updated after deletes?

Thanks.

答:
Add a class method for course using statics, where you delete both the course and its dependencies.

Assuming you are storing ids in courses array:

```<code>var Instructor = require('./instructor');

courseSchema.statics = {
    removeOneWithDependencies : function(id, done){
        this.findByIdAndRemove(id, function(err, course){
            if(err){
                return done(err);
            }
            else{
                //Removes the course id from courses array of all instructor docs
                Instructor.update({courses: course._id}, { $pullAll: {courses: [course._id] } }, {multi: true}, function(err){ //http://stackoverflow.com/a/27917378/
                    if(err){
                        return done(err);
                    }
                    else{
                        return done();
                    }
                })
            }
        });
    }
}
</code>```

In case you are storing course documents in courses array you need to change the update query to:

```<code>Instructor.update({"courses._id": course._id}, { $pull: {courses:{_id: course._id} } }, {multi: true}, function(err){ //http://stackoverflow.com/a/15122017/
</code>```

Finally use the above method in your API:

```<code>module.exports.deleteCourse = function(req, res){
    var courseid = req.params.courseid;
    if(courseid){
        Course.removeOneWithDependencies(courseid, function(err){
            if(err){
                return sendJSONResponse(res, 500, err);
            }
            else{
                return sendJSONResponse(res, 204, null);
            }
        });
    } else{
        sendJSONResponse(res, 404, {"message":"NoId"});
    }
};
</code>```

Body:
I have an API in which I am deleting 'course' documents in the following way:

module.exports.deleteCourse = function(req, res){
  var courseid = req.params.courseid;
  if(courseid){
    Course.findByIdAndRemove(courseid, function(err, course){
      if(err){
        sendJSONResponse(res, 404, err);
        return;
      }
      sendJSONResponse(res, 204, null)
    });
  } else{
      sendJSONResponse(res, 404, {"message":"NoId"});
    }
  };

This is successful in deleting the course from the database, as is shown when attempting to find it by id.

The issue is that in user documents:

    var instructorSchema = new mongoose.Schema({
   name: {type: String,
         unique: true,
         required: true},
   password: {type: String,
            required: true},
   courses: [course.schema]
});

If the document was pushed to the courses array it remains after the deletion method.

So my question. Is there a relatively painless way to keep this document updated after deletes?

Thanks.

Body:
Add a class method for course using statics, where you delete both the course and its dependencies.

Assuming you are storing ids in courses array:

var Instructor = require('./instructor');

courseSchema.statics = {
    removeOneWithDependencies : function(id, done){
        this.findByIdAndRemove(id, function(err, course){
            if(err){
                return done(err);
            }
            else{
                //Removes the course id from courses array of all instructor docs
                Instructor.update({courses: course._id}, { $pullAll: {courses: [course._id] } }, {multi: true}, function(err){ //http://stackoverflow.com/a/27917378/
                    if(err){
                        return done(err);
                    }
                    else{
                        return done();
                    }
                })
            }
        });
    }
}

In case you are storing course documents in courses array you need to change the update query to:

Instructor.update({"courses._id": course._id}, { $pull: {courses:{_id: course._id} } }, {multi: true}, function(err){ //http://stackoverflow.com/a/15122017/

Finally use the above method in your API:

module.exports.deleteCourse = function(req, res){
    var courseid = req.params.courseid;
    if(courseid){
        Course.removeOneWithDependencies(courseid, function(err){
            if(err){
                return sendJSONResponse(res, 500, err);
            }
            else{
                return sendJSONResponse(res, 204, null);
            }
        });
    } else{
        sendJSONResponse(res, 404, {"message":"NoId"});
    }
};


问:
Unable to install caffe
I am new to caffe. I am trying to install it in Ubuntu 14.04 which is running as a dual boot on my macbook pro. I managed to get it running initially but soon after my laptop crashed, following which I have the same error "No module named caffe" I have followed the instructions to the letter and it seems to be an issue with opencv. I get an error message while compiling caffe which I have copied below.

/usr/bin/ld: cannot find -lopencv_imgcodecs collect2: error: ld

  returned 1 exit status make: ***

  [.build_release/lib/libcaffe.so.1.0.0-rc3] Error 1

This leads me to believe there is something wrong with my OpenCV installation? Would really appreciate some help!

答:
Check the installation guide

When compiling with OpenCV 3.0 or errors show imread,imencode,imdecode or VideoCapture open your Makefile with some text editor, add opencv_imgcodecs behind.

LIBRARIES += glog gflags protobuf leveldb snappy \
  lmdb boost_system boost_filesystem hdf5_hl hdf5 m \
  opencv_core opencv_highgui opencv_imgproc opencv_imgcodecs opencv_videoio

(See the discussion at: https://github.com/BVLC/caffe/issues/1276)

Title: Unable to install caffe


问:
Java - Flatten nested map using Stream
I have been messing around with Java 8 Stream API and ran into something I could only do through traditional for-loops.

Given a nested map of

```<code>{
    1999: {
             3: [23, 24, 25],
             4: [1, 2, 3]
          },
    2001: {
             11: [12, 13, 14],
             12: [25, 26, 27]

          }
}
</code>```

How can I transform this into

```<code>['23,3,1999', '24,3,1999', '25,3,1999', '1,4,1999', '2,4,1999', '3,4,1999', '12,11,2001', '13,11,2001', '14,11,2001', '25,12,2001', '26,12,2001', '27,12,2001']
</code>```

Basically I want to replicate:

```<code>    Map<Integer, Map<Integer, List<Integer>>> dates...
    List<String> flattened = new ArrayList<>();
    for (Integer key1 : map.keySet()) {
        for (Integer key2 : map.get(key1).keySet()) {
            for (Integer value : map.get(key1).get(key2)) {
                flattened.add(value + "," + key2 + "," + key1);
            }
        }
    }
</code>```

答:
Assuming there is a Holder that can take 3 integers for example:

```<code> static class Holder {

      private final int first;
      private final int second;
      private final int third;
 }
</code>```

And these are some nested maps, then 2 flatMap will achieve what you want:

```<code> List<Holder> holders = map.entrySet().stream().flatMap(
            e -> e.getValue()
                    .entrySet()
                    .stream()
                    .flatMap(x -> x.getValue().stream().map(y -> new Holder(e.getKey(), x.getKey(), y))))
            .collect(Collectors.toList());

    System.out.println(holders);
</code>```

Title: Java - Flatten nested map using Stream

Body:
I have been messing around with Java 8 Stream API and ran into something I could only do through traditional for-loops.

Given a nested map of

{
    1999: {
             3: [23, 24, 25],
             4: [1, 2, 3]
          },
    2001: {
             11: [12, 13, 14],
             12: [25, 26, 27]

          }
}

How can I transform this into

['23,3,1999', '24,3,1999', '25,3,1999', '1,4,1999', '2,4,1999', '3,4,1999', '12,11,2001', '13,11,2001', '14,11,2001', '25,12,2001', '26,12,2001', '27,12,2001']

Basically I want to replicate:

    Map<Integer, Map<Integer, List<Integer>>> dates...
    List<String> flattened = new ArrayList<>();
    for (Integer key1 : map.keySet()) {
        for (Integer key2 : map.get(key1).keySet()) {
            for (Integer value : map.get(key1).get(key2)) {
                flattened.add(value + "," + key2 + "," + key1);
            }
        }
    }

Body:
Assuming there is a Holder that can take 3 integers for example:

 static class Holder {

      private final int first;
      private final int second;
      private final int third;
 }

And these are some nested maps, then 2 flatMap will achieve what you want:

 List<Holder> holders = map.entrySet().stream().flatMap(
            e -> e.getValue()
                    .entrySet()
                    .stream()
                    .flatMap(x -> x.getValue().stream().map(y -> new Holder(e.getKey(), x.getKey(), y))))
            .collect(Collectors.toList());

    System.out.println(holders);


问:
How to convert minutes to Hours and Minutes (hh:mm) in Java?
I need to convert minutes to hours and minutes in Java. For example 260 minutes should be 4:20.

Can anyone help me how to do such conversion?

答:
```<code>int mHours = t / 60; //since both are ints, you get an int
int mMinutes = t % 60;
System.out.printf("%d:%02d", "" +mHours, "" +mMinutes);
</code>```


问:
Issue of propertyChanged update for all subproperty in a class in winform
I implemented a model class and want to raise PropertyChanged events for all subproperty when the object is modified. But I found it 's not working. When I push the button, the label's text is't changed.Does i miss something?I got this from MSDN -"The PropertyChanged event can indicate all properties on the object have changed by using either null or String.Empty as the property name in the PropertyChangedEventArgs."
the platform is .net framework 4.0 and VS2015

```<code>   public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Model = new Model()
        {
            data = new User()
            {
                Name = "test"
            }
        };
        label1.DataBindings.Add("Text", Model.data, "Name", false, DataSourceUpdateMode.OnPropertyChanged);
    }
    private Model model;
    public Model Model
    {
        get
        {
            return this.model;
        }
        set
        {
            model = value;
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        User temp = new User()
        {
            Name = "test1"
        };
        Model.data = temp;
    }
}

public class NotifyPropertyChanged : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    protected bool SetField<T>(ref T field, T value, string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        OnPropertyChanged(null);
        return true;
    }
}
public class Model : NotifyPropertyChanged
{
    private User m_data;
    public User data
    {
        get { return m_data; }
        set
        {
            SetField(ref m_data, value,"data");
        }
    }
}
public class User : NotifyPropertyChanged
{
    private string name;
    public string Name
    {
        get { return this.name; }
        set
        {
            SetField(ref name, value, "Name");
        }
    }
    private string tel;
    public string Tel
    {
        get { return this.tel; }
        set
        {
            SetField(ref tel, value, "Tel");
        }
    }
}
</code>```

答:
Your problem is that your binding on Model.data, but later on, assign it a new value.

So the instance that is being monitored by the binding, is no more being used.

You've 2 options:

First one: don't create new User, just change it's Name:

```<code>private void button1_Click(object sender, EventArgs e)
{
    Model.data.Name = "test1";
}
</code>```

Or, if you really need to support both case (creation and assigment), then you have to change the binding to the Model and take the text from data.Name:

```<code>label1.DataBindings.Add("Text", Model, "data.Name", false,
                        DataSourceUpdateMode.OnPropertyChanged);
</code>```

And the set part of the User Property in the Model to this:

```<code>set
{
    SetField(ref m_data, value, "data");
    this.data.PropertyChanged += (sender, args) => this.OnPropertyChanged("data");
}
</code>```

So, this will create a PropertyChanged on the data, if data.Name has been changed, well if the data property itself has been set

Body:
I implemented a model class and want to raise PropertyChanged events for all subproperty when the object is modified. But I found it 's not working. When I push the button, the label's text is't changed.Does i miss something?I got this from MSDN -"The PropertyChanged event can indicate all properties on the object have changed by using either null or String.Empty as the property name in the PropertyChangedEventArgs."
the platform is .net framework 4.0 and VS2015

   public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Model = new Model()
        {
            data = new User()
            {
                Name = "test"
            }
        };
        label1.DataBindings.Add("Text", Model.data, "Name", false, DataSourceUpdateMode.OnPropertyChanged);
    }
    private Model model;
    public Model Model
    {
        get
        {
            return this.model;
        }
        set
        {
            model = value;
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        User temp = new User()
        {
            Name = "test1"
        };
        Model.data = temp;
    }
}

public class NotifyPropertyChanged : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    protected bool SetField<T>(ref T field, T value, string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(field, value)) return false;
        field = value;
        OnPropertyChanged(propertyName);
        OnPropertyChanged(null);
        return true;
    }
}
public class Model : NotifyPropertyChanged
{
    private User m_data;
    public User data
    {
        get { return m_data; }
        set
        {
            SetField(ref m_data, value,"data");
        }
    }
}
public class User : NotifyPropertyChanged
{
    private string name;
    public string Name
    {
        get { return this.name; }
        set
        {
            SetField(ref name, value, "Name");
        }
    }
    private string tel;
    public string Tel
    {
        get { return this.tel; }
        set
        {
            SetField(ref tel, value, "Tel");
        }
    }
}

Body:
Your problem is that your binding on Model.data, but later on, assign it a new value.

So the instance that is being monitored by the binding, is no more being used.

You've 2 options:

First one: don't create new User, just change it's Name:

private void button1_Click(object sender, EventArgs e)
{
    Model.data.Name = "test1";
}

Or, if you really need to support both case (creation and assigment), then you have to change the binding to the Model and take the text from data.Name:

label1.DataBindings.Add("Text", Model, "data.Name", false,
                        DataSourceUpdateMode.OnPropertyChanged);

And the set part of the User Property in the Model to this:

set
{
    SetField(ref m_data, value, "data");
    this.data.PropertyChanged += (sender, args) => this.OnPropertyChanged("data");
}

So, this will create a PropertyChanged on the data, if data.Name has been changed, well if the data property itself has been set


问:
boost::shared_array<char> to std::string
What is the best way to convert a boost::shared_array<char> to a std::string?
The following snippet works but it does not look very elegant.

```<code>boost::shared_array<char> boostString = DatabaseFileName.GetCString(CZString::eAscii);
std::string stdString;
for(size_t i = 0; boostString[i] != 0; i++)
{
    stdString.append(1, boostString[i]);
}
</code>```

答:
Checkout following code. This will give you clear idea:</p>

```<code>#include <iostream>
#include <string>
#include <boost\shared_array.hpp>

void main()
{
    char *ptr = "mystring" ;
    boost::shared_array<char> myIntArray(new char[strlen(ptr) + 1]);
    strncpy(myIntArray.get(), ptr, strlen(ptr) + 1);
    std::string str(myIntArray.get());
    std::cout << str << std::endl;

    system("pause");
}
</code>```

Body:
What is the best way to convert a boost::shared_array<char> to a std::string?
The following snippet works but it does not look very elegant.

boost::shared_array<char> boostString = DatabaseFileName.GetCString(CZString::eAscii);
std::string stdString;
for(size_t i = 0; boostString[i] != 0; i++)
{
    stdString.append(1, boostString[i]);
}

Body:
Checkout following code. This will give you clear idea:

#include <iostream>
#include <string>
#include <boost\shared_array.hpp>

void main()
{
    char *ptr = "mystring" ;
    boost::shared_array<char> myIntArray(new char[strlen(ptr) + 1]);
    strncpy(myIntArray.get(), ptr, strlen(ptr) + 1);
    std::string str(myIntArray.get());
    std::cout << str << std::endl;

    system("pause");
}