问:
Regarding decimal -> hexadecimal conversion without using pre-existing utils or methods
I am currently working on assignments related to Class (JAVA),

and I am near to the finishing line but my public string getHex() will be just returning me value of 0.

To make it easier to view, I have uploaded the codes I've been working on:

https://codeshare.io/5DAzYk

So the upper half is the TestSmallInt.java program that runs based on SmallInt.java class file.

I can't figure out why the getHex() wouldn't work !

Thanks so much for your help

答:
The actual logic in your getHex method is fine, but it doesn't work because your other methods (and the getHex method) mutate 'value', so by the time you call getHex() the value has been destroyed.

Adjust your code such that if you need to mutate the value then you make a copy of it, eg:

```<code>public String getHex() {
    int number = value;
    // now mutate number, not value
</code>```

Incidentally, declaring value final would flag this mutation up automatically:

```<code>private final int value;

public SmallInt(final int value) {
    this.value = value;
}
...
</code>```

Thus, the edited code would be:

```<code>import java.util.Scanner;

public class TestSmallInt
{
    /** Main method */
    public static void main(String[] args)
    {
        Scanner sc = new Scanner (System.in);
        System.out.print("Enter a desired number: ");
        int decimal = sc.nextInt();
        SmallInt number = new SmallInt (decimal);

        String numberAsString = number.getDec ();
        String numberAsBin = number.getBin ();
        String numberAsHex = number.getHex ();
        System.out.println ("Your number in decimal is " + numberAsString);
        System.out.println ("Your number in binary is " + numberAsBin);
        System.out.println ("Your number in hexadecimal is " + numberAsHex);
        sc.close();
    }
}

////////////////////////////////////////////////////////////////////////

class SmallInt
{
    private final int value;

    public SmallInt (int value) {
        this.value = value;
    }

    public String getDec ()
    {
        return ""+ value;
    }

    public String getBin (){
        int number = value;
        if (number == 0) {
                 return "0";
         }
         String binary = "";
         while (number > 0) {
                 int rem = number % 2;
                 binary = rem + binary;
                 number = number / 2;
         }
         return binary;
    }

    public String getHex (){
        String digits = "0123456789ABCDEF";
        int number = value;
         if (number <= 0) {
                 return "0";
                }
         int base = 16;   // flexible to change in any base under 16
         String hex = "";
         while (number > 0) {
             int digit = number % base;              // rightmost digit
             hex = digits.charAt(digit) + hex;  // string concatenation
             number = number / base;
         }
         return hex;
    }

}
</code>```

Body:
The actual logic in your getHex method is fine, but it doesn't work because your other methods (and the getHex method) mutate 'value', so by the time you call getHex() the value has been destroyed.

Adjust your code such that if you need to mutate the value then you make a copy of it, eg:

public String getHex() {
    int number = value;
    // now mutate number, not value

Incidentally, declaring value final would flag this mutation up automatically:

private final int value;

public SmallInt(final int value) {
    this.value = value;
}
...

Thus, the edited code would be:

import java.util.Scanner;

public class TestSmallInt
{
    /** Main method */
    public static void main(String[] args)
    {
        Scanner sc = new Scanner (System.in);
        System.out.print("Enter a desired number: ");
        int decimal = sc.nextInt();
        SmallInt number = new SmallInt (decimal);

        String numberAsString = number.getDec ();
        String numberAsBin = number.getBin ();
        String numberAsHex = number.getHex ();
        System.out.println ("Your number in decimal is " + numberAsString);
        System.out.println ("Your number in binary is " + numberAsBin);
        System.out.println ("Your number in hexadecimal is " + numberAsHex);
        sc.close();
    }
}

////////////////////////////////////////////////////////////////////////

class SmallInt
{
    private final int value;

    public SmallInt (int value) {
        this.value = value;
    }

    public String getDec ()
    {
        return ""+ value;
    }

    public String getBin (){
        int number = value;
        if (number == 0) {
                 return "0";
         }
         String binary = "";
         while (number > 0) {
                 int rem = number % 2;
                 binary = rem + binary;
                 number = number / 2;
         }
         return binary;
    }

    public String getHex (){
        String digits = "0123456789ABCDEF";
        int number = value;
         if (number <= 0) {
                 return "0";
                }
         int base = 16;   // flexible to change in any base under 16
         String hex = "";
         while (number > 0) {
             int digit = number % base;              // rightmost digit
             hex = digits.charAt(digit) + hex;  // string concatenation
             number = number / base;
         }
         return hex;
    }

}


来源: stackexchange

问:
Vertx - Restrict Upload file type
I'm creating an API using Vertx to let user upload images but I want to restrict to certain file types - jpg|Jpeg|png.

What's the best way to do this?

```<code>private void uploadLogoHandler(RoutingContext context) {
   //Filter content type

}
</code>```

答:
I am not aware of a "best" way to do it.  But here are some options

[1] on the client, look at the extension of the file before you allow the user to upload it (hide the final upload button and only show it after they select a filename with the correct extension).  You can do this in client side javascript, you can't access the full path of the file, but you can access the name of the file (minus the path).

[2] Do the same as the above on the server.  You should be able to grab the name of the file in the muti-part uplaod.

[3] There is no easy way to check what the actual file type is while the upload is in progress.  What I would do (if you are checking for an image) is write it to a temp file and then run Java ImageIO to read the image.  If it reads without error, then it is an image, if not, you will get an exception, and delete the file.  I am not aware of a security problems of doing this.  Note that reading the file via ImageIO is a blocking operation, so put it in a vert.x execute blocking.

ContentLicense: CC BY-SA 3.0

Title: Vertx - Restrict Upload file type

Body:
I'm creating an API using Vertx to let user upload images but I want to restrict to certain file types - jpg|Jpeg|png.

What's the best way to do this?

private void uploadLogoHandler(RoutingContext context) {
   //Filter content type

}


问:
How to convert an object to a list in netbeans?
here is my code, the sql query returns objects, but the return method returns a list, i can't fix it.</p>

```<code>@GET
@Path("returnPlaceName/{studentid}")
@Produces({"application/json"})
public List<Location> returnPlaceName(@PathParam("studentid") Integer studentid) {
    TypedQuery<Location> q = em.createQuery("SELECT l.locationname, count(l.locationname) FROM Location l where l.studentid.studentid = :studentid GROUP BY l.locationname", Location.class);
    q.setParameter("studentid", studentid);
    return q.getResultList();
}
</code>```

答:
I don't understand all, but your query return ever list for condition:

```<code>SELECT l.locationname, count(l.locationname) FROM Location l where l.studentid.studentid = :studentid GROUP BY l.locationname
</code>```

If you want only 1 record, take:

```<code>SELECT l.locationname, count(l.locationname) FROM Location l where l.studentid.studentid = :studentid AND l.locationname = :locationname
</code>```

And if you want get who first option, you need use foreach, example:

```<code>for(Location loc : yourList){
.
.
.
}
</code>```

Good luck!

Body:
here is my code, the sql query returns objects, but the return method returns a list, i can't fix it.

@GET
@Path("returnPlaceName/{studentid}")
@Produces({"application/json"})
public List<Location> returnPlaceName(@PathParam("studentid") Integer studentid) {
    TypedQuery<Location> q = em.createQuery("SELECT l.locationname, count(l.locationname) FROM Location l where l.studentid.studentid = :studentid GROUP BY l.locationname", Location.class);
    q.setParameter("studentid", studentid);
    return q.getResultList();
}

Body:
I don't understand all, but your query return ever list for condition:

SELECT l.locationname, count(l.locationname) FROM Location l where l.studentid.studentid = :studentid GROUP BY l.locationname

If you want only 1 record, take:

SELECT l.locationname, count(l.locationname) FROM Location l where l.studentid.studentid = :studentid AND l.locationname = :locationname

And if you want get who first option, you need use foreach, example:

for(Location loc : yourList){
.
.
.
}

Good luck!


问:
Set function data into variable using Javascript
I'd like to set the width of an external image (from another url) into a variable, so I can use the newly assigned variable on another function.

The problem is that I get undefined message on the variable, see the code below.

```<code>var site_url = 'http://fabricjs.com/assets/1.svg';

function getMeta(url, callback) {
    var img = new Image();
    img.src = url;
    img.onload = function() { callback(this.width, this.height); }
}
var a = getMeta(site_url, function(width, height) {
    return width;
});

alert(a); //undefined
</code>```

What am I doing wrong, how should I proceed ?

答:
When working with asynchronous functions, you need to put the rest of the code in the callback function (or use promises). Here, you need to put alert inside callback.

```<code>var a = getMeta(site_url, function(width, height) {
  alert(width);
});
</code>```

Body:
I'd like to set the width of an external image (from another url) into a variable, so I can use the newly assigned variable on another function.

The problem is that I get undefined message on the variable, see the code below.

var site_url = 'http://fabricjs.com/assets/1.svg';

function getMeta(url, callback) {
    var img = new Image();
    img.src = url;
    img.onload = function() { callback(this.width, this.height); }
}
var a = getMeta(site_url, function(width, height) {
    return width;
});

alert(a); //undefined

What am I doing wrong, how should I proceed ?

Body:
When working with asynchronous functions, you need to put the rest of the code in the callback function (or use promises). Here, you need to put alert inside callback.

var a = getMeta(site_url, function(width, height) {
  alert(width);
});


问:
Are values of ConcurrentHashMap being synchronized by default?
Below is a piece of code I found here.
It mimics an online gameserver, where players can join to the tables.

```<code>public class GameServer {
  public Map<String, List<Player>> tables = new ConcurrentHashMap<String, List<Player>>();

  public void join(Player player, Table table) {
    if (player.getAccountBalance() > table.getLimit()) {
      List<Player> tablePlayers = tables.get(table.getId());

      synchronized (tablePlayers) {
        if (tablePlayers.size() < 9) {
          tablePlayers.add(player);
        }
      }
    }
  }

  public void leave(Player player, Table table) {/*Method body skipped for brevity*/}

  public void createTable() {
    Table table = new Table();
    tables.put(table.getId(), table);
  }

  public void destroyTable(Table table) {
    tables.remove(table.getId());
  }
}
</code>```

tablePlayers is one of the value of ConcurrentHashMap.

```<code>List<Player> tablePlayers = tables.get(table.getId());
</code>```

Now that ConcurrentHashMap is already thread-safe, why do we still need to synchronize its value object when we want to use it?

```<code>  synchronized (tablePlayers) {
    ...
  }
</code>```

答:
Now that ConcurrentHashMap is already thread-safe, why do we still need to synchronize its value object when we want to use it?

CHM is thread-safe but that only means that it protects itself from concurrent operations.  Just because you are storing an object in a CHM doesn't then make the object magically thread-safe as well.  Once you retrieve the table-list from the CHM it is up to you to lock the object appropriately if it is going to be accessed by multiple threads.

In the case of your code, what happens if two threads call join at the same time?

```<code>synchronized (tablePlayers) {
   // race condition here because a test...
   if (tablePlayers.size() < 9) {
      // and then the add method
      tablePlayers.add(player);
   }
}
</code>```

If there was not the synchronized block then the 2 threads might both check at the same time and see that the size of the table was 8 (for example) and then both go to add themselves to the table.  That's what a race condition is all about.  Because there are 2 operations (a test and then an add), the synchronized is necessary to ensure that only 1 threads at a time can see if they can join a table and then join it.

Also, the synchronized block also protects the table-list itself which probably is not a synchronized collection itself.  Without the synchronized block there, then the 2 threads could write to the List at the same time and corrupt it.

Body:
Below is a piece of code I found here.
It mimics an online gameserver, where players can join to the tables.

public class GameServer {
  public Map<String, List<Player>> tables = new ConcurrentHashMap<String, List<Player>>();

  public void join(Player player, Table table) {
    if (player.getAccountBalance() > table.getLimit()) {
      List<Player> tablePlayers = tables.get(table.getId());

      synchronized (tablePlayers) {
        if (tablePlayers.size() < 9) {
          tablePlayers.add(player);
        }
      }
    }
  }

  public void leave(Player player, Table table) {/*Method body skipped for brevity*/}

  public void createTable() {
    Table table = new Table();
    tables.put(table.getId(), table);
  }

  public void destroyTable(Table table) {
    tables.remove(table.getId());
  }
}

tablePlayers is one of the value of ConcurrentHashMap.

List<Player> tablePlayers = tables.get(table.getId());

Now that ConcurrentHashMap is already thread-safe, why do we still need to synchronize its value object when we want to use it?

  synchronized (tablePlayers) {
    ...
  }

Body:
Now that ConcurrentHashMap is already thread-safe, why do we still need to synchronize its value object when we want to use it?

CHM is thread-safe but that only means that it protects itself from concurrent operations.  Just because you are storing an object in a CHM doesn't then make the object magically thread-safe as well.  Once you retrieve the table-list from the CHM it is up to you to lock the object appropriately if it is going to be accessed by multiple threads.

In the case of your code, what happens if two threads call join at the same time?

synchronized (tablePlayers) {
   // race condition here because a test...
   if (tablePlayers.size() < 9) {
      // and then the add method
      tablePlayers.add(player);
   }
}

If there was not the synchronized block then the 2 threads might both check at the same time and see that the size of the table was 8 (for example) and then both go to add themselves to the table.  That's what a race condition is all about.  Because there are 2 operations (a test and then an add), the synchronized is necessary to ensure that only 1 threads at a time can see if they can join a table and then join it.

Also, the synchronized block also protects the table-list itself which probably is not a synchronized collection itself.  Without the synchronized block there, then the 2 threads could write to the List at the same time and corrupt it.


问:
How often should I remind the user on "Rate the app" (iPhone)?
I have this application: http://www.youtube.com/watch?v=Tn7_yNt1OaE

I made a mechanism that counts the number of times the app has launched, and measure the playtime duration as well.

I want to remind the user on she/he can support the development, can help others to find my app by dropping a rate in the App Store (I have instant App Store link format as well).

The only thing I want to discuss here: How often/rare should I remind the user?

The first should be about after 15 launch, and 3-6 hours of playtime... ...or not? And the second? Have you any experience on it?

答:
I know that I get annoyed as hell about this type of thing. Not pestering me with such a question will actually yield the highest probability that I care to vote.

Make quality content, then people will give you high ratings.

You might keep your first reminder in, but if I haven't voted after the 15th launch, I certainly won't vote after the 100th launch.

ContentLicense: CC BY-SA 2.5


问:
Rails Webpacker and stage-2 class transform properties not working
I'm trying out Webpacker on a new Rails application to get familiar with it and I can't get it to compile my javascript code.

Here's the code:

```<code>import React, { Component, PropTypes } from 'react'
import DayPicker, { DateUtils } from 'react-day-picker'
import 'react-day-picker/lib/style.css'

export default class Example extends Component {
  constructor(props) {
    super(props)
    this.state = {
      selectedDays: []
    }
  }

  handleDayClick = (day, selected) => {
    console.log(day)
  }

  render() {
    return (
      <p>Test</p>
    )
  }
}

20:05:21 hot.1  | ERROR in ./app/javascript/packs/components/example/example.jsx
20:05:21 hot.1  | Module build failed: SyntaxError: Missing class properties transform.
20:05:21 hot.1  |
20:05:21 hot.1  |   11 |   }
20:05:21 hot.1  |   12 |
20:05:21 hot.1  | > 13 |   handleDayClick = (day, selected) => {
20:05:21 hot.1  |      |   ^
</code>```

This is on a brand new Rails app using the latest Webpacker gem from github.

My .babelrc:

```<code>{
  "presets": ["env", "es2015", "react", "stage-2"]
}
</code>```

My devDependencies are:

```<code>"devDependencies": {
  "babel-preset-es2015": "^6.24.0",
  "babel-preset-stage-2": "^6.22.0",
  "webpack-dev-server": "^2.4.2"
}
</code>```

According to this Babel REPL link,  this should be working. https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-2&targets=&browsers=&builtIns=false&experimental=true&loose=false&spec=false&code=class%20PostInfo%20extends%20React.Component%20%7B%0A%09handleOptionsButtonClick%20%3D%20(e)%20%3D%3E%20%7B%0A%20%20%20%20this.setState(%7BshowOptionsModal%3A%20true%7D)%3B%0A%20%20%7D%0A%7D

Any ideas?

答:
Your comment was most illuminating: this is a method declaration in a class; there should be no equal sign or fat arrow. This is how it should look:

```<code>handleDayClick (day, selected) {
    console.log(day)
}
</code>```

Take a look at how the constructor and render methods look; that's how all methods in a react component look.

D'oh!

Body:
I'm trying out Webpacker on a new Rails application to get familiar with it and I can't get it to compile my javascript code.

Here's the code:

import React, { Component, PropTypes } from 'react'
import DayPicker, { DateUtils } from 'react-day-picker'
import 'react-day-picker/lib/style.css'

export default class Example extends Component {
  constructor(props) {
    super(props)
    this.state = {
      selectedDays: []
    }
  }

  handleDayClick = (day, selected) => {
    console.log(day)
  }

  render() {
    return (

Test

    )
  }
}

20:05:21 hot.1  | ERROR in ./app/javascript/packs/components/example/example.jsx
20:05:21 hot.1  | Module build failed: SyntaxError: Missing class properties transform.
20:05:21 hot.1  |
20:05:21 hot.1  |   11 |   }
20:05:21 hot.1  |   12 |
20:05:21 hot.1  | > 13 |   handleDayClick = (day, selected) => {
20:05:21 hot.1  |      |   ^

This is on a brand new Rails app using the latest Webpacker gem from github.

My .babelrc:

{
  "presets": ["env", "es2015", "react", "stage-2"]
}

My devDependencies are:

"devDependencies": {
  "babel-preset-es2015": "^6.24.0",
  "babel-preset-stage-2": "^6.22.0",
  "webpack-dev-server": "^2.4.2"
}

According to this Babel REPL link,  this should be working. https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Creact%2Cstage-2&targets=&browsers=&builtIns=false&experimental=true&loose=false&spec=false&code=class%20PostInfo%20extends%20React.Component%20%7B%0A%09handleOptionsButtonClick%20%3D%20(e)%20%3D%3E%20%7B%0A%20%20%20%20this.setState(%7BshowOptionsModal%3A%20true%7D)%3B%0A%20%20%7D%0A%7D

Any ideas?

Body:
Your comment was most illuminating: this is a method declaration in a class; there should be no equal sign or fat arrow. This is how it should look:

handleDayClick (day, selected) {
    console.log(day)
}

Take a look at how the constructor and render methods look; that's how all methods in a react component look.

D'oh!


问:
How do I calculate an array of very large numbers without getting NaN in my output?
I made a calculator that works for small numbers but when the results get too large it returns NaN

```<code>List<string> memory = new List<string> { };

string display = "";
while (display.Contains("%") == false)
{
    string line = ReadLine();
    display = line;
    memory.Add(line);
}

float result = float.Parse(memory[0]);

for (int i = 1; i < memory.Count; i++)
{
    string temp = memory[i];
    char[] _temp = temp.ToCharArray();
    _temp = _temp.Where(x => x > _temp[0]).ToArray();
    float num = float.Parse(string.Join("", _temp));

    if (temp.Contains("+") == true) result += num;
    else if (temp.Contains("-") == true) result -= num;
    else if (temp.Contains("*") == true) result *= num;
    else if (temp.Contains("/") == true) result /= num;
    else if (temp.Contains("%") == true) result %= num;
}
</code>```

Take these numbers for example:

```<code>797 * 2 + 38 * 212 * 275 * 806 * 67 * 9939 + 7 + 74 + 515 + 610 * 516 * 6921
+ 4 * 2 * 494 * 3153 * 8 + 2501 * 769 + 4 * 2472 + 1 * 21 * 6535 + 30 + 26
+ 44 + 240 + 88 * 1111 * 817 * 1576 + 551 * 535 + 9150 + 36 * 85 * 4598
* 9276 * 766 + 584 + 5 * 1 + 7 + 45 * 8152 % 7984
</code>```

I enter each number in a new readline with the math symbol infront of it.
If you test it with these numbers just be aware.

I've looked everywhere and cant figure out a solution to this problem so that it can return a real number.

Anyone know what I can do to fix this?

答:
The values you are using are too large for float. When the value gets too large for your float, it returns PositiveInfinity (or NegativeInfinity) instead of a number value. According to MSDN:

This constant is returned when the result of an operation is greater than MaxValue.

so your float becomes 'infinity' instead of a number.

Then, when you try an operation like divide or mod, float returns NaN. Again, from MSDN:

A method or operator returns NaN when the result of an operation is undefined.

so when you divide your float (infinity) by a number, the result is NaN

You may want to consider using BigInteger.

Body:
I made a calculator that works for small numbers but when the results get too large it returns NaN

List<string> memory = new List<string> { };

string display = "";
while (display.Contains("%") == false)
{
    string line = ReadLine();
    display = line;
    memory.Add(line);
}

float result = float.Parse(memory[0]);

for (int i = 1; i < memory.Count; i++)
{
    string temp = memory[i];
    char[] _temp = temp.ToCharArray();
    _temp = _temp.Where(x => x > _temp[0]).ToArray();
    float num = float.Parse(string.Join("", _temp));

    if (temp.Contains("+") == true) result += num;
    else if (temp.Contains("-") == true) result -= num;
    else if (temp.Contains("*") == true) result *= num;
    else if (temp.Contains("/") == true) result /= num;
    else if (temp.Contains("%") == true) result %= num;
}

Take these numbers for example:

797 * 2 + 38 * 212 * 275 * 806 * 67 * 9939 + 7 + 74 + 515 + 610 * 516 * 6921
+ 4 * 2 * 494 * 3153 * 8 + 2501 * 769 + 4 * 2472 + 1 * 21 * 6535 + 30 + 26
+ 44 + 240 + 88 * 1111 * 817 * 1576 + 551 * 535 + 9150 + 36 * 85 * 4598
* 9276 * 766 + 584 + 5 * 1 + 7 + 45 * 8152 % 7984

I enter each number in a new readline with the math symbol infront of it.
If you test it with these numbers just be aware.

I've looked everywhere and cant figure out a solution to this problem so that it can return a real number.

Anyone know what I can do to fix this?


问:
VBA SYNTAX to EXCLUDE .XLS file types being attached to bulk email send
Have a quick question in relation to the attached. section -I have some VBA that will ask a user if they want to attach any additional documents (Atach = MsgBox("Do you wish to attach any additional Documents", vbYesNo) to a looped email task - however, I need to find a smarter way to alert the user that .xls file types cannot be attached and not allow them to attach that file type only.

Have tried if syntax but I think I am missing something. I am rather new to VBA so appreciate all your feedback.

```<code>Application.ScreenUpdating = False

Dim OutApp As Object
Dim OutMail As Object
Dim OutWordEditor As Object

Dim Tocell As Range
Dim SigString As String
Dim t               '' Overall timer after selecting files
Dim i As Integer    '' ASLS looping
Dim j As String    '' extra attachment
Dim x As Single     '' Delay timer
Dim valid As Integer

Dim titlestring As String
Dim FileW As Boolean
Dim Attachrng As String
Dim attach As String

Dim Worddoc As Object
Dim WordFile As String
Dim ToRangeCounter As Variant

Dim attachrange() As String

i = 0
j = 0
valid = 0
FileW = False
WordFile = ""

Atach = MsgBox("You have selected the Notifications Auto Email Macro",    vbYesNo)

If Atach = vbNo Then
            MsgBox ("Macro will now close")
            Exit Sub
            End If
WordFile = ""
FileW = False

Do Until FileW = True
WordFile = Application.GetOpenFilename(Title:="Select Notificatin to send as the email body", MultiSelect:=False)

Call Preview(WordFile)

Usercheck = MsgBox("Confirm this is correct ", vbYesNo)

If Usercheck = vbYes Then
FileW = True
End If
Loop
Else
MsgBox ("Please re select the file you wish to attach")
End If
Loop

***

Atach = MsgBox("Do you wish to attach any additional Documents", vbYesNo)
If Atach = vbYes Then

    For k = 0 To 1
    j = InputBox("How many files do you wish to attach?" & vbNewLine & "Only enter a number", "Enter a number here", 1)
    If Not IsNumeric(j) Then
        MsgBox ("You have failed to enter a number, please try again")
        k = 0
        valid = valid + 1
        If valid = 3 Then
            MsgBox ("You have failed to input a number 3 times" & vbNewLine & "Macro will now close")
            Exit Sub
            End If

        Else
            k = k + 1
            ReDim Preserve attachrange(j)
        End If
    Next
</code>```

```<code>For Z = 1 To j
   titlestring = "You are attaching file number " & Z & " of " & j
   attachrange(Z) = Application.GetOpenFilename(Title:=titlestring, MultiSelect:=False)
   Next

  End If

On Error GoTo Cleanup
</code>```

答:
If you were to use Word's FileDialog you could do two things. One, you could filter out xlx files. They wouldn't show up for selection. Two, you could allow multiple selections, doing away with your question of how many the user wants to add. You might adapt the following code to your needs.

```<code>Function FilePicker(ByVal Tit As String, _
                    ByVal Btn As String, _
                    ByVal FltDesc As String, _
                    ByVal Flt As String, _
                    Fn As String, _
                    Optional Multi As Boolean = False) As Boolean
    ' 22 Mar 2017

    ' ==================================================
    '   Parameters:
    '       Tit               = Title
    '       Btn               = Button caption
    '       FltDesc           = Plain language filter
    '       Flt               = Filter string
    '       Fn                = Initial file name
    '                           Returns selected full file name
    ' ==================================================

    Dim FoD As FileDialog                           ' FilePicker Dialog

    ' ==================================================

    Set FoD = Application.FileDialog(msoFileDialogFilePicker)
    With FoD
        .Title = Tit
        .ButtonName = Btn
        .Filters.Clear
        .Filters.Add FltDesc, Flt, 1
        .AllowMultiSelect = Multi
        .InitialFileName = Fn
        If .Show Then
            Fn = .SelectedItems(1)
            FilePicker = True
        End If
    End With

    Set FoD = Nothing
End Function
</code>```

Then, you might work on the files the user has attached (perhaps using some other method or by modifying the FileDialog) and check the FileFormat property of the attached files. Remove any you don't which to approve. Look for xlFileFormat constants to identify specific file formats.

Body:
Have a quick question in relation to the attached. section -I have some VBA that will ask a user if they want to attach any additional documents (Atach = MsgBox("Do you wish to attach any additional Documents", vbYesNo) to a looped email task - however, I need to find a smarter way to alert the user that .xls file types cannot be attached and not allow them to attach that file type only.

Have tried if syntax but I think I am missing something. I am rather new to VBA so appreciate all your feedback.

Application.ScreenUpdating = False

Dim OutApp As Object
Dim OutMail As Object
Dim OutWordEditor As Object

Dim Tocell As Range
Dim SigString As String
Dim t               '' Overall timer after selecting files
Dim i As Integer    '' ASLS looping
Dim j As String    '' extra attachment
Dim x As Single     '' Delay timer
Dim valid As Integer

Dim titlestring As String
Dim FileW As Boolean
Dim Attachrng As String
Dim attach As String

Dim Worddoc As Object
Dim WordFile As String
Dim ToRangeCounter As Variant

Dim attachrange() As String

i = 0
j = 0
valid = 0
FileW = False
WordFile = ""

Atach = MsgBox("You have selected the Notifications Auto Email Macro",    vbYesNo)

If Atach = vbNo Then
            MsgBox ("Macro will now close")
            Exit Sub
            End If
WordFile = ""
FileW = False

Do Until FileW = True
WordFile = Application.GetOpenFilename(Title:="Select Notificatin to send as the email body", MultiSelect:=False)

Call Preview(WordFile)

Usercheck = MsgBox("Confirm this is correct ", vbYesNo)

If Usercheck = vbYes Then
FileW = True
End If
Loop
Else
MsgBox ("Please re select the file you wish to attach")
End If
Loop

***

Atach = MsgBox("Do you wish to attach any additional Documents", vbYesNo)
If Atach = vbYes Then

    For k = 0 To 1
    j = InputBox("How many files do you wish to attach?" & vbNewLine & "Only enter a number", "Enter a number here", 1)
    If Not IsNumeric(j) Then
        MsgBox ("You have failed to enter a number, please try again")
        k = 0
        valid = valid + 1
        If valid = 3 Then
            MsgBox ("You have failed to input a number 3 times" & vbNewLine & "Macro will now close")
            Exit Sub
            End If

        Else
            k = k + 1
            ReDim Preserve attachrange(j)
        End If
    Next

For Z = 1 To j
   titlestring = "You are attaching file number " & Z & " of " & j
   attachrange(Z) = Application.GetOpenFilename(Title:=titlestring, MultiSelect:=False)
   Next

  End If

On Error GoTo Cleanup

Body:
If you were to use Word's FileDialog you could do two things. One, you could filter out xlx files. They wouldn't show up for selection. Two, you could allow multiple selections, doing away with your question of how many the user wants to add. You might adapt the following code to your needs.

Function FilePicker(ByVal Tit As String, _
                    ByVal Btn As String, _
                    ByVal FltDesc As String, _
                    ByVal Flt As String, _
                    Fn As String, _
                    Optional Multi As Boolean = False) As Boolean
    ' 22 Mar 2017

    ' ==================================================
    '   Parameters:
    '       Tit               = Title
    '       Btn               = Button caption
    '       FltDesc           = Plain language filter
    '       Flt               = Filter string
    '       Fn                = Initial file name
    '                           Returns selected full file name
    ' ==================================================

    Dim FoD As FileDialog                           ' FilePicker Dialog

    ' ==================================================

    Set FoD = Application.FileDialog(msoFileDialogFilePicker)
    With FoD
        .Title = Tit
        .ButtonName = Btn
        .Filters.Clear
        .Filters.Add FltDesc, Flt, 1
        .AllowMultiSelect = Multi
        .InitialFileName = Fn
        If .Show Then
            Fn = .SelectedItems(1)
            FilePicker = True
        End If
    End With

    Set FoD = Nothing
End Function

Then, you might work on the files the user has attached (perhaps using some other method or by modifying the FileDialog) and check the FileFormat property of the attached files. Remove any you don't which to approve. Look for xlFileFormat constants to identify specific file formats.


问:
How I ignore slashes in Ruby Regular Expression
```<code>a = 'CS 141 FALL 2016/SessionData/L1609211319.xml'
Class = a.match(/(.*)SessionData/)
class = Class.to_s
puts "Class is " + class
</code>```

When I try to match the regular expression of that string it gives me "CS 141 FALL 2016/" When I tried to ignore the '/' after 2016 it didn't work. How do I do it?

答:
Here's something to consider: URLs contain a "path", and that path can easily be extracted using URI, then munged using File's methods.

```<code>require 'uri'

uri = URI.parse('http://example.com/path/to/a/resource.xml')
the_path = uri.path # => "/path/to/a/resource.xml"
File.split(the_path) # => ["/path/to/a", "resource.xml"]
File.basename(the_path) # => "resource.xml"
File.extname(the_path) # => ".xml"
File.basename(the_path, File.extname(the_path)) # => "resource"
File.dirname(the_path) # => "/path/to/a"
File.absolute_path('..', the_path) # => "/path/to/a"
</code>```

There are more methods available, but that gives an idea of what can be done without having to get dirty.

You can also start with String's split:

```<code>the_path.split('/') # => ["", "path", "to", "a", "resource.xml"]
</code>```

then grab the chunks that way too.

Bringing it all home:

```<code>the_path = 'CS 141 FALL 2016/SessionData/L1609211319.xml'
File.split(the_path) # => ["CS 141 FALL 2016/SessionData", "L1609211319.xml"]
File.basename(the_path) # => "L1609211319.xml"
File.extname(the_path) # => ".xml"
File.basename(the_path, File.extname(the_path)) # => "L1609211319"
File.dirname(the_path) # => "CS 141 FALL 2016/SessionData"

the_path.split('/') # => ["CS 141 FALL 2016", "SessionData", "L1609211319.xml"]
</code>```

and of course:

```<code>the_path.split('/').first # => "CS 141 FALL 2016"
</code>```

Regular expressions are nice, but often there are effective ways of doing something without resorting to them. If you insist:

```<code>the_path = 'CS 141 FALL 2016/SessionData/L1609211319.xml'
the_path[ %r#^([^/]+)# ] # => "CS 141 FALL 2016"
</code>```

Ruby's %r literal defines whatever is inside the delimiters as a regular expression. The Regexp documentation says:

Regexps are created using the /.../ and %r{...} literals, and by the Regexp::new constructor.

Knowing that, it's easy to step around the leaning-toothpick syndrome of dealing with /.../ as delimiters, forcing the need to escape the delimiters if they're inside the pattern. This'd be the equivalent that only hints at the dragons that wait for the unwary:

```<code>the_path[ /^([^\/]+)/ ] # => "CS 141 FALL 2016"
</code>```

Body:
a = 'CS 141 FALL 2016/SessionData/L1609211319.xml'
Class = a.match(/(.*)SessionData/)
class = Class.to_s
puts "Class is " + class

When I try to match the regular expression of that string it gives me "CS 141 FALL 2016/" When I tried to ignore the '/' after 2016 it didn't work. How do I do it?

Body:
Here's something to consider: URLs contain a "path", and that path can easily be extracted using URI, then munged using File's methods.

require 'uri'

uri = URI.parse('http://example.com/path/to/a/resource.xml')
the_path = uri.path # => "/path/to/a/resource.xml"
File.split(the_path) # => ["/path/to/a", "resource.xml"]
File.basename(the_path) # => "resource.xml"
File.extname(the_path) # => ".xml"
File.basename(the_path, File.extname(the_path)) # => "resource"
File.dirname(the_path) # => "/path/to/a"
File.absolute_path('..', the_path) # => "/path/to/a"

There are more methods available, but that gives an idea of what can be done without having to get dirty.

You can also start with String's split:

the_path.split('/') # => ["", "path", "to", "a", "resource.xml"]

then grab the chunks that way too.

Bringing it all home:

the_path = 'CS 141 FALL 2016/SessionData/L1609211319.xml'
File.split(the_path) # => ["CS 141 FALL 2016/SessionData", "L1609211319.xml"]
File.basename(the_path) # => "L1609211319.xml"
File.extname(the_path) # => ".xml"
File.basename(the_path, File.extname(the_path)) # => "L1609211319"
File.dirname(the_path) # => "CS 141 FALL 2016/SessionData"

the_path.split('/') # => ["CS 141 FALL 2016", "SessionData", "L1609211319.xml"]

and of course:

the_path.split('/').first # => "CS 141 FALL 2016"

Regular expressions are nice, but often there are effective ways of doing something without resorting to them. If you insist:

the_path = 'CS 141 FALL 2016/SessionData/L1609211319.xml'
the_path[ %r#^([^/]+)# ] # => "CS 141 FALL 2016"

Ruby's %r literal defines whatever is inside the delimiters as a regular expression. The Regexp documentation says:

Regexps are created using the /.../ and %r{...} literals, and by the Regexp::new constructor.

Knowing that, it's easy to step around the leaning-toothpick syndrome of dealing with /.../ as delimiters, forcing the need to escape the delimiters if they're inside the pattern. This'd be the equivalent that only hints at the dragons that wait for the unwary:

the_path[ /^([^\/]+)/ ] # => "CS 141 FALL 2016"


问:
How can I make an Parallel AsyncTask or a method that reacts to a change in a variable in android?
I'm creating an app that shows bus location and routes in android with google maps. I have the bus location updates by running an AsyncTask getting a Json with the lat lon coordinates and modifying the value of the marker. What I want to do now is to modify the bus marker to display an ETA to the next bus stop (by measuring the difference of lat long to the next marker in route and assigning a time to it to count down to or another way). The thing is that I don't know how to make a method that reacts to changes on the variable that is updated

My questions are Is it possible to make a method that reacts to the changes on a set variable? How can I achieve this? or Is there a way to run multiple AsyncTask to realize the updates I want to do to the bus marker?

Note:I have a 15+ sized arraylist with the latlon of the bus stops markers. Since i believe i will have to do various methods to calculate and update the marker i don't know if asynctask would be good for it.

Note2: I keep calling the asynctask with a handler that executes every 10 sec like this:

```<code> public void tiempo(){
    final Handler hadleupd=new Handler();
    hadleupd.postDelayed(new Runnable() {

        @Override
        public void run() {
            new GetBus().execute();//My AsyncTask
            hadleupd.postDelayed(this, 1000);
        }
    }, 1000);

}
</code>```

答:
what you can basically do, is to add an Callback (or Listener) to your AsyncTask.

Inside your class, which is extending AsyncTask, you need to implement Listener interface.

Example:

```<code>public class CustomTask extends AsyncTask<Void, Void, YourDataType> {

    private final Context mContext;
    private final Callback mCallback;

    public interface Callback {
        void onComplete(YourDataType result);
        void onError(Exception e);
    }

    public CustomTask(Context context, Callback callback) {
        mContext = context;
        mCallback = callback;
    }

    @Override
    protected void onPostExecute(YourDataType result) {
        super.onPostExecute(result);
        if (mException != null) {
            mCallback.onError(mException);
        } else {
            mCallback.onComplete(result);
        }
    }

    @Override
    protected File doInBackground(Void... params) {
            // Do your stuff
    }
}
</code>```

Then, simply when calling the Task in your timer, your instantiating will look like this

```<code>public void tiempo(){
    final Handler hadleupd=new Handler();
    hadleupd.postDelayed(new Runnable() {

        @Override
        public void run() {
            new GetBus(getContext(), new Callback(
            @Override
            public void onComplete(YourDataType result){
            // Handle success
            }

            @Override
            public void onError(Exception e) {
            // Handle Error

        }).execute();//My AsyncTask
            hadleupd.postDelayed(this, 1000);
        }
    }, 1000);

}
</code>```

Body:
I'm creating an app that shows bus location and routes in android with google maps. I have the bus location updates by running an AsyncTask getting a Json with the lat lon coordinates and modifying the value of the marker. What I want to do now is to modify the bus marker to display an ETA to the next bus stop (by measuring the difference of lat long to the next marker in route and assigning a time to it to count down to or another way). The thing is that I don't know how to make a method that reacts to changes on the variable that is updated

My questions are Is it possible to make a method that reacts to the changes on a set variable? How can I achieve this? or Is there a way to run multiple AsyncTask to realize the updates I want to do to the bus marker?

Note:I have a 15+ sized arraylist with the latlon of the bus stops markers. Since i believe i will have to do various methods to calculate and update the marker i don't know if asynctask would be good for it.

Note2: I keep calling the asynctask with a handler that executes every 10 sec like this:

 public void tiempo(){
    final Handler hadleupd=new Handler();
    hadleupd.postDelayed(new Runnable() {

        @Override
        public void run() {
            new GetBus().execute();//My AsyncTask
            hadleupd.postDelayed(this, 1000);
        }
    }, 1000);

}

Body:
what you can basically do, is to add an Callback (or Listener) to your AsyncTask.

Inside your class, which is extending AsyncTask, you need to implement Listener interface.

Example:

public class CustomTask extends AsyncTask<Void, Void, YourDataType> {

    private final Context mContext;
    private final Callback mCallback;

    public interface Callback {
        void onComplete(YourDataType result);
        void onError(Exception e);
    }

    public CustomTask(Context context, Callback callback) {
        mContext = context;
        mCallback = callback;
    }

    @Override
    protected void onPostExecute(YourDataType result) {
        super.onPostExecute(result);
        if (mException != null) {
            mCallback.onError(mException);
        } else {
            mCallback.onComplete(result);
        }
    }

    @Override
    protected File doInBackground(Void... params) {
            // Do your stuff
    }
}

Then, simply when calling the Task in your timer, your instantiating will look like this

public void tiempo(){
    final Handler hadleupd=new Handler();
    hadleupd.postDelayed(new Runnable() {

        @Override
        public void run() {
            new GetBus(getContext(), new Callback(
            @Override
            public void onComplete(YourDataType result){
            // Handle success
            }

            @Override
            public void onError(Exception e) {
            // Handle Error

        }).execute();//My AsyncTask
            hadleupd.postDelayed(this, 1000);
        }
    }, 1000);

}


问:
Browser Repaint/Reflow performance: using CSS3 Gradients vs PNG Gradients
I am working at an app that causes lots of browser reflows. Performance is a key issue here. From the performance point of view Is it better to use a CSS3 gradient or an image gradient for some DOM elements? Does a page that uses CSS text shadows and gradients will have a slower reflow as a page that uses images to achieve those visual effects?
Also, are there any reflow tests out there I can use?</p>

答: For drawing, CSS gradients and shadows do task the CPU more than images. Performance used to be pretty bad, these days they are acceptable. If you have a ton of gradients/shadows, you should just implement them and do the tests in your real-world setting. If you just have a few, I wouldn't worry about it.</p>


问:
Regex for removing consecutive character formatting tags
I need a regex to match and replace the consecutive character formatting tags enclosing the entire paragraph tags in simple DOM Html Parser

Input :

```<code><p><b><i>Lorem Ipsum Content</i></b></p>
</code>```

Expected output :
Lorem Ipsum

In the below case regex should match and replace only the  tags since that's the only tag that encloses the entire paragraph tag

eg :Input :
Text  some more text text inside

output :
Text  some more text text inside

Thanks .

答:
It will look something like this:

```<code>foreach($html->find('p') as $p) {
  while(preg_match('/^<([^>]+)>(.*)<\/\1>$/', $p->innertext, $m)){
    $p->innertext = $m[2];
  }
}
</code>```

Note that the \1 in the regex matches the html tag name from the first capture group, probably not necessary but I did it for the bonus.

Body:
I need a regex to match and replace the consecutive character formatting tags enclosing the entire paragraph tags in simple DOM Html Parser

Input :

Lorem Ipsum Content

Expected output :
Lorem Ipsum

In the below case regex should match and replace only the  tags since that's the only tag that encloses the entire paragraph tag

eg :Input :
Text  some more text text inside

output :
Text  some more text text inside

Thanks .

Body:
It will look something like this:

foreach($html->find('p') as $p) {
  while(preg_match('/^<([^>]+)>(.*)<\/\1>$/', $p->innertext, $m)){
    $p->innertext = $m[2];
  }
}

Note that the \1 in the regex matches the html tag name from the first capture group, probably not necessary but I did it for the bonus.


问:
Using FirebaseListAdapter to display a list of User
I'm trying to add a "Search User" Activity to a simple App I'm trying to make. But I'm having trouble taking the user input (from a SearchView) and using it to make a query into the Firebase Database to finally display everything in a Listview (using FirebaseListAdapter).

The problem is mainly with the Firebase part that I can't really figure out. Here is the code:

```<code>SearchView userSearchView;
ListView userListView;
SearchUserListAdapter UserAdapter;
String currentUserName;
String currentEnteredQuery = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_user);

    userSearchView = (SearchView) findViewById(R.id.user_searchview);
    userListView = ( ListView) findViewById(R.id.listview_search);
    final Intent startConversation = new Intent(this,ConversationActivity.class);

    //Start a new conversation
    userListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            startActivity(startConversation);
        }
    });

    Query query = UserDbRef.orderByChild(currentEnteredQuery);
    final FirebaseListAdapter firebaseListAdapter = new FirebaseListAdapter<UserItem>(this, UserItem.class, R.layout.user_item, query) {
        @Override
        protected void populateView(View v, UserItem userItem) {
            ((TextView)v.findViewById(android.R.id.text1)).setText(userItem.getUser_name());
        }
    };
    userListView.setAdapter(firebaseListAdapter);

    userSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

        @Override
        public boolean onQueryTextSubmit(String inputQuery) {
            currentEnteredQuery = inputQuery;
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_search_user, menu);
    return true;
}
</code>```

答:
Put your query inside the Listener for the SearchView so that it would query everytime you search with a specific criteria:

```<code>userSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

    @Override
    public boolean onQueryTextSubmit(String inputQuery) {
        currentEnteredQuery = inputQuery;
        //Your Firebase Query here
        Query query = UserDbRef.orderByChild(currentEnteredQuery);
        final FirebaseListAdapter firebaseListAdapter = new FirebaseListAdapter<UserItem>(this, UserItem.class, R.layout.user_item, query) {
            @Override
            protected void populateView(View v, UserItem userItem) {
                ((TextView)v.findViewById(android.R.id.text1)).setText(userItem.getUser_name());
            }
        };
        userListView.setAdapter(firebaseListAdapter);
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }
});
</code>```

Also in these lines:

```<code>final FirebaseListAdapter firebaseListAdapter = new FirebaseListAdapter<UserItem>(this, UserItem.class, R.layout.user_item, query) {
    @Override
    protected void populateView(View v, UserItem userItem) {
        ((TextView)v.findViewById(android.R.id.text1)).setText(userItem.getUser_name());
    }
};
</code>```

You are using R.layout.user_item as your layout for the list but you are using android.R.id.text1. As far as I know, android.R are resources built-in the Android SDK. I think this is the view if you are using android.R.layout.simple_list_item_1. Go ahead and check your R.layout.user_item and change the id to the corresponding view in your layout.

Body:
I'm trying to add a "Search User" Activity to a simple App I'm trying to make. But I'm having trouble taking the user input (from a SearchView) and using it to make a query into the Firebase Database to finally display everything in a Listview (using FirebaseListAdapter).

The problem is mainly with the Firebase part that I can't really figure out. Here is the code:

SearchView userSearchView;
ListView userListView;
SearchUserListAdapter UserAdapter;
String currentUserName;
String currentEnteredQuery = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_user);

    userSearchView = (SearchView) findViewById(R.id.user_searchview);
    userListView = ( ListView) findViewById(R.id.listview_search);
    final Intent startConversation = new Intent(this,ConversationActivity.class);

    //Start a new conversation
    userListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            startActivity(startConversation);
        }
    });

    Query query = UserDbRef.orderByChild(currentEnteredQuery);
    final FirebaseListAdapter firebaseListAdapter = new FirebaseListAdapter<UserItem>(this, UserItem.class, R.layout.user_item, query) {
        @Override
        protected void populateView(View v, UserItem userItem) {
            ((TextView)v.findViewById(android.R.id.text1)).setText(userItem.getUser_name());
        }
    };
    userListView.setAdapter(firebaseListAdapter);

    userSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

        @Override
        public boolean onQueryTextSubmit(String inputQuery) {
            currentEnteredQuery = inputQuery;
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_search_user, menu);
    return true;
}

