问:
Spring MVC http status 404 error
I am getting this error after typing url
localhost:8080/HelloWeb

```<code>HTTP Status 404 - /HelloWeb

type Status report

message /HelloWeb

description The requested resource is not available.
Apache Tomcat/7.0.30
</code>```

I am not able to solve it please help someone
 here are my files which are needed to do execute this SPRING MVC hello program

HelloController.java

```<code>package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/hello")
public class HelloController {
    @RequestMapping(method = RequestMethod.GET)
    public String printHello(ModelMap model) {
        model.addAttribute("message", "Hello Spring MVC Framework!");

        return "hello";
    }
}
</code>```

hello.jsp

```<code><%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
   <h2>${message}</h2>
</body>
</html>
</code>```

web.xml

```<code><web-app id="WebApp_ID" version="2.4"
   xmlns="http://java.sun.com/xml/ns/j2ee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

   <display-name>Spring MVC Application</display-name>

   <servlet>
      <servlet-name>HelloWeb</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>HelloWeb</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>

</web-app>
</code>```

HelloWeb-servlet.xml

```<code><beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package="com.tutorialspoint" />

   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>

</beans>
</code>```

and here is my project hierarchy

HelloWeb

 src

   com.tutorialspoint

 WebContent

   jsp

     hello.jsp

   META-INF

     MANIFEST.MF

   WEB_INF

     lib

     HelloWeb-servlet.xml

     index.jsp

     web.xml

sorry, i forgot to include that i following this Spring MVC example from

tutorialspoint.com/spring/spring_mvc_hello_world_example.htm

答:
This is your code...

```<code>`<property name="prefix" value="/WEB-INF/jsp/" />`

it shows that you have folder 'jsp' inside the 'WEB-INF' .
</code>```

But you don't have a folder there as by looking at your project hierarchy.

Hence, change your code into below:

```<code>`<property name="prefix" value="/WEB-INF/" />.`
</code>```

Title: Spring MVC http status 404 error

Body:
I am getting this error after typing url
localhost:8080/HelloWeb

HTTP Status 404 - /HelloWeb

type Status report

message /HelloWeb

description The requested resource is not available.
Apache Tomcat/7.0.30

I am not able to solve it please help someone
 here are my files which are needed to do execute this SPRING MVC hello program

HelloController.java

package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/hello")
public class HelloController {
    @RequestMapping(method = RequestMethod.GET)
    public String printHello(ModelMap model) {
        model.addAttribute("message", "Hello Spring MVC Framework!");

        return "hello";
    }
}

hello.jsp

<%@ page contentType="text/html; charset=UTF-8" %>

<title>Hello World</title>

${message}

web.xml

<web-app id="WebApp_ID" version="2.4"
   xmlns="http://java.sun.com/xml/ns/j2ee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

   <display-name>Spring MVC Application</display-name>

   <servlet>
      <servlet-name>HelloWeb</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>HelloWeb</servlet-name>
      <url-pattern>/</url-pattern>
   </servlet-mapping>

</web-app>

HelloWeb-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package="com.tutorialspoint" />

   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/" />
      <property name="suffix" value=".jsp" />
   </bean>

</beans>

and here is my project hierarchy

HelloWeb

 src

   com.tutorialspoint

 WebContent

   jsp

     hello.jsp

   META-INF

     MANIFEST.MF

   WEB_INF

     lib

     HelloWeb-servlet.xml

     index.jsp

     web.xml

sorry, i forgot to include that i following this Spring MVC example from

tutorialspoint.com/spring/spring_mvc_hello_world_example.htm

Body:
This is your code...

`<property name="prefix" value="/WEB-INF/jsp/" />`

it shows that you have folder 'jsp' inside the 'WEB-INF' .

But you don't have a folder there as by looking at your project hierarchy.

Hence, change your code into below:

`<property name="prefix" value="/WEB-INF/" />.`


来源: stackexchange

问:
A complete solution to LOCALLY validate an in-app receipts and bundle receipts on iOS 7
I have read a lot of docs and code that in theory will validate an in-app and/or bundle receipt.

Given that my knowledge of SSL, certificates, encryption, etc., is nearly zero, all of the explanations I have read, like this promising one, I have found difficult to understand.

They say the explanations are incomplete because every person has to figure out how to do it, or the hackers will have an easy job creating a cracker app that can recognize and identify patterns and patch the application. OK, I agree with this up to a certain point. I think they could explain completely how to do it and put a warning saying "modify this method", "modify this other method", "obfuscate this variable", "change the name of this and that", etc.

Can some good soul out there be kind enough to explain how to LOCALLY validate, bundle receipts and in-app purchase receipts on iOS 7 as I am five years old (ok, make it 3), from top to bottom, clearly?

Thanks!!!

If you have a version working on your apps and your concerns are that hackers will see how you did it, simply change your sensitive methods before publishing here. Obfuscate strings, change the order of lines, change the way you do loops (from using for to block enumeration and vice-versa) and things like that. Obviously, every person that uses the code that may be posted here, has to do the same thing, not to risk being easily hacked.

答:
Note: It's not recommend to do this type of verification in the client side

This is a Swift 4 version for validation of in-app-purchase receipt...

Lets create an enum to represent the possible errors of the receipt validation

```<code>enum ReceiptValidationError: Error {
    case receiptNotFound
    case jsonResponseIsNotValid(description: String)
    case notBought
    case expired
}
</code>```

Then let's create the function that validates the receipt, it will throws an error if it's unable to validate it.

```<code>func validateReceipt() throws {
    guard let appStoreReceiptURL = Bundle.main.appStoreReceiptURL, FileManager.default.fileExists(atPath: appStoreReceiptURL.path) else {
        throw ReceiptValidationError.receiptNotFound
    }

    let receiptData = try! Data(contentsOf: appStoreReceiptURL, options: .alwaysMapped)
    let receiptString = receiptData.base64EncodedString()
    let jsonObjectBody = ["receipt-data" : receiptString, "password" : <#String#>]

    #if DEBUG
    let url = URL(string: "https://sandbox.itunes.apple.com/verifyReceipt")!
    #else
    let url = URL(string: "https://buy.itunes.apple.com/verifyReceipt")!
    #endif

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = try! JSONSerialization.data(withJSONObject: jsonObjectBody, options: .prettyPrinted)

    let semaphore = DispatchSemaphore(value: 0)

    var validationError : ReceiptValidationError?

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, let httpResponse = response as? HTTPURLResponse, error == nil, httpResponse.statusCode == 200 else {
            validationError = ReceiptValidationError.jsonResponseIsNotValid(description: error?.localizedDescription ?? "")
            semaphore.signal()
            return
        }
        guard let jsonResponse = (try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [AnyHashable: Any] else {
            validationError = ReceiptValidationError.jsonResponseIsNotValid(description: "Unable to parse json")
            semaphore.signal()
            return
        }
        guard let expirationDate = self.expirationDate(jsonResponse: jsonResponse, forProductId: <#String#>) else {
            validationError = ReceiptValidationError.notBought
            semaphore.signal()
            return
        }

        let currentDate = Date()
        if currentDate > expirationDate {
            validationError = ReceiptValidationError.expired
        }

        semaphore.signal()
    }
    task.resume()

    semaphore.wait()

    if let validationError = validationError {
        throw validationError
    }
}
</code>```

Let's use this helper function, to get the expiration date of a specific product. The function receives a JSON response and a product id. The JSON response can contain multiple receipts info for different products, so it get the last info for the specified parameter.

```<code>func expirationDate(jsonResponse: [AnyHashable: Any], forProductId productId :String) -> Date? {
    guard let receiptInfo = (jsonResponse["latest_receipt_info"] as? [[AnyHashable: Any]]) else {
        return nil
    }

    let filteredReceipts = receiptInfo.filter{ return ($0["product_id"] as? String) == productId }

    guard let lastReceipt = filteredReceipts.last else {
        return nil
    }

    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss VV"

    if let expiresString = lastReceipt["expires_date"] as? String {
        return formatter.date(from: expiresString)
    }

    return nil
}
</code>```

Now you can call this function and handle of the possible error cases

```<code>do {
    try validateReceipt()
    // The receipt is valid
    print("Receipt is valid")
} catch ReceiptValidationError.receiptNotFound {
    // There is no receipt on the device
} catch ReceiptValidationError.jsonResponseIsNotValid(let description) {
    // unable to parse the json
    print(description)
} catch ReceiptValidationError.notBought {
    // the subscription hasn't being purchased
} catch ReceiptValidationError.expired {
    // the subscription is expired
} catch {
    print("Unexpected error: \(error).")
}
</code>```

You can get a Password from the App Store Connect. https://developer.apple.com open this link click on

Account tab

Do Sign in

Open iTune Connect

Open My App

Open Feature Tab

Open In App Purchase

Click at the right side on 'View Shared Secret'

At the bottom you will get a secrete key

Copy that key and paste into the password field.

ContentLicense: CC BY-SA 3.0

Body:
Note: It's not recommend to do this type of verification in the client side

This is a Swift 4 version for validation of in-app-purchase receipt...

Lets create an enum to represent the possible errors of the receipt validation

enum ReceiptValidationError: Error {
    case receiptNotFound
    case jsonResponseIsNotValid(description: String)
    case notBought
    case expired
}

Then let's create the function that validates the receipt, it will throws an error if it's unable to validate it.

