问:
Google sign in not redirect to application after allow
I'm using this tutorial to implement Sign in with google in app.

I installed GoogleSignIn via cocoapods. pod 'GoogleSignIn', '~> 2.4.0'

Added GSignIn-Bridging-Header.h with #import <GoogleSignIn/GoogleSignIn.h> inside.

Create url types:

Create a view with GIDSignInButton class

Added code:

```<code>class ViewController: UIViewController, GIDSignInDelegate,    GIDSignInUIDelegate {
override func viewDidLoad() {
    super.viewDidLoad()
    GIDSignIn.sharedInstance().delegate = self
    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().clientID = "KEY"
 }

 func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
if let err = error {
   print(error)
}
else {
   print(GIDSignIn.sharedInstance().currentUser.profile.name)
   print(GIDSignIn.sharedInstance().currentUser.profile.email)
   self.performSegueWithIdentifier("idSegueContent", sender: self)
  }
}

func signIn(signIn: GIDSignIn!, didDisconnectWithUser user: GIDGoogleUser!, withError error: NSError!) {

}
}
</code>```

But when i click allow

It redirects me to google.com, not to app.

答:
I did found another answer for it. In my case, in AppDelegate I did implement 2 delegate methods

```<code>- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
</code>```

and

```<code>- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
</code>```

The first is the delegate method and should not implement anymore, it was replaced by the the second method. But somehow I still use both and just add

```<code>return [[GIDSignIn sharedInstance] handleURL:url
                                   sourceApplication:sourceApplication
                                          annotation:annotation];
</code>```

in the second one and then somehow again, it just callback to the first method then it not navigate to my app anymore.

So I want to post my case for someone who may get this mistake to, it took me too long to find out

Body:
I'm using this tutorial to implement Sign in with google in app.

I installed GoogleSignIn via cocoapods. pod 'GoogleSignIn', '~> 2.4.0'

Added GSignIn-Bridging-Header.h with #import <GoogleSignIn/GoogleSignIn.h> inside.

Create url types:

Create a view with GIDSignInButton class

Added code:

class ViewController: UIViewController, GIDSignInDelegate,    GIDSignInUIDelegate {
override func viewDidLoad() {
    super.viewDidLoad()
    GIDSignIn.sharedInstance().delegate = self
    GIDSignIn.sharedInstance().uiDelegate = self
    GIDSignIn.sharedInstance().clientID = "KEY"
 }

 func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!, withError error: NSError!) {
if let err = error {
   print(error)
}
else {
   print(GIDSignIn.sharedInstance().currentUser.profile.name)
   print(GIDSignIn.sharedInstance().currentUser.profile.email)
   self.performSegueWithIdentifier("idSegueContent", sender: self)
  }
}

func signIn(signIn: GIDSignIn!, didDisconnectWithUser user: GIDGoogleUser!, withError error: NSError!) {

}
}

But when i click allow

It redirects me to google.com, not to app.

Body:
I did found another answer for it. In my case, in AppDelegate I did implement 2 delegate methods

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options

and

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation

The first is the delegate method and should not implement anymore, it was replaced by the the second method. But somehow I still use both and just add

return [[GIDSignIn sharedInstance] handleURL:url
                                   sourceApplication:sourceApplication
                                          annotation:annotation];

in the second one and then somehow again, it just callback to the first method then it not navigate to my app anymore.

So I want to post my case for someone who may get this mistake to, it took me too long to find out


来源: stackexchange

问:
How to write a unit test for a REST login web service using spring boot
I am developing one application using spring boot. I would like to unit test my Rest service login(), my service works well (I used postman). please take a look at what I tried for my unite test.
for example when I type a correct username and password I got a token as a return value:

and when I enter a false username and password I got this:

these is my architecture of my app:

```<code>app
 |
src/main/java
 |--DemoApplication.java
 |--dao.package
         |--UserRepository.java
 |--jwt.package
         |--UserController.java
src/test/java
 |--jwt.package.test
         |--UserControllerTest.java
</code>```

DemoApplication.java

```<code>@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    public static void main(String[] args) {

        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

    }
}
</code>```

UserController.java

```<code>@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @PostMapping("login")
    public LoginResponse login(@RequestBody final UserLogin login)
        throws ServletException,
            UnsupportedEncodingException {

        User user = userRepository.findByUsernameAndPassword(login.username,
            login.password);

        if (user == null)
            throw new ServletException("Invalid login");

        StringBuilder roles = new StringBuilder();
        user.getRoles()
            .forEach(role -> roles.append(role.getName()).append(","));
        return new LoginResponse(Jwts.builder().setSubject(login.username)
            .claim("roles", roles).setIssuedAt(new Date())
            .signWith(SignatureAlgorithm.HS256, "accenture".getBytes("UTF-8"))
            .compact());
    }

    private static class UserLogin {

        public String username;

        public String password;
    }

    private static class LoginResponse {

        public String token;

        public LoginResponse(final String token) {
            this.token = token;
        }
    }
}
</code>```

I tried to test my login web service but still not correct. Anyone could help me please to unit test my login service

UserControllerTest.java:

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(value = UserController.class, secure = false)
public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserRepository userRepository;

    User mockUser = new User("test", "test");

    String exampleUserJson = "{\"username\":\"toto\",\"password\":\"toto\"}";

    @Test
    public void loginTest() throws Exception {

        User mockUser = new User("test", "test");

    Mockito.when(
            userRepository.findByUsernameAndPassword(Mockito.anyString(),
                Mockito.anyString())).thenReturn(mockUser);

    // Send course as body to /students/Student1/courses
    RequestBuilder requestBuilder = MockMvcRequestBuilders
            .post("/user/login")
            .accept(MediaType.APPLICATION_JSON).content(exampleUserJson)
            .contentType(MediaType.APPLICATION_JSON);

    MvcResult result = mockMvc.perform(requestBuilder).andReturn();

    MockHttpServletResponse response = result.getResponse();

    assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), response.getStatus());

    assertEquals("http://localhost/user/login",
            response.getHeader(HttpHeaders.LOCATION));

    }
</code>```

答:
First of all understand how spring security works.

if you do not provide any configuration it will ask for authentication for every thing.

if you want to test authentication then what you just need to do is call any secure api with username and password like below,

```<code> curl -v http://localhost:9090/mynet/ -u admin:admin12344 -c D:\cookies.txt -H "Accept: application/json"
</code>```

Success senario : In above example i have called secured endpoint and get a cookie in response with  HTTP/1.1 200 if authentication is success which you can use for further call as below,

```<code>curl -v http://localhost:9090/mynet/customers -b D:\cookies.txt
</code>```

Failure scenario : We get  HTTP/1.1 401 with json

```<code>{"timestamp":1496645081468,"status":401,"error":"Unauthorized","message":"No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken","path":"/mynet/"}
</code>```

Note : I know you need to check above call using java code instead curl. I have used this just to explain concept.

ContentLicense: CC BY-SA 3.0

Body:
I am developing one application using spring boot. I would like to unit test my Rest service login(), my service works well (I used postman). please take a look at what I tried for my unite test.
for example when I type a correct username and password I got a token as a return value:

and when I enter a false username and password I got this:

these is my architecture of my app:

app
 |
src/main/java
 |--DemoApplication.java
 |--dao.package
         |--UserRepository.java
 |--jwt.package
         |--UserController.java
src/test/java
 |--jwt.package.test
         |--UserControllerTest.java

DemoApplication.java

@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

    public static void main(String[] args) {

        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

    }
}

UserController.java

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @PostMapping("login")
    public LoginResponse login(@RequestBody final UserLogin login)
        throws ServletException,
            UnsupportedEncodingException {

        User user = userRepository.findByUsernameAndPassword(login.username,
            login.password);

        if (user == null)
            throw new ServletException("Invalid login");

        StringBuilder roles = new StringBuilder();
        user.getRoles()
            .forEach(role -> roles.append(role.getName()).append(","));
        return new LoginResponse(Jwts.builder().setSubject(login.username)
            .claim("roles", roles).setIssuedAt(new Date())
            .signWith(SignatureAlgorithm.HS256, "accenture".getBytes("UTF-8"))
            .compact());
    }

    private static class UserLogin {

        public String username;

        public String password;
    }

    private static class LoginResponse {

        public String token;

        public LoginResponse(final String token) {
            this.token = token;
        }
    }
}

I tried to test my login web service but still not correct. Anyone could help me please to unit test my login service

UserControllerTest.java:

@RunWith(SpringRunner.class)
@WebMvcTest(value = UserController.class, secure = false)
public class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserRepository userRepository;

    User mockUser = new User("test", "test");

    String exampleUserJson = "{\"username\":\"toto\",\"password\":\"toto\"}";

    @Test
    public void loginTest() throws Exception {

        User mockUser = new User("test", "test");

    Mockito.when(
            userRepository.findByUsernameAndPassword(Mockito.anyString(),
                Mockito.anyString())).thenReturn(mockUser);

    // Send course as body to /students/Student1/courses
    RequestBuilder requestBuilder = MockMvcRequestBuilders
            .post("/user/login")
            .accept(MediaType.APPLICATION_JSON).content(exampleUserJson)
            .contentType(MediaType.APPLICATION_JSON);

    MvcResult result = mockMvc.perform(requestBuilder).andReturn();

    MockHttpServletResponse response = result.getResponse();

    assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), response.getStatus());

    assertEquals("http://localhost/user/login",
            response.getHeader(HttpHeaders.LOCATION));

    }

Body:
First of all understand how spring security works.

if you do not provide any configuration it will ask for authentication for every thing.

if you want to test authentication then what you just need to do is call any secure api with username and password like below,

 curl -v http://localhost:9090/mynet/ -u admin:admin12344 -c D:\cookies.txt -H "Accept: application/json"

Success senario : In above example i have called secured endpoint and get a cookie in response with  HTTP/1.1 200 if authentication is success which you can use for further call as below,

curl -v http://localhost:9090/mynet/customers -b D:\cookies.txt

Failure scenario : We get  HTTP/1.1 401 with json

{"timestamp":1496645081468,"status":401,"error":"Unauthorized","message":"No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken","path":"/mynet/"}

Note : I know you need to check above call using java code instead curl. I have used this just to explain concept.


问:
onblur taking last clicked value not taking current clicked value?
I am using onblur event to get the value of date in datepicker. Here is my control:

<input placeholder="MM/DAY/YEAR" data-bind="value: CustomerBookingTbl.PickUpDate" class="input date" name="pickupdate" onblur="UpdatePrice(this)" type="text" required>
```

