问:
"No Socket Available" - Wifi Shield on Arduino
I have an LDR/Photocell which sends a value 1 or 0 (depending on the value) to a text file on my web address. The code works for a few seconds then prints out No Socket available.

Any help will be appreciated; code below.

```<code>#include <SPI.h>
#include <WiFi.h>

int LDR = A0;
int LED = 11;
char ssid[] = "SSID";
char password[] = "password";
int status = WL_IDLE_STATUS;

char server[] = "www.example.com";
int value;

void setup() {
  Serial.begin(9600);
  pinMode(LDR, INPUT);
  pinMode(LED, OUTPUT);
  connectWifi();
  printWifiStatus();
  // postData();
}

void loop() {
  value = analogRead(LDR);
  postData();

  delay(10000);
}

void connectWifi() {
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, password);
    delay(500);
  }
}

void printWifiStatus() {
  // Print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // Print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // Print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

void postData() {
  WiFiClient client;
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");
    if (value > 350) {
      Serial.println("0");
      digitalWrite(LED, LOW);
      String data = "value=0";
      client.print("GET /example/client.php?");
      client.print(data);
      client.println(" HTTP/1.1");
      client.println("Host: www.example.com");
      client.println("Connection: close");
      client.println(); client.println();
      //client.stop();
    } else {
      Serial.println("1");
      digitalWrite(LED, HIGH);
      String data = "value=1";
      client.print("GET /example/client.php?");
      client.print(data);
      client.println(" HTTP/1.1");
      client.println("Host: www.example.com");
      client.println("Connection: close");
      client.println(); client.println();
      //client.stop();
    }
  } else {
    Serial.println("Connection failed");
    client.stop();
  }

}
</code>```

Output:

```<code>Attempting to connect to SSID
SSID: SSID
IP Address: 255.255.255.255
signal strength (RSSI):-47 dBm
Connecting...
1
Connecting...
0
Connecting...
0
Connecting...
0
No Socket available
Connection failed
No Socket available
Connection failed
No Socket available
Connection failed
No Socket available
</code>```

Actual web address omitted.

答:
first of all, try not use "delay()" and your are calling this function "postData()" every 0,5 seconds. Try use the millis() function to do the timer thing, like this:

```<code>unsigned long timerBefore = 0;
const int timer = 1000; //1 second
</code>```

now inside your loop()

```<code>unsigned long timerNow=millis();
if((unsigned long)(timerNow-timerBefore)>=timer){
   postData();
   timerBefore=millis();
}
</code>```

that code i'll not "pause" your microcontroller and will call that function every one second.

Body:
I have an LDR/Photocell which sends a value 1 or 0 (depending on the value) to a text file on my web address. The code works for a few seconds then prints out No Socket available.

Any help will be appreciated; code below.

#include <SPI.h>
#include <WiFi.h>

int LDR = A0;
int LED = 11;
char ssid[] = "SSID";
char password[] = "password";
int status = WL_IDLE_STATUS;

char server[] = "www.example.com";
int value;

void setup() {
  Serial.begin(9600);
  pinMode(LDR, INPUT);
  pinMode(LED, OUTPUT);
  connectWifi();
  printWifiStatus();
  // postData();
}

void loop() {
  value = analogRead(LDR);
  postData();

  delay(10000);
}

void connectWifi() {
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, password);
    delay(500);
  }
}

void printWifiStatus() {
  // Print the SSID of the network you're attached to
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // Print your WiFi shield's IP address
  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  // Print the received signal strength
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

void postData() {
  WiFiClient client;
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");
    if (value > 350) {
      Serial.println("0");
      digitalWrite(LED, LOW);
      String data = "value=0";
      client.print("GET /example/client.php?");
      client.print(data);
      client.println(" HTTP/1.1");
      client.println("Host: www.example.com");
      client.println("Connection: close");
      client.println(); client.println();
      //client.stop();
    } else {
      Serial.println("1");
      digitalWrite(LED, HIGH);
      String data = "value=1";
      client.print("GET /example/client.php?");
      client.print(data);
      client.println(" HTTP/1.1");
      client.println("Host: www.example.com");
      client.println("Connection: close");
      client.println(); client.println();
      //client.stop();
    }
  } else {
    Serial.println("Connection failed");
    client.stop();
  }

}

Output:

Attempting to connect to SSID
SSID: SSID
IP Address: 255.255.255.255
signal strength (RSSI):-47 dBm
Connecting...
1
Connecting...
0
Connecting...
0
Connecting...
0
No Socket available
Connection failed
No Socket available
Connection failed
No Socket available
Connection failed
No Socket available

Actual web address omitted.

Body:
first of all, try not use "delay()" and your are calling this function "postData()" every 0,5 seconds. Try use the millis() function to do the timer thing, like this:

unsigned long timerBefore = 0;
const int timer = 1000; //1 second

now inside your loop()

unsigned long timerNow=millis();
if((unsigned long)(timerNow-timerBefore)>=timer){
   postData();
   timerBefore=millis();
}

that code i'll not "pause" your microcontroller and will call that function every one second.


来源: stackexchange

问:
Find index of an element in javascript array of objects
I am new to javascript and want to find the index of the given key-value at the bottom but not able to do so. Where am i wrong? The data in the array is copied form a json file which is valid as checked on jsonlint.

var productArray=[
{
 "name1":"Electronics",
 "id1":{
         "products1":{
                   "id":1.1,
                   "name":"Microsoft Keyboard",
                   "description":"good keyboard",
                   "rating":3,
                   "price":500,
                   "freeDeliv":true,
                   "seller":"MS",
                   "quanAvl":10
                     },
         "products2":{
                   "id":1.2,
                   "name":"ASUS phone",
                   "description":"good phone",
                   "rating":4,
                   "price":10000,
                   "freeDeliv":true,
                   "seller":"ASUS",
                   "quanAvl":10
                     },
         "products3":{
                   "id":1.3,
                   "name":"iPhone",
                   "description":"good phone",
                   "rating":3,
                   "price":50000,
                   "freeDeliv":false,
                   "seller":"Apple",
                   "quanAvl":100
                     }
       },

 "name2":"Clothing",
 "id2":{
         "products4":{
                   "id":2.1,
                   "name":"Jeans",
                   "description":"good Jeans",
                   "rating":3,
                   "price":800,
                   "freeDeliv":true,
                   "seller":"Levis",
                   "quanAvl":100
                     },
         "products5":{
                   "id":2.2,
                   "name":"TShirt",
                   "description":"good TShirt",
                   "rating":4,
                   "price":1000,
                   "freeDeliv":true,
                   "seller":"Peter",
                   "quanAvl":1000
                     },
         "products6":{
                   "id":2.3,
                   "name":"Sherwani",
                   "description":"very good",
                   "rating":4,
                   "price":50000,
                   "freeDeliv":false,
                   "seller":"Maanyavar",
                   "quanAvl":1000
                     }

}},

];

var display=function(productArray,prodKey,value){
 for(x in productArray)
 {
  if(productArray[x][prodKey]==value)
  {
   console.log(x);
  }
  else{
   alert("Not Found");
  }
 }
}
display(productArray,"name","Sherwani");```

答:
this is the answer. I have tried this

```<code>var display=function(productArray_,prodKey,value){

    p = productArray_[0]["id2"];

    found = false;

    for (var key in p) {
      if (p.hasOwnProperty(key)) {
        p2 = p[key];
        for(var key2 in p2){
            if(p2.hasOwnProperty(key2)){
                if(key2 == prodKey && p2[key2] == value){
                    console.log(key2); //index of value you looking for
                    console.log(p2[key2]) //value from index you looking for

                    alert(key2);

                    found = true;
                }
            }
        }
      }
    }

    if(!found)
        alert("not found");
}

display(productArray,"name","Sherwani");
</code>```

but I'm agree, this is a very bad object structure. you should change the json structure so you can parse it more easily

UPDATE: you should avoid creating json object wherever possible (begins with "{" and ends with "}"), and instead create json array (begins with "[" and ends with "]").

here is a better structure and how to parse it

```<code>var productArray=[
  {
    "name": "Electronics",
    "list": [
      {
        "code": "products1",
        "id": 1.1,
        "name": "Microsoft Keyboard",
        "description": "good keyboard",
        "rating": 3,
        "price": 500,
        "freeDeliv": true,
        "seller": "MS",
        "quanAvl": 10
      },
      {
        "code": "products2",
        "id": 1.2,
        "name": "ASUS phone",
        "description": "good phone",
        "rating": 4,
        "price": 10000,
        "freeDeliv": true,
        "seller": "ASUS",
        "quanAvl": 10
      },
      {
        "code": "products3",
        "id": 1.3,
        "name": "iPhone",
        "description": "good phone",
        "rating": 3,
        "price": 50000,
        "freeDeliv": false,
        "seller": "Apple",
        "quanAvl": 100
      }
    ]
  },
  {
    "name": "Clothing",
    "list": [
      {
        "code": "products4",
        "id": 2.1,
        "name": "Jeans",
        "description": "good Jeans",
        "rating": 3,
        "price": 800,
        "freeDeliv": true,
        "seller": "Levis",
        "quanAvl": 100
      },
      {
        "code": "products5",
        "id": 2.2,
        "name": "TShirt",
        "description": "good TShirt",
        "rating": 4,
        "price": 1000,
        "freeDeliv": true,
        "seller": "Peter",
        "quanAvl": 1000
      },
      {
        "code": "products6",
        "id": 2.3,
        "name": "Sherwani",
        "description": "very good",
        "rating": 4,
        "price": 50000,
        "freeDeliv": false,
        "seller": "Maanyavar",
        "quanAvl": 1000
      }
    ]
  },

]

