问:
Resize Named Range VBA
VBA
Excel 2016

I'm trying to dynamically resize a range if the number of columns is less for that range after some code is executed. Referenced the MS files and various online examples with no luck. https://msdn.microsoft.com/en-us/library/office/ff193274.aspx

I can achieve the correct resize only if I do something like "testRange.Resize Range("A1:G1"). However I am looking for something along the lines of:

```<code>Sub Test_Range()

  Dim Test As Worksheet
  Set Test = Worksheets("test")

  Dim testTable As Range
  Set testTable = Test.Range("testTable[]")

  Dim testTableWidth, testNumbersWidth As Integer
  Set testTableWidth = testTable.Columns.Count

  'Some code
  'testNumbersWith is defined here

  If testNumbersWidth < testTableWidth Then
    testTable.Resize(, testNumbersWidth)
  End If

End Sub
</code>```

答:
Assuming your other code .ClearContents on some columns in the Table (ListObject), say originally you have this:

Then lets say some code clears the content of columns D and I (headers C and H):

Running the code below will remove those columns from Table (by deleting the entire column). You can then use the list table's .DataBodyRange to access the table data only.

```<code>Option Explicit

Sub TableResize()
    Dim oTable As ListObject, oRng As Range, sColsToDelete As String
    Set oTable = ActiveSheet.ListObjects("Table1")
    For Each oRng In oTable.HeaderRowRange
        Debug.Print oRng.Address(0, 0), oRng.Value
        If oRng.Value Like "Column*" Then
            Debug.Print "Column " & oRng.Column & " to be deleted"
            ' Note order to delete is reversed!
            If Len(sColsToDelete) > 0 Then sColsToDelete = "," & sColsToDelete
            sColsToDelete = oRng.Column & sColsToDelete
        End If
    Next
    If Len(sColsToDelete) > 0 Then DeleteCol sColsToDelete
    ' Example to access the data ranges
    For Each oRng In oTable.DataBodyRange
        Debug.Print oRng.Address(0, 0), oRng.Value
    Next
    Set oTable = Nothing
End Sub

Private Sub DeleteCol(sList As String)
    Dim oItem As Variant
    For Each oItem In Split(sList, ",")
        ActiveSheet.Columns(CLng(oItem)).Delete
    Next
End Sub
</code>```

The result of the TableResize execution:

Title: Resize Named Range VBA

Body:
VBA
Excel 2016

I'm trying to dynamically resize a range if the number of columns is less for that range after some code is executed. Referenced the MS files and various online examples with no luck. https://msdn.microsoft.com/en-us/library/office/ff193274.aspx

I can achieve the correct resize only if I do something like "testRange.Resize Range("A1:G1"). However I am looking for something along the lines of:

Sub Test_Range()

  Dim Test As Worksheet
  Set Test = Worksheets("test")

  Dim testTable As Range
  Set testTable = Test.Range("testTable[]")

  Dim testTableWidth, testNumbersWidth As Integer
  Set testTableWidth = testTable.Columns.Count

  'Some code
  'testNumbersWith is defined here

  If testNumbersWidth < testTableWidth Then
    testTable.Resize(, testNumbersWidth)
  End If

End Sub

Body:
Assuming your other code .ClearContents on some columns in the Table (ListObject), say originally you have this:

Then lets say some code clears the content of columns D and I (headers C and H):

Running the code below will remove those columns from Table (by deleting the entire column). You can then use the list table's .DataBodyRange to access the table data only.

Option Explicit

Sub TableResize()
    Dim oTable As ListObject, oRng As Range, sColsToDelete As String
    Set oTable = ActiveSheet.ListObjects("Table1")
    For Each oRng In oTable.HeaderRowRange
        Debug.Print oRng.Address(0, 0), oRng.Value
        If oRng.Value Like "Column*" Then
            Debug.Print "Column " & oRng.Column & " to be deleted"
            ' Note order to delete is reversed!
            If Len(sColsToDelete) > 0 Then sColsToDelete = "," & sColsToDelete
            sColsToDelete = oRng.Column & sColsToDelete
        End If
    Next
    If Len(sColsToDelete) > 0 Then DeleteCol sColsToDelete
    ' Example to access the data ranges
    For Each oRng In oTable.DataBodyRange
        Debug.Print oRng.Address(0, 0), oRng.Value
    Next
    Set oTable = Nothing
End Sub

Private Sub DeleteCol(sList As String)
    Dim oItem As Variant
    For Each oItem In Split(sList, ",")
        ActiveSheet.Columns(CLng(oItem)).Delete
    Next
End Sub

The result of the TableResize execution:


来源: stackexchange

问:
how to make this function more (time) efficient?
i ve got a dataframe series which contain sentences. (some are kind of long)

i ve also got 2 dictionaries which contain words as keys and ints as count.

Not all words from strings are present in both dictionaries. Some are in only one, some are in neither.

Dataframe is 124011 units long. function is taking me about 0.4 per string. which is waaaay to long.

W is just a reference value for the dictionary (weights = {}, weights[W] = {})

here is the function:

```<code>def match_share(string, W, weights, rel_weight):

    words = string.split()

    words_counts = Counter(words)

    ratios = []

    for word in words:

        if ((word in weights[W].keys())&(word in rel_weight[W].keys())):

            if (weights[W][word]!=0):

                ratios.append(words_counts[word]*rel_weight[W][word]/weights[W][word])

        else:

            ratios.append(0)

    if len(words)>0:

        ratios = np.divide(ratios, float(len(words)))

    ratio = np.sum(ratios)

    return ratio
</code>```

thx

答:
It would be good if you had a profile of that function execution, but here are some generic ideas:

You needlessly get some elements on every iteration. You can extract these before the loop

For example

```<code>weights_W = weights[W]
rel_weights_W = rel_weights[W]
</code>```

You don't need to call .keys() on dicts.

These are equivalent:

```<code>word in weights_W.keys()
word in weights_W
</code>```

Attempt to get values without looking them up first. This will save you one lookup.

For example instead of:

```<code>if ((word in weights[W].keys())&(word in rel_weight[W].keys())):
        if (weights[W][word]!=0):
</code>```

you can do:

```<code>word_weight = weights_W.get(word)
if word_weight is not None:
    word_rel_weight = rel_weights_W.get(word)
    if word_rel_weight is not None:
        if word_weight != 0:  # lookup saved here
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i ve got a dataframe series which contain sentences. (some are kind of long)

i ve also got 2 dictionaries which contain words as keys and ints as count.

Not all words from strings are present in both dictionaries. Some are in only one, some are in neither.

Dataframe is 124011 units long. function is taking me about 0.4 per string. which is waaaay to long.

W is just a reference value for the dictionary (weights = {}, weights[W] = {})

here is the function:

def match_share(string, W, weights, rel_weight):

    words = string.split()

    words_counts = Counter(words)

    ratios = []

    for word in words:

        if ((word in weights[W].keys())&(word in rel_weight[W].keys())):

            if (weights[W][word]!=0):

                ratios.append(words_counts[word]*rel_weight[W][word]/weights[W][word])

        else:

            ratios.append(0)

    if len(words)>0:

        ratios = np.divide(ratios, float(len(words)))

    ratio = np.sum(ratios)

    return ratio

thx

Body:
It would be good if you had a profile of that function execution, but here are some generic ideas:

You needlessly get some elements on every iteration. You can extract these before the loop

For example

weights_W = weights[W]
rel_weights_W = rel_weights[W]

You don't need to call .keys() on dicts.

These are equivalent:

word in weights_W.keys()
word in weights_W

Attempt to get values without looking them up first. This will save you one lookup.

For example instead of:

if ((word in weights[W].keys())&(word in rel_weight[W].keys())):
        if (weights[W][word]!=0):

you can do:

word_weight = weights_W.get(word)
if word_weight is not None:
    word_rel_weight = rel_weights_W.get(word)
    if word_rel_weight is not None:
        if word_weight != 0:  # lookup saved here


问:
How do I retrieve Email-ID from auth_user table in Django?
How do I retrieve Email-ID from auth_user table in Django?
 I am getting only id and username if I access the auth_user table.

Models.py

```<code>class AuthUser(models.Model):
id = models.IntegerField(primary_key=True)
    password = models.CharField(max_length=128)
    last_login = models.DateTimeField()
    is_superuser = models.BooleanField()
    username = models.CharField(max_length=30, unique=True)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.CharField(max_length=75)
    is_staff = models.BooleanField()
    is_active = models.BooleanField()
    date_joined = models.DateTimeField()

class Meta:
    db_table = 'auth_user'

def as_json(self):
    return dict(
        user_id=self.id,
        username=self.username,
        email=self.email
    )
</code>```

views.py

```<code>class UserViewSet(generics.ListCreateAPIView):
    serializer_class = AuthUserSerializer

    def get_queryset(self):
        q = self.kwargs['username']
        if q != '*':
            return AuthUser.objects.filter(username=q)
        else:
            return AuthUser.objects.all()
</code>```

urls.py

```<code>url(r'^getUserData/(?P<username>.+)/$',
                                                  views.UserViewSet.as_view(),
                                                  name='user-details'),
</code>```

I need only email from AuthUser object

答:
Have you created a template? Your view class should specify which html file you want to use to render the view

i.e.

template_name = 'app/template.html'

Check out the example here in the docs:
https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-display/

You can then have the following code in your tamplate to list the user emails

```<code>     <ul>
        {% for user in object_list %}
            <li>{{ user.email }}</li>
        {% endfor %}
    </ul>
</code>```

Body:
How do I retrieve Email-ID from auth_user table in Django?
 I am getting only id and username if I access the auth_user table.

Models.py

class AuthUser(models.Model):
id = models.IntegerField(primary_key=True)
    password = models.CharField(max_length=128)
    last_login = models.DateTimeField()
    is_superuser = models.BooleanField()
    username = models.CharField(max_length=30, unique=True)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.CharField(max_length=75)
    is_staff = models.BooleanField()
    is_active = models.BooleanField()
    date_joined = models.DateTimeField()

class Meta:
    db_table = 'auth_user'

def as_json(self):
    return dict(
        user_id=self.id,
        username=self.username,
        email=self.email
    )

views.py

class UserViewSet(generics.ListCreateAPIView):
    serializer_class = AuthUserSerializer

    def get_queryset(self):
        q = self.kwargs['username']
        if q != '*':
            return AuthUser.objects.filter(username=q)
        else:
            return AuthUser.objects.all()

urls.py

url(r'^getUserData/(?P<username>.+)/$',
                                                  views.UserViewSet.as_view(),
                                                  name='user-details'),

I need only email from AuthUser object

Body:
Have you created a template? Your view class should specify which html file you want to use to render the view

i.e.

template_name = 'app/template.html'

Check out the example here in the docs:
https://docs.djangoproject.com/en/1.10/topics/class-based-views/generic-display/

You can then have the following code in your tamplate to list the user emails

     <ul>
        {% for user in object_list %}
            <li>{{ user.email }}</li>
        {% endfor %}
    </ul>


问:
Simple .bat keeps popping up errors
I'm making a .bat to open some programs when I'm going to start streaming, but it says it can't find the pathways.

This is my bat:

```<code>taskkill /f /im Spotify.exe
taskkill /f /im Snaz.exe
taskkill /f /im obs64.exe
taskkill /f /im chrome.exe

