问:
Add nested enumerable support to custom class
I am currently working in Visual Studio 2015 using Visual Basic and I have a class that takes a delimited string and can extract/replace data at positions within the string, similar to a jagged array, up to three levels deep.  I may expand the class to handle deeper than three levels, but for now, I'll stick with the three.  This is exactly like a PICK mvdbms data structure for those who are familiar.  The base class to read and write the data within the class has already been built.  For space and expediency, I have included redacted code as a reference in assisting with my question.  If more data is needed, I can provide the whole class.  Also, if during the discussion of this question there are concerns or suggestions to improve my code, I am always willing to listen to constructive feedback.

The class:

```<code>Public Class MVString

#Region " Properties "
    Private Record As String
    Default WriteOnly Property MV(ByVal str As String) As MVString
        Set
            Record = str
        End Set
    End Property

    Default Public Property MV(ByVal AMPos As Integer) As MVString
       'Get and set value at top level
    End Property

    Default Public Property MV(ByVal AMPos As Integer, ByVal VMPos As Integer) As MVString
        'Get and set value at middle level
    End Property

    Default Public Property MV(ByVal AMPos As Integer, ByVal VMPos As Integer, ByVal SMPos As Integer) As MVString
        'Get and set value at deepest level
    End Property
#End Region

#Region " Constructors "
    Public Sub New()
        Record = ""
    End Sub

    Public Sub New(ByVal str As String)
        Record = str
    End Sub
#End Region

#Region " Methods "
    Public Sub Clear()
        Record = ""
    End Sub

    Public Overrides Function ToString() As String
        Return Record
    End Function
#End Region

#Region " Operators "
    Public Shared Widening Operator CType(v As String) As MVString
        Return New MVString(v)
    End Operator

    Public Shared Widening Operator CType(v As MVString) As String
        Return v.ToString
    End Operator
#End Region

End Class
</code>```

My question is this: How do I go about creating enumerable support for this class and limit it to the three levels so the system knows which level it is on and which delimiter it needs to use?  For example, if I have the following variable:

Dim DelimitedString As String = "Foo,4,7,1-2,,6|Bar,4,2,8-7,5,7|Fly,4,,8-7,5,7"

The delimiter for the top level would be the "|", the second level would be "," and the deepest level would be "-".  In this instance, the top level would be an array {"Foo,4,7,1-2,,6", "Bar,4,2,8-7,5,7", "Fly,4,,8-7,5,7"}, the second level would first enumerate through the first element in the upper level, and return {"Foo", "4", "7", "1-2", "", "6"}, etc...

Any ideas on where to start?

Update:

I'm Not sure how to incorporate the dictionary into the class so I've updated my post with what I had come up with before.

```<code>Public Function GetEnumerator() As IEnumerator(Of String) Implements IEnumerable(Of String).GetEnumerator
    Return New MVStringEnumerator(Record)
End Function

Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
    Return Me.GetEnumerator()
End Function

Private Class MVStringEnumerator
    Implements IEnumerator(Of String)

    Private _ThisArray() As String
    Private idx As Integer

    Public ReadOnly Property Current As String Implements IEnumerator(Of String).Current
        Get
            Return If(idx < _ThisArray.Count, _ThisArray(idx), DirectCast(Nothing, String))
        End Get
    End Property

    Private ReadOnly Property IEnumerator_Current As Object Implements IEnumerator.Current
        Get
            Return Me.Current
        End Get
    End Property

    Public Sub New(ByVal record As String)
        Select Case True
            Case record.Contains("|"c)
                _ThisArray = Split(record, "|"c)
            Case record.Contains(","c)
                _ThisArray = Split(record, ","c)
            Case record.Contains("-"c)
                _ThisArray = Split(record, "-"c)
        End Select
        idx = -1
    End Sub

    Public Sub Reset() Implements IEnumerator.Reset
        idx = -1
    End Sub

    Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext
        idx += 1
        If idx >= _ThisArray.Count Then Return False
        Return True
    End Function

End Class
</code>```

答:
I think you have the right idea with the MVStringEnumerator, where you're ultimately enumerating an array of strings rather than a MV delimited string. (As an MVDBMS expert I understand your references.) This could be fairly simple. I'd eliminate the double duty of this task, parsing delimiters And enumeration.

First whittle the enumerated object down to the lowest level of the dynamic array desired:

myValue = myMVString.MV(1,4)

Second, make that enumerable:

mySubValues = myValue.AsEnumerable()

Last, enumerate mySubValues as a common array of strings. So the enumeration is unaware of the MV-nature of the original dynamic array.
Of course all of the above can be done more elegantly and encapsulated into a single method that returns the desired enumerable, like :

myEnumerable = myMVString.AsEnumerable(1,4)

Or ultimately just iterate over something like new MyEnumerable(myMVSTRING(1,4)).

Note that if you're actually working with a MVDBMS, each platform has its own free class libraries to do this kind of thing: MVSP, UO.NET, QMClient, etc. So you may not need to write this from scratch at all - though it is a good exercise.

Side note

If you are emulating MV dynamic arrays, your code uses a base index of 0 where MV uses 1.

Body:
I am currently working in Visual Studio 2015 using Visual Basic and I have a class that takes a delimited string and can extract/replace data at positions within the string, similar to a jagged array, up to three levels deep.  I may expand the class to handle deeper than three levels, but for now, I'll stick with the three.  This is exactly like a PICK mvdbms data structure for those who are familiar.  The base class to read and write the data within the class has already been built.  For space and expediency, I have included redacted code as a reference in assisting with my question.  If more data is needed, I can provide the whole class.  Also, if during the discussion of this question there are concerns or suggestions to improve my code, I am always willing to listen to constructive feedback.

The class:

Public Class MVString

#Region " Properties "
    Private Record As String
    Default WriteOnly Property MV(ByVal str As String) As MVString
        Set
            Record = str
        End Set
    End Property

    Default Public Property MV(ByVal AMPos As Integer) As MVString
       'Get and set value at top level
    End Property

    Default Public Property MV(ByVal AMPos As Integer, ByVal VMPos As Integer) As MVString
        'Get and set value at middle level
    End Property

    Default Public Property MV(ByVal AMPos As Integer, ByVal VMPos As Integer, ByVal SMPos As Integer) As MVString
        'Get and set value at deepest level
    End Property
#End Region

#Region " Constructors "
    Public Sub New()
        Record = ""
    End Sub

    Public Sub New(ByVal str As String)
        Record = str
    End Sub
#End Region

#Region " Methods "
    Public Sub Clear()
        Record = ""
    End Sub

    Public Overrides Function ToString() As String
        Return Record
    End Function
#End Region

#Region " Operators "
    Public Shared Widening Operator CType(v As String) As MVString
        Return New MVString(v)
    End Operator

    Public Shared Widening Operator CType(v As MVString) As String
        Return v.ToString
    End Operator
#End Region

End Class

My question is this: How do I go about creating enumerable support for this class and limit it to the three levels so the system knows which level it is on and which delimiter it needs to use?  For example, if I have the following variable:

Dim DelimitedString As String = "Foo,4,7,1-2,,6|Bar,4,2,8-7,5,7|Fly,4,,8-7,5,7"

The delimiter for the top level would be the "|", the second level would be "," and the deepest level would be "-".  In this instance, the top level would be an array {"Foo,4,7,1-2,,6", "Bar,4,2,8-7,5,7", "Fly,4,,8-7,5,7"}, the second level would first enumerate through the first element in the upper level, and return {"Foo", "4", "7", "1-2", "", "6"}, etc...

Any ideas on where to start?

Update:

I'm Not sure how to incorporate the dictionary into the class so I've updated my post with what I had come up with before.

Public Function GetEnumerator() As IEnumerator(Of String) Implements IEnumerable(Of String).GetEnumerator
    Return New MVStringEnumerator(Record)
End Function

Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
    Return Me.GetEnumerator()
End Function

Private Class MVStringEnumerator
    Implements IEnumerator(Of String)

    Private _ThisArray() As String
    Private idx As Integer

    Public ReadOnly Property Current As String Implements IEnumerator(Of String).Current
        Get
            Return If(idx < _ThisArray.Count, _ThisArray(idx), DirectCast(Nothing, String))
        End Get
    End Property

    Private ReadOnly Property IEnumerator_Current As Object Implements IEnumerator.Current
        Get
            Return Me.Current
        End Get
    End Property

    Public Sub New(ByVal record As String)
        Select Case True
            Case record.Contains("|"c)
                _ThisArray = Split(record, "|"c)
            Case record.Contains(","c)
                _ThisArray = Split(record, ","c)
            Case record.Contains("-"c)
                _ThisArray = Split(record, "-"c)
        End Select
        idx = -1
    End Sub

    Public Sub Reset() Implements IEnumerator.Reset
        idx = -1
    End Sub

    Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext
        idx += 1
        If idx >= _ThisArray.Count Then Return False
        Return True
    End Function

End Class


来源: stackexchange

问:
how to use Scope variable base on index?
In AngularJS, one scope variable is assigned to ng-repeat. I have multiple div with click event function. When I click on the first div,  its data is displayed with ng-repeatusing the mydatalist scope variable. After this, if I click on another div same function is called and same scope variable is initialized with different data.display in this second div. The effect and the data of the first div are removed, and the second div data is filled.

I want that both data are different. How can I manage different scope variables with ng-repeat?

答:
The approach is easy, you only need to use a different scope variable for each div. In the function that opens your data list items, you need to create a copy of your mydatalist variable instead of using it. Check the next snippet and it surely gives you an idea to solve your issue:

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