func validateReceipt() throws {
    guard let appStoreReceiptURL = Bundle.main.appStoreReceiptURL, FileManager.default.fileExists(atPath: appStoreReceiptURL.path) else {
        throw ReceiptValidationError.receiptNotFound
    }

    let receiptData = try! Data(contentsOf: appStoreReceiptURL, options: .alwaysMapped)
    let receiptString = receiptData.base64EncodedString()
    let jsonObjectBody = ["receipt-data" : receiptString, "password" : <#String#>]

    #if DEBUG
    let url = URL(string: "https://sandbox.itunes.apple.com/verifyReceipt")!
    #else
    let url = URL(string: "https://buy.itunes.apple.com/verifyReceipt")!
    #endif

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = try! JSONSerialization.data(withJSONObject: jsonObjectBody, options: .prettyPrinted)

    let semaphore = DispatchSemaphore(value: 0)

    var validationError : ReceiptValidationError?

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, let httpResponse = response as? HTTPURLResponse, error == nil, httpResponse.statusCode == 200 else {
            validationError = ReceiptValidationError.jsonResponseIsNotValid(description: error?.localizedDescription ?? "")
            semaphore.signal()
            return
        }
        guard let jsonResponse = (try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [AnyHashable: Any] else {
            validationError = ReceiptValidationError.jsonResponseIsNotValid(description: "Unable to parse json")
            semaphore.signal()
            return
        }
        guard let expirationDate = self.expirationDate(jsonResponse: jsonResponse, forProductId: <#String#>) else {
            validationError = ReceiptValidationError.notBought
            semaphore.signal()
            return
        }

        let currentDate = Date()
        if currentDate > expirationDate {
            validationError = ReceiptValidationError.expired
        }

        semaphore.signal()
    }
    task.resume()

    semaphore.wait()

    if let validationError = validationError {
        throw validationError
    }
}

Let's use this helper function, to get the expiration date of a specific product. The function receives a JSON response and a product id. The JSON response can contain multiple receipts info for different products, so it get the last info for the specified parameter.

func expirationDate(jsonResponse: [AnyHashable: Any], forProductId productId :String) -> Date? {
    guard let receiptInfo = (jsonResponse["latest_receipt_info"] as? [[AnyHashable: Any]]) else {
        return nil
    }

    let filteredReceipts = receiptInfo.filter{ return ($0["product_id"] as? String) == productId }

    guard let lastReceipt = filteredReceipts.last else {
        return nil
    }

    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss VV"

    if let expiresString = lastReceipt["expires_date"] as? String {
        return formatter.date(from: expiresString)
    }

    return nil
}

Now you can call this function and handle of the possible error cases

do {
    try validateReceipt()
    // The receipt is valid
    print("Receipt is valid")
} catch ReceiptValidationError.receiptNotFound {
    // There is no receipt on the device
} catch ReceiptValidationError.jsonResponseIsNotValid(let description) {
    // unable to parse the json
    print(description)
} catch ReceiptValidationError.notBought {
    // the subscription hasn't being purchased
} catch ReceiptValidationError.expired {
    // the subscription is expired
} catch {
    print("Unexpected error: \(error).")
}

You can get a Password from the App Store Connect. https://developer.apple.com open this link click on

Account tab

Do Sign in

Open iTune Connect

Open My App

Open Feature Tab

Open In App Purchase

Click at the right side on 'View Shared Secret'

At the bottom you will get a secrete key

Copy that key and paste into the password field.

ContentLicense: CC BY-SA 4.0


问:
Insert Array of values into columns of the table in SQL Server
I have an array

```<code>(1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16;)
</code>```

I want to insert this array of values into the table like

```<code>Column1 |  Column2 | Column3 | Column4
-----------------------------------------
    1   |   2      |   3     |    4
    5   |   6      |   7     |    8
    9   |  10      |  11     |   12
   13   |  14      |  15     |   16
</code>```

答:
```<code>DECLARE @array varchar(max) = '(1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16;)'
SET @array = REPLACE( REPLACE(@array, ';', '), ('), ', ()', '')
DECLARE @SQLQuery VARCHAR(MAX) = 'INSERT INTO TABLENAME (Column1,Column2,Column3,Column4) VALUES ' + @array
EXEC (@SQLQuery)
</code>```

Body:
I have an array

(1,2,3,4;5,6,7,8;9,10,11,12;13,14,15,16;)

I want to insert this array of values into the table like

Column1 |  Column2 | Column3 | Column4
-----------------------------------------
    1   |   2      |   3     |    4
    5   |   6      |   7     |    8
    9   |  10      |  11     |   12
   13   |  14      |  15     |   16


问:
Invalid element type
```<code>// This is my test.cjsx
React = require 'react'
createClass = require 'create-react-class'
DataGrid = require './grid/react/TestJs'

module.exports = createClass
    getInitialState: ->
        fullName: ''
    render: ->
        <div className='greeting'>
           <input type='button'/>
           <DataGrid/>
        </div>

// This is my TestJs.js file
const React = require('react');

class DefaultRow extends React.Component {
    constructor(props) {
        super(props)
    }

    render() {
        return (
            <div>
              Hello!
            </div>
        )
    }
};

export default DefaultRow;
</code>```

I got this error always - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object." I double check the export default but I think it is fine.

答:
I think you need to mount your root component in some DOM element.
Use react-dom for this case.
For example:</p>

```<code>import { render } from 'react-dom'

render(
<App></App>
,
  document.getElementById('root')
)
</code>```

Title: Invalid element type

Body:
// This is my test.cjsx
React = require 'react'
createClass = require 'create-react-class'
DataGrid = require './grid/react/TestJs'

module.exports = createClass
    getInitialState: ->
        fullName: ''
    render: ->

           <input type='button'/>
           <DataGrid/>

// This is my TestJs.js file
const React = require('react');

class DefaultRow extends React.Component {
    constructor(props) {
        super(props)
    }

    render() {
        return (

              Hello!

        )
    }
};

export default DefaultRow;

I got this error always - "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object." I double check the export default but I think it is fine.

Body:
I think you need to mount your root component in some DOM element.
Use react-dom for this case.
For example:

import { render } from 'react-dom'

render(
<App></App>
,
  document.getElementById('root')
)


问:
filter Java collection in lambda w/o creating new one
I have a final ConcurrentMap in Java and want to filter it's elements without creating a new one.

Question is: can I reference collection (people) from inside the lambda?

```<code>final ConcurrentMap<String, String> people = new ConcurrentHashMap<>();
people.put("Sam", "developer");
people.put("Kate", "tester");

people.forEach((name, role) -> {
    if (name.length() > 3)
        people.remove(name);
});
</code>```

答:
This has sort of been discussed just recently, for example here.

The documentation states that CHM provide weakly consistent traversal, as opposed to fail-fast traversal; as seen here What this means:

they may proceed concurrently with other operations

they are guaranteed to traverse elements as they existed upon construction exactly once, and may (but are not guaranteed to) reflect any modifications subsequent to construction.

Generally CHM operations that change it's structure are thread-safe, but what you want to achieve is still discouraged by the Stream documentation. This is called interference and should be avoided. If you change that structure with an simple HashMap you will get ConcurrentModificationException since you are modifying the source while traversing it. Unless you have a compelling reason not to discard your previous map, you should just filter the values you are interested in and collect those.

You can also see how you can get un-expected results when you add to a CMH from the link above.

Body:
I have a final ConcurrentMap in Java and want to filter it's elements without creating a new one.

Question is: can I reference collection (people) from inside the lambda?

final ConcurrentMap<String, String> people = new ConcurrentHashMap<>();
people.put("Sam", "developer");
people.put("Kate", "tester");

people.forEach((name, role) -> {
    if (name.length() > 3)
        people.remove(name);
});


问:
How to setup my phone as a hotspot
My phone is connected to a wifi network which provide internet. But it is password protected and my phone is selected as a user with unique password. That password cannot be used to connect another device to the wifi connection. Is there any way to share the internet (from wifi router) to another phone or laptop using my phone as a hotspot? How to share?</p>

答:
Yes it can be done, (I have tried it right now in my Redmi note 3 (no root required))

Here, Try These:-

1. USB Tethering: (I tried this method in my Redmi Note 3)

Connect your mobile to WiFi Connect your mobile to laptop using USB
cable.

Go to Settings->Mobile Network-> Tethering and portable hotspot

Enable USB Tethering

2. Bluetooth Tethering

Connect your mobile to WiFi Pair laptop and mobile phone using
Bluetooth.

Go to Settings->Mobile Network-> Tethering and portable
hotspot

Enable Bluetooth Tethering

Establish connection between laptop and mobile using laptop

Note:

If when you turn on USB tethering it disables the Wi-Fi and uses the mobile data, that means the phone software is programmed stupidly and whoever your phone maker is doesn't want you to do this. It's common, for whatever ungodly reason, for programmers to intentionally break functionality for the users.

Source:- How Do I Create A WiFi hotspot from a mobile already connected to a WiFi

Title: How to setup my phone as a hotspot


问:
Use box shadow on an element with padding instead of margins
Menu with a box shadow. I need to give it a padding top of 30px instead of margin-top so that when the parent has hovered, the sub menu appears and stays appeared when the cursor moves down into space between. If I give it margin-top 30px then the box-shadow works fine, but the submenu disappears when moving the cursor down away from the parent item

Here is a picture of what it looks like

As you can see there is padding at the top of the submenu but the box shadow gets affected by the padding.

Is there any way to have the box shadow go to the top edge of the first white list item instead of pushing it down and creating that transparent area while keeping the padding?

Here is the bare bones code:

HTML:

```<code><ul>
    <li>text</li>
    <li>text</li>
    <li class="menu-item-has-children">text
        <ul class="submenu">
            <li>text</li>
            <li>text</li>
        </ul>
    </li>
</ul>
</code>```

CSS:

```<code> li {
     position: relative;
 }

 .menu-item-has-children:hover .submenu {
     display: none;
 }

 .menu-item-has-children:hover .submenu {
      display: block;
      padding-top: 30px;
      position: absolute;
      box-shadow: 0px 1px 15px 0px rgba(0, 0, 0, 0.15);
 }
</code>```

Anyone have an idea how to overcome this issue?

Thanks

答:
Firstly you really shouldn't tell it to hide when hovering when you want it to show. Secondly giving the submenu an absolute position takes it out of the flow of the page and causes it to stop being "inside" the parent li.

Stop it being absolute and you should stop having problems.

Body:
Menu with a box shadow. I need to give it a padding top of 30px instead of margin-top so that when the parent has hovered, the sub menu appears and stays appeared when the cursor moves down into space between. If I give it margin-top 30px then the box-shadow works fine, but the submenu disappears when moving the cursor down away from the parent item

Here is a picture of what it looks like

As you can see there is padding at the top of the submenu but the box shadow gets affected by the padding.

Is there any way to have the box shadow go to the top edge of the first white list item instead of pushing it down and creating that transparent area while keeping the padding?

Here is the bare bones code:

HTML:

text

text

text

text

text

CSS:

 li {
     position: relative;
 }

 .menu-item-has-children:hover .submenu {
     display: none;
 }

 .menu-item-has-children:hover .submenu {
      display: block;
      padding-top: 30px;
      position: absolute;
      box-shadow: 0px 1px 15px 0px rgba(0, 0, 0, 0.15);
 }

Anyone have an idea how to overcome this issue?

Thanks


问:
Vue, how do I pass data to component in render method
This is the main vue component. I want to make an ajax request and pass the data using the render method to my app component, which is a standalone component in a different file. How do I pass this data and how can I retrieve it in my app component. I am learning Vue, I know how to do this with <template></template> but would like to know if it is possible to do it this way.

```<code>new Vue({
    el: '#app',
    data: {
        data: {}
    },
    mounted() {
        axios.get("http://stag.cyberserge.com:4000/autos").then(res => this.data = res.data)
    },
    render: h => h(App, this.data)
});
</code>```

答:
Pass it as a property.

```<code>render(h){
  return h(App, {props: {appData: this.data}})
},
</code>```

See the documentation here.

In your App component, add appData (or whatever you want to call it) as a property.

```<code>export default {
    props: ["appData"],
    ...
}
</code>```

Here is an example of this working.

Body:
This is the main vue component. I want to make an ajax request and pass the data using the render method to my app component, which is a standalone component in a different file. How do I pass this data and how can I retrieve it in my app component. I am learning Vue, I know how to do this with <template></template> but would like to know if it is possible to do it this way.

new Vue({
    el: '#app',
    data: {
        data: {}
    },
    mounted() {
        axios.get("http://stag.cyberserge.com:4000/autos").then(res => this.data = res.data)
    },
    render: h => h(App, this.data)
});

Body:
Pass it as a property.

render(h){
  return h(App, {props: {appData: this.data}})
},

See the documentation here.

In your App component, add appData (or whatever you want to call it) as a property.

export default {
    props: ["appData"],
    ...
}

Here is an example of this working.


问:
Watching for a DOM change without losing performance (javascript)
This might be a newbie question. What I want to do iswatch if a particular element has custom scrollbar I want to change the width of its parent.This works perfectly if I wrap in setInterval as it will be checking all the time for changes, but I am concerned about performance. How this could be implemented more elegantly in jQuery or even Angularjs?</p>

```<code>(function($) {
  $.fn.hasScrollBar = function() {
    return this.get(0).scrollHeight > this.height();
  }
})(jQuery);
   if ($('#tab-content-3').hasScrollBar()) {
      $('#basics md-content').css('width', '95%');
   } else {
      $('#basics md-content').css('width', '100%');
   }
</code>```

答:
You can make use of MutationObserver. This is supported is most of the modern browsers and there is a fallback for old browsers.

Have a look at below example and various configuration supported by MutationObserver. I would suggest using MutationObserver with attributes change configuration so that performance impact will be minimal.

MDN MutationObserver

Example Tutorial by Google

Similar Stackoverflow Answer

Underscore.js's throttle

You can use it along with underscore.js's throttle method to increase performance.

Body:
This might be a newbie question. What I want to do iswatch if a particular element has custom scrollbar I want to change the width of its parent.This works perfectly if I wrap in setInterval as it will be checking all the time for changes, but I am concerned about performance. How this could be implemented more elegantly in jQuery or even Angularjs?

(function($) {
  $.fn.hasScrollBar = function() {
    return this.get(0).scrollHeight > this.height();
  }
})(jQuery);
   if ($('#tab-content-3').hasScrollBar()) {
      $('#basics md-content').css('width', '95%');
   } else {
      $('#basics md-content').css('width', '100%');
   }


问:
Can you uniquely identify a BLE MAC address in Android 5.0?
In Android 5.0, BLE doesn't use static MAC addresses anymore, but the MACs change after intervals, using a method called IRK and public key cryptography.

Is it possible to uniquely identify an Android phone in a way that can not be spoofed by the user of that phone, or has that become completely impossible now unless the other side co-operates?

答: The private address is generated using the devices IRK exchanged during the previous pairing/bonding procedure. So if they have not bonded, you can't get irk.</p>


问:
Java : Cast String Array to an Object
I'm trying to cast String Array to an Object.

```<code>Object string="[FIBER,CABLE]";
String[] strArray = (String[])string;
</code>```

I got ClassCastException.

I can get by splitting str by slash and comma

```<code>Object string="[FIBER,CABLE]";
String[] strArray = ((String)string).split("[,\\]\\[]");

for(int i=1;i<strArray.length;i++)
    System.out.println(strArray[i]);
</code>```

I wanted to know "Is there any better way to do it?"

答:
The correct fix here would be to refactor the database so that you aren't storing arrays in text fields but rather as separate rows in a table. In saying this, I assume you don't have access to the process which inserts into the database and therefore can't do anything about it.

Your solution looks good given the problem at hand.

Title: Java : Cast String Array to an Object

Body:
I'm trying to cast String Array to an Object.

Object string="[FIBER,CABLE]";
String[] strArray = (String[])string;

I got ClassCastException.

I can get by splitting str by slash and comma

Object string="[FIBER,CABLE]";
String[] strArray = ((String)string).split("[,\\]\\[]");

for(int i=1;i<strArray.length;i++)
    System.out.println(strArray[i]);

I wanted to know "Is there any better way to do it?"


问:
Query to find employee who has worked in all locations
Imagine a simple employee database:
Employee [ empId, location vachar (30) ]

We want to find employee who has worked in all locations ?

Not looking for a specific SQL server.

答:
This should work for SQL Server (or any database that supports count(distinct <column>):

```<code>SELECT empId
FROM Employee
GROUP BY empId
HAVING COUNT(DISTINCT location) = (SELECT COUNT(DISTINCT location) FROM Employee)
</code>```

Body:
This should work for SQL Server (or any database that supports count(distinct <column>):

SELECT empId
FROM Employee
GROUP BY empId
HAVING COUNT(DISTINCT location) = (SELECT COUNT(DISTINCT location) FROM Employee)


问:
How to modify a JSON file in a script?
I am trying to edit Chrome's preferences using command line. The file is a JSON file and I want to edit the data below:

```<code>{"browser":{"last_redirect_origin":""}}
</code>```

to

```<code>{"browser":{"enabled_labs_experiments":["ssl-version-max@2"],"last_redirect_origin":""}}
</code>```

I was using sed command earlier to accomplish this but want to know how this can be done using python. This was the command I was using:

```<code>sed -i '.bak' -e 's|\(\"browser\"\):{\(\".*origin\":\"\"\)}|\1:{\"enabled_labs_experiments\":[\"ssl-version-max@2\"],\2}|' ~/Library/Application\ Support/Google/Chrome/Local\ State
</code>```

The reason I can't use jq is that it is not native to macs and will need installation. I am not able to understand how to do this with python.

I will really appreciate it if someone could help me with this or point me in the right direction.

EDIT

This is what my python script looks like:

```<code>import json
jsonData = json.loads(open('/Users/username/Library/Application Support/Google/Chrome/Local state').read())
if 'enabled_labs_experiments' in jsonData['browser']:
    if 'ssl-version-max@2' in jsonData['browser']['enabled_labs_experiments']:
        print('Exist')
    else:
        jsonData['browser']['enabled_labs_experiments'] = ['ssl-version-max@2']
        print('Added')
</code>```

After the changes are made, I would like to commit the changes to the file.

答:
Why are you using regex why are you not using the built in json module in python?</p>

```<code>import json
d = json.loads(path_to_your_file)
d["browser"]["enabled_labs_experiments"] = ["ssl-version-max@2"]
</code>```

Title: How to modify a JSON file in a script?

Body:
I am trying to edit Chrome's preferences using command line. The file is a JSON file and I want to edit the data below:

{"browser":{"last_redirect_origin":""}}

to

{"browser":{"enabled_labs_experiments":["ssl-version-max@2"],"last_redirect_origin":""}}

I was using sed command earlier to accomplish this but want to know how this can be done using python. This was the command I was using:

sed -i '.bak' -e 's|\(\"browser\"\):{\(\".*origin\":\"\"\)}|\1:{\"enabled_labs_experiments\":[\"ssl-version-max@2\"],\2}|' ~/Library/Application\ Support/Google/Chrome/Local\ State

The reason I can't use jq is that it is not native to macs and will need installation. I am not able to understand how to do this with python.

I will really appreciate it if someone could help me with this or point me in the right direction.

EDIT

This is what my python script looks like:

import json
jsonData = json.loads(open('/Users/username/Library/Application Support/Google/Chrome/Local state').read())
if 'enabled_labs_experiments' in jsonData['browser']:
    if 'ssl-version-max@2' in jsonData['browser']['enabled_labs_experiments']:
        print('Exist')
    else:
        jsonData['browser']['enabled_labs_experiments'] = ['ssl-version-max@2']
        print('Added')

After the changes are made, I would like to commit the changes to the file.

Body:
Why are you using regex why are you not using the built in json module in python?

import json
d = json.loads(path_to_your_file)
d["browser"]["enabled_labs_experiments"] = ["ssl-version-max@2"]


问:
Crypto Random not working?
I'm trying out AES encryption on Python and my code is fine but in  from Crypto import Random, the Random is giving an error. When I run the code, I get the following traceback:

```<code>Traceback (most recent call last):
  File "C:/Users/RedCode/PycharmProjects/SecurityApps/Encryption/AES.py", line 3, in <module>
  from Crypto import Random
  ImportError: cannot import name 'Random'
</code>```

How can I correct this issue?

If it helps, I checked my site-package folder and I have pycrypto, pycryptodome, pycryptodomex, Crypto, and crypto-1.4.1.

答:
Okay, so my issue was that PyCharm was not reading the site-packages folder properly. I had a Crypto package folder but it wasn't the proper one as it was missing a lot of sub-folders. I can't remember where I downloaded it from but it was basically given the wrong name.

By some random luck I found the proper Crypto folder inside the pycryptodome-3.4.6-py3.6-win32.egg folder, which contained the Random package inside it (along with other packages). So I removed the Crypto folder I had, and replaced it with the one I found and everything works now

Title: Crypto Random not working?

Body:
I'm trying out AES encryption on Python and my code is fine but in  from Crypto import Random, the Random is giving an error. When I run the code, I get the following traceback:

Traceback (most recent call last):
  File "C:/Users/RedCode/PycharmProjects/SecurityApps/Encryption/AES.py", line 3, in <module>
  from Crypto import Random
  ImportError: cannot import name 'Random'

How can I correct this issue?

If it helps, I checked my site-package folder and I have pycrypto, pycryptodome, pycryptodomex, Crypto, and crypto-1.4.1.


问:
Mysql Select and count rows with multiple same values
I am trying to create a query that allows me to select the data like shown below

```<code>id  Counter_Type Champion_Name Counter_Lane
---|------------|------------|--------------
1  | 1          | Ahri       | 1
2  | 1          | Ahri       | 2
5  | 1          | Ahri       | 2
3  | 1          | Ahri       | 3
4  | 1          | Ahri       | 2
6  | 1          | Teemo      | 1
7  | 1          | Warwick    | 4
8  | 1          | Warwick    | 4
</code>```

It should count the Counter_Lane and then the Counter_Type with the most should be shown for that name as shown below how it should show the data:

```<code>id  Counter_Type Champion_Name Counter_Lane
---|------------|------------|--------------
1  | 1          | Ahri       | 2
2  | 1          | Teemo      | 1
3  | 1          | Warwick    | 4
</code>```

I have tried the following code and its the closest I have came for over 3 hours now, so could someone help please.

```<code>SELECT
    a.Counter_Type, Champion_For, a.Counter_Lane, a.Champion_Name, COUNT(*) as Amount, sum(vote_type = 'up') as Upvotes, sum(vote_type = 'down') as Downvotes, sum(vote_type = 'up')-sum(vote_type = 'down') as Totalvotes
FROM Champion_Counters_Data a
JOIN ( SELECT c.Counter_Lane, c.Champion_Name, COUNT(*) magnitude
FROM Champion_Counters_Data c
WHERE
    Champion_For = "Aatrox" AND Counter_Type = 1 GROUP BY Champion_Name, Counter_Lane ORDER BY magnitude) b ON a.Champion_Name = b.Champion_Name AND b.Counter_Lane = a.Counter_Lane
GROUP BY Champion_Name
</code>```

答:
You will need many subqueries as MySQL doesn't allow windows function or CTE.

Rextester Demo

```<code>SELECT @rn := @rn + 1 as id,
t3.*
from
    (select t1.*
    FROM
      (SELECT counter_type,
              champion_name,
              counter_lane,
              count(*) AS cnt
       FROM table53
       GROUP BY champion_name,
                counter_lane
      ) t1
    INNER JOIN
      (SELECT counter_type,
              champion_name,
              max(cnt) AS mcnt
       FROM
            (SELECT counter_type,
                 champion_name,
                 counter_lane,
                 count(*) AS cnt
          FROM table53
          GROUP BY champion_name,
                   counter_lane
            ) t
       GROUP BY counter_type,
                champion_name
       ) t2
    ON t1.counter_type=t2.counter_type
    AND t1.champion_name=t2.champion_name
    AND t1.cnt=t2.mcnt
    ) t3
,(SELECT @rn := 0) t
;
</code>```

Output

```<code>+-----+--------------+---------------+--------------+-----+
|  id | counter_type | champion_name | counter_lane | cnt |
+-----+--------------+---------------+--------------+-----+
|   1 |            1 | Ahri          |            2 |   3 |
|   2 |            1 | Teemo         |            1 |   1 |
|   3 |            1 | Warwick       |            4 |   2 |
+-----+--------------+---------------+--------------+-----+
</code>```

Idea is to first group by champion_name and counter_lane and get the count . So for Ahri you will get cnt as 3. Now use another subquery to get corresponding counter_lane, which will be 2 for Ahri. At last, use a sequence number to generate id as 1,2,3 etc.

Body:
I am trying to create a query that allows me to select the data like shown below

id  Counter_Type Champion_Name Counter_Lane
---|------------|------------|--------------
1  | 1          | Ahri       | 1
2  | 1          | Ahri       | 2
5  | 1          | Ahri       | 2
3  | 1          | Ahri       | 3
4  | 1          | Ahri       | 2
6  | 1          | Teemo      | 1
7  | 1          | Warwick    | 4
8  | 1          | Warwick    | 4

It should count the Counter_Lane and then the Counter_Type with the most should be shown for that name as shown below how it should show the data:

id  Counter_Type Champion_Name Counter_Lane
---|------------|------------|--------------
1  | 1          | Ahri       | 2
2  | 1          | Teemo      | 1
3  | 1          | Warwick    | 4

I have tried the following code and its the closest I have came for over 3 hours now, so could someone help please.

SELECT
    a.Counter_Type, Champion_For, a.Counter_Lane, a.Champion_Name, COUNT(*) as Amount, sum(vote_type = 'up') as Upvotes, sum(vote_type = 'down') as Downvotes, sum(vote_type = 'up')-sum(vote_type = 'down') as Totalvotes
FROM Champion_Counters_Data a
JOIN ( SELECT c.Counter_Lane, c.Champion_Name, COUNT(*) magnitude
FROM Champion_Counters_Data c
WHERE
    Champion_For = "Aatrox" AND Counter_Type = 1 GROUP BY Champion_Name, Counter_Lane ORDER BY magnitude) b ON a.Champion_Name = b.Champion_Name AND b.Counter_Lane = a.Counter_Lane
GROUP BY Champion_Name

Body:
You will need many subqueries as MySQL doesn't allow windows function or CTE.

Rextester Demo

SELECT @rn := @rn + 1 as id,
t3.*
from
    (select t1.*
    FROM
      (SELECT counter_type,
              champion_name,
              counter_lane,
              count(*) AS cnt
       FROM table53
       GROUP BY champion_name,
                counter_lane
      ) t1
    INNER JOIN
      (SELECT counter_type,
              champion_name,
              max(cnt) AS mcnt
       FROM
            (SELECT counter_type,
                 champion_name,
                 counter_lane,
                 count(*) AS cnt
          FROM table53
          GROUP BY champion_name,
                   counter_lane
            ) t
       GROUP BY counter_type,
                champion_name
       ) t2
    ON t1.counter_type=t2.counter_type
    AND t1.champion_name=t2.champion_name
    AND t1.cnt=t2.mcnt
    ) t3
,(SELECT @rn := 0) t
;

Output

+-----+--------------+---------------+--------------+-----+
|  id | counter_type | champion_name | counter_lane | cnt |
+-----+--------------+---------------+--------------+-----+
|   1 |            1 | Ahri          |            2 |   3 |
|   2 |            1 | Teemo         |            1 |   1 |
|   3 |            1 | Warwick       |            4 |   2 |
+-----+--------------+---------------+--------------+-----+

Idea is to first group by champion_name and counter_lane and get the count . So for Ahri you will get cnt as 3. Now use another subquery to get corresponding counter_lane, which will be 2 for Ahri. At last, use a sequence number to generate id as 1,2,3 etc.


问:
Dot in base url codeigniter
I have got a source code of a codeigniter project.in the config.php file there is a dot in the base url.

Code:

```<code>$config['base_url'] = 'http://codeigniter-ajaxcrud.local/';
</code>```

what is the purpose of using this dot in the base url?

答:
Yes, It is virtual host. you can try to create virtual host with same name using:
https://www.digitalocean.com/community/tutorials/how-to-set-up-apache-virtual-hosts-on-ubuntu-14-04-lts

or change the URL of your path.

Purpose:
When you develop web app then the URL taken like:
http://localhost/codeigniter/

here codeigniter is your main folder where you develop website..

and then you create any controller (e.g Users) then URL looks like http://localhost/codeigniter/users

then web app take the codeigniter as controller and users as method.
but actually the codeigniter is your root directory of your project not a controller.

So you have to create virtual host to deprecate this issue.

Title: Dot in base url codeigniter

Body:
I have got a source code of a codeigniter project.in the config.php file there is a dot in the base url.

Code:

$config['base_url'] = 'http://codeigniter-ajaxcrud.local/';

what is the purpose of using this dot in the base url?


问:
jQuery click on appended elements
I have generated some html links with jQuery and appended it to some div
but it seams that i can't call click method now, when these elements are appended (it worked ok when they were hardcoded into html)
$('#something a').click(function() ...

Does anyone know a solution for this?

答:
you need to use the live function to make sure that the click event gets binded to elements that have been added to the DOM after the page has been loaded:</p>

```<code>$('#something a').live('click',function() .....
</code>```

ContentLicense: CC BY-SA 2.5

Title: jQuery click on appended elements

Body:
you need to use the live function to make sure that the click event gets binded to elements that have been added to the DOM after the page has been loaded:

$('#something a').live('click',function() .....


问:
R dplyr: Drop multiple columns
I have a dataframe and list of columns in that dataframe that I'd like to drop. Let's use the iris dataset as an example. I'd like to drop Sepal.Length and Sepal.Width and use only the remaining columns. How do I do this using select or select_ from the dplyr package?

Here's what I've tried so far:

```<code>drop.cols <- c('Sepal.Length', 'Sepal.Width')
iris %>% select(-drop.cols)
</code>```

Error in -drop.cols : invalid argument to unary operator

```<code>iris %>% select_(.dots = -drop.cols)
</code>```

Error in -drop.cols : invalid argument to unary operator

```<code>iris %>% select(!drop.cols)
</code>```

Error in !drop.cols : invalid argument type

```<code>iris %>% select_(.dots = !drop.cols)
</code>```

Error in !drop.cols : invalid argument type

I feel like I'm missing something obvious because these seems like a pretty useful operation that should already exist. On Github, someone posted a similar issue, and Hadley said to use 'negative indexing'. That's what (I think) I've tried, but to no avail. Any suggestions?

答: Be careful with the select() function, because it's used both in the dplyr and MASS packages, so if MASS is loaded, select() may not work properly. To find out what packages are loaded, type sessionInfo() and look for it in the "other attached packages:" section. If it is loaded, type detach( "package:MASS", unload = TRUE ), and your select() function should work again.

Title: R dplyr: Drop multiple columns

Body:
I have a dataframe and list of columns in that dataframe that I'd like to drop. Let's use the iris dataset as an example. I'd like to drop Sepal.Length and Sepal.Width and use only the remaining columns. How do I do this using select or select_ from the dplyr package?

Here's what I've tried so far:

drop.cols <- c('Sepal.Length', 'Sepal.Width')
iris %>% select(-drop.cols)

Error in -drop.cols : invalid argument to unary operator

iris %>% select_(.dots = -drop.cols)

Error in -drop.cols : invalid argument to unary operator

iris %>% select(!drop.cols)

Error in !drop.cols : invalid argument type

iris %>% select_(.dots = !drop.cols)

Error in !drop.cols : invalid argument type

I feel like I'm missing something obvious because these seems like a pretty useful operation that should already exist. On Github, someone posted a similar issue, and Hadley said to use 'negative indexing'. That's what (I think) I've tried, but to no avail. Any suggestions?


问:
Generate closest teams based on employee schedules C#
I am given a csv of employee schedules with columns:

```<code>employee ID, first last name, sunday schedule, monday schedule, ... , saturday schedule
</code>```

1 week schedule for each employee. I've attached a screenshot of a portion of the csv file. The total file has around 300 rows.

I need to generate teams of 15 based on the employees' schedules (locations don't matter) so that the employees on each team have the closest schedules to each other. Pseudocode of what I have tried:

parse csv file into array of schedules (my own struct definition)

match employees who have the same exact schedule into teams (creates ~5 full sized teams, 20 - 25 half filled teams, leaves ~50 schedules who don't match with anyone)

for i = 1 to 14, for each member of teams of size i, find the team with the closest schedule (as a whole) and add the member to that team. Once a team reaches size 15, mark them as "done".

This worked somewhat but definitely did not give me the best teams. My question is does anyone know a better way to do this? Pseudocode or just a general idea will help, thanks.

EDIT: Here is an example of the formula of comparison
The comparison is based on half hour blocks of difference between the agents schedules. Agent 25 has a score of 16 because he has a difference of 8 half hours with Agent 23 and 24. The team's total score is 32 based on everyone's scores added together.

Not all agents work 8 hour days, and many have different days off, which have the greatest effect on their "closeness" score. Also, a few agents have a different schedule on a certain day than their normal schedule. For example, one agent might work 7am - 3pm on mondays but work 8am - 4pm on tuesday - friday.

答:
Unless you find a method that gets you an exact best answer, I would add a hill-climbing phase at the end that repeatedly checks to see if swapping any pair of agents between teams would improve things, and swaps them if this is the case, only stopping when it has rechecked every pair of agents and there are no more improvements to be made.

I would do this for two reasons:

1) Such hill-climbing finds reasonably good solutions surprisingly often.

2) People are good at finding improvements like this. If you produce a computer-generated schedule and people can find simple improvements (perhaps because they notice they are often scheduled at the same time as somebody from another team) then you're going to look silly.

Thinking about (2) another way to find local improvements would be to look for cases where a small number of people from different teams are scheduled at the same time and see if you can swap them all onto the same team.

Body:
I am given a csv of employee schedules with columns:

employee ID, first last name, sunday schedule, monday schedule, ... , saturday schedule

1 week schedule for each employee. I've attached a screenshot of a portion of the csv file. The total file has around 300 rows.

I need to generate teams of 15 based on the employees' schedules (locations don't matter) so that the employees on each team have the closest schedules to each other. Pseudocode of what I have tried:

parse csv file into array of schedules (my own struct definition)

match employees who have the same exact schedule into teams (creates ~5 full sized teams, 20 - 25 half filled teams, leaves ~50 schedules who don't match with anyone)

for i = 1 to 14, for each member of teams of size i, find the team with the closest schedule (as a whole) and add the member to that team. Once a team reaches size 15, mark them as "done".

This worked somewhat but definitely did not give me the best teams. My question is does anyone know a better way to do this? Pseudocode or just a general idea will help, thanks.

EDIT: Here is an example of the formula of comparison
The comparison is based on half hour blocks of difference between the agents schedules. Agent 25 has a score of 16 because he has a difference of 8 half hours with Agent 23 and 24. The team's total score is 32 based on everyone's scores added together.

Not all agents work 8 hour days, and many have different days off, which have the greatest effect on their "closeness" score. Also, a few agents have a different schedule on a certain day than their normal schedule. For example, one agent might work 7am - 3pm on mondays but work 8am - 4pm on tuesday - friday.


问:
Dice Simulation java
I'm writing a dice simulation program, however I'm having problems with the results because it just prints:

```<code>You rolled a ...1 and 1

You rolled double ones 0 out of 10000 rolls.
You rolled double twos 0 out of 10000 rolls.
You rolled double threes 0 out of 10000 rolls.
You rolled double fours 0 out of 10000 rolls.
You rolled double fives 0 out of 10000 rolls.
You rolled double sixes 0 out of 10000 rolls.
</code>```

it always prints this and I don't understand why, since it should print different numbers each time.

```<code>    public class Dice
{
    private int die1;
    private int die2;

    public Dice()
    {
        die1 = 1;
        die2 = 1;
    }

    public void rollDice()
    {
        Random myRan = new Random();

        die1 = myRan.nextInt(6) + 1;
        die2 = myRan.nextInt(6) + 1;
    }

   public int getDie1()
   {
   return die1;
   }

   public int getDie2()
   {
    return die2;
   }

    public String toString()
    {
         return "You rolled a ..." + die1 + " and " + die2 + "\n";   }
}
</code>```

and...

```<code> import java.util.Random;
public class DiceSimulation
{
    static final int NUMBER = 10000;
    static Random generator = new Random();

    static int die1Value;
    static int die2Value;
    static int count = 0;
    static int ones = 0;
    static int twos = 0;
    static int threes = 0;
    static int fours = 0;
    static int fives = 0;
    static int sixes = 0;
    static int c=1;

public static void main(String[] args)
{

    rollDiceAndTabulateWhile();
    rollDiceAndTabulteDoWhile();
    rollDiceAndTabulteFor();
    summarizeResults();
}

public static void rollDiceAndTabulateWhile()
{

        Dice d = new Dice();
        while(c<= NUMBER)
        {
        d.rollDice();
        die1Value = d.getDie1();
        die2Value = d.getDie2();
        if(die1Value == die2Value)
        count++;
        else if(die1Value == 1 && die2Value == 1)
        ones++;
        else if(die1Value == 2 && die2Value == 2)
        twos++;
        else if(die1Value == 3 && die2Value == 3)
        threes++;
        else if(die1Value == 4 && die2Value == 4)
        fours++;
        else if(die1Value == 5 && die2Value == 5)
        fives++;
        else if(die1Value == 6 && die2Value == 6)
        sixes++;

        c++;
        }
}

public static void rollDiceAndTabulteDoWhile()
{

     DiceSimulation dw = new DiceSimulation();

        Dice d = new Dice();
        do
        {
        d.rollDice();
        dw.die1Value = d.getDie1();
        dw.die2Value = d.getDie2();
        if(die1Value == die2Value)
        count++;
        else if(dw.die1Value == 1 && dw.die2Value == 1)
        ones++;
        else if(dw.die1Value == 2 && dw.die2Value == 2)
        twos++;
        else if(dw.die1Value == 3 && dw.die2Value == 3)
        threes++;
        else if(dw.die1Value == 4 && dw.die2Value == 4)
        fours++;
        else if(dw.die1Value == 5 && dw.die2Value == 5)
        fives++;
        else if(dw.die1Value == 6 && dw.die2Value == 6)
        sixes++;
        c++;
        } while(c <= NUMBER);
}

public static void rollDiceAndTabulteFor()
  {
    DiceSimulation dw = new DiceSimulation();
    Dice d = new Dice();

    for(c=1;c<=NUMBER;c++)
    {
    d.rollDice();
    dw.die1Value = d.getDie1();
    dw.die2Value = d.getDie2();
    if(die1Value == die2Value)
    count++;
    else if(dw.die1Value == 1 && dw.die2Value == 1)
    ones++;
    else if(dw.die1Value == 2 && dw.die2Value == 2)
    twos++;
    else if(dw.die1Value == 3 && dw.die2Value == 3)
    threes++;
    else if(dw.die1Value == 4 && dw.die2Value == 4)
    fours++;
    else if(dw.die1Value == 5 && dw.die2Value == 5)
    fives++;
    else if(dw.die1Value == 6 && dw.die2Value == 6)
    sixes++;
  }
  }
public static void summarizeResults()
{
    Dice d = new Dice();
    System.out.println(d.toString());
    System.out.println("You rolled double ones " + ones
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double twos " + twos
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double threes " + threes
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double fours " + fours
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double fives " + fives
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double sixes " + sixes
            + " out of " + NUMBER + " rolls.");
}
</code>```

}

答:
Here is your problem

```<code>if(die1Value == die2Value)
    count++;
</code>```

None of your else if statements run when this statement is true.

For instance, if you roll a 4 and 4, then count will increment, and the following else if will never run:

```<code>else if(die1Value == 4 && die2Value == 4)
        fours++; // Never runs
</code>```

Title: Dice Simulation java

Body:
I'm writing a dice simulation program, however I'm having problems with the results because it just prints:

You rolled a ...1 and 1

You rolled double ones 0 out of 10000 rolls.
You rolled double twos 0 out of 10000 rolls.
You rolled double threes 0 out of 10000 rolls.
You rolled double fours 0 out of 10000 rolls.
You rolled double fives 0 out of 10000 rolls.
You rolled double sixes 0 out of 10000 rolls.

it always prints this and I don't understand why, since it should print different numbers each time.

    public class Dice
{
    private int die1;
    private int die2;

    public Dice()
    {
        die1 = 1;
        die2 = 1;
    }

    public void rollDice()
    {
        Random myRan = new Random();

        die1 = myRan.nextInt(6) + 1;
        die2 = myRan.nextInt(6) + 1;
    }

   public int getDie1()
   {
   return die1;
   }

   public int getDie2()
   {
    return die2;
   }

    public String toString()
    {
         return "You rolled a ..." + die1 + " and " + die2 + "\n";   }
}

and...

 import java.util.Random;
public class DiceSimulation
{
    static final int NUMBER = 10000;
    static Random generator = new Random();

    static int die1Value;
    static int die2Value;
    static int count = 0;
    static int ones = 0;
    static int twos = 0;
    static int threes = 0;
    static int fours = 0;
    static int fives = 0;
    static int sixes = 0;
    static int c=1;

public static void main(String[] args)
{

    rollDiceAndTabulateWhile();
    rollDiceAndTabulteDoWhile();
    rollDiceAndTabulteFor();
    summarizeResults();
}

public static void rollDiceAndTabulateWhile()
{

        Dice d = new Dice();
        while(c<= NUMBER)
        {
        d.rollDice();
        die1Value = d.getDie1();
        die2Value = d.getDie2();
        if(die1Value == die2Value)
        count++;
        else if(die1Value == 1 && die2Value == 1)
        ones++;
        else if(die1Value == 2 && die2Value == 2)
        twos++;
        else if(die1Value == 3 && die2Value == 3)
        threes++;
        else if(die1Value == 4 && die2Value == 4)
        fours++;
        else if(die1Value == 5 && die2Value == 5)
        fives++;
        else if(die1Value == 6 && die2Value == 6)
        sixes++;

        c++;
        }
}

public static void rollDiceAndTabulteDoWhile()
{

     DiceSimulation dw = new DiceSimulation();

        Dice d = new Dice();
        do
        {
        d.rollDice();
        dw.die1Value = d.getDie1();
        dw.die2Value = d.getDie2();
        if(die1Value == die2Value)
        count++;
        else if(dw.die1Value == 1 && dw.die2Value == 1)
        ones++;
        else if(dw.die1Value == 2 && dw.die2Value == 2)
        twos++;
        else if(dw.die1Value == 3 && dw.die2Value == 3)
        threes++;
        else if(dw.die1Value == 4 && dw.die2Value == 4)
        fours++;
        else if(dw.die1Value == 5 && dw.die2Value == 5)
        fives++;
        else if(dw.die1Value == 6 && dw.die2Value == 6)
        sixes++;
        c++;
        } while(c <= NUMBER);
}

public static void rollDiceAndTabulteFor()
  {
    DiceSimulation dw = new DiceSimulation();
    Dice d = new Dice();

    for(c=1;c<=NUMBER;c++)
    {
    d.rollDice();
    dw.die1Value = d.getDie1();
    dw.die2Value = d.getDie2();
    if(die1Value == die2Value)
    count++;
    else if(dw.die1Value == 1 && dw.die2Value == 1)
    ones++;
    else if(dw.die1Value == 2 && dw.die2Value == 2)
    twos++;
    else if(dw.die1Value == 3 && dw.die2Value == 3)
    threes++;
    else if(dw.die1Value == 4 && dw.die2Value == 4)
    fours++;
    else if(dw.die1Value == 5 && dw.die2Value == 5)
    fives++;
    else if(dw.die1Value == 6 && dw.die2Value == 6)
    sixes++;
  }
  }
public static void summarizeResults()
{
    Dice d = new Dice();
    System.out.println(d.toString());
    System.out.println("You rolled double ones " + ones
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double twos " + twos
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double threes " + threes
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double fours " + fours
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double fives " + fives
            + " out of " + NUMBER + " rolls.");
    System.out.println("You rolled double sixes " + sixes
            + " out of " + NUMBER + " rolls.");
}

}

Body:
Here is your problem

if(die1Value == die2Value)
    count++;

None of your else if statements run when this statement is true.

For instance, if you roll a 4 and 4, then count will increment, and the following else if will never run:

else if(die1Value == 4 && die2Value == 4)
        fours++; // Never runs


问:
Using ng-if inside ng-repeat doesn't work
I have an array called polls with many objects poll. Each poll has a property moduleState which is initally set to the string "notVoted". The moduleState for an individual poll may later  be set to the string "voted". Here is the template for one of my partials:

```<code><div ng-init="loadPage()">
    <div ng-repeat="poll in polls">
        <div ng-if="poll.moduleState  === 'notVoted'">
          //Template 1
        </div>
        <div ng-if="poll.moduleState === 'voted'">
          //Template 2
        </div>
    </div>
</div>
</code>```

The problem is, both templates are used for each poll in polls. So if there were 3 poll objects in the array polls, the partial would put out:

Template 1

Template 2

Template 1

Template 2

Template 1

Template 2

I suspect this is because of a weird interaction between ng-if and ng-repeat. How can I get it so only one template per poll shows?

Edit: As requested, here is a console.log of a poll object. As you can see, moduleState is in fact set to "notVoted"

答:
Your code is fine ng-if works in ng-repeat:

HTML:

```<code>   <div>
    <div ng-repeat="poll in polls">
        <div ng-if="poll.moduleState  === 'notVoted'">
          <!-- Template 1 -->
          Not Voted: {{poll.name}}
        </div>
        <div ng-if="poll.moduleState === 'voted'">
          <!-- Template 2 -->
          Voted: {{poll.name}}
        </div>
    </div>
</div>

</div>
</code>```

Angular:

```<code>var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

        $scope.polls =
            [
                {
                    "name": "module1",
                    "moduleState": "notVoted"
                },
                {
                    "name": "module2",
                    "moduleState": "voted"
                }
            ];

});
</code>```

Here is the fiddle showing ng-if working with ng-repeat: https://jsfiddle.net/AKMorris/nkqkunfr/

Body:
I have an array called polls with many objects poll. Each poll has a property moduleState which is initally set to the string "notVoted". The moduleState for an individual poll may later  be set to the string "voted". Here is the template for one of my partials:

          //Template 1

          //Template 2

The problem is, both templates are used for each poll in polls. So if there were 3 poll objects in the array polls, the partial would put out:

Template 1

Template 2

Template 1

Template 2

Template 1

Template 2

I suspect this is because of a weird interaction between ng-if and ng-repeat. How can I get it so only one template per poll shows?

Edit: As requested, here is a console.log of a poll object. As you can see, moduleState is in fact set to "notVoted"

Body:
Your code is fine ng-if works in ng-repeat:

HTML:

   <div>
    <div ng-repeat="poll in polls">
        <div ng-if="poll.moduleState  === 'notVoted'">
          <!-- Template 1 -->
          Not Voted: {{poll.name}}
        </div>
        <div ng-if="poll.moduleState === 'voted'">
          <!-- Template 2 -->
          Voted: {{poll.name}}
        </div>
    </div>
</div>

</div>

Angular:

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

        $scope.polls =
            [
                {
                    "name": "module1",
                    "moduleState": "notVoted"
                },
                {
                    "name": "module2",
                    "moduleState": "voted"
                }
            ];

});