var display=function(productArray_,prodKey,value){
    found = false;

    for(var key in productArray_){
        for(var key2 in productArray_[key]){
            if(key2 == "list"){
                for(var key3 in productArray_[key][key2]){
                    for(var key4 in productArray_[key][key2][key3]){
                        if(key4 == prodKey
                            && productArray_[key][key2][key3][key4] == value
                            ){
                            console.log(key4);
                            console.log(productArray_[key][key2][key3][key4]);
                            alert(key4);

                            found = true;
                        }
                    }
                }
            }
        }
    }

    if(!found)
        alert("not found");
}

display(productArray,"name","Sherwani");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
this is the answer. I have tried this

var display=function(productArray_,prodKey,value){

    p = productArray_[0]["id2"];

    found = false;

    for (var key in p) {
      if (p.hasOwnProperty(key)) {
        p2 = p[key];
        for(var key2 in p2){
            if(p2.hasOwnProperty(key2)){
                if(key2 == prodKey && p2[key2] == value){
                    console.log(key2); //index of value you looking for
                    console.log(p2[key2]) //value from index you looking for

                    alert(key2);

                    found = true;
                }
            }
        }
      }
    }

    if(!found)
        alert("not found");
}

display(productArray,"name","Sherwani");

but I'm agree, this is a very bad object structure. you should change the json structure so you can parse it more easily

UPDATE: you should avoid creating json object wherever possible (begins with "{" and ends with "}"), and instead create json array (begins with "[" and ends with "]").

here is a better structure and how to parse it

var productArray=[
  {
    "name": "Electronics",
    "list": [
      {
        "code": "products1",
        "id": 1.1,
        "name": "Microsoft Keyboard",
        "description": "good keyboard",
        "rating": 3,
        "price": 500,
        "freeDeliv": true,
        "seller": "MS",
        "quanAvl": 10
      },
      {
        "code": "products2",
        "id": 1.2,
        "name": "ASUS phone",
        "description": "good phone",
        "rating": 4,
        "price": 10000,
        "freeDeliv": true,
        "seller": "ASUS",
        "quanAvl": 10
      },
      {
        "code": "products3",
        "id": 1.3,
        "name": "iPhone",
        "description": "good phone",
        "rating": 3,
        "price": 50000,
        "freeDeliv": false,
        "seller": "Apple",
        "quanAvl": 100
      }
    ]
  },
  {
    "name": "Clothing",
    "list": [
      {
        "code": "products4",
        "id": 2.1,
        "name": "Jeans",
        "description": "good Jeans",
        "rating": 3,
        "price": 800,
        "freeDeliv": true,
        "seller": "Levis",
        "quanAvl": 100
      },
      {
        "code": "products5",
        "id": 2.2,
        "name": "TShirt",
        "description": "good TShirt",
        "rating": 4,
        "price": 1000,
        "freeDeliv": true,
        "seller": "Peter",
        "quanAvl": 1000
      },
      {
        "code": "products6",
        "id": 2.3,
        "name": "Sherwani",
        "description": "very good",
        "rating": 4,
        "price": 50000,
        "freeDeliv": false,
        "seller": "Maanyavar",
        "quanAvl": 1000
      }
    ]
  },

]

var display=function(productArray_,prodKey,value){
    found = false;

    for(var key in productArray_){
        for(var key2 in productArray_[key]){
            if(key2 == "list"){
                for(var key3 in productArray_[key][key2]){
                    for(var key4 in productArray_[key][key2][key3]){
                        if(key4 == prodKey
                            && productArray_[key][key2][key3][key4] == value
                            ){
                            console.log(key4);
                            console.log(productArray_[key][key2][key3][key4]);
                            alert(key4);

                            found = true;
                        }
                    }
                }
            }
        }
    }

    if(!found)
        alert("not found");
}

display(productArray,"name","Sherwani");


问:
Javax Validation
I'm trying to use Javax Validation with Spring. When I run my application, I get this strange error message

```<code>javax.servlet.ServletException: Servlet.init() for servlet dispatcher threw exception
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
    java.lang.Thread.run(Thread.java:619)

root cause

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.engine.ConfigurationImpl
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1412)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:563)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:872)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
    javax.servlet.GenericServlet.init(GenericServlet.java:212)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
    java.lang.Thread.run(Thread.java:619)

root cause

java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.engine.ConfigurationImpl
    org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:43)
    javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:269)
    org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:161)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1469)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1409)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:563)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:872)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
    javax.servlet.GenericServlet.init(GenericServlet.java:212)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
    java.lang.Thread.run(Thread.java:619)
</code>```

I have hibernate-validator-4.0.2 GA.jar in my classpath which seems to have the missing class. I also use jdk 6. What is going wrong? I've googled, but no answer is found.

答: Found the solution. My slf4j jar versions were not matching together, aswell as I had the undirect libraries.</p>

ContentLicense: CC BY-SA 2.5

Title: Javax Validation

Body:
I'm trying to use Javax Validation with Spring. When I run my application, I get this strange error message

javax.servlet.ServletException: Servlet.init() for servlet dispatcher threw exception
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
    java.lang.Thread.run(Thread.java:619)

root cause

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.engine.ConfigurationImpl
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1412)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:563)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:872)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
    javax.servlet.GenericServlet.init(GenericServlet.java:212)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
    java.lang.Thread.run(Thread.java:619)

root cause

java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.validator.engine.ConfigurationImpl
    org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:43)
    javax.validation.Validation$GenericBootstrapImpl.configure(Validation.java:269)
    org.springframework.validation.beanvalidation.LocalValidatorFactoryBean.afterPropertiesSet(LocalValidatorFactoryBean.java:161)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1469)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1409)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:563)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:872)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:442)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:458)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:339)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:306)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
    javax.servlet.GenericServlet.init(GenericServlet.java:212)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849)
    org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454)
    java.lang.Thread.run(Thread.java:619)

I have hibernate-validator-4.0.2 GA.jar in my classpath which seems to have the missing class. I also use jdk 6. What is going wrong? I've googled, but no answer is found.


问:
How to insert text box values from C# into Oracle Database
Okay I'm new to all of this and am struggling to insert TextBox values (user input) in Windows Form Application and storing these into an Oracle Database Table.

C# code:

```<code>string oradb = "DATA SOURCE = larry.uopnet.plymouth.ac.uk:1521/orcl.fost.plymouth.ac.uk;PERSIST SECURITY INFO = True;USER ID = xxxxxxxxxx;password = xxxxxxxxx";

OracleConnection con = new OracleConnection(oradb);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "Insert into USER.Client VALUES (txtBoxClientName, txtBoxClientCity, txtBoxClientCountry, txtBoxClientNumber, txtBoxClientURL, comboClientStatus)";

int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
    MessageBox.Show("Please fill in required fields");
else
    MessageBox.Show("Client has been added");
con.Dispose();
</code>```

This error appears at the int rowsUpdated = cmd.ExecuteNonQuery(); line - An unhandled exception of type Oracle.DataAccess.Client.OracleException occurred in Oracle.DataAccess.dll

Trigger code in Oracle:

```<code>create or replace TRIGGER trg_client_ClientID
BEFORE INSERT ON client FOR EACH ROW
BEGIN
  :NEW.ClientID := seq_client_ClientID.nextval;
END;
</code>```

答:
I've managed to fix it with the help of adding in the OracleException and ArgumentException and by using the Parameter code from Elkhan - here is my altered and working code:</p>

```<code>    private void btnClientSave_Click(object sender, EventArgs e)
    {

        string oradb = "DATA SOURCE = larry.uopnet.plymouth.ac.uk:1521/orcl.fost.plymouth.ac.uk;PERSIST SECURITY INFO = True;USER ID = xxxxxxxxx;password = xxxxxxxx";
        string insertquery = "Insert into Client VALUES (:1, :2, :3, :4, :5, :6, :7)";

        OracleConnection con = new OracleConnection(oradb);
        con.Open();
        OracleCommand cmd = new OracleCommand();
        cmd.Connection = con;
        cmd.CommandText = insertquery;
        try
        {

            cmd.Parameters.Add(new OracleParameter("1", OracleDbType.Decimal, ParameterDirection.ReturnValue));
            cmd.Parameters.Add(new OracleParameter("2", OracleDbType.Varchar2, txtBoxClientName.Text, ParameterDirection.Input));
            cmd.Parameters.Add(new OracleParameter("3", OracleDbType.Varchar2, txtBoxClientCity.Text, ParameterDirection.Input));
            cmd.Parameters.Add(new OracleParameter("4", OracleDbType.Varchar2, txtBoxClientCountry.Text, ParameterDirection.Input));
            cmd.Parameters.Add(new OracleParameter("5", OracleDbType.Varchar2, txtBoxClientNumber.Text, ParameterDirection.Input));
            cmd.Parameters.Add(new OracleParameter("6", OracleDbType.Varchar2, txtBoxClientURL.Text, ParameterDirection.Input));
            cmd.Parameters.Add(new OracleParameter("7", OracleDbType.Varchar2, comboClientStatus.Text, ParameterDirection.Input));

            cmd.ExecuteNonQuery();

            MessageBox.Show("Client has been added");
            con.Close();
            Close();
        }
        catch (OracleException e1)
        {
            MessageBox.Show("Error: " + e1.Message);
        }
        catch (ArgumentException e2)
        {
            MessageBox.Show("Error: " + e2.Message);
        }
        finally
        {
            cmd.Dispose();
            con.Dispose();
        }
</code>```

Body:
Okay I'm new to all of this and am struggling to insert TextBox values (user input) in Windows Form Application and storing these into an Oracle Database Table.

C# code:

string oradb = "DATA SOURCE = larry.uopnet.plymouth.ac.uk:1521/orcl.fost.plymouth.ac.uk;PERSIST SECURITY INFO = True;USER ID = xxxxxxxxxx;password = xxxxxxxxx";

OracleConnection con = new OracleConnection(oradb);
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "Insert into USER.Client VALUES (txtBoxClientName, txtBoxClientCity, txtBoxClientCountry, txtBoxClientNumber, txtBoxClientURL, comboClientStatus)";

int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated == 0)
    MessageBox.Show("Please fill in required fields");
else
    MessageBox.Show("Client has been added");
con.Dispose();

This error appears at the int rowsUpdated = cmd.ExecuteNonQuery(); line - An unhandled exception of type Oracle.DataAccess.Client.OracleException occurred in Oracle.DataAccess.dll

Trigger code in Oracle:

create or replace TRIGGER trg_client_ClientID
BEFORE INSERT ON client FOR EACH ROW
BEGIN
  :NEW.ClientID := seq_client_ClientID.nextval;
END;

Body:
I've managed to fix it with the help of adding in the OracleException and ArgumentException and by using the Parameter code from Elkhan - here is my altered and working code:

    private void btnClientSave_Click(object sender, EventArgs e)
    {

        string oradb = "DATA SOURCE = larry.uopnet.plymouth.ac.uk:1521/orcl.fost.plymouth.ac.uk;PERSIST SECURITY INFO = True;USER ID = xxxxxxxxx;password = xxxxxxxx";
        string insertquery = "Insert into Client VALUES (:1, :2, :3, :4, :5, :6, :7)";

        OracleConnection con = new OracleConnection(oradb);
        con.Open();
        OracleCommand cmd = new OracleCommand();
        cmd.Connection = con;
        cmd.CommandText = insertquery;
        try
        {

            cmd.Parameters.Add(new OracleParameter("1", OracleDbType.Decimal, ParameterDirection.ReturnValue));
            cmd.Parameters.Add(new OracleParameter("2", OracleDbType.Varchar2, txtBoxClientName.Text, ParameterDirection.Input));
            cmd.Parameters.Add(new OracleParameter("3", OracleDbType.Varchar2, txtBoxClientCity.Text, ParameterDirection.Input));
            cmd.Parameters.Add(new OracleParameter("4", OracleDbType.Varchar2, txtBoxClientCountry.Text, ParameterDirection.Input));
            cmd.Parameters.Add(new OracleParameter("5", OracleDbType.Varchar2, txtBoxClientNumber.Text, ParameterDirection.Input));
            cmd.Parameters.Add(new OracleParameter("6", OracleDbType.Varchar2, txtBoxClientURL.Text, ParameterDirection.Input));
            cmd.Parameters.Add(new OracleParameter("7", OracleDbType.Varchar2, comboClientStatus.Text, ParameterDirection.Input));

            cmd.ExecuteNonQuery();

            MessageBox.Show("Client has been added");
            con.Close();
            Close();
        }
        catch (OracleException e1)
        {
            MessageBox.Show("Error: " + e1.Message);
        }
        catch (ArgumentException e2)
        {
            MessageBox.Show("Error: " + e2.Message);
        }
        finally
        {
            cmd.Dispose();
            con.Dispose();
        }


问:
Catch if user presses enter key in textbox
I'm trying to catch in a Event if the user presses the enter key. If followed these instructions found on the MSDN documentation pages.

This is my Event code for the Textbox:

```<code>Private Sub tbOccurrenceElevation_KeyDown(sender As Object, e As KeyEventArgs) Handles tbOccurrenceElevation.KeyDown

    ' Check if the enter key is pressed
    If e.KeyCode = Keys.Return Then
        OccurrenceElevation_Changed()
    End If

End Sub
</code>```

My problem is: when I push any button on the keyboard the Event is triggered, but when I press the enter ( return ) key nothing happens?

I tried changing the Textbox property to AcceptsReturn = True but no luck.

Extra info: The textbox is located on a UserControl and not a form control.

答:
Try this:

```<code>Private Sub tbOccurrenceElevation_KeyDown(sender As Object, e As KeyEventArgs) Handles tbOccurrenceElevation.KeyDown

    ' Check if the enter key is pressed
    If e.KeyCode = Keys.Enter or e.KeyCode = Keys.Return Then
        OccurrenceElevation_Changed()
    End If

End Sub
</code>```

You have to remember most of the keyboards have both Enter and Return. The code for those is different so you have to include them both

Body:
I'm trying to catch in a Event if the user presses the enter key. If followed these instructions found on the MSDN documentation pages.

This is my Event code for the Textbox:

Private Sub tbOccurrenceElevation_KeyDown(sender As Object, e As KeyEventArgs) Handles tbOccurrenceElevation.KeyDown

    ' Check if the enter key is pressed
    If e.KeyCode = Keys.Return Then
        OccurrenceElevation_Changed()
    End If

End Sub

My problem is: when I push any button on the keyboard the Event is triggered, but when I press the enter ( return ) key nothing happens?

I tried changing the Textbox property to AcceptsReturn = True but no luck.

Extra info: The textbox is located on a UserControl and not a form control.

Body:
Try this:

Private Sub tbOccurrenceElevation_KeyDown(sender As Object, e As KeyEventArgs) Handles tbOccurrenceElevation.KeyDown

    ' Check if the enter key is pressed
    If e.KeyCode = Keys.Enter or e.KeyCode = Keys.Return Then
        OccurrenceElevation_Changed()
    End If

End Sub

You have to remember most of the keyboards have both Enter and Return. The code for those is different so you have to include them both


问:
multiple separate arguments in 'tidyr's separate function
I have an issue about separation of one column into multiple columns.

The string example I want to separate is something like '87 BestMovie.GOOD'
separate locations are space ' ' and '.'

I tried like this

```<code>df=data.frame(Eastwood=c('87 BestMovie.GOOD'))
sep=df%>%
separate(Eastwood,into=c('age','Select','Movie'),sep=c(' ','.'))
</code>```

Warning messages:
      1: Too many values at 1 locations: 2
      2: Too few values at 1 locations: 1

or for another perspective, can we implement string locations for separation?

Thanks!

答:
"sep" needs to be a single character value representing a regular expression.  Do this:</p>
```<code>df %>% separate(Eastwood,into=c('age','Select','Movie'),sep=" |\\\\.")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an issue about separation of one column into multiple columns.

The string example I want to separate is something like '87 BestMovie.GOOD'
separate locations are space ' ' and '.'

I tried like this

df=data.frame(Eastwood=c('87 BestMovie.GOOD'))
sep=df%>%
separate(Eastwood,into=c('age','Select','Movie'),sep=c(' ','.'))

Warning messages:
      1: Too many values at 1 locations: 2
      2: Too few values at 1 locations: 1

or for another perspective, can we implement string locations for separation?

Thanks!

Body:
"sep" needs to be a single character value representing a regular expression.  Do this:

df %>% separate(Eastwood,into=c('age','Select','Movie'),sep=" |\\\\.")


问:
Implementing method callback in Android
Currently in my project, I am making Http requests and I want different http response to be sent to different callback methods.

I wrote a quick sample below to show what I want to do. I know it probably wont be possible the way i want it, but are there any clean solutions to achieve the same thing?

Sample:

Activity Class:

```<code>public class Main extends Activity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Services service = new Services();
        service.login("user", "password", **onLoginComplete()** );
    }

    public void onLoginComplete(String HTTPResponse){
        // Do something with the response
    }
}
</code>```

Service Class:

```<code>public class Services{

    public void login(String user, String password, CALLBACK){
        Request request = createLoginRequest(user, password);
        sendRequest(request, CALLBACK);
    }

    public class sendRequest extends AsyncTask{
        @Override
        protected Object doInBackground(Object... params) {
             // Do Http Request
             // Get Response
             CALLBACK(response);
        }
    }
}
</code>```

答:
I think I had the same problem as yours.

I was looking for a good answer and this was the implementation that worked for me:

First create an interface which contains your methods; in my case I use the typical onSuccess and onFailure but you can make your own methods:

```<code>//MyInterface.java

public interface MyInterface
{
    void onSuccess(String response);
    void onFailure(String response);
}
</code>```

Then create class Services:

```
//Services.java