cd /d "C:\Users\marka\AppData\Roaming\Spotify"
start C:\Users\marka\AppData\Roaming\Spotify\Spotify.exe

cd /d "F:\Stream Local\Snaz"
start F:\Stream Local\Snaz\Snaz.exe

cd /d "C:\Program Files (x86)\obs-studio\bin\64bit"
start C:\Program Files (x86)\obs-studio\bin\64bit\obs64.exe

start chrome https://www.twitch.tv/markaabo
TIMEOUT 1
start chrome https://streamlabs.com/dashboard#/
TIMEOUT 1
start chrome https://inspector.twitch.tv/#/
TIMEOUT 1
start chrome https://twitter.com/markaabo
pause
</code>```

But when it comes to cd /d "F:\Stream Local\Snaz" it fails a puts out an error message says "Windows can not find F:\Stream. control that you spelled it correct, and then try again" (Sorry if its translated wrong my pc is on danish)

答:
you were missing double quotes around some of your start paths

EDIT
I've updated the answer to be more compact

```<code>start "Launch Spotify" /d "C:\Users\marka\AppData\Roaming\Spotify" "Spotify.exe"
start "Launch Snaz" /d "F:\Stream Local\Snaz" Snaz.exe"
start "Launch obs64" /d "C:\Program Files (x86)\obs-studio\bin\64bit" obs64.exe"

start chrome https://www.twitch.tv/markaabo
TIMEOUT 1
start chrome https://streamlabs.com/dashboard#/
TIMEOUT 1
start chrome https://inspector.twitch.tv/#/
TIMEOUT 1
start chrome https://twitter.com/markaabo
pause
</code>```

Title: Simple .bat keeps popping up errors

Body:
I'm making a .bat to open some programs when I'm going to start streaming, but it says it can't find the pathways.

This is my bat:

taskkill /f /im Spotify.exe
taskkill /f /im Snaz.exe
taskkill /f /im obs64.exe
taskkill /f /im chrome.exe

cd /d "C:\Users\marka\AppData\Roaming\Spotify"
start C:\Users\marka\AppData\Roaming\Spotify\Spotify.exe

cd /d "F:\Stream Local\Snaz"
start F:\Stream Local\Snaz\Snaz.exe

cd /d "C:\Program Files (x86)\obs-studio\bin\64bit"
start C:\Program Files (x86)\obs-studio\bin\64bit\obs64.exe

start chrome https://www.twitch.tv/markaabo
TIMEOUT 1
start chrome https://streamlabs.com/dashboard#/
TIMEOUT 1
start chrome https://inspector.twitch.tv/#/
TIMEOUT 1
start chrome https://twitter.com/markaabo
pause

But when it comes to cd /d "F:\Stream Local\Snaz" it fails a puts out an error message says "Windows can not find F:\Stream. control that you spelled it correct, and then try again" (Sorry if its translated wrong my pc is on danish)

Body:
you were missing double quotes around some of your start paths

EDIT
I've updated the answer to be more compact

start "Launch Spotify" /d "C:\Users\marka\AppData\Roaming\Spotify" "Spotify.exe"
start "Launch Snaz" /d "F:\Stream Local\Snaz" Snaz.exe"
start "Launch obs64" /d "C:\Program Files (x86)\obs-studio\bin\64bit" obs64.exe"

start chrome https://www.twitch.tv/markaabo
TIMEOUT 1
start chrome https://streamlabs.com/dashboard#/
TIMEOUT 1
start chrome https://inspector.twitch.tv/#/
TIMEOUT 1
start chrome https://twitter.com/markaabo
pause


问:
Whaleclub api opening a turbo position
Im trying to test opening a turbo position in the whaleclub api

http://docs.whaleclub.co/

and so far I have

```<code>wc.newTurboPosition({
direction: 'short',
market: 'BTC-USD',
type: '1min',
size: (1 * 1e8)/100
}).then(console.log);
</code>```

using this client library

https://github.com/askmike/whaleclub

I can open a regular position fine using

```<code>wc.newPosition({
direction: 'long',
market: 'BTC-USD',
leverage: 10,
size: 1 * 1e8, // 1 btc
}).then(console.log);
</code>```

nothing shows up in my log either

so not sure why its not working for the turbo position and I tried changing the size too since the turbo market has .1 btc limit but that didnt work either. I am very new at this and thank you in advance

答:
I got it to work using

```<code>wc.newTurboPosition({
direction: 'short',
market: 'BTC-USD',
type: '5min',
size: 1 * 1e6
}).then(console.log)
</code>```

feel kind of dumb now lol

Title: Whaleclub api opening a turbo position

Body:
Im trying to test opening a turbo position in the whaleclub api

http://docs.whaleclub.co/

and so far I have

wc.newTurboPosition({
direction: 'short',
market: 'BTC-USD',
type: '1min',
size: (1 * 1e8)/100
}).then(console.log);

using this client library

https://github.com/askmike/whaleclub

I can open a regular position fine using

wc.newPosition({
direction: 'long',
market: 'BTC-USD',
leverage: 10,
size: 1 * 1e8, // 1 btc
}).then(console.log);

nothing shows up in my log either

so not sure why its not working for the turbo position and I tried changing the size too since the turbo market has .1 btc limit but that didnt work either. I am very new at this and thank you in advance

Body:
I got it to work using

wc.newTurboPosition({
direction: 'short',
market: 'BTC-USD',
type: '5min',
size: 1 * 1e6
}).then(console.log)

feel kind of dumb now lol


问:
How to reinitialize a script in an HTML document?
I have a document that uses the jscolor.com library, for the user to be able to select and store a color. I'm also using a JQuery function to add rows to the screen, so the user can create and define a number of colors. The problem is, when the new row is added, the Javascript isn't re-initialized for the added elements.

Here is the code in question:

```<code><script type="text/javascript">
$(document).ready(function(){
    var i=1;
    $("#add_row").click(function(){
        $('#addr'+i).html("<div id='addr" + i + "'>" +
            "<div class='col-xs-4'>" +
            "<input type='text' name='config_color[" + i + "][css]' id='input-color[" + i + "][css]' class='form-control' />" +
            "</div>" +
            "<div class='col-xs-2'>" +
            "<input type='text' name='config_color[" + i + "][value]' id='input-color[" + i + "][value]' class='form-control jscolor' />" +
            "</div>" +
            "<div class='col-xs-2'>" +
            "<input type='text' name='config_color[" + i + "][default]' id='input-color[" + i + "][default]' class='form-control' />" +
            "</div>" +
            "<div class='col-xs-4'>" +
            "<input type='text' name='config_color[" + i + "][notes]' id='input-color[" + i + "][notes]' class='form-control' />" +
            "</div>" +
            "</div>");

        $('#tab_logic').append('<div id="addr'+(i+1)+'"></div>');
        i++;
    });
    $("#delete_row").click(function(){
        if(i>1){
            $("#addr"+(i-1)).html('');
            i--;
        }
    });
}).trigger('change');
</script>
</code>```

I've made an simplified example of what I'm talking about on JSFiddle - you can see in the first row, if you click in the color cell, it gives you a pop up color palette.

If you add additional rows, the popup picker doesn't work.

However, all of the data stores in the database properly, so i have an instance where some elements added by Javascript work properly and others don't?

(Also full disclosure, I asked on Reddit first - this is therefore a cross-post.

答:
In their examples, jscolor has one called "Instantiating new Color Pickers" which shows you how to do it.

You're adding the new row as a string, which I wouldn't recommend, because if you created each input separately using jQuery it would be easier to call jscolor() on only one element, but this works too.

Just add the following to your click handler:

```<code>// Get all the inputs first
var allInputs = $('.jscolor');

// From there, get the newest one
var newestInput = allInputs[allInputs.length - 1];