Body:
Put your query inside the Listener for the SearchView so that it would query everytime you search with a specific criteria:

userSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

    @Override
    public boolean onQueryTextSubmit(String inputQuery) {
        currentEnteredQuery = inputQuery;
        //Your Firebase Query here
        Query query = UserDbRef.orderByChild(currentEnteredQuery);
        final FirebaseListAdapter firebaseListAdapter = new FirebaseListAdapter<UserItem>(this, UserItem.class, R.layout.user_item, query) {
            @Override
            protected void populateView(View v, UserItem userItem) {
                ((TextView)v.findViewById(android.R.id.text1)).setText(userItem.getUser_name());
            }
        };
        userListView.setAdapter(firebaseListAdapter);
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        return false;
    }
});

Also in these lines:

final FirebaseListAdapter firebaseListAdapter = new FirebaseListAdapter<UserItem>(this, UserItem.class, R.layout.user_item, query) {
    @Override
    protected void populateView(View v, UserItem userItem) {
        ((TextView)v.findViewById(android.R.id.text1)).setText(userItem.getUser_name());
    }
};

You are using R.layout.user_item as your layout for the list but you are using android.R.id.text1. As far as I know, android.R are resources built-in the Android SDK. I think this is the view if you are using android.R.layout.simple_list_item_1. Go ahead and check your R.layout.user_item and change the id to the corresponding view in your layout.