Here is the fiddle showing ng-if working with ng-repeat: https://jsfiddle.net/AKMorris/nkqkunfr/


问:
How do I allow all parameters even if they are blank?
I have the following:

```<code>def index
  @dealFilter = DealFilter.new params[:deal_filter].permit(deal_filter: {})
</code>```

It works when parameters are given, but not when they are missing. It gives undefined method ``permit' for nil:NilClass Did you mean? print error. I would like it to work in both cases.

I tried params[:deal_filter] but it complained about ActiveModel::ForbiddenAttributesError.

I tried params.permit(deal_filter: {}) but it said  unknown attribute 'deal_filter' for DealFilter..

I tried params.permit(:deal_filter) but it ignores the parameter values then: Unpermitted parameters: utf8, deal_filter, commit.

答:
If params is blank, we need to set a default value for it using fetch:

params.fetch(:deal_filter, {}).permit(:some_params)

so that params[:deal_filter] will be {} when it is missing.

From your errors, the final code should be:

params.fetch(:deal_filter, {}).permit(:min, :max, :sector_id)

Body:
I have the following:

def index
  @dealFilter = DealFilter.new params[:deal_filter].permit(deal_filter: {})

It works when parameters are given, but not when they are missing. It gives undefined method ``permit' for nil:NilClass Did you mean? print error. I would like it to work in both cases.