// And call jscolor() on it!
new jscolor(newestInput);
</code>```

Here's an updated fiddle

Body:
I have a document that uses the jscolor.com library, for the user to be able to select and store a color. I'm also using a JQuery function to add rows to the screen, so the user can create and define a number of colors. The problem is, when the new row is added, the Javascript isn't re-initialized for the added elements.

Here is the code in question:

I've made an simplified example of what I'm talking about on JSFiddle - you can see in the first row, if you click in the color cell, it gives you a pop up color palette.

If you add additional rows, the popup picker doesn't work.

However, all of the data stores in the database properly, so i have an instance where some elements added by Javascript work properly and others don't?

(Also full disclosure, I asked on Reddit first - this is therefore a cross-post.

Body:
In their examples, jscolor has one called "Instantiating new Color Pickers" which shows you how to do it.

You're adding the new row as a string, which I wouldn't recommend, because if you created each input separately using jQuery it would be easier to call jscolor() on only one element, but this works too.

Just add the following to your click handler:

// Get all the inputs first
var allInputs = $('.jscolor');

// From there, get the newest one
var newestInput = allInputs[allInputs.length - 1];

// And call jscolor() on it!
new jscolor(newestInput);

Here's an updated fiddle


问:
Java's HttpURLConnection doesn't support REPORT/PROPFIND - what shall I do?
HttpURLConnection does only support things like GET, POST and HEAD - but no REPORT/PROPFIND. I'm going to implement a CalDAV-Client but without theese operations (if I want to use them I get a ProtocolException) I have to write/deliver a complete and huge HTTP library with auth and so on.

"Overkill".

How do I send requests with PROPFIND and REPORT?

答:
```<code>private static void setRequestMethod(HttpURLConnection conn, String method) throws Throwable {
    try {
        conn.setRequestMethod(method);
    } catch (ProtocolException e) {
        Class<?> c = conn.getClass();
        Field methodField = null;
        Field delegateField = null;
        try {
            delegateField = c.getDeclaredField("delegate");
        } catch (NoSuchFieldException nsfe) {

        }
        while (c != null && methodField == null) {
            try {
                methodField = c.getDeclaredField("method");
            } catch (NoSuchFieldException nsfe) {

            }
            if (methodField == null) {
                c = c.getSuperclass();
            }
        }
        if (methodField != null) {
            methodField.setAccessible(true);
            methodField.set(conn, method);
        }

        if (delegateField != null) {
            delegateField.setAccessible(true);
            HttpURLConnection delegate = (HttpURLConnection) delegateField.get(conn);
            setRequestMethod(delegate, method);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 2.5


问:
Border-radius breaks aesthetically when applied.. Bug?
I have a small form that has a button at the end.

Without border-radius it looks like this --> https://s29.postimg.org/3yw0js3qf/screenshot--2017-04-02-20-18-33.png

When I apply border-radius it looks like this --> https://s11.postimg.org/t25tmdsf7/screenshot--2017-04-02-20-19-12.png

I'm working on Chrome, Windows OS. I've tried using web-kit just in case, with the same results.. Has this ever happened to anyone else?

Here's that bit of code in case there's anything I haven't seen there:

```<code>HTML
<div id="boton">
    <button type="button" class="texto">INGRESAR</button>
</div>

CSS
#boton{
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
width: 100%;
margin: auto;
margin-top: 2%;
}

#boton>button{
width: 20%;
padding: 10px;
}
</code>```

Thanks!

答:
You will need to replicate the default style with the border and background gradient:

```<code>border-radius: 4px;
border: 1px solid #AFAFAF;
background: linear-gradient(#E3E3E3, #F7F7F7);
</code>```

see fiddle: https://jsfiddle.net/1gxkyq9c/

Body:
I have a small form that has a button at the end.

Without border-radius it looks like this --> https://s29.postimg.org/3yw0js3qf/screenshot--2017-04-02-20-18-33.png

When I apply border-radius it looks like this --> https://s11.postimg.org/t25tmdsf7/screenshot--2017-04-02-20-19-12.png

I'm working on Chrome, Windows OS. I've tried using web-kit just in case, with the same results.. Has this ever happened to anyone else?

Here's that bit of code in case there's anything I haven't seen there:

HTML

    <button type="button" class="texto">INGRESAR</button>

CSS
#boton{
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
width: 100%;
margin: auto;
margin-top: 2%;
}

#boton>button{
width: 20%;
padding: 10px;
}

Thanks!

Body:
You will need to replicate the default style with the border and background gradient:

border-radius: 4px;
border: 1px solid #AFAFAF;
background: linear-gradient(#E3E3E3, #F7F7F7);

see fiddle: https://jsfiddle.net/1gxkyq9c/


问:
Returning the Key in a Map<String,List<Pair<Integer,String>>>
I have defined a collection using the type TreeMap< String, List < Pair < Integer, String >>> in which pair is a class that I defined: </p>

```<code>public class Pair<L,R> {
    private L l;
    private R r;
    public Pair(L l, R r) {
        this.l = l;
        this.r = r;
    }
public L getL() {return l;}
public R getR() {return r;}
public void setL(L l){this.l = l;}
public void setR(R r){this.r = r;}

}
</code>```

<p>I want to return the string (TreeMap key) that is paired with a list that contains a given String value. For example, I have a String "bob" that is stored in one of the pairs in the list, and I want to return the key (string) of the Treemap that is associated with that list of pairs that "bob" is in. How would I go about doing this? </p>

答:
I would create predicates, working from inside out.  I hope you can follow the logic.  This will find the first List that has "Bob" and get that key.</p>

```<code>Predicate<Pair<Integer, String>> pairHasBobPred = pair -> ((String) pair.getR()).equals("Bob");

Predicate<String> keyHasBobPred = key -> myTree.get(key).stream()
                                                    .anyMatch(pairHasBobPred::test);

String keyWithBob =  myTree.keySet().stream()
                                    .filter(keyHasBobPred::test)
                                    .findFirst()
                                    .get();
</code>```

Body:
I have defined a collection using the type TreeMap< String, List < Pair < Integer, String >>> in which pair is a class that I defined:

public class Pair<L,R> {
    private L l;
    private R r;
    public Pair(L l, R r) {
        this.l = l;
        this.r = r;
    }
public L getL() {return l;}
public R getR() {return r;}
public void setL(L l){this.l = l;}
public void setR(R r){this.r = r;}

}

I want to return the string (TreeMap key) that is paired with a list that contains a given String value. For example, I have a String "bob" that is stored in one of the pairs in the list, and I want to return the key (string) of the Treemap that is associated with that list of pairs that "bob" is in. How would I go about doing this?

Body:
I would create predicates, working from inside out.  I hope you can follow the logic.  This will find the first List that has "Bob" and get that key.

Predicate<Pair<Integer, String>> pairHasBobPred = pair -> ((String) pair.getR()).equals("Bob");

Predicate<String> keyHasBobPred = key -> myTree.get(key).stream()
                                                    .anyMatch(pairHasBobPred::test);

String keyWithBob =  myTree.keySet().stream()
                                    .filter(keyHasBobPred::test)
                                    .findFirst()
                                    .get();


问:
Compilation errors in simple Java program with Scanner
```<code>import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}
</code>```

<p>I dont know why im getting 2 errors on strings cannot converted to int. </p>

答:
Try using

```<code>keyboard.nextInt();
</code>```

not

```<code>keyboard.next();
</code>```

it displays that it cannot convert because .next is for strings, but for other data types is .next and then the data types with a capital. For example:

```<code>long l=keyboard.nextLong();
</code>```

and boolean b=keyboard.nextBoolean();

Body:
import java.util.*;
public class strings {
    public static void main (String [] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Type your first integer: ");
        int first = keyboard.next();
        System.out.print("Type your seconds integer : ");
        int second = keyboard.next();
        System.out.print("The sum of your two integers are:");
    }
}

I dont know why im getting 2 errors on strings cannot converted to int.

Body:
Try using

keyboard.nextInt();

not

keyboard.next();

it displays that it cannot convert because .next is for strings, but for other data types is .next and then the data types with a capital. For example:

long l=keyboard.nextLong();

and boolean b=keyboard.nextBoolean();


问:
Modify the content of a dataframe in R
I would like to transform/modify the content of dataframe. Basically I have a dataframe like below:

```<code>        bins      pval
1   2L:1:150 0.9224217
2 2L:151:300 0.9478824
3 2L:301:450 0.9671139
4 2L:451:600 0.9280847
5 2L:601:750 0.9698584
6 2L:751:900 0.9725379
</code>```

And I would like to transform/modify into another dataframe like this, where I split the content of my "bins" column (first row) into 150 rows containing the same values. And so on for the second row.

```<code>    chr  pos    pval
1   2L   1 0.9224217
2   2L   2 0.9224217
3   2L   3 0.9224217
4   2L   4 0.9224217
5   2L   5 0.9224217
...
150  2L   150 0.9224217
151  2L   151 0.9478824
152  2L   152 0.9478824
153  2L   153 0.9478824
etc...
</code>```

Any help much appreciated,

Ben

答:
The quick answer which may be, I fear, too specific and may need generalization. Assume the first dataframe is named "df1":

data.frame(chr="2L", pos=1:(150*NROW(df1)), pval=rep(df1$pval, each=150) )

Argument recycling should make the "chr" long enough without a rep function.

Edit in reply to comment. If the repeat length is always 150 then the fix is easy:

```<code>data.frame(chr = rep(substr(df1$bins, 1,2), each=150),
           pos = 1:(150*NROW(df1)),
           pval = rep(df1$pval, each=150) )
</code>```

Title: Modify the content of a dataframe in R

Body:
I would like to transform/modify the content of dataframe. Basically I have a dataframe like below:

        bins      pval
1   2L:1:150 0.9224217
2 2L:151:300 0.9478824
3 2L:301:450 0.9671139
4 2L:451:600 0.9280847
5 2L:601:750 0.9698584
6 2L:751:900 0.9725379

And I would like to transform/modify into another dataframe like this, where I split the content of my "bins" column (first row) into 150 rows containing the same values. And so on for the second row.

    chr  pos    pval
1   2L   1 0.9224217
2   2L   2 0.9224217
3   2L   3 0.9224217
4   2L   4 0.9224217
5   2L   5 0.9224217
...
150  2L   150 0.9224217
151  2L   151 0.9478824
152  2L   152 0.9478824
153  2L   153 0.9478824
etc...

Any help much appreciated,

Ben

Body:
The quick answer which may be, I fear, too specific and may need generalization. Assume the first dataframe is named "df1":

data.frame(chr="2L", pos=1:(150*NROW(df1)), pval=rep(df1$pval, each=150) )

Argument recycling should make the "chr" long enough without a rep function.

Edit in reply to comment. If the repeat length is always 150 then the fix is easy:

data.frame(chr = rep(substr(df1$bins, 1,2), each=150),
           pos = 1:(150*NROW(df1)),
           pval = rep(df1$pval, each=150) )


问:
Dynamically Set View Title
Not even sure if I asked the question the right way.  Been looking at this for about an hour and its too simple to take to long.  Trouble is I am too simple to know the answer or even how to correctly phrase a search to find the answer.

I have a history of jobs completed for a site set up.

Controller:

```<code>public async Task<IActionResult> JobSiteHistory(int id, int? page)
{
    var jobs = from j in _context.Job
        .Include(j => j.Site)
        .Include(j=>j.WaterBody)
        .Where(j=>j.Site.SiteID==id)
        .OrderByDescending(j=>j.BookingDate)
        select j;
    int pageSize = 9;
    return View(await PaginatedList<Job>.CreateAsync(jobs.AsNoTracking(), page ?? 1, pageSize));
}
</code>```

This is returning the correct records all good.

I then have a view set up:

```<code><h2> Site Jobs History</h2>

<p>
<a asp-action="Create">Add New Job</a>
</p>

<table class="table">
<thead>
    <tr>
        <th>Booking Date</th>
        <th>Job Number</th>
        <th>Waterbody</th>
        <th>Job Description</th>
        <th></th>
    </tr>
</thead>
<tbody>
@foreach (var item in Model) {
    <tr>
        <td>@Html.DisplayFor(modelItem => item.BookingDate)</td>
        <td>@Html.DisplayFor(modelItem => item.JobNumber)</td>
        <td>@Html.DisplayFor(modelItem => item.WaterBody.WBName)</td>
        <td>@item.JobDescription.Substring(0, Math.Min(item.JobDescription.Length, 30))</td>
        <td>
            <a asp-action="Edit" asp-route-id="@item.JobID">Edit</a> |
            <a asp-action="Details" asp-route-id="@item.JobID">Details</a> |
            <a asp-action="Delete" asp-route-id="@item.JobID">Delete</a> |
        </td>
    </tr>
  }
</tbody>
</table>
</code>```

This is working wellish so far.

All I want to do is add something like:

```<code>@Html.DisplayFor(ModelItem=>item.Site.SiteName)
</code>```

To the
 element.  I know this wont work as typed, thanks for thinking that.

I just cant see a way to add it.  I considered ViewData, but may be using it wrong as I cant get it to populate with SiteName.

Is there a way to do this or am I thinking all ass about as usual?

答:
The easiest change would be to use this:

```<code><h2>@Html.DisplayFor(m => m[0].Site.SiteName);</h2>
</code>```

Other options:

Is there any reason why you can't use the ViewBag?
In controller:

```<code>ViewBag.SiteName = Site.name
</code>```

In view:

```<code><h2>@ViewBag.SiteName</h2>
</code>```

If you must use your model to pass the whole site object then change your view model that you pass to the view.

You are currently returning a list of jobs with the site object for each job, but it looks like you only need it once.

I would change your view model to be something like:

```<code>public class SiteJobsHistoryModel
{
    public Site Site { get; set;}
    public PaginatedList<Job> Jobs { get; set; }
}
</code>```

Then you don't have to include the site on your query, and just retrieve it once from the database:

```<code>var site = _context.Site.Single(j => j.Site.SiteID==id);
var jobs = from j in _context.Job
    //.Include(j => j.Site) -- this can be removed
    .Include(j=>j.WaterBody)
    .Where(j=>j.Site.SiteID==id)
    .OrderByDescending(j=>j.BookingDate)
    select j;

return View(new SiteJobsHistoryModel
    {
        Site = site,
        Jobs = await PaginatedList<Job>.CreateAsync(jobs.AsNoTracking(), page ?? 1, pageSize)
    });
</code>```

Then for the title in
 tag you can use:

```<code>@Html.DisplayFor(ModelItem=>model.Site.SiteName)
</code>```

And your foreach loop becomes:

```<code>@foreach (var item in Model.Jobs)
</code>```

Title: Dynamically Set View Title

Body:
Not even sure if I asked the question the right way.  Been looking at this for about an hour and its too simple to take to long.  Trouble is I am too simple to know the answer or even how to correctly phrase a search to find the answer.

I have a history of jobs completed for a site set up.

Controller:

public async Task<IActionResult> JobSiteHistory(int id, int? page)
{
    var jobs = from j in _context.Job
        .Include(j => j.Site)
        .Include(j=>j.WaterBody)
        .Where(j=>j.Site.SiteID==id)
        .OrderByDescending(j=>j.BookingDate)
        select j;
    int pageSize = 9;
    return View(await PaginatedList<Job>.CreateAsync(jobs.AsNoTracking(), page ?? 1, pageSize));
}

This is returning the correct records all good.

I then have a view set up:

 Site Jobs History

Add New Job

        Booking Date
        Job Number
        Waterbody
        Job Description

@foreach (var item in Model) {

        @Html.DisplayFor(modelItem => item.BookingDate)
        @Html.DisplayFor(modelItem => item.JobNumber)
        @Html.DisplayFor(modelItem => item.WaterBody.WBName)
        @item.JobDescription.Substring(0, Math.Min(item.JobDescription.Length, 30))

            Edit |
            Details |
            Delete |

  }

This is working wellish so far.

All I want to do is add something like:

@Html.DisplayFor(ModelItem=>item.Site.SiteName)

To the
 element.  I know this wont work as typed, thanks for thinking that.

I just cant see a way to add it.  I considered ViewData, but may be using it wrong as I cant get it to populate with SiteName.

Is there a way to do this or am I thinking all ass about as usual?

Body:
The easiest change would be to use this:

<h2>@Html.DisplayFor(m => m[0].Site.SiteName);</h2>

Other options:

Is there any reason why you can't use the ViewBag?
In controller:

ViewBag.SiteName = Site.name

In view:

<h2>@ViewBag.SiteName</h2>

If you must use your model to pass the whole site object then change your view model that you pass to the view.

You are currently returning a list of jobs with the site object for each job, but it looks like you only need it once.

I would change your view model to be something like:

public class SiteJobsHistoryModel
{
    public Site Site { get; set;}
    public PaginatedList<Job> Jobs { get; set; }
}

Then you don't have to include the site on your query, and just retrieve it once from the database:

var site = _context.Site.Single(j => j.Site.SiteID==id);
var jobs = from j in _context.Job
    //.Include(j => j.Site) -- this can be removed
    .Include(j=>j.WaterBody)
    .Where(j=>j.Site.SiteID==id)
    .OrderByDescending(j=>j.BookingDate)
    select j;

return View(new SiteJobsHistoryModel
    {
        Site = site,
        Jobs = await PaginatedList<Job>.CreateAsync(jobs.AsNoTracking(), page ?? 1, pageSize)
    });

Then for the title in <h2> tag you can use:

@Html.DisplayFor(ModelItem=>model.Site.SiteName)

And your foreach loop becomes:

@foreach (var item in Model.Jobs)


问:
DocumentDB how to get documents which matches the most number of items from a given array
I have a collection with documents like this:

```<code>{
   "User": { _id: 1, UserName: "username", DisplayName: "DisplayName" },
   "Interests": [1, 4, 7, 25, 30, 34, 46],
   "MinAge": 11,
   "Title": "ad title",
   ...
}
</code>```

I want to select the 10 documents which matches the most number of interests from a given array, like:

```<code>array = [1,7, 30, 33, 38, 46, 55];
</code>```

How could I do that?

答:
It would not use an index and thus be a full table scan but the only way I can think to do it is with either a stored procedure or a UDF.

In either case, you'd first need a count of the number that intersect. I suggest you do this by first calculating the intersection array and then taking the length of that. Here is an SO answer with javascript code for calculating array intersection.

If you put that in a UDF named intersectionCount(), you can then use it to return all the rows with the count:

```<code>SELECT c.id, intersectionCount(c.Interests, [1, 7, 30, 33, 38, 46, 55]) AS intersectionCount FROM c ...
</code>```

Then on the client side, you can sort by intersectionCount and take the top 10. Alternatively, you could get the top 10 by using a TOP clause in your SQL but that would not allow you to deal with ties. For instance, what if there are 15 records that have the same number of intersections? One strategy would be to return all 15 eventhough it's more than your desired 10. Another would be to truncate the list. And another strategy would be to use some other criteria to pick the top 10.

To do it in a stored procedure, you'd have to include that function in your stored procedure. You'd then read all the records in batches in your stored procedure, calculate the count by calling the function, and then keeping the top 10. Again, you might want to deal with ties.

Body:
I have a collection with documents like this:

{
   "User": { _id: 1, UserName: "username", DisplayName: "DisplayName" },
   "Interests": [1, 4, 7, 25, 30, 34, 46],
   "MinAge": 11,
   "Title": "ad title",
   ...
}

I want to select the 10 documents which matches the most number of interests from a given array, like:

array = [1,7, 30, 33, 38, 46, 55];

How could I do that?

Body:
It would not use an index and thus be a full table scan but the only way I can think to do it is with either a stored procedure or a UDF.

In either case, you'd first need a count of the number that intersect. I suggest you do this by first calculating the intersection array and then taking the length of that. Here is an SO answer with javascript code for calculating array intersection.

If you put that in a UDF named intersectionCount(), you can then use it to return all the rows with the count:

SELECT c.id, intersectionCount(c.Interests, [1, 7, 30, 33, 38, 46, 55]) AS intersectionCount FROM c ...

Then on the client side, you can sort by intersectionCount and take the top 10. Alternatively, you could get the top 10 by using a TOP clause in your SQL but that would not allow you to deal with ties. For instance, what if there are 15 records that have the same number of intersections? One strategy would be to return all 15 eventhough it's more than your desired 10. Another would be to truncate the list. And another strategy would be to use some other criteria to pick the top 10.

To do it in a stored procedure, you'd have to include that function in your stored procedure. You'd then read all the records in batches in your stored procedure, calculate the count by calling the function, and then keeping the top 10. Again, you might want to deal with ties.


问:
How to install new module/package in python coding online environment?
I want to install third party package in python online coding environments. Could you please tell me how we can achieve this?

The below line needs to execute
from watson_developer_cloud import SpeechToTestV1 as STT
when I run the above line, I am getting the following error,

Error:
Traceback (most recent call last):
  File "..\Playground\", line 1, in
    \ufefffrom watson_developer_cloud import SpeechToTestV1 as STT
ImportError: No module named 'watson_developer_cloud'

Even tried the below command in CODE Playground but it throwing incorrect syntax.
pip install watson_developer_cloud

Thanks in advance,

答:
You can install packages when using SoloLearn. You need to ask SoloLearn's administrators to install the package for you.

The python playground includes some of the most popular packages but it's very limited in terms of what you can do if the package you want to use is not there.


问:
What is this called in C#?
```<code>Book x = new Book(){
              Author = "Rowling",
              Title = "Harry Potter",
              Genre = Genres.Fantasy
              };
</code>```

I've tried googling for Inline declaration, but I guess thats not what it's officially called.

Thoughts?

答:
This in itself appears to be illegal code.  It's very close to an object initializer but that would require the member being set to be paired with the value it was set to.  For example

```<code>Book x = new Book() {
  Author = "Rowling",
  Title = "Harry Potter",
  Category = Geners.Fantasy };
</code>```

EDIT OP corrected the question to now have the correct object initializer syntax.

OwnerDisplayName: delete

LastEditorDisplayName: delete

Title: What is this called in C#?

Body:
Book x = new Book(){
              Author = "Rowling",
              Title = "Harry Potter",
              Genre = Genres.Fantasy
              };

I've tried googling for Inline declaration, but I guess thats not what it's officially called.

Thoughts?

Body:
This in itself appears to be illegal code.  It's very close to an object initializer but that would require the member being set to be paired with the value it was set to.  For example

Book x = new Book() {
  Author = "Rowling",
  Title = "Harry Potter",
  Category = Geners.Fantasy };

EDIT OP corrected the question to now have the correct object initializer syntax.


问:
Erlang newbie - concurrency and message passing
I'm still new to programming and brand new erlang (2 week newbie!). I edited slightly so atleast it'll compile and run. But I still can't figure out the concept of sending the results to a "joiner process" to join all the seperate results.

It does split and send the "chunks" an received to count the chunks. Just don't know how to get all those processes to join their individual results. I sort of understand the concept below, but have no idea how that's implimented. I've been trying for many days and hours to get it to this point, but can't get it to do anything without getting errors or unbound variables, etc.

```<code>-module (ccharcount1d).
-compile(export_all).

load(F)->
 {ok, Bin} = file:read_file(F),
  List=binary_to_list(Bin),
  Ls=string:to_lower(List),
  Length=round(length(List)/20),
  Collect_Results = spawn(ccharcount1d, collect_results, []),

  Sl=split(Ls,Length),

  io:fwrite("Loaded, Split, and sent to multiple processes~n").

%%splits txt file into "chunks" and sends those "chunks" to be processed
split([],_)->[];
split(List,Length)->
S1=string:substr(List,1,Length),
case length(List) > Length of
   true->S2=string:substr(List,Length+1,length(List)),
   Process_Split = spawn(ccharcount1d,receive_splits,[]),
   Process_Split ! {self(), S1};

   false->S2=[],
   Process_Split = spawn(ccharcount1d,receive_splits,[]),
   Process_Split ! {self(), S1}

 end,

[S1]++split(S2,Length).

%%recieves the split "chunks" and counts the results
receive_splits()->
    receive
        {From, S1} ->
            Result=go(S1)
            %Collect_Results ! Result
    end.

collect_results()->
    receive
        {Process_Split, Result} ->
            Result=join([],Result)
    end.

join([],[])->[];
join([],R)->R;
join([H1 |T1],[H2|T2])->
{C,N}=H1,
{C1,N1}=H2,
[{C1,N+N1}]++join(T1,T2).

count(Ch, [],N)->N;
count(Ch, [H|T],N) ->
   case Ch==H of
   true-> count(Ch,T,N+1);
   false -> count(Ch,T,N)
end.

go(L)->
Alph=[$a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l,$m,$n,$o,$p,$q,$r,$s,$t,$u,$v,$w,$x,$y,$z],
rgo(Alph,L,[]).

rgo([H|T],L,Result)->
N=count(H,L,0),
Result2=Result++[{[H],N}],
rgo(T,L,Result2);

rgo([],L,Result)-> Result.
</code>```

答:
again, i'm new. I'm understanding the concept. I'm not understanding
  the syntax. the how to "pass a Pid to a worker process"

```<code>start() ->
    Work = ...,
    JoinPid = spawn(fun() -> join_func([]) end),
    WorkerPid = spawn(fun() -> worker_func(JoinPid, Work) end),  %Pass JoinPid to worker process.
    ...

join_func(Acc) ->
    receive
        Result ->
            join_func([Result|Acc]);  %Recursive function call--the life blood of all functional languages.

        ...
    end

worker_func(JoinPid, Work) ->
    Result = ... Work ...,
    JoinPid ! Result.  %Worker process uses JoinPid to send back the results.
</code>```

Also, check out this:

```<code>8> [$a, $b, $c].
"abc"

9> "abc".
"abc"
</code>```

The output shows that [$a, $b, $c] is equivalent to "abc".  That means you can write this:

```<code>[$a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l,$m,$n,$o,$p,$q,$r,$s,$t,$u,$v,$w,$x,$y,$z]
</code>```

much more succinctly like this:

```<code>"abcdefghijklmnopqrstuvwxyz"
</code>```

and even more so, like this:

```<code>11> lists:seq(97, 122).
"abcdefghijklmnopqrstuvwxyz"
</code>```

Body:
I'm still new to programming and brand new erlang (2 week newbie!). I edited slightly so atleast it'll compile and run. But I still can't figure out the concept of sending the results to a "joiner process" to join all the seperate results.

It does split and send the "chunks" an received to count the chunks. Just don't know how to get all those processes to join their individual results. I sort of understand the concept below, but have no idea how that's implimented. I've been trying for many days and hours to get it to this point, but can't get it to do anything without getting errors or unbound variables, etc.

-module (ccharcount1d).
-compile(export_all).

load(F)->
 {ok, Bin} = file:read_file(F),
  List=binary_to_list(Bin),
  Ls=string:to_lower(List),
  Length=round(length(List)/20),
  Collect_Results = spawn(ccharcount1d, collect_results, []),

  Sl=split(Ls,Length),

  io:fwrite("Loaded, Split, and sent to multiple processes~n").

%%splits txt file into "chunks" and sends those "chunks" to be processed
split([],_)->[];
split(List,Length)->
S1=string:substr(List,1,Length),
case length(List) > Length of
   true->S2=string:substr(List,Length+1,length(List)),
   Process_Split = spawn(ccharcount1d,receive_splits,[]),
   Process_Split ! {self(), S1};

   false->S2=[],
   Process_Split = spawn(ccharcount1d,receive_splits,[]),
   Process_Split ! {self(), S1}

 end,

[S1]++split(S2,Length).

%%recieves the split "chunks" and counts the results
receive_splits()->
    receive
        {From, S1} ->
            Result=go(S1)
            %Collect_Results ! Result
    end.

collect_results()->
    receive
        {Process_Split, Result} ->
            Result=join([],Result)
    end.

join([],[])->[];
join([],R)->R;
join([H1 |T1],[H2|T2])->
{C,N}=H1,
{C1,N1}=H2,
[{C1,N+N1}]++join(T1,T2).

count(Ch, [],N)->N;
count(Ch, [H|T],N) ->
   case Ch==H of
   true-> count(Ch,T,N+1);
   false -> count(Ch,T,N)
end.

go(L)->
Alph=[$a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l,$m,$n,$o,$p,$q,$r,$s,$t,$u,$v,$w,$x,$y,$z],
rgo(Alph,L,[]).

rgo([H|T],L,Result)->
N=count(H,L,0),
Result2=Result++[{[H],N}],
rgo(T,L,Result2);

rgo([],L,Result)-> Result.

Body:
again, i'm new. I'm understanding the concept. I'm not understanding
  the syntax. the how to "pass a Pid to a worker process"

start() ->
    Work = ...,
    JoinPid = spawn(fun() -> join_func([]) end),
    WorkerPid = spawn(fun() -> worker_func(JoinPid, Work) end),  %Pass JoinPid to worker process.
    ...

join_func(Acc) ->
    receive
        Result ->
            join_func([Result|Acc]);  %Recursive function call--the life blood of all functional languages.

        ...
    end

worker_func(JoinPid, Work) ->
    Result = ... Work ...,
    JoinPid ! Result.  %Worker process uses JoinPid to send back the results.

Also, check out this:

8> [$a, $b, $c].
"abc"

9> "abc".
"abc"

The output shows that [$a, $b, $c] is equivalent to "abc".  That means you can write this:

[$a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l,$m,$n,$o,$p,$q,$r,$s,$t,$u,$v,$w,$x,$y,$z]

much more succinctly like this:

"abcdefghijklmnopqrstuvwxyz"

and even more so, like this:

11> lists:seq(97, 122).
"abcdefghijklmnopqrstuvwxyz"


问:
OS X Lion, Attempting Nokogiri install - libxml2 is missing
```<code>sudo gem install nokogiri
Building native extensions.  This could take a while...
ERROR:  Error installing nokogiri:
    ERROR: Failed to build gem native extension.

        /Users/sajeev86/.rvm/rubies/ruby-1.8.7-p352/bin/ruby extconf.rb
checking for libxml/parser.h... no
-----
libxml2 is missing.  please visit http://nokogiri.org/tutorials/installing_nokogiri.html for help with installing dependencies.
-----
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.
</code>```

I can't get Nokogiri to install. This has been taxing me for a while now. I've installed the dependencies via MacPorts and Homebrew as well.

I've got a feeling the right directories are not pointed to each other? But haven't a clue how to fix.

答:
For me, I simply did the following

```<code>xcode-select --install
gem install nokogiri
</code>```

For more in-depth troubleshooting, checkout Installing Nokogiri

Body:
sudo gem install nokogiri
Building native extensions.  This could take a while...
ERROR:  Error installing nokogiri:
    ERROR: Failed to build gem native extension.

        /Users/sajeev86/.rvm/rubies/ruby-1.8.7-p352/bin/ruby extconf.rb
checking for libxml/parser.h... no
-----
libxml2 is missing.  please visit http://nokogiri.org/tutorials/installing_nokogiri.html for help with installing dependencies.
-----
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

I can't get Nokogiri to install. This has been taxing me for a while now. I've installed the dependencies via MacPorts and Homebrew as well.

I've got a feeling the right directories are not pointed to each other? But haven't a clue how to fix.

Body:
For me, I simply did the following

xcode-select --install
gem install nokogiri

For more in-depth troubleshooting, checkout Installing Nokogiri


问:
How to take url output(JSON) as Java Variable
I am trying to use the value of rate in the below JSON object as my variable.

URL is : http://rate-exchange-1.appspot.com/currency?from=USD&to=INR

Output of above URL is like " {"to": "INR", "rate": 64.806700000000006, "from": "USD"}  ". I am assuming it as JSON object. how to get the value of 64, shall i get it by parsing?

答:
There're many options to deserialize JSON as mentioned in other answers, most of the time it would be better to define a corresponding Java class and then do serialization/deserialization. One example implementation with Gson would be:

```<code>public class Main {
    public static void main(String[] args) {
        Gson gson = new Gson();
        String jsonString = "{\"to\": \"INR\", \"rate\": 64.806700000000006, \"from\": \"USD\"}";
        CurrencyRate currencyRate = gson.fromJson(jsonString, CurrencyRate.class);
    }

    class CurrencyRate {
        private String from;
        private String to;
        private BigDecimal rate;

        public String getFrom() {
            return from;
        }

        public void setFrom(String from) {
            this.from = from;
        }

        public String getTo() {
            return to;
        }

        public void setTo(String to) {
            this.to = to;
        }

        public BigDecimal getRate() {
            return rate;
        }

        public void setRate(BigDecimal rate) {
            this.rate = rate;
        }
    }
}
</code>```

And Gson is Thread Safe, so it's OK to init only one Gson instance and share it among all threads.

Body:
There're many options to deserialize JSON as mentioned in other answers, most of the time it would be better to define a corresponding Java class and then do serialization/deserialization. One example implementation with Gson would be:

public class Main {
    public static void main(String[] args) {
        Gson gson = new Gson();
        String jsonString = "{\"to\": \"INR\", \"rate\": 64.806700000000006, \"from\": \"USD\"}";
        CurrencyRate currencyRate = gson.fromJson(jsonString, CurrencyRate.class);
    }

    class CurrencyRate {
        private String from;
        private String to;
        private BigDecimal rate;

        public String getFrom() {
            return from;
        }

        public void setFrom(String from) {
            this.from = from;
        }

        public String getTo() {
            return to;
        }

        public void setTo(String to) {
            this.to = to;
        }

        public BigDecimal getRate() {
            return rate;
        }

        public void setRate(BigDecimal rate) {
            this.rate = rate;
        }
    }
}

And Gson is Thread Safe, so it's OK to init only one Gson instance and share it among all threads.


问:
ExpressJS and Angular 1 routing
Im trying to use Express to create a API and Angular for front-end of my page but  Im unable to correctly route my pages. can somebody see my code and tell me what am I missing or doing wrong ?
The error Im getting is 404 everytime I go try to go to /about it seems that it defaults to index.html
 here is my code:

//SERVER.JS

var express = require("express");
var app = express();
var PORT = process.env.PORT || 3001;
var path = require('path');
var router = express.Router();

app.use(express.static(__dirname + '/public'));

app.listen(PORT, function () {
    console.log("Server running in PORT " + PORT);
});```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//MAIN.JS

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

console.log("in myApp module");

myApp.config(['$routeProvider','$locationProvider',function ($routeProvider,$locationProvider) {

    console.log("in app.config")

$routeProvider
    .when('/',{
       templateUrl:'../index.html',
    })
    .when('about',{
        templateUrl:"<h1>Banana</h1><p>Bananas contain around 75% water.</p>",
        controller:'AboutController'
    });

    console.log('after provider');
$locationProvider.html5Mode(true);

}]);</code>```

<!DOCTYPE html >

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Morand Transportation</title>
    <link href="css/reset.css" rel="stylesheet">

    <link rel="stylesheet" href="./lib/bootstrap/css/bootstrap.min.css">

    <link href="css/style.css" rel="stylesheet">

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        Toggle navigation Menu
                    </button>
                    Home

                            Services

                            About

                            Team

                            Contact

                        Morand Trasnportation

    footer

```

答:
probably you've made 2 mistakes:

```<code>.when('/about',{ //should have a slash
    templateUrl:"<h1>Banana</h1><p>Bananas contain around 75% water.</p>",
    // this is not a templateUrl
    controller:'AboutController'
});
</code>```

should be like this instead:

```<code>template:"<h1>Banana</h1><p>Bananas contain around 75% water.</p>",
</code>```

i also suggest using this awesome ui-router router with angular ;)

Title: ExpressJS and Angular 1 routing

Body:
Im trying to use Express to create a API and Angular for front-end of my page but  Im unable to correctly route my pages. can somebody see my code and tell me what am I missing or doing wrong ?
The error Im getting is 404 everytime I go try to go to /about it seems that it defaults to index.html
 here is my code:

//SERVER.JS

var express = require("express");
var app = express();
var PORT = process.env.PORT || 3001;
var path = require('path');
var router = express.Router();

app.use(express.static(__dirname + '/public'));

app.listen(PORT, function () {
    console.log("Server running in PORT " + PORT);
});

//MAIN.JS

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

console.log("in myApp module");

myApp.config(['$routeProvider','$locationProvider',function ($routeProvider,$locationProvider) {

    console.log("in app.config")

$routeProvider
    .when('/',{
       templateUrl:'../index.html',
    })
    .when('about',{
        templateUrl:"
Banana

Bananas contain around 75% water.
",
        controller:'AboutController'
    });

    console.log('after provider');
$locationProvider.html5Mode(true);

}]);

<!DOCTYPE html >

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Morand Transportation</title>
    <link href="css/reset.css" rel="stylesheet">

    <link rel="stylesheet" href="./lib/bootstrap/css/bootstrap.min.css">

    <link href="css/style.css" rel="stylesheet">

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                        Toggle navigation Menu
                    </button>
                    Home

                            Services

                            About

                            Team

                            Contact

                        Morand Trasnportation

    footer

Body:
probably you've made 2 mistakes:

.when('/about',{ //should have a slash
    templateUrl:"<h1>Banana</h1><p>Bananas contain around 75% water.</p>",
    // this is not a templateUrl
    controller:'AboutController'
});

should be like this instead:

template:"<h1>Banana</h1><p>Bananas contain around 75% water.</p>",

i also suggest using this awesome ui-router router with angular ;)


答:
You could try this one bro. Just click the demo to see the result. Hope this answer yours.

#boton {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  width: 100%;
  margin: auto;
  margin-top: 2%;
}

#boton > button {
  width: 20%;
  padding: 10px;
  border-radius: 7px;
  background: #F8F9F9;
  color: grey;
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="boton">
    <button type="button" class="texto">INGRESAR</button>
</div></code>```

Title: Border-radius breaks aesthetically when applied.. Bug?

Body:
I have a small form that has a button at the end.

Without border-radius it looks like this --> https://s29.postimg.org/3yw0js3qf/screenshot--2017-04-02-20-18-33.png

When I apply border-radius it looks like this --> https://s11.postimg.org/t25tmdsf7/screenshot--2017-04-02-20-19-12.png

I'm working on Chrome, Windows OS. I've tried using web-kit just in case, with the same results.. Has this ever happened to anyone else?

Here's that bit of code in case there's anything I haven't seen there:

HTML

    <button type="button" class="texto">INGRESAR</button>

CSS
#boton{
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
width: 100%;
margin: auto;
margin-top: 2%;
}

#boton>button{
width: 20%;
padding: 10px;
}