public class Services
{
    public void login(String user, String password, MyInterface myInterface)
    {
        Request request = createLoginRequest(user, password);

        if(/*Request successful*/)
            myInterface.onSuccess("Login succesful");

        else
            myInterface.onFailure("Login failed");
    }
}
```

And finally call the method on your Activity:

```
//Main.java

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

        Services service = new Services();
        service.login("user", "password", new Myinterface()
        {
            @Override
            public void onSuccess(String response)
            {
                Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(String response)
            {
                Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
```

Title: Implementing method callback in Android

Body:
Currently in my project, I am making Http requests and I want different http response to be sent to different callback methods.

I wrote a quick sample below to show what I want to do. I know it probably wont be possible the way i want it, but are there any clean solutions to achieve the same thing?

Sample:

Activity Class:

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

        Services service = new Services();
        service.login("user", "password", **onLoginComplete()** );
    }

    public void onLoginComplete(String HTTPResponse){
        // Do something with the response
    }
}

Service Class:

public class Services{

    public void login(String user, String password, CALLBACK){
        Request request = createLoginRequest(user, password);
        sendRequest(request, CALLBACK);
    }

    public class sendRequest extends AsyncTask{
        @Override
        protected Object doInBackground(Object... params) {
             // Do Http Request
             // Get Response
             CALLBACK(response);
        }
    }
}

Body:
I think I had the same problem as yours.

I was looking for a good answer and this was the implementation that worked for me:

First create an interface which contains your methods; in my case I use the typical onSuccess and onFailure but you can make your own methods:

//MyInterface.java

public interface MyInterface
{
    void onSuccess(String response);
    void onFailure(String response);
}

Then create class Services:

//Services.java

public class Services
{
    public void login(String user, String password, MyInterface myInterface)
    {
        Request request = createLoginRequest(user, password);

        if(/*Request successful*/)
            myInterface.onSuccess("Login succesful");

        else
            myInterface.onFailure("Login failed");
    }
}

And finally call the method on your Activity:

//Main.java

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

        Services service = new Services();
        service.login("user", "password", new Myinterface()
        {
            @Override
            public void onSuccess(String response)
            {
                Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(String response)
            {
                Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
            }
        });
    }
}


问:
armv8-a: test if SIMD register is != 0
It's a question very similar to this one.

On armv7-a, I have the following assembly code:

```<code>vcmp.f64 d0, #0
vmrs APSR_nzcv, fpscr
beq .jumpover
</code>```

How can I convert this code to armv8-a? I want to test if there is any non-zero pixel in v0.16b.

EDIT #1

I was thinking about something like:

```<code>addv b0, v0.16b
fcmp s0, #0.0
beq .jumpover
</code>```

Is this correct? Also, I read the following statement "Floating point FCMP and FCCMP instructions set the integer condition flags directly, and do not modify the condition flags in the FPSR." which I'm not 100% sure to understand.

答:
sh1 in the comments found a working solution:

```<code>mov x0, v0.d[0]
cmp x0, #0
beq .jumpover

mov x0, v0.d[1]
cmp x0, #0
beq .jumpover
</code>```

You have to do it for both d[0] and d[1] to check the 16 pixels.

Title: armv8-a: test if SIMD register is != 0

Body:
It's a question very similar to this one.

On armv7-a, I have the following assembly code:

vcmp.f64 d0, #0
vmrs APSR_nzcv, fpscr
beq .jumpover

How can I convert this code to armv8-a? I want to test if there is any non-zero pixel in v0.16b.

EDIT #1

I was thinking about something like:

addv b0, v0.16b
fcmp s0, #0.0
beq .jumpover

Is this correct? Also, I read the following statement "Floating point FCMP and FCCMP instructions set the integer condition flags directly, and do not modify the condition flags in the FPSR." which I'm not 100% sure to understand.

Body:
sh1 in the comments found a working solution:

mov x0, v0.d[0]
cmp x0, #0
beq .jumpover

mov x0, v0.d[1]
cmp x0, #0
beq .jumpover

You have to do it for both d[0] and d[1] to check the 16 pixels.


问:
When to invalidate Fragment
My activity uses a FragmentPagerAdapter that creates a new instance of my Fragment from the  FragmentPagerAdapter.getItem() method.

Whenever I select the page containing my fragment of interest, I want to update its views because they may have been invalidated in the meantime when this page wasn't on screen.

What is the correct moment/method to do this? I've tried a few things:

MyFragment.onCreateView: this is only called the first time

PagerAdapter.onPageSelected: since the PagerAdapter creates new instances all the time, field references to Views obtained with findViewById in onCreateView are unavailable (unless they're static members I guess).

The other lifecycle events including onResume, onAttach

I found that if I pass the Activity reference to the Fragment from the onPageSelected event, and use findViewById on that to obtain new references to my Views it works, but I can't imagine there isn't a more intended way of doing this.

答:
OverRide this method, setUserVisibleHint Set a hint to the system about whether this fragment's UI is currently visible to the user. This hint defaults to true and is persistent across fragment instance state save and restore. Whenever it is true then that means the fragment is being viewed, either from a view pager or something triggering the validation of its views.
An app may set this to false to indicate that the fragment's UI is scrolled out of visibility or is otherwise not directly visible to the user.

More info:

Title: When to invalidate Fragment


问:
Setting up OpenGL on Mac and use it on Windows
For a project at university I need OpenGL. Since we need to run our program on a windows PC I have to code it accordingly (although I have a Mac).

So is there a better tool than XCode (since frameworks like glew are not intended there) ?

And if not - do I only have to include glew- and SDK2-lib?

答:
I recently had the same problem. I opted to run a Windows virtual machine on my Mac.

University computer science departments often have group software licenses that you can use to get free software while you're a student. My university provided access to vmware fusion, Windows 10, and Visual Studio. You should see if your school provides anything.

Performance was an issue for me when I was running more complex scenes in my ray tracer, but that is because I have a Macbook Air that's a few years old already. If you have a more powerful Mac, you should have no trouble at all.


问:
In which package can I find Xamarin IDevice
I am writing a Xamarin Forms PCL application (both iOS and Android)

I have to pick an image from phone gallery.

I have read some documentation about this plugin:

```<code>Labs.Platform.Services.Media.MediaPicker
</code>```

In my Common project, i have to put this code:

```<code>   var device = Resolver.Resolve<IDevice>();
   picker = DependencyService.Get<IMediaPicker>() ?? device.MediaPicker;
</code>```

But I have an error on the first line: IDevice and Resolver Objects are not know. I think I am missing a reference or a using clause.

Thanks

答:
You need to install the following Nuget package in all of your projects in the solution (i.e. PCL core project, iOS project, and the Android Project, and UWP project if using it):

https://www.nuget.org/packages/XLabs.Forms/

And you will need to add the following using statements:

```<code>using XLabs.Ioc;
using XLabs.Platform.Device;
using XLabs.Platform.Services.Media;
</code>```

Body:
I am writing a Xamarin Forms PCL application (both iOS and Android)

I have to pick an image from phone gallery.

I have read some documentation about this plugin:

Labs.Platform.Services.Media.MediaPicker

In my Common project, i have to put this code:

   var device = Resolver.Resolve<IDevice>();
   picker = DependencyService.Get<IMediaPicker>() ?? device.MediaPicker;

But I have an error on the first line: IDevice and Resolver Objects are not know. I think I am missing a reference or a using clause.

Thanks

Body:
You need to install the following Nuget package in all of your projects in the solution (i.e. PCL core project, iOS project, and the Android Project, and UWP project if using it):

https://www.nuget.org/packages/XLabs.Forms/

And you will need to add the following using statements:

using XLabs.Ioc;
using XLabs.Platform.Device;
using XLabs.Platform.Services.Media;


问:
Telerik Silverlight Organization Chart
Does any body know if Telerik has any control that supports drawing of Organization Charts.
If Telerik does not have, can anybody advise how can I draw organization chart with SilverLight.</p>

答:
You can use template nodes in the TreeView control.  The Telerik Silverlight demo application has an example.  Use this URL:
Templated Nodes

The sample is rudimentary but will serve as a good starting point

Regards
Jaco

Title: Telerik Silverlight Organization Chart


问:
Is there a PHP/Composer tool which works like npm version?
Is there an automated way of updating the version number in composer.json and adding the necessary tags before publishing, like the way npm version does?

I mean, if you had a composer.json with the line "version": "2.1.3", and executed:

```<code>composer version minor
</code>```

It would do the following:

Updating the version number in composer.json to 2.2.0

Triggering composer update to update composer.lock

Making a new git commit

Making a new git tag v2.2.0

I know that the composer version command doesn't exist, but is there an equivalent tool?

答:
npm version does stuff that you very likely do not need for Composer:

The version number is not recorded in composer.json if there are other means available - and because you are referring to Git later on, they are available.

Updating dependencies in the lock file is unnecessary. The lock file will be ignored when the project you are dealing with is included somewhere else.

Because nothing has changed in the project, a git commit wouldn't do anything.

All this leaves you with creating a new tag in the Git repository. Putting this into Composer would mean you'd exchange one command with another, without any big benefit besides you won't have to lookup the current version number you are dealing with if you use some of the relative version parameters.

All in all I'd say that simply tagging your new version is enough for Composer. You'd probably need to have some infrastructure in place and configured to make the world aware of the new version:

If your package is open source and on packagist.org, you should have a post-commit hook to notify them as soon as a new version is available. This is a standard option on Github, I don't know about other source code hosts.

Otherwise if you have to feed closed source code, you'd probably start a new update cycle of whatever system is used to create an alternative package information source (be it Satis, locally hosted Packagist, Toran Proxy or Private Packagist)

This however depends on how you set up things.

Body:
Is there an automated way of updating the version number in composer.json and adding the necessary tags before publishing, like the way npm version does?

I mean, if you had a composer.json with the line "version": "2.1.3", and executed:

composer version minor

It would do the following:

Updating the version number in composer.json to 2.2.0

Triggering composer update to update composer.lock

Making a new git commit

Making a new git tag v2.2.0

I know that the composer version command doesn't exist, but is there an equivalent tool?


问:
finding log4j appender to apply to my log
I have my appender configured in the log4j2.xml file

```<code><Appenders>
    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="${PATTERN}" />
    </Console>
    <Routing name="ConferenceLog">
        <Routes pattern="${ctx:logFileName}">
            <Route>
                <RollingFile name="Rolling-${ctx:logFileName}"
                    fileName="${LOG_DIR}/${ctx:logFileName}.log"
                    filePattern="${LOG_DIR}/${ctx:logFileName}.%i.log.gz">
                    <PatternLayout pattern="${PATTERN}" />
                    <SizeBasedTriggeringPolicy size="20971520" />
                </RollingFile>
            </Route>
            <Route ref="Console" key="${ctx:logFileName}" />
        </Routes>
    </Routing>
</Appenders>
<Loggers>
    <Logger name="conference.logger" level="DEBUG" additivity="false">
        <AppenderRef ref="ConferenceLog" />
    </Logger>
</Loggers>
</code>```

At run time Im trying to find and apply this to a particular log entry

```<code>private void logger(Long meetingId, Log log, Logger logger, Level level, String message, Throwable error) {
    ThreadContext.put(LOG_FILE_NAME, String.valueOf(meetingId));

    Logger rootLogger = Logger.getRootLogger();
    Appender conferenceLoggerAppender = rootLogger.getAppender("ConferenceLog");
    logger.addAppender(conferenceLoggerAppender);
    logger(log, level, message, error);
    logger.removeAppender(conferenceLoggerAppender);

    ThreadContext.remove(LOG_FILE_NAME);
}
</code>```

but my conferenceLoggerAppender is always null.  What is wrong with my logic?  Im trying to change it from what we currently do which is to use conference.logger

```<code>Log conferenceLogger = LogFactory.getLog("conference.logger");
</code>```

However that creates entries like so

2017-03-30 18:30:11.576 [taskScheduler-24] DEBUG conference.logger

where as I need it to use the class name its coming from like all the rest of our logs do

2017-03-30 18:30:11.576 [taskScheduler-24] DEBUG com.foo.bar

We can see the appender is there (in the rootLogger)

答:
Here is the answer

FYI: renamed logger to conferenceLogger

```<code>private void conferenceLogger(Long meetingId, String className, Log log, Level level, String message, Throwable error) {
    addConferenceLogAppender(className);
    ThreadContext.put(LOG_FILE_NAME, String.valueOf(meetingId));
    logger(log, level, message, error);
    ThreadContext.remove(LOG_FILE_NAME);
    removeConferenceLogAppender(className);

}

static void removeConferenceLogAppender(String package_name) {
    LoggerContext context = (LoggerContext) LogManager.getContext(false);
    Configuration configuration = context.getConfiguration();
    Appender appender = configuration.getAppender("ConferenceLog");
    LoggerConfig loggerConfig = configuration.getLoggerConfig(package_name);
    loggerConfig.removeAppender(appender.getName());
    context.updateLoggers();
}

static void addConferenceLogAppender(String package_name) {
    LoggerContext context = (LoggerContext) LogManager.getContext(false);
    Configuration configuration = context.getConfiguration();
    Appender appender = configuration.getAppender("ConferenceLog");
    LoggerConfig loggerConfig = configuration.getLoggerConfig(package_name);
    loggerConfig.addAppender(appender, loggerConfig.getLevel(), null);
    context.updateLoggers();
}
</code>```

Body:
I have my appender configured in the log4j2.xml file

<Appenders>
    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="${PATTERN}" />
    </Console>
    <Routing name="ConferenceLog">
        <Routes pattern="${ctx:logFileName}">
            <Route>
                <RollingFile name="Rolling-${ctx:logFileName}"
                    fileName="${LOG_DIR}/${ctx:logFileName}.log"
                    filePattern="${LOG_DIR}/${ctx:logFileName}.%i.log.gz">
                    <PatternLayout pattern="${PATTERN}" />
                    <SizeBasedTriggeringPolicy size="20971520" />
                </RollingFile>
            </Route>
            <Route ref="Console" key="${ctx:logFileName}" />
        </Routes>
    </Routing>
</Appenders>
<Loggers>
    <Logger name="conference.logger" level="DEBUG" additivity="false">
        <AppenderRef ref="ConferenceLog" />
    </Logger>
</Loggers>

At run time Im trying to find and apply this to a particular log entry

private void logger(Long meetingId, Log log, Logger logger, Level level, String message, Throwable error) {
    ThreadContext.put(LOG_FILE_NAME, String.valueOf(meetingId));

    Logger rootLogger = Logger.getRootLogger();
    Appender conferenceLoggerAppender = rootLogger.getAppender("ConferenceLog");
    logger.addAppender(conferenceLoggerAppender);
    logger(log, level, message, error);
    logger.removeAppender(conferenceLoggerAppender);

    ThreadContext.remove(LOG_FILE_NAME);
}

but my conferenceLoggerAppender is always null.  What is wrong with my logic?  Im trying to change it from what we currently do which is to use conference.logger

Log conferenceLogger = LogFactory.getLog("conference.logger");

However that creates entries like so

2017-03-30 18:30:11.576 [taskScheduler-24] DEBUG conference.logger

where as I need it to use the class name its coming from like all the rest of our logs do

2017-03-30 18:30:11.576 [taskScheduler-24] DEBUG com.foo.bar

We can see the appender is there (in the rootLogger)

Body:
Here is the answer

FYI: renamed logger to conferenceLogger

private void conferenceLogger(Long meetingId, String className, Log log, Level level, String message, Throwable error) {
    addConferenceLogAppender(className);
    ThreadContext.put(LOG_FILE_NAME, String.valueOf(meetingId));
    logger(log, level, message, error);
    ThreadContext.remove(LOG_FILE_NAME);
    removeConferenceLogAppender(className);

}

static void removeConferenceLogAppender(String package_name) {
    LoggerContext context = (LoggerContext) LogManager.getContext(false);
    Configuration configuration = context.getConfiguration();
    Appender appender = configuration.getAppender("ConferenceLog");
    LoggerConfig loggerConfig = configuration.getLoggerConfig(package_name);
    loggerConfig.removeAppender(appender.getName());
    context.updateLoggers();
}

static void addConferenceLogAppender(String package_name) {
    LoggerContext context = (LoggerContext) LogManager.getContext(false);
    Configuration configuration = context.getConfiguration();
    Appender appender = configuration.getAppender("ConferenceLog");
    LoggerConfig loggerConfig = configuration.getLoggerConfig(package_name);
    loggerConfig.addAppender(appender, loggerConfig.getLevel(), null);
    context.updateLoggers();
}


问:
Play youtube video when scroll is in view
With this code the video pauses as soon as I scroll. I want to pause the video when it goes out of view instead. How do I do this?

```<code>//This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

//This function creates an <iframe> (and YouTube player)

var player;

function onYouTubeIframeAPIReady() {

    player = new YT.Player('video', {
    height: '100%',
    width: '100%',
    videoId: 'V6Y-ahQFQDA',
    playerVars: {
        'start': '1',
        'color': 'white',
        'controls': '1',
        'showinfo': '0'
    },
    events: {
      'onReady': playOnScroll,
      'onStateChange': playOnScroll
    }
  });

}
</code>```

The part before is to load the video. I think my problem is in this if else statement. As soon as I start to scroll the log starts commanding paused, and I can't get it to work.

```<code>function playOnScroll() {
  var video = document.getElementById('video');

  var x = video.offsetLeft,
      y = video.offsetTop,
      w = video.offsetWidth,
      h = video.offsetHeight,
      r = x + w, //right
      b = y + h, //bottom
      visibleX,  visibleY,  visible;

      visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
      visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));

      visible = visibleX * visibleY / (w * h);

  var percent = 0.6;
  var inView = visible > percent;

      if (inView) {
          console.log('play');
          player.playVideo();

      } else {
          console.log('paused');
          player.pauseVideo();
      }
}

window.addEventListener('scroll', playOnScroll, false);
window.addEventListener('resize', playOnScroll, false);
</code>```

答:
```<code><script>
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</script>
<script>
var players = new Array();
var playingVideo = false;
var done = false;
var iterator = 0;
var pausedVideo = "";
function createPlayer(playerInfo) {
    playerVars = { 'autoplay': 0, 'controls': 0, 'rel': 0, 'showinfo': 0, 'loop': 1, 'modestbranding': 1 };
    return new YT.Player(playerInfo.id, {
        height: playerInfo.height,
        width: playerInfo.width,
        videoId: playerInfo.videoId,
        playerVars,
        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
            }
    });
}
function onPlayerReady(event) {
    // Play/pause video's which do not auto play for seamless playback
        if(event.target.a.src.search('autoplay=0')) {
            event.target.playVideo();
            event.target.pauseVideo();
        }
    }
    function onPlayerStateChange(event) {
    if(event.data === 2){
        pausedVideo = event.target.a.id;
    }
    if(event.data === 1){
        pausedVideo =  "";
    }
    if (event.data == YT.PlayerState.PLAYING && !done) {
        done = true;
    }
}
window.onYouTubeIframeAPIReady = function(){
    players.push(createPlayer({
        id: 'ytPlayer',
        height: '506',
        width: '900',
        videoId: 'l-OgbAqWs20',
        events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
        }
    }));
    jq(window).scroll(function(){
        _embedContainerTop = jq('.embed-container').offset().top;
        if( jq(window).scrollTop() >= (_embedContainerTop - 544) && jq(window).scrollTop()<= (_embedContainerTop + 344)) {
            if(typeof players[0].playVideo=="function"){
                players[0].playVideo();
            }
        } else {
            if(typeof players[0].pauseVideo=="function"){
                players[0].pauseVideo();
            }
        }
    });

};
</code>```

Body:
With this code the video pauses as soon as I scroll. I want to pause the video when it goes out of view instead. How do I do this?

//This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

//This function creates an  (and YouTube player)

var player;

function onYouTubeIframeAPIReady() {

    player = new YT.Player('video', {
    height: '100%',
    width: '100%',
    videoId: 'V6Y-ahQFQDA',
    playerVars: {
        'start': '1',
        'color': 'white',
        'controls': '1',
        'showinfo': '0'
    },
    events: {
      'onReady': playOnScroll,
      'onStateChange': playOnScroll
    }
  });

}

The part before is to load the video. I think my problem is in this if else statement. As soon as I start to scroll the log starts commanding paused, and I can't get it to work.

function playOnScroll() {
  var video = document.getElementById('video');

  var x = video.offsetLeft,
      y = video.offsetTop,
      w = video.offsetWidth,
      h = video.offsetHeight,
      r = x + w, //right
      b = y + h, //bottom
      visibleX,  visibleY,  visible;

      visibleX = Math.max(0, Math.min(w, window.pageXOffset + window.innerWidth - x, r - window.pageXOffset));
      visibleY = Math.max(0, Math.min(h, window.pageYOffset + window.innerHeight - y, b - window.pageYOffset));

      visible = visibleX * visibleY / (w * h);

  var percent = 0.6;
  var inView = visible > percent;

      if (inView) {
          console.log('play');
          player.playVideo();

      } else {
          console.log('paused');
          player.pauseVideo();
      }
}

window.addEventListener('scroll', playOnScroll, false);
window.addEventListener('resize', playOnScroll, false);


问:
Get rid of strings containing a pattern within a file
Within a linux file with the following content I want to get rid of everything starting with a specific pattern, which is aws: in this particular case:

```<code>aws:cloudformation:logical-id="somestring" Name="abc" Product="xyz" Role="www" aws:autoscaling:groupName="strings-and-numbers-012345" aws:cloudformation:stack-id="strings-and-numbers-012345" aws:cloudformation:stack-name="strings-and-numbers-012345"
</code>```

The output I need is just: Name="abc" Product="xyz" Role="www"; how do I do it?

答:
```<code>awk '{print $2,$3,$4}' file