问:
accessing an element in a list in Scheme
I have to write a function in scheme to access the element 'a' in the following list.
'(1 (2 a 4 5))

I wrote

```<code>(car (cdr (cdr '(1 (2 a 4 5)))))
</code>```

but i get error

```<code>"car: contract violation
  expected: pair?
  given: '()"
</code>```

How do i fix this to work ?

答:
Proceeding from @soegaard's response...
The thing that is causing the problem is the fact that you have a list contained in a list.

starting with (car (cdr '(1 (2 a 4 5)))), which is '(2 a 4 5), you now need to pull the second item from that list, which you can do with the single cadr procedure or you can nest them, producing (car (cdr (car (cdr '(1 (2 a 4 5))))))

As soegaard explained, there is an "invisible" empty list in there, which explains why you need (car (cdr '(1 (2 a 4 5)))) to get the list.

Remember, '(2 a 4 5) is a list, so you need to treat it as a list. Get the cdr and then pull the car from it.

As @Sylwester noted, you can combine the letters to form compound names. Racket supports up to four layers, so you can create the one you need (barely) and obtain the same result with (cadadr '(1 (2 a 4 5))).

Remember the "invisible" empty list. That seems to be what was tripping you up.

Body:
I have to write a function in scheme to access the element 'a' in the following list.
'(1 (2 a 4 5))

I wrote

(car (cdr (cdr '(1 (2 a 4 5)))))

but i get error

"car: contract violation
  expected: pair?
  given: '()"

How do i fix this to work ?


问:
NodesJS SocketIO - How can I make sure websockets are being used?
Background

I'm working to connect a Unity application to a SocketIO application

Unity is using a SocketIO Plugin (only uses websockets, not polling/xhr)

To connect to my websocket from Unity I'm using ws://localhost:3000/socket.io/?EIO=4&transport=websocket. If I hit that link via browser I see the following:

```<code>{"code":3,"message":"Bad request"}
</code>```

At this point I forced websockets for my NodeJS application with io.set('transports', ['websocket']); but then my application stopped working.

Question

How can I make sure websockets are available for NodeJS+SocketIO?

Code

app.js

```<code>var app = require('express')();
var http = require('http').Server(app);

app.get('/', function(req, res){
        res.sendFile(__dirname + '/index.html');
});

var server = app.listen(3000, function () {
   var host = server.address().address
   var port = server.address().port
});
var io = require('socket.io').listen(server);
//io.set('transports', ['websocket']);

...
</code>```

Setup

Ubuntu@14.04

NodeJS@0.10.25

SocketI@O1.7.3

express@4.15.2

答:
By default, a socket.io client starts out with http polling and then switches to webSocket after a few polling transactions.  As best I've been able to tell, nothing you can do on the server will change the way the client behaves so if you don't support polling on your server and you don't change the way the client is configured, then the initial socket.io client connection will not work.  But, you can make corresponding changes in BOTH client and server to force socket.io to only use webSocket, even from the beginning.  If you're looking at the network trace, you will still see an initial HTTP connection because all webSocket connections start with an HTTP connection, but then that HTTP connection is "upgraded" to the webSocket protocol.

You can see all the details on how to configure both client and server to ONLY use webSocket here: Socket.io 1.x: use WebSockets only?.  In a nutshell, you will want to do this in the client for making a connection:

```<code>var socket = io({transports: ['websocket'], upgrade: false});
</code>```

Body:
Background

I'm working to connect a Unity application to a SocketIO application

Unity is using a SocketIO Plugin (only uses websockets, not polling/xhr)

To connect to my websocket from Unity I'm using ws://localhost:3000/socket.io/?EIO=4&transport=websocket. If I hit that link via browser I see the following:

{"code":3,"message":"Bad request"}

At this point I forced websockets for my NodeJS application with io.set('transports', ['websocket']); but then my application stopped working.

Question

How can I make sure websockets are available for NodeJS+SocketIO?

Code

app.js

var app = require('express')();
var http = require('http').Server(app);

app.get('/', function(req, res){
        res.sendFile(__dirname + '/index.html');
});

var server = app.listen(3000, function () {
   var host = server.address().address
   var port = server.address().port
});
var io = require('socket.io').listen(server);
//io.set('transports', ['websocket']);

...

Setup

Ubuntu@14.04

NodeJS@0.10.25

SocketI@O1.7.3

express@4.15.2

Body:
By default, a socket.io client starts out with http polling and then switches to webSocket after a few polling transactions.  As best I've been able to tell, nothing you can do on the server will change the way the client behaves so if you don't support polling on your server and you don't change the way the client is configured, then the initial socket.io client connection will not work.  But, you can make corresponding changes in BOTH client and server to force socket.io to only use webSocket, even from the beginning.  If you're looking at the network trace, you will still see an initial HTTP connection because all webSocket connections start with an HTTP connection, but then that HTTP connection is "upgraded" to the webSocket protocol.

You can see all the details on how to configure both client and server to ONLY use webSocket here: Socket.io 1.x: use WebSockets only?.  In a nutshell, you will want to do this in the client for making a connection:

var socket = io({transports: ['websocket'], upgrade: false});


问:
Reusing a angular 1.4 directive inside an angular 1.5 application
I would like to reuse an angularjs 1.4 directive within an angularjs 1.5 application.
Is this possible?
Are there any issues ?
Thank you</p>

答:
Are there any issues ?

Not much an issue with a simple directive.

However with a complex directive, watch out for depreciated methods and keywords between versions 1.4 and 1.5. There are lots of changes between 1.4 and 1.5. So, try to add 1.4 directive into angular 1.5 app one at a time and test the application for easier debug.  Write Unit Test as much as possible.

Don't be afraid: If you run into a problem when adding 1.4 directive into 1.5 application and could not figure out the error: Set up a simple bare-bone 1.5 application and add your 1.4 directive in Plunker project and ask the Angularjs community here about the issue you have.  Good luck!


问:
Adding something to a dynamic array
I want to add X to the end of my Array if the array is full I double the size but i'm having trouble inserting it into newArray after I get it into newArray I use pointers to switch dynamicArray to newArray.</p>

```<code>  #include <iostream>
using namespace std;

class IntegerDynamicArray {
    public:
        IntegerDynamicArray();
      ~IntegerDynamicArray();
        int add(int x);
    private:
        int * dynamicArray;
        int currentSize=maxSize;
        int maxSize=4;

};``

IntegerDynamicArray::IntegerDynamicArray()
   {
      dynamicArray = new int [maxSize];
   }
   IntegerDynamicArray::~IntegerDynamicArray()
   {
      delete [] dynamicArray;
   }

int IntegerDynamicArray::add(int x)
   {
     cout<<x<<endl;
      if(dynamicArray[currentSize-1]!=0)
      {
         int * newArray;
         newArray= new int[currentSize*2];
         for(int i =0;i<currentSize;i++)
         {
            newArray[i]=dynamicArray[i];
            newArray[currentSize]=x;

         }
         currentSize=currentSize*2;
         dynamicArray = newArray;

      }
      else
      {
         int * newArray;
         newArray= new int[currentSize];
         for(int i =0;i<currentSize;i++)
         {
            newArray[i]=dynamicArray[i];
            newArray[currentSize-1]=x;

         }

          dynamicArray = newArray;

      }
      return *dynamicArray;
   }

int main() {
    IntegerDynamicArray intDynArray;
    while (1) {
        char input;
        cout << "Enter A for add or anything else to quit: ";
        cin >> input;
        if (input == 'A') {
            cout << "Enter number to add: ";
            int x;
            cin >> x;
            cout << intDynArray.add(x) << endl;
        } else {
            break;
        }
    }
}
</code>```

答:
There are several problems with your code. Because you didn't asked a dedicated question these are the main ones:

Your class lacks a variable containing the index of the last written (or next free) index of the array. Instead you (mis)use currentSize as such index variable.

On each call of add() you allocate a new array although it might not be full already.

As already mentioned in the comments you do not delete [] your old arrays after copying into the new one.

You use 0 as indicator that a slot in your array is empty, but you do not prevent adding 0 as regular element and you do not initialize your array to zero.

Title: Adding something to a dynamic array

Body:
I want to add X to the end of my Array if the array is full I double the size but i'm having trouble inserting it into newArray after I get it into newArray I use pointers to switch dynamicArray to newArray.

  #include <iostream>
using namespace std;

class IntegerDynamicArray {
    public:
        IntegerDynamicArray();
      ~IntegerDynamicArray();
        int add(int x);
    private:
        int * dynamicArray;
        int currentSize=maxSize;
        int maxSize=4;

};``

IntegerDynamicArray::IntegerDynamicArray()
   {
      dynamicArray = new int [maxSize];
   }
   IntegerDynamicArray::~IntegerDynamicArray()
   {
      delete [] dynamicArray;
   }

int IntegerDynamicArray::add(int x)
   {
     cout<<x<<endl;
      if(dynamicArray[currentSize-1]!=0)
      {
         int * newArray;
         newArray= new int[currentSize*2];
         for(int i =0;i<currentSize;i++)
         {
            newArray[i]=dynamicArray[i];
            newArray[currentSize]=x;

         }
         currentSize=currentSize*2;
         dynamicArray = newArray;

      }
      else
      {
         int * newArray;
         newArray= new int[currentSize];
         for(int i =0;i<currentSize;i++)
         {
            newArray[i]=dynamicArray[i];
            newArray[currentSize-1]=x;

         }

          dynamicArray = newArray;

      }
      return *dynamicArray;
   }

int main() {
    IntegerDynamicArray intDynArray;
    while (1) {
        char input;
        cout << "Enter A for add or anything else to quit: ";
        cin >> input;
        if (input == 'A') {
            cout << "Enter number to add: ";
            int x;
            cin >> x;
            cout << intDynArray.add(x) << endl;
        } else {
            break;
        }
    }
}


答:
As  Thomas Matthews pointed out:

You are leaking memory while calling add(int x). For each use of new, there should be a call for delete

Consider the following:

```<code> int n=10;
 int* x= new int[n];
 //assign some values

 int* temp=new int[n*2]; //create new array

 for(int i=0;i<n;i++)
  temp[i]=x[i]; //assign values from x

 delete[] x; //free memory

 x=temp; //assign to x address of new array
</code>```

Manual memory managment can be risky, so consider using std::vector in future

Title: Adding something to a dynamic array

Body:
As  Thomas Matthews pointed out:

You are leaking memory while calling add(int x). For each use of new, there should be a call for delete

Consider the following:

 int n=10;
 int* x= new int[n];
 //assign some values

 int* temp=new int[n*2]; //create new array

 for(int i=0;i<n;i++)
  temp[i]=x[i]; //assign values from x

 delete[] x; //free memory

 x=temp; //assign to x address of new array

Manual memory managment can be risky, so consider using std::vector in future


问:
Github/Cygwin error: cygheap base mismatch detected
Git has been giving me this error

```<code>    0 [main] sh (47116) C:\Users\Marcus\AppData\Local\GitHub\PortableGit_c7e0cbde92ba565cb218a521411d0e854079a28c\usr\bin\sh.exe: *** fatal error - cygheap base mismatch detected - 0x11C7400/0x1297400.
This problem is probably due to using incompatible versions of the cygwin DLL.
Search for cygwin1.dll using the Windows Start->Find/Search facility
and delete all but the most recent version.  The most recent version *should*
reside in x:\cygwin\bin, where 'x' is the drive on which you have
installed the cygwin distribution.  Rebooting is also suggested if you
are unable to find another cygwin DLL.
    0 [main] sh 42052 fork: child -1 - forked process 47116 died unexpectedly, retry 0, exit code 0xC0000142, errno 11
/mingw32/libexec/git-core/git-sh-setup: fork: retry: No child processes
This problem is probably due to using incompatible versions of the cygwin DLL.
Search for cygwin1.dll using the Windows Start->Find/Search facility
and delete all but the most recent version.  The most recent version *should*
reside in x:\cygwin\bin, where 'x' is the drive on which you have
installed the cygwin distribution.  Rebooting is also suggested if you
are unable to find another cygwin DLL.
    0 [main] sh 42052 fork: child -1 - forked process 47116 died unexpectedly, retry 0, exit code 0xC0000142, errno 11
/mingw32/libexec/git-core/git-sh-setup: fork: retry: No child processes
</code>```

Things I've tried include:

deleting cygwin from C:\cygwin and C:\cygwin64 and reinstalling

reinstalling github using the uninstaller and installer.

uninstalling github and manually removing its local and roaming appdata folders, and reinstalling.

rebooting the computer

rebasing C:\cygwin, it succeeded, but didnt fix any issues.

rebasing %appdata%\Local\Github\PortableGit_c7e...\. it returned the original error again.

for reference, I'm running windows 10 64 bit. The only other question I could find that pin pointed the error I'm getting never reached a solution: link here

I'm not sure where else to go aside from just reinstalling windows altogether, any help would be greatly appreciated.

答: Rebooting fixed it for me. I probably got this error because of upgrading Git for Windows. Try rebooting before doing any of the other crazy things!</p>

Body:
Git has been giving me this error

    0 [main] sh (47116) C:\Users\Marcus\AppData\Local\GitHub\PortableGit_c7e0cbde92ba565cb218a521411d0e854079a28c\usr\bin\sh.exe: *** fatal error - cygheap base mismatch detected - 0x11C7400/0x1297400.
This problem is probably due to using incompatible versions of the cygwin DLL.
Search for cygwin1.dll using the Windows Start->Find/Search facility
and delete all but the most recent version.  The most recent version *should*
reside in x:\cygwin\bin, where 'x' is the drive on which you have
installed the cygwin distribution.  Rebooting is also suggested if you
are unable to find another cygwin DLL.
    0 [main] sh 42052 fork: child -1 - forked process 47116 died unexpectedly, retry 0, exit code 0xC0000142, errno 11
/mingw32/libexec/git-core/git-sh-setup: fork: retry: No child processes
This problem is probably due to using incompatible versions of the cygwin DLL.
Search for cygwin1.dll using the Windows Start->Find/Search facility
and delete all but the most recent version.  The most recent version *should*
reside in x:\cygwin\bin, where 'x' is the drive on which you have
installed the cygwin distribution.  Rebooting is also suggested if you
are unable to find another cygwin DLL.
    0 [main] sh 42052 fork: child -1 - forked process 47116 died unexpectedly, retry 0, exit code 0xC0000142, errno 11
/mingw32/libexec/git-core/git-sh-setup: fork: retry: No child processes

Things I've tried include:

deleting cygwin from C:\cygwin and C:\cygwin64 and reinstalling

reinstalling github using the uninstaller and installer.

uninstalling github and manually removing its local and roaming appdata folders, and reinstalling.

rebooting the computer

rebasing C:\cygwin, it succeeded, but didnt fix any issues.

rebasing %appdata%\Local\Github\PortableGit_c7e...\. it returned the original error again.

for reference, I'm running windows 10 64 bit. The only other question I could find that pin pointed the error I'm getting never reached a solution: link here

I'm not sure where else to go aside from just reinstalling windows altogether, any help would be greatly appreciated.


问:
Pushing icon to the right of text in Bootstrap
Using Bootstrap 3.3.7, I'm trying to create a two-column row with the following content and characteristics:

Left column (col-sm-9) that contains text

Right column (col-sm-3) that contains one horizontally and vertically centered image

Non-full-height vertical divider in between those two divs

I am having trouble getting the entire row to display with a minimum of 980 pixels and created a fiddle here:

Originally, the image div container on the right was only as tall as the image itself, so I added the following code to force same heights, but that caused the width to be reduced to the size of the contents within each div:

```<code>[class*="ccol-"] {
float: none;
display: table-cell;
vertical-align: middle;
}
</code>```

I was wondering how other Bootstrappers might code out a simple row with text on the left, a vertical divider, and an image on the right.

答: Have you tried using the  min-width attribute? You could force a container to be a certain size or bigger by adding, for instance, "min-width: 980px;" to the relevant container.

Body:
Using Bootstrap 3.3.7, I'm trying to create a two-column row with the following content and characteristics:

Left column (col-sm-9) that contains text

Right column (col-sm-3) that contains one horizontally and vertically centered image

Non-full-height vertical divider in between those two divs

I am having trouble getting the entire row to display with a minimum of 980 pixels and created a fiddle here:

Originally, the image div container on the right was only as tall as the image itself, so I added the following code to force same heights, but that caused the width to be reduced to the size of the contents within each div:

[class*="ccol-"] {
float: none;
display: table-cell;
vertical-align: middle;
}

I was wondering how other Bootstrappers might code out a simple row with text on the left, a vertical divider, and an image on the right.


问:
How do I read from a socket and return individual lines?
Am I supposed to read each character until it reaches the \n character, join them all together and return or is there a better way? Should I use std::string or char for this?

I tried the following two examples but I need to read them as separate lines

Example 1:

```<code>std::string sockread()
{
    std::string s;
    s.resize(DEFAULT_BUFLEN);
    int result = recv(m_socket, &s[0], DEFAULT_BUFLEN, 0);

    if (result > 0) {
        return s;
    } else if (result == 0) {
        connected = false;
    } else {
        std::cout << "recv failed with error " << WSAGetLastError() << "\n";
    }
    throw std::runtime_error("Socket connection failed!");
}
</code>```

Example 2:

```<code>char sockread(void)

  {
    int result;
    char buffer[DEFAULT_BUFLEN];
        result = recv(m_socket, buffer, DEFAULT_BUFLEN, 0);

        if (result > 0) {
             return *buffer;
              }
          else if (result == 0)
              {
             connected = false;
                 return *buffer;
              }
          else {
         printf("recv failed with error: %d\n", WSAGetLastError());
         return *buffer;
        }

   }
</code>```

答:
Use Boost.ASIO - line-based operations covered here.

Many commonly-used internet protocols
  are line-based, which means that they
  have protocol elements that are
  delimited by the character sequence
  "\r\n". Examples include HTTP, SMTP
  and FTP. To more easily permit the
  implementation of line-based
  protocols, as well as other protocols
  that use delimiters, Boost.Asio
  includes the functions read_until()
  and async_read_until().

Body:
Am I supposed to read each character until it reaches the \n character, join them all together and return or is there a better way? Should I use std::string or char for this?

I tried the following two examples but I need to read them as separate lines

Example 1:

std::string sockread()
{
    std::string s;
    s.resize(DEFAULT_BUFLEN);
    int result = recv(m_socket, &s[0], DEFAULT_BUFLEN, 0);

    if (result > 0) {
        return s;
    } else if (result == 0) {
        connected = false;
    } else {
        std::cout << "recv failed with error " << WSAGetLastError() << "\n";
    }
    throw std::runtime_error("Socket connection failed!");
}

Example 2:

char sockread(void)

  {
    int result;
    char buffer[DEFAULT_BUFLEN];
        result = recv(m_socket, buffer, DEFAULT_BUFLEN, 0);

        if (result > 0) {
             return *buffer;
              }
          else if (result == 0)
              {
             connected = false;
                 return *buffer;
              }
          else {
         printf("recv failed with error: %d\n", WSAGetLastError());
         return *buffer;
        }

   }


问:
Pycharm 2017.1 Open Debug Command Line is not working at all
I was not sure if anyone else has run into this issue, but in the new Pycharm 2017.1 the Open Debug Command Line option is not working at all. I created a test case and ran it with py.test with no problem. But when I have a breakpoint and try to Open Debug Command Line the debug console only opens a regular python console with no connection to the underlying debug process. I can't seem to access any variables in the debug scope either.

I have posted an issue to the Jetbrains Pycharm issue tracker issue PY-23401.

In the image below you can see the debug console opened at the bottom of the screenshot. I tried to enter some variable values from the debug session, but don't receive an error and don't receive any info either. Has anyone else run into this, and has anyone found a way to fix this?

答:
It looks like your lower_ml variable is None.

Try going back into the debugger tab, and setting a watcher for it. Or try lower_ml is None in the console.


问:
clone git repo at specfic commit
As part of our current workflow we pre-clone certain git repos into user homedirs at the time of creation. However, as these repositories grow and user count increases the disk usage has become more and more problematic.

I am attacking this on two fronts:

Existing repos with no changed files get git reset --hard $first_commit which reverts them to a much tinier initial state. The usual git pull on login brings them up to current as always.

New users get repos that start at $initial commit and can get brought up to current via git pull.

While I've come up with a solution for #1 and submitted it for review I'm having trouble coming up with a solution for #2 that doesn't incur a lot of IO overhead.

The simple solution would just be:

```<code>git clone /opt/git/app.git /home/user/app && \
git -C /home/user/app reset --hard $first_commit
</code>```

However, checking out the full working tree only to delete it incurs a lot of extra IO, which is a valid concern when a new application server is created along with all of the requisite users.

I've tried the following based on this answer, but the resulting repo isn't properly set up to pull from origin/master:

```<code>git init /home/user/app
git -C /home/user/app remote add origin /opt/git/app.git
git -C /home/user/app fetch origin $first_commit
</code>```

It doesn't seem to have any branch set at all somehow, and the following is missing from .git/config:

```<code>[branch "master"]
        remote = origin
        merge = refs/heads/master
</code>```

Thanks in advance.

答:
Use git branch --set-upstream-to to set master’s upstream:

```<code>git init
git remote add origin /opt/git/app.git
git fetch origin
git reset --hard "$first_commit"
git branch --set-upstream-to=origin/master
</code>```

Title: clone git repo at specfic commit

Body:
As part of our current workflow we pre-clone certain git repos into user homedirs at the time of creation. However, as these repositories grow and user count increases the disk usage has become more and more problematic.

I am attacking this on two fronts:

Existing repos with no changed files get git reset --hard $first_commit which reverts them to a much tinier initial state. The usual git pull on login brings them up to current as always.

New users get repos that start at $initial commit and can get brought up to current via git pull.

While I've come up with a solution for #1 and submitted it for review I'm having trouble coming up with a solution for #2 that doesn't incur a lot of IO overhead.

The simple solution would just be:

git clone /opt/git/app.git /home/user/app && \
git -C /home/user/app reset --hard $first_commit

However, checking out the full working tree only to delete it incurs a lot of extra IO, which is a valid concern when a new application server is created along with all of the requisite users.

I've tried the following based on this answer, but the resulting repo isn't properly set up to pull from origin/master:

git init /home/user/app
git -C /home/user/app remote add origin /opt/git/app.git
git -C /home/user/app fetch origin $first_commit

It doesn't seem to have any branch set at all somehow, and the following is missing from .git/config:

[branch "master"]
        remote = origin
        merge = refs/heads/master

Thanks in advance.

Body:
Use git branch --set-upstream-to to set master’s upstream:

git init
git remote add origin /opt/git/app.git
git fetch origin
git reset --hard "$first_commit"
git branch --set-upstream-to=origin/master


问:
Google play services leader board not showing
I have it showing fine for one leader board, whatever board, I call it by itself. When I want to show all of the boards I make the call below. It shows the last board called only. I understand this, what I want to know is there a way to just call the leader boards without calling one at a time so the user can compare the scores to each other?</p>

```<code> private void signToLeaderBoard() {
    if (mGoogleApiClient.isConnected()) {
        startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mGoogleApiClient,
                context.getString(R.string.leaderboard_game_high_score)), 1);
        startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mGoogleApiClient,
                context.getString(R.string.leaderboard_total_high_score)),1);
        startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mGoogleApiClient,
                context.getString(R.string.leaderboard_grab_a_word_count)), 1);
    } else {
        // make dialog asking to sign in
    }
}
</code>```

答:
Ok, I guess if I spent more time researching for an answer I'd saved myself time asking the question. I have made the changes to the code below. and it works great.

```<code> private static final int RC_UNUSED = 5001;

 private void signToLeaderBoard() {
    if (mGoogleApiClient.isConnected()) {
        startActivityForResult(Games.Leaderboards.getAllLeaderboardsIntent(mGoogleApiClient),
                RC_UNUSED);
        // startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mGoogleApiClient,
         //        context.getString(R.string.leaderboard_game_high_score)), 1);
    } else {
        // make dialog asking to sign in
    }
}
</code>```

Body:
I have it showing fine for one leader board, whatever board, I call it by itself. When I want to show all of the boards I make the call below. It shows the last board called only. I understand this, what I want to know is there a way to just call the leader boards without calling one at a time so the user can compare the scores to each other?

 private void signToLeaderBoard() {
    if (mGoogleApiClient.isConnected()) {
        startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mGoogleApiClient,
                context.getString(R.string.leaderboard_game_high_score)), 1);
        startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mGoogleApiClient,
                context.getString(R.string.leaderboard_total_high_score)),1);
        startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mGoogleApiClient,
                context.getString(R.string.leaderboard_grab_a_word_count)), 1);
    } else {
        // make dialog asking to sign in
    }
}

Body:
Ok, I guess if I spent more time researching for an answer I'd saved myself time asking the question. I have made the changes to the code below. and it works great.

 private static final int RC_UNUSED = 5001;

 private void signToLeaderBoard() {
    if (mGoogleApiClient.isConnected()) {
        startActivityForResult(Games.Leaderboards.getAllLeaderboardsIntent(mGoogleApiClient),
                RC_UNUSED);
        // startActivityForResult(Games.Leaderboards.getLeaderboardIntent(mGoogleApiClient,
         //        context.getString(R.string.leaderboard_game_high_score)), 1);
    } else {
        // make dialog asking to sign in
    }
}


问:
How to retrieve serialize template of fingerprint from the database?
I'm using digitalpersona u.are.u 4500 fingerprint reader.

This is the codes I used to save fingerprint template to database:

```<code>    Dim str As New MemoryStream
    Enroller.Template.Serialize(str)
    Dim serializedTemplate As Byte() = str.ToArray()
    Dim bytes() as Byte = serializedTemplate
    comm.Parameters.AddWithValue("@Emp_FPrint", bytes)
</code>```

The problem is when I try to retrieve fingerprint  from the database and Deserialize it , I have this error:

Conversion from type 'Byte()' to type 'Byte' is not valid.

This is the code I used to retrieve  and Deserialize fingerprint:

```<code>    Sub OnComplete(ByVal Capture As Object, ByVal ReaderSerialNumber As String, ByVal Sample As DPFP.Sample) Implements DPFP.Capture.EventHandler.OnComplete
      MakeReport("The fingerprint sample was captured.")
      SetPrompt("Scan the same fingerprint again.")
      Process(Sample)

      CheckTemplate()
      If ds1MaxRow > 0 Then
        For i = 0 To ds1MaxRow - 1
            '  byteArray = CType(ds1VerifyFPrintp.Tables("TestImage").Rows(i).Item(1), Byte())
            con1 = New SqlConnection
            con1.ConnectionString = "Data Source=ERSERVER;Initial Catalog=Timekeeping;User ID=sa;Password=sa"
            Dim thequery As String = "Select Emp_FPrint from TestImage "
            con1.Open()
            Dim cmd As SqlCommand = New SqlCommand(thequery, con1)
            Dim rsBioData As SqlDataReader = cmd.ExecuteReader

            Dim byteTemplate As Byte
            Dim memStreamTemplate As MemoryStream
            If rsBioData.HasRows Then
                While rsBioData.Read
                    byteTemplate = rsBioData("Emp_FPrint")      ''''''''ERROR HERE :   Conversion from type 'Byte()' to type 'Byte' is not valid. '''''''
                    memStreamTemplate = New MemoryStream(byteTemplate)
                    Me.Template.DeSerialize(memStreamTemplate)
                End While
            End If
            '''''''STUCK UNTO THIS LINE''''''''''

            Dim features As DPFP.FeatureSet = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification)

            ' Check quality of the sample and start verification if it's good
            If Not features Is Nothing Then
                ' Compare the feature set with our template
                Dim result As DPFP.Verification.Verification.Result = New DPFP.Verification.Verification.Result()
                Verificator.Verify(features, Template, result)
                '  UpdateStatus(result.FARAchieved)
                If result.Verified Then
                    MakeReport("The fingerprint was VERIFIED.")
                Else
                    MakeReport("The fingerprint was NOT VERIFIED.")
                End If
            End If

        Next i
    End If
 End Sub
</code>```

答:
Try this

Dim cmd As New MySqlCommand("SELECT * FROM employeefp  ", conn)
    Dim rdr As MySqlDataReader = cmd.ExecuteReader()

```<code>While (rdr.Read())
    Dim MemStream As IO.MemoryStream
    Dim fpBytes As Byte()

    fpBytes = rdr("FP")
    MemStream = New IO.MemoryStream(fpBytes)

    Dim templa8 As DPFP.Template = New DPFP.Template()
    templa8.DeSerialize(MemStream)

    Dim tmpObj As New AppData
    tmpObj.No = rdr("No").ToString()
    tmpObj.Template = templa8
    FPList.Add(tmpObj)
End While
</code>```

Body:
I'm using digitalpersona u.are.u 4500 fingerprint reader.

This is the codes I used to save fingerprint template to database:

    Dim str As New MemoryStream
    Enroller.Template.Serialize(str)
    Dim serializedTemplate As Byte() = str.ToArray()
    Dim bytes() as Byte = serializedTemplate
    comm.Parameters.AddWithValue("@Emp_FPrint", bytes)

The problem is when I try to retrieve fingerprint  from the database and Deserialize it , I have this error:

Conversion from type 'Byte()' to type 'Byte' is not valid.

This is the code I used to retrieve  and Deserialize fingerprint:

    Sub OnComplete(ByVal Capture As Object, ByVal ReaderSerialNumber As String, ByVal Sample As DPFP.Sample) Implements DPFP.Capture.EventHandler.OnComplete
      MakeReport("The fingerprint sample was captured.")
      SetPrompt("Scan the same fingerprint again.")
      Process(Sample)

      CheckTemplate()
      If ds1MaxRow > 0 Then
        For i = 0 To ds1MaxRow - 1
            '  byteArray = CType(ds1VerifyFPrintp.Tables("TestImage").Rows(i).Item(1), Byte())
            con1 = New SqlConnection
            con1.ConnectionString = "Data Source=ERSERVER;Initial Catalog=Timekeeping;User ID=sa;Password=sa"
            Dim thequery As String = "Select Emp_FPrint from TestImage "
            con1.Open()
            Dim cmd As SqlCommand = New SqlCommand(thequery, con1)
            Dim rsBioData As SqlDataReader = cmd.ExecuteReader

            Dim byteTemplate As Byte
            Dim memStreamTemplate As MemoryStream
            If rsBioData.HasRows Then
                While rsBioData.Read
                    byteTemplate = rsBioData("Emp_FPrint")      ''''''''ERROR HERE :   Conversion from type 'Byte()' to type 'Byte' is not valid. '''''''
                    memStreamTemplate = New MemoryStream(byteTemplate)
                    Me.Template.DeSerialize(memStreamTemplate)
                End While
            End If
            '''''''STUCK UNTO THIS LINE''''''''''

            Dim features As DPFP.FeatureSet = ExtractFeatures(Sample, DPFP.Processing.DataPurpose.Verification)

            ' Check quality of the sample and start verification if it's good
            If Not features Is Nothing Then
                ' Compare the feature set with our template
                Dim result As DPFP.Verification.Verification.Result = New DPFP.Verification.Verification.Result()
                Verificator.Verify(features, Template, result)
                '  UpdateStatus(result.FARAchieved)
                If result.Verified Then
                    MakeReport("The fingerprint was VERIFIED.")
                Else
                    MakeReport("The fingerprint was NOT VERIFIED.")
                End If
            End If

        Next i
    End If
 End Sub

Body:
Try this

Dim cmd As New MySqlCommand("SELECT * FROM employeefp  ", conn)
    Dim rdr As MySqlDataReader = cmd.ExecuteReader()

While (rdr.Read())
    Dim MemStream As IO.MemoryStream
    Dim fpBytes As Byte()

    fpBytes = rdr("FP")
    MemStream = New IO.MemoryStream(fpBytes)

    Dim templa8 As DPFP.Template = New DPFP.Template()
    templa8.DeSerialize(MemStream)

    Dim tmpObj As New AppData
    tmpObj.No = rdr("No").ToString()
    tmpObj.Template = templa8
    FPList.Add(tmpObj)
End While


问:
Boost:asio time taken for socket read/write
I have the following code to measure the total time taken for a socket write from client to server. (assuming that the call back method invocation is done on successful write of the data to the destination socket (TCP-ACK received)) Does this ensure that - this time is the actual "network time" for the data transfer ? </p>

```<code>  void on_successful_read_from_client(const boost::system::error_code& error,
                              const size_t& bytes_transferred)
  {
     if (!error)
     {

      m_telnet_server_write_time = posix_time::microsec_clock::universal_time();
      async_write(telnet_server,
              boost::asio::buffer(data_from_device_,bytes_transferred),
              boost::bind(&bridge::on_successful_send_to_server,
                    shared_from_this(),
                    boost::asio::placeholders::error));

     }
     else
        close();
  }

  void on_successful_send_to_server(const boost::system::error_code& error)
  {
     if (!error)
     {
        posix_time::ptime now = posix_time::microsec_clock::universal_time();

        if ((now - m_telnet_server_write_time).total_milliseconds() > 0)
        {
            std::ostringstream log;
            log << "Time Taken for server write: " << (now - m_telnet_server_write_time).total_milliseconds() << " ms";

            write_log(log.str());
        }
</code>```

答: No I don't think it does. I think it measures the time needed to get the data into the buffers in the network stack of your OS, but not the time taken for the data to be transferred to and read by the program at the other end of the connection. The only way you can do that is to have accurate clocks at both ends and have the send time sent to the recipient as part of the message so that it can do the elapsed time calculation. </p>

Body:
I have the following code to measure the total time taken for a socket write from client to server. (assuming that the call back method invocation is done on successful write of the data to the destination socket (TCP-ACK received)) Does this ensure that - this time is the actual "network time" for the data transfer ?

  void on_successful_read_from_client(const boost::system::error_code& error,
                              const size_t& bytes_transferred)
  {
     if (!error)
     {

      m_telnet_server_write_time = posix_time::microsec_clock::universal_time();
      async_write(telnet_server,
              boost::asio::buffer(data_from_device_,bytes_transferred),
              boost::bind(&bridge::on_successful_send_to_server,
                    shared_from_this(),
                    boost::asio::placeholders::error));

     }
     else
        close();
  }

  void on_successful_send_to_server(const boost::system::error_code& error)
  {
     if (!error)
     {
        posix_time::ptime now = posix_time::microsec_clock::universal_time();

        if ((now - m_telnet_server_write_time).total_milliseconds() > 0)
        {
            std::ostringstream log;
            log << "Time Taken for server write: " << (now - m_telnet_server_write_time).total_milliseconds() << " ms";

            write_log(log.str());
        }


问:
Amazon Redshift, getting slower in every update run
I am beginning with Amanzon Redshift.

I have just loaded a big table, millions of rows and 171 fields. The data quality is poor, there are a lot of characters that must be removed.

I have prepare updates for every column, since redshift stores in column mode, I suppose it is faster by column.

UPDATE MyTable SET Field1 = REPLACE(Field1, '~', '');

UPDATE MyTable SET Field2 = REPLACE(Field2, '~', '');

.
.
.

UPDATE MyTable set FieldN = Replace(FieldN, '~', '');

The first 'update' took 1 min. The second one took 1 min and 40 sec...

Every time a run one of the updates, it takes more time than the last one. I have run 19 and the last one took almost 25 min. The time consumed by every 'update' increases one after another.

Another thing is that with the first update, the cpu utilization was minimal, now with the last update it is taking 100%

I have a 3-nodes cluster of dc1.large instances.

I have rebooted the cluster but the problem continues.

Please, I need orientation to find the cause of this problem.

答:
When you update a column, Redshift actually deletes all those rows and inserts new rows with the new value. So there are bunch of space that needs to be reclaimed. So you need to VACUUM your table after the update.

They also recommend that you run ANALYZE after each update to update statistics for the query planner.

http://docs.aws.amazon.com/redshift/latest/dg/r_UPDATE.html


问:
Put data in object
```<code>var mypafgfr = [];
mypafgfr[0] = "tt";
mypafgfr[1] = "tt";
mypafgfr[2] = "tt";
var outputdata = {};

function ls() {
    console.log(mypafgfr[0]); {
        var gg = {};
        gg["n"] = mypafgfr[0];
        gg["image1"] = mypafgfr[1];
        gg["image2"] = mypafgfr[2];
        outputdata["folder"] = gg;
    }
    console.log(outputdata);
}

ls();

mypafgfr[0] = "yy";
mypafgfr[1] = "yy";
mypafgfr[2] = "yy";

ls();
</code>```

In console I'm expect to see

```<code>Object { n="tt",  image1="tt",  image2="tt"}
Object { n="yy",  image1="yy",  image2="yy"}
</code>```

but I got

```<code>Object { n="yy",  image1="yy",  image2="yy"}
Object { n="yy",  image1="yy",  image2="yy"}
</code>```

What I'm doing wrong? How it happen?

答:
That is because console.log() prints the reference of the object.

You could you console.dir() instead to see how the object looks at call time.

One more fallback you can use is to use JSON.stringify() at the time of logging it, which does not point to the reference.

```<code>console.log(JSON.stringify(outputdata));
</code>```

Title: Put data in object

Body:
var mypafgfr = [];
mypafgfr[0] = "tt";
mypafgfr[1] = "tt";
mypafgfr[2] = "tt";
var outputdata = {};

function ls() {
    console.log(mypafgfr[0]); {
        var gg = {};
        gg["n"] = mypafgfr[0];
        gg["image1"] = mypafgfr[1];
        gg["image2"] = mypafgfr[2];
        outputdata["folder"] = gg;
    }
    console.log(outputdata);
}

ls();

mypafgfr[0] = "yy";
mypafgfr[1] = "yy";
mypafgfr[2] = "yy";

ls();

In console I'm expect to see

Object { n="tt",  image1="tt",  image2="tt"}
Object { n="yy",  image1="yy",  image2="yy"}

but I got

Object { n="yy",  image1="yy",  image2="yy"}
Object { n="yy",  image1="yy",  image2="yy"}

What I'm doing wrong? How it happen?

Body:
That is because console.log() prints the reference of the object.

You could you console.dir() instead to see how the object looks at call time.

One more fallback you can use is to use JSON.stringify() at the time of logging it, which does not point to the reference.

console.log(JSON.stringify(outputdata));


问:
log4net: How to store data in DB
I am planning to replace few different logging mechanism with the only 1. Also I would like to store data not in file, but in DB.

For this purpose I am planning to choose log4net. But looking on the documentation I don't see a way to configure it to use DB as logs storage.

Am I missed something? Could you please point me if there is a way to store data in DB using log4net. And how to do that?

Thanks a lot!

答:
There is a good runthrough here:

How to store log in database using log4net

Also the log4net Config Examples show how to setup the config for most databases.

Title: log4net: How to store data in DB


问:
Error connecting to a remote SQL server database Visual Studio 2017
I have an SQL server 2016 instance running on Windows server 2016,
I'm trying to connect to the DB from a remote PC in Visual Studio 2017 Community using the Server Explorer. The connection is successful and I can see the Databases available on the server and login just fine but when I try to expand the tables folder I get this error:

Failed to retrieve data for this request

  Failed to connect to server (local)

  Login Failed for user 'xxxxx'

The thing is I can connect just fine the same way using Visual Studio 2015 Enterprise means I can see the tables and alter them.

I made sure that the user had all the permissions granted on the server,
And to me it doesn't seem to be a permission issue since the connection work just fine in VS 2015.

答: I am having the exact same issue.  loging failed when trying to expand the tables folder.  all other folders actually work, Views, Stored Procedures but not Tables.</p>