Thanks!

Body:
You could try this one bro. Just click the demo to see the result. Hope this answer yours.

#boton {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
  width: 100%;
  margin: auto;
  margin-top: 2%;
}

#boton > button {
  width: 20%;
  padding: 10px;
  border-radius: 7px;
  background: #F8F9F9;
  color: grey;
  font-weight: bold;
}

<div id="boton">
    <button type="button" class="texto">INGRESAR</button>
</div>


问:
Angular uiGrid: D3 CellTemplate not sorting
I am trying to show custom D3 cellTemplate in UiGrid angular library and implement the sorting functionality. By following this answer I was able to implement it but used a custom directory instead of nvd3. For sorting of column with custom template(here D3 elements) I am using sortingAlgorithm attribute of uiGrid. The problem is once the D3 is drawn for the whole grid, on sorting it is not updating.

columDef:

```<code>columnObj = {
                field: reportEvidenceHeaders[i],
                enableHiding: false,
                headerTooltip: true,
                cellTemplate: '<div class="ui-grid-cell-contents"><ui-grid-bar-chart data="row.entity.'+reportEvidenceHeaders[i]+'"></ui-grid-bar-chart></div>',
                sortingAlgorithm: uiGridViewSorting
            };
</code>```

uiGridViewSorting:

```<code>var uiGridViewSorting = function(a, b, rowA, rowB, direction){
          a = Number(a.split("/")[0]);
          b = Number(b.split("/")[0]);
          if (a == b) return 0;
          if (a < b) return -1;
          return 1;
      };
</code>```