Name="abc" Product="xyz" Role="www"
</code>```

Body:
Within a linux file with the following content I want to get rid of everything starting with a specific pattern, which is aws: in this particular case:

aws:cloudformation:logical-id="somestring" Name="abc" Product="xyz" Role="www" aws:autoscaling:groupName="strings-and-numbers-012345" aws:cloudformation:stack-id="strings-and-numbers-012345" aws:cloudformation:stack-name="strings-and-numbers-012345"

The output I need is just: Name="abc" Product="xyz" Role="www"; how do I do it?


问:
Strategy Pattern the right thing?
i hope you can help me with my problem:

I have a Class doing soap calls. But if the soap definition changes i'll have to write a new class or inherit from it etc.
So I came to the solution to write something like that:

```<code>switch(version)
{
  case "1.0":
     saopV1.getData()
  case "2.0":
     soapV2.getData()
}
</code>```

Well pretty bad code, i know. Then I read about the Strategy pattern and i thought, wow that's what i need to get rid of this bad switch-case thing:

```<code>abstract SoapVersion
{
    public SoapVersion GetSoapVersion(string version)
    {
         //Damn switch-case thing
         //with return new SoapV1() and return new SoapV2()
    }
    public string[] virtual getData()
    {
          //Basic Implementation
    }
}