<p>and here is my function:</p>

<pre class="lang-js prettyprint-override"><code>function UpdatePrice(_this)
{
    console.log(_this.value);
}
</code>```

When I clicked on 06/07/2017 then it takes null. Afterward, I clicked on  06/07/2017 then it takes 06/06/2017 as a value.

I am attaching the image also

答:
Check out events provided by datePicker

Datepicker triggers a number of events in certain circumstances. All
  events have extra data attached to the event object that is passed to
  any event handlers

You could use this event to track changeDate event of date

changeDate

Fired when the date is changed.

```<code>$("YOUR_DATE_PICKER").on("changeDate", function(e) {
    //// `e` here contains the extra attributes
    alert('hey');
});
</code>```

Check this fiddle

Body:
I am using onblur event to get the value of date in datepicker. Here is my control:

<input placeholder="MM/DAY/YEAR" data-bind="value: CustomerBookingTbl.PickUpDate" class="input date" name="pickupdate" onblur="UpdatePrice(this)" type="text" required>

and here is my function:

function UpdatePrice(_this)
{
    console.log(_this.value);
}

When I clicked on 06/07/2017 then it takes null. Afterward, I clicked on  06/07/2017 then it takes 06/06/2017 as a value.

I am attaching the image also

Body:
Check out events provided by datePicker

Datepicker triggers a number of events in certain circumstances. All
  events have extra data attached to the event object that is passed to
  any event handlers

You could use this event to track changeDate event of date

changeDate

Fired when the date is changed.

$("YOUR_DATE_PICKER").on("changeDate", function(e) {
    //// `e` here contains the extra attributes
    alert('hey');
});

Check this fiddle


问:
Unable to locate input element under div in Selenium
I am trying to located input element "mpcname" in js file which is under div and table elements.

The code I have written to locate the element is as follows but is not detecting the Input element with the name mpcName in it.

```<code>Driver.FindElement(By.XPath(".//input[contains(.,'mpcName')]"));
</code>```

The HTML code looks like below.

```<code><div enable-tooltips="" class="ng-scope">
<form name="InstanceDetailForm" ng-submit="doApply()" novalidate="" class="ng-pristine ng-invalid ng-invalid-required ng-valid-unnamed ng-valid-maxlength ng-valid-not-integer">
    <table class="table-condensed" style="width: 100%;">
        <tbody><tr>
            <td></td>
        </tr>
        <tr>
            <td>
                <table style="width: 100%;">
                    <tbody><tr>
                        <td class="pull-left">
                            <h4 class="ng-binding">Controller Configuration<b ng-show="InstanceIsDirty()" class="ng-hide"> *</b></h4>
                        </td>

                        <td class="pull-right">
                            <button id="btnApply" type="submit" class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title="Save an APC instance">
                                <span class="glyphicon glyphicon-save"></span> Apply
                            </button>

                            <button id="btnExportConfig" type="button" class="btn btn-primary" ng-click="goToInstanceList()" data-toggle="tooltip" data-placement="bottom" title="Cancel save and redirect to APC instance list page.">
                                <span class="glyphicon glyphicon-remove"></span> Cancel
                            </button>
                        </td>
                    </tr>
                </tbody></table>
            </td>
        </tr>
        <tr>
            <td>
                <table style="width: 100%" class="table-condensed table-striped  table-bordered">
                    <tbody><tr>
                        <td>Name</td>
                        <td>
                            **<input id="mpcname" name="mpcname" ng-model="mpcname" value="" ng-required="true" is-named="" size="50" autocomplete="off" ng-disabled="!allowEditInstanceName(mpcname,state)" class="ng-pristine ng-empty ng-invalid ng-invalid-required ng-valid-unnamed ng-touched" required="required" type="text">**
</code>```

答:
following code may be helpful

Driver.FindElement(By.XPath(".//input[contains(@id,'mpc')]");

Driver.FindElement(By.XPath(".//input[contains(@class,'ng-pris')]");

Body:
I am trying to located input element "mpcname" in js file which is under div and table elements.

The code I have written to locate the element is as follows but is not detecting the Input element with the name mpcName in it.

Driver.FindElement(By.XPath(".//input[contains(.,'mpcName')]"));

The HTML code looks like below.

<form name="InstanceDetailForm" ng-submit="doApply()" novalidate="" class="ng-pristine ng-invalid ng-invalid-required ng-valid-unnamed ng-valid-maxlength ng-valid-not-integer">

Controller Configuration *

                            <button id="btnApply" type="submit" class="btn btn-primary" data-toggle="tooltip" data-placement="bottom" title="Save an APC instance">
                                 Apply
                            </button>

                            <button id="btnExportConfig" type="button" class="btn btn-primary" ng-click="goToInstanceList()" data-toggle="tooltip" data-placement="bottom" title="Cancel save and redirect to APC instance list page.">
                                 Cancel
                            </button>

                        Name

                            **<input id="mpcname" name="mpcname" ng-model="mpcname" value="" ng-required="true" is-named="" size="50" autocomplete="off" ng-disabled="!allowEditInstanceName(mpcname,state)" class="ng-pristine ng-empty ng-invalid ng-invalid-required ng-valid-unnamed ng-touched" required="required" type="text">**


问:
Casting Const to non Const in c
I'm working on a school project in which I need to reproduce many of the C library functions. I'm just struggling with one specific aspect of it.

If you look at the man page for memchr you will see that it takes a const void * as input and returns a plain void *. I would assume that somewhere in the function they are casting from const to non const for the return variable.

However, when I do this (clang -Weverything +Werror) it won't compile. It works without the -Weverything tag but I would prefer to use it if possible anyway.

Is there any "correct" way to do this?

答:
The problem is unwanted GCC-style (Clang included) diagnostic triggered by the -Wcast-qual option in a specific place (-Weverything includes -Wcast-qual). The solution is to disable just -Wcast-qual in just that place.

```<code>#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
#endif
    void* non_const_ptr = (void*)const_ptr;
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
</code>```

A cast to a non-pointer type and back to a pointer type would inhibit all kinds of useful diagnostics wholesale and thus defeat the purpose of -Weverything.

#ifdef __GNUC__ is included for more portability. Some compilers are known to warn about pragmas they don't recognise, unless such pragmas are #ifdefed out.

Title: Casting Const to non Const in c

Body:
The problem is unwanted GCC-style (Clang included) diagnostic triggered by the -Wcast-qual option in a specific place (-Weverything includes -Wcast-qual). The solution is to disable just -Wcast-qual in just that place.

#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-qual"
#endif
    void* non_const_ptr = (void*)const_ptr;
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif

A cast to a non-pointer type and back to a pointer type would inhibit all kinds of useful diagnostics wholesale and thus defeat the purpose of -Weverything.

#ifdef __GNUC__ is included for more portability. Some compilers are known to warn about pragmas they don't recognise, unless such pragmas are #ifdefed out.


问:
how to create a service in python in windows?
I want to run a service in windows which will keep running in background and will run a cron with specific time.

how i can do that in windows using python?

答:
A combination of cx_freeze and srvany could do the job.

See this for srvany usage (replace dropbox with your exe)

ContentLicense: CC BY-SA 2.5


问:
Position:Fixed; adding a small amount of blank space below it
http://tylerh.info, I have a fixed navigation bar. But whenever I use the attribute "position:fixed;" it leaves a small amount of space below it, causing my title to not border up with it. However, this doesn't happen with the attribute taken out.

Thanks!

CSS:

```<code>.qmmc .qmdivider{
display:block;
font-size:1px;
border-width:0px;
border-style:solid;
position:relative;
z-index:1;
}

.qmmc .qmdividery{
float:left;
width:0px;
}

.qmmc .qmtitle{
display:block;
cursor:default;
white-space:nowrap;
position:relative;
z-index:1;
}

.qmclear {
font-size:1px;
height:0px;
width:0px;
clear:left;
line-height:0px;
display:block;
float:none !important;
}

.qmmc {
position:relative;
z-index:10;}

.qmmc a, .qmmc li {
float:left;
display:block;
white-space:nowrap;
position:relative;
z-index:1;
}

.qmmc div a, .qmmc ul a, .qmmc ul li {
float:none;
}