ui-grid-bar-chart is the D3 directory.

ui-grid-bar-chart:

```<code>link: function(scope, element, attrs){
    d3.select(element[0]).append("svg").height("100%").width("100%");
}
</code>```

Here, I am appending the D3 on element[0].

Grid:

The grid on first drawing looks fine.

But on sorting all the other columns are updated except the one containing the D3 elements.

Plunker: Here

What is the problem here?

答:
There are two issues.

You would need to wrap the drawing of the graph in a $watch otherwise it doesn't know to redraw when the grid changes (more detailed explanation here: https://github.com/angular-ui/ui-grid/issues/743). This fixes scrolling, and sorting on the other columns, but by itself it won't fix sorting on the graph column:

```<code>scope.$watch('data', function() {
   drawUiGridBarChart(scope.data, scope.width);
});
</code>```

Now to fix sorting on this column, field needs to point to spark.data

```<code>{ field: 'spark.data', // not field: 'uiGrid',
    cellTemplate: '...
</code>```

Updated Plunker: https://plnkr.co/edit/t281BcETvrLihSBAcWWo?p=preview

Body:
I am trying to show custom D3 cellTemplate in UiGrid angular library and implement the sorting functionality. By following this answer I was able to implement it but used a custom directory instead of nvd3. For sorting of column with custom template(here D3 elements) I am using sortingAlgorithm attribute of uiGrid. The problem is once the D3 is drawn for the whole grid, on sorting it is not updating.