class SoapV1:SoapVersion
{
       public override string[] getData()
       {
           //Detail Implementation
       }
}

class SoapV2:SoapVersion
{//the same like soapv1}
</code>```

But i can't avoid using "ifs" or switch cases in my code. Is this possible using OO-techniques??

Edit:
The GetSoapVersion-Function should be static

答: In similar circumstances I choose between reflection and if/cases using the following criterion: if new version support should be added dynamically (like plug-ins) I choose reflection, otherwise - if/case. As mentioned in other answers that it should inside a factory method to provide a single place to create things. It worths to mention that Strategy is a behavioral pattern, while what you asked for looks like to be creational.

Title: Strategy Pattern the right thing?

Body:
i hope you can help me with my problem:

I have a Class doing soap calls. But if the soap definition changes i'll have to write a new class or inherit from it etc.
So I came to the solution to write something like that:

switch(version)
{
  case "1.0":
     saopV1.getData()
  case "2.0":
     soapV2.getData()
}

Well pretty bad code, i know. Then I read about the Strategy pattern and i thought, wow that's what i need to get rid of this bad switch-case thing:

abstract SoapVersion
{
    public SoapVersion GetSoapVersion(string version)
    {
         //Damn switch-case thing
         //with return new SoapV1() and return new SoapV2()
    }
    public string[] virtual getData()
    {
          //Basic Implementation
    }
}

class SoapV1:SoapVersion
{
       public override string[] getData()
       {
           //Detail Implementation
       }
}

class SoapV2:SoapVersion
{//the same like soapv1}

But i can't avoid using "ifs" or switch cases in my code. Is this possible using OO-techniques??

Edit:
The GetSoapVersion-Function should be static


问:
Passing argv from client to server using RMI
Iḿ trying for the first time to use RMI and I do not know much about java, just the basics.
So for starters, I'd like to program a simple calculator with the 4 basic arithmetic operations (+ - * /), where when executing on the terminal (linux):

```<code>java CalculatorClient <host> 1 + 2
</code>```

therefore argv[0] is the host, and I'd like to pass argv[] to the server so it can remotely calculate and return the value.

I did get the basic working, with this code where the client only receives how many times the server has been accessed:

```<code>    // CounterServerCaller.java
    import java.rmi.*;
    public class CounterServerCaller {
        public static void main(String args[])  {

        try {
            Counter c = new CounterServer();
            Naming.rebind("Counter", c);
            System.out.println("Counter ready.");
        }
        catch (Exception e) {
            System.out.println("Erro:"+e.getMessage());}
        }
    }
</code>```

.

```<code>    // CounterServer.java
    import java.rmi.*;
    import java.rmi.server.*;