I tried params[:deal_filter] but it complained about ActiveModel::ForbiddenAttributesError.

I tried params.permit(deal_filter: {}) but it said  unknown attribute 'deal_filter' for DealFilter..

I tried params.permit(:deal_filter) but it ignores the parameter values then: Unpermitted parameters: utf8, deal_filter, commit.


问:
Detaching disk from stopped instance
I am trying to detach a disk from a stopped instance which is currently holding the disk. here's how I am doing it currently.

```<code>def detach_disk_from_instance(disk_name, zone=GCLOUD_ZONE):
    disk_info = get_disk_info(disk_name=disk_name, zone=zone)
    if disk_info.get('users'):
        instance_name = disk_info['users'][0].rsplit('/').pop()
        logger.info("detatching disk : {} from instance : {}".format(disk_name, instance_name))
        request = compute.instances().detachDisk(
            project=GCLOUD_PROJECT_NAME, zone=zone, instance=instance_name, deviceName=disk_name)
        return make_http_request(request, {})

def wait_for_operation(operation, zone=GCLOUD_ZONE, worker=1):
    logger.info('Waiting for operation {} to finish...'.format(operation))
    with ThreadPoolExecutor(worker) as executor:
        future = executor.submit(_check_operation_status, operation=operation, zone=zone)
        wait([future])
        return future.result()

req = detach_disk_from_instance(disk_name='test-disk')
wait_for_operation(operation=req['name'])
</code>```