columDef:

columnObj = {
                field: reportEvidenceHeaders[i],
                enableHiding: false,
                headerTooltip: true,
                cellTemplate: '
<ui-grid-bar-chart data="row.entity.'+reportEvidenceHeaders[i]+'"></ui-grid-bar-chart>
',
                sortingAlgorithm: uiGridViewSorting
            };

uiGridViewSorting:

var uiGridViewSorting = function(a, b, rowA, rowB, direction){
          a = Number(a.split("/")[0]);
          b = Number(b.split("/")[0]);
          if (a == b) return 0;
          if (a < b) return -1;
          return 1;
      };

ui-grid-bar-chart is the D3 directory.

ui-grid-bar-chart:

link: function(scope, element, attrs){
    d3.select(element[0]).append("svg").height("100%").width("100%");
}

Here, I am appending the D3 on element[0].

Grid:

The grid on first drawing looks fine.

But on sorting all the other columns are updated except the one containing the D3 elements.

Plunker: Here

What is the problem here?

Body:
There are two issues.

You would need to wrap the drawing of the graph in a $watch otherwise it doesn't know to redraw when the grid changes (more detailed explanation here: https://github.com/angular-ui/ui-grid/issues/743). This fixes scrolling, and sorting on the other columns, but by itself it won't fix sorting on the graph column:

scope.$watch('data', function() {
   drawUiGridBarChart(scope.data, scope.width);
});

Now to fix sorting on this column, field needs to point to spark.data