app.controller("myController", ["$scope", function($scope) {

  var mydatalist = ["Subitem 1", "Subitem 2", "Subitem 3"];

  $scope.datos = [
    {value: "Item 1", items: []},
    {value: "Item 2", items: []},
    {value: "Item 3", items: []},
    {value: "Item 4", items: []},
    {value: "Item 5", items: []}
  ];

  $scope.openItem = function(item) {

    if (item.open) {

      item.items = [];

    } else {

      item.items = angular.copy(mydatalist);

    }

    item.open = !item.open;

  };

}]);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.item {
  background: #FFF;
  border: 1px solid #CCC;
  font: normal 14px Arial;
  line-height: 25px;
  text-indent: 10px;
}

.item:nth-last-child(n + 2) {
  border-bottom: none;
}

.subitem {
  background: #EEE;
  border-top: 1px solid #CCC;
  line-height: 25px;
  text-indent: 10px;
}</code>```

{{item.value}} ({{item.open ? "open" : "close"}})

 0">

          {{subitem}}

```

ContentLicense: CC BY-SA 3.0

Body:
The approach is easy, you only need to use a different scope variable for each div. In the function that opens your data list items, you need to create a copy of your mydatalist variable instead of using it. Check the next snippet and it surely gives you an idea to solve your issue:

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

app.controller("myController", ["$scope", function($scope) {

  var mydatalist = ["Subitem 1", "Subitem 2", "Subitem 3"];

  $scope.datos = [
    {value: "Item 1", items: []},
    {value: "Item 2", items: []},
    {value: "Item 3", items: []},
    {value: "Item 4", items: []},
    {value: "Item 5", items: []}
  ];

  $scope.openItem = function(item) {

    if (item.open) {

      item.items = [];

    } else {

      item.items = angular.copy(mydatalist);

    }

    item.open = !item.open;

  };

}]);

.item {
  background: #FFF;
  border: 1px solid #CCC;
  font: normal 14px Arial;
  line-height: 25px;
  text-indent: 10px;
}

.item:nth-last-child(n + 2) {
  border-bottom: none;
}

