问:
IQueryable - Why does this logic fail?
I have a data base with several tables, the pertinent ones in this case are

VolunteerSignups and ProgramEvents:

```<code>CREATE TABLE [dbo].[VolunteerSignups] (
    [EventId]      INT            IDENTITY (1, 1) NOT NULL,
    [VolunteerNum] INT            NOT NULL,
    [UserId]       NVARCHAR (128) NULL,
    CONSTRAINT [PK_dbo.VolunteerSignups] PRIMARY KEY CLUSTERED ([EventId] ASC, [VolunteerNum] ASC),
    CONSTRAINT [FK_VolunteerSignups_ProgramEvents_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[AspNetUsers] ([Id]) ON DELETE SET NULL ON UPDATE CASCADE,
    CONSTRAINT [FK_VolunteerSignups_ProgramEvents_EventId] FOREIGN KEY ([EventId]) REFERENCES [dbo].[ProgramEvents] ([EventId])
);
--Triggers and other unneeded info

CREATE TABLE [dbo].[ProgramEvents] (
    [EventId]            INT            IDENTITY (1, 1) NOT NULL,
    [EventTitle]         NVARCHAR (256) NOT NULL,
    [NumVolunteers]      INT            NOT NULL,
    [EventLocation]      NVARCHAR (512) NOT NULL,
    [ServiceDescription] NVARCHAR (MAX) NOT NULL,
    [StartTime]          DATETIME       NOT NULL,
    [EndTime]            DATETIME       NOT NULL,
    CONSTRAINT [PK_dbo.ProgramEvents] PRIMARY KEY CLUSTERED ([EventId] ASC)
);
--Triggers and other unneeded info
</code>```

What I have, overall, is a simple web app that allows events to be made (each event may have anywhere from 1 to N volunteers needed), and volunteers to sign up for said events.  The restriction is, of course, that the volunteers cannot sign up for the same event twice and that they cannot sign up for overlapping ( time-wise) slots.

I have quite literally everything else in the MVC app done except the second half of the volunteer slot requirement. I struggled with it some, got annoyed, so I left it for last instead of letting it delay the project overall.  But now I can't put it off anymore, because everything else works but this one query....

What I have so far is:

```<code>[Authorize( Roles = "Administrator, Volunteer" )]
public class VolunteerSignupsController : Controller
{
    private EntitiesDb db = new EntitiesDb();

    // GET: VolunteerSignups
    public async Task<ActionResult> Index()
    {
        var uid = User.Identity.GetUserId();
        var exclude = ( db.VolunteerSignups.Where( o => o.UserId == uid ) );

        var volunteerSignups = db.VolunteerSignups.Include( v => v.AspNetUser ).Include( v => v.ProgramEvent );
        var diff = volunteerSignups.Where( u => ( !exclude.Any( p => p.EventId == u.EventId ) ) && u.UserId == null );

        return View( await diff.ToListAsync() );
    }
</code>```

This code work perfectly at retrieving the events that the user has not signed up for already.  The problem is that it returns overlapping events after they have signed up for an event.  So I modified the code to the following:

```<code>[Authorize( Roles = "Administrator, Volunteer" )]
public class VolunteerSignupsController : Controller
{
    private EntitiesDb db = new EntitiesDb();

    // GET: VolunteerSignups
    public async Task<ActionResult> Index()
    {
        ApplicationDbContext db1 = new ApplicationDbContext();

        var uid = User.Identity.GetUserId();
        var exclude = ( db.VolunteerSignups.Where( o => o.UserId == uid ) );

        var volunteerSignups = db.VolunteerSignups.Include( v => v.AspNetUser ).Include( v => v.ProgramEvent );
        var diff = volunteerSignups.Where( u => ( !exclude.Any( p => p.EventId == u.EventId ) ) && u.UserId == null );

        //GET: ProgramEvents that user has already signed up for
        var alreadyVolunteeredFor = db.ProgramEvents.Where( i => exclude.Any( u => i.EventId == u.EventId ) );

        //GET: ProgramEvents that the user has not signed up for
        var qualifiesFor = db.ProgramEvents.Where( i => diff.Any( u => i.EventId == u.EventId ) );

        /*Get: VolunteerSignups where the ProgramEvent is one where:
               -The user has not previously volunteered
               -The user has not previously volunteered for a different event where the time overlaps with an event they have not signed up for*/
        var intersect = db.VolunteerSignups.Where( i => ( diff.Any( d => ( d.EventId == i.EventId ) &&
            !qualifiesFor.Any( q => q.EventId == i.EventId &&
             alreadyVolunteeredFor.Any( a => a.EventId == i.EventId &&
               a.EndTime.CompareTo( q.StartTime ) >= 0  &&
               a.StartTime.CompareTo( q.EndTime ) <= 0  ) ) ) ) );

        return View( await intersect.ToListAsync() );
    }
</code>```

I am pretty sure the logic failure lies in the lambda expressions that make up intersect.  As it is written, it just returns the exact same things that diff did prior. Any changes I make to it, though, seem to remove everything from that list.

EDIT to respond to mjwillis comment:

The data in diff will be VolunteerSignups rows that are not filled for an event that the user has not volunteered for.  The columns are

 1.xyz 1 null

2.xyz 2 null

3.abc 1 null

qualifiesFor should correspond to ProgramEvents rows that have the same EventId as the entries in diff:

 1.xyz "First Title" 2 "Some Location" "A Description" "11/1/2020 4:00pm" "11/1/2020 7:00pm"

 2. abc "Second Title" 1 "A Location" "Some Description" "11/1/2020 5:00pm" "11/1/2020 6:00pm"

alreadyVonteeredFor should correspond to ProgramEvents rows person has volunteered for, none of the EventId columns should equal eachother, nor should they be if either diff or qualifiesFor:

dsd "Already Volunteered" 1 "Some Place" "Time overlaps" "11/1/2020 3:00pm" "11/1/2020 4:30pm"

What I need is for intersect to contain diff row 3 only, because rows 1 and 2 correspond to an event who's time overlaps with an event that the volunteer is already attached to.

答:
I have found the solution.  The issue was with the a => a.EventId == i.EventId && in the intersect lambda.  That is nonsense, and I don't know why it would be in there.  Nothing in alreadyVolunteeredFor would be in qualifiesFor and none of the EventId column would be in it either.

The correct answer ended up being to change the declaration of intersect to:

```<code>var intersect = db.VolunteerSignups.Where( i => ( diff.Any( d => ( d.EventId == i.EventId ) &&
            qualifiesFor.Any( q => q.EventId == i.EventId &&
             !alreadyVolunteeredFor.Any( a =>
               (a.EndTime.CompareTo( q.StartTime ) >= 0)  &&
               (a.StartTime.CompareTo( q.EndTime ) <= 0 ) ) ) ) ) );
</code>```

Title: IQueryable - Why does this logic fail?

Body:
I have a data base with several tables, the pertinent ones in this case are

VolunteerSignups and ProgramEvents:

CREATE TABLE [dbo].[VolunteerSignups] (
    [EventId]      INT            IDENTITY (1, 1) NOT NULL,
    [VolunteerNum] INT            NOT NULL,
    [UserId]       NVARCHAR (128) NULL,
    CONSTRAINT [PK_dbo.VolunteerSignups] PRIMARY KEY CLUSTERED ([EventId] ASC, [VolunteerNum] ASC),
    CONSTRAINT [FK_VolunteerSignups_ProgramEvents_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[AspNetUsers] ([Id]) ON DELETE SET NULL ON UPDATE CASCADE,
    CONSTRAINT [FK_VolunteerSignups_ProgramEvents_EventId] FOREIGN KEY ([EventId]) REFERENCES [dbo].[ProgramEvents] ([EventId])
);
--Triggers and other unneeded info

CREATE TABLE [dbo].[ProgramEvents] (
    [EventId]            INT            IDENTITY (1, 1) NOT NULL,
    [EventTitle]         NVARCHAR (256) NOT NULL,
    [NumVolunteers]      INT            NOT NULL,
    [EventLocation]      NVARCHAR (512) NOT NULL,
    [ServiceDescription] NVARCHAR (MAX) NOT NULL,
    [StartTime]          DATETIME       NOT NULL,
    [EndTime]            DATETIME       NOT NULL,
    CONSTRAINT [PK_dbo.ProgramEvents] PRIMARY KEY CLUSTERED ([EventId] ASC)
);
--Triggers and other unneeded info

What I have, overall, is a simple web app that allows events to be made (each event may have anywhere from 1 to N volunteers needed), and volunteers to sign up for said events.  The restriction is, of course, that the volunteers cannot sign up for the same event twice and that they cannot sign up for overlapping ( time-wise) slots.

I have quite literally everything else in the MVC app done except the second half of the volunteer slot requirement. I struggled with it some, got annoyed, so I left it for last instead of letting it delay the project overall.  But now I can't put it off anymore, because everything else works but this one query....

What I have so far is:

[Authorize( Roles = "Administrator, Volunteer" )]
public class VolunteerSignupsController : Controller
{
    private EntitiesDb db = new EntitiesDb();

    // GET: VolunteerSignups
    public async Task<ActionResult> Index()
    {
        var uid = User.Identity.GetUserId();
        var exclude = ( db.VolunteerSignups.Where( o => o.UserId == uid ) );

        var volunteerSignups = db.VolunteerSignups.Include( v => v.AspNetUser ).Include( v => v.ProgramEvent );
        var diff = volunteerSignups.Where( u => ( !exclude.Any( p => p.EventId == u.EventId ) ) && u.UserId == null );

        return View( await diff.ToListAsync() );
    }

This code work perfectly at retrieving the events that the user has not signed up for already.  The problem is that it returns overlapping events after they have signed up for an event.  So I modified the code to the following:

[Authorize( Roles = "Administrator, Volunteer" )]
public class VolunteerSignupsController : Controller
{
    private EntitiesDb db = new EntitiesDb();

    // GET: VolunteerSignups
    public async Task<ActionResult> Index()
    {
        ApplicationDbContext db1 = new ApplicationDbContext();

        var uid = User.Identity.GetUserId();
        var exclude = ( db.VolunteerSignups.Where( o => o.UserId == uid ) );

        var volunteerSignups = db.VolunteerSignups.Include( v => v.AspNetUser ).Include( v => v.ProgramEvent );
        var diff = volunteerSignups.Where( u => ( !exclude.Any( p => p.EventId == u.EventId ) ) && u.UserId == null );

        //GET: ProgramEvents that user has already signed up for
        var alreadyVolunteeredFor = db.ProgramEvents.Where( i => exclude.Any( u => i.EventId == u.EventId ) );

        //GET: ProgramEvents that the user has not signed up for
        var qualifiesFor = db.ProgramEvents.Where( i => diff.Any( u => i.EventId == u.EventId ) );

        /*Get: VolunteerSignups where the ProgramEvent is one where:
               -The user has not previously volunteered
               -The user has not previously volunteered for a different event where the time overlaps with an event they have not signed up for*/
        var intersect = db.VolunteerSignups.Where( i => ( diff.Any( d => ( d.EventId == i.EventId ) &&
            !qualifiesFor.Any( q => q.EventId == i.EventId &&
             alreadyVolunteeredFor.Any( a => a.EventId == i.EventId &&
               a.EndTime.CompareTo( q.StartTime ) >= 0  &&
               a.StartTime.CompareTo( q.EndTime ) <= 0  ) ) ) ) );

        return View( await intersect.ToListAsync() );
    }

I am pretty sure the logic failure lies in the lambda expressions that make up intersect.  As it is written, it just returns the exact same things that diff did prior. Any changes I make to it, though, seem to remove everything from that list.

EDIT to respond to mjwillis comment:

The data in diff will be VolunteerSignups rows that are not filled for an event that the user has not volunteered for.  The columns are

 1.xyz 1 null

2.xyz 2 null

3.abc 1 null

qualifiesFor should correspond to ProgramEvents rows that have the same EventId as the entries in diff:

 1.xyz "First Title" 2 "Some Location" "A Description" "11/1/2020 4:00pm" "11/1/2020 7:00pm"

 2. abc "Second Title" 1 "A Location" "Some Description" "11/1/2020 5:00pm" "11/1/2020 6:00pm"

alreadyVonteeredFor should correspond to ProgramEvents rows person has volunteered for, none of the EventId columns should equal eachother, nor should they be if either diff or qualifiesFor:

dsd "Already Volunteered" 1 "Some Place" "Time overlaps" "11/1/2020 3:00pm" "11/1/2020 4:30pm"

What I need is for intersect to contain diff row 3 only, because rows 1 and 2 correspond to an event who's time overlaps with an event that the volunteer is already attached to.

Body:
I have found the solution.  The issue was with the a => a.EventId == i.EventId && in the intersect lambda.  That is nonsense, and I don't know why it would be in there.  Nothing in alreadyVolunteeredFor would be in qualifiesFor and none of the EventId column would be in it either.

The correct answer ended up being to change the declaration of intersect to:

var intersect = db.VolunteerSignups.Where( i => ( diff.Any( d => ( d.EventId == i.EventId ) &&
            qualifiesFor.Any( q => q.EventId == i.EventId &&
             !alreadyVolunteeredFor.Any( a =>
               (a.EndTime.CompareTo( q.StartTime ) >= 0)  &&
               (a.StartTime.CompareTo( q.EndTime ) <= 0 ) ) ) ) ) );


来源: stackexchange

问:
SSRS Cache Schedule Re
I have about ~50 reports that are scheduled to be "cached" on a recurring schedule (image below).

Is this information only available in Report Server Database or can the schedule information be retrieved using Powershell? All of the "obvious" methods I've run thus far (with powershell ise) either return no information or boolean values (all 'false')

答:
You can use GetItemHistoryOptions to get the schedule for the report item.

Then based on the type of Item property of the ScheduleDefinitionOrReference [ref] parameter of the method, you can decide how to show the information.

Type of the Item, can be one of MinuteRecurrence, DailyRecurrence, WeeklyRecurrence, MonthlyRecurrence or MonthlyDOWRecurrence.

Example

For example to format MonthlyRecurrence you can use such code:

```<code>$svcUrl = 'http://the-host-name/ReportServer/reportservice2010.asmx'
$svc = New-WebServiceProxy -Class 'RS' -Namespace 'RS' -Uri $svcUrl -UseDefaultCredential
$reports = $svc.ListChildren("/", $true) | Where-Object { $_.TypeName -eq "Report" }

$KeepExecutionSnapshots = $false
$ScheduleDefinitionOrReference = New-Object RS.ScheduleDefinitionOrReference

foreach ($report in $reports) {
    $result = $svc.GetItemHistoryOptions($report.Path,
        [ref]$KeepExecutionSnapshots,
        [ref]$ScheduleDefinitionOrReference)
    if($ScheduleDefinitionOrReference.Item -is [RS.MonthlyRecurrence])
    {
        "'$($report.Name)' Schedule Information:"
        "StartDateTime: $($ScheduleDefinitionOrReference.StartDateTime)"
        "StartDateTime: $($ScheduleDefinitionOrReference.EndDate)"
        "EndDateSpecified: $($ScheduleDefinitionOrReference.EndDateSpecified)"
        "Days: $($ScheduleDefinitionOrReference.Item.Days)"
        $months = Get-Member `
            -InputObject $($ScheduleDefinitionOrReference.Item.MonthsOfYear) `
            -MemberType Property | Where-Object {
            $ScheduleDefinitionOrReference.Item.MonthsOfYear.$($_.Name) -eq $true
        }
        "Months:$($months.Name -join ",")"
    }
}
</code>```

And the result will be something like this:

```<code>'MyReport' Schedule Information:
StartDateTime: 12/19/2017 18:00:00
StartDateTime: 01/01/0001 00:00:00
EndDateSpecified: False
Days: 1,3-5
Months:August,December,July,November,October,September
</code>```

ContentLicense: CC BY-SA 3.0

Title: SSRS Cache Schedule Re

Body:
You can use GetItemHistoryOptions to get the schedule for the report item.

Then based on the type of Item property of the ScheduleDefinitionOrReference [ref] parameter of the method, you can decide how to show the information.

Type of the Item, can be one of MinuteRecurrence, DailyRecurrence, WeeklyRecurrence, MonthlyRecurrence or MonthlyDOWRecurrence.

Example

For example to format MonthlyRecurrence you can use such code:

$svcUrl = 'http://the-host-name/ReportServer/reportservice2010.asmx'
$svc = New-WebServiceProxy -Class 'RS' -Namespace 'RS' -Uri $svcUrl -UseDefaultCredential
$reports = $svc.ListChildren("/", $true) | Where-Object { $_.TypeName -eq "Report" }

$KeepExecutionSnapshots = $false
$ScheduleDefinitionOrReference = New-Object RS.ScheduleDefinitionOrReference

foreach ($report in $reports) {
    $result = $svc.GetItemHistoryOptions($report.Path,
        [ref]$KeepExecutionSnapshots,
        [ref]$ScheduleDefinitionOrReference)
    if($ScheduleDefinitionOrReference.Item -is [RS.MonthlyRecurrence])
    {
        "'$($report.Name)' Schedule Information:"
        "StartDateTime: $($ScheduleDefinitionOrReference.StartDateTime)"
        "StartDateTime: $($ScheduleDefinitionOrReference.EndDate)"
        "EndDateSpecified: $($ScheduleDefinitionOrReference.EndDateSpecified)"
        "Days: $($ScheduleDefinitionOrReference.Item.Days)"
        $months = Get-Member `
            -InputObject $($ScheduleDefinitionOrReference.Item.MonthsOfYear) `
            -MemberType Property | Where-Object {
            $ScheduleDefinitionOrReference.Item.MonthsOfYear.$($_.Name) -eq $true
        }
        "Months:$($months.Name -join ",")"
    }
}

And the result will be something like this:

'MyReport' Schedule Information:
StartDateTime: 12/19/2017 18:00:00
StartDateTime: 01/01/0001 00:00:00
EndDateSpecified: False
Days: 1,3-5
Months:August,December,July,November,October,September


问:
What does "@@YAHXZ" mean in VS link error description?
i would like to understand the @@YAHXZ  part of such an error:

Error LNK2019 unresolved external symbol "int __cdecl func2(void)"
  (?func2@@YAHXZ) referenced in function _main  .

this is just one example but i've seen other types of strange letters i just dont remember them right now. where can i find an explanation on each of them?

答:
This is called «name mangling», or «name decoration».

As C++ supports function overloading, the name of the symbols are generated in a specific way, usually based on the argument's types.

Here's the official documentation on Microsoft website:

https://msdn.microsoft.com/en-us/library/56h2zst2.aspx

EDIT

Microsoft doesn't provide a complete documentation about name decoration.

If you're interested in knowing exactly what the symbols mean, I recommend reading Agner Fog's documentation on calling conventions:

http://www.agner.org/optimize/calling_conventions.pdf


问:
What is the common header format of Python files?
I came across the following header format for Python source files in a document about Python coding guidelines:

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

"""Foobar.py: Description of what foobar does."""

__author__      = "Barack Obama"
__copyright__   = "Copyright 2009, Planet Earth"
</code>```

Is this the standard format of headers in the Python world?
What other fields/information can I put in the header?
Python gurus share your guidelines for good Python source headers :-)

答:
The answers above are really complete, but if you want a quick and dirty header to copy'n paste, use this:

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Module documentation goes here
   and here
   and ...
"""
</code>```

Why this is a good one:

The first line is for *nix users. It will choose the Python interpreter in the user path, so will automatically choose the user preferred interpreter.

The second one is the file encoding. Nowadays every file must have a encoding associated. UTF-8 will work everywhere. Just legacy projects would use other encoding.

And a very simple documentation. It can fill multiple lines.

See also: https://www.python.org/dev/peps/pep-0263/

If you just write a class in each file, you don't even need the documentation (it would go inside the class doc).

Body:
I came across the following header format for Python source files in a document about Python coding guidelines:

#!/usr/bin/env python

"""Foobar.py: Description of what foobar does."""

__author__      = "Barack Obama"
__copyright__   = "Copyright 2009, Planet Earth"

Is this the standard format of headers in the Python world?
What other fields/information can I put in the header?
Python gurus share your guidelines for good Python source headers :-)

Body:
The answers above are really complete, but if you want a quick and dirty header to copy'n paste, use this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Module documentation goes here
   and here
   and ...
"""

Why this is a good one:

The first line is for *nix users. It will choose the Python interpreter in the user path, so will automatically choose the user preferred interpreter.

The second one is the file encoding. Nowadays every file must have a encoding associated. UTF-8 will work everywhere. Just legacy projects would use other encoding.

And a very simple documentation. It can fill multiple lines.

See also: https://www.python.org/dev/peps/pep-0263/

If you just write a class in each file, you don't even need the documentation (it would go inside the class doc).


问:
Log is not getting printed for Extent Test Manager reports
I am using extent test manager reports but while the reports are generated there are no step name column added in the reports that is generated

I have used the below method:

```<code>ExtentTestManager.getTest().log(LogStatus.PASS,"Click on the \"Add Alarm Group\" button.","'Add Alarm Group' should be clickable.");
</code>```

Issue is that the 2nd parameter in the .log is not getting printed that is the step name.

答:
If you are using the latest version 3 of Extent Reports you can actually use the Markups to achieve a better reporting, please find below the code</p>

```<code>String stepName = "Click on the \"Add Alarm Group\" button.";
String description = "'Add Alarm Group' should be clickable.";

String code = "Step Name: " + stepName + "\nDescription: " +
description;
Markup m = MarkupHelper.createCodeBlock(code);
t1.pass(m);
</code>```

Body:
I am using extent test manager reports but while the reports are generated there are no step name column added in the reports that is generated

I have used the below method:

ExtentTestManager.getTest().log(LogStatus.PASS,"Click on the \"Add Alarm Group\" button.","'Add Alarm Group' should be clickable.");

Issue is that the 2nd parameter in the .log is not getting printed that is the step name.

Body:
If you are using the latest version 3 of Extent Reports you can actually use the Markups to achieve a better reporting, please find below the code

String stepName = "Click on the \"Add Alarm Group\" button.";
String description = "'Add Alarm Group' should be clickable.";

String code = "Step Name: " + stepName + "\nDescription: " +
description;
Markup m = MarkupHelper.createCodeBlock(code);
t1.pass(m);


问:
Micro-services: Zuul & consul in Spring cloud application
I'm trying to create a Spring cloud microservice application using Zuul and Consul.

I have 2 components in my project:

api-gateway microservice using Zuul

Hello world microservice (a simple hello world Rest Webservice)

Here is the code of The api-gateway:

```<code> @SpringBootApplication
 @EnableZuulProxy
 @EnableDiscoveryClient
 public class ZuulApplication {

 public static void main(String[] args) {
    SpringApplication.run(ZuulApplication.class, args);
  }

 }
</code>```

The pom.xml

```<code><parent>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-parent</artifactId>
    <version>Brixton.M3</version>
</parent>

<properties>
    <java.version>1.8</java.version>
    <spring.cloud.consul.version>1.0.0.M4</spring.cloud.consul.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-commons</artifactId>
    </dependency>

    <dependency>
        <!-- Setup Spring Boot -->
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
        <!-- Setup Spring MVC & REST, use Embedded Tomcat -->
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
    </dependency>

    <dependency>
        <!-- Spring Cloud starter -->
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-zuul</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-consul-all</artifactId>
        <version>${spring.cloud.consul.version}</version>
    </dependency>

</dependencies>
</code>```

application.yml

```<code> zuul:
  routes:
    hello1:
     path: /hello1/**
     serviceId: microservice-example

logging:
  level:
   org.springframework: INFO
   com.netflix: DEBUG
</code>```

bootstrap.yml

```<code>spring:
  application:
    name: edge-server

 cloud:
   consul:
    config:
      enabled: true
      host: localhost
      port: 8500
</code>```

Here is the code of hello microservice:

```<code> @SpringBootApplication
 @EnableConfigServer
 @EnableDiscoveryClient
 @RestController
 public class Application {

 @RequestMapping(value="/hello1",method = RequestMethod.GET)
 public String hello() {
    System.out.print("hello1");
    return "Hello1";
 }
 public static void main(String[] args) {
    new SpringApplicationBuilder(Application.class).web(true).run(args);
 }
}
</code>```

bootstrap.yml:
   spring:
     application:
       name: microservice-example
     profiles:
       active: native

```<code> cloud:
  consul:
   config:
    enabled: true
    host: localhost
    port: 8500
</code>```

But, when I start the api-gateway I got the following exception:

```<code>   Caused by: org.springframework.beans.BeanInstantiationException: Failed     to instantiate [org.springframework.cloud.netflix.zuul.filters.RouteLocator]: Factory method 'routeLocator' threw exception; nested exception is java.lang.IllegalStateException: Unable to locate service in consul agent: edge-server
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
... 69 common frames omitted
 Caused by: java.lang.IllegalStateException: Unable to locate service in consul agent: edge-server
at org.springframework.cloud.consul.discovery.ConsulDiscoveryClient.getLocalServiceInstance(ConsulDiscoveryClient.java:66) ~[spring-cloud-consul-discovery-1.0.0.M4.jar:1.0.0.M4]
</code>```

答: This issue is fixed in Brixton.M3 (1.0.0.M5). As mentioned above this was an issue with spring-cloud-consul. The new version is working fine</p>

Body:
I'm trying to create a Spring cloud microservice application using Zuul and Consul.

I have 2 components in my project:

api-gateway microservice using Zuul

Hello world microservice (a simple hello world Rest Webservice)

Here is the code of The api-gateway:

 @SpringBootApplication
 @EnableZuulProxy
 @EnableDiscoveryClient
 public class ZuulApplication {

 public static void main(String[] args) {
    SpringApplication.run(ZuulApplication.class, args);
  }

 }

The pom.xml

<parent>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-parent</artifactId>
    <version>Brixton.M3</version>
</parent>

<properties>
    <java.version>1.8</java.version>
    <spring.cloud.consul.version>1.0.0.M4</spring.cloud.consul.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-commons</artifactId>
    </dependency>

    <dependency>

        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>

        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
    </dependency>

    <dependency>

        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-zuul</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-consul-all</artifactId>
        <version>${spring.cloud.consul.version}</version>
    </dependency>

</dependencies>

application.yml

 zuul:
  routes:
    hello1:
     path: /hello1/**
     serviceId: microservice-example

logging:
  level:
   org.springframework: INFO
   com.netflix: DEBUG

bootstrap.yml

spring:
  application:
    name: edge-server

 cloud:
   consul:
    config:
      enabled: true
      host: localhost
      port: 8500

Here is the code of hello microservice:

 @SpringBootApplication
 @EnableConfigServer
 @EnableDiscoveryClient
 @RestController
 public class Application {

 @RequestMapping(value="/hello1",method = RequestMethod.GET)
 public String hello() {
    System.out.print("hello1");
    return "Hello1";
 }
 public static void main(String[] args) {
    new SpringApplicationBuilder(Application.class).web(true).run(args);
 }
}

bootstrap.yml:
   spring:
     application:
       name: microservice-example
     profiles:
       active: native

 cloud:
  consul:
   config:
    enabled: true
    host: localhost
    port: 8500

But, when I start the api-gateway I got the following exception:

   Caused by: org.springframework.beans.BeanInstantiationException: Failed     to instantiate [org.springframework.cloud.netflix.zuul.filters.RouteLocator]: Factory method 'routeLocator' threw exception; nested exception is java.lang.IllegalStateException: Unable to locate service in consul agent: edge-server
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.2.3.RELEASE.jar:4.2.3.RELEASE]
... 69 common frames omitted
 Caused by: java.lang.IllegalStateException: Unable to locate service in consul agent: edge-server
at org.springframework.cloud.consul.discovery.ConsulDiscoveryClient.getLocalServiceInstance(ConsulDiscoveryClient.java:66) ~[spring-cloud-consul-discovery-1.0.0.M4.jar:1.0.0.M4]


问:
Bcrypt may be create same hash for inputs? - Symfony
Bcrypt may be create same hash for inputs?

Is that possible bcrypt create hash for 'abc' and 'egf' same password?

答:
For any hashing algorithm, or any algorithm with a finite output space and an infinite input space, there will be an infinite number of inputs that produce the same output.

Is this a problem? No, not really. The only thing we care about is that the same password produces the same hash and that it is very unlikely to ever get the same hash with any other password. It is very unlikely to find two input strings that produce the same bcrypt hash.


问:
How can I get the window position/size from a different program's window?
What I want to do is create a semi-transparent overlay over another program's window that displays stats on what is happening on the window in the background.  I know how to do everything that I want to do with this program except find the properties of window such as position, size, and title so I can position my transparent windows in front of the right window.  For example, if you don't know what I mean, if you play online poker and use Poker Tracker.  They have the transparent HUD that appears over each table.  I basically need to do the same type of thing.  I have searched many things and have not had any luck so far.  I will be using Qt4 or PyQt4 most likely for the GUI so if that toolkit provides the right functions to do this and I just haven't been able to find them yet, that would be great.  If I need to use another toolkit too, that doesn't matter.  If I need to use something other than the Qt tool kit I would still like to know.  However it can be done I would like to know.</p>

答:
In Windows you have to use the Windows API.
GetWindowRect can do it.
http://msdn.microsoft.com/en-us/library/ms633519%28v=vs.85%29.aspx

But first you have to get the another Window hwnd, with something like FindWindow

ContentLicense: CC BY-SA 2.5


问:
How do I swizzle main bundle with test bundle
I use to swizzle main bundle with test bundle like follow in obj c

```<code>#import "NSBundle+Bundle.h"
#import <objc/runtime.h>

@implementation NSBundle (Bundle)

+(void)loadSwizzler {
    static dispatch_once_t once_token;
    dispatch_once(&once_token,  ^{
        Method originalMethod = class_getClassMethod(self, @selector(mainBundle));
        Method extendedMethod = class_getClassMethod(self, @selector(bundleForTestTarget));
        //swizzling mainBundle method with our own custom method
        method_exchangeImplementations(originalMethod, extendedMethod);
    });
}

//method for returning app Test target
+(NSBundle *)bundleForTestTarget {
    NSBundle * bundle = [NSBundle bundleWithIdentifier:@"Philips.AppInfraTests"];

    return bundle;
}

@end
</code>```

But I tried the following for the same in swift

```<code>     extension Bundle {
  class func swizzle() {
        let originalSelector = #selector(mainBundle)
        let swizzledSelector = #selector(testBundle)
        let originalMethod = class_getInstanceMethod(self, originalSelector)
        let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
        method_exchangeImplementations(originalMethod, swizzledMethod)
    }

    func mainBundle() -> Bundle
    {
        return Bundle.main
    }
    func testBundle() -> Bundle
    {
        return Bundle(for: self.classNamed("swizzler")!)
    }
}
</code>```

But this is throwing some errors "Argument of '#selector' cannot refer to variable 'testBundle'"

could some one help me how do I do it

答:
This answer has been tested in Swift 3 & 4 Playground, any other version and YMMV.

Your Objective-C code swizzles two class methods, your Swift version attempts to swizzle two instance methods - so they are not doing the same thing.

You (probably) cannot swizzle a (pure) Swift function, you can swizzle Objective-C methods, this is due to the differences in how functions/methods are dispatched. So in Swift the replacement function must be marked @objc in Swift 4 (it is optional and apparently harmless in Swift 3).

Swift renames mainBundle to main and surfaces it as a property, so to get the selector for mainBundle you need to use getter: main.

Combine the above and you get the following Playground code:

```<code>extension Bundle
{
    class func swizzle()
    {
        let originalSelector = #selector(getter: main)
        let swizzledSelector = #selector(testBundle)
        let originalMethod = class_getClassMethod(self, originalSelector)!
        let swizzledMethod = class_getClassMethod(self, swizzledSelector)!
        method_exchangeImplementations(originalMethod, swizzledMethod)
    }

    @objc class func testBundle() -> Bundle
    {
        // just for testing in Playground
        return Bundle(path: "/Applications/TextEdit.app")!
    }
}

let b = Bundle.main
print(b)
Bundle.swizzle()
let c = Bundle.main
print(c)
</code>```

which prints:

```<code>NSBundle </Applications/Xcode.app> (not yet loaded)
NSBundle </Applications/TextEdit.app> (not yet loaded)
</code>```

Note that class_getClassMethod() returns a Method? and the above code forces this without any checks, those checks should exist in real code!

Finally note that your swizzle code assumes mainBundle is implemented directly by NSBundle and not one of its ancestors, that is probably a safe assumption in this case but is not always. See for example this question on doing swizzling safely.

HTH

Body:
I use to swizzle main bundle with test bundle like follow in obj c

#import "NSBundle+Bundle.h"
#import <objc/runtime.h>

@implementation NSBundle (Bundle)

+(void)loadSwizzler {
    static dispatch_once_t once_token;
    dispatch_once(&once_token,  ^{
        Method originalMethod = class_getClassMethod(self, @selector(mainBundle));
        Method extendedMethod = class_getClassMethod(self, @selector(bundleForTestTarget));
        //swizzling mainBundle method with our own custom method
        method_exchangeImplementations(originalMethod, extendedMethod);
    });
}

//method for returning app Test target
+(NSBundle *)bundleForTestTarget {
    NSBundle * bundle = [NSBundle bundleWithIdentifier:@"Philips.AppInfraTests"];

    return bundle;
}

@end

But I tried the following for the same in swift

     extension Bundle {
  class func swizzle() {
        let originalSelector = #selector(mainBundle)
        let swizzledSelector = #selector(testBundle)
        let originalMethod = class_getInstanceMethod(self, originalSelector)
        let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
        method_exchangeImplementations(originalMethod, swizzledMethod)
    }

    func mainBundle() -> Bundle
    {
        return Bundle.main
    }
    func testBundle() -> Bundle
    {
        return Bundle(for: self.classNamed("swizzler")!)
    }
}

But this is throwing some errors "Argument of '#selector' cannot refer to variable 'testBundle'"

could some one help me how do I do it

Body:
This answer has been tested in Swift 3 & 4 Playground, any other version and YMMV.

Your Objective-C code swizzles two class methods, your Swift version attempts to swizzle two instance methods - so they are not doing the same thing.

You (probably) cannot swizzle a (pure) Swift function, you can swizzle Objective-C methods, this is due to the differences in how functions/methods are dispatched. So in Swift the replacement function must be marked @objc in Swift 4 (it is optional and apparently harmless in Swift 3).

Swift renames mainBundle to main and surfaces it as a property, so to get the selector for mainBundle you need to use getter: main.

Combine the above and you get the following Playground code:

extension Bundle
{
    class func swizzle()
    {
        let originalSelector = #selector(getter: main)
        let swizzledSelector = #selector(testBundle)
        let originalMethod = class_getClassMethod(self, originalSelector)!
        let swizzledMethod = class_getClassMethod(self, swizzledSelector)!
        method_exchangeImplementations(originalMethod, swizzledMethod)
    }

    @objc class func testBundle() -> Bundle
    {
        // just for testing in Playground
        return Bundle(path: "/Applications/TextEdit.app")!
    }
}

let b = Bundle.main
print(b)
Bundle.swizzle()
let c = Bundle.main
print(c)

which prints:

NSBundle </Applications/Xcode.app> (not yet loaded)
NSBundle </Applications/TextEdit.app> (not yet loaded)

Note that class_getClassMethod() returns a Method? and the above code forces this without any checks, those checks should exist in real code!

Finally note that your swizzle code assumes mainBundle is implemented directly by NSBundle and not one of its ancestors, that is probably a safe assumption in this case but is not always. See for example this question on doing swizzling safely.

HTH


问:
Anybody seen the quick find dialogue box in VS2015 go very small?
For some reason the quick find box (CTRL-F) in VS2015 has gone absolutely tiny. It's almost unusable. Has anybody seen this?

I can extend it width wise, but absolutely can't change it's height to make the text in it more legible.

答:
In case anyone else has this problem, I finally figured out how to fix it on my VS2015 without resetting everything...

Place the cursor anywhere in the text editor.  Hold down CTRL key and use the scroll wheel on your mouse to enlarge the search box until it is the size you want.  This will make everything in your code editor huge.

Open Tools/Options/Environment/Fonts and Colors.  "Text Editor" should already be selected.

Change the font size to another other than was you see.  If it's 10 and you want it to be 10, change it to something other than 10, then go back in and change it back to 10.


问:
JSON Web Token validity verification passed on .NET Core but failed on .NET 4.6.1
I am trying to varify validity of JSON Web Token in both .NET Core and .NET 4.6.1 by using Microsoft.IdentityModel.Tokens library. I dug into source code and noticed that AsymmetricSignatureProvider differently handle signaure verification in method bool Verify(byte[] input, byte[] signature) for .NET Core and other versions, which is also place where my verification failed. You can find source code in this link.

In general I am first downloading JSON Web Key Sets, then I am building security keys and last I am building TokenValidationParameters and validating token.

My code starts here

Downloading JSON Web Key Sets:

```<code>string data = null;
using (WebClient client = new WebClient())
{
    data = client.DownloadString(URL_TO_JWKS);
}

var jwks = new JsonWebKeySet(data);
</code>```

Here I am building security keys from JSON Web Key Sets. Please notice how I decoding exponent and modulus, maybe is wrong in .NET 4.1.6:

```<code>    var keys = new List<SecurityKey>();
    foreach (var webKey in jwks.Keys)
    {
         var e = Base64UrlEncoder.DecodeBytes(webKey.E);
         var n = Base64UrlEncoder.DecodeBytes(webKey.N);
         var key = new RsaSecurityKey(new RSAParameters { Exponent = e, Modulus = n })
          {
             KeyId = webKey.Kid
          };

          keys.Add(key);
   }
</code>```

Here I am verifying token:

```<code>var token = new JwtSecurityToken(tokenString);
ClaimsPrincipal claimsPrincipal = null;

            var parameters = new TokenValidationParameters()
            {
                ValidAudiences = token.Audiences,
                IssuerSigningKeys = keys,
                NameClaimType = nameClaimType ?? JwtRegisteredClaimNames.Sub,
                ValidIssuers = new[] { token.Issuer }
            };

            bool isValid = false;

            try
            {
                string jwt = token.RawData;
                SecurityToken securityToken = null;
                claimsPrincipal = new JwtSecurityTokenHandler().ValidateToken(jwt, parameters, out securityToken);
                isValid = claimsPrincipal.Identity.IsAuthenticated;
            }
            catch (SecurityTokenExpiredException)
            {
            }
            catch (SecurityTokenInvalidSignatureException ex)
            {
            }
</code>```

What is correct way to verify validity for both .NET 4.6.1 and .NET Core?

答:
Thanks to lovemaths and brentschmaltz.

This behaviour happened because .net 4.6.1 doesn't remove leading 0x00. Pull request is already merged and it will be available in version 5.2.0.

For more details please visit issues on github.

Body:
I am trying to varify validity of JSON Web Token in both .NET Core and .NET 4.6.1 by using Microsoft.IdentityModel.Tokens library. I dug into source code and noticed that AsymmetricSignatureProvider differently handle signaure verification in method bool Verify(byte[] input, byte[] signature) for .NET Core and other versions, which is also place where my verification failed. You can find source code in this link.

In general I am first downloading JSON Web Key Sets, then I am building security keys and last I am building TokenValidationParameters and validating token.

My code starts here

Downloading JSON Web Key Sets:

string data = null;
using (WebClient client = new WebClient())
{
    data = client.DownloadString(URL_TO_JWKS);
}

var jwks = new JsonWebKeySet(data);

Here I am building security keys from JSON Web Key Sets. Please notice how I decoding exponent and modulus, maybe is wrong in .NET 4.1.6:

    var keys = new List<SecurityKey>();
    foreach (var webKey in jwks.Keys)
    {
         var e = Base64UrlEncoder.DecodeBytes(webKey.E);
         var n = Base64UrlEncoder.DecodeBytes(webKey.N);
         var key = new RsaSecurityKey(new RSAParameters { Exponent = e, Modulus = n })
          {
             KeyId = webKey.Kid
          };

          keys.Add(key);
   }

Here I am verifying token:

var token = new JwtSecurityToken(tokenString);
ClaimsPrincipal claimsPrincipal = null;

            var parameters = new TokenValidationParameters()
            {
                ValidAudiences = token.Audiences,
                IssuerSigningKeys = keys,
                NameClaimType = nameClaimType ?? JwtRegisteredClaimNames.Sub,
                ValidIssuers = new[] { token.Issuer }
            };

            bool isValid = false;

            try
            {
                string jwt = token.RawData;
                SecurityToken securityToken = null;
                claimsPrincipal = new JwtSecurityTokenHandler().ValidateToken(jwt, parameters, out securityToken);
                isValid = claimsPrincipal.Identity.IsAuthenticated;
            }
            catch (SecurityTokenExpiredException)
            {
            }
            catch (SecurityTokenInvalidSignatureException ex)
            {
            }

What is correct way to verify validity for both .NET 4.6.1 and .NET Core?


问:
How to search a list for two items in Python3
I need some help with searching a single list for two different pieces of data, how could this be done so that if this if both pieces of data it will output the values are found.</p>

答:
Used a couple in operators to do this.

```<code>    list = [2,4,8,14,16]
    if 2 in list and 4 in list
        print("2 and 4 are found in this list.")
    else:
        print("These numbers are not found in this list.")
</code>```

Body:
Used a couple in operators to do this.

    list = [2,4,8,14,16]
    if 2 in list and 4 in list
        print("2 and 4 are found in this list.")
    else:
        print("These numbers are not found in this list.")


问:
That A-Ha Moment for Understanding OO Design in C#
I've been studying C# for a couple of years, reading voraciously, even taking a few C# data access courses from Microsoft.  I've also been reading books on OOP.  I'm coding a web-based database application at work.  While my job title is not "programmer", I'm fortunate enough to be able to work on this as a side project.  I coded in Basic in the early 80's and was even good at utilizing pokes and peeks to manipulate the Apple ][ + and the TRS-80 to astound and amaze my friends.  But that was a very linear approach to coding.

All this being said, something is just not clicking with me.  I haven't had that a-ha moment with either C# or OOP that gives me the ability to sit down, open up VS2008, and start coding.  I have to study other people's code so much that it simply seems like I'm not doing anything on my own.  I'm getting discouraged.

It's not like I'm not capable of it.  I picked up t-sql really quickly.  Someone can tell me what information they want out of the database and I can code out the tsql in a matter of a few minutes to give them what they want.  SQL is something that I get.  This isn't happening for me with OOP or C#.  Granted, C# is inherently more complex, but at some point it has to click.  Right?

I read over stackoverflow and I'm overwhelmed at how infinitely smart you all are.

What was it for you that made it click?

Edited to add:
A lot of the answers here were outstanding.  However, one in particular seemed to have risen to the top and that's the one I marked as the "answer".  I also hate not marking my questions with the answer.

答:
Write code. Lots of it. Bad code, good code, useless code - it doesn't matter. Just write it. When you're sick of writing code (and if you're not getting sick of it occasionally, you're not writing enough) read blogs, magazines, and books about code.

Then, go back and look at some of your previously written code. Refactor it, clean it up, and change the design. Add features, fix bugs, whatever - doesn't matter. Delete your existing code, and write more code.

At some point, you'll begin to think in C# - just like you do in SQL.

Note that this is similar to learning a foreign language by immersing yourself in it. Sure, you can study it in school, read a book, and listen to tapes. But, there's no better way to learn a foreign language than to moving where it's spoken every day.

OwnerDisplayName: GregD

LastEditorDisplayName: GregD

OwnerDisplayName: Mark Brackett


问:
Mongo Scala Async Client not writing
trying to upsert with the new Scala Async Driver using this code, but the DB never gets created even though this is called many times:

```<code>override def insertOrUpdateOne(user: UserNew): Future[Unit] = {
  users.replaceOne(equal("_id", user._id), user)
    .toFuture
    .map(_ => ())
}
</code>```

mongo client created fine, collection created fine, but the above causes no write to be performed in fact the db is never created (which should happen on the first write). I have other code that uses casbah and that is working synchronously.

users is the Mongo collection with no syntactic sugar from me. (edited)

toFuture seems to do the subscribe (which should trigger the write?) but it still doesn't work. I'm mixing some collections with casbah and one with the async client, the casbah ones work but not the one above using async.

Any ideas?

答:
it should be

```<code>override def insertOrUpdateOne(user: UserNew): Future[Unit] = {
  users.replaceOne(equal("_id", user._id), user, UpdateOptions().upsert(true))
    .toFuture
    .map(_ => ())
}
</code>```

Nothing in the docs but when I read the code I see it defaults upsert to false.

BTW this allows us to ignore all the Observable and subscribe stuff and setup of callbacks. Just process the results in a Scala idiomatic someFuture.map() This makes the UsersDaonon-Mongo specific code as an interface. This in turn allows all code in the UsersDaoImplto handle Mongo specific stuff, which enables the Impl to be injected so a runtime choice can be made about which Impl to use. Mongo can be replaced without dependent code caring or knowing about the Impl.

Title: Mongo Scala Async Client not writing

Body:
trying to upsert with the new Scala Async Driver using this code, but the DB never gets created even though this is called many times:

override def insertOrUpdateOne(user: UserNew): Future[Unit] = {
  users.replaceOne(equal("_id", user._id), user)
    .toFuture
    .map(_ => ())
}

mongo client created fine, collection created fine, but the above causes no write to be performed in fact the db is never created (which should happen on the first write). I have other code that uses casbah and that is working synchronously.

users is the Mongo collection with no syntactic sugar from me. (edited)

toFuture seems to do the subscribe (which should trigger the write?) but it still doesn't work. I'm mixing some collections with casbah and one with the async client, the casbah ones work but not the one above using async.

Any ideas?

Body:
it should be

override def insertOrUpdateOne(user: UserNew): Future[Unit] = {
  users.replaceOne(equal("_id", user._id), user, UpdateOptions().upsert(true))
    .toFuture
    .map(_ => ())
}

Nothing in the docs but when I read the code I see it defaults upsert to false.

BTW this allows us to ignore all the Observable and subscribe stuff and setup of callbacks. Just process the results in a Scala idiomatic someFuture.map() This makes the UsersDaonon-Mongo specific code as an interface. This in turn allows all code in the UsersDaoImplto handle Mongo specific stuff, which enables the Impl to be injected so a runtime choice can be made about which Impl to use. Mongo can be replaced without dependent code caring or knowing about the Impl.


问:
With Amazon S3, can I prevent trolls/grievers from making millions of GET-requests with bots?
I'm working on a website that contains photo galleries, and these images are stored on Amazon S3. Since Amazon charges like $0.01 per 10k GET-requests, it seems that a potential troll could seriously drive up my costs with a bot that makes millions of page requests per day.

Is there an easy way to protect myself from this?

答:
As @mohan-shanmugam pointed out, you should use a CloudFront CDN with your origin as the S3 bucket. It is considered bad practice for external entities to hit S3 buckets directly.

http://docs.aws.amazon.com/AmazonS3/latest/dev/request-rate-perf-considerations.html

With a CloudFront distribution, you can alter your S3 bucket's security policy to only allow access from the distribution. This will block direct access to S3 even if the URLs are known.

In reality, you would likely suffer from website performance way before needing to worry about additional charges as a direct DDOS attempt against S3 should result in AWS throttling API requests.

In addition, you can set up AWS WAF in front of your CloudFront distribution and use it for advanced control of security related concerns.


问:
Shortcut for creating constructor with variables (C# Visual Studio 2010)
In Visual Studio 2010 C# you can, in a class, type ctor and then press tab and Visual Studio will create a constructor for that class for me. It is very convenient.

But is there a way to make Visual Studio create a constructor with all my variables, properties and so on?

For example,

```<code>public class User
{
    public String UserName { get; private set; }
}
</code>```

And for this I want ctor + tab to make me a

```<code>public User(string UserName)
{
    this.UserName = UserName;
}
</code>```

答:
Use ReSharper's ctorf.

This will allow you to create a constructor with generated arguments based on fields defined in the class.

ContentLicense: CC BY-SA 4.0

Body:
In Visual Studio 2010 C# you can, in a class, type ctor and then press tab and Visual Studio will create a constructor for that class for me. It is very convenient.

But is there a way to make Visual Studio create a constructor with all my variables, properties and so on?

For example,

public class User
{
    public String UserName { get; private set; }
}

And for this I want ctor + tab to make me a

public User(string UserName)
{
    this.UserName = UserName;
}


问:
Dynamically change Image content using JSON file?
Essentially I want to create a JS script (using jQuery) that uses the id of a clicked
 element, finds the corresponding "id" value in the JSON file, and then adds the "image" url value to the
 element. I'm not sure whether the best way to do this would be via an  tag, or by changing the CSS background-image property using the jQuery code, (or another way entirely), as ideally I'd like to fade between the images as the user clicks on each box.

I have a HTML file set up as follows:

```<code><div class="box" id="1"><h1>Box 1</h1></div>
<div class="box" id="2"><h1>Box 2</h1></div>
<div class="box" id="3"><h1>Box 3</h1></div>

<div class="output-box"></div>
</code>```

And a separate JSON file:

```<code>{
    "content" : [
        {
        "id"     : 1,
        "image"  : "img/test01.jpg"
        },
        {
        "id"     : 2,
        "image"  : "img/test02.jpg"
        },
        {
        "id"     : 3,
        "image"  : "img/test03.jpg"
        }
    ]
}
</code>```

And a JS file (using jQuery), set up as follows:

```<code>$.getJSON('content.json', function (data) {

    "use strict";

    var content = data.content;

    $('.box').click(function () {

        //Box <div> id is obtained on click
        //Object with corresponding 'id' value from JSON file is then found
        //Image url is then used to add the image to the '.output-box' <div>

    });

});
</code>```

This needs to be easily scalable and work regardless of how many
 elements are added.

Detailed answers would be appreciated, as I'm still fairly new to JS and JSON and haven't found any that exactly explain what I'm trying to achieve.

Thanks! :)

答:
Here's one way to do it:</p>

```<code>// set a click handler on all .box elements
$('.box').click(function () {

  // return the first element, if it exists, of the content array that has a matching id to the clicked .box element's id
  var c = content.find(o => o.id == this.id);

  // make sure there was a match
  if (c) {
    // append an image with the appropriate .src property
    $('.output-box').append("<img src='" + c.image + "'>");
  }
});
</code>```

Body:
Essentially I want to create a JS script (using jQuery) that uses the id of a clicked
 element, finds the corresponding "id" value in the JSON file, and then adds the "image" url value to the
 element. I'm not sure whether the best way to do this would be via an  tag, or by changing the CSS background-image property using the jQuery code, (or another way entirely), as ideally I'd like to fade between the images as the user clicks on each box.

I have a HTML file set up as follows:

Box 1

Box 2

Box 3

And a separate JSON file:

{
    "content" : [
        {
        "id"     : 1,
        "image"  : "img/test01.jpg"
        },
        {
        "id"     : 2,
        "image"  : "img/test02.jpg"
        },
        {
        "id"     : 3,
        "image"  : "img/test03.jpg"
        }
    ]
}

And a JS file (using jQuery), set up as follows:

$.getJSON('content.json', function (data) {

    "use strict";

    var content = data.content;

    $('.box').click(function () {

        //Box
 id is obtained on click
        //Object with corresponding 'id' value from JSON file is then found
        //Image url is then used to add the image to the '.output-box'

    });

});

This needs to be easily scalable and work regardless of how many
 elements are added.

Detailed answers would be appreciated, as I'm still fairly new to JS and JSON and haven't found any that exactly explain what I'm trying to achieve.

Thanks! :)

Body:
Here's one way to do it:

// set a click handler on all .box elements
$('.box').click(function () {

  // return the first element, if it exists, of the content array that has a matching id to the clicked .box element's id
  var c = content.find(o => o.id == this.id);

  // make sure there was a match
  if (c) {
    // append an image with the appropriate .src property
    $('.output-box').append("<img src='" + c.image + "'>");
  }
});


问:
PHP: replacement for DateTime object
The server that I have my sited hosted is on PHP5.12.14, and I have an error when I run the DateTime object from PHP5.3

```<code># DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
$date = new DateTime($item_user['mem_updated']);

# add a day to the object
$date -> add(new DateInterval('P1D'));
</code>```

the error,

```<code>Fatal error: Call to undefined method DateTime::add() in /homepages/xxx.php on line xx
</code>```

So, I have look for the other solutions rather than sticking to PHP5.3's DateTime object. How can I write the code to replace the code above?

basically I have this date and time data (for instance - 2011-01-21 02:08:39) from the mysql database, and I just need to add 1 day or 24 hours to that date/time, then passing it into a function below,

```<code>$time_togo = time_togo($date -> format('Y-m-d H:i:s'));
</code>```

thanks.

答:
strtotime would work</p>

```<code>$timestamp = strtotime($item_user['mem_updated']);
$time_togo = date("Y-m=d H:i:s", strtotime("+1 Day", $timestamp));
</code>```

Title: PHP: replacement for DateTime object

Body:
The server that I have my sited hosted is on PHP5.12.14, and I have an error when I run the DateTime object from PHP5.3

# DateTime::add — Adds an amount of days, months, years, hours, minutes and seconds to a DateTime object
$date = new DateTime($item_user['mem_updated']);

# add a day to the object
$date -> add(new DateInterval('P1D'));

the error,

Fatal error: Call to undefined method DateTime::add() in /homepages/xxx.php on line xx

So, I have look for the other solutions rather than sticking to PHP5.3's DateTime object. How can I write the code to replace the code above?

basically I have this date and time data (for instance - 2011-01-21 02:08:39) from the mysql database, and I just need to add 1 day or 24 hours to that date/time, then passing it into a function below,

$time_togo = time_togo($date -> format('Y-m-d H:i:s'));

thanks.

Body:
strtotime would work

$timestamp = strtotime($item_user['mem_updated']);
$time_togo = date("Y-m=d H:i:s", strtotime("+1 Day", $timestamp));


问:
md-datepicker shows scrollbar on the side on Edge and IE 11
I am using the standard md-datepicker on my page. Its working fine on all browsers but on IE11 and Edge, theres a weird scrollbar displayed on the right.

Please find the screenshot below.

Here is my code:

HTML:

```<code><div id="myDatepicker" layout="column" ng-cloak>
  <md-content>
    <md-datepicker
      ng-model = "myDate"
      md-placeholder = "Enter date" md-hide-icons="triangle">
    </md-datepicker>
  </md-content>
</div>
</code>```

JS:

```<code>$scope.myDate = "";
this.isOpen = false;
</code>```

CSS:

```<code>.md-default-theme .md-datepicker-input-container, .md-datepicker-input-container {
  border-bottom-color: white;
}

.md-default-theme .md-datepicker-input, .md-datepicker-input {
  color: #1797c0;
}

#myDatepicker .md-datepicker-calendar-icon {
  color: #1797c0;
}
</code>```

Also there's an orange line underneath the placeholder which I have tried changing to white in the CSS above - not sure why its not being applied?

Link - IE 11 - scrollbar on the right of datepicker

Link - Edge - scrollbar on the right of datepicker

答:
If it's an issue with the height of md-datepicker for some reason, it's possible that adding overflow: hidden; to md-datepicker CSS could resolve. Without seeing it in JSFiddle or similar, it's difficult to tell for sure.

If you inspect the page in Chrome using Dev Tools can you see a property that has the orange color? It's likely something built into the default theme that you're not over-riding or changing correctly. I think you might have to apply a border color to .md-input-container and .md-input

Body:
I am using the standard md-datepicker on my page. Its working fine on all browsers but on IE11 and Edge, theres a weird scrollbar displayed on the right.

Please find the screenshot below.

Here is my code:

HTML:

  <md-content>
    <md-datepicker
      ng-model = "myDate"
      md-placeholder = "Enter date" md-hide-icons="triangle">
    </md-datepicker>
  </md-content>

JS:

$scope.myDate = "";
this.isOpen = false;

CSS:

.md-default-theme .md-datepicker-input-container, .md-datepicker-input-container {
  border-bottom-color: white;
}

.md-default-theme .md-datepicker-input, .md-datepicker-input {
  color: #1797c0;
}

#myDatepicker .md-datepicker-calendar-icon {
  color: #1797c0;
}

Also there's an orange line underneath the placeholder which I have tried changing to white in the CSS above - not sure why its not being applied?

Link - IE 11 - scrollbar on the right of datepicker

Link - Edge - scrollbar on the right of datepicker


问:
VB.Net How do I store lines in a textbox as a variable for later use?
I have a software development assessment which requires me to create a form in which the user can order products. This form looks like this: https://i.imgur.com/48qrsIc.jpg

When adding a product, the product name as well as the quantity, appear in the textbox below like so: https://i.imgur.com/OGzG8Jf.jpg

I want to be able to set each line in the bottom textbox as a variable so I can store it in my database. I don't know if I need to make it an array or a list as I also don't know how to do that.

Any assistance would be greatly appreciated. Thank you very much!!!

答:
You should never use a control to store data. What you should be doing is have an "Cart" object which is a list of item orders. An item order should be an object which contains the order code, the quantity, and MAYBE the product description.

```<code>Private Class Product
    Property ProductCode As Integer
    Property Description As String
    Property StockQuantity As Integer
    Property Price As Decimal
End Class

Dim products As New List(Of Product)

Private Class OrderItem
    Public Property ProductCode As Integer
    Public Property Quantity As Integer
End Class

Dim cart As New List(Of OrderItem)
</code>```

And in your combo box, you should bind it to the product list using Description as the .DisplayMember

When you click the "Add to Cart" button, you can then use the ComboBox.SelectedItem which will be the actual product object and add that directly to your cart.

At this point, instead of your data being stored in the RichTextBox, it is stored in a Cart object as a list of order items. You can use this list to populate your RichTextBox something like this.

```<code>Private Sub RefreshRtbOrders()
    RtbOrders.SuspendLayout()
    RtbOrders.Clear()
    For Each item As OrderItem In cart
        RtbOrders.AppendText(item.Quantity.ToString("0000  ") & products.Find(Function(x) x.ProductCode = item.ProductCode).Description & vbCrLf)
    Next
    CboProducts.ResumeLayout()
End Sub
</code>```

You can then use the Cart object to update your database.

Body:
You should never use a control to store data. What you should be doing is have an "Cart" object which is a list of item orders. An item order should be an object which contains the order code, the quantity, and MAYBE the product description.

Private Class Product
    Property ProductCode As Integer
    Property Description As String
    Property StockQuantity As Integer
    Property Price As Decimal
End Class

Dim products As New List(Of Product)

Private Class OrderItem
    Public Property ProductCode As Integer
    Public Property Quantity As Integer
End Class

Dim cart As New List(Of OrderItem)

And in your combo box, you should bind it to the product list using Description as the .DisplayMember

When you click the "Add to Cart" button, you can then use the ComboBox.SelectedItem which will be the actual product object and add that directly to your cart.

At this point, instead of your data being stored in the RichTextBox, it is stored in a Cart object as a list of order items. You can use this list to populate your RichTextBox something like this.

Private Sub RefreshRtbOrders()
    RtbOrders.SuspendLayout()
    RtbOrders.Clear()
    For Each item As OrderItem In cart
        RtbOrders.AppendText(item.Quantity.ToString("0000  ") & products.Find(Function(x) x.ProductCode = item.ProductCode).Description & vbCrLf)
    Next
    CboProducts.ResumeLayout()
End Sub

You can then use the Cart object to update your database.


问:
Change styles on ngb-tab title
I would like to style the title in ngb-tab so that it is not the default blue of an anchor tag. Ideally something like this, but the class property doesn't seem to have an effect on ngb-tab.

The HTML:

```<code><ngb-tabset #t="ngbTabset">
    <ngb-tab [title]="'Followers'" class="tab-title">
        <ng-template ngbTabContent>
            ...
        </ng-template>
    </ngb-tab>
    <ngb-tab [title]="'Following'" class="tab-title">
        <ng-template ngbTabContent>
            ...
        </ng-template>
    </ngb-tab>
</ngb-tabset>
</code>```

The CSS:

```<code>.tab-title {
  color: inherit;
}
</code>```

答:
According to the documentation https://ng-bootstrap.github.io/#/components/tabs/ you can style the title by using their ngbTabTitle directive.

Example:

```<code><ngb-tabset>
 <ngb-tab>
  <ng-template ngbTabTitle><span class="tab-title">Fancy Title</span></ng-template>
  <ng-template ngbTabContent>Content</ng-template>
 </ngb-tab>
</ngb-tabset>
</code>```

Title: Change styles on ngb-tab title

Body:
I would like to style the title in ngb-tab so that it is not the default blue of an anchor tag. Ideally something like this, but the class property doesn't seem to have an effect on ngb-tab.

The HTML:

<ngb-tabset #t="ngbTabset">
    <ngb-tab [title]="'Followers'" class="tab-title">
        <ng-template ngbTabContent>
            ...
        </ng-template>
    </ngb-tab>
    <ngb-tab [title]="'Following'" class="tab-title">
        <ng-template ngbTabContent>
            ...
        </ng-template>
    </ngb-tab>
</ngb-tabset>

The CSS:

.tab-title {
  color: inherit;
}

Body:
According to the documentation https://ng-bootstrap.github.io/#/components/tabs/ you can style the title by using their ngbTabTitle directive.

Example:

<ngb-tabset>
 <ngb-tab>
  <ng-template ngbTabTitle><span class="tab-title">Fancy Title</span></ng-template>
  <ng-template ngbTabContent>Content</ng-template>
 </ngb-tab>
</ngb-tabset>


问:
java walkFileTree to mimic chmod -R 755 does not work
I want to ensure correct permissions in a directory tree (0755 for directories and 644 for files). Here is my class:

```<code>package NRF_Utils;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import static java.nio.file.FileVisitResult.*;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.logging.Logger;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;

public class DirectoryTreeOperations {
    private static final Logger log = Logger.getLogger("spv." + DirectoryTreeOperations.class.getName());

    public static boolean setPermissions(String root, String directoryPermissions, String filePermissions) {
        boolean result = true;
        //declaring the path to delete
        final Path path = Paths.get(root);
        final Set<PosixFilePermission> dirPermissions = PosixFilePermissions.fromString(directoryPermissions);
        final Set<PosixFilePermission> filPermissions = PosixFilePermissions.fromString(filePermissions);

        try {
            Files.walkFileTree(path, new FileVisitor<Path>() {

                @Override
                public FileVisitResult preVisitDirectory(Path dir,
                        BasicFileAttributes attrs) throws IOException {
                    System.out.println("setting dir permission on " + dir);
                    Files.setPosixFilePermissions(dir, dirPermissions);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file,
                        BasicFileAttributes attrs) throws IOException {
                    System.out.println("setting file permission on " + file);
                    Files.setPosixFilePermissions(file, filPermissions);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc)
                        throws IOException {
                    log.severe("visitFileFailed failed on " + file + " : " + exc);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir,
                        IOException exc) throws IOException {
                    return CONTINUE;
                }

            });
        } catch (IOException e) {
            log.severe("setPermissions failed " + e);
            result = false;
        }
        return result;
    }

    // TODO remove and provide a proper unit test
    public static void main(String [] arg) {
        System.out.println ("setPermissions returned: " + setPermissions("/tmp/x", "rwxr-xr-x", "rw-r--r--"));
    }
}
</code>```

To perform test, I have done:

```<code>mkdir -p /tmp/x/y/z;touch /tmp/x/y/z/f;chmod 000 /tmp/x/y/z
</code>```

The output is:

```<code>setting dir permission on /tmp/x
setting dir permission on /tmp/x/y
setPermissions returned: true
nov. 26, 2017 2:45:00 PM NRF_Utils.DirectoryTreeOperations$1 visitFileFailed
GRAVE: visitFileFailed failed on /tmp/x/y/z : java.nio.file.AccessDeniedException: /tmp/x/y/z
</code>```

It seems java does not want to explore the directory tree because the permissions are wrong, but my aim was to explore the directory tree to fix permissions. Is the API crazy ?

答:
When you do chmod 755 /tmp/x/y/z from the command line, it does not check the permission on z itself. As long as you have sufficient access to y, you can perform chmod on z.

OTOH, if you look at the source code of Files.walkFileTree, it actually tries to access every target file in its own visit method, to gather file attributes etc., before it calls your visitor methods. Hence the access denied error.

By the look of it, you might have to roll your own file tree walker, where you would just go ahead change the permission without trying to access the target path first.

Body:
I want to ensure correct permissions in a directory tree (0755 for directories and 644 for files). Here is my class:

package NRF_Utils;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import static java.nio.file.FileVisitResult.*;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.logging.Logger;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;

public class DirectoryTreeOperations {
    private static final Logger log = Logger.getLogger("spv." + DirectoryTreeOperations.class.getName());

    public static boolean setPermissions(String root, String directoryPermissions, String filePermissions) {
        boolean result = true;
        //declaring the path to delete
        final Path path = Paths.get(root);
        final Set<PosixFilePermission> dirPermissions = PosixFilePermissions.fromString(directoryPermissions);
        final Set<PosixFilePermission> filPermissions = PosixFilePermissions.fromString(filePermissions);

        try {
            Files.walkFileTree(path, new FileVisitor<Path>() {

                @Override
                public FileVisitResult preVisitDirectory(Path dir,
                        BasicFileAttributes attrs) throws IOException {
                    System.out.println("setting dir permission on " + dir);
                    Files.setPosixFilePermissions(dir, dirPermissions);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path file,
                        BasicFileAttributes attrs) throws IOException {
                    System.out.println("setting file permission on " + file);
                    Files.setPosixFilePermissions(file, filPermissions);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc)
                        throws IOException {
                    log.severe("visitFileFailed failed on " + file + " : " + exc);
                    return CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir,
                        IOException exc) throws IOException {
                    return CONTINUE;
                }

            });
        } catch (IOException e) {
            log.severe("setPermissions failed " + e);
            result = false;
        }
        return result;
    }

    // TODO remove and provide a proper unit test
    public static void main(String [] arg) {
        System.out.println ("setPermissions returned: " + setPermissions("/tmp/x", "rwxr-xr-x", "rw-r--r--"));
    }
}

To perform test, I have done:

mkdir -p /tmp/x/y/z;touch /tmp/x/y/z/f;chmod 000 /tmp/x/y/z

The output is:

setting dir permission on /tmp/x
setting dir permission on /tmp/x/y
setPermissions returned: true
nov. 26, 2017 2:45:00 PM NRF_Utils.DirectoryTreeOperations$1 visitFileFailed
GRAVE: visitFileFailed failed on /tmp/x/y/z : java.nio.file.AccessDeniedException: /tmp/x/y/z

It seems java does not want to explore the directory tree because the permissions are wrong, but my aim was to explore the directory tree to fix permissions. Is the API crazy ?


问:
Can't able to read the binary file
```<code>         // STRUCTURE FOR ADD NEW DRIVER'S RECORD
        struct driver
       {
        int long reg;
        string name;
        string fhname;
        string peraddress;
        string pesentaddress;
        string dob;
        string cnic;
        string qualification;
        string occupation;
        string phone;
        string mobile;
        string licnum;
        string email;
        string city;
        string gender;
        string province;
        string lictype;
        string vitype;

    }e[100];

     // FUNCTION FOR ADD NEW RECORD OF DRIVER

      void add_driver_record()
      {
       system("CLS");
       char option;

       fstream driverTextFile, addrecord;
       addrecord.open("rcd.data", ios::out | ios::app | ios::binary);

       cout << "Do you Want to Enter New Record (Y/N) ";
       option = _getch();

       system("cls");

       if (option == 'Y' || option == 'y')
        {
          for (int i = 1; i == 1; i++)
           {
              while (option != 'N')
               {
                  cout << "\t\t Driver Information " << endl;
                  cout << "\t\t++++++++++++++++++++" << endl;

                  cout << "\t\tEnter Token No             :";
                  cin >> e[i].reg;

                  cout << "\t\tEnter License Number       :";
                  cin.ignore();
                  getline(cin, e[i].licnum);

                  cout << "\t\tEnter Full Name            :";
                  getline(cin, e[i].name);

                  cout << "\t\tEnter Father/Husband Name  :";
                  getline(cin, e[i].fhname);

                  cout << "\t\tEnter Permanent Address    :";
                  getline(cin, e[i].peraddress);

                  cout << "\t\tEnter Present Address      :";
                  getline(cin, e[i].pesentaddress);

                  cout << "\t\tEnter Date of Birth        :";
                  getline(cin, e[i].dob);

                  cout << "\t\tEnter CNI                  :";
                  getline(cin, e[i].cnic);

                  cout << "\t\tEnter city                 :";
                  getline(cin, e[i].city);

                  cout << "\t\tEnter Province             :";
                  getline(cin, e[i].province);

                  cout << "\t\tEnter Gender               :";
                  cin >> e[i].gender;

                  cout << "\t\tEnter Occupation           :";
                  cin >> e[i].occupation;

                  cout << "\t\tEnter Qaulification        :";
                  cin.ignore();
                  getline(cin, e[i].qualification);

                  cout << "\t\tEnter E-mail               :";
                  cin.ignore();
                  getline(cin, e[i].email);

                  cout << "\t\tEnter Phone No             :";
                  cin >> e[i].phone;

                  cout << "\t\tEnter Mobile No            :";
                  cin >> e[i].mobile;

                  cout << "\t\tEnter License Type         :";
                  cin.ignore();
                  getline(cin, e[i].lictype);

                  cout << "\t\tEnter Vehicle Type         :";
                  cin.ignore();
                  getline(cin, e[i].vitype);

                  addrecord.write((char *)&e, sizeof(driver));

                  driverTextFile <<                                                                                "========================================================\n";
                  driverTextFile << "\t\t   Driver Information  " << endl;
                  driverTextFile << "\t\t+++++++++++++++++++++++" << endl;
                  driverTextFile << "\t\t Token No              :" << e[i].reg << endl;
                  driverTextFile << "\t\t License Number        :" << e[i].licnum << endl;
                  driverTextFile << "\t\t Full Name             :" << e[i].name << endl;
                  driverTextFile << "\t\t Father/Husband Name   :" << e[i].fhname << endl;
                  driverTextFile << "\t\t Permanent Address     :" << e[i].peraddress << endl;
                  driverTextFile << "\t\t Present Address       :" << e[i].pesentaddress << endl;
                  driverTextFile << "\t\t Date of Birth         :" << e[i].dob << endl;
                  driverTextFile << "\t\t CNIC                  :" << e[i].cnic << endl;
                  driverTextFile << "\t\t City                  :" << e[i].city << endl;
                  driverTextFile << "\t\t Province              :" << e[i].province << endl;
                  driverTextFile << "\t\t Gender                :" << e[i].gender << endl;
                  driverTextFile << "\t\t Occupation            :" << e[i].occupation << endl;
                  driverTextFile << "\t\t Qaulification         :" << e[i].qualification << endl;
                  driverTextFile << "\t\t E-mail                :" << e[i].email << endl;
                  driverTextFile << "\t\t Phone No              :" << e[i].phone << endl;
                  driverTextFile << "\t\t Mobile No             :" << e[i].mobile << endl;
                  driverTextFile << "\t\t Enter License Type    :" << e[i].lictype << endl;
                  driverTextFile << "\t\t Enter Vehicle Type    :" << e[i].vitype << endl;
                  driverTextFile << "========================================================\n";

                  addrecord.close();

                  cout << "Do you Want to Enter New Record (Y/N) ";
                  cin >> option;

                  switch (option) {
                  case 'Y':
                  case 'y':
                   add_driver_record();
                   break;
                  case 'N':
                  case 'n':
                   exit(1);
                   break;
                  default:
                   printf("Please select suitable option \n");
                   add_driver_record();
                   break;
               }
              } // while Loop ends
             }// for loop ends
            } // if condition ends

           else if (option == 'N' || option == 'n')
           {
             printf("Please Select Suitable Option \n");
           }
        }

        // FUNCTION FOR DISPLAY ALL RECORDS OF DRIVER'S
         void display_all_driver()
         {

            system("CLS");
            system("color f5");

            fstream myfile, driverTextFile;
            myfile.open("rcd.data", ios::in | ios::out | ios::binary);

            int idx = 1;
            while (idx == 1)
             {

                myfile.read((char*)&e[idx].reg, sizeof(e[idx].reg));
                myfile.read((char*)&e[idx].licnum, sizeof(e[idx].licnum));
                myfile.read((char*)&e[idx].name, sizeof(e[idx].name));
                myfile.read((char*)&e[idx].fhname, sizeof(e[idx].fhname));
                myfile.read((char*)&e[idx].peraddress,              sizeof(e[idx].peraddress));
                myfile.read((char*)&e[idx].pesentaddress, sizeof(e[idx].pesentaddress));
                myfile.read((char*)&e[idx].dob, sizeof(e[idx].dob));
                myfile.read((char*)&e[idx].cnic, sizeof(e[idx].cnic));
                myfile.read((char*)&e[idx].city, sizeof(e[idx].city));
                myfile.read((char*)&e[idx].province, sizeof(e[idx].province));
                myfile.read((char*)&e[idx].gender, sizeof(e[idx].gender));
                myfile.read((char*)&e[idx].occupation, sizeof(e[idx].occupation));
                myfile.read((char*)&e[idx].qualification, sizeof(e[idx].qualification));
                myfile.read((char*)&e[idx].email, sizeof(e[idx].email));
                myfile.read((char*)&e[idx].phone, sizeof(e[idx].phone));
                myfile.read((char*)&e[idx].mobile, sizeof(e[idx].mobile));
                myfile.read((char*)&e[idx].lictype, sizeof(e[idx].lictype));
                myfile.read((char*)&e[idx].vitype, sizeof(e[idx].vitype));

                        cout << "========================================================\n";
                         cout << "\t\t   Driver Information  " << endl;
                         cout << "\t\t+++++++++++++++++++++++" << endl;
                         cout << "\t\t Token No              :" << e[idx].reg << endl;
                         cout << "\t\t License Number        :" << e[idx].licnum << endl;
                         cout << "\t\t Full Name             :" << e[idx].name << endl;
                         cout << "\t\t Father/Husband Name   :" << e[idx].fhname << endl;
                         cout << "\t\t Permanent Address     :" << e[idx].peraddress << endl;
                         cout << "\t\t Present Address       :" << e[idx].pesentaddress << endl;
                         cout << "\t\t Date of Birth         :" << e[idx].dob << endl;
                         cout << "\t\t CNIC                  :" << e[idx].cnic << endl;
                         cout << "\t\t City                  :" << e[idx].city << endl;
                         cout << "\t\t Province              :" << e[idx].province << endl;
                         cout << "\t\t Gender                :" << e[idx].gender << endl;
                         cout << "\t\t Occupation            :" << e[idx].occupation << endl;
                         cout << "\t\t Qaulification         :" << e[idx].qualification << endl;
                         cout << "\t\t E-mail                :" << e[idx].email << endl;
                         cout << "\t\t Phone No              :" << e[idx].phone << endl;
                         cout << "\t\t Mobile No             :" << e[idx].mobile << endl;
                         cout << "\t\t Enter License Type    :" << e[idx].lictype << endl;
                         cout << "\t\t Enter Vehicle Type    :" << e[idx].vitype << endl;
                         cout << "========================================================\n";

                         idx++;
                        }

                          myfile.close();

           }
</code>```

I am so sorry if somebody else had already asked this question. But I am unable to rectify the problem that I "can not" read the binary file on console. Let me tell what my code is doing. I took structure with bunch of attribute and taking the input in that and saving that data in Binary file. And i want to read that in second method. But I am completely unable to read the data. This is my code please provide me solution. I have already tried several ways but I am still unable. Your help will save me semester project.

答: Do you have read permissions for the file? That is my first thought that it is a permissions issue. </p>

Title: Can't able to read the binary file

Body:
         // STRUCTURE FOR ADD NEW DRIVER'S RECORD
        struct driver
       {
        int long reg;
        string name;
        string fhname;
        string peraddress;
        string pesentaddress;
        string dob;
        string cnic;
        string qualification;
        string occupation;
        string phone;
        string mobile;
        string licnum;
        string email;
        string city;
        string gender;
        string province;
        string lictype;
        string vitype;

    }e[100];

     // FUNCTION FOR ADD NEW RECORD OF DRIVER

      void add_driver_record()
      {
       system("CLS");
       char option;

       fstream driverTextFile, addrecord;
       addrecord.open("rcd.data", ios::out | ios::app | ios::binary);

       cout << "Do you Want to Enter New Record (Y/N) ";
       option = _getch();

       system("cls");

       if (option == 'Y' || option == 'y')
        {
          for (int i = 1; i == 1; i++)
           {
              while (option != 'N')
               {
                  cout << "\t\t Driver Information " << endl;
                  cout << "\t\t++++++++++++++++++++" << endl;

                  cout << "\t\tEnter Token No             :";
                  cin >> e[i].reg;

                  cout << "\t\tEnter License Number       :";
                  cin.ignore();
                  getline(cin, e[i].licnum);

                  cout << "\t\tEnter Full Name            :";
                  getline(cin, e[i].name);

                  cout << "\t\tEnter Father/Husband Name  :";
                  getline(cin, e[i].fhname);

                  cout << "\t\tEnter Permanent Address    :";
                  getline(cin, e[i].peraddress);

                  cout << "\t\tEnter Present Address      :";
                  getline(cin, e[i].pesentaddress);

                  cout << "\t\tEnter Date of Birth        :";
                  getline(cin, e[i].dob);

                  cout << "\t\tEnter CNI                  :";
                  getline(cin, e[i].cnic);

                  cout << "\t\tEnter city                 :";
                  getline(cin, e[i].city);

                  cout << "\t\tEnter Province             :";
                  getline(cin, e[i].province);

                  cout << "\t\tEnter Gender               :";
                  cin >> e[i].gender;

                  cout << "\t\tEnter Occupation           :";
                  cin >> e[i].occupation;

                  cout << "\t\tEnter Qaulification        :";
                  cin.ignore();
                  getline(cin, e[i].qualification);

                  cout << "\t\tEnter E-mail               :";
                  cin.ignore();
                  getline(cin, e[i].email);

                  cout << "\t\tEnter Phone No             :";
                  cin >> e[i].phone;

                  cout << "\t\tEnter Mobile No            :";
                  cin >> e[i].mobile;

                  cout << "\t\tEnter License Type         :";
                  cin.ignore();
                  getline(cin, e[i].lictype);

                  cout << "\t\tEnter Vehicle Type         :";
                  cin.ignore();
                  getline(cin, e[i].vitype);

                  addrecord.write((char *)&e, sizeof(driver));

                  driverTextFile <<                                                                                "========================================================\n";
                  driverTextFile << "\t\t   Driver Information  " << endl;
                  driverTextFile << "\t\t+++++++++++++++++++++++" << endl;
                  driverTextFile << "\t\t Token No              :" << e[i].reg << endl;
                  driverTextFile << "\t\t License Number        :" << e[i].licnum << endl;
                  driverTextFile << "\t\t Full Name             :" << e[i].name << endl;
                  driverTextFile << "\t\t Father/Husband Name   :" << e[i].fhname << endl;
                  driverTextFile << "\t\t Permanent Address     :" << e[i].peraddress << endl;
                  driverTextFile << "\t\t Present Address       :" << e[i].pesentaddress << endl;
                  driverTextFile << "\t\t Date of Birth         :" << e[i].dob << endl;
                  driverTextFile << "\t\t CNIC                  :" << e[i].cnic << endl;
                  driverTextFile << "\t\t City                  :" << e[i].city << endl;
                  driverTextFile << "\t\t Province              :" << e[i].province << endl;
                  driverTextFile << "\t\t Gender                :" << e[i].gender << endl;
                  driverTextFile << "\t\t Occupation            :" << e[i].occupation << endl;
                  driverTextFile << "\t\t Qaulification         :" << e[i].qualification << endl;
                  driverTextFile << "\t\t E-mail                :" << e[i].email << endl;
                  driverTextFile << "\t\t Phone No              :" << e[i].phone << endl;
                  driverTextFile << "\t\t Mobile No             :" << e[i].mobile << endl;
                  driverTextFile << "\t\t Enter License Type    :" << e[i].lictype << endl;
                  driverTextFile << "\t\t Enter Vehicle Type    :" << e[i].vitype << endl;
                  driverTextFile << "========================================================\n";

                  addrecord.close();

                  cout << "Do you Want to Enter New Record (Y/N) ";
                  cin >> option;

                  switch (option) {
                  case 'Y':
                  case 'y':
                   add_driver_record();
                   break;
                  case 'N':
                  case 'n':
                   exit(1);
                   break;
                  default:
                   printf("Please select suitable option \n");
                   add_driver_record();
                   break;
               }
              } // while Loop ends
             }// for loop ends
            } // if condition ends

           else if (option == 'N' || option == 'n')
           {
             printf("Please Select Suitable Option \n");
           }
        }

        // FUNCTION FOR DISPLAY ALL RECORDS OF DRIVER'S
         void display_all_driver()
         {

            system("CLS");
            system("color f5");

            fstream myfile, driverTextFile;
            myfile.open("rcd.data", ios::in | ios::out | ios::binary);

            int idx = 1;
            while (idx == 1)
             {

                myfile.read((char*)&e[idx].reg, sizeof(e[idx].reg));
                myfile.read((char*)&e[idx].licnum, sizeof(e[idx].licnum));
                myfile.read((char*)&e[idx].name, sizeof(e[idx].name));
                myfile.read((char*)&e[idx].fhname, sizeof(e[idx].fhname));
                myfile.read((char*)&e[idx].peraddress,              sizeof(e[idx].peraddress));
                myfile.read((char*)&e[idx].pesentaddress, sizeof(e[idx].pesentaddress));
                myfile.read((char*)&e[idx].dob, sizeof(e[idx].dob));
                myfile.read((char*)&e[idx].cnic, sizeof(e[idx].cnic));
                myfile.read((char*)&e[idx].city, sizeof(e[idx].city));
                myfile.read((char*)&e[idx].province, sizeof(e[idx].province));
                myfile.read((char*)&e[idx].gender, sizeof(e[idx].gender));
                myfile.read((char*)&e[idx].occupation, sizeof(e[idx].occupation));
                myfile.read((char*)&e[idx].qualification, sizeof(e[idx].qualification));
                myfile.read((char*)&e[idx].email, sizeof(e[idx].email));
                myfile.read((char*)&e[idx].phone, sizeof(e[idx].phone));
                myfile.read((char*)&e[idx].mobile, sizeof(e[idx].mobile));
                myfile.read((char*)&e[idx].lictype, sizeof(e[idx].lictype));
                myfile.read((char*)&e[idx].vitype, sizeof(e[idx].vitype));

                        cout << "========================================================\n";
                         cout << "\t\t   Driver Information  " << endl;
                         cout << "\t\t+++++++++++++++++++++++" << endl;
                         cout << "\t\t Token No              :" << e[idx].reg << endl;
                         cout << "\t\t License Number        :" << e[idx].licnum << endl;
                         cout << "\t\t Full Name             :" << e[idx].name << endl;
                         cout << "\t\t Father/Husband Name   :" << e[idx].fhname << endl;
                         cout << "\t\t Permanent Address     :" << e[idx].peraddress << endl;
                         cout << "\t\t Present Address       :" << e[idx].pesentaddress << endl;
                         cout << "\t\t Date of Birth         :" << e[idx].dob << endl;
                         cout << "\t\t CNIC                  :" << e[idx].cnic << endl;
                         cout << "\t\t City                  :" << e[idx].city << endl;
                         cout << "\t\t Province              :" << e[idx].province << endl;
                         cout << "\t\t Gender                :" << e[idx].gender << endl;
                         cout << "\t\t Occupation            :" << e[idx].occupation << endl;
                         cout << "\t\t Qaulification         :" << e[idx].qualification << endl;
                         cout << "\t\t E-mail                :" << e[idx].email << endl;
                         cout << "\t\t Phone No              :" << e[idx].phone << endl;
                         cout << "\t\t Mobile No             :" << e[idx].mobile << endl;
                         cout << "\t\t Enter License Type    :" << e[idx].lictype << endl;
                         cout << "\t\t Enter Vehicle Type    :" << e[idx].vitype << endl;
                         cout << "========================================================\n";

                         idx++;
                        }

                          myfile.close();

           }

I am so sorry if somebody else had already asked this question. But I am unable to rectify the problem that I "can not" read the binary file on console. Let me tell what my code is doing. I took structure with bunch of attribute and taking the input in that and saving that data in Binary file. And i want to read that in second method. But I am completely unable to read the data. This is my code please provide me solution. I have already tried several ways but I am still unable. Your help will save me semester project.