{ field: 'spark.data', // not field: 'uiGrid',
    cellTemplate: '...

Updated Plunker: https://plnkr.co/edit/t281BcETvrLihSBAcWWo?p=preview


问:
Why is array co-variance considered so horrible?
In .NET reference type arrays are co-variant. This is considered a mistake. However, I don't see why this is so bad consider the following code:

```<code>string[] strings = new []{"Hey there"};
object[] objects = strings;
objects[0] = new object();
</code>```

Oh ho, this compiles and will fail at runtime. As we tried to stick an object into a string[]. Okay, I agree that stinks, but a T[] extends Array and also implements IList (and IList<T>, I wonder if it implements IList<BaseType>...>. Both Array and IList allow us to make the same horrid mistake.

```<code>string[] strings = new []{"Hey there"};
Array objects = strings;
objects.SetValue(new object(),new[]{0});
</code>```

IList version

```<code>string[] strings = new []{"Hey there"};
IList objects = strings;
objects[0] = new object();
</code>```

The T[] classes are generated by the CLR, and have to include a type check on the equivalent of the set_Item method (arrays don't actually have one).

Is the concern that setting to a T[] has to do the type check at runtime (which violates the type-safety you expect at compile time)? Why is it considered harmful for arrays to exhibit this property when there are equivalent means to shoot yourself in the foot through the provided means above?

答:
Yes, IList and Array allow you to make the same mistake - because they're weakly-typed APIs to start with.

Arrays look like they're strongly typed (at compile time) but in reality they're not. They could so easily have been safe (and faster) but they're not. It's just a wasted opportunity for both performance and compile-time safety :(

Body:
In .NET reference type arrays are co-variant. This is considered a mistake. However, I don't see why this is so bad consider the following code:

string[] strings = new []{"Hey there"};
object[] objects = strings;
objects[0] = new object();

Oh ho, this compiles and will fail at runtime. As we tried to stick an object into a string[]. Okay, I agree that stinks, but a T[] extends Array and also implements IList (and IList<T>, I wonder if it implements IList<BaseType>...>. Both Array and IList allow us to make the same horrid mistake.

string[] strings = new []{"Hey there"};
Array objects = strings;
objects.SetValue(new object(),new[]{0});

IList version

string[] strings = new []{"Hey there"};
IList objects = strings;
objects[0] = new object();

The T[] classes are generated by the CLR, and have to include a type check on the equivalent of the set_Item method (arrays don't actually have one).

Is the concern that setting to a T[] has to do the type check at runtime (which violates the type-safety you expect at compile time)? Why is it considered harmful for arrays to exhibit this property when there are equivalent means to shoot yourself in the foot through the provided means above?


问:
How to open a file / browse dialog using javascript?
Is there any way to open the browse for files dialog box when a href> link is clicked using javascript? It should function like a normal browse for files button and give the names/list of files selected in response.

答:
Create input element.

Missing from these answers is how to get a file dialog without a input element on the page.

The function to show the input file dialog.

function openFileDialog (accept, callback) {  // this function must be called from  a user
                                              // activation event (ie an onclick event)

    // Create an input element
    var inputElement = document.createElement("input");

    // Set its type to file
    inputElement.type = "file";

    // Set accept to the file types you want the user to select.
    // Include both the file extension and the mime type
    inputElement.accept = accept;

    // set onchange event to call callback when user has selected file
    inputElement.addEventListener("change", callback)

    // dispatch a click event to open the file dialog
    inputElement.dispatchEvent(new MouseEvent("click"));
}
```
<blockquote>
<p><strong>NOTE</strong> the function must be part of a user activation such as a click event. Attempting to open the file dialog without user activation will fail.</p>
<p><strong>NOTE</strong> <code>input.accept</code> is not used in Edge</p>
</blockquote>
<h3>Example.</h3>
<p>Calling above function when user clicks an anchor element.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="true">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// wait for window to load
window.addEventListener("load", windowLoad);

// open a dialog function
function openFileDialog (accept, multy = false, callback) {
    var inputElement = document.createElement("input");
    inputElement.type = "file";
    inputElement.accept = accept; // Note Edge does not support this attribute
    if (multy) {
        inputElement.multiple = multy;
    }
    if (typeof callback === "function") {
         inputElement.addEventListener("change", callback);
    }
    inputElement.dispatchEvent(new MouseEvent("click"));
}

// onload event
function windowLoad () {
    // add user click event to userbutton
    userButton.addEventListener("click", openDialogClick);
}

// userButton click event
function openDialogClick () {
    // open file dialog for text files
    openFileDialog(".txt,text/plain", true, fileDialogChanged);
}

// file dialog onchange event handler
function fileDialogChanged (event) {
    [...this.files].forEach(file => {
        var div = document.createElement("div");
        div.className = "fileList common";
        div.textContent = file.name;
        userSelectedFiles.appendChild(div);
    });
}</code>```

.common {
    font-family: sans-serif;
    padding: 2px;
    margin : 2px;
    border-radius: 4px;
 }
.fileList {
    background: #229;
    color: white;
}
#userButton {
    background: #999;
    color: #000;
    width: 8em;
    text-align: center;
    cursor: pointer;
}

#userButton:hover {
   background : #4A4;
   color : white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Open file dialog
<div id = "userSelectedFiles" class = "common"></div></code>```

Warning the above snippet is written in ES6.

Body: Is there any way to open the browse for files dialog box when a  link is clicked using javascript? It should function like a normal browse for files button and give the names/list of files selected in response.

Body:
Create input element.

Missing from these answers is how to get a file dialog without a input element on the page.

The function to show the input file dialog.

function openFileDialog (accept, callback) {  // this function must be called from  a user
                                              // activation event (ie an onclick event)

    // Create an input element
    var inputElement = document.createElement("input");

    // Set its type to file
    inputElement.type = "file";

    // Set accept to the file types you want the user to select.
    // Include both the file extension and the mime type
    inputElement.accept = accept;

    // set onchange event to call callback when user has selected file
    inputElement.addEventListener("change", callback)

    // dispatch a click event to open the file dialog
    inputElement.dispatchEvent(new MouseEvent("click"));
}

NOTE the function must be part of a user activation such as a click event. Attempting to open the file dialog without user activation will fail.

NOTE input.accept is not used in Edge

Example.

Calling above function when user clicks an anchor element.

// wait for window to load
window.addEventListener("load", windowLoad);

// open a dialog function
function openFileDialog (accept, multy = false, callback) {
    var inputElement = document.createElement("input");
    inputElement.type = "file";
    inputElement.accept = accept; // Note Edge does not support this attribute
    if (multy) {
        inputElement.multiple = multy;
    }
    if (typeof callback === "function") {
         inputElement.addEventListener("change", callback);
    }
    inputElement.dispatchEvent(new MouseEvent("click"));
}

// onload event
function windowLoad () {
    // add user click event to userbutton
    userButton.addEventListener("click", openDialogClick);
}

// userButton click event
function openDialogClick () {
    // open file dialog for text files
    openFileDialog(".txt,text/plain", true, fileDialogChanged);
}

// file dialog onchange event handler
function fileDialogChanged (event) {
    [...this.files].forEach(file => {
        var div = document.createElement("div");
        div.className = "fileList common";
        div.textContent = file.name;
        userSelectedFiles.appendChild(div);
    });
}

.common {
    font-family: sans-serif;
    padding: 2px;
    margin : 2px;
    border-radius: 4px;
 }
.fileList {
    background: #229;
    color: white;
}
#userButton {
    background: #999;
    color: #000;
    width: 8em;
    text-align: center;
    cursor: pointer;
}

#userButton:hover {
   background : #4A4;
   color : white;
}

<a id = "userButton" class = "common" title = "Click to open file selection dialog">Open file dialog</a>
<div id = "userSelectedFiles" class = "common"></div>

Warning the above snippet is written in ES6.


问:
How put all extension of a datatables jquery in the dt-toolbar in spesific order?
I used the datatables jQuery plugin in my tables, and I add a button to the dt-toolbar. I want to add all extension of a datatables plugin like: Show and hide columns, filter, show number of rows in page.

I tried this code :

```<code>"sDom": "<'dt-toolbar'<'col-sm-6 col-xs-12  '<'toolbar1'f>> <'col-sm-6 col-xs-12 '<'toolbar'lC>>>"
</code>```

In the toolbar I add my button with this code:

```<code>$("div.toolbar").prepend('<button class=" btn btn-primary " data-toggle="modal" data-target="#myModal" > Ajouter fonction</button>');
$("div.toolbar").addClass('text-right');
</code>```

I have this result:

but I want the filter and show rows on the left, and the button and the show hide column on the right, how can I do this?

答:
```<code>This the answer of the second question !!

"oLanguage": {

  "sLengthMenu" : "<label>Show <select name='my-table_length' aria-controls='my-table' class='form-control input-sm'> <option value='5'>5</option> <option value='10'>10</option> <option value='25'>25</option> <option value='50'>50</option> </select>entries </label>"

          },
</code>```

Body:
I used the datatables jQuery plugin in my tables, and I add a button to the dt-toolbar. I want to add all extension of a datatables plugin like: Show and hide columns, filter, show number of rows in page.

I tried this code :

"sDom": "<'dt-toolbar'<'col-sm-6 col-xs-12  '<'toolbar1'f>> <'col-sm-6 col-xs-12 '<'toolbar'lC>>>"

In the toolbar I add my button with this code:

$("div.toolbar").prepend('<button class=" btn btn-primary " data-toggle="modal" data-target="#myModal" > Ajouter fonction</button>');
$("div.toolbar").addClass('text-right');

I have this result:

but I want the filter and show rows on the left, and the button and the show hide column on the right, how can I do this?


问:
Difficulty in inserting HTML output table from R into Outlook
I created a HTML table in R using the package HTMLTable. However, the output generated from HTMLTable shows up terribly in Outlook. It's basically almost unreadable. The borders don't show up in Outlook at all, and spacing is far too large. I know the output from R2HTML works in Outlook, but as far as I know I can't get up the  tags to show up with R2HTML.

Help or advice would be much appreciated. Below is the current code I'm using to export my .html table:

```<code>htmltools::save_html(htmlTable::htmlTable(data), file = "data")
</code>```

答:
This will add the HTML tags to the saved file:</p>

```<code>mytableout <-htmlTable(data)

sink("data.html")
cat("<head>")
print(mytableout,type="html",useViewer=TRUE)
cat("</head>")
sink()
</code>```

Body:
I created a HTML table in R using the package HTMLTable. However, the output generated from HTMLTable shows up terribly in Outlook. It's basically almost unreadable. The borders don't show up in Outlook at all, and spacing is far too large. I know the output from R2HTML works in Outlook, but as far as I know I can't get up the  tags to show up with R2HTML.

Help or advice would be much appreciated. Below is the current code I'm using to export my .html table:

htmltools::save_html(htmlTable::htmlTable(data), file = "data")

Body:
This will add the HTML tags to the saved file:

mytableout <-htmlTable(data)

sink("data.html")
cat("<head>")
print(mytableout,type="html",useViewer=TRUE)
cat("</head>")
sink()


问:
react-native - this.porps.inGrid is not a function
I'm trying to display a nested array containing numbers. The array has 6 elements (arrays). Each nested array contains 6 further elements/numbers. I'm trying to display each number in a Square component. I've got an error: this.props.inGrid.foreach is not a function.

```<code>import React, { Component, PropTypes } from 'react';
import { View, StyleSheet } from 'react-native';
import Square from './Square';
import * as globalStyles from '../styles/global';

export default class Grid extends Component {

  render() {
    const row = [];
    this.props.inGrid.foreach((r, i) => {
      row.push(
        <Square key={i} sqValue={r[i]} />
      );
    });
    return (
      <View style={styles.grid}>
        {row}
      </View>
    );
  }

}

Grid.propTypes = {
  numbers: PropTypes.object
};

const styles = StyleSheet.create({
  grid: {
    backgroundColor: globalStyles.BG_COLOR,
    flexDirection: 'row',
    padding: 20,
    justifyContent: 'center'
  }
});
</code>```

Below is the Square component:

```<code>import React, { PropTypes } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import * as globalStyles from '../styles/global';

const Square = ({ sqValue }) => {
  return (
    <View style={styles.square}>
      <Text>{sqValue}</Text>
    </View>
  );
};

Square.propTypes = {
  sqValue: PropTypes.number
};

const styles = StyleSheet.create({
  square: {
    backgroundColor: globalStyles.BAR_COLOR,
    width: 50,
    height: 50,
    borderWidth: 1,
    borderStyle: 'solid',
    borderColor: 'red'
  }
});
export default Square;
</code>```

What am I doing wrong?

答:
It appears that you're calling:

this.props.inGrid.foreach

but the function is actually called forEach

Body:
I'm trying to display a nested array containing numbers. The array has 6 elements (arrays). Each nested array contains 6 further elements/numbers. I'm trying to display each number in a Square component. I've got an error: this.props.inGrid.foreach is not a function.

import React, { Component, PropTypes } from 'react';
import { View, StyleSheet } from 'react-native';
import Square from './Square';
import * as globalStyles from '../styles/global';

export default class Grid extends Component {

  render() {
    const row = [];
    this.props.inGrid.foreach((r, i) => {
      row.push(
        <Square key={i} sqValue={r[i]} />
      );
    });
    return (
      <View style={styles.grid}>
        {row}
      </View>
    );
  }

}

Grid.propTypes = {
  numbers: PropTypes.object
};

const styles = StyleSheet.create({
  grid: {
    backgroundColor: globalStyles.BG_COLOR,
    flexDirection: 'row',
    padding: 20,
    justifyContent: 'center'
  }
});

Below is the Square component:

import React, { PropTypes } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import * as globalStyles from '../styles/global';

const Square = ({ sqValue }) => {
  return (
    <View style={styles.square}>
      <Text>{sqValue}</Text>
    </View>
  );
};

Square.propTypes = {
  sqValue: PropTypes.number
};

const styles = StyleSheet.create({
  square: {
    backgroundColor: globalStyles.BAR_COLOR,
    width: 50,
    height: 50,
    borderWidth: 1,
    borderStyle: 'solid',
    borderColor: 'red'
  }
});
export default Square;

What am I doing wrong?


问:
Database says missing column even though column is there
EDIT: I found the cause to be the error of not having a column in my database called Col_Name, however I did code the column into the database and yet it tells me it isnt there.

Error message:
Error Code : 1 (SQLITE_ERROR)
                                                                       Caused By : SQL(query) error or missing database.
                                                                        (table Expense_Table has no column named Name (code 1): , while compiling: INSERT INTO Expense_Table(Am,Name) VALUES (?,?))

I have a database with 2 Columns. I save inputs into the 2 columns then load them into a listview. I have successfully done 1 column and it works perfectly. When I add the 2nd column and I load the app, my Toast message tells me my database is empty. Any help on why this happens?

My MainActivity(Only relevant parts):

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    listView = (ListView)findViewById(R.id.listView);
    if (android.os.Build.VERSION.SDK_INT >= 21) {
        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimary));
    }
    //Code for Ads
    mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

    nameList = new ArrayList<>();
    expenseList = new ArrayList<>();
    Row = new ArrayList<>();
    adapter = new CustomAdapter(this, Row);
    listView.setAdapter(adapter);

    //Get Database to populate Listview
    myDb = new DBHelper(this);
    Cursor data = myDb.getListContent();
    if(data.getCount() == 0){
        Toast.makeText(this, "Data NOT loaded", Toast.LENGTH_SHORT).show();
    } else{
        while(data.moveToNext()){
            String dbAmount = data.getString(1);
            String dbName = data.getString(2);
            ExRow exRow = new ExRow(dbAmount, dbName);
            expenseList.add(dbAmount);
            Row.add(exRow);
            adapter.notifyDataSetChanged();
            Toast.makeText(this, "Data loaded", Toast.LENGTH_SHORT).show();
        }
    }
</code>```

And here is my Database class for retrieving and saving data:

```<code>private static final String DATABASE_NAME = "Expenses.db";
    public static final String TABLE_NAME = "Expense_Table";
    public static final String Col_ID = "id";
    public static final String Col_AMOUNT = "Am";
    public static final String Col_NAME = "Name";

   //public  static final String Col_Date = "date";

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    //Set up database here
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("Create table " + TABLE_NAME +
                "(ID INTEGER PRIMARY KEY AUTOINCREMENT, AM TEXT, Name TEXT)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

    }

public boolean saveData(String Am, String Name) {
   SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(Col_AMOUNT, Am);
    contentValues.put(Col_NAME, Name);

    long result = db.insert(TABLE_NAME, null, contentValues);
    if(result == -1){
        return false;
    }else {
        return true;
    }
}
public Cursor getListContent(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
    return data;
}
</code>```

There is more to my MainActivity that adds the inputs into the database. I figured it's too simple to paste the code. It's simply saveData(String, String);

答: I found the answer. It was because I added the column later after already creating the database. I change the name of the database and it worked.</p>

Body:
EDIT: I found the cause to be the error of not having a column in my database called Col_Name, however I did code the column into the database and yet it tells me it isnt there.

Error message:
Error Code : 1 (SQLITE_ERROR)
                                                                       Caused By : SQL(query) error or missing database.
                                                                        (table Expense_Table has no column named Name (code 1): , while compiling: INSERT INTO Expense_Table(Am,Name) VALUES (?,?))

I have a database with 2 Columns. I save inputs into the 2 columns then load them into a listview. I have successfully done 1 column and it works perfectly. When I add the 2nd column and I load the app, my Toast message tells me my database is empty. Any help on why this happens?

My MainActivity(Only relevant parts):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    listView = (ListView)findViewById(R.id.listView);
    if (android.os.Build.VERSION.SDK_INT >= 21) {
        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.setStatusBarColor(this.getResources().getColor(R.color.colorPrimary));
    }
    //Code for Ads
    mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);

    nameList = new ArrayList<>();
    expenseList = new ArrayList<>();
    Row = new ArrayList<>();
    adapter = new CustomAdapter(this, Row);
    listView.setAdapter(adapter);

    //Get Database to populate Listview
    myDb = new DBHelper(this);
    Cursor data = myDb.getListContent();
    if(data.getCount() == 0){
        Toast.makeText(this, "Data NOT loaded", Toast.LENGTH_SHORT).show();
    } else{
        while(data.moveToNext()){
            String dbAmount = data.getString(1);
            String dbName = data.getString(2);
            ExRow exRow = new ExRow(dbAmount, dbName);
            expenseList.add(dbAmount);
            Row.add(exRow);
            adapter.notifyDataSetChanged();
            Toast.makeText(this, "Data loaded", Toast.LENGTH_SHORT).show();
        }
    }

And here is my Database class for retrieving and saving data:

private static final String DATABASE_NAME = "Expenses.db";
    public static final String TABLE_NAME = "Expense_Table";
    public static final String Col_ID = "id";
    public static final String Col_AMOUNT = "Am";
    public static final String Col_NAME = "Name";

   //public  static final String Col_Date = "date";

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);

    }

    @Override
    //Set up database here
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("Create table " + TABLE_NAME +
                "(ID INTEGER PRIMARY KEY AUTOINCREMENT, AM TEXT, Name TEXT)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

    }

public boolean saveData(String Am, String Name) {
   SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(Col_AMOUNT, Am);
    contentValues.put(Col_NAME, Name);

    long result = db.insert(TABLE_NAME, null, contentValues);
    if(result == -1){
        return false;
    }else {
        return true;
    }
}
public Cursor getListContent(){
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
    return data;
}

There is more to my MainActivity that adds the inputs into the database. I figured it's too simple to paste the code. It's simply saveData(String, String);


问: How to remove only one inline

答:
You can use wp_dequeue_style  and wp_deregister_style.

If you are going to view source, you can see the WP_HEAD generate link style like below:

```<code> <link rel='stylesheet' id='mystyle-css'  href='www.your_domain.com/css.style.css' type='text/css' media='all' />
</code>```

Now, if you want to remove this line, just go to your functions.php and include the code below:

```<code>function dequeue_unnecessary_styles_vxt() {
    $styles = array('mystyle'); //store here all the CSS you want to remove
    foreach ($styles as $key => $value) {
        wp_dequeue_style( $value );
        wp_deregister_style( $value );
    }
}
add_action( 'wp_print_styles', 'dequeue_unnecessary_styles_vxt' );
</code>```

I have edited the code above so you can dynamically remove all css styles you want to remove. Note that, from css link style, there is an id called, mystyle-css this is how you will track the css in your custom functions.php. Add the ID (without -css) insde the $styles.

Hope it helps.

Title: How to remove only one inline <style> from Wordpress head

Body:
I'm designing a Wordpress site that's not yet live. There is a block of inline css in the head of the home page that needs to go. I'm not sure where it's being generated from but the I've modified the css since and the inline css isn't updating to match it.

I've tried overruling it by using !important in my custom.css.

I've tried adding my style sheet just above the  so it loads last.

<link rel='stylesheet' href='http://mywebsite/wpnew/wp-content/themes/mytheme/custom.css?counter=1491147962' type='text/css' media='all' />

I've tried adding this to my functions.php:

wp_enqueue_style( 'customcss', get_template_directory_uri() . '/custom.css', array(), time() );

I've deleted the widget that the css belongs to thinking the page might render without the inline css since the widget was gone but it's still there.

I'm at a loss. I'm not a programmer and not entirely comfortable with php. I found a plugin that strips all inline tags but I only want to get rid of this one block of css.

Any help would be appreciated!

Body:
You can use wp_dequeue_style  and wp_deregister_style.

If you are going to view source, you can see the WP_HEAD generate link style like below:

 <link rel='stylesheet' id='mystyle-css'  href='www.your_domain.com/css.style.css' type='text/css' media='all' />

Now, if you want to remove this line, just go to your functions.php and include the code below:

function dequeue_unnecessary_styles_vxt() {
    $styles = array('mystyle'); //store here all the CSS you want to remove
    foreach ($styles as $key => $value) {
        wp_dequeue_style( $value );
        wp_deregister_style( $value );
    }
}
add_action( 'wp_print_styles', 'dequeue_unnecessary_styles_vxt' );

I have edited the code above so you can dynamically remove all css styles you want to remove. Note that, from css link style, there is an id called, mystyle-css this is how you will track the css in your custom functions.php. Add the ID (without -css) insde the $styles.

Hope it helps.


问:
How to get content by urllib when link will be redirect to another?
I'm trying to use urllib to get content from this url:"https://blockexplorer.com/block-index/0" . But when the browser load this link, it will be redirect to another link "https://blockexplorer.com/block/000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f".

Here is my code:

```<code>import urllib

link = "https://blockexplorer.com/block-index/0"
f = urllib.urlopen(link)
myfile = f.read()
print myfile
</code>```

But I get the message "Cannot GET /block-index/0".
So could I get the content of page after parsed with block index as above.

Please help me solve this issue.

Thank a lot.

答:
The site you are trying to crawl does not accept the header */* (default for urllib), but accept text/html. You can crawl with the following code:

```<code>import urllib2

link = "http://blockexplorer.com/block-index/0"
r = urllib2.Request(url=link)
r.add_header('Accept', 'text/html')
response = urllib2.urlopen(r)
print(response.read())
</code>```

But i think you will have more problems later. The data is not printed at html, but dynamically retrieved via javascript (angularJS).

Body:
I'm trying to use urllib to get content from this url:"https://blockexplorer.com/block-index/0" . But when the browser load this link, it will be redirect to another link "https://blockexplorer.com/block/000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f".

Here is my code:

import urllib

link = "https://blockexplorer.com/block-index/0"
f = urllib.urlopen(link)
myfile = f.read()
print myfile

But I get the message "Cannot GET /block-index/0".
So could I get the content of page after parsed with block index as above.

Please help me solve this issue.

Thank a lot.

Body:
The site you are trying to crawl does not accept the header */* (default for urllib), but accept text/html. You can crawl with the following code:

import urllib2

link = "http://blockexplorer.com/block-index/0"
r = urllib2.Request(url=link)
r.add_header('Accept', 'text/html')
response = urllib2.urlopen(r)
print(response.read())

But i think you will have more problems later. The data is not printed at html, but dynamically retrieved via javascript (angularJS).


问:
How to use regular expressions to pull something from a terminal output?
I'm attempting to use the re module to look through some terminal output. When I ping a server through terminal using ping -n 1 host (I'm using Windows), it gives me much more information than I want. I want just the amount of time that it takes to get a reply from the server, which in this case is always denoted by an integer and then the letters 'ms'. The error I get explains that the output from the terminal is not a string, so I cannot use regular expressions on it.

```<code>from os import system as system_call
import re

def ping(host):
    return system_call("ping -n 1 " + host) == 0

host = input("Select a host to ping: ")

regex = re.compile(r"\w\wms")
final_ping = regex.search(ping(host))
print(final_ping)
</code>```

答:
system returns 0, not anything too useful.  However, if we were to do subprocess, we can get teh output, and store it to a variable, out, then we can regex search that.

```<code>import subprocess
import re

def ping(host):
   ping = subprocess.Popen(["ping", "-n", "1", host], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
   out, error = ping.communicate()
   return str(out)

host = input("Select a host to ping: ")

final_ping = re.findall("\d+ms",ping(host))[0]
print(final_ping)
</code>```

Output:

```<code>22ms
</code>```

Body:
I'm attempting to use the re module to look through some terminal output. When I ping a server through terminal using ping -n 1 host (I'm using Windows), it gives me much more information than I want. I want just the amount of time that it takes to get a reply from the server, which in this case is always denoted by an integer and then the letters 'ms'. The error I get explains that the output from the terminal is not a string, so I cannot use regular expressions on it.

from os import system as system_call
import re

def ping(host):
    return system_call("ping -n 1 " + host) == 0

host = input("Select a host to ping: ")

regex = re.compile(r"\w\wms")
final_ping = regex.search(ping(host))
print(final_ping)

Body:
system returns 0, not anything too useful.  However, if we were to do subprocess, we can get teh output, and store it to a variable, out, then we can regex search that.

import subprocess
import re

def ping(host):
   ping = subprocess.Popen(["ping", "-n", "1", host], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
   out, error = ping.communicate()
   return str(out)

host = input("Select a host to ping: ")

final_ping = re.findall("\d+ms",ping(host))[0]
print(final_ping)

Output:

22ms