    public class CounterServer extends UnicastRemoteObject {
        private int value;
        public int nextValue() throws RemoteException {
            return value++;
        }
        public CounterServer() throws RemoteException {
            super();
            value = 0;
        }
    }
</code>```

.

```<code>    // CounterCliente.java
    import java.rmi.*;
    public class CounterClient {
        public static void main(String args[]) {
            try {
                String host = args[0];
                Counter c = (Counter)
                    Naming.lookup("rmi://"+host+"/Contador");
                System.out.println("Contador: "+c.nextValue());
            } catch (Exception e) {
                System.out.println("Erro: "+e.getMessage());
            }
        }
    }
</code>```

.

```<code>// Counter.java
import java.rmi.*;
public interface Counter extends Remote {
    int nextValue() throws RemoteException;
}
</code>```

I did search for an answer but I can only find really complicated code, with CallBacks which I don't think is the simplest solution. Maybe I was searching using the wrong key words? Can anyone shed some light into this matter please?

答:
```<code>public interface Counter extends Remote {
    int nextValue() throws RemoteException;
}
</code>```

This remote interface doesn't meet your objective in any way. I don't understand why you posted it, or even wrote it.

What you need is something like:

```<code>public interface Calculator extends Remote {
    public int evaluate(String expression) throws RemoteException;
}
</code>```

Have it return long or double or BigDecimal if you like, whatever you need.

Body:
Iḿ trying for the first time to use RMI and I do not know much about java, just the basics.
So for starters, I'd like to program a simple calculator with the 4 basic arithmetic operations (+ - * /), where when executing on the terminal (linux):

java CalculatorClient <host> 1 + 2

therefore argv[0] is the host, and I'd like to pass argv[] to the server so it can remotely calculate and return the value.

I did get the basic working, with this code where the client only receives how many times the server has been accessed:

    // CounterServerCaller.java
    import java.rmi.*;
    public class CounterServerCaller {
        public static void main(String args[])  {

        try {
            Counter c = new CounterServer();
            Naming.rebind("Counter", c);
            System.out.println("Counter ready.");
        }
        catch (Exception e) {
            System.out.println("Erro:"+e.getMessage());}
        }
    }

.

    // CounterServer.java
    import java.rmi.*;
    import java.rmi.server.*;

    public class CounterServer extends UnicastRemoteObject {
        private int value;
        public int nextValue() throws RemoteException {
            return value++;
        }
        public CounterServer() throws RemoteException {
            super();
            value = 0;
        }
    }

.

    // CounterCliente.java
    import java.rmi.*;
    public class CounterClient {
        public static void main(String args[]) {
            try {
                String host = args[0];
                Counter c = (Counter)
                    Naming.lookup("rmi://"+host+"/Contador");
                System.out.println("Contador: "+c.nextValue());
            } catch (Exception e) {
                System.out.println("Erro: "+e.getMessage());
            }
        }
    }

.

// Counter.java
import java.rmi.*;
public interface Counter extends Remote {
    int nextValue() throws RemoteException;
}

I did search for an answer but I can only find really complicated code, with CallBacks which I don't think is the simplest solution. Maybe I was searching using the wrong key words? Can anyone shed some light into this matter please?

Body:
public interface Counter extends Remote {
    int nextValue() throws RemoteException;
}

This remote interface doesn't meet your objective in any way. I don't understand why you posted it, or even wrote it.

What you need is something like:

public interface Calculator extends Remote {
    public int evaluate(String expression) throws RemoteException;
}

Have it return long or double or BigDecimal if you like, whatever you need.


问:
Regex to Match Hashtags in string that contain no more than 1 space
What I'm looking to do is match hashtags in a string, but the hashtag may have a space in it: #brown fox. Most hashtags are single words, #brown, #fox, but some were improperly formatted and resulted in spaces being entered.

The hashtags that have spaces are only allowed to be two words, so #space suit is allowed, but #brown fox jumps is not allowed.

The quick #brown #fox #jumps over the lazy dog.

brown, fox, jumps

The quick #brown fox #jumps over the lazy dog.

brown fox, jumps

The quick #brown fox #jumps over the lazy #dog.

brown fox, jumps, dog

If there is a hashtag, followed by one word, then followed by a hashtag, then we can assume the word is for that hashtag. Otherwise, we shouldn't capture it in the group.

Here is what I've tried so far, but clearly it's nowhere close to what I need:
https://regex101.com/r/vHOCaf/1

```<code>(\#+\w{2,})|(\#([\w]){2,}\s{0,1}([\w]){2,})
</code>```

Body:
What I'm looking to do is match hashtags in a string, but the hashtag may have a space in it: #brown fox. Most hashtags are single words, #brown, #fox, but some were improperly formatted and resulted in spaces being entered.

The hashtags that have spaces are only allowed to be two words, so #space suit is allowed, but #brown fox jumps is not allowed.

The quick #brown #fox #jumps over the lazy dog.

brown, fox, jumps

The quick #brown fox #jumps over the lazy dog.

brown fox, jumps

The quick #brown fox #jumps over the lazy #dog.

brown fox, jumps, dog

If there is a hashtag, followed by one word, then followed by a hashtag, then we can assume the word is for that hashtag. Otherwise, we shouldn't capture it in the group.

Here is what I've tried so far, but clearly it's nowhere close to what I need:
https://regex101.com/r/vHOCaf/1

(\#+\w{2,})|(\#([\w]){2,}\s{0,1}([\w]){2,})

Body:
How about this

#(\w+(?:\s+\w+)?)


问:
SQL Server Iterating through a table and scrubbing sensitive data
I have a table that contains the names of tables and fields that need to be scrubbed.

I need to loop through this table and scrub the field name in each table.  I would also like any suggestions on a scrubbing algorithm.

Thank you!

答:
Hi you should really update your request to say data obfuscating.

But that aside this is how you can do it.
First create a function in whatever this database is (Don't alter this part load it in as is):

```<code>CREATE FUNCTION Character_Mask
(
    @OrigVal varchar(max),
    @InPlain int,
    @MaskChar char(1)
)
RETURNS varchar(max)
WITH ENCRYPTION
AS
BEGIN
    DECLARE @PlainVal varchar(max);
    DECLARE @MaskVal varchar(max);
    DECLARE @MaskLen int;

    SET @PlainVal = RIGHT(@OrigVal,@InPlain);
    SET @MaskLen = (DATALENGTH(@OrigVal) - @InPlain);
    SET @MaskVal = REPLICATE(@MaskChar, @MaskLen);
    Return @MaskVal + @PlainVal;
END
GO

GRANT EXECUTE ON dbo.Character_Mask
    TO Sensitive_high, Sensitive_medium, Sensitive_low;
GO
</code>```

Once you have that in your database, you can start using it in views:

```<code>CREATE VIEW dbo.MyObbedData
AS
SELECT
    dbo.Character_Scramble(c.FirstName) AS Ob_First_Name,
    dbo.Character_Scramble(c.LastName) AS Ob_LastName,
    dbo.Character_Scramble(c.Email) AS Ob_Email,
    dbo.Character_Scramble(u.UserName) AS Ob_UserName
FROM
    dbo.Customer c
    INNER JOIN dbo.User u
        ON c.UserID = u.UserID
GO

GRANT SELECT ON dbo.MyObbedData
    TO Sensitive_high, Sensitive_medium;
GO
</code>```

The Character_Mask code was taken from here, it can do heaps more and if you want to read up on it here is the LINK

Caz

Body:
Hi you should really update your request to say data obfuscating.

But that aside this is how you can do it.
First create a function in whatever this database is (Don't alter this part load it in as is):

CREATE FUNCTION Character_Mask
(
    @OrigVal varchar(max),
    @InPlain int,
    @MaskChar char(1)
)
RETURNS varchar(max)
WITH ENCRYPTION
AS
BEGIN
    DECLARE @PlainVal varchar(max);
    DECLARE @MaskVal varchar(max);
    DECLARE @MaskLen int;

    SET @PlainVal = RIGHT(@OrigVal,@InPlain);
    SET @MaskLen = (DATALENGTH(@OrigVal) - @InPlain);
    SET @MaskVal = REPLICATE(@MaskChar, @MaskLen);
    Return @MaskVal + @PlainVal;
END
GO

GRANT EXECUTE ON dbo.Character_Mask
    TO Sensitive_high, Sensitive_medium, Sensitive_low;
GO

Once you have that in your database, you can start using it in views:

CREATE VIEW dbo.MyObbedData
AS
SELECT
    dbo.Character_Scramble(c.FirstName) AS Ob_First_Name,
    dbo.Character_Scramble(c.LastName) AS Ob_LastName,
    dbo.Character_Scramble(c.Email) AS Ob_Email,
    dbo.Character_Scramble(u.UserName) AS Ob_UserName
FROM
    dbo.Customer c
    INNER JOIN dbo.User u
        ON c.UserID = u.UserID
GO

GRANT SELECT ON dbo.MyObbedData
    TO Sensitive_high, Sensitive_medium;
GO

The Character_Mask code was taken from here, it can do heaps more and if you want to read up on it here is the LINK

Caz


问:
Python injecting newlines when using f.write for no reason
to the best of my knowledge this hasn't been asked before and I'm at a loss. I have a python script that takes a bunch of strings and writes them to file in csv format. However in my write function python seems to be adding newlines and I cannot figure out how. Here's my code

```<code>monday_break_one = "2:00 PM - 2:15 PM"
monday_break_two = "3:30 PM - 3:45 PM"
day_one_string = "3/27/2017"

mb1s,mb1e= monday_break_one.split(" - ")
mb2s,mb2e= monday_break_two.split(" - ")
foo = ','
f = open('outputcsv.txt','w')
f.write("Subject,Start Date,Start Time, End Date ,End Time, All day Event, Categories,Show Time As\n")
f.write("Break 1," )
f.write(day_one_string + foo + mb1s + foo + day_one_string + foo + mb1e)
</code>```

My output looks like this

```<code>Subject,Start Date,Start Time, End Date ,End Time, All day Event,Categories,Show Time As

Break 1,3/27/2017
,2:00 PM,3/27/2017
,2:15 PM
</code>```

and it just doesn't make sense to me because it seems like my output has a new line after each instance of my "day_one_string" but that string really only equals "3/27/2017" and I've checked it multiple times through printing it to console. I would be wildly grateful for any help or pointers here, I am pulling my hair out trying to figure out where the new line is coming from.

答:
Use the csv module, and a context manager.

```<code>import csv

monday_break_one = "2:00 PM - 2:15 PM"
monday_break_two = "3:30 PM - 3:45 PM"
day_one_string = "3/27/2017"

mb1s, mb1e = monday_break_one.split(" - ")
mb2s, mb2e = monday_break_two.split(" - ")

with open(r"/Users/rohan/Downloads/outputcsv.txt", "w") as fh:
    writer = csv.writer(fh, delimiter=",")
    writer.writerow(["Subject", "Start", "Date", "Start Time", "End Date", "End Time", "All day Event", "Categories", "Show Time As"])
    writer.writerow(["Break 1"])
    writer.writerow([day_one_string, mb1s, day_one_string, mb1e])
</code>```

Body:
to the best of my knowledge this hasn't been asked before and I'm at a loss. I have a python script that takes a bunch of strings and writes them to file in csv format. However in my write function python seems to be adding newlines and I cannot figure out how. Here's my code

monday_break_one = "2:00 PM - 2:15 PM"
monday_break_two = "3:30 PM - 3:45 PM"
day_one_string = "3/27/2017"

mb1s,mb1e= monday_break_one.split(" - ")
mb2s,mb2e= monday_break_two.split(" - ")
foo = ','
f = open('outputcsv.txt','w')
f.write("Subject,Start Date,Start Time, End Date ,End Time, All day Event, Categories,Show Time As\n")
f.write("Break 1," )
f.write(day_one_string + foo + mb1s + foo + day_one_string + foo + mb1e)

My output looks like this

Subject,Start Date,Start Time, End Date ,End Time, All day Event,Categories,Show Time As

Break 1,3/27/2017
,2:00 PM,3/27/2017
,2:15 PM

and it just doesn't make sense to me because it seems like my output has a new line after each instance of my "day_one_string" but that string really only equals "3/27/2017" and I've checked it multiple times through printing it to console. I would be wildly grateful for any help or pointers here, I am pulling my hair out trying to figure out where the new line is coming from.

Body:
Use the csv module, and a context manager.

import csv

monday_break_one = "2:00 PM - 2:15 PM"
monday_break_two = "3:30 PM - 3:45 PM"
day_one_string = "3/27/2017"

mb1s, mb1e = monday_break_one.split(" - ")
mb2s, mb2e = monday_break_two.split(" - ")

with open(r"/Users/rohan/Downloads/outputcsv.txt", "w") as fh:
    writer = csv.writer(fh, delimiter=",")
    writer.writerow(["Subject", "Start", "Date", "Start Time", "End Date", "End Time", "All day Event", "Categories", "Show Time As"])
    writer.writerow(["Break 1"])
    writer.writerow([day_one_string, mb1s, day_one_string, mb1e])


问:
Ruby - how to find the NEXT occurrence of a given hour?
I want to return a Ruby Time object (miliseconds) that represents the next X hour from a given DateTime.

Examples for the next 5am

if it currently is 9pm on 3/28, the NEXT 5am would be 3/29 5am

if it currently is 6am on 3/29, the NEXT 5am would be 3/30 5am

Code wise:

```<code># for the below attribute
@object.created_at
=> "2017-03-28 21:00:00"

# given the definition of the next X hour in question
next_hour_to_find = 5 # for 5am

# what's the equation to produce 3/29 5am?
</code>```

I'd like something flexible so that if next_hour_to_find = 14 then the function would be able to find the next 2pm. No worries about time zone, this is all within the scope of the time zone of the @object.created_at.

My current thinking is below, but I feel like there's a cleaner way...

```<code>if @object.created_at.hour > next_hour_to_find
  # the next X hour is always going to occur on the next date
  date = (@object.created_at + 1.days).strftime(...) # get the date out
else
  # the next X hour is always going to occur on the same date
  date = (@object.created_at).strftime(...) # get the date out
end

# now that we have a date in a string, we have to append that string with the next_hour_to_find
# not sure if below works for both single and double digit hours
string = date + next_hour_to_find + ":00:00"

# finish by returning Time object, but this seems suuuuper inefficient since we converted to string and then back again
return Time.parse(string)
</code>```

答:
You might want to check out Chronic, which is a great lib that allows for natural language when working with dates in Ruby.

```<code>five_today = Chronic.parse('5am')
five_today < Time.now ? Chronic.parse('tomorrow 5am') : five_today
</code>```

Since Chronic returns regular Date and Time objects, this would also work without it. You're left with a less pleasant syntax, however.

Body:
I want to return a Ruby Time object (miliseconds) that represents the next X hour from a given DateTime.

Examples for the next 5am

if it currently is 9pm on 3/28, the NEXT 5am would be 3/29 5am

if it currently is 6am on 3/29, the NEXT 5am would be 3/30 5am

Code wise:

# for the below attribute
@object.created_at
=> "2017-03-28 21:00:00"

# given the definition of the next X hour in question
next_hour_to_find = 5 # for 5am

# what's the equation to produce 3/29 5am?

I'd like something flexible so that if next_hour_to_find = 14 then the function would be able to find the next 2pm. No worries about time zone, this is all within the scope of the time zone of the @object.created_at.

My current thinking is below, but I feel like there's a cleaner way...

if @object.created_at.hour > next_hour_to_find
  # the next X hour is always going to occur on the next date
  date = (@object.created_at + 1.days).strftime(...) # get the date out
else
  # the next X hour is always going to occur on the same date
  date = (@object.created_at).strftime(...) # get the date out
end

# now that we have a date in a string, we have to append that string with the next_hour_to_find
# not sure if below works for both single and double digit hours
string = date + next_hour_to_find + ":00:00"

# finish by returning Time object, but this seems suuuuper inefficient since we converted to string and then back again
return Time.parse(string)

Body:
You might want to check out Chronic, which is a great lib that allows for natural language when working with dates in Ruby.

five_today = Chronic.parse('5am')
five_today < Time.now ? Chronic.parse('tomorrow 5am') : five_today

Since Chronic returns regular Date and Time objects, this would also work without it. You're left with a less pleasant syntax, however.


问:
Crash Log on Windows Phone 7 device
I don't have a WP7 device yet. Everything is functional in My App on a Simulator, but when my customer test it, app does not function at all. e.g. VDO is not playing.

Is there a way to get a crash log from Windows Phone 7? (like iPhone).

答:
You can easily create your own crash report. Basically this is what you have to do:

In your App class add an handler for the UnhandledException event

inside the handler prepare a log with everything you need (stacktrace, memory allocated, etc.)

use an email composer Task to send the report.

Title: Crash Log on Windows Phone 7 device


问:
Nested for loops python DNS programming
I am trying to loop through two lists in order to get web server IP resolutions from DNS servers. I am trying to figure out how to get the IP resolution from each url with each DNS server IP. The code I have works but I am just trying to figure out how to loop through both of these lists so I don't have to manually enter the index of the list each time I run the code.</p>

```<code>url = ["www.facebook.com","www.google.com","www.uiowa.edu"] #list of urls
ips = ["168.1.79.229","156.154.70.1","138.197.25.214","94.206.181.22","122.176.20.6","217.73.226.120","27.34.140.46","110.165.44.152","187.86.59.3","128.255.1.3"]

clientSocket = socket(AF_INET, SOCK_DGRAM)
message = create_DNS_query(url[i])
clientSocket.sendto(message, (ips[i], 53))
rMessage, address = clientSocket.recvfrom(1000)
ip = decode_dns_message(rMessage)
print ip
clientSocket.close()
</code>```

答:
Just nest your loops, as you say in the title:</p>

```<code>for name in url:
    for dns in ips:
        clientSocket = socket(AF_INET, SOCK_DGRAM)
        message = create_DNS_query(name)
        clientSocket.sendTo(message, dns, 53)
        rMessage, address = clientSocket.recvfrom(1000)
        ip = decode_dns_message(rMessage)
        print "Server: {} Name: {} IP: {}".format(dns, name, ip)
        clientSocket.close
</code>```

Title: Nested for loops python DNS programming

Body:
I am trying to loop through two lists in order to get web server IP resolutions from DNS servers. I am trying to figure out how to get the IP resolution from each url with each DNS server IP. The code I have works but I am just trying to figure out how to loop through both of these lists so I don't have to manually enter the index of the list each time I run the code.

url = ["www.facebook.com","www.google.com","www.uiowa.edu"] #list of urls
ips = ["168.1.79.229","156.154.70.1","138.197.25.214","94.206.181.22","122.176.20.6","217.73.226.120","27.34.140.46","110.165.44.152","187.86.59.3","128.255.1.3"]

clientSocket = socket(AF_INET, SOCK_DGRAM)
message = create_DNS_query(url[i])
clientSocket.sendto(message, (ips[i], 53))
rMessage, address = clientSocket.recvfrom(1000)
ip = decode_dns_message(rMessage)
print ip
clientSocket.close()

Body:
Just nest your loops, as you say in the title:

for name in url:
    for dns in ips:
        clientSocket = socket(AF_INET, SOCK_DGRAM)
        message = create_DNS_query(name)
        clientSocket.sendTo(message, dns, 53)
        rMessage, address = clientSocket.recvfrom(1000)
        ip = decode_dns_message(rMessage)
        print "Server: {} Name: {} IP: {}".format(dns, name, ip)
        clientSocket.close


问:
Custom programmable widgets in Draft.js (plugin)
As an example of what I'd like to do, in Draft.js I'd like to allow the users to include a slideshow of images in the page that could change externally later on. So if there is a slideshow defined in my app, the user could select that slideshow to put in their page, and if the images were changed later then they would automatically update on the page. A visual representation in the editor would a nice-to-have as well. Am I asking too much or is this possible in Draft.js?</p>

答:
It never fails. I post a question and almost immediately I find something that might answer my question. Draft.js has what is called "decorators", which are currently documented here: https://draftjs.org/docs/advanced-topics-decorators.html

Basically you'd create a series of decorators using functions / components. Strategy takes a function, component is obvious.

```<code>const compositeDecorator = new CompositeDecorator([
  {
    strategy: handleStrategy,
    component: HandleSpan,
  },
  {
    strategy: hashtagStrategy,
    component: HashtagSpan,
  },
]);
</code>```

Strategies can be defined using regexes. This enables you to write your own syntax or use that of a template engine's for embedding widgets. The strategies in the documentation are a fairly good example:

```<code>// Note: these aren't very good regexes, don't use them!
const HANDLE_REGEX = /\@[\w]+/g;
const HASHTAG_REGEX = /\#[\w\u0590-\u05ff]+/g;

function handleStrategy(contentBlock, callback, contentState) {
  findWithRegex(HANDLE_REGEX, contentBlock, callback);
}

function hashtagStrategy(contentBlock, callback, contentState) {
  findWithRegex(HASHTAG_REGEX, contentBlock, callback);
}

function findWithRegex(regex, contentBlock, callback) {
  const text = contentBlock.getText();
  let matchArr, start;
  while ((matchArr = regex.exec(text)) !== null) {
    start = matchArr.index;
    callback(start, start + matchArr[0].length);
  }
}
</code>```

And then here are the components:

```<code>const HandleSpan = (props) => {
  return <span {...props} style={styles.handle}>{props.children}</span>;
};

const HashtagSpan = (props) => {
  return <span {...props} style={styles.hashtag}>{props.children}</span>;
};
</code>```

Body:
It never fails. I post a question and almost immediately I find something that might answer my question. Draft.js has what is called "decorators", which are currently documented here: https://draftjs.org/docs/advanced-topics-decorators.html

Basically you'd create a series of decorators using functions / components. Strategy takes a function, component is obvious.

const compositeDecorator = new CompositeDecorator([
  {
    strategy: handleStrategy,
    component: HandleSpan,
  },
  {
    strategy: hashtagStrategy,
    component: HashtagSpan,
  },
]);

Strategies can be defined using regexes. This enables you to write your own syntax or use that of a template engine's for embedding widgets. The strategies in the documentation are a fairly good example:

// Note: these aren't very good regexes, don't use them!
const HANDLE_REGEX = /\@[\w]+/g;
const HASHTAG_REGEX = /\#[\w\u0590-\u05ff]+/g;

function handleStrategy(contentBlock, callback, contentState) {
  findWithRegex(HANDLE_REGEX, contentBlock, callback);
}

function hashtagStrategy(contentBlock, callback, contentState) {
  findWithRegex(HASHTAG_REGEX, contentBlock, callback);
}

function findWithRegex(regex, contentBlock, callback) {
  const text = contentBlock.getText();
  let matchArr, start;
  while ((matchArr = regex.exec(text)) !== null) {
    start = matchArr.index;
    callback(start, start + matchArr[0].length);
  }
}

And then here are the components:

const HandleSpan = (props) => {
  return <span {...props} style={styles.handle}>{props.children}</span>;
};

const HashtagSpan = (props) => {
  return <span {...props} style={styles.hashtag}>{props.children}</span>;
};


问:
Excel's COUNTIF() function returns a wrong count
Spent an hour on this but can't figure out what seems to be the problem. Any help is appreciated.

答:
Put in the =

```<code>=COUNTIF(A13:A15,"=<abc")
</code>```

The mathematical sequence is >= or <= not => and =<, so countif will see the beginning < or > as Greater than or Less than, but if it is preceded by the = it assumes it is part of the text and not the mathematical operand.

Body:
Put in the =

=COUNTIF(A13:A15,"=<abc")

The mathematical sequence is >= or <= not => and =<, so countif will see the beginning < or > as Greater than or Less than, but if it is preceded by the = it assumes it is part of the text and not the mathematical operand.