above code works if instance which is holding the disk is currently running.
but it doesn't work if instance is stopped. I get the following error when I try to detach disk from a stopped instance.

{'errors': [{'message': "No attached disk found with device name
  'test-disk'", 'code': 'INVALID_USAGE'}]}

and I assure you that disk is still attached to the instance and gcp dashboard also shows that.

答:
TL;DR - You're passing the name of the disk resource instead of the device name by which the disk is attached to the instance.

In the instances.attachDisk request to attach a disk to a VM instance you can specify the device name in the deviceName field of the request.

deviceName

string

Specifies a unique device name of your choice that
  is reflected into the /dev/disk/by-id/google-* tree of a Linux
  operating system running within the instance. This name can be used to
  reference the device for mounting, resizing, and so on, from within
  the instance.

If not specified, the server chooses a default device name to apply to
  this disk, in the form persistent-disks-x, where x is a number
  assigned by Google Compute Engine. This field is only applicable for
  persistent disks.

You will need to use this name as the deviceName query parameter for the instances.detachDisk request.

Required query parameters

deviceName

string

Disk device name to detach.

As mentioned in the doc, if you did not specify a device name while attaching the disk GCE generates a device name in the form persistent-disks-x and you will have to specify this name.

Title: Detaching disk from stopped instance

Body:
I am trying to detach a disk from a stopped instance which is currently holding the disk. here's how I am doing it currently.

def detach_disk_from_instance(disk_name, zone=GCLOUD_ZONE):
    disk_info = get_disk_info(disk_name=disk_name, zone=zone)
    if disk_info.get('users'):
        instance_name = disk_info['users'][0].rsplit('/').pop()
        logger.info("detatching disk : {} from instance : {}".format(disk_name, instance_name))
        request = compute.instances().detachDisk(
            project=GCLOUD_PROJECT_NAME, zone=zone, instance=instance_name, deviceName=disk_name)
        return make_http_request(request, {})

def wait_for_operation(operation, zone=GCLOUD_ZONE, worker=1):
    logger.info('Waiting for operation {} to finish...'.format(operation))
    with ThreadPoolExecutor(worker) as executor:
        future = executor.submit(_check_operation_status, operation=operation, zone=zone)
        wait([future])
        return future.result()

req = detach_disk_from_instance(disk_name='test-disk')
wait_for_operation(operation=req['name'])

above code works if instance which is holding the disk is currently running.
but it doesn't work if instance is stopped. I get the following error when I try to detach disk from a stopped instance.

{'errors': [{'message': "No attached disk found with device name
  'test-disk'", 'code': 'INVALID_USAGE'}]}

and I assure you that disk is still attached to the instance and gcp dashboard also shows that.


问:
Microservices: how to effectively deal with data dependencies between microservices
I am developing an application utilizing the microservices development approach with the mean stack.  I am running into a situation where data needs to be shared between multiple microservices.  For example, let's say I have user, video, message(sending/receiving,inbox, etc.) services.  Now the video and message records belong to an account record.  As users create video and send /receive message there is a foreign key(userId) that has to be associated with the video and message records they create. I have scenarios where I need to display the first, middle and last name associated with each video for example.  Let's now say on the front end a user is scrolling through a list of videos uploaded to the system, 50 at a time.  In the worst case scenario, I could see a situation where a pull of 50 occurs where each video is tied to a unique user.

There seems to be two approaches to this issue:

One, I make an api call to the user service and get each user tied to each video in the list.  This seems inefficient as it could get really chatty if I am making one call per video.  In the second of the api call scenario, I would get the list of video and send a distinct list of user foreign keys to query to get each user tied to each video.  This seems more efficient but still seems like I am losing performance putting everything back together to send out for display or however it needs to be manipulated.

Two, whenever a new user is created, the account service sends a message with the user information each other service needs to a fanout queue and then it is the responsibility of the individual services to add the new user to a table in it's own database thus maintaining loose coupling.  The extreme downside here would be the data duplication and having to have the fanout queue to handle when updates needs to be made to ensure eventual consistency.  Though, in the long run, this approach seems like it would be the most efficient from a performance perspective.

I am torn between these two approaches, as they both have their share of tradeoffs.  Which approach makes the most sense to implement and why?

答:
Don't restrict your design decision to those 2 options you've outlined. The hardest thing about microservices is to get your head around what a service is and how to cut your application into chunks/services that make sense to be implemented as a 'microservice'.

Just because you have those 3 entities (user, video & message) doesn't mean you have to implement 3 services. If your actual use case shows that these services (or entities) depend heavily on each other to fulfil a simple request from the front-end than that's a clear signal that your cutting was not right.

From what I see from your example I'd design 1 microservice that fulfills the request. Remember that one of the design fundamentals of a microservice is to be as independent as possible.
There's no need to over complicate services, it's not SOA.

https://martinfowler.com/articles/microservices.html -> great read!

Regards,
Lars


问:
How to display even number and a multiple of 3 from arraylist
Sorry, maybe I did not explain clearly. This is my pracitce

input a positive integer. If the input is not positive then then your algorithm should output an error message and re-prompt the user for the input. This process should continue to loop until the input is valid. Your algorithm should then output whether or not the input is an even number and a multiple of 3. Note your solution must make appropriate use of sub modules.

I have to create a method which gets a positive number from user input, And I need to display even numbers and multiple of 3 from this ArrayList. I have written code for that but I have struggled with how to use another submodule to display this ArrayList.

```<code>import java.util.ArrayList;
import java.util.*;

public class Array {

    public static void main(String[] args)
    {

        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> list;
        list = new ArrayList<Integer>();
         int number = -1;
        printList(list, number );
        System.out.println("Enter number.  Enter 0 to end.");
        while (true)
        {
            System.out.print(" ");
            number = sc.nextInt();

        while( number < 0)
        {
        System.out.print("Enter your next positive integer, or 0 to end: ");
        number = sc.nextInt();
        }
         if (number == 0)
                break;
            list.add(number);
        }

    }
        public static void printList (ArrayList<Integer> list, int number)
        {
            for(int i = 0;i <= number.size(); i++)
            {
            if(i % 2 ==0 && i % 3 ==0)
            {
                 System.out.println(list(i));
            }
            }
        }
    }
</code>```

答:
I think you are looking for a program behaving like this right?

```<code>public class Array {

    public static void main(String... args) {
        Scanner sc = new Scanner(System.in);
        List<Integer> list = new ArrayList<>();
        int number;
        do {
            System.out.print("Enter a positive integer or 0 to end: ");
            number = sc.nextInt();
            if (number > 0) { list.add(number); }
        } while (number != 0);

        for (int i = 0; i < list.size(); i++) {
            int number = list.get(i);
            if (number % 2 == 0 && number % 3 == 0) {
                System.out.println(number);
            }
        }
    }
}
</code>```

And due to the IndexOutOfBoundException discussion, consider to print your numbers in a more safe and readable way like this (if you are using Java 8):

```<code>list.stream().filter(num -> num % 2 == 0)
             .filter(num -> num % 3 == 0)
             .forEach(System.out::println);
</code>```

Body:
Sorry, maybe I did not explain clearly. This is my pracitce

input a positive integer. If the input is not positive then then your algorithm should output an error message and re-prompt the user for the input. This process should continue to loop until the input is valid. Your algorithm should then output whether or not the input is an even number and a multiple of 3. Note your solution must make appropriate use of sub modules.

I have to create a method which gets a positive number from user input, And I need to display even numbers and multiple of 3 from this ArrayList. I have written code for that but I have struggled with how to use another submodule to display this ArrayList.

import java.util.ArrayList;
import java.util.*;

public class Array {

    public static void main(String[] args)
    {

        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> list;
        list = new ArrayList<Integer>();
         int number = -1;
        printList(list, number );
        System.out.println("Enter number.  Enter 0 to end.");
        while (true)
        {
            System.out.print(" ");
            number = sc.nextInt();

        while( number < 0)
        {
        System.out.print("Enter your next positive integer, or 0 to end: ");
        number = sc.nextInt();
        }
         if (number == 0)
                break;
            list.add(number);
        }

    }
        public static void printList (ArrayList<Integer> list, int number)
        {
            for(int i = 0;i <= number.size(); i++)
            {
            if(i % 2 ==0 && i % 3 ==0)
            {
                 System.out.println(list(i));
            }
            }
        }
    }

Body:
I think you are looking for a program behaving like this right?

public class Array {

    public static void main(String... args) {
        Scanner sc = new Scanner(System.in);
        List<Integer> list = new ArrayList<>();
        int number;
        do {
            System.out.print("Enter a positive integer or 0 to end: ");
            number = sc.nextInt();
            if (number > 0) { list.add(number); }
        } while (number != 0);

        for (int i = 0; i < list.size(); i++) {
            int number = list.get(i);
            if (number % 2 == 0 && number % 3 == 0) {
                System.out.println(number);
            }
        }
    }
}

And due to the IndexOutOfBoundException discussion, consider to print your numbers in a more safe and readable way like this (if you are using Java 8):

list.stream().filter(num -> num % 2 == 0)
             .filter(num -> num % 3 == 0)
             .forEach(System.out::println);


问:
Installing SQL Server Express 2005 from VS setup project - named instance
I'm installing SQL Server Express 2005 from my Visual Studio 2008 setup project.

This works fine and installs the instance "SQLExpress".

Does anyone know if you can pass it some kind of command line to install or change a property to give it a different instance name?

答:
If you are calling out to SQL Server's setup.exe from your installer I believe you can pass the instance name as an argument, like this: setup.exe INSTANCENAME=YourInstance

See here for more info: http://technet.microsoft.com/en-us/library/ms144259(SQL.90).aspx


问:
Display and dismiss a modal view controller in Swift
When a button is pressed I want to segue between two view controllers by using a Modal Transition style CoverVertical and then dismiss it. There is allot of info out there for how to do it in objective C but can't find any good info in Swift. So far I've done this but I don't think it's correct:

```<code> @IBAction func insertStatus(sender: UIButton) {

         var StatusVC: StatusViewController = StatusViewController()
    var modalStyle: UIModalTransitionStyle = UIModalTransitionStyle.CoverVertical
    StatusVC.modalTransitionStyle = modalStyle
    self.presentViewController(StatusVC, animated: true, completion: nil)

    }
</code>```

The Dismiss I am using like so does not work either:

```<code>@IBAction func statusSaved(sender: UIBarButtonItem) {

        self.dismissViewControllerAnimated(false, completion: { () -> Void in
            let usersVC: UsersViewController = self.storyboard?.instantiateViewControllerWithIdentifier("UsersViewController") as UsersViewController
       })
    }
</code>```

答:
Its pretty easy :

to dismiss a modal view with swift 3.0 :
 Use dismiss Api like below :

```<code>> @IBAction func dismissClick(_ sender: Any) {
>         dismiss(animated: true, completion: nil)
>
>     }
</code>```

For present :

```<code>> @IBAction func dismissClick(_ sender: Any) {
> present(UIViewController(), animated: true, completion: nil)
>
>     }
</code>```

For more details here you go :

https://developer.apple.com/documentation/uikit/uiviewcontroller#//apple_ref/doc/uid/TP40006926-CH3-SW96

Body:
When a button is pressed I want to segue between two view controllers by using a Modal Transition style CoverVertical and then dismiss it. There is allot of info out there for how to do it in objective C but can't find any good info in Swift. So far I've done this but I don't think it's correct:

 @IBAction func insertStatus(sender: UIButton) {

         var StatusVC: StatusViewController = StatusViewController()
    var modalStyle: UIModalTransitionStyle = UIModalTransitionStyle.CoverVertical
    StatusVC.modalTransitionStyle = modalStyle
    self.presentViewController(StatusVC, animated: true, completion: nil)

    }

The Dismiss I am using like so does not work either:

@IBAction func statusSaved(sender: UIBarButtonItem) {

        self.dismissViewControllerAnimated(false, completion: { () -> Void in
            let usersVC: UsersViewController = self.storyboard?.instantiateViewControllerWithIdentifier("UsersViewController") as UsersViewController
       })
    }

Body:
Its pretty easy :

to dismiss a modal view with swift 3.0 :
 Use dismiss Api like below :

> @IBAction func dismissClick(_ sender: Any) {
>         dismiss(animated: true, completion: nil)
>
>     }

For present :

> @IBAction func dismissClick(_ sender: Any) {
> present(UIViewController(), animated: true, completion: nil)
>
>     }

For more details here you go :

https://developer.apple.com/documentation/uikit/uiviewcontroller#//apple_ref/doc/uid/TP40006926-CH3-SW96


问:
Can't register code-push
I try to check code-push.

I use Cordova into a docker machine into a virtual machine, in Windows.

My problem is that when I try to create an account with "code-push register", I get "A browser is being launched to authenticate your account...". This doesn't help me at all because this runs into a docker machine and no browser can start.
What can I do?

It could help me if I could link a Microsoft account.

Thanks in advance

答:
You can use following commands to be able to authenticate against the CodePush service without launching a browser and/or without needing to use your GitHub and/or Microsoft credentials (e.g. in a CI environment),

```<code>code-push access-key add "VSTS Integration"
</code>```

By default, access keys expire in 60 days. You can specify a different expiry duration by using the --ttl option and passing in a human readable duration string (e.g. "2d" => 2 days, "1h 15 min" => 1 hour and 15 minutes). For security, the key will only be shown once on creation, so remember to save it somewhere if needed!

After creating the new key, you can specify its value using the --accessKey flag of the login command, which allows you to perform "headless" authentication, as opposed to launching a browser.

code-push login --accessKey <accessKey>

if at any point you need to change a key's name and/or expiration date, you can use the following command:

```<code>code-push access-key patch <accessKeyName> --name "new name" --ttl 10d
</code>```

Title: Can't register code-push

Body:
You can use following commands to be able to authenticate against the CodePush service without launching a browser and/or without needing to use your GitHub and/or Microsoft credentials (e.g. in a CI environment),

code-push access-key add "VSTS Integration"

By default, access keys expire in 60 days. You can specify a different expiry duration by using the --ttl option and passing in a human readable duration string (e.g. "2d" => 2 days, "1h 15 min" => 1 hour and 15 minutes). For security, the key will only be shown once on creation, so remember to save it somewhere if needed!

After creating the new key, you can specify its value using the --accessKey flag of the login command, which allows you to perform "headless" authentication, as opposed to launching a browser.

code-push login --accessKey <accessKey>

if at any point you need to change a key's name and/or expiration date, you can use the following command:

code-push access-key patch <accessKeyName> --name "new name" --ttl 10d


答:
So actually they have created virtual host in local machine.

You also can create virtual host in your local machine, Please find below example so you can understand it in brief.

Open this file if you are using xampp, and add this line at the end of page.

c:\xampp\apache\conf\extra\httpd-vhosts.conf

```<code><VirtualHost codeigniter-ajaxcrud.local:80>
      DocumentRoot "C:/xampp/htdocs/codeigniter-ajaxcrud"
      ServerName codeigniter-ajaxcrud.local
      ServerAlias www.codeigniter-ajaxcrud.local
      <Directory "c:/xampp/htdocs/codeigniter-ajaxcrud">
          Options Indexes FollowSymLinks Includes ExecCGI
          AllowOverride All
          Require all Granted
      </Directory>
</VirtualHost>
</code>```

Once you done with this add codeigniter-ajaxcrud.local in hosts file.
This file will be located in below location in windows.

Drivers/etc/host

add below line at end of the page.

```<code>127.0.0.1         codeigniter-ajaxcrud.local
</code>```

Once you done with this please save all files and restart apache server.
Than this host will work.

Title: Dot in base url codeigniter

Body:
So actually they have created virtual host in local machine.

You also can create virtual host in your local machine, Please find below example so you can understand it in brief.

Open this file if you are using xampp, and add this line at the end of page.

c:\xampp\apache\conf\extra\httpd-vhosts.conf

<VirtualHost codeigniter-ajaxcrud.local:80>
      DocumentRoot "C:/xampp/htdocs/codeigniter-ajaxcrud"
      ServerName codeigniter-ajaxcrud.local
      ServerAlias www.codeigniter-ajaxcrud.local
      <Directory "c:/xampp/htdocs/codeigniter-ajaxcrud">
          Options Indexes FollowSymLinks Includes ExecCGI
          AllowOverride All
          Require all Granted
      </Directory>
</VirtualHost>

Once you done with this add codeigniter-ajaxcrud.local in hosts file.
This file will be located in below location in windows.

Drivers/etc/host

add below line at end of the page.

127.0.0.1         codeigniter-ajaxcrud.local

Once you done with this please save all files and restart apache server.
Than this host will work.


问:
NServiceBus: How to move messages from the error queue
I had a bug in my application that cause a number of messages to be moved into the error queue.  Now that I have fixed the bug, is there a simple way to move them back to the original queue so they can be processed?</p>

答:
You can use a simple command line tool, ReturnToSourceQueue.exe, which is included with NServiceBus.

It's located in the tools folder IIRC.


问:
Domain Driven Design and Automapper
I have a circular reference problem or a SOLID Violation in the following architecture:

```<code> MVC / WebAPI (Presentation Layer)
     - ViewModels
     - Automapper

ApplicationServices
    - AppServices

Domain
     - Services
     - Models (Business Layer)

Infra.Data
     - Repositories
</code>```

I need to perform the Mappings between the ViewModel and DTOs. However, I have a reference between MVC and Domain (That works fine). The Mapping should be done in the topmost layer, where it is the Presentation Layer. How to decouple it, make the mapping in Presentation Layer without reference the Domain?

If I Decouple the Automapper from Presentation Layer, I will have a circular reference because it needs the ViewModel, and the Presentation needs to call the mapping.

答:
It depends a bit on how you defined your interface. That will tell you where you need to do your mapping

When calling the next layer from the presentation layer your code would have to look like this

```<code> ISomeService MyService;//Resolve this with your favorite dependency injection fromwork

 var result = MyService.MySeriviceCall(Automapper.Map<SomeEntity>(fooDto));
</code>```

Notice here that the presentation layer depends on the interface (not implementation) of your service with everything that interface needs.

If your interface looks like this

```<code> interface SomeService(SomeEntity foo)
</code>```

THen you need to do your mapping in the presentation layer. But notice in order to call this service you already need to be aware of your domain layer since it's defined in your interface.

However, If your interface looks like this

```<code>interface SomeService(SomeDTo foo);
</code>```

Then the reference is from your applicationService to both your domain model and presentation layer. And the mapping is done in the application service (my prefered place, and now you have Dependency Inversion).
Note: you can put your DTO's in a separate project so you only need to be aware of those.

Also notice that defining your mapping and calling your mapping can de decoupled as well (https://github.com/AutoMapper/AutoMapper/wiki/Configuration)

Title: Domain Driven Design and Automapper

Body:
I have a circular reference problem or a SOLID Violation in the following architecture:

 MVC / WebAPI (Presentation Layer)
     - ViewModels
     - Automapper

ApplicationServices
    - AppServices

Domain
     - Services
     - Models (Business Layer)

Infra.Data
     - Repositories

I need to perform the Mappings between the ViewModel and DTOs. However, I have a reference between MVC and Domain (That works fine). The Mapping should be done in the topmost layer, where it is the Presentation Layer. How to decouple it, make the mapping in Presentation Layer without reference the Domain?

If I Decouple the Automapper from Presentation Layer, I will have a circular reference because it needs the ViewModel, and the Presentation needs to call the mapping.

Body:
It depends a bit on how you defined your interface. That will tell you where you need to do your mapping

When calling the next layer from the presentation layer your code would have to look like this

 ISomeService MyService;//Resolve this with your favorite dependency injection fromwork

 var result = MyService.MySeriviceCall(Automapper.Map<SomeEntity>(fooDto));

Notice here that the presentation layer depends on the interface (not implementation) of your service with everything that interface needs.

If your interface looks like this

 interface SomeService(SomeEntity foo)

THen you need to do your mapping in the presentation layer. But notice in order to call this service you already need to be aware of your domain layer since it's defined in your interface.

However, If your interface looks like this

interface SomeService(SomeDTo foo);

Then the reference is from your applicationService to both your domain model and presentation layer. And the mapping is done in the application service (my prefered place, and now you have Dependency Inversion).
Note: you can put your DTO's in a separate project so you only need to be aware of those.

Also notice that defining your mapping and calling your mapping can de decoupled as well (https://github.com/AutoMapper/AutoMapper/wiki/Configuration)


问:
Finding Duplicate record on phpmyadmin Server type: MariaDB
I have a table of students and I wish to display a list of all occurances where:

A student's name is shared with at least one other student

The frequency of each duplication

My query is as follows:

```<code>SELECT
    name
    , COUNT(*) AS frequency
FROM
    student
GROUP BY
    name
HAVING
    COUNT(*) > 1
</code>```

My results are as follows:

```<code>1054 - Unknown column 'gt' in 'having clause'
</code>```

Has anyone else experienced this error?

I don't understand it.

答:
That is an editing problem.  What the heck are you using to type your SQL?

The "htmlentity" for > is >.  Fix that character; the gt will work, and the HAVING will work.  (And it work faster thn using a subquery.)

Body:
I have a table of students and I wish to display a list of all occurances where:

A student's name is shared with at least one other student

The frequency of each duplication

My query is as follows:

SELECT
    name
    , COUNT(*) AS frequency
FROM
    student
GROUP BY
    name
HAVING
    COUNT(*) > 1

My results are as follows:

1054 - Unknown column 'gt' in 'having clause'

Has anyone else experienced this error?

I don't understand it.

Body:
That is an editing problem.  What the heck are you using to type your SQL?

The "htmlentity" for > is &gt;.  Fix that character; the gt will work, and the HAVING will work.  (And it work faster thn using a subquery.)


问:
How to change Custom Spinner Text color android
I am working on a android project where i have to implement a custom spinner in the register form for selecting the Profession,Family name. Spinner functionality is working fine but spinner is a custom spinner and  its not accepting the text color to be changed. Is there any way i can change the color of the text?

Below is my xml code:

```<code><com.infantstudio.CatholicMithrulu.Spinner.SearchableSpinnerProfestion
    android:id="@+id/profestion_spinner"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:entries="@array/profestion"
    app:hintTextCountry="Select"/>
</code>```

答:
For creating the custom spinner you need to set the custom layout in which you change the text color like the following example

```<code>ArrayAdapter<String>  arrayAdapter = new ArrayAdapter<String>(this, R.layout.spinner_adapter, getResources().getStringArray(R.array.profestion));
    profestion_spinner.setAdapter(arrayAdapter);
</code>```

you may chnage the text color here:-
spinner_adapter.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="@dimen/_12sdp"
    android:padding="@dimen/_8sdp"
    android:textColor="@color/txt_color">

</TextView>
</code>```

Body:
I am working on a android project where i have to implement a custom spinner in the register form for selecting the Profession,Family name. Spinner functionality is working fine but spinner is a custom spinner and  its not accepting the text color to be changed. Is there any way i can change the color of the text?

Below is my xml code:

<com.infantstudio.CatholicMithrulu.Spinner.SearchableSpinnerProfestion
    android:id="@+id/profestion_spinner"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:entries="@array/profestion"
    app:hintTextCountry="Select"/>

Body:
For creating the custom spinner you need to set the custom layout in which you change the text color like the following example

ArrayAdapter<String>  arrayAdapter = new ArrayAdapter<String>(this, R.layout.spinner_adapter, getResources().getStringArray(R.array.profestion));
    profestion_spinner.setAdapter(arrayAdapter);

you may chnage the text color here:-
spinner_adapter.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="@dimen/_12sdp"
    android:padding="@dimen/_8sdp"
    android:textColor="@color/txt_color">

</TextView>