.subitem {
  background: #EEE;
  border-top: 1px solid #CCC;
  line-height: 25px;
  text-indent: 10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="myController">
    <div ng-repeat="item in datos" class="item">
      <div ng-click="openItem(item)">{{item.value}} ({{item.open ? "open" : "close"}})</div>
      <div ng-show="item.items.length > 0">
        <div ng-repeat="subitem in item.items" class="subitem">
          {{subitem}}
        </div>
      </div>
    </div>
  </div>
</div>


问:
How to make line through not affect the whole text in a list
I have this code in react which have inline style of line-through on textDecoration when completed is true:

```<code><li
    onClick = {onClick}
    style={{
      textDecoration: completed ? 'line-through' : 'none',
    }}
  >
    {text}
      <span>
       <a
         style={{ textDecoration: 'none', color: 'red' }}
         onClick={onTrashClick}
         href="#"
       >
         X
       </a>
      </span>
  </li>
</code>```

I tried to override the style in li in my a href and enclose it on span but I have no success, I also tried to put the style on span but no success, I want the line through not affect the X text in my href. Help?

答:
Create a span to put your text into and apply the style to that rather than the entire li:

```<code>   <li onClick = {onClick}>
       <span
         style={{
           textDecoration: completed ? 'line-through' : 'none',
         }}
       >
         {text}
       </span>
       <a
         style={{ color: 'red' }}
         onClick={onTrashClick}
         href="#"
       >
         X
       </a>
  </li>
</code>```

Body:
I have this code in react which have inline style of line-through on textDecoration when completed is true:

    {text}

         X

I tried to override the style in li in my a href and enclose it on span but I have no success, I also tried to put the style on span but no success, I want the line through not affect the X text in my href. Help?

Body:
Create a span to put your text into and apply the style to that rather than the entire li:

   <li onClick = {onClick}>
       <span
         style={{
           textDecoration: completed ? 'line-through' : 'none',
         }}
       >
         {text}
       </span>
       <a
         style={{ color: 'red' }}
         onClick={onTrashClick}
         href="#"
       >
         X
       </a>
  </li>


问:
How to implode a mysql query result array
I am running an SQL query which returns 18 results then I try to implode them. When I use the implode command right after mysqli_fetch_array to implode the mysqli_fetch_array result, I get only the first element of the array. However when I do the same with a while loop it works fine.

Here is my code: (it's simplified for ease of understanding)

```<code>$q = "SELECT id from sr WHERE m_id = '4';";
$my_query = mysqli_query($conn, $q);

$records = mysqli_num_rows($my_query);
echo 'records=' . $records;

$result = mysqli_fetch_array($my_query, MYSQLI_ASSOC);
print_r ($result);

$imploded_result = implode(",", $result);
echo 'imploded_result=' . $imploded_result;
</code>```

Here is what I get:

```<code>records=14
Array ( [id] => 14 )
imploded_result=14
</code>```

Now, when I use a while loop instead of the implode(), I get the correct results:

```<code>$imploded_result = '';
while ($result = mysqli_fetch_array($my_query, MYSQLI_ASSOC))
     $imploded_result .= $result['id'] . ',';
echo 'imploded_result=' . $imploded_result;
</code>```

I get:

```<code>imploded_result=14,21,24,27,28,30,31,32,37,152,155,154,156,157,158,159,181,196,
</code>```

Thank you in advance!

答:
In case someone else needs to get a similar outcome. I decided to use GROUP_CONCAT in my query line. So I changed my query line from:

```<code>$q = "SELECT id from sr WHERE m_id = '4';";
</code>```

to:

```<code>$q = "SELECT GROUP_CONCAT(id ORDER BY id ASC SEPARATOR ',') AS id from sr WHERE m_id = '4';";
</code>```

which will give me my desired outcome.

Body:
I am running an SQL query which returns 18 results then I try to implode them. When I use the implode command right after mysqli_fetch_array to implode the mysqli_fetch_array result, I get only the first element of the array. However when I do the same with a while loop it works fine.

Here is my code: (it's simplified for ease of understanding)

$q = "SELECT id from sr WHERE m_id = '4';";
$my_query = mysqli_query($conn, $q);

$records = mysqli_num_rows($my_query);
echo 'records=' . $records;

$result = mysqli_fetch_array($my_query, MYSQLI_ASSOC);
print_r ($result);

$imploded_result = implode(",", $result);
echo 'imploded_result=' . $imploded_result;

Here is what I get:

records=14
Array ( [id] => 14 )
imploded_result=14

Now, when I use a while loop instead of the implode(), I get the correct results:

$imploded_result = '';
while ($result = mysqli_fetch_array($my_query, MYSQLI_ASSOC))
     $imploded_result .= $result['id'] . ',';
echo 'imploded_result=' . $imploded_result;

I get:

imploded_result=14,21,24,27,28,30,31,32,37,152,155,154,156,157,158,159,181,196,

Thank you in advance!

Body:
In case someone else needs to get a similar outcome. I decided to use GROUP_CONCAT in my query line. So I changed my query line from:

$q = "SELECT id from sr WHERE m_id = '4';";

to:

$q = "SELECT GROUP_CONCAT(id ORDER BY id ASC SEPARATOR ',') AS id from sr WHERE m_id = '4';";

which will give me my desired outcome.


问:
Oracle query looking for particular string format
Am working with an Oracle 11g db in which I need to run a query that returns all rows with values in a specific format.

I.e., I need to find all rows with a value like 'abc1234'. The actual values aren't important....what I need is to find all rows with the first 3 characters being alpha and the subsequent 4 characters all being numeric.

Any input would be much appreciated.

答:
Might not be exact since I don't have an Oracle server handy to test but something like this should get you started in the right direction:

SELECT * FROM your_table WHERE REGEXP_LIKE(your_column, '([a-z]\3[0123456789]\4', 'i')

This will check all rows in your table where the specified column has any alphabet character A to Z three times followed by 4 numbers and return that list.  The 'i' at the end just says ignore case on the alphabet part.  You can choose to not have that option if you so wish.

Here are a couple links as well with more information on the regexp_like syntax:

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

https://docs.oracle.com/cd/B28359_01/server.111/b28286/conditions007.htm#SQLRF00501


问:
How to open (expand) block element to the left?
lets say I have 2 block elements that have fixed position and look like this in a window:

```<code>--------------
|        xxx |
|        xxx |
|            |
|        xxx |
|        xxx |
|            |
--------------
</code>```

I want an element to expand to the left on hover, like this:

```<code>--------------
|        xxx |
|        xxx |
|            |
|     xxxxxx |
|     xxxxxx |
|            |
--------------
</code>```

However, right now it expands to the right. Working example can be seen here: https://jsfiddle.net/eeuho5vq/2/

Any solution would be highly appreciated.

答:
Just add this to .container:

```<code>  float: right;
  clear: both;
</code>```

Updated snippet: https://jsfiddle.net/eeuho5vq/3/

Body:
lets say I have 2 block elements that have fixed position and look like this in a window:

--------------
|        xxx |
|        xxx |
|            |
|        xxx |
|        xxx |
|            |
--------------

I want an element to expand to the left on hover, like this:

--------------
|        xxx |
|        xxx |
|            |
|     xxxxxx |
|     xxxxxx |
|            |
--------------

However, right now it expands to the right. Working example can be seen here: https://jsfiddle.net/eeuho5vq/2/

Any solution would be highly appreciated.

Body:
Just add this to .container:

  float: right;
  clear: both;

Updated snippet: https://jsfiddle.net/eeuho5vq/3/


问:
Django handle photo upload
I have model whiuch has photo attachment.

```<code>class Forum_message(models.Model):
    text = models.TextField()
    photo = models.ImageField(upload_to= 'forum_attachments')
</code>```

I have my form(I prefer writing forms in pure html so I can have full access to modifying them)

```<code><form action="/forum_new" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input id="img_msg" type="file">
    <textarea name="new_msg"></textarea>
    <input type="submit" value="Submit"/>
</form>
</code>```

What do I write in my function
def forum_new(request): in views.py to handle file upload and save new forum message to database?

答:
In views.py, you can use what is propose on the django website (https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/)
If the picture is not so large, you can directly handle it as follow :

```<code>def forum_new(request):
    if request.method == 'POST':
        form = your_form_here(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('/bar.html/')
    else:
        form = your_form_here()
    return render(request, 'url.html', {'form': form})
</code>```

The file should be saved in your media files in the folder forum_attachments

Title: Django handle photo upload

Body:
I have model whiuch has photo attachment.

class Forum_message(models.Model):
    text = models.TextField()
    photo = models.ImageField(upload_to= 'forum_attachments')

I have my form(I prefer writing forms in pure html so I can have full access to modifying them)

<form action="/forum_new" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <input id="img_msg" type="file">
    <textarea name="new_msg"></textarea>
    <input type="submit" value="Submit"/>
</form>

What do I write in my function
def forum_new(request): in views.py to handle file upload and save new forum message to database?

Body:
In views.py, you can use what is propose on the django website (https://docs.djangoproject.com/en/1.11/topics/http/file-uploads/)
If the picture is not so large, you can directly handle it as follow :

def forum_new(request):
    if request.method == 'POST':
        form = your_form_here(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('/bar.html/')
    else:
        form = your_form_here()
    return render(request, 'url.html', {'form': form})

The file should be saved in your media files in the folder forum_attachments


问:
What is the best pattern for two way communication between classes?
I have classes that need to communicate with each other. The problem is that if you make one contain the other (a child parent relationship) then things get tricky. You either need to pass an instance of the parent into the child, (then which one do you create first if you are using dependency injection) or you can use delegates/events. But I want to enforce the fact that the parent must be able to handle the event that the child raises. Not too sure how to do that. I also don't want multiple subscribers to the event.

The parent-child relationship just feels wrong for two way communication. Unfortunately it is not a case that one of the objects always initiates and the other responds. Either can initiate and the other should respond.

Is there another pattern that I am missing?

UPDATE:
Sorry this is quite hard to explain. I forgot to add that when one class sends a message to another class it is not expecting the response immediately. The response comes in asynchronously which is why you either need an instance of the parent to call the right method or a delegate/event. Sorry the example below is pseudo code. Hopefully it is enough to get the idea. Should I look at the mediator pattern.

```<code>public class Foo
    {
        public void SendMessageAToBar()
        {
            MessageA msg = new MessageA();
            Bar.ReceiveMessageAFromFoo(msg);
        }

        public void ReceiveMessageARespFromBar(MessageAResp msgResp)
        {
            //Got a response do something
        }

        public void ReceiveMessageBFromBar(MessageB msg)
        {
            //Do something msg
            MessageBResp msgBResp = new MessageBResp();
            Bar.ReceiveMessageBRespFromFoo()
        }
    }

    public class Bar
    {

        public void ReceiveMessageAFromFoo(MessageA msg)
        {
            //DO something.
            MessageAResp resp = new MessageAResp();
            Foo.ReceiveMessageARespFromBar(resp);
        }

        public void SendMessageBToFoo()
        {
            MessageB msg = new MessageB();
            Foo.ReceiveMessageBFromBar(msg);
        }

        public void ReceiveMessageBRespFromFoo(MessageBResp msgResp)
        {
            //Got a response do something
        }
    }
</code>```

答: You might want to look at the Domain Events Pattern and code sample by Udi Dahan. It is has the same basic principle to the code snippet posted by Chad. Martin Fowler has also written about the pattern and provides a little more information on the topic.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have classes that need to communicate with each other. The problem is that if you make one contain the other (a child parent relationship) then things get tricky. You either need to pass an instance of the parent into the child, (then which one do you create first if you are using dependency injection) or you can use delegates/events. But I want to enforce the fact that the parent must be able to handle the event that the child raises. Not too sure how to do that. I also don't want multiple subscribers to the event.

The parent-child relationship just feels wrong for two way communication. Unfortunately it is not a case that one of the objects always initiates and the other responds. Either can initiate and the other should respond.

Is there another pattern that I am missing?

UPDATE:
Sorry this is quite hard to explain. I forgot to add that when one class sends a message to another class it is not expecting the response immediately. The response comes in asynchronously which is why you either need an instance of the parent to call the right method or a delegate/event. Sorry the example below is pseudo code. Hopefully it is enough to get the idea. Should I look at the mediator pattern.

public class Foo
    {
        public void SendMessageAToBar()
        {
            MessageA msg = new MessageA();
            Bar.ReceiveMessageAFromFoo(msg);
        }

        public void ReceiveMessageARespFromBar(MessageAResp msgResp)
        {
            //Got a response do something
        }

        public void ReceiveMessageBFromBar(MessageB msg)
        {
            //Do something msg
            MessageBResp msgBResp = new MessageBResp();
            Bar.ReceiveMessageBRespFromFoo()
        }
    }

    public class Bar
    {

        public void ReceiveMessageAFromFoo(MessageA msg)
        {
            //DO something.
            MessageAResp resp = new MessageAResp();
            Foo.ReceiveMessageARespFromBar(resp);
        }

        public void SendMessageBToFoo()
        {
            MessageB msg = new MessageB();
            Foo.ReceiveMessageBFromBar(msg);
        }

        public void ReceiveMessageBRespFromFoo(MessageBResp msgResp)
        {
            //Got a response do something
        }
    }


问:
Showing Pandas data frame as a table
since I have installed the updated version of pandas every time I type in the name of a dataframe, e.g.

```<code>df[0:5]
</code>```

To see the first few rows, it gives me a summary of the columns, the number of values in them and the data types instead.

How do I get to see the tabular view instead? (I am using iPython btw).

Thanks in advance!

答:
First Step :
I am using this to get GUI in pydev of eclipse. Make sure your pydev has GUI set . Use this tutorial : http://popdevelop.com/2010/04/setting-up-ide-and-creating-a-cross-platform-qt-python-gui-application/ for doing that.

Second Step :
taking examples from here Fastest way to populate QTableView from Pandas data frame
and doing some modification,
run the below code once :

```<code>import pandas as pd
from PyQt5 import QtCore, QtGui ,QtWidgets
class PandasModel2(QtCore.QAbstractTableModel):
    """
    Class to populate a table view with a pandas dataframe
    """
    def __init__(self, data, parent=None):
        QtCore.QAbstractTableModel.__init__(self, parent)
        self._data = data

    def rowCount(self, parent=None):
        return self._data.shape[0]

    def columnCount(self, parent=None):
        return self._data.shape[1]

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if index.isValid():
            if role == QtCore.Qt.DisplayRole:
                return str(self._data.iloc[index.row(), index.column()])
        return None

    def headerData(self, col, orientation, role):
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            return self._data.columns[col]
        return None

view = QtWidgets.QTableView()
</code>```

Once this is done . All you need is simply type the below commands and you can have the GUI

```<code>view.setModel(PandasModel2("your dataframe name"))
view.show()
</code>```

Title: Showing Pandas data frame as a table

Body:
since I have installed the updated version of pandas every time I type in the name of a dataframe, e.g.

df[0:5]

To see the first few rows, it gives me a summary of the columns, the number of values in them and the data types instead.

How do I get to see the tabular view instead? (I am using iPython btw).

Thanks in advance!

Body:
First Step :
I am using this to get GUI in pydev of eclipse. Make sure your pydev has GUI set . Use this tutorial : http://popdevelop.com/2010/04/setting-up-ide-and-creating-a-cross-platform-qt-python-gui-application/ for doing that.

Second Step :
taking examples from here Fastest way to populate QTableView from Pandas data frame
and doing some modification,
run the below code once :

import pandas as pd
from PyQt5 import QtCore, QtGui ,QtWidgets
class PandasModel2(QtCore.QAbstractTableModel):
    """
    Class to populate a table view with a pandas dataframe
    """
    def __init__(self, data, parent=None):
        QtCore.QAbstractTableModel.__init__(self, parent)
        self._data = data

    def rowCount(self, parent=None):
        return self._data.shape[0]

    def columnCount(self, parent=None):
        return self._data.shape[1]

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if index.isValid():
            if role == QtCore.Qt.DisplayRole:
                return str(self._data.iloc[index.row(), index.column()])
        return None

    def headerData(self, col, orientation, role):
        if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
            return self._data.columns[col]
        return None

view = QtWidgets.QTableView()

Once this is done . All you need is simply type the below commands and you can have the GUI

view.setModel(PandasModel2("your dataframe name"))
view.show()


问:
Chrome HID API extensions support
Does Chrome HID API are supported by extensions or only by apps? Chrome apps will be phased out and we need to understand if HID API can be used with extensions</p>

答:
From what I can tell, it is disabled in chrome extesnions.

The only exceptions are Google's own U2F extensions, that are built-in and use HID. However those cannot be modified by user.

Title: Chrome HID API extensions support


问:
Where is the documentation that explains chaining a field name after findOne() in Mongo?
MongoDB's documentation for find() talks about chaining limit() and sort() to a query. The documentation for findOne() makes no mention of chaining these methods or anything else for that matter.

In the collection widgets, if we run db.widgets.findOne({}, {name:1}), we get this:

```<code>{
  "_id": ObjectId("58bfaba203063eab31a1923e"),
  "name": "Deluxe spinning widget"
}
</code>```

But if we chain name to the prior command, as in db.widgets.findOne({}, {name:1}).name, we get just the value of name, like this:

```<code> Deluxe spinning widget
</code>```

Is there any documentation behind this?

If not, would it be correct to say that this example is not chaining at all but simple dot notation to retrieve the value of a key in an object?

答:
Is there any documentation behind this?

This is standard behaviour of javascript. As such, it is not explicitly described in mongodb documentation, there's no need.

If not, would it be correct to say that this example is not chaining at all but simple dot notation to retrieve the value of a key in an object?

Correct.

Body:
MongoDB's documentation for find() talks about chaining limit() and sort() to a query. The documentation for findOne() makes no mention of chaining these methods or anything else for that matter.

In the collection widgets, if we run db.widgets.findOne({}, {name:1}), we get this:

{
  "_id": ObjectId("58bfaba203063eab31a1923e"),
  "name": "Deluxe spinning widget"
}

But if we chain name to the prior command, as in db.widgets.findOne({}, {name:1}).name, we get just the value of name, like this:

 Deluxe spinning widget

Is there any documentation behind this?

If not, would it be correct to say that this example is not chaining at all but simple dot notation to retrieve the value of a key in an object?


问:
Extending VC++ compiler for instrumentation
I am very new to the windows world and development. I want to extend the VC++ compiler so that I can add some instrumentation instructions in a "pass" before creating the final shared lib. I googled somewhat, read some docs, installed Visual Studio and the compiler to play around but haven't been able to find a straightforward solution.  Any pointers will be really helpful

Thanks

答:
What you described seems close to Profile Guided Optimization in Visual Studio:
https://msdn.microsoft.com/en-us/library/e7k32f4k.aspx.
Not sure if it allows you to provide your own instrumentation database though, but, worth a look: https://msdn.microsoft.com/en-us/library/438sd1tf.aspx </p>

ContentLicense: CC BY-SA 4.0


问:
How to call another api via express?
My goal is to put http://localhost:3000/test into my browser and get the response from http://my_virtual_machine:8080/rest/stuff/test.

I followed this tutorial to setup Express, mongoose (although the final version of this will not connect to Mongo, only the VM's endpoints), etc. I produced a to-do list API, and it works as expected.

However, I can't figure out how to call my VM with this API.

I read "External API Calls With Express, Node.JS and Require Module", and came up with the following addition to server.js:

```<code>router = express.Router(),
request = require('request');

router.get("/test", function(req,res,next){
    request({
        uri: 'http://my_virtual_machine:8080/rest/stuff/test/',
    }).pipe(res)
})
</code>```

But, when I put http://localhost:3000/test into my browser I get a 404 error in the console.

Here's a PLUNK of all my code. server.js contains the changes I have made to try to get this to work.

I'm an Express noob, so I'm not sure why this doesn't work.

答:
You need to add the router to the express app instance. This can be done using

```<code>app.use('/test', router);
</code>```

The above line tells express to route all requests to /test to your router instance.

And inside your router, since you already specified the path, you should change the get function to

```<code>router.get('/', function(req, res, next) {
     request({
         uri: 'http://my_virtual_machine:8080/rest/stuff/test/',
     }).pipe(res)
});
</code>```

Title: How to call another api via express?

Body:
My goal is to put http://localhost:3000/test into my browser and get the response from http://my_virtual_machine:8080/rest/stuff/test.

I followed this tutorial to setup Express, mongoose (although the final version of this will not connect to Mongo, only the VM's endpoints), etc. I produced a to-do list API, and it works as expected.

However, I can't figure out how to call my VM with this API.

I read "External API Calls With Express, Node.JS and Require Module", and came up with the following addition to server.js:

router = express.Router(),
request = require('request');

router.get("/test", function(req,res,next){
    request({
        uri: 'http://my_virtual_machine:8080/rest/stuff/test/',
    }).pipe(res)
})

But, when I put http://localhost:3000/test into my browser I get a 404 error in the console.

Here's a PLUNK of all my code. server.js contains the changes I have made to try to get this to work.

I'm an Express noob, so I'm not sure why this doesn't work.

Body:
You need to add the router to the express app instance. This can be done using

app.use('/test', router);

The above line tells express to route all requests to /test to your router instance.

And inside your router, since you already specified the path, you should change the get function to

router.get('/', function(req, res, next) {
     request({
         uri: 'http://my_virtual_machine:8080/rest/stuff/test/',
     }).pipe(res)
});


问:
python panda join dynamic columns by removing duplicates
we have an use case where we need to join all column values in a row by removing duplicates.Data is stored in a data frame of panda.
For eg consider below data frame df  with columns A,B,C

```<code>A   B   C
X1  AX  X1
X2  X2  X1
X3  X3  X3
X4  XX  XX
</code>```

I would like to add a new column which concatenates A to B to C and remove duplicates if any found by preserving the order. The output would be like

```<code>A   B   C   Newcol

X1  AX  X1  X1_AX
X2  X2  X1  X2_X1
X3  X3  X3  X3
X4  XX  XX  X4_XX
</code>```

Note that the number of columns are dynamic.
As of now I am doing it by using the command

```<code>df.apply(lambda x: '-'.join(x.dropna().astype(str).drop_duplicates()),axis=1)
</code>```

But this is very slow and takes around 150 seconds for my data.
But since 90% of the data frame are usually with only 2 columns , I put an if statement in my code and run the below command for cases with 2 columns

```<code>t1=pd.Series(np.where(df.iloc[:,0].dropna().astype(str) != df.iloc[:,1].dropna().astype(str), df.iloc[:,0].dropna().astype(str)+"-"+df.iloc[:,1].dropna().astype(str),df.iloc[:,1].dropna().astype(str)))
</code>```

which takes around 55.3 milli seconds

or even

```<code>t1=df.iloc[:,0].dropna().astype(str).where(df.iloc[:,0].dropna().astype(str) == df.iloc[:,1].dropna().astype(str), df.iloc[:,0].dropna().astype(str)+"-"+df.iloc[:,1].dropna().astype(str))
</code>```

both consumes almost same time ( 55 ms opposed to 150 seconds ), but issue is that it is applicable only for 2 columns.
I would like to create a generalised statement , so that it can handle n number of columns.
I tried using reduce on top ,but it gave  error while i tried for 3 columns.

```<code>reduce((lambda x,y:pd.Series(np.where(df.iloc[:,x].dropna().astype(str) != df.iloc[:,y].dropna().astype(str), df.iloc[:,x].dropna().astype(str)+"-"+df.iloc[:,y].dropna().astype(str),df.iloc[:,y].dropna().astype(str)))),list(range(df.shape[1])))
</code>```

TypeError: '>=' not supported between instances of 'str' and 'int'

Please note that the df is actually a chunk of a multicore parallel task. So it would be great if the suggestions excludes parallelism.

答:
pd.unique doesn't sort.  Use it wrapped in a comprehension

```<code>df.assign(new_col=['_'.join(pd.unique(row)) for row in df.values])

    A   B   C new_col
0  X1  AX  X1   X1_AX
1  X2  X2  X1   X2_X1
2  X3  X3  X3      X3
3  X4  XX  XX   X4_XX
</code>```

Handle NaN

```<code>df.assing(new_col=[
        '_'.join(pd.unique([i for i in row if pd.notnull(i)])) for row in df.values
    ])
</code>```

Body:
we have an use case where we need to join all column values in a row by removing duplicates.Data is stored in a data frame of panda.
For eg consider below data frame df  with columns A,B,C

A   B   C
X1  AX  X1
X2  X2  X1
X3  X3  X3
X4  XX  XX

I would like to add a new column which concatenates A to B to C and remove duplicates if any found by preserving the order. The output would be like

A   B   C   Newcol

X1  AX  X1  X1_AX
X2  X2  X1  X2_X1
X3  X3  X3  X3
X4  XX  XX  X4_XX

Note that the number of columns are dynamic.
As of now I am doing it by using the command

df.apply(lambda x: '-'.join(x.dropna().astype(str).drop_duplicates()),axis=1)

But this is very slow and takes around 150 seconds for my data.
But since 90% of the data frame are usually with only 2 columns , I put an if statement in my code and run the below command for cases with 2 columns

t1=pd.Series(np.where(df.iloc[:,0].dropna().astype(str) != df.iloc[:,1].dropna().astype(str), df.iloc[:,0].dropna().astype(str)+"-"+df.iloc[:,1].dropna().astype(str),df.iloc[:,1].dropna().astype(str)))

which takes around 55.3 milli seconds

or even

t1=df.iloc[:,0].dropna().astype(str).where(df.iloc[:,0].dropna().astype(str) == df.iloc[:,1].dropna().astype(str), df.iloc[:,0].dropna().astype(str)+"-"+df.iloc[:,1].dropna().astype(str))

both consumes almost same time ( 55 ms opposed to 150 seconds ), but issue is that it is applicable only for 2 columns.
I would like to create a generalised statement , so that it can handle n number of columns.
I tried using reduce on top ,but it gave  error while i tried for 3 columns.

reduce((lambda x,y:pd.Series(np.where(df.iloc[:,x].dropna().astype(str) != df.iloc[:,y].dropna().astype(str), df.iloc[:,x].dropna().astype(str)+"-"+df.iloc[:,y].dropna().astype(str),df.iloc[:,y].dropna().astype(str)))),list(range(df.shape[1])))

TypeError: '>=' not supported between instances of 'str' and 'int'

Please note that the df is actually a chunk of a multicore parallel task. So it would be great if the suggestions excludes parallelism.

Body:
pd.unique doesn't sort.  Use it wrapped in a comprehension

df.assign(new_col=['_'.join(pd.unique(row)) for row in df.values])

    A   B   C new_col
0  X1  AX  X1   X1_AX
1  X2  X2  X1   X2_X1
2  X3  X3  X3      X3
3  X4  XX  XX   X4_XX

Handle NaN

df.assing(new_col=[
        '_'.join(pd.unique([i for i in row if pd.notnull(i)])) for row in df.values
    ])


答:
It is a bit difficult to provide a good answer, since your question is a bit abstract.
But, what about the Mediator pattern ?</p>

Title: What is the best pattern for two way communication between classes?


问:
Javascript: How to count number of instances of a phrase in a larger string?
I need to create a javacript function that downloads the html source code of a web page and returns the number of times a CSS class is mentioned.

```<code>var str = document.body.innerHTML;
function getFrequency(str) {
    var freq = {};
    for (var i=0; i<string.length;i++) {
        var css_class = "ENTER CLASS HERE";
        if (freq[css_class]) {
           freq[css_class]++;
        } else {
           freq[css_class] = 1;
        }
    }

    return freq;
};
</code>```

What am I doing wrong here?

答:
What am I doing wrong here?

I hate to say it, but fundamentally... everything. Getting information about HTML does not involve string functions or regular expressions. HTML cannot be dealt with this way, its rules are way too complex.

HTML needs to be parsed by an HTML parser.

In the browser there are two possible scenarios:

If you work with the current document (as you seem to do), then the parsing is already done by the browser.

Counting the number of times a CSS class is used actually is the same thing as finding out how many HTML elements have that class. And that is easily done via document.querySelectorAll() and a CSS selector.

```<code>var elements = document.querySelectorAll(".my-css-class");
alert("There are " + elements.length + " occurrences of the class.");
</code>```

If you have an HTML string that you loaded from somewhere, you need to parse it first. In JavaScript you can make the browser parse the HTML for you very easily:

```<code>var html = '<div class="my-css-class">some random HTML</div>';
var div = document.createElement("div");
div.innerHTML = html; // parsing happens here
</code>```

Now you can employ the same strategy as above, only with div as your selector context:

```<code>var elements = div.querySelectorAll(".my-css-class");
alert("There are " + elements.length + " occurrences of the class.");
</code>```

Body:
I need to create a javacript function that downloads the html source code of a web page and returns the number of times a CSS class is mentioned.

var str = document.body.innerHTML;
function getFrequency(str) {
    var freq = {};
    for (var i=0; i<string.length;i++) {
        var css_class = "ENTER CLASS HERE";
        if (freq[css_class]) {
           freq[css_class]++;
        } else {
           freq[css_class] = 1;
        }
    }

    return freq;
};

What am I doing wrong here?

Body:
What am I doing wrong here?

I hate to say it, but fundamentally... everything. Getting information about HTML does not involve string functions or regular expressions. HTML cannot be dealt with this way, its rules are way too complex.

HTML needs to be parsed by an HTML parser.

In the browser there are two possible scenarios:

If you work with the current document (as you seem to do), then the parsing is already done by the browser.

Counting the number of times a CSS class is used actually is the same thing as finding out how many HTML elements have that class. And that is easily done via document.querySelectorAll() and a CSS selector.

var elements = document.querySelectorAll(".my-css-class");
alert("There are " + elements.length + " occurrences of the class.");

If you have an HTML string that you loaded from somewhere, you need to parse it first. In JavaScript you can make the browser parse the HTML for you very easily:

var html = '<div class="my-css-class">some random HTML</div>';
var div = document.createElement("div");
div.innerHTML = html; // parsing happens here

Now you can employ the same strategy as above, only with div as your selector context:

var elements = div.querySelectorAll(".my-css-class");
alert("There are " + elements.length + " occurrences of the class.");


问:
Is there any way to accept only numeric values in a JTextField?
Is there any way to accept only numeric values in a JTextField?  Is there any special method for this?

答:
A very easy solution is to use a action listener.

```<code>TextFieldActionPerformed(java.awt.event.ActionEvent evt) {
    String textFieldValue = TextField.getText();
    try {
        Integer.parseInteger(textFieldValue);
    } catch(Exception e){
        JOptionPane.showMessageDialog(null, "Please insert Valid Number Only");
        TextField.setText(textFieldValue.substring(0,textFieldValue.length()-1));
    }
}
</code>```

You Can use it for Double as well:

```<code>Double.parseDouble(TextField.getText());
</code>```

Body:
A very easy solution is to use a action listener.

TextFieldActionPerformed(java.awt.event.ActionEvent evt) {
    String textFieldValue = TextField.getText();
    try {
        Integer.parseInteger(textFieldValue);
    } catch(Exception e){
        JOptionPane.showMessageDialog(null, "Please insert Valid Number Only");
        TextField.setText(textFieldValue.substring(0,textFieldValue.length()-1));
    }
}

You Can use it for Double as well:

Double.parseDouble(TextField.getText());


问:
I am creating an email spammer, for an outstanding cause
In Cuba, web access is extremely censored, so I created a tool that allows more than 50,000 people to browse the Internet through email. Cubans send me an email with an URL in the subject line, and I email them back with the response. Read more at https://apretaste.com.

It was working like a charm, till the communist government of Cuba started blocking my emails. My solution was rotation.

I started with Amazon SES, and I was changing the domain each time it was blocked, but Amazon adds a header to all emails, and once they blocked the header no email from SES was able to reach Cuba any more. The same happened with Mailgun and others, they all add headers.

Currently I am creating Gmail accounts and sending via SMTP, but Google blocks me for no reason and only allows to send 100 emails a day per account. Also I can only create few emails using the same IP address/phone, so I was forced to use anonymous proxies and fake Chinese phones. Now I am fighting a war on two fronts.

An email can be blocked by three parameters: IP address, domain, and email address.

It will be terrific if I can set up my own Postfix server at a VPS that auto-rotates the IP address. Even better if I can simulate "gmail.com", to avoid purchasing a new domain every day.

All the intents to create what I call "the ultimate sender" just either reach the spam folder or add unwanted headers making it too easy to block. I feel exhausted. I hit a knowledge barrier here.

I know I am crossing to the dark side, but this is for a very good cause. Thousands count on this service as their only source of unbiased news, social network and to feel part of the 21st century.

Can you please help me implementing "the ultimate sender", or pointing to another solution that I may be missing?

答:
Crowd source it.
Find a way that volunteers can send some emails for you. This is the only long term approach that I can think of. A simple web interface with mail to links would be be enough to get started although there are other potential problems with this approach too.

Because you are talking about low numbers of users, you could also use crowdsourcing to create the single email address per person approach. They can create an account on a specific set of email providers and give you the credentials.  This would allow the single email per user approach or could be used to rotate through a large set of email accounts to send emails.


问:
Prolog member/2 predicate
Why does prolog answer false to: member([5], [2, 5]).?

Is there a way to work around it?

Any help will be greatly appreciated.

答:
It could be that you are looking for another predicate?

From the SWI Prolog documentation for subset/2:

subset( +SubSet, +Set )

  True if all elements of SubSet belong to Set as well.

It works as expected:

```<code>Welcome to SWI-Prolog (threaded, 64 bits, version 7.5.5)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.

?- subset([5], [2, 5]).
true.

?- subset([5, 3], [2, 3, 5, 7]).
true.

?- subset([5, 3], [2, 5]).
false.
</code>```

Title: Prolog member/2 predicate

Body:
It could be that you are looking for another predicate?

From the SWI Prolog documentation for subset/2:

subset( +SubSet, +Set )

  True if all elements of SubSet belong to Set as well.

It works as expected:

Welcome to SWI-Prolog (threaded, 64 bits, version 7.5.5)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.

?- subset([5], [2, 5]).
true.

?- subset([5, 3], [2, 3, 5, 7]).
true.

?- subset([5, 3], [2, 5]).
false.


问:
Visual Studio 2008 user controls registered in the web.config not registering with intellisense
I have a C# Web application built in Visual Studio 2008 where we rely heavily on user controls for 'pre-built' blocks of ASP.NET.

Instead of registering a big stack of user controls on each page, we register all the controls in a local (to a specific folder) web.config file. The advantage is that we can use the controls and the pages look 'cleaner' in source view. However, neither the VS2008 Design view nor Intellisense recognize the fact the controls are registered in web.config. However, the application itself works as expected.

Normally at the top of each page we'd have a tag like this:

```<code><%@ Register src="~/CommonControls/Foo.ascx" tagname="Foo" tagprefix="Bar" %>
</code>```

And we register the controls in a local web.config like so:

```<code><?xml version="1.0"?>
<configuration>
    <system.web>
        <pages>
            <controls>
                <add src="~/CommonControls/Foo.ascx" tagName="Foo" tagPrefix="Bar"/>
            </controls>
        </pages>
    </system.web>
</configuration>
</code>```

Does anyone know of a fix for getting Intellisense to recognize these custom controls? Or, is there a 'better' way of doing this?

答:
I tried your sample code and Intellisense works in both the code view of the aspx page and the code behind page.  You might check the class names of your user controls, visual studio includes the folder name in the class name by default.  So your control may be named CommonControls_Foo instead of Foo as you would expect.

Either way the web.config file has nothing to do with the Intellisense of the code behind. Check the name and namespace of the class.

OwnerDisplayName: Mike McClelland

Body:
I have a C# Web application built in Visual Studio 2008 where we rely heavily on user controls for 'pre-built' blocks of ASP.NET.

Instead of registering a big stack of user controls on each page, we register all the controls in a local (to a specific folder) web.config file. The advantage is that we can use the controls and the pages look 'cleaner' in source view. However, neither the VS2008 Design view nor Intellisense recognize the fact the controls are registered in web.config. However, the application itself works as expected.

Normally at the top of each page we'd have a tag like this:

<%@ Register src="~/CommonControls/Foo.ascx" tagname="Foo" tagprefix="Bar" %>

And we register the controls in a local web.config like so:

<?xml version="1.0"?>
<configuration>
    <system.web>
        <pages>
            <controls>
                <add src="~/CommonControls/Foo.ascx" tagName="Foo" tagPrefix="Bar"/>
            </controls>
        </pages>
    </system.web>
</configuration>

Does anyone know of a fix for getting Intellisense to recognize these custom controls? Or, is there a 'better' way of doing this?

LastEditorDisplayName: Gortok

OwnerDisplayName: Seth Reno

LastEditorDisplayName: Seth Reno


问:
Transform SQL Table
We have a table that has the following format

```<code>RecordID FieldName FieldValue

1         Name      John
1         Age       30
2         Name      Alice
2         Age       40
</code>```

We would like to present this as:

```<code>John   30
Alice  40
</code>```

Anyone have a good solution for this?

答:
This ain't pretty (but nor's the data), but this will work if your column names are known when you write the query:

```<code>SELECT
RecordId,
group_concat( if( FieldName = 'name', FieldValue, '' ) SEPARATOR '' ) AS person_name,
group_concat( if( FieldName = 'age', FieldValue, '' ) SEPARATOR '' ) AS person_age
FROM test_table
GROUP BY RecordId
</code>```

(works in MySQL 5.0)

You should also use CAST to get the fields to the correct type

If you don't know the fields, you'll need to (programatically) do a select distinct FieldName beforehand in order to build your query

I've a feeling the the Drupal Content Creation Kit (CCK) does something rather similar to this

Title: Transform SQL Table

Body:
We have a table that has the following format

RecordID FieldName FieldValue

1         Name      John
1         Age       30
2         Name      Alice
2         Age       40

We would like to present this as:

John   30
Alice  40

Anyone have a good solution for this?

Body:
This ain't pretty (but nor's the data), but this will work if your column names are known when you write the query:

SELECT
RecordId,
group_concat( if( FieldName = 'name', FieldValue, '' ) SEPARATOR '' ) AS person_name,
group_concat( if( FieldName = 'age', FieldValue, '' ) SEPARATOR '' ) AS person_age
FROM test_table
GROUP BY RecordId

(works in MySQL 5.0)

You should also use CAST to get the fields to the correct type

If you don't know the fields, you'll need to (programatically) do a select distinct FieldName beforehand in order to build your query

I've a feeling the the Drupal Content Creation Kit (CCK) does something rather similar to this


问:
Filter a Pandas DataFrame Through a Dictionary
I have a pandas dataframe with a number of columns. (Please see the table below.) Each column belongs to a group categorization G1-G4. This mapping of groups is in a data dictionary. If I want to filter the columns in the pandas dataframe based on the grouping data dictionary, for example to filter out all G3 and produce the resulting table below, what is the most efficient way of doing this?

Thank you.

Body:
I'm late to the party, but here's an another way to do this:

import pandas as pd
import numpy as np

filter_dict = {'T1': 'G1', 'T2': 'G3', 'T3': 'G3', 'T4': 'G1', 'T5': 'G2'}

#some play data
dta = np.random.rand(10,5)
rows = pd.date_range('1-Jan-2001', periods=10)
cols = ['T'+ str(x) for x in range(1,6)]
df = pd.DataFrame(dta, rows, cols)

'''
                  T1        T2        T3        T4        T5
2001-01-01  0.981817  0.590287  0.421105  0.060628  0.007345
2001-01-02  0.643111  0.813921  0.301809  0.414912  0.116028
2001-01-03  0.366478  0.582521  0.997483  0.642552  0.662618
2001-01-04  0.485125  0.062310  0.278239  0.838958  0.174067
2001-01-05  0.953075  0.612431  0.204880  0.258736  0.551282
2001-01-06  0.633442  0.852040  0.338404  0.137305  0.114481
2001-01-07  0.828730  0.477185  0.456451  0.560955  0.713365
2001-01-08  0.860316  0.809366  0.656306  0.728917  0.383045
2001-01-09  0.492210  0.639744  0.511768  0.623203  0.495040
2001-01-10  0.956224  0.188009  0.938048  0.999993  0.556607
'''

#convert wide to long cleanup the index and col names
df1 = df.stack()\
        .reset_index()\
        .rename(columns={'level_0':'date','level_1':'ticker', 0:'val'})\
        .reset_index('date')

#map ticker to group
df1['grp'] = df1.ticker.map(filter_dict)

#select stuff not in group 3 and pivot to wide format
df1[df1.grp != 'G3'].pivot('date','ticker','val')

'''
ticker            T1        T4        T5
date
2001-01-01  0.981817  0.060628  0.007345
2001-01-02  0.643111  0.414912  0.116028
2001-01-03  0.366478  0.642552  0.662618
2001-01-04  0.485125  0.838958  0.174067
2001-01-05  0.953075  0.258736  0.551282
2001-01-06  0.633442  0.137305  0.114481
2001-01-07  0.828730  0.560955  0.713365
2001-01-08  0.860316  0.728917  0.383045
2001-01-09  0.492210  0.623203  0.495040
2001-01-10  0.956224  0.999993  0.556607
'''


问:
Responsible design - don't process all the elements
I am testing responsible design for defined standard resolutions (defined resolutions are get from FireFox). If page width is set to maximum width 650px all works, but if I change browser width to 651px and more, CSS code is not process. I don't see problem.

        window.onresize = displayWindowSize;
        window.onload = displayWindowSize;

        function displayWindowSize() {
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
            // your size calculation code here
            document.getElementById("responsible-design-debug").innerHTML = "Responsible design debug: " + myWidth + "x" + myHeight;
        };```
<pre class="snippet-code-css lang-css prettyprint-override"><code>        body {
            background-color: #F5F5F5;
            font-family: Verdana, Geneva, Tahoma, sans-serif;
            font-size: 0.8em;
        }

        .Logo {
            height: 35px;
            margin-bottom: 15px;
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  1920px and more
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 1920px) {
            .responsible-design-debug {
                background-color: green;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  1280px - 1920px
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 1280px) and (max-width: 1919px) {
            .responsible-design-debug {
                background-color: lightgreen;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  980px - 1280px
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 980px) and (max-width: 1279px) {
            .responsible-design-debug {
                background-color: red;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  800px - 980px
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 800px) and (max-width: 979px) {
            .responsible-design-debug {
                background-color: orange;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  768px - 800px
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 768px) and (max-width: 799px) {
            .responsible-design-debug {
                background-color: blueviolet;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  360px - 768px
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 360px) and (max-width: 767px) {
            .responsible-design-debug {
                background-color: blue;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  320px - 360px
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 320px) and (max-width: 359px) {
            .responsible-design-debug {
                background-color: aqua;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  0px - 320px
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 0px) and (max-width: 319px) {
            .responsible-design-debug {
                background-color: yellow;
                float: left;
            }
        }</code>```

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Responsible design</title>

Responsible design debug: init

Lorem ipsum dolor sit amet consectetuer In et elit diam arcu. Lacus enim molestie dictumst quis convallis pellentesque consectetuer ipsum ligula pellentesque. Nullam elit nunc amet et nec semper lacus ac lacinia et. At Sed Proin tempor lacus tristique senectus eu est lacinia dui. Nisl Ut Vestibulum ac Vestibulum Phasellus lacinia ut auctor consequat felis. Sapien dolor Morbi Ut fringilla at molestie eu.

Augue sodales est ligula eget cursus quis id orci magna et. Dapibus ac elit diam pede mauris Nam interdum adipiscing et suscipit. Nonummy justo laoreet In elit magna condimentum enim quis non tempor. Malesuada eget habitant ligula ut consequat ut felis amet libero cursus. Lobortis tellus volutpat pellentesque leo ipsum id Vestibulum suscipit convallis Donec. Amet eget dui.

```

Thank you and best regards,
 Petr

答:
It's because you're using and (orientation: portrait), so once the width of the window has a higher value than the height, none of your CSS will be taken into account because it's considered landscape orientation at that point. If you remove that from all your media queries it will work as expected:

window.onresize = displayWindowSize;
window.onload = displayWindowSize;

function displayWindowSize() {
  myWidth = window.innerWidth;
  myHeight = window.innerHeight;
  // your size calculation code here
  document.getElementById("responsible-design-debug").innerHTML = "Responsible design debug: " + myWidth + "x" + myHeight;
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
            background-color: #F5F5F5;
            font-family: Verdana, Geneva, Tahoma, sans-serif;
            font-size: 0.8em;
        }

        .Logo {
            height: 35px;
            margin-bottom: 15px;
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  1920px and more

        **/
        @media screen and (min-width: 1920px) {
            .responsible-design-debug {
                background-color: green;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  1280px - 1920px
        **/
        @media screen and (min-width: 1280px) and (max-width: 1919px) {
            .responsible-design-debug {
                background-color: lightgreen;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  980px - 1280px
        **/
        @media screen and (min-width: 980px) and (max-width: 1279px) {
            .responsible-design-debug {
                background-color: red;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  800px - 980px
        **/
        @media screen and (min-width: 800px) and (max-width: 979px) {
            .responsible-design-debug {
                background-color: orange;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  768px - 800px
        **/
        @media screen and (min-width: 768px) and (max-width: 799px) {
            .responsible-design-debug {
                background-color: blueviolet;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  360px - 768px
        **/
        @media screen and (min-width: 360px) and (max-width: 767px) {
            .responsible-design-debug {
                background-color: blue;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  320px - 360px
        **/
        @media screen and (min-width: 320px) and (max-width: 359px) {
            .responsible-design-debug {
                background-color: aqua;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  0px - 320px
        **/
        @media screen and (min-width: 0px) and (max-width: 319px) {
            .responsible-design-debug {
                background-color: yellow;
                float: left;
            }
        }</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Responsible design</title>

Responsible design debug: init

Lorem ipsum dolor sit amet consectetuer In et elit diam arcu. Lacus enim molestie dictumst quis convallis pellentesque consectetuer ipsum ligula pellentesque. Nullam elit nunc amet et nec semper lacus ac lacinia et. At Sed Proin tempor lacus tristique
      senectus eu est lacinia dui. Nisl Ut Vestibulum ac Vestibulum Phasellus lacinia ut auctor consequat felis. Sapien dolor Morbi Ut fringilla at molestie eu.

Augue sodales est ligula eget cursus quis id orci magna et. Dapibus ac elit diam pede mauris Nam interdum adipiscing et suscipit. Nonummy justo laoreet In elit magna condimentum enim quis non tempor. Malesuada eget habitant ligula ut consequat ut
      felis amet libero cursus. Lobortis tellus volutpat pellentesque leo ipsum id Vestibulum suscipit convallis Donec. Amet eget dui.

```

Body:
I am testing responsible design for defined standard resolutions (defined resolutions are get from FireFox). If page width is set to maximum width 650px all works, but if I change browser width to 651px and more, CSS code is not process. I don't see problem.

        window.onresize = displayWindowSize;
        window.onload = displayWindowSize;

        function displayWindowSize() {
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
            // your size calculation code here
            document.getElementById("responsible-design-debug").innerHTML = "Responsible design debug: " + myWidth + "x" + myHeight;
        };

        body {
            background-color: #F5F5F5;
            font-family: Verdana, Geneva, Tahoma, sans-serif;
            font-size: 0.8em;
        }

        .Logo {
            height: 35px;
            margin-bottom: 15px;
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  1920px and more
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 1920px) {
            .responsible-design-debug {
                background-color: green;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  1280px - 1920px
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 1280px) and (max-width: 1919px) {
            .responsible-design-debug {
                background-color: lightgreen;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  980px - 1280px
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 980px) and (max-width: 1279px) {
            .responsible-design-debug {
                background-color: red;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  800px - 980px
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 800px) and (max-width: 979px) {
            .responsible-design-debug {
                background-color: orange;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  768px - 800px
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 768px) and (max-width: 799px) {
            .responsible-design-debug {
                background-color: blueviolet;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  360px - 768px
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 360px) and (max-width: 767px) {
            .responsible-design-debug {
                background-color: blue;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  320px - 360px
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 320px) and (max-width: 359px) {
            .responsible-design-debug {
                background-color: aqua;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  0px - 320px
         * ORIENTATION: Portrait
        **/
        @media screen and (orientation: portrait) and (min-width: 0px) and (max-width: 319px) {
            .responsible-design-debug {
                background-color: yellow;
                float: left;
            }
        }

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Responsible design</title>

Responsible design debug: init

Lorem ipsum dolor sit amet consectetuer In et elit diam arcu. Lacus enim molestie dictumst quis convallis pellentesque consectetuer ipsum ligula pellentesque. Nullam elit nunc amet et nec semper lacus ac lacinia et. At Sed Proin tempor lacus tristique senectus eu est lacinia dui. Nisl Ut Vestibulum ac Vestibulum Phasellus lacinia ut auctor consequat felis. Sapien dolor Morbi Ut fringilla at molestie eu.

Augue sodales est ligula eget cursus quis id orci magna et. Dapibus ac elit diam pede mauris Nam interdum adipiscing et suscipit. Nonummy justo laoreet In elit magna condimentum enim quis non tempor. Malesuada eget habitant ligula ut consequat ut felis amet libero cursus. Lobortis tellus volutpat pellentesque leo ipsum id Vestibulum suscipit convallis Donec. Amet eget dui.

Thank you and best regards,
 Petr

Body:
It's because you're using and (orientation: portrait), so once the width of the window has a higher value than the height, none of your CSS will be taken into account because it's considered landscape orientation at that point. If you remove that from all your media queries it will work as expected:

window.onresize = displayWindowSize;
window.onload = displayWindowSize;

function displayWindowSize() {
  myWidth = window.innerWidth;
  myHeight = window.innerHeight;
  // your size calculation code here
  document.getElementById("responsible-design-debug").innerHTML = "Responsible design debug: " + myWidth + "x" + myHeight;
};

body {
            background-color: #F5F5F5;
            font-family: Verdana, Geneva, Tahoma, sans-serif;
            font-size: 0.8em;
        }

        .Logo {
            height: 35px;
            margin-bottom: 15px;
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  1920px and more

        **/
        @media screen and (min-width: 1920px) {
            .responsible-design-debug {
                background-color: green;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  1280px - 1920px
        **/
        @media screen and (min-width: 1280px) and (max-width: 1919px) {
            .responsible-design-debug {
                background-color: lightgreen;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  980px - 1280px
        **/
        @media screen and (min-width: 980px) and (max-width: 1279px) {
            .responsible-design-debug {
                background-color: red;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  800px - 980px
        **/
        @media screen and (min-width: 800px) and (max-width: 979px) {
            .responsible-design-debug {
                background-color: orange;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  768px - 800px
        **/
        @media screen and (min-width: 768px) and (max-width: 799px) {
            .responsible-design-debug {
                background-color: blueviolet;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  360px - 768px
        **/
        @media screen and (min-width: 360px) and (max-width: 767px) {
            .responsible-design-debug {
                background-color: blue;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  320px - 360px
        **/
        @media screen and (min-width: 320px) and (max-width: 359px) {
            .responsible-design-debug {
                background-color: aqua;
                float: left;
            }
        }

        /**
         * DEVICE:      Universally
         * DIMENSIONS:  0px - 320px
        **/
        @media screen and (min-width: 0px) and (max-width: 319px) {
            .responsible-design-debug {
                background-color: yellow;
                float: left;
            }
        }

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Responsible design</title>
</head>

<body>

  <div id="responsible-design-debug" class="responsible-design-debug">Responsible design debug: init</div>
  <img src="Image.png" alt="Image.png" class="Logo" />

  <div id="example">
    <p>Lorem ipsum dolor sit amet consectetuer In et elit diam arcu. Lacus enim molestie dictumst quis convallis pellentesque consectetuer ipsum ligula pellentesque. Nullam elit nunc amet et nec semper lacus ac lacinia et. At Sed Proin tempor lacus tristique
      senectus eu est lacinia dui. Nisl Ut Vestibulum ac Vestibulum Phasellus lacinia ut auctor consequat felis. Sapien dolor Morbi Ut fringilla at molestie eu.</p>
    <p>Augue sodales est ligula eget cursus quis id orci magna et. Dapibus ac elit diam pede mauris Nam interdum adipiscing et suscipit. Nonummy justo laoreet In elit magna condimentum enim quis non tempor. Malesuada eget habitant ligula ut consequat ut
      felis amet libero cursus. Lobortis tellus volutpat pellentesque leo ipsum id Vestibulum suscipit convallis Donec. Amet eget dui.</p>
  </div>

</body>

</html>


问:
Bintray does not link new artifact to Jcenter
We have a maven package published to Bintray and linked to Jcenter.

In version 1.1.0 we've added a new artifact to the package: koptional-reactor-extensions, and uploaded release to Bintray.

All the artifacts are visible on Bintray without problems: https://dl.bintray.com/gojuno/maven/com/gojuno/koptional/

However Jcenter only shows artifacts that were already published and does not show koptional-reactor-extensions: https://jcenter.bintray.com/com/gojuno/koptional/

Neither Bintray's Gradle plugin nor Bintray web ui shows why it does not show up and how can we link new artifact to the Jcenter, this is very, very confusing.

P.S. Previously I was able to solve similar issue only by asking a question on StackOverflow so I'm doing it here again (I've also contacted Bintray through Inbox on website but with no luck).

And to be clear, I've never had such problems with oss.sonatype.org.

答:
Thank you for your submitting this issue.

We have managed to resolve the issue you were experiencing.
The issue occurred due to the reason of artifactID that was not approved.

Usually in order to add packages to JCenter, we add only packages under 'groupID/groupID/artifactID'. Usually we approve only one path for package, but since we wanted to expedite the resolution for your issue we decided to approve the package with only groupID. (i.e /com/gojuno/koptional).
This means that all three artifactIDs (koptional, koptional-reactor-extensions, koptional-rxjava2-extensions) are now approved and synced to JCenter.

We hope this clarifies. Please let us know if you encounter any other issues.

Best Regards,
Yonatan Brand
JFrog Support


问:
Handling data from csv file with Python
I know Python is almost made for these kind of purposes, but I am really struggling to understand how I get access to specific values in the dataset, and I tried both with pandas and csv modules. It is probably a matter of syntax. Here's the thing: I have a csv file in the form of

```<code>Nation, Year, No. of refugees
Afghanistan,2013,6657
Albania,2013,199
Algeria,2013,91
Angola,2013,47
Armenia,2013,156
...
...
Afghanistan,2012,6960
Albania,2012,157
Algeria,2012,67
Angola,2012,43
Armenia,2012,143
...
</code>```

and so on. What I would like to do is to get the total amount of refugees per year, i.e. selecting all the rows with a certain year and summing all the elements in the related "no. of refugees" column. I managed to do this:

```<code>import csv

with open('refugees.csv', 'r') as f:
    d_reader = csv.DictReader(f)
    headers = d_reader.fieldnames
    print headers

    #2013
    list2013=[]
    for line in d_reader:
        if (line['Year']=='2013'):
            list2013.append(line['Refugees'])
    list2013=map(int,list2013) #I have str values in my file
    ref13=sum(list2013)
</code>```

but I am looking for a more elegant (and, above all, iterative) solution. Moreover, if I perform that procedure multiple times for different years, I always get 0: it works for 2013 only, not sure why.

Edit: I tried this as well, without success, but I think this could be totally wrong:

```<code>import csv
refugees_dict={}
a=range(2005,2014)
a=map(str, a)
with open('refugees.csv', 'r') as f:
    d_reader = csv.DictReader(f)

    for element in a:
        for line in d_reader:
            if (line['Year']==element):
                print 'hello!'
                temp_list=[]
                temp_list.append(line['Refugees'])
                temp_list=map(int, temp_list)
                refugees_dict[a]=sum(temp_list)

print refugees_dict
</code>```

The next step of my work will involve further studies on the dataset, eg I am probably gonna need to access data nation-wise instead of year-wise, and I really appreciate any hint so I understand how to manipulate data.
Thanks a lot.

答:
To sum by year you can try this:

```<code>f = open('file.csv').readlines()

f = [i.strip('\n').split(',') for i in f]

years = {i[1]:0 for i in f}

for i in f:
    years[i[1]] += int(i[-1])
</code>```

Now, you have a dictionary that has the sum of all the refugees by year.

To access nation-wise:

```<code>nations = {i[0]:0 for i in f}

for i in f:
    nations[i[0]] += int(i[-1])
</code>```

Title: Handling data from csv file with Python

Body:
I know Python is almost made for these kind of purposes, but I am really struggling to understand how I get access to specific values in the dataset, and I tried both with pandas and csv modules. It is probably a matter of syntax. Here's the thing: I have a csv file in the form of

Nation, Year, No. of refugees
Afghanistan,2013,6657
Albania,2013,199
Algeria,2013,91
Angola,2013,47
Armenia,2013,156
...
...
Afghanistan,2012,6960
Albania,2012,157
Algeria,2012,67
Angola,2012,43
Armenia,2012,143
...

and so on. What I would like to do is to get the total amount of refugees per year, i.e. selecting all the rows with a certain year and summing all the elements in the related "no. of refugees" column. I managed to do this:

import csv

with open('refugees.csv', 'r') as f:
    d_reader = csv.DictReader(f)
    headers = d_reader.fieldnames
    print headers

    #2013
    list2013=[]
    for line in d_reader:
        if (line['Year']=='2013'):
            list2013.append(line['Refugees'])
    list2013=map(int,list2013) #I have str values in my file
    ref13=sum(list2013)

but I am looking for a more elegant (and, above all, iterative) solution. Moreover, if I perform that procedure multiple times for different years, I always get 0: it works for 2013 only, not sure why.

Edit: I tried this as well, without success, but I think this could be totally wrong:

import csv
refugees_dict={}
a=range(2005,2014)
a=map(str, a)
with open('refugees.csv', 'r') as f:
    d_reader = csv.DictReader(f)

    for element in a:
        for line in d_reader:
            if (line['Year']==element):
                print 'hello!'
                temp_list=[]
                temp_list.append(line['Refugees'])
                temp_list=map(int, temp_list)
                refugees_dict[a]=sum(temp_list)

print refugees_dict

The next step of my work will involve further studies on the dataset, eg I am probably gonna need to access data nation-wise instead of year-wise, and I really appreciate any hint so I understand how to manipulate data.
Thanks a lot.

Body:
To sum by year you can try this:

f = open('file.csv').readlines()

f = [i.strip('\n').split(',') for i in f]

years = {i[1]:0 for i in f}

for i in f:
    years[i[1]] += int(i[-1])

Now, you have a dictionary that has the sum of all the refugees by year.

To access nation-wise:

nations = {i[0]:0 for i in f}

for i in f:
    nations[i[0]] += int(i[-1])


问:
angular-translate multiple keys in one element
In my application I am pulling translations keys from a single cell in a database table and displaying them dynamically in a setting page. Most will only have one key in the display object but there will be a number of entries that would have multiple.

Is there a way in angular-translate to have one element host multiple keys and translate them?

en.json={"title1":"balance","title2":"other stuff"}

ctrl.list=[{display:"title1 title2"}]

```<code><tbody class="validation-table-body">
  <tr ng-repeat="entry in ctrl.list">
    <td class="validation-name" >
      {{entry.display | translate}}
    </td>
  </tr>
</tbody>
</code>```

displayed:

```<code><td>title1 title2</td>
</code>```

expected:

```<code><td>balance other stuff</td>
</code>```

I am just trying to get this to work before trying to add a comma or something to display.

答:
This is possible in the translate directive at least:

```<code><ANY translate="{{toBeInterpolated}}"></ANY>
</code>```

toBeInterpolated is the name of the key to be looked up.

Ref:https://angular-translate.github.io/docs/#/guide/05_using-translate-directive

Body:
In my application I am pulling translations keys from a single cell in a database table and displaying them dynamically in a setting page. Most will only have one key in the display object but there will be a number of entries that would have multiple.

Is there a way in angular-translate to have one element host multiple keys and translate them?

en.json={"title1":"balance","title2":"other stuff"}

ctrl.list=[{display:"title1 title2"}]

      {{entry.display | translate}}

displayed:

title1 title2

expected:

balance other stuff

I am just trying to get this to work before trying to add a comma or something to display.

Body:
This is possible in the translate directive at least:

<ANY translate="{{toBeInterpolated}}"></ANY>

toBeInterpolated is the name of the key to be looked up.

Ref:https://angular-translate.github.io/docs/#/guide/05_using-translate-directive


问:
ASP.NET Mvc Button in jumbotron can't be moved up
I've tried margin-bottom, padding, top:5px; but nothing seems to be moving it.

Find out more! »

css contains too many stuff for me to find the css I need to change. Is there anyway I can change it from my Index view?

答: Try changing padding-bottom to a higher value in the jumbotron class. If you post your code or css it will be easier to identify the problem and help you.


问:
How to change the arrow color of the html select box?
I want to style a select element of bootstrap like the following picture provided:

but unfortunately couldn't change the color of the arrow.

#test{
    border: 1px solid #dd6592;
    border-radius: 0px;
    text-align: center;
    width:20%;
    font-size: 16px;
    margin-bottom: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<select class="form-control" id="test">
  <option>Test</option>
  <option>Test</option>
  <option>Test</option>
</select></code>```

答: If you are using Bootstrap, you should see right inside the button element a span with class "caret". You need to change the COLOR style. </p>

Body:
I want to style a select element of bootstrap like the following picture provided:

but unfortunately couldn't change the color of the arrow.

#test{
    border: 1px solid #dd6592;
    border-radius: 0px;
    text-align: center;
    width:20%;
    font-size: 16px;
    margin-bottom: 20px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

<select class="form-control" id="test">
  <option>Test</option>
  <option>Test</option>
  <option>Test</option>
</select>


答:
Since you tagged pandas in the question, here's a pandas solution to getting the number of refugees per year.

Let's say my input csv looks like this (note that I've eliminated the extra space before the column names):

```<code>Nation,Year,No. of refugees
Afghanistan,2013,6657
Albania,2013,199
Algeria,2013,91
Angola,2013,47
Armenia,2013,156
Afghanistan,2012,6960
Albania,2012,157
Algeria,2012,67
Angola,2012,43
Armenia,2012,143
</code>```

You can read that into a pandas DataFrame like this:

```<code>df = pd.read_csv('data.csv')
</code>```

You can then get the total like this:

```<code>df.groupby(['Year']).sum()
</code>```

This gives:

```<code>        No. of refugees
 Year
2012               7370
2013               7150
</code>```

Title: Handling data from csv file with Python

Body:
Since you tagged pandas in the question, here's a pandas solution to getting the number of refugees per year.

Let's say my input csv looks like this (note that I've eliminated the extra space before the column names):

Nation,Year,No. of refugees
Afghanistan,2013,6657
Albania,2013,199
Algeria,2013,91
Angola,2013,47
Armenia,2013,156
Afghanistan,2012,6960
Albania,2012,157
Algeria,2012,67
Angola,2012,43
Armenia,2012,143

You can read that into a pandas DataFrame like this:

df = pd.read_csv('data.csv')

You can then get the total like this:

df.groupby(['Year']).sum()

This gives:

        No. of refugees
 Year
2012               7370
2013               7150