.qmsh div a {
float:left;}.qmmc div{visibility:hidden;position:absolute;}.qmmc li {z-index:auto;}.qmmc ul {left:-10000px;position:absolute;z-index:10;}.qmmc, .qmmc ul {list-style:none;padding:0px;margin:0px;}.qmmc li a {float:none}.qmmc li:hover>ul{left:auto;}#qm0 ul {top:100%;}#qm0 ul li:hover>ul{top:0px;left:100%;}

    #qm0
    {
                background-image: linear-gradient(bottom, #363636 19%, #1A1A1A 53%, #000000 80%);
        background-image: -o-linear-gradient(bottom, #363636 19%, #1A1A1A 53%, #000000 80%);
        background-image: -moz-linear-gradient(bottom, #363636 19%, #1A1A1A 53%, #000000 80%);
        background-image: -webkit-linear-gradient(bottom, #363636 19%, #1A1A1A 53%, #000000 80%);
        background-image: -ms-linear-gradient(bottom, #363636 19%, #1A1A1A 53%, #000000 80%);
        padding-bottom: 4.5px;
        position:fixed;
        border-color:#A2BFE9;
        margin-top: -4.7em;
        position:fixed;
        width: 100%;
        height: 50px;
        border-bottom: 1px solid #00A3EF;
    }

    #qm0 a
    {
        text-align: center;
        padding-top: 18px;
        padding-bottom: 18px;
        padding-left: 18px;
        padding-right: 18px;
        color:#FFFFFF;
        font-family:Karla;
        font-size:100%;
        text-decoration:none;

    }

    #qm0 a:hover
    {
           background-image: -moz-linear-gradient(bottom, #5465FF 0%, #00A3EF 100%);
   background-image: -ms-linear-gradient(bottom, #5465FF 0%, #00A3EF 100%);
   background-image: -o-linear-gradient(bottom, #5465FF 0%, #00A3EF 100%);
   background-image: -webkit-linear-gradient(bottom, #5465FF 0%, #00A3EF 100%);
   background-image: linear-gradient(bottom, #5465FF 0%, #00A3EF 100%);
   border-bottom-color:#000000;
   border-bottom-style:solid;
    }

    body #qm0 .qmactive, body #qm0 .qmactive:hover
    {
        background-color:#808080;
        text-decoration:underline;
        font-size: 80%;
    }

    #qm0 div, #qm0 ul
    {   padding-top:4px;
        padding-bottom:4px;
        margin:0px 0px 0px -1px;
        background-color:#808080;
        border-width:4px 1px 1px;
        border-style:solid;
        border-color:#285DA8;
    }

    #qm0 div a, #qm0 ul a
    {
        padding:2px 40px 2px 5px;
        border-width:0px;
        border-style:none;
    }

        #qm0 div a:hover, #qm0 ul a:hover
        <ul id="qm0" class="qmmc">

div#header {
    width: 100%;
    margin-bottom: 20px;
    padding-top: 1px;
    /*gradients */
    background-image: -ms-radial-gradient(center, circle farthest-corner, #006AD4 0%, #2500A1 100%);
    background-image: -moz-radial-gradient(center, circle farthest-corner, #006AD4 0%, #2500A1 100%);
    background-image: -o-radial-gradient(center, circle farthest-corner, #006AD4 0%, #2500A1 100%);
    background-image: -webkit-gradient(radial, center center, 0, center center, 506, color-stop(0, #006AD4), color-stop(1, #2500A1));
    background-image: -webkit-radial-gradient(center, circle farthest-corner, #006AD4 0%, #2500A1 100%);
    background-image: radial-gradient(circle farthest-corner at center, #006AD4 0%, #2500A1 100%);
    /*end gradients*/
    border-bottom: solid 2px #808080;
    padding-top:60px;
}
</code>```

Html:

```<code><li><a class="qmparent" href="/">Home</a></li>
<li><a class="qmparent" href="/?page_id=7">Ask a Question</a></li>

<li><a class="qmparent" href="javascript:void(0)">Menu3</a>

    <ul>
    <li><a href="javascript:void(0)">Placeholder1</a> </li>

    <li><a href="javascript:void(0)">Placeholder1</a></li>

    <li><a href="javascript:void(0)">Placeholder2</a></li>
    <li><a href="javascript:void(0)">Placeholder3</a></li>
    <li><a href="javascript:void(0)">Placeholder4</a></li>
    <li><a href="javascript:void(0)">Placeholder5</a></li>
    <li><a href="javascript:void(0)">Placeholder6</a></li>
    </ul></li>

<li><a class="qmparent" href="javascript:void(0)">Categories</a>

    <ul>
    <?php wp_list_categories('title_li=&orderby=name&use_desc_for_title=1&hierarchical=1') ?>

    </ul></li>{
        text-decoration:underline;
    }
</code>```

答:
I had the same problem. After applied position:fixed to an element, a margin of 8px is somehow applied to the parent element, so I styled the parent element to margin:0, and it's resolved.(Chrome)

Here's the example

```<code><body style="margin:0"><!-- the parent element -->
    <div style="position:fixed:background-color:grey;width:100%">
        Hello World
    </div>
</body>
</code>```

The margin:8px interpreted by browser when using position:fixed

Body:
http://tylerh.info, I have a fixed navigation bar. But whenever I use the attribute "position:fixed;" it leaves a small amount of space below it, causing my title to not border up with it. However, this doesn't happen with the attribute taken out.

Thanks!

CSS:

.qmmc .qmdivider{
display:block;
font-size:1px;
border-width:0px;
border-style:solid;
position:relative;
z-index:1;
}

.qmmc .qmdividery{
float:left;
width:0px;
}

.qmmc .qmtitle{
display:block;
cursor:default;
white-space:nowrap;
position:relative;
z-index:1;
}

.qmclear {
font-size:1px;
height:0px;
width:0px;
clear:left;
line-height:0px;
display:block;
float:none !important;
}

.qmmc {
position:relative;
z-index:10;}

.qmmc a, .qmmc li {
float:left;
display:block;
white-space:nowrap;
position:relative;
z-index:1;
}

.qmmc div a, .qmmc ul a, .qmmc ul li {
float:none;
}

.qmsh div a {
float:left;}.qmmc div{visibility:hidden;position:absolute;}.qmmc li {z-index:auto;}.qmmc ul {left:-10000px;position:absolute;z-index:10;}.qmmc, .qmmc ul {list-style:none;padding:0px;margin:0px;}.qmmc li a {float:none}.qmmc li:hover>ul{left:auto;}#qm0 ul {top:100%;}#qm0 ul li:hover>ul{top:0px;left:100%;}

    #qm0
    {
                background-image: linear-gradient(bottom, #363636 19%, #1A1A1A 53%, #000000 80%);
        background-image: -o-linear-gradient(bottom, #363636 19%, #1A1A1A 53%, #000000 80%);
        background-image: -moz-linear-gradient(bottom, #363636 19%, #1A1A1A 53%, #000000 80%);
        background-image: -webkit-linear-gradient(bottom, #363636 19%, #1A1A1A 53%, #000000 80%);
        background-image: -ms-linear-gradient(bottom, #363636 19%, #1A1A1A 53%, #000000 80%);
        padding-bottom: 4.5px;
        position:fixed;
        border-color:#A2BFE9;
        margin-top: -4.7em;
        position:fixed;
        width: 100%;
        height: 50px;
        border-bottom: 1px solid #00A3EF;
    }

    #qm0 a
    {
        text-align: center;
        padding-top: 18px;
        padding-bottom: 18px;
        padding-left: 18px;
        padding-right: 18px;
        color:#FFFFFF;
        font-family:Karla;
        font-size:100%;
        text-decoration:none;

    }

    #qm0 a:hover
    {
           background-image: -moz-linear-gradient(bottom, #5465FF 0%, #00A3EF 100%);
   background-image: -ms-linear-gradient(bottom, #5465FF 0%, #00A3EF 100%);
   background-image: -o-linear-gradient(bottom, #5465FF 0%, #00A3EF 100%);
   background-image: -webkit-linear-gradient(bottom, #5465FF 0%, #00A3EF 100%);
   background-image: linear-gradient(bottom, #5465FF 0%, #00A3EF 100%);
   border-bottom-color:#000000;
   border-bottom-style:solid;
    }

    body #qm0 .qmactive, body #qm0 .qmactive:hover
    {
        background-color:#808080;
        text-decoration:underline;
        font-size: 80%;
    }

    #qm0 div, #qm0 ul
    {   padding-top:4px;
        padding-bottom:4px;
        margin:0px 0px 0px -1px;
        background-color:#808080;
        border-width:4px 1px 1px;
        border-style:solid;
        border-color:#285DA8;
    }

    #qm0 div a, #qm0 ul a
    {
        padding:2px 40px 2px 5px;
        border-width:0px;
        border-style:none;
    }

        #qm0 div a:hover, #qm0 ul a:hover

div#header {
    width: 100%;
    margin-bottom: 20px;
    padding-top: 1px;
    /*gradients */
    background-image: -ms-radial-gradient(center, circle farthest-corner, #006AD4 0%, #2500A1 100%);
    background-image: -moz-radial-gradient(center, circle farthest-corner, #006AD4 0%, #2500A1 100%);
    background-image: -o-radial-gradient(center, circle farthest-corner, #006AD4 0%, #2500A1 100%);
    background-image: -webkit-gradient(radial, center center, 0, center center, 506, color-stop(0, #006AD4), color-stop(1, #2500A1));
    background-image: -webkit-radial-gradient(center, circle farthest-corner, #006AD4 0%, #2500A1 100%);
    background-image: radial-gradient(circle farthest-corner at center, #006AD4 0%, #2500A1 100%);
    /*end gradients*/
    border-bottom: solid 2px #808080;
    padding-top:60px;
}

Html:

Home

Ask a Question

Menu3

Placeholder1

Placeholder1

Placeholder2

Placeholder3

Placeholder4

Placeholder5

Placeholder6

Categories

    <?php wp_list_categories('title_li=&orderby=name&use_desc_for_title=1&hierarchical=1') ?>

{
        text-decoration:underline;
    }

Body:
I had the same problem. After applied position:fixed to an element, a margin of 8px is somehow applied to the parent element, so I styled the parent element to margin:0, and it's resolved.(Chrome)

Here's the example

<body style="margin:0"><!-- the parent element -->
    <div style="position:fixed:background-color:grey;width:100%">
        Hello World
    </div>
</body>

The margin:8px interpreted by browser when using position:fixed


问:
Making a prime generator
This is supposed to be a prime generator. I try running this but it doesn't print out the integers. The program will also end right away. I don't know if its running  </p>

```<code>def prime_gen():

    start = 1

    while start:

        if start % start == 0:
            print(start)

            start += 1
</code>```

答:
You can do something like:</p>

```<code>def prime_gen(limit):
    current = 2 # 1 is not exactly prime
    primes = []
    while current <= limit:
        isPrime = True
        for p in primes:
            if current % p == 0:
                isPrime = False
                break
        if isPrime:
            primes.append(current)
            print current, ", ",
        current += 1
    return primes
</code>```

Title: Making a prime generator

Body:
This is supposed to be a prime generator. I try running this but it doesn't print out the integers. The program will also end right away. I don't know if its running

def prime_gen():

    start = 1

    while start:

        if start % start == 0:
            print(start)

            start += 1

Body:
You can do something like:

def prime_gen(limit):
    current = 2 # 1 is not exactly prime
    primes = []
    while current <= limit:
        isPrime = True
        for p in primes:
            if current % p == 0:
                isPrime = False
                break
        if isPrime:
            primes.append(current)
            print current, ", ",
        current += 1
    return primes


问:
Reading a .txt file using Scanner class in Java
I am working on a Java program that reads a text file line-by-line, each with a number, takes each number throws it into an array, then tries and use insertion sort to sort the array. I need help with getting the program to read the text file.

I am getting the following error messages:

```<code>java.io.FileNotFoundException: 10_Random (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at insertionSort.main(insertionSort.java:14)
</code>```

I have a copy of the .txt file in my "src" "bin" and main project folder but it still cannot find the file. I am using Eclipse by the way.

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class insertionSort {

public static void main(String[] args) {

    File file = new File("10_Random");

    try {

        Scanner sc = new Scanner(file);

        while (sc.hasNextLine()) {
            int i = sc.nextInt();
            System.out.println(i);
        }
        sc.close();
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
 }
}
</code>```

答:
At first check the file address, it must be beside your .java file or in any address that you define in classpath environment variable. When you check this then try below.

you must use a file name by it's extension in File object constructor, as an example:

File myFile = new File("test.txt");

but there is a better way to use it inside Scanner object by pass the filename absolute address, as an example:

Scanner sc = new Scanner(Paths.get("test.txt"));

in this way you must import java.nio.file.Paths as well.

Body:
I am working on a Java program that reads a text file line-by-line, each with a number, takes each number throws it into an array, then tries and use insertion sort to sort the array. I need help with getting the program to read the text file.

I am getting the following error messages:

java.io.FileNotFoundException: 10_Random (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at insertionSort.main(insertionSort.java:14)

I have a copy of the .txt file in my "src" "bin" and main project folder but it still cannot find the file. I am using Eclipse by the way.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class insertionSort {

public static void main(String[] args) {

    File file = new File("10_Random");

    try {

        Scanner sc = new Scanner(file);

        while (sc.hasNextLine()) {
            int i = sc.nextInt();
            System.out.println(i);
        }
        sc.close();
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }
 }
}


问:
Cannot read property 'post' of undefined - Angular 2
Below is the code snippet from my component file

```<code>import { Component,Injectable,Inject,OnInit, OnDestroy, EventEmitter,Output } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/switchMap';
...
@Injectable()
export class MyComponent {
    constructor (private http: Http) { }
    saveDetails()
    {
        var response:any;
        var body       = customer_details;
        var headers    = new Headers({ 'Content-Type': 'application/json' });
        var options    = new RequestOptions({ headers: headers });
        this.http.post("/user/add-customer-details", body, options)
            .map((res:Response) => res.json()).subscribe(
                data => { response = data},
                err => console.error(err),
                () => {
                    console.log(response);
                }
        );
    }
}
</code>```

There is no compilation error or any other error but
when I am calling the post method it's saying Cannot read property 'post' of undefined so I tried console.log(this.http); right before the post method call, then its showing undefined in the browser console, I tried all the possible solutions but unable to understand why it's not working, please help...

thanks in advance!!!

答:
After spending a few hours in scratching my head and reading all the possible articles, answers, documentation and possibly everything available on the Internet, finally I found the solution.

I have just changed my constructor from

```<code>constructor (private http: Http) { }
</code>```

To

```<code>constructor (@Inject(Http) private http:Http) { }
</code>```

Though @Inject is an Experimental decorator, It's working

Thank you everyone for helping me...

Body:
Below is the code snippet from my component file

import { Component,Injectable,Inject,OnInit, OnDestroy, EventEmitter,Output } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/switchMap';
...
@Injectable()
export class MyComponent {
    constructor (private http: Http) { }
    saveDetails()
    {
        var response:any;
        var body       = customer_details;
        var headers    = new Headers({ 'Content-Type': 'application/json' });
        var options    = new RequestOptions({ headers: headers });
        this.http.post("/user/add-customer-details", body, options)
            .map((res:Response) => res.json()).subscribe(
                data => { response = data},
                err => console.error(err),
                () => {
                    console.log(response);
                }
        );
    }
}

There is no compilation error or any other error but
when I am calling the post method it's saying Cannot read property 'post' of undefined so I tried console.log(this.http); right before the post method call, then its showing undefined in the browser console, I tried all the possible solutions but unable to understand why it's not working, please help...

thanks in advance!!!

Body:
After spending a few hours in scratching my head and reading all the possible articles, answers, documentation and possibly everything available on the Internet, finally I found the solution.

I have just changed my constructor from

constructor (private http: Http) { }

To

constructor (@Inject(Http) private http:Http) { }

Though @Inject is an Experimental decorator, It's working

Thank you everyone for helping me...


问:
Android MVP pattern integrating third party SDKs
I am learning MVP pattern by following Google sample https://github.com/googlesamples/android-architecture/tree/todo-mvp.
Now I need to integrate third party SDK like Gigya for my app login. To initialize Gigya I need to write
GSAPI.getInstance().initialize(getActivity(), API_Key);. So where I am suppose to write this, that is in Fragment or Presenter. If in presenter then is it good approach to use activity context in presenter?

答:
I would strongly suggest that the presenter should have no concept of the Android Context (or any other Android classes). By completely separating your Presenter code from the Android system code you are able to test it on the JVM without the complication of mocking system components.

You have two ways:

Use Dagger

Or create a repository interface

I have never done this so i cannot explain it in detail.Search the net
for my two suggested ways,Hope it helps.


问:
Issues in writing multiple if conditions inside vlookup
I have two sheets.

1st sheet has an unique information in the first two columns about bike and its repair date (DD/MM/YYYY) format.

2nd sheet has multiple duplicate entries in the first three columns about bike and its repair date (DD/MM/YYYY) and diagnostic date (DD/MM/YYYY).

Now using vlookup, I have find the diagnostic date, can be equal as the repair date or just before the repair date for the particular bike.

ex:-

for a bike, I have a repair date as 20/02/2017. but with three different diagnostic dates such as (21/02/2017, 27/05/2017 and 28/12/2015).

so Finally I would expect the answer as the follows:-

```<code>Bike     Repair date              Diagnostic date

Name     20/02/2017                 28/12/2015
</code>```

I was managed to do for the entries which has same year for the repair and diagnostic date.

In the prescribed example, It is different.

I would be happy If you help me on this.......

答:
You need INDEX/MATCH because it works with (composed) arrays, while VLOOKUP works only with ranges. The following "array formula" for Sheet2!C2 (enter in C2 then type Ctrl+Shift+Enter, then copy down in column C) uses a composed boolean array to match multiple criteria, then indexes the first successful match in column C (Diagnostic date) of Sheet1.

```<code>'Sheet2!C2:
=INDEX(Sheet1!C:C,MATCH(1,(Sheet1!A:A=A2)*(Sheet1!B:B=B2)*(Sheet1!C:C<=B2),0))
'Ctrl+Shift+Enter
</code>```

p.s.: it will be much faster if you limit the columns to some known upperbound on the row, i.e C2:C1000 intead of C:C and the same for B:B and A:A.

Body:
I have two sheets.

1st sheet has an unique information in the first two columns about bike and its repair date (DD/MM/YYYY) format.

2nd sheet has multiple duplicate entries in the first three columns about bike and its repair date (DD/MM/YYYY) and diagnostic date (DD/MM/YYYY).

Now using vlookup, I have find the diagnostic date, can be equal as the repair date or just before the repair date for the particular bike.

ex:-

for a bike, I have a repair date as 20/02/2017. but with three different diagnostic dates such as (21/02/2017, 27/05/2017 and 28/12/2015).

so Finally I would expect the answer as the follows:-

Bike     Repair date              Diagnostic date

Name     20/02/2017                 28/12/2015

I was managed to do for the entries which has same year for the repair and diagnostic date.

In the prescribed example, It is different.

I would be happy If you help me on this.......

Body:
You need INDEX/MATCH because it works with (composed) arrays, while VLOOKUP works only with ranges. The following "array formula" for Sheet2!C2 (enter in C2 then type Ctrl+Shift+Enter, then copy down in column C) uses a composed boolean array to match multiple criteria, then indexes the first successful match in column C (Diagnostic date) of Sheet1.

'Sheet2!C2:
=INDEX(Sheet1!C:C,MATCH(1,(Sheet1!A:A=A2)*(Sheet1!B:B=B2)*(Sheet1!C:C<=B2),0))
'Ctrl+Shift+Enter

p.s.: it will be much faster if you limit the columns to some known upperbound on the row, i.e C2:C1000 intead of C:C and the same for B:B and A:A.


问:
How to get Dom tree in GeckoFX
I started to play with GeckoFX. Unfortunately I didn't found any big documentation for that. I need to get DOM tree for the page. Iterate every element and get it's information. Can someone please help me?</p>

答:
I know this is an older question but someone may still be looking for an answer.    </p>

```<code>GeckoNodeCollection nodes = geckoWebBrowser1.Document.GetElementsByName("*");
foreach(GeckoNode node in nodes)
{
    //do whatever you need to do with the node ..
    GeckoElement element = node as GeckoElement;
    //..
}
</code>```

Title: How to get Dom tree in GeckoFX

Body:
I know this is an older question but someone may still be looking for an answer.

GeckoNodeCollection nodes = geckoWebBrowser1.Document.GetElementsByName("*");
foreach(GeckoNode node in nodes)
{
    //do whatever you need to do with the node ..
    GeckoElement element = node as GeckoElement;
    //..
}


问:
Why is Redis returning 2 different types when the same key is accessed by 2 different windows?
I'm using Python and the redis-py Python client to talk to the same Redis, which is provided by Redis Labs as Redis(e) Cloud. In the terminal, a key is retrieved and the value is returned as a string type.

Whereas when I run a code file in my IDE, the same code returns a bytes object.

I don't understand why they are returning different types. I blocked out the Redis host and port details, but they are accessing the same Redis, and I did not change anything between taking those 2 screenshots.

答:
This is not a redis issue but a difference between Py2 and Py3.

Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings. All text is Unicode; however encoded Unicode is represented as binary data. The type used to hold text is str, the type used to hold data is bytes. The biggest difference with the 2.x situation is that any attempt to mix text and data in Python 3.0 raises TypeError, whereas if you were to mix Unicode and 8-bit strings in Python 2.x, it would work if the 8-bit string happened to contain only 7-bit (ASCII) bytes, but you would get UnicodeDecodeError if it contained non-ASCII values. This value-specific behavior has caused numerous sad faces over the years.


问:
Install and use Protocol Buffers for Java on Windows
The documentation for using Google Protobuf for Java in Windows environment is not very friendly, scattered and puts the new user into confusion. Here is a small attempt to assist the new explorers.</p>

答:
Download the Win32 binary from https://github.com/google/protobuf/releases - At the time of writing, the latest is v3.3.0 and hence appropriate binary is https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-win32.zip

Extract this zip file into a directory and add the bin directory under this into the system path environment variable.

Checkout the source code from Github repository - As v3.3.0 is the latest release, checkout the same tag rather than master.

Copy protoc.exe from step 1 and paste it under src directory in the checked out location.

Continue to run maven tasks as provided here - https://github.com/google/protobuf/tree/master/java

To run the examples in the library -

Copy the protoc.exe from step 1 above to a preferred location and ensure that location is added into the Path environment variable. To ensure it is done properly, open a new command prompt and run protoc --version to see the appropriate version you installed.

Create the Java package for protocol format given with the examples - defined in addressbook.proto as explained here - protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/addressbook.proto - This generates the required AddressBookProtos class under the package com.example.tutorial which is required for compiling the example code.

Once the generated code is in the example classpath, the code can be executed.


问:
Klocwork 9 vs Klocwork 12
For the same code base, when executing klocwork, for two different versions of KW, we are getting difference in results.

For e.g. for a particular file, KW 9 is throwing the following error :

#6325: Infinite loop
"file Path"
Code: INFINITE_LOOP.LOCAL | Severity: Error (2) | State: Existing | Status: Analyze | Taxonomy: C and C++ | Owner: unowned

However, for KW 12, there is no such error.

Both the KW are on different machines so I suspect this may be due difference in configuration, but the configuration file "problems_default.pconf.xml" is same in both the cases.

Can someone help ?

答:
i can help you here. Klocwork is keep on tuning/adding checkers to detect all possible vulnerabilities.
the Checker "INFINITE_LOOP.LOCAL" got tuned/modified on Klocwork v10.1 and v12.0 to get accurate issue rate. This might have caused the difference in results. Please revert back if you need more clarification. </p>

Title: Klocwork 9 vs Klocwork 12


问:
table tag is adding extra td in tr tag automatically
Hi I am just going through a mysterious condition in my code.
single  Or  in chrome and Mozilla Firefox don't know why.

```<code>        <div class="right_content">
                <table style="width: 100%; height: 200px; margin-top: 5px;" id="mainTable">
                    <tr>
                        <th colspan="1">Participant Name</th>
                        <td colspan="1">${fullName}<td>
                        <th colspan="1">Role</th>
                        <td colspan="1">${role}<td>
                        <th colspan="1">Brand/Location</th>
                        <td colspan="1">${location}<td>
                    </tr>
                    <tr>
                        <th>Goal Text</th>
                        <td><input name="goalText" id="goalText" name="goalText"
                            class="text_field" size="40" maxlength="95" tabindex="1"
                            title="Minimum Rating For This Competency" /></td>
                        <th>Assessment Center</th>
                        <td><select name="assessmentCenterId" id="assessmentCenterId" class="text_field"
                            tabindex="2" title="Select Assessment Center">
                                <option value="-1">--Select Assessment Center--</option>
                                <c:forEach items="${acList}" var="singleAC" varStatus="sts">
                                <c:choose>
                                <c:when test="${singleAC.id eq 0}">
                                <option value="${singleAC.id}" selected="selected">${singleAC.name} </option>
                                </c:when>
                                <c:otherwise>
                                <option value="${singleAC.id}">${singleAC.name}</option>
                                </c:otherwise>
                                </c:choose>
                                </c:forEach>
                        </select></td>

                        <th>Status</th>
                        <td><select name="status" id="status" class="text_field"
                            tabindex="3" title="Select Status Of IDP">
                                <option value="-1" selected="selected">--Select Status--</option>
                                <c:forEach items="${EnumIDPStatus}" var="singleStatus"
                                    varStatus="sts">
                                    <c:choose>
                                    <c:when test="${(singleStatus.key eq 0)  &&(mode eq 'Add')}">
                                    <option value="${singleStatus.key}" selected="selected">${singleStatus.value}</option>
                                    </c:when>
                                    <c:otherwise>
                                    <option value="${singleStatus.key}">${singleStatus.value}</option>
                                    </c:otherwise>
                                    </c:choose>
                                </c:forEach>
                        </select></td>
                    </tr>

                    <tr>
                        <th>Score</th>
                        <td><input type="text" name="score" id="score" class="text_field"
                            size="40" maxlength="95" tabindex="4" title="Score" /></td>
                        <th>Target Date</th>
                        <td><input type="text" name="targetDate" id="targetDate"
                            class="text_field"  title="Minimum Rating For This Competency" /></td>
                        <th>Extended Date</th>
                        <td><input type="text" name="extendedDate" id="extendedDate"
                            class="text_field"  /></td>
                    </tr>

                    <tr>
                        <th>Manger Comments</th>
                        <td><textarea name="managerComments" id="managerComments"
                                class="text_field" rows="5" cols="50" tabindex="7"
                                title="Minimum Rating For This Competency"></textarea></td>
                        <th>Assessor Comments</th>
                        <td><textarea name="assessorComments" id="assessorComments"
                                class="text_field" rows="5" cols="50" tabindex="8"
                                title="Minimum Rating For This Competency"></textarea></td>
                        <th>Participant Comments</th>
                        <td><textarea name="participantComments"
                                id="participantComments" class="text_field" rows="5" cols="50"
                                tabindex="9" title="Minimum Rating For This Competency"></textarea>
                        </td>
                    </tr>

                    <tr>
                        <td colspan="6" class="frm_footer_buttons"
                            style="text-align: center;"><input type="button"
                            name="btnsubmit" id="btnsubmit" class="frm_button"
                            value="<spring:message code='button.save' />" tabindex="10"
                            onclick="return errorPopup();" /> <input type="reset"
                            class="frm_button" value="Reset" tabindex="11" /> <input
                            type="button" class="frm_button"
                            value="<spring:message code='button.cancel'/>" tabindex="12"
                            onclick="submitRequest('showIDPList.html');" /></td>
                    </tr>
                </table>
        </div>
</code>```

答:
Make sure to always close your HTML tags properly.

Here's a part of your HTML:

```<code><tr>
    <th colspan="1">Participant Name</th>
    <td colspan="1">${fullName}<td>
    <th colspan="1">Role</th>
    <td colspan="1">${role}<td>
    <th colspan="1">Brand/Location</th>
    <td colspan="1">${location}<td>
</tr>
</code>```

Can you spot a problem?

Look carefully at your closing tags. Your  opening tags have proper 	 closing tags, but you  don't. They miss / in their closing tags which effectively means you open a new tag instead of closing the previous one.

Body:
Hi I am just going through a mysterious condition in my code.
single  Or  in chrome and Mozilla Firefox don't know why.

                        Participant Name
                        ${fullName}
                        Role
                        ${role}
                        Brand/Location
                        ${location}

                        Goal Text
                        <input name="goalText" id="goalText" name="goalText"
                            class="text_field" size="40" maxlength="95" tabindex="1"
                            title="Minimum Rating For This Competency" />
                        Assessment Center
                        <select name="assessmentCenterId" id="assessmentCenterId" class="text_field"
                            tabindex="2" title="Select Assessment Center">
                                <option value="-1">--Select Assessment Center--</option>
                                <c:forEach items="${acList}" var="singleAC" varStatus="sts">
                                <c:choose>
                                <c:when test="${singleAC.id eq 0}">
                                <option value="${singleAC.id}" selected="selected">${singleAC.name} </option>
                                </c:when>
                                <c:otherwise>
                                <option value="${singleAC.id}">${singleAC.name}</option>
                                </c:otherwise>
                                </c:choose>
                                </c:forEach>
                        </select>

                        Status
                        <select name="status" id="status" class="text_field"
                            tabindex="3" title="Select Status Of IDP">
                                <option value="-1" selected="selected">--Select Status--</option>
                                <c:forEach items="${EnumIDPStatus}" var="singleStatus"
                                    varStatus="sts">
                                    <c:choose>
                                    <c:when test="${(singleStatus.key eq 0)  &&(mode eq 'Add')}">
                                    <option value="${singleStatus.key}" selected="selected">${singleStatus.value}</option>
                                    </c:when>
                                    <c:otherwise>
                                    <option value="${singleStatus.key}">${singleStatus.value}</option>
                                    </c:otherwise>
                                    </c:choose>
                                </c:forEach>
                        </select>

                        Score
                        <input type="text" name="score" id="score" class="text_field"
                            size="40" maxlength="95" tabindex="4" title="Score" />
                        Target Date
                        <input type="text" name="targetDate" id="targetDate"
                            class="text_field"  title="Minimum Rating For This Competency" />
                        Extended Date
                        <input type="text" name="extendedDate" id="extendedDate"
                            class="text_field"  />

                        Manger Comments
                        <textarea name="managerComments" id="managerComments"
                                class="text_field" rows="5" cols="50" tabindex="7"
                                title="Minimum Rating For This Competency"></textarea>
                        Assessor Comments
                        <textarea name="assessorComments" id="assessorComments"
                                class="text_field" rows="5" cols="50" tabindex="8"
                                title="Minimum Rating For This Competency"></textarea>
                        Participant Comments
                        <textarea name="participantComments"
                                id="participantComments" class="text_field" rows="5" cols="50"
                                tabindex="9" title="Minimum Rating For This Competency"></textarea>

                        <input type="button"
                            name="btnsubmit" id="btnsubmit" class="frm_button"
                            value="<spring:message code='button.save' />" tabindex="10"
                            onclick="return errorPopup();" /> <input type="reset"
                            class="frm_button" value="Reset" tabindex="11" /> <input
                            type="button" class="frm_button"
                            value="<spring:message code='button.cancel'/>" tabindex="12"
                            onclick="submitRequest('showIDPList.html');" />

Body:
Make sure to always close your HTML tags properly.

Here's a part of your HTML:

<tr>
    <th colspan="1">Participant Name</th>
    <td colspan="1">${fullName}<td>
    <th colspan="1">Role</th>
    <td colspan="1">${role}<td>
    <th colspan="1">Brand/Location</th>
    <td colspan="1">${location}<td>
</tr>

Can you spot a problem?

Look carefully at your closing tags. Your <th> opening tags have proper </th> closing tags, but you <td> don't. They miss / in their closing tags which effectively means you open a new tag instead of closing the previous one.


问:
hide or show the data based on the dropdown value selected
I am working on angularjs application.
My requirement is to hide or show the data based on the dropdown list value selected. If i choose the option Show from dropdown list, i need to display the tab's data, if user selects 'Hide' from dropdown list, the content inside the tab should not be displayed.Please advice.

One approach i want to follow is ,by default the option should be Show in the dropdown list and the tab data should be available and when user selects hide, the tab content should be hidden or should ot display.
Please advice how to perform the same in angularjs.
Another one i was tring is, right now my select box doesn't show any selected option ,by default i want to make "Show" option selected.Please find the demo here

js code:

```<code>var myApp = angular.module('tabs', [ 'ui.bootstrap']);
myApp.controller('tabsctrl', function ($rootScope,$scope) {
          $rootScope.tabName ='MyTab Name';

    $rootScope.tabValue="tab1Value";
    $scope.applicationData = {};
    $scope.activeModule = "tab1Value";
    $scope.programModules=[{"tabName":"Tab1","tabValue":"tab1Value"},{"tabName":"Tab2","tabValue":"tab2Value"}];
    $scope.loadApplicationData = function(tabVal,tabName){
        $rootScope.tabName =tabName;
        alert("$rootScope.tabName :: "+$rootScope.tabName);
        $rootScope.tabValue=tabVal;
        $scope.activeModule = tabVal;

    };
    $scope.loadApplicationData($scope.activeModule,'Tab1');

});
myApp.controller('chapter',function($scope,$http){
    $scope.modelidchange = function () {
        $scope.id = $scope.selectedValue;

        alert($scope.id)
    }
});
</code>```

答:
You can use only only one controller to do these functionalities. One more thing instead of calling function to set default value, you could use ng-init in html page itself. And use ng-show instead of ng-if. cause, ng-if everytime it will create a DOM again and again once it is became true But ng-show only shows the hided part. so below code part that I have made changes. here you go,

var app = angular.module('app',[]);
            app.controller('tabCtrl',['$rootScope','$scope' ,function($rootScope,$scope){
                $rootScope.tabName ='MyTab Name';
                $rootScope.tabValue="tab1Value";
                $scope.applicationData = {};
                $scope.activeModule = "tab1Value";
                $scope.programModules=[{"tabName":"Tab1","tabValue":"tab1Value"},{"tabName":"Tab2","tabValue":"tab2Value"}];

                $scope.loadApplicationData = function(tabVal,tabName){
                    $rootScope.tabName =tabName;
                    if(tabName === 'Tab1'){
                        $scope.tab1Data = true;
                        $scope.tab2Data = false;
                    }else{
                        $scope.tab1Data = false;
                        $scope.tab2Data = true;
                    }
                    $rootScope.tabValue=tabVal;
                    $scope.activeModule = tabVal;
                };

                $scope.modelidchange = function () {
                    $scope.id = $scope.selectedValue;
                    if($scope.id === 'show'){
                       $scope.tab1 = true;
                       $scope.tab2 = true;
                    }else{
                        $scope.tab1 = false;
                        $scope.tab2 = false;
                    }
                };

        }]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
         <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.3.js"></script>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div ng-app="app" ng-controller="tabCtrl">

 Select a Option: <select ng-init="selectedValue = 'show'" ng-model="selectedValue"  ng-change="modelidchange()" >
    <option value="show">Show</option>
    <option value="hide">Hide</option>
</select> <br><br>

<div >
    <div class="top-tabs">
        <!-- Nav tabs -->
        <ul class="nav nav-tabs" role="tablist">
            <li role="presentation" class="{{ pg.tabValue == activeModule? 'active':''}}" ng-repeat="pg in programModules">
                {{pg.tabName}}
            </li>
        </ul>

        <div class="tab-content">
            <div  ng-init="tab1 = true;tab1Data = true " ng-show="tab1 === true && tab1Data === true" role="tabpanel" class="tab-pane active" id="tab1">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="panel panel-primary">
                            <div class="panel-heading">
                                Tab1 data
                            </div>This should be shown when user click tab1
                        </div>
                    </div>
                </div>
            </div>

            <div  ng-init="tab2 = true" ng-show="tab2 === true && tab2Data === true" role="tabpanel" class="tab-pane active" id="tab2">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="panel panel-primary">
                            <div class="panel-heading">
                                Tab2 data
                            </div>This should be shown when user click tab2
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div></code>```

Body:
I am working on angularjs application.
My requirement is to hide or show the data based on the dropdown list value selected. If i choose the option Show from dropdown list, i need to display the tab's data, if user selects 'Hide' from dropdown list, the content inside the tab should not be displayed.Please advice.

One approach i want to follow is ,by default the option should be Show in the dropdown list and the tab data should be available and when user selects hide, the tab content should be hidden or should ot display.
Please advice how to perform the same in angularjs.
Another one i was tring is, right now my select box doesn't show any selected option ,by default i want to make "Show" option selected.Please find the demo here

js code:

var myApp = angular.module('tabs', [ 'ui.bootstrap']);
myApp.controller('tabsctrl', function ($rootScope,$scope) {
          $rootScope.tabName ='MyTab Name';

    $rootScope.tabValue="tab1Value";
    $scope.applicationData = {};
    $scope.activeModule = "tab1Value";
    $scope.programModules=[{"tabName":"Tab1","tabValue":"tab1Value"},{"tabName":"Tab2","tabValue":"tab2Value"}];
    $scope.loadApplicationData = function(tabVal,tabName){
        $rootScope.tabName =tabName;
        alert("$rootScope.tabName :: "+$rootScope.tabName);
        $rootScope.tabValue=tabVal;
        $scope.activeModule = tabVal;

    };
    $scope.loadApplicationData($scope.activeModule,'Tab1');

});
myApp.controller('chapter',function($scope,$http){
    $scope.modelidchange = function () {
        $scope.id = $scope.selectedValue;

        alert($scope.id)
    }
});

Body:
You can use only only one controller to do these functionalities. One more thing instead of calling function to set default value, you could use ng-init in html page itself. And use ng-show instead of ng-if. cause, ng-if everytime it will create a DOM again and again once it is became true But ng-show only shows the hided part. so below code part that I have made changes. here you go,

var app = angular.module('app',[]);
            app.controller('tabCtrl',['$rootScope','$scope' ,function($rootScope,$scope){
                $rootScope.tabName ='MyTab Name';
                $rootScope.tabValue="tab1Value";
                $scope.applicationData = {};
                $scope.activeModule = "tab1Value";
                $scope.programModules=[{"tabName":"Tab1","tabValue":"tab1Value"},{"tabName":"Tab2","tabValue":"tab2Value"}];

                $scope.loadApplicationData = function(tabVal,tabName){
                    $rootScope.tabName =tabName;
                    if(tabName === 'Tab1'){
                        $scope.tab1Data = true;
                        $scope.tab2Data = false;
                    }else{
                        $scope.tab1Data = false;
                        $scope.tab2Data = true;
                    }
                    $rootScope.tabValue=tabVal;
                    $scope.activeModule = tabVal;
                };

                $scope.modelidchange = function () {
                    $scope.id = $scope.selectedValue;
                    if($scope.id === 'show'){
                       $scope.tab1 = true;
                       $scope.tab2 = true;
                    }else{
                        $scope.tab1 = false;
                        $scope.tab2 = false;
                    }
                };

        }]);

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
         <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.3.js"></script>
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <div ng-app="app" ng-controller="tabCtrl">

 Select a Option: <select ng-init="selectedValue = 'show'" ng-model="selectedValue"  ng-change="modelidchange()" >
    <option value="show">Show</option>
    <option value="hide">Hide</option>
</select> <br><br>

<div >
    <div class="top-tabs">
        <!-- Nav tabs -->
        <ul class="nav nav-tabs" role="tablist">
            <li role="presentation" class="{{ pg.tabValue == activeModule? 'active':''}}" ng-repeat="pg in programModules">
                <a href="javascript:void(0)" ng-click="loadApplicationData(pg.tabValue,pg.tabName)">{{pg.tabName}}</a>
            </li>
        </ul>

        <div class="tab-content">
            <div  ng-init="tab1 = true;tab1Data = true " ng-show="tab1 === true && tab1Data === true" role="tabpanel" class="tab-pane active" id="tab1">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="panel panel-primary">
                            <div class="panel-heading">
                                Tab1 data
                            </div>This should be shown when user click tab1
                        </div>
                    </div>
                </div>
            </div>

            <div  ng-init="tab2 = true" ng-show="tab2 === true && tab2Data === true" role="tabpanel" class="tab-pane active" id="tab2">
                <div class="row">
                    <div class="col-sm-12">
                        <div class="panel panel-primary">
                            <div class="panel-heading">
                                Tab2 data
                            </div>This should be shown when user click tab2
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>


问:
Raw query changes does not appeared in Entity Object c#
I've using raw query for update status of a column but after update, changes not appeared in Entity Object:</p>

```<code>CDIMDEntities oDB = new CDIMDEntities();
SystemYear oSY = oDB.SystemYears.FirstOrDefault(x => x.Year == Year);
if (oSY != null)
{
    string thsQuery = "UPDATE SystemYears SET  " + Column + " = {0} WHERE Id = {1}";
    oDB.Database.ExecuteSqlCommand(thsQuery, Status, oSY.Id);
    //After this changes appeared in database
    // But when again when trying get object ,It's showing old values
    oSY = oDB.SystemYears.FirstOrDefault(x => x.Id == oSY.Id);
    this.SystemYearRep.SaveSystemYear(oSY);
}
</code>```

答:
That happens because Entity Framework in certain sense "caches" entities. When you make second query

```<code>oSY = oDB.SystemYears.FirstOrDefault(x => x.Id == oSY.Id);
</code>```

EF will make a database query and it will receive updated values from database. But, after doing that it will notice that there is already SystemYear with given id attached to the context (that one you received with a first query oDB.SystemYears.FirstOrDefault(x => x.Year == Year)). So it will discard new entity and return old one (already attached, with old values) back to you. To force EF refresh entity - use Reload:

```<code>ctx.Entry(oSY).Reload(); // no need to make second query, will be done for you
</code>```

or just use fresh context.

Body:
I've using raw query for update status of a column but after update, changes not appeared in Entity Object:

CDIMDEntities oDB = new CDIMDEntities();
SystemYear oSY = oDB.SystemYears.FirstOrDefault(x => x.Year == Year);
if (oSY != null)
{
    string thsQuery = "UPDATE SystemYears SET  " + Column + " = {0} WHERE Id = {1}";
    oDB.Database.ExecuteSqlCommand(thsQuery, Status, oSY.Id);
    //After this changes appeared in database
    // But when again when trying get object ,It's showing old values
    oSY = oDB.SystemYears.FirstOrDefault(x => x.Id == oSY.Id);
    this.SystemYearRep.SaveSystemYear(oSY);
}

Body:
That happens because Entity Framework in certain sense "caches" entities. When you make second query

oSY = oDB.SystemYears.FirstOrDefault(x => x.Id == oSY.Id);

EF will make a database query and it will receive updated values from database. But, after doing that it will notice that there is already SystemYear with given id attached to the context (that one you received with a first query oDB.SystemYears.FirstOrDefault(x => x.Year == Year)). So it will discard new entity and return old one (already attached, with old values) back to you. To force EF refresh entity - use Reload:

ctx.Entry(oSY).Reload(); // no need to make second query, will be done for you

or just use fresh context.


问:
image not taking full width on mobile
I am using bootstrap in my webpage and when I view my page on a small screen, ex iPhone7, the image in it gets very very small, I tried using @media but it is not working, can someone please tell me, what I am missing
here is my code for the CSS and html</p>

```<code><img src="example" style="width: 40%; margin: 0 auto" class="img-responsive img-center" alt="Responsive image">

@media (max-width: 768px) {
            .img-responsive {
                width: 100%;
            }
        }
</code>```

答:
Don't target img-responsive class.
add another class or ID and apply css with !impoprtant at the end.

Title: image not taking full width on mobile

Body:
I am using bootstrap in my webpage and when I view my page on a small screen, ex iPhone7, the image in it gets very very small, I tried using @media but it is not working, can someone please tell me, what I am missing
here is my code for the CSS and html

@media (max-width: 768px) {
            .img-responsive {
                width: 100%;
            }
        }


问:
Rails Ajax form_for is enabling multiple submissions (cannot disable submit button)
I have an issue with an ajax form I use for rendering errors, but it's allowing the user to submit basically an unlimited number of time as long as they keep mashing the submit button. What happens is when the user presses the submit button, it grays out for a fraction of a second with the disable_with text and then becomes clickable again. The user can then keep pressing and making post requests. Only when the user stops does the redirect happen. I've searched through basically all the answers for this particular problem, and they don't seem to work for me. I was wondering if someone could help.

I've tried using javascript to disable the button and using data: {disable_with: "..."}.

Here is my .html.erb code right as of now:

```<code><div class="container-fluid main-container">
  <%= form_for [@group, @task], remote: true do |f| %>
    <%= f.label :name %>
    <%= f.text_field :name, class: "form-control" %>

    <%= f.label :description %>
    <%= f.text_area :description, class: "form-control" %>

    <%= f.label :priority %>
    <%= f.text_field :priority, class: "form-control" %>

    <%= f.label :user %>
    <%= f.select :user_id, options_for_select(@group.options_for_user), {}, class: "form-control" %>

    <%= f.submit "Create Task", class: "btn btn-primary new-task-button", data: {disable_with: "Creating task..."} %>
  <% end %>
</div>
</code>```

And here is my controller code for the task new and create actions

```<code>def new
  @group = Group.find(params[:group_id])
  @task = Task.new
end

def create
  new_user = User.find(task_params.delete(:user_id))
  @task = Task.new(to_update)
  respond_to do |format|
    if @task.save
      @group.tasks << @task
      new_user.tasks << @task
      format.html {redirect_to @group}
      TasksChannel.broadcast_to(@group, {action: "create", data: @task, user: new_user})
    else
      @errors = @task.errors
      format.js {render :file => "layouts/errors.js.erb"}
    end
  end
end

def task_params
  return params.require(:task).permit(:name, :description, :priority, :user_id)
end
</code>```

I've been stuck on this for a while and it's so frustrating. I would greatly appreciate any help.

答:
Check that the html in your page has that attribute. Open your browser at localhost:3000 and open the developer toolbar to check that html element.

Write some Jquery in your applicationscript.js file  and test if the problem is solved. Maybe there is some conflict with turbo-links or something else

```<code>$('#my-button').prop('disabled', true);
</code>```

Disabling button after disable_with

Test the effect also on a simple jquery project without ruby on rails..

Body:
I have an issue with an ajax form I use for rendering errors, but it's allowing the user to submit basically an unlimited number of time as long as they keep mashing the submit button. What happens is when the user presses the submit button, it grays out for a fraction of a second with the disable_with text and then becomes clickable again. The user can then keep pressing and making post requests. Only when the user stops does the redirect happen. I've searched through basically all the answers for this particular problem, and they don't seem to work for me. I was wondering if someone could help.

I've tried using javascript to disable the button and using data: {disable_with: "..."}.

Here is my .html.erb code right as of now:

  <%= form_for [@group, @task], remote: true do |f| %>
    <%= f.label :name %>
    <%= f.text_field :name, class: "form-control" %>

    <%= f.label :description %>
    <%= f.text_area :description, class: "form-control" %>

    <%= f.label :priority %>
    <%= f.text_field :priority, class: "form-control" %>

    <%= f.label :user %>
    <%= f.select :user_id, options_for_select(@group.options_for_user), {}, class: "form-control" %>

    <%= f.submit "Create Task", class: "btn btn-primary new-task-button", data: {disable_with: "Creating task..."} %>
  <% end %>

And here is my controller code for the task new and create actions

def new
  @group = Group.find(params[:group_id])
  @task = Task.new
end

def create
  new_user = User.find(task_params.delete(:user_id))
  @task = Task.new(to_update)
  respond_to do |format|
    if @task.save
      @group.tasks << @task
      new_user.tasks << @task
      format.html {redirect_to @group}
      TasksChannel.broadcast_to(@group, {action: "create", data: @task, user: new_user})
    else
      @errors = @task.errors
      format.js {render :file => "layouts/errors.js.erb"}
    end
  end
end

def task_params
  return params.require(:task).permit(:name, :description, :priority, :user_id)
end

I've been stuck on this for a while and it's so frustrating. I would greatly appreciate any help.

Body:
Check that the html in your page has that attribute. Open your browser at localhost:3000 and open the developer toolbar to check that html element.

Write some Jquery in your applicationscript.js file  and test if the problem is solved. Maybe there is some conflict with turbo-links or something else

$('#my-button').prop('disabled', true);

Disabling button after disable_with

Test the effect also on a simple jquery project without ruby on rails..


问:
React Native react-native-google-places-autocomplete implementation
I am trying to implement the react-native-google-places-autocomplete module, but the following codebit does not produce any results in the list view. I put breakpoints and console logs within the package and found that the request is successful and the API is returning values, but none of the places are being populated in a list view. I have also attached screen shots to show what my issue is.

<img src="https://i.stack.imgur.com/BljDN.png" alt="

答:
It seems the Listview is hiding behind all other views.</p>

```<code>styles={{
          description: {
                        fontWeight: 'bold',
                       },
          predefinedPlacesDescription: {
                          color: '#1faadb',
                       },
          listView: { color: 'black', //To see where exactly the list is
                      zIndex: 16, //To popover the component outwards
                      position: 'absolute',
       }}
</code>```

Body:
It seems the Listview is hiding behind all other views.

styles={{
          description: {
                        fontWeight: 'bold',
                       },
          predefinedPlacesDescription: {
                          color: '#1faadb',
                       },
          listView: { color: 'black', //To see where exactly the list is
                      zIndex: 16, //To popover the component outwards
                      position: 'absolute',
       }}


问:
Easy way to store and retrieve objects in Java without using a relational DB?
Do you know of an "easy" way to store and retrieve objects in Java without using a relational DB / ORM like Hibernate?

[Note that I am not considering serialization as-is for this purpose, as it won't allow to retrieve arbitrary objects in the middle of an object graph. Neither am I considering DB4O because of its restrictive license. Thanks.]

"Easy" meaning: not having to handle low-level details such as key/value pairs to rebuild an object graph (as with BerkeleyDB or traditional caches). The same applies for rebuilding objects from a document- or column-oriented DB (CouchDB, HBase, ..., even Lucene).

Perhaps there are interesting projects out there that provide a layer of integration between the mentioned storage systems and the object model (like ORM would be for RDBMSs) that I am not aware of.

Anyone successfully using those in production, or experimenting with persistence strategies other than relational DBs? How about RDF stores?

Update: I came across a very interesting article: A list of distributed key-value stores

答:
I'd recommend Hibernate (or, more general, OR-mapping) like Matt, but there is also a RDBMS at the backend and I'm not so sure about what you mean by

...without using a relational DB?...

It also would be interesting to know more about the application, because OR-mapping is not always a good idea (development performance vs. runtime performance).

Edit: I shortly learned about terracotta and there is a good stackoverflow discussion here about replacing DBs with that tool. Still experimental, but worth reading.


问:
How to cut off int at the end of a line
I have a txt file similar to the following:

```<code>f1, max, inputs: 10 2 4

f2, sum, inputs: 2 4 5

f3, prod, inputs: 6 5
</code>```

I should find the max from the line where the max is stated (10), print the sum of the numbers from where the sum is (11), and the product from where the prod is (30).

My code looks like this:

```<code>f = File.open("test.txt") or die "Unable to open file..."
contentArray=[]
f.each_line {|line|
    contentArray.push line
}

i=0
while i<contentArray.size() do
    if contentArray[i].include? "max"
        print "max is here"
        i+=1
    elsif contentArray[i].include? "sum"
        print "sum is here"
        i+=1
    elsif contentArray[i].include? "prod"
        print "prod is here"
        i+=1
    end
end
</code>```

I can find which line has the max, sum, or prod string, but I don't know how I should cut off the integers from the end and do the maths with them.

答:
If it is for sure, that the first field ('f1',....) always starts with an alphabetic character, a cheap solution would be to simply split the line on spaces:

```<code>fields = line.split(' ')
</code>```

or

```<code>fields = line.split(/\s/)
</code>```

depending on your taste.

You get the numbers then by

```<code>numbers = fields.select { |element| /^\d/ =~ element }.map(&:to_i)
</code>```

As a side effect, you also get the operators for free, for example

```<code>case fields[1]
when 'sum,'
  result = numbers.reduce(:+)
when 'max,'
  ...
end
</code>```

Of course this assumes that the input corresponds strictly to this formatting. If this can not be ensured (for instance because the input file is manually created by a human being), you should add some sanitary checks on the input format.

Title: How to cut off int at the end of a line

Body:
I have a txt file similar to the following:

f1, max, inputs: 10 2 4

f2, sum, inputs: 2 4 5

f3, prod, inputs: 6 5

I should find the max from the line where the max is stated (10), print the sum of the numbers from where the sum is (11), and the product from where the prod is (30).

My code looks like this:

f = File.open("test.txt") or die "Unable to open file..."
contentArray=[]
f.each_line {|line|
    contentArray.push line
}

i=0
while i<contentArray.size() do
    if contentArray[i].include? "max"
        print "max is here"
        i+=1
    elsif contentArray[i].include? "sum"
        print "sum is here"
        i+=1
    elsif contentArray[i].include? "prod"
        print "prod is here"
        i+=1
    end
end

I can find which line has the max, sum, or prod string, but I don't know how I should cut off the integers from the end and do the maths with them.

Body:
If it is for sure, that the first field ('f1',....) always starts with an alphabetic character, a cheap solution would be to simply split the line on spaces:

fields = line.split(' ')

or

fields = line.split(/\s/)

depending on your taste.

You get the numbers then by

numbers = fields.select { |element| /^\d/ =~ element }.map(&:to_i)

As a side effect, you also get the operators for free, for example

case fields[1]
when 'sum,'
  result = numbers.reduce(:+)
when 'max,'
  ...
end

Of course this assumes that the input corresponds strictly to this formatting. If this can not be ensured (for instance because the input file is manually created by a human being), you should add some sanitary checks on the input format.


问:
How to get List<String> from JSON list using Retrofit 2?
I am new to Android. I need to get a list of strings from a JSON list. It will be added to a Spinner list. I have the list on server like

```<code>[{"bgroup":"A+"},{"bgroup":"A1+"},{"bgroup":"A1-"}].
</code>```

tried with Retrofit Scalars.
Response  as

```<code>[{"bgroup":"A+"},{"bgroup":"A1+"},{"bgroup":"A1-"}]
</code>```

but error detecting as:

Expected a string but was BEGIN_OBJECT at line 1 column 3 path $[0]*

Any better way to retrieve the list of strings from the JSON?

答:
This is sample code :

```<code> GroupService groupService = createService(GroupService.class);

 Call<List<Groups>> groupCall = groupService.getGroups();

    groupCall.enqueue(new Callback<List<Groups>>() {
            @Override
            public void onResponse(retrofit.Response<List<Groups>> response, Retrofit retrofit) {

            }

            @Override
            public void onFailure(Throwable t) {
                t.printStackTrace();

            }
        });
</code>```

Interfaces :

```<code>public interface GroupService {

@GET("<URL>")
Call<List<Groups>> getGroups();
}
</code>```

Also create model name Groups.

I hope this helps you.

Body:
I am new to Android. I need to get a list of strings from a JSON list. It will be added to a Spinner list. I have the list on server like

[{"bgroup":"A+"},{"bgroup":"A1+"},{"bgroup":"A1-"}].

tried with Retrofit Scalars.
Response  as

[{"bgroup":"A+"},{"bgroup":"A1+"},{"bgroup":"A1-"}]

but error detecting as:

Expected a string but was BEGIN_OBJECT at line 1 column 3 path $[0]*

Any better way to retrieve the list of strings from the JSON?

Body:
This is sample code :

 GroupService groupService = createService(GroupService.class);

 Call<List<Groups>> groupCall = groupService.getGroups();

    groupCall.enqueue(new Callback<List<Groups>>() {
            @Override
            public void onResponse(retrofit.Response<List<Groups>> response, Retrofit retrofit) {

            }

            @Override
            public void onFailure(Throwable t) {
                t.printStackTrace();

            }
        });

Interfaces :

public interface GroupService {

@GET("<URL>")
Call<List<Groups>> getGroups();
}

Also create model name Groups.

I hope this helps you.


问:
Generate charts with asp.net
I'm doing a project with MVC in asp.net and C#.
I have to display the chart of yearly orders.The orders will be stored in MySqlServer db.
Please suggest me any idea how to do this.

Another requirement is I have to find the distance b/w 2 selected cities. Can I do this in my program??

Thanks in advance..

答: One other powerful charting library is Shield UI's - they also have ASP.NET wrapper components for the different chart functionalities.</p>

Title: Generate charts with asp.net


问:
What does Symfony cache:clear actually do?
I have bee using Symfony for a while now, and recently ran into an issue where the app/console cache:clear  didn't want to clear the cache.

I then discovered that you can manually remove the app/cache directory to clear the cache.

So aside from doing the app/cache folder, what does cache:clear actually do? Why would i keep using it rather than removing the cache folder?

答:
It also does the cache warmup (at least in version 3.1, which I'm currently using) unless you tell it not to do so with --no-warmup.

It's also easier and faster to run commands in IDEs like PHPStorm then manually doing things such as removing files.

Basically you can just remove cache directory if you prefer such way. Cache warmup will be performed at first Symfony request is needed.


问:
onblur taking last clicked value not taking current clicked value?
I am using onblur event to get the value of date in datepicker. Here is my control:

<input placeholder="MM/DAY/YEAR" data-bind="value: CustomerBookingTbl.PickUpDate" class="input date" name="pickupdate" onblur="UpdatePrice(this)" type="text" required>
```

<p>and here is my function:</p>

<pre class="lang-js prettyprint-override"><code>function UpdatePrice(_this)
{
    console.log(_this.value);
}
</code>```

When I clicked on 06/07/2017 then it takes null. Afterward, I clicked on  06/07/2017 then it takes 06/06/2017 as a value.

I am attaching the image also

答:
You can do this one as well

```<code><input placeholder="MM/DAY/YEAR" data-bind="value: CustomerBookingTbl.PickUpDate" class="input date" name="pickupdate" onchange="UpdatePrice(this)" type="text" required>

<script>
function UpdatePrice(_this) {
  console.log(_this.value);
}
</script>
</code>```

Its quite easy solution

Live demo : https://jsfiddle.net/jalayoza/pyc1vp19/3/

Hope this helps

Body:
I am using onblur event to get the value of date in datepicker. Here is my control:

<input placeholder="MM/DAY/YEAR" data-bind="value: CustomerBookingTbl.PickUpDate" class="input date" name="pickupdate" onblur="UpdatePrice(this)" type="text" required>

and here is my function:

function UpdatePrice(_this)
{
    console.log(_this.value);
}

When I clicked on 06/07/2017 then it takes null. Afterward, I clicked on  06/07/2017 then it takes 06/06/2017 as a value.

I am attaching the image also

Body:
You can do this one as well

<input placeholder="MM/DAY/YEAR" data-bind="value: CustomerBookingTbl.PickUpDate" class="input date" name="pickupdate" onchange="UpdatePrice(this)" type="text" required>

<script>
function UpdatePrice(_this) {
  console.log(_this.value);
}
</script>

Its quite easy solution

Live demo : https://jsfiddle.net/jalayoza/pyc1vp19/3/

Hope this helps


问:
How to add different constraints depend on iPhone screen size?
This is my xib file viewed as iPhone6/iPhone7,it looks good.

but if i turn it into iPhoneSE,it becomes abnormal.

Becasue the space blank doesn't change when the device changes,and i can not change the space constraint adapting to device without code.

答:
You need to make constants for supporting all devices like this.

```<code>var SCREEN_WIDTH = UIScreen.main.bounds.size.width
var SCREEN_HEIGHT = UIScreen.main.bounds.size.height
var BASE_SCREEN_HEIGHT:CGFloat = 667.0
var SCREEN_MAX_LENGTH = max(SCREEN_WIDTH, SCREEN_HEIGHT)
var ASPECT_RATIO_RESPECT_OF_7 = SCREEN_MAX_LENGTH / BASE_SCREEN_HEIGHT
</code>```

I suppose your base layout is iPhone 7 that is your design resides in iPhone 7 layout.

Now create a function which will help to update your constraint according to device. like this.

```<code>func updateConstraint() {
    topConstantOfYourLabel.constant = 10*ASPECT_RATIO_RESPECT_OF_7
}
</code>```

Call this method in viewDidLoad and your layout is just fine.

Note:
For landscape mode you need to make some changes depending on your needs.I assume that you are supporting only portrait mode.

Body:
You need to make constants for supporting all devices like this.

var SCREEN_WIDTH = UIScreen.main.bounds.size.width
var SCREEN_HEIGHT = UIScreen.main.bounds.size.height
var BASE_SCREEN_HEIGHT:CGFloat = 667.0
var SCREEN_MAX_LENGTH = max(SCREEN_WIDTH, SCREEN_HEIGHT)
var ASPECT_RATIO_RESPECT_OF_7 = SCREEN_MAX_LENGTH / BASE_SCREEN_HEIGHT

I suppose your base layout is iPhone 7 that is your design resides in iPhone 7 layout.

Now create a function which will help to update your constraint according to device. like this.

func updateConstraint() {
    topConstantOfYourLabel.constant = 10*ASPECT_RATIO_RESPECT_OF_7
}

Call this method in viewDidLoad and your layout is just fine.

Note:
For landscape mode you need to make some changes depending on your needs.I assume that you are supporting only portrait mode.