答:
this is a perfect opportunity to use a groupingBy collector.

```<code>Map<String, List<User>> resultSet =
           unfilteredList.stream().collect(
                  Collectors.groupingBy(u -> u.getInterest().toLowerCase());
</code>```

now you can retrieve the list of users for a given key by doing:

```<code>List<User> java = resultSet.get("java");
List<User> c = resultSet.get("c");
List<User> javascript = resultSet.get("javascript");
</code>```

Title: Categorize objects in different lists depending on a property

Body:
this is a perfect opportunity to use a groupingBy collector.

Map<String, List<User>> resultSet =
           unfilteredList.stream().collect(
                  Collectors.groupingBy(u -> u.getInterest().toLowerCase());

now you can retrieve the list of users for a given key by doing:

List<User> java = resultSet.get("java");
List<User> c = resultSet.get("c");
List<User> javascript = resultSet.get("javascript");


来源: stackexchange

问:
Unable to get json web token from Flask
I have the below code for app.py:

```<code>from flask import Flask
from flask_jwt import JWT, jwt_required, current_identity
from werkzeug.security import safe_str_cmp

class User(object):
    def __init__(self, id, username, password):
        self.id = id
        self.username = username
        self.password = password

    def __str__(self):
        return "User(id='%s')" % self.id

users = [
    User(1, 'user1', 'abcxyz'),
    User(2, 'user2', 'abcxyz'),
]

username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}

def authenticate(username, password):
    user = username_table.get(username, None)
    if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
        return user

def identity(payload):
    user_id = payload['identity']
    return userid_table.get(user_id, None)

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'super-secret'

jwt = JWT(app, authenticate, identity)

@app.route('/protected')
@jwt_required()
def protected():
    return '%s' % current_identity

if __name__ == '__main__':
    app.run()
</code>```

When i try to make a post request to get the authentication token from Postman :
http://127.0.0.1:5000/auth

{
    "username": "joe",
    "password": "pass"
}

I get a peculiar error which i am not able to solve :

```<code>(flask-restful) C:\Users\bhatsubh\Projects\flask-restful>python Test.py
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 973-755-004
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [06/Sep/2017 13:38:08] "POST /auth HTTP/1.1" 500 -
Traceback (most recent call last):
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1985, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\_compat.py"
, line 33, in reraise
    raise value
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\_compat.py"
, line 33, in reraise
    raise value
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask_jwt\__init_
_.py", line 115, in _default_auth_request_handler
    username = data.get(current_app.config.get('JWT_AUTH_USERNAME_KEY'), None)
AttributeError: 'NoneType' object has no attribute 'get'
</code>```

I have absolutely no idea what is going wrong. Can someone please help me with this?

答:
make sure have set correct header

Content-Type:application/json

try curl for cross check

```<code>$ curl -H "Content-Type: application/json" -X POST -d '{ "username": "joe", "password": "pass" }' http://localhost:5000/auth
</code>```

ContentLicense: CC BY-SA 3.0

Title: Unable to get json web token from Flask

Body:
I have the below code for app.py:

from flask import Flask
from flask_jwt import JWT, jwt_required, current_identity
from werkzeug.security import safe_str_cmp

class User(object):
    def __init__(self, id, username, password):
        self.id = id
        self.username = username
        self.password = password

    def __str__(self):
        return "User(id='%s')" % self.id

users = [
    User(1, 'user1', 'abcxyz'),
    User(2, 'user2', 'abcxyz'),
]

username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}

def authenticate(username, password):
    user = username_table.get(username, None)
    if user and safe_str_cmp(user.password.encode('utf-8'), password.encode('utf-8')):
        return user

def identity(payload):
    user_id = payload['identity']
    return userid_table.get(user_id, None)

app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'super-secret'

jwt = JWT(app, authenticate, identity)

@app.route('/protected')
@jwt_required()
def protected():
    return '%s' % current_identity

if __name__ == '__main__':
    app.run()

When i try to make a post request to get the authentication token from Postman :
http://127.0.0.1:5000/auth

{
    "username": "joe",
    "password": "pass"
}

I get a peculiar error which i am not able to solve :

(flask-restful) C:\Users\bhatsubh\Projects\flask-restful>python Test.py
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 973-755-004
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [06/Sep/2017 13:38:08] "POST /auth HTTP/1.1" 500 -
Traceback (most recent call last):
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1985, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\_compat.py"
, line 33, in reraise
    raise value
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\_compat.py"
, line 33, in reraise
    raise value
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask\app.py", li
ne 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\bhatsubh\Envs\flask-restful\lib\site-packages\flask_jwt\__init_
_.py", line 115, in _default_auth_request_handler
    username = data.get(current_app.config.get('JWT_AUTH_USERNAME_KEY'), None)
AttributeError: 'NoneType' object has no attribute 'get'

I have absolutely no idea what is going wrong. Can someone please help me with this?

Body:
make sure have set correct header

Content-Type:application/json

try curl for cross check

$ curl -H "Content-Type: application/json" -X POST -d '{ "username": "joe", "password": "pass" }' http://localhost:5000/auth


问:
ng-repeat to open content
I am trying to make a list of buttons appear, and once selected for the appropriate div underneath the button to be shown, I have used similar code before:

```<code><li><button class="w3-button w3-grey w3-hover-dark-grey w3-round-xxlarge" ng-click="section = !section">Structure and function of the processor</button></li>
</code>```

Which works fine so I am guessing it has something to do with $index

Do you have any idea how I could achieve this?

```<code><div class="w3-panel" ng-show="section">
    henlo content
</div>

<div ng-app="tApp" ng-controller="tController">
    <ul class="w3-ul">
    <div ng-repeat="x in items">
        <li>
            <button class="w3-button w3-grey w3-hover-dark-grey w3-round-xxlarge" ng-click="section{{$index}} = !section{{$index}}">{{x.name}}</button>
        </li>
        <div class="w3-panel" ng-show="section{{$index}}">
            {{x.content}}
        </div>
    </div>
    </ul>
</div>
<script>
        var app=angular.module("tApp", []);
        app.controller("tController", function($scope)
        {
                $scope.items=[{name:"first",content:"henlo first"},{name:"second", content:"henlo second"}];
        });
</script>
</code>```

答:
you can initialise a property with ng-init and use that property to show/hide content</p>

```<code><div ng-repeat="x in items" ng-init="x.displayContent = false">
    <li>
        <button class="w3-button w3-grey w3-hover-dark-grey w3-round-xxlarge" ng-click="x.displayContent = !x.displayContent">{{x.name}}</button>
    </li>
    <div class="w3-panel" ng-show="x.displayContent">
        {{x.content}}
    </div>
</div>
</code>```

Title: ng-repeat to open content

Body:
I am trying to make a list of buttons appear, and once selected for the appropriate div underneath the button to be shown, I have used similar code before:

<button class="w3-button w3-grey w3-hover-dark-grey w3-round-xxlarge" ng-click="section = !section">Structure and function of the processor</button>

Which works fine so I am guessing it has something to do with $index

Do you have any idea how I could achieve this?

    henlo content

            <button class="w3-button w3-grey w3-hover-dark-grey w3-round-xxlarge" ng-click="section{{$index}} = !section{{$index}}">{{x.name}}</button>

            {{x.content}}

Body:
you can initialise a property with ng-init and use that property to show/hide content

<div ng-repeat="x in items" ng-init="x.displayContent = false">
    <li>
        <button class="w3-button w3-grey w3-hover-dark-grey w3-round-xxlarge" ng-click="x.displayContent = !x.displayContent">{{x.name}}</button>
    </li>
    <div class="w3-panel" ng-show="x.displayContent">
        {{x.content}}
    </div>
</div>


问:
Generation of pdf file using java
I am developing a standalone application in Java. I want to generate a pdf file using Java code. I have a display form in which all the details are fetched from database and displayed in the window. Details are Customer Name, Order Details etc.

Now I want to have a button there which says Convert to pdf.
I want to convert this to pdf file with proper alignment and formatting like tables, font etc.

What can be an ideal way to go about it?

答:
Use iText:

http://itextpdf.com/

Title: Generation of pdf file using java

Body:
Use iText:

http://itextpdf.com/

ContentLicense: CC BY-SA 2.5


问:
Firebase upload multiple images in swift
I want to upload multiple images with some text in firebase when user pushed the button. to do that I implemented for loop. Let's say if user picked 3 photos, then I think firebase should look like this

```<code> "Post": {
    "uid": {
      "Text": "some text",
      "imageUrl": "url",
      "imageUrl2": "url2",
      "imageUrl3": "url3"
    }
  }
</code>```

But it returns like this. That tweetImageUrl is the third photo's url which is picked last. also inside storage, there is only one photo which is the third photo as well.

How can I upload images correctly?
Here is my code.

```<code>    func sendTweets() {

         let text = textView.text
         let tweetLength = textView.text.count
         let imagesNumber = imagesArray.count
         format.dateFormat = "yyyy-MM-dd HH:mm"
         let strDate = format.string(from: date as Date)
         let childRef = ref.child("TWEETS").child(uid!).childByAutoId()
         let key = ref.child("TWEETS").child(uid!).childByAutoId().key
         let childStorageRef = storageRef.child("tweetImage").child(uid!).child(key)

  if(tweetLength>0 && imagesNumber>0)
    {

       for image in imagesArray {

        let tweetImage = image
        if let uploadData = UIImagePNGRepresentation(tweetImage) {

         childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                    if error != nil {
                        print("error")
        } else {

        if let imageUrl = metadata?.downloadURL()?.absoluteString {
          let values = ["Text": text!, "tweetImageUrl": imageUrl, "Date": strDate]  as [String : Any]
            childRef.updateChildValues(values)

              }
            }
          })
        }
      }
       dismiss(animated: true, completion: nil)
    }
         else if(tweetLength>0)
         {
            let values = ["Text": text!, "Date": strDate]  as [String : Any]

         childRef.updateChildValues(values)

         dismiss(animated: true, completion: nil)

         }

         else if(imagesNumber>0)
         {

        for image in imagesArray {

            let tweetImage = image
            if let uploadData = UIImagePNGRepresentation(tweetImage) {

             childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                if error != nil {
                    print("error")
                } else {

            if let imageUrl = metadata?.downloadURL()?.absoluteString {
            let values = ["tweetImageUrl": imageUrl, "Date": strDate]  as [String : Any]
            childRef.updateChildValues(values)
                }
             }
          })
        }
      }
        dismiss(animated: true, completion: nil)
  }  else {
        alertTheUser(title: "error", message: "enter something.")
    }
}//func
</code>```

Also when it comes to retrieve those images and display on the collection view after uploaded, is this proper way to achieve that?
Thank you in advance!

答:
Thanks to Rozario's help, I figured it out. What I was missing was I didn't declare AutoId inside for-loop. That's why old value was replaced by new value. code below worked as I expected. Node looks like this. hope it would help.

```<code>  "Post": {
    "uid": {
      "Text": "some text",
      "images": {
         autoID1: url1,
         autoID2: url2
      }
    }
  }
</code>```

code below.

```<code>func sendTweets() {

             let text = textView.text
             let tweetLength = textView.text.count
             let imagesNumber = imagesArray.count
             format.dateFormat = "yyyy-MM-dd HH:mm"
             let strDate = format.string(from: date as Date)
             let childRef = ref.child("TWEETS").child(uid!).childByAutoId()

      if(tweetLength>0 && imagesNumber>0)
        {

           for image in imagesArray {

            let postRef = childRef.child("tweetImageUrl")
            let autoID = postRef.childByAutoId().key
            let childStorageRef = storageRef.child("Images").child(uid!).child(autoID)
            let tweetImage = image

            if let uploadData = UIImagePNGRepresentation(tweetImage) {

             childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                        if error != nil {
                            print("error")
            } else {

            if let imageUrl = metadata?.downloadURL()?.absoluteString {
                let values = ["Text": text!, "Date": strDate]  as [String : Any]
                let value = [autoID: imageUrl]  as [String : Any]
                childRef.updateChildValues(values)
                postRef.updateChildValues(value)
                  }
                }
              })
            }
          }
           dismiss(animated: true, completion: nil)
        }
             else if(tweetLength>0)
             {
                let values = ["Text": text!, "Date": strDate]  as [String : Any]

             childRef.updateChildValues(values)

             dismiss(animated: true, completion: nil)

             }

             else if(imagesNumber>0)
             {

            for image in imagesArray {

                let postRef = childRef.child("tweetImageUrl")
                let autoID = postRef.childByAutoId().key
                let childStorageRef = storageRef.child("Images").child(uid!).child(autoID)
                let tweetImage = image

                if let uploadData = UIImagePNGRepresentation(tweetImage) {

                 childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                    if error != nil {
                        print("error")
                    } else {

                if let imageUrl = metadata?.downloadURL()?.absoluteString {
                let values = ["Date": strDate]  as [String : Any]
                childRef.updateChildValues(values)
                postRef.child(autoID).setValue(imageUrl)
                    }
                 }
              })
            }
          }
            dismiss(animated: true, completion: nil)
      }  else {
            alertTheUser(title: "error", message: "enter something.")
        }

    }//func
</code>```

Body:
I want to upload multiple images with some text in firebase when user pushed the button. to do that I implemented for loop. Let's say if user picked 3 photos, then I think firebase should look like this

 "Post": {
    "uid": {
      "Text": "some text",
      "imageUrl": "url",
      "imageUrl2": "url2",
      "imageUrl3": "url3"
    }
  }

But it returns like this. That tweetImageUrl is the third photo's url which is picked last. also inside storage, there is only one photo which is the third photo as well.

How can I upload images correctly?
Here is my code.

    func sendTweets() {

         let text = textView.text
         let tweetLength = textView.text.count
         let imagesNumber = imagesArray.count
         format.dateFormat = "yyyy-MM-dd HH:mm"
         let strDate = format.string(from: date as Date)
         let childRef = ref.child("TWEETS").child(uid!).childByAutoId()
         let key = ref.child("TWEETS").child(uid!).childByAutoId().key
         let childStorageRef = storageRef.child("tweetImage").child(uid!).child(key)

  if(tweetLength>0 && imagesNumber>0)
    {

       for image in imagesArray {

        let tweetImage = image
        if let uploadData = UIImagePNGRepresentation(tweetImage) {

         childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                    if error != nil {
                        print("error")
        } else {

        if let imageUrl = metadata?.downloadURL()?.absoluteString {
          let values = ["Text": text!, "tweetImageUrl": imageUrl, "Date": strDate]  as [String : Any]
            childRef.updateChildValues(values)

              }
            }
          })
        }
      }
       dismiss(animated: true, completion: nil)
    }
         else if(tweetLength>0)
         {
            let values = ["Text": text!, "Date": strDate]  as [String : Any]

         childRef.updateChildValues(values)

         dismiss(animated: true, completion: nil)

         }

         else if(imagesNumber>0)
         {

        for image in imagesArray {

            let tweetImage = image
            if let uploadData = UIImagePNGRepresentation(tweetImage) {

             childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                if error != nil {
                    print("error")
                } else {

            if let imageUrl = metadata?.downloadURL()?.absoluteString {
            let values = ["tweetImageUrl": imageUrl, "Date": strDate]  as [String : Any]
            childRef.updateChildValues(values)
                }
             }
          })
        }
      }
        dismiss(animated: true, completion: nil)
  }  else {
        alertTheUser(title: "error", message: "enter something.")
    }
}//func

Also when it comes to retrieve those images and display on the collection view after uploaded, is this proper way to achieve that?
Thank you in advance!

Body:
Thanks to Rozario's help, I figured it out. What I was missing was I didn't declare AutoId inside for-loop. That's why old value was replaced by new value. code below worked as I expected. Node looks like this. hope it would help.

  "Post": {
    "uid": {
      "Text": "some text",
      "images": {
         autoID1: url1,
         autoID2: url2
      }
    }
  }

code below.

func sendTweets() {

             let text = textView.text
             let tweetLength = textView.text.count
             let imagesNumber = imagesArray.count
             format.dateFormat = "yyyy-MM-dd HH:mm"
             let strDate = format.string(from: date as Date)
             let childRef = ref.child("TWEETS").child(uid!).childByAutoId()

      if(tweetLength>0 && imagesNumber>0)
        {

           for image in imagesArray {

            let postRef = childRef.child("tweetImageUrl")
            let autoID = postRef.childByAutoId().key
            let childStorageRef = storageRef.child("Images").child(uid!).child(autoID)
            let tweetImage = image

            if let uploadData = UIImagePNGRepresentation(tweetImage) {

             childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                        if error != nil {
                            print("error")
            } else {

            if let imageUrl = metadata?.downloadURL()?.absoluteString {
                let values = ["Text": text!, "Date": strDate]  as [String : Any]
                let value = [autoID: imageUrl]  as [String : Any]
                childRef.updateChildValues(values)
                postRef.updateChildValues(value)
                  }
                }
              })
            }
          }
           dismiss(animated: true, completion: nil)
        }
             else if(tweetLength>0)
             {
                let values = ["Text": text!, "Date": strDate]  as [String : Any]

             childRef.updateChildValues(values)

             dismiss(animated: true, completion: nil)

             }

             else if(imagesNumber>0)
             {

            for image in imagesArray {

                let postRef = childRef.child("tweetImageUrl")
                let autoID = postRef.childByAutoId().key
                let childStorageRef = storageRef.child("Images").child(uid!).child(autoID)
                let tweetImage = image

                if let uploadData = UIImagePNGRepresentation(tweetImage) {

                 childStorageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                    if error != nil {
                        print("error")
                    } else {

                if let imageUrl = metadata?.downloadURL()?.absoluteString {
                let values = ["Date": strDate]  as [String : Any]
                childRef.updateChildValues(values)
                postRef.child(autoID).setValue(imageUrl)
                    }
                 }
              })
            }
          }
            dismiss(animated: true, completion: nil)
      }  else {
            alertTheUser(title: "error", message: "enter something.")
        }

    }//func


问:
Hide a column using Jquery
I have a table created dynamically and I want to hide columns based on group.

But so far all I could do is to hide the tableHeaders instead. And I can hide the header but the input for data still there http://prntscr.com/hl5so6

My question is:

How can I hide the entire column with class name = "DDA" for example.

So instead of this: $('.dda').hide(); I want something like: $('.dda').hideColumn(); and $('.dda').show(); to $('.dda').showColumns();

```<code>    $(document).ready(function () {
    appendHeader();
    select();
    var amountOfDayEnds = parseInt($('#amountOfDayEnds').val());
    appendBody(amountOfDayEnds);

});

$('#group').change(function () {
   select();
});

//Change Header based on the select
function select() {
    var group = $('#group').val();
    var table = $('#dataTable');
    console.log(group);
    switch (group) {
        case "DDA":
            $('.mtg').hide();
            $('.sav').hide();
            $('.dda').show();
            break;
        case "SAV":
            $('.mtg').hide();
            $('.sav').show();
            $('.dda').hide();
            break;
        case "MTG":
            $('.mtg').show();
            $('.sav').hide();
            $('.dda').hide();
            break;
    }
}

//Append Header
function appendHeader() {
    var thead = '<thead>';
    thead += "<tr class='text-primary text-center'>";
    thead += '<th>Day</th>';
    thead += '<th class="dda">Type 400</th>';
    thead += '<th class="dda">Type 4044</th>';
    thead += '<th class="dda">Type 4045</th>';
    thead += '<th class="sav">Type 300</th>';
    thead += '<th class="sav">Type 310</th>';
    thead += '<th class="mtg">Type 700</th>';
    thead += '<th class="mtg">Type 710</th>';
    thead += '</tr>';
    thead += '</thead>';

    $('#dataTableHead').append(thead);
}
function appendBody(amountOfDayEnds) {
    var data = "";
    console.log(amountOfDayEnds);
    for(var i=1;i<=amountOfDayEnds;i++) {
        data += '<tr align="center" class="hover-table">';
        data += '<td>' + i + '</td>';
        for (var j = 0; j< 8;j++) {
            data += '<td>' + '<input class="text-center config-input amountOfAccounts" type="number" value="0" min="0" max="500" name="dataAccounts[]" data-error="Please, insert a value"  required></td>'
        }
        data += '</tr>';
    }
    $('#dataTableBody').append(data);
}
</code>```

答:
Well, you can always add those classes dynamicaly.
In my solution, I have declared classes into array, in TH I pass the valies and then adding this (little bit altered for e.g. styling purposes) class in iteration where td are generated.

then you can simply call a hide on it.

so the major changes are:

```<code>var classes = ["dda","dda","dda","sav","sav","mtg","mtg"];
</code>```

then

```<code>thead += '<th class="'+classes[0]+'">(dda)Type 400</th>';
</code>```

and then

```<code>for (var j = 0; j< 7;j++) {
            data += '<td class="'+classes[j]+'td">' + '<input class="text-center config-input amountOfAccounts" type="number" value="0" min="0" max="500" name="dataAccounts[]" data-error="Please, insert a value"  required></td>'
        }
</code>```

and then I have added a dummy button:

```<code><button onclick="$('.dda').hide(); $('.ddatd').hide();">HIDE DDA</button>
</code>```

I have also altered generating THEAD as you havent provided any source, and I believe all labels should be over correct column, so look at it too...

heres a solution:

   $(document).ready(function () {
    appendHeader();
    //select();
    var amountOfDayEnds = 3;
    appendBody(amountOfDayEnds);

});

$('#group').change(function () {
   select();
});

//Change Header based on the select
function select() {
    var group = $('#group').val();
    var table = $('#dataTable');
    console.log(group);
    switch (group) {
        case "DDA":
            $('.mtg').hide();
            $('.sav').hide();
            $('.dda').show();
            break;
        case "SAV":
            $('.mtg').hide();
            $('.sav').show();
            $('.dda').hide();
            break;
        case "MTG":
            $('.mtg').show();
            $('.sav').hide();
            $('.dda').hide();
            break;
    }
}

var classes = ["dda","dda","dda","sav","sav","mtg","mtg"];
//Append Header
function appendHeader() {
    var thead = '';
    thead += "
";
    thead += 'Day	';
    thead += '(dda)Type 400	';
    thead += '(dda)Type 4044	';
    thead += '(dda)Type 4045	';
    thead += '(sav)Type 300	';
    thead += '(sav)Type 310	';
    thead += '(mtg)Type 700	';
    thead += '(mtg)Type 710	';
    thead += '
';
    thead += '';

    $('#dataTableHead').append(thead);
}
function appendBody(amountOfDayEnds) {
    var data = "";
    console.log(amountOfDayEnds);
    for(var i=1;i<=amountOfDayEnds;i++) {
        data += '
';
        data += '' + i + '	';
        for (var j = 0; j< 7;j++) {
            data += '' + '<input class="text-center config-input amountOfAccounts" type="number" value="0" min="0" max="500" name="dataAccounts[]" data-error="Please, insert a value"  required>	'
        }
        data += '
';
    }
    $('#dataTableBody').append(data);
}```
<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>
<button onclick="$('.dda').hide(); $('.ddatd').hide();">HIDE DDA</button>
<table id="dataTable"><thead id="dataTableHead"></thead><tbody id="dataTableBody"></tbody></table></code>```

Title: Hide a column using Jquery

Body:
I have a table created dynamically and I want to hide columns based on group.

But so far all I could do is to hide the tableHeaders instead. And I can hide the header but the input for data still there http://prntscr.com/hl5so6

My question is:

How can I hide the entire column with class name = "DDA" for example.

So instead of this: $('.dda').hide(); I want something like: $('.dda').hideColumn(); and $('.dda').show(); to $('.dda').showColumns();

    $(document).ready(function () {
    appendHeader();
    select();
    var amountOfDayEnds = parseInt($('#amountOfDayEnds').val());
    appendBody(amountOfDayEnds);

});

$('#group').change(function () {
   select();
});

//Change Header based on the select
function select() {
    var group = $('#group').val();
    var table = $('#dataTable');
    console.log(group);
    switch (group) {
        case "DDA":
            $('.mtg').hide();
            $('.sav').hide();
            $('.dda').show();
            break;
        case "SAV":
            $('.mtg').hide();
            $('.sav').show();
            $('.dda').hide();
            break;
        case "MTG":
            $('.mtg').show();
            $('.sav').hide();
            $('.dda').hide();
            break;
    }
}

//Append Header
function appendHeader() {
    var thead = '
';
    thead += "
";
    thead += 'Day	';
    thead += 'Type 400	';
    thead += 'Type 4044	';
    thead += 'Type 4045	';
    thead += 'Type 300	';
    thead += 'Type 310	';
    thead += 'Type 700	';
    thead += 'Type 710	';
    thead += '
';
    thead += '
';

    $('#dataTableHead').append(thead);
}
function appendBody(amountOfDayEnds) {
    var data = "";
    console.log(amountOfDayEnds);
    for(var i=1;i<=amountOfDayEnds;i++) {
        data += '
';
        data += '' + i + '	';
        for (var j = 0; j< 8;j++) {
            data += '' + '<input class="text-center config-input amountOfAccounts" type="number" value="0" min="0" max="500" name="dataAccounts[]" data-error="Please, insert a value"  required>	'
        }
        data += '
';
    }
    $('#dataTableBody').append(data);
}

Body:
Well, you can always add those classes dynamicaly.
In my solution, I have declared classes into array, in TH I pass the valies and then adding this (little bit altered for e.g. styling purposes) class in iteration where td are generated.

then you can simply call a hide on it.

so the major changes are:

var classes = ["dda","dda","dda","sav","sav","mtg","mtg"];

then

thead += '<th class="'+classes[0]+'">(dda)Type 400</th>';

and then

for (var j = 0; j< 7;j++) {
            data += '<td class="'+classes[j]+'td">' + '<input class="text-center config-input amountOfAccounts" type="number" value="0" min="0" max="500" name="dataAccounts[]" data-error="Please, insert a value"  required></td>'
        }

and then I have added a dummy button:

<button onclick="$('.dda').hide(); $('.ddatd').hide();">HIDE DDA</button>

I have also altered generating THEAD as you havent provided any source, and I believe all labels should be over correct column, so look at it too...

heres a solution:

   $(document).ready(function () {
    appendHeader();
    //select();
    var amountOfDayEnds = 3;
    appendBody(amountOfDayEnds);

});

$('#group').change(function () {
   select();
});

//Change Header based on the select
function select() {
    var group = $('#group').val();
    var table = $('#dataTable');
    console.log(group);
    switch (group) {
        case "DDA":
            $('.mtg').hide();
            $('.sav').hide();
            $('.dda').show();
            break;
        case "SAV":
            $('.mtg').hide();
            $('.sav').show();
            $('.dda').hide();
            break;
        case "MTG":
            $('.mtg').show();
            $('.sav').hide();
            $('.dda').hide();
            break;
    }
}

var classes = ["dda","dda","dda","sav","sav","mtg","mtg"];
//Append Header
function appendHeader() {
    var thead = '';
    thead += "<tr class='text-primary text-center'>";
    thead += '<th>Day</th>';
    thead += '<th class="'+classes[0]+'">(dda)Type 400</th>';
    thead += '<th class="'+classes[1]+'">(dda)Type 4044</th>';
    thead += '<th class="'+classes[2]+'">(dda)Type 4045</th>';
    thead += '<th class="'+classes[3]+'">(sav)Type 300</th>';
    thead += '<th class="'+classes[4]+'">(sav)Type 310</th>';
    thead += '<th class="'+classes[5]+'">(mtg)Type 700</th>';
    thead += '<th class="'+classes[6]+'">(mtg)Type 710</th>';
    thead += '</tr>';
    thead += '';

    $('#dataTableHead').append(thead);
}
function appendBody(amountOfDayEnds) {
    var data = "";
    console.log(amountOfDayEnds);
    for(var i=1;i<=amountOfDayEnds;i++) {
        data += '<tr align="center" class="hover-table">';
        data += '<td>' + i + '</td>';
        for (var j = 0; j< 7;j++) {
            data += '<td class="'+classes[j]+'td">' + '<input class="text-center config-input amountOfAccounts" type="number" value="0" min="0" max="500" name="dataAccounts[]" data-error="Please, insert a value"  required></td>'
        }
        data += '</tr>';
    }
    $('#dataTableBody').append(data);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="$('.dda').hide(); $('.ddatd').hide();">HIDE DDA</button>
<table id="dataTable"><thead id="dataTableHead"></thead><tbody id="dataTableBody"></tbody></table>


问:
How to get the latitude and longitude from a Google Map marker in order to update in a form?
I want to make a form that auto-updates the coordinates of a marker.
Here's my part of the script:

```<code>google.maps.event.addListener(map, "click", function(event) {
  marker = new google.maps.Marker({
    position: event.latLng,
    map: map,
  });
  var x = document.getElementById("coordinates");
  if (x.style.display === "none") {
    x.style.display = "block";
  };
  var lati, longi;
  lati = event.latLng;
  longi = event.latLng;
  $("#lat").val(lati);
  $("#lng").val(longi);
});
</code>```

And here's the form:

```<code><div id="coordinates" class="container" style="margin-top: 10px; display: none;">
  <div class="col-sm-5 col-md-5 col-lg-5">
    <input class="form-control" id="lat" name="lat" placeholder="Latitude" type="text" required>
  </div>
  <div class="col-sm-5 col-md-5 col-lg-5">
    <input class="form-control" id="lng" name="lng" placeholder="Longitude" type="text" required>
  </div>
</code>```

答:
You need to separate them using .lat()/.lng():

```<code>var myLatLng = event.latLng;

var lati = myLatLng.lat();
var lngi = myLatLng.lng();

$("#lat").val(lati);
$("#lng").val(longi);
_^______________________ //Make sure you correct the typo here
</code>```

Body:
I want to make a form that auto-updates the coordinates of a marker.
Here's my part of the script:

google.maps.event.addListener(map, "click", function(event) {
  marker = new google.maps.Marker({
    position: event.latLng,
    map: map,
  });
  var x = document.getElementById("coordinates");
  if (x.style.display === "none") {
    x.style.display = "block";
  };
  var lati, longi;
  lati = event.latLng;
  longi = event.latLng;
  $("#lat").val(lati);
  $("#lng").val(longi);
});

And here's the form:

    <input class="form-control" id="lat" name="lat" placeholder="Latitude" type="text" required>

    <input class="form-control" id="lng" name="lng" placeholder="Longitude" type="text" required>

Body:
You need to separate them using .lat()/.lng():

var myLatLng = event.latLng;

var lati = myLatLng.lat();
var lngi = myLatLng.lng();

$("#lat").val(lati);
$("#lng").val(longi);
_^______________________ //Make sure you correct the typo here


问:
Javascript serialized POST
I am trying to achieve that when I call the JS function, a post request is send. In my browser I would send:

```<code>http://myuser:password@hc2:80/api/callAction?deviceID=185&name=turnOn
</code>```

This works. Yet in my code it doesn't.

Important to note:
- Chrome does raise an Error: Request doesn't pass access control. If I disable this in Chrome, I doesn't display this error (yet no response from the server either).

```<code><script type="text/javascript">

    function changestate() {
        var http = new XMLHttpRequest();
        http.withCredentials = true;
        var user = "bassie"
        var pass = "password"
        var url = "http://hc2/api/callAction";
        var params = "deviceID=185&name=turnOff";
        http.open("POST", url, true);
        http.setRequestHeader("Authorization", "Basic " + user + ":" + pass);
        //Send the proper header information along with the request
        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        alert(http.responseText);
        http.onreadystatechange = function() {//Call a function when the state changes.
            if(http.readyState == 4 && http.status == 200) {
                    alert(http.responseText);
            }
        }
        http.send(params);
    }

</script>
</code>```

答:
Eventually ended up creating a sort of like proxy. This was the main component. Not in the example (My script gets the HTTP requested) and gets the output. Below the gist of it: </p>

```<code>   req = urllib.request.Request('http://hc2:80/api/callAction?param1=1&param2=2')
   credentials = ('%s:%s' % ('user', 'password'))
   encoded_credentials = base64.b64encode(credentials.encode('ascii'))
   req.add_header('Authorization', 'Basic %s' %
   encoded_credentials.decode("ascii"))
   response = urllib.request.urlopen(req)
</code>```

Title: Javascript serialized POST

Body:
I am trying to achieve that when I call the JS function, a post request is send. In my browser I would send:

http://myuser:password@hc2:80/api/callAction?deviceID=185&name=turnOn

This works. Yet in my code it doesn't.

Important to note:
- Chrome does raise an Error: Request doesn't pass access control. If I disable this in Chrome, I doesn't display this error (yet no response from the server either).

Body:
Eventually ended up creating a sort of like proxy. This was the main component. Not in the example (My script gets the HTTP requested) and gets the output. Below the gist of it:

   req = urllib.request.Request('http://hc2:80/api/callAction?param1=1&param2=2')
   credentials = ('%s:%s' % ('user', 'password'))
   encoded_credentials = base64.b64encode(credentials.encode('ascii'))
   req.add_header('Authorization', 'Basic %s' %
   encoded_credentials.decode("ascii"))
   response = urllib.request.urlopen(req)


问:
Get updated IndexPath for visible item after UICollectionView has scrolled
I have a collectionView with different periods (day to year) for user to choose. Each item's size is equal to the size of collectionView itself.

```<code>@IBOutlet weak var periodCollectionView: UICollectionView!
@IBOutlet weak var itemLabel: UILabel!

let collectionValues = ["Day", "Week", "Month", "Year"]
var currentVisibleItem: Int?

override func viewDidLoad() {
    super.viewDidLoad()

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 4
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PeriodName", for: indexPath) as? DisplayPeriodCollectionViewCell
    else {
        fatalError("Unable to cast collection view cell as DisplayPeriodCollectionViewCell")
    }

    cell.periodName.text = collectionValues[indexPath.item]

    return cell

}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let height = collectionView.frame.height
    let width = collectionView.frame.width

    return CGSize(width: width, height: height)
}
</code>```

What i am trying to do is get an info label to display the index of current visible item after collectionView has scrolled. Her is the code:

```<code>func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

    let centerPoint = CGPoint(x: periodCollectionView.center.x + periodCollectionView.contentOffset.x, y: 1.0)
    print("centerPoint: \(centerPoint)")

    if let currentItemIndexPath = periodCollectionView.indexPathForItem(at: centerPoint) {
        currentVisibleItem = currentItemIndexPath.item
        print("index of current item: \(currentVisibleItem!)")
        itemLabel.text = "\(currentVisibleItem!)"
    } else {
        print("could not get index of current item...")
    }

}
</code>```

I've added print statements to check if values are defined correctly at runtime, and they show everything is fine. The problem is that label does not always update its text after scrolling ends, but instead waits for new scrolling to occur:

I can't figure out why this is happening - setting a breakpoint at scrollViewDidEndDecelerating shows that all code gets executed, so what's wrong with the label text?

UPD. Not-updating label text appears to be a Simulator issue - when running on device, label updates correctly.

答:
In your case you can use:

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
</code>```

because each item is at the same size as your collection view.
if you still want to use scroll view delegate you should write your page calculation in the following delegate functions:

```<code>func scrollViewDidEndDragging(UIScrollView, willDecelerate: Bool)

func scrollViewDidEndDecelerating(UIScrollView)

func scrollViewDidEndScrollingAnimation(UIScrollView)
</code>```

Body:
I have a collectionView with different periods (day to year) for user to choose. Each item's size is equal to the size of collectionView itself.

@IBOutlet weak var periodCollectionView: UICollectionView!
@IBOutlet weak var itemLabel: UILabel!

let collectionValues = ["Day", "Week", "Month", "Year"]
var currentVisibleItem: Int?

override func viewDidLoad() {
    super.viewDidLoad()

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 4
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PeriodName", for: indexPath) as? DisplayPeriodCollectionViewCell
    else {
        fatalError("Unable to cast collection view cell as DisplayPeriodCollectionViewCell")
    }

    cell.periodName.text = collectionValues[indexPath.item]

    return cell

}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let height = collectionView.frame.height
    let width = collectionView.frame.width

    return CGSize(width: width, height: height)
}

What i am trying to do is get an info label to display the index of current visible item after collectionView has scrolled. Her is the code:

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

    let centerPoint = CGPoint(x: periodCollectionView.center.x + periodCollectionView.contentOffset.x, y: 1.0)
    print("centerPoint: \(centerPoint)")

    if let currentItemIndexPath = periodCollectionView.indexPathForItem(at: centerPoint) {
        currentVisibleItem = currentItemIndexPath.item
        print("index of current item: \(currentVisibleItem!)")
        itemLabel.text = "\(currentVisibleItem!)"
    } else {
        print("could not get index of current item...")
    }

}

I've added print statements to check if values are defined correctly at runtime, and they show everything is fine. The problem is that label does not always update its text after scrolling ends, but instead waits for new scrolling to occur:

I can't figure out why this is happening - setting a breakpoint at scrollViewDidEndDecelerating shows that all code gets executed, so what's wrong with the label text?

UPD. Not-updating label text appears to be a Simulator issue - when running on device, label updates correctly.

Body:
In your case you can use:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell

because each item is at the same size as your collection view.
if you still want to use scroll view delegate you should write your page calculation in the following delegate functions:

func scrollViewDidEndDragging(UIScrollView, willDecelerate: Bool)

func scrollViewDidEndDecelerating(UIScrollView)

func scrollViewDidEndScrollingAnimation(UIScrollView)


问:
How should you end a Spark job inside an if statement?
What is the recommended way to end a spark job inside a conditional statement?

I am doing validation on my data, and if false, I want to end the spark job gracefully.

Right now I have:

```<code>if (isValid(data)) {
    sparkSession.sparkContext.stop()
}
</code>```

However, I get the following error:

```<code>Exception in thread "main" java.lang.IllegalStateException: SparkContext has been shutdown
</code>```

Then it shows a stacktrace.

Is sparkContext.stop() not the proper way to end a spark job gracefully?

答:
There is nothing to say that you can't call stop in an if statement, but there is very little reason to do so and it is probably a mistake to do so. It seems implicit in your question that you may be attempting to open multiple Spark sessions.

The Spark session is intended to be left open for the life of the program - if you try to start two you will find that Spark throws an exception and prints some background including a JIRA ticket that discusses the topic to the logs.

If you wish to run multiple Spark tasks, you may submit them to the same context. One context can run multiple tasks at once.

Body:
What is the recommended way to end a spark job inside a conditional statement?

I am doing validation on my data, and if false, I want to end the spark job gracefully.

Right now I have:

if (isValid(data)) {
    sparkSession.sparkContext.stop()
}

However, I get the following error:

Exception in thread "main" java.lang.IllegalStateException: SparkContext has been shutdown

Then it shows a stacktrace.

Is sparkContext.stop() not the proper way to end a spark job gracefully?


问:
Perl 6 Grammar doesn't match like I think it should
I'm doing Advent of Code day 9:

You sit for a while and record part of the stream (your puzzle input). The characters represent groups - sequences that begin with { and end with }. Within a group, there are zero or more other things, separated by commas: either another group or garbage. Since groups can contain other groups, a } only closes the most-recently-opened unclosed group - that is, they are nestable. Your puzzle input represents a single, large group which itself contains many smaller ones.

Sometimes, instead of a group, you will find garbage. Garbage begins with < and ends with >. Between those angle brackets, almost any character can appear, including { and }. Within garbage, < has no special meaning.

In a futile attempt to clean up the garbage, some program has canceled some of the characters within it using !: inside garbage, any character that comes after ! should be ignored, including <, >, and even another !.

Of course, this screams out for a Perl 6 Grammar...

```<code>grammar Stream
{
    rule TOP { ^ <group> $ }

    rule group { '{' [ <group> || <garbage> ]* % ',' '}' }
    rule garbage { '<' [ <garbchar> | <garbignore> ]* '>' }

    token garbignore { '!' . }
    token garbchar { <-[ !> ]> }
}
</code>```

This seems to work fine on simple examples, but it goes wrong with two garbchars in a row:

```<code>say Stream.parse('{<aa>}');
</code>```

gives Nil.

Grammar::Tracer is no help:

```<code>TOP
|  group
|  |  group
|  |  * FAIL
|  |  garbage
|  |  |  garbchar
|  |  |  * MATCH "a"
|  |  * FAIL
|  * FAIL
* FAIL
Nil
</code>```

Multiple garbignores are no problem:

```<code>say Stream.parse('{<!!a!a>}');
</code>```

gives:

```<code>｢{<!!a!a>}｣
 group => ｢{<!!a!a>}｣
  garbage => ｢<!!a!a>｣
   garbignore => ｢!!｣
   garbchar => ｢a｣
   garbignore => ｢!a｣
</code>```

Any ideas?

答:
A partial answer to my own question:  Change all the rules to tokens and it works.
It makes sense, because the difference is :sigspace, which we don't need or want here.  What I don't understand, though, is why it did work for some input, like my second example.

The resulting code is here, if you're interested.

Body:
I'm doing Advent of Code day 9:

You sit for a while and record part of the stream (your puzzle input). The characters represent groups - sequences that begin with { and end with }. Within a group, there are zero or more other things, separated by commas: either another group or garbage. Since groups can contain other groups, a } only closes the most-recently-opened unclosed group - that is, they are nestable. Your puzzle input represents a single, large group which itself contains many smaller ones.

Sometimes, instead of a group, you will find garbage. Garbage begins with < and ends with >. Between those angle brackets, almost any character can appear, including { and }. Within garbage, < has no special meaning.

In a futile attempt to clean up the garbage, some program has canceled some of the characters within it using !: inside garbage, any character that comes after ! should be ignored, including <, >, and even another !.

Of course, this screams out for a Perl 6 Grammar...

grammar Stream
{
    rule TOP { ^ <group> $ }

    rule group { '{' [ <group> || <garbage> ]* % ',' '}' }
    rule garbage { '<' [ <garbchar> | <garbignore> ]* '>' }

    token garbignore { '!' . }
    token garbchar { <-[ !> ]> }
}

This seems to work fine on simple examples, but it goes wrong with two garbchars in a row:

say Stream.parse('{<aa>}');

gives Nil.

Grammar::Tracer is no help:

TOP
|  group
|  |  group
|  |  * FAIL
|  |  garbage
|  |  |  garbchar
|  |  |  * MATCH "a"
|  |  * FAIL
|  * FAIL
* FAIL
Nil

Multiple garbignores are no problem:

say Stream.parse('{<!!a!a>}');

gives:

｢{<!!a!a>}｣
 group => ｢{<!!a!a>}｣
  garbage => ｢<!!a!a>｣
   garbignore => ｢!!｣
   garbchar => ｢a｣
   garbignore => ｢!a｣

Any ideas?


问:
Spring Boot Application which triggers another App with CLI
I am currently developing a Spring Boot Application which triggers a Python program via CLI. I've used Processbuilder to do that and it's been working ok so far.

Now I'm trying to get the Spring Boot Application and the Python program in a Docker container. Since I'm new to Docker I don't know the best way to do this. I've tried using COPY to copy the whole folder to create an image but for some reason the folder pythonapp in the Container is always empty.

Am I missing something or is there a better way to do this?

```<code>FROM openjdk:8u151-jdk-slim
EXPOSE 8080
ADD springbootapp-0.0.1.jar app.jar
COPY . /root/pythonapp
RUN sh -c 'touch /app.jar'
RUN apt-get update && apt-get install -y python \
python-gi \
gir1.2-gtk-3.0
ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]
</code>```

答:
Normally the idea of docker is that 1 container does 1 thing and 1 thing good. So it mostly is not a good idea to put two things in 1 docker container. Think about two containers :-)

Other than that it might be a good idea to add files separately or as a tar/zip file and extract it in the image.

Body:
I am currently developing a Spring Boot Application which triggers a Python program via CLI. I've used Processbuilder to do that and it's been working ok so far.

Now I'm trying to get the Spring Boot Application and the Python program in a Docker container. Since I'm new to Docker I don't know the best way to do this. I've tried using COPY to copy the whole folder to create an image but for some reason the folder pythonapp in the Container is always empty.

Am I missing something or is there a better way to do this?

FROM openjdk:8u151-jdk-slim
EXPOSE 8080
ADD springbootapp-0.0.1.jar app.jar
COPY . /root/pythonapp
RUN sh -c 'touch /app.jar'
RUN apt-get update && apt-get install -y python \
python-gi \
gir1.2-gtk-3.0
ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]


问:
How to handle complicated input form in Python according PHP approach?
I have got the following HTML form with several complicated input elements:

```<code><input type="text" name="images[1]">
<input type="text" name="images[2]">
<input type="text" name="video[1]">
<input type="text" name="video[2]">
</code>```

When I talk about cimplicated inputs I mean sophisticated name of elements:

```<code>name="images[1]"
</code>```

Where images is indicate group of input and [1] number or identificator of input.

Using PHP approach of handling form It can be achieved like:

```<code>if(isset($_POST['images'])) {
    foreach($_POST['images'] as $index) { // $key
         echo $_POST['images'][$index]; // or key
    }
}
</code>```

How to reproduce this in Python?

答:
it depends if you are using a python framework (django, Flask, ...) or not.
if you are using a framework, you must read its docs. for example with django, you can handle form element by request.POST['images'].

you can read How are POST and GET variables handled in Python?

Body:
I have got the following HTML form with several complicated input elements:

<input type="text" name="images[1]">
<input type="text" name="images[2]">
<input type="text" name="video[1]">
<input type="text" name="video[2]">

When I talk about cimplicated inputs I mean sophisticated name of elements:

name="images[1]"

Where images is indicate group of input and [1] number or identificator of input.

Using PHP approach of handling form It can be achieved like:

if(isset($_POST['images'])) {
    foreach($_POST['images'] as $index) { // $key
         echo $_POST['images'][$index]; // or key
    }
}

How to reproduce this in Python?


问:
Python design pattern for many conditions
What is the recommended structure to write validate functions with many conditions? See these two examples. The first looks ugly, the second isn't very common, perhaps because assert is generally used to rule out unexpected behaviour. Are there better alternatives?

```<code>def validate(val):
  if cond1(val):
    return False
  if cond2(val):
    return False
  if cond3(val)
    return False
  return True
</code>```

Or

```<code>def validate(val):
  try:
    assert cond1(val)
    assert cond2(val)
    assert cond3(val)
    return True
  except AssertionError:
    return False
</code>```

答:
```<code>def valid(value):
    return (is_this(value)
            and that(value)
            and other(value))
</code>```

and operator exhibits "short-circuit" behavior in Python.

Body:
What is the recommended structure to write validate functions with many conditions? See these two examples. The first looks ugly, the second isn't very common, perhaps because assert is generally used to rule out unexpected behaviour. Are there better alternatives?

def validate(val):
  if cond1(val):
    return False
  if cond2(val):
    return False
  if cond3(val)
    return False
  return True

Or

def validate(val):
  try:
    assert cond1(val)
    assert cond2(val)
    assert cond3(val)
    return True
  except AssertionError:
    return False

Body:
def valid(value):
    return (is_this(value)
            and that(value)
            and other(value))

and operator exhibits "short-circuit" behavior in Python.


问:
Are filenames case sensitive in VS2017?
I migrated a solution from VS 2010 to VS 2017. When I build the solution, some files are reported to be missing while they're existing in the specified paths. The solution (which is in C#) was compiling in VS 2010 without any problem. The filenames are the same except their cases. I need to know whether file names are case-sensitive in VS 2017 while they were not in VS 2010? If so, how can I revert this feature, or set the option to ignore the file names cases?</p>

答:
This is not a VS issue. The drive has been mapped by SFTP Net Drive. For such virtual drives, in which the original drive is case-sensitive and will be mapped in Windows which is not case-sensitive, there's an option in the last tab, 'Drive', which one should set it. It's:
Handle case-sensitive filenames</p>

Title: Are filenames case sensitive in VS2017?


问:
angularjs-uirouter $state.go Error as .go undefined
Here imgetting Error in $statechangStart    Here im trying to checking my credentials in $statechageStart

```<code>.config(function ($stateProvider, $urlRouterProvider) {
        $stateProvider
         .state('Login',{
                url:'/LoginService',
                templateUrl: '/ApiClient/Home/LoginPage.html',
                controller:'LoginController'

            })
  $urlRouterProvider.otherwise('/')
    })

     .run(function ($rootScope) {
            $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options, $scope, $state) {
                debugger;
                if (toState.module == "Private" && sessionStorage.getItem('employee')!=null) {}

                else {
                    event.preventDefault();
                     $state.go('Login');
                }
</code>```

答:
You need to inject $state to your .run , otherwise it is undefined

```<code>.run(function ($rootScope, $state)
</code>```

EDIT

It's a bad practice to use $state.go in $stateChangeStart event. For your purposes, you'd better apply the state.go after setting a timeout

```<code>   $timeout($state.go.bind(null, 'Login'), 3000);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here imgetting Error in $statechangStart    Here im trying to checking my credentials in $statechageStart

.config(function ($stateProvider, $urlRouterProvider) {
        $stateProvider
         .state('Login',{
                url:'/LoginService',
                templateUrl: '/ApiClient/Home/LoginPage.html',
                controller:'LoginController'

            })
  $urlRouterProvider.otherwise('/')
    })

     .run(function ($rootScope) {
            $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams, options, $scope, $state) {
                debugger;
                if (toState.module == "Private" && sessionStorage.getItem('employee')!=null) {}

                else {
                    event.preventDefault();
                     $state.go('Login');
                }

Body:
You need to inject $state to your .run , otherwise it is undefined

.run(function ($rootScope, $state)

EDIT

It's a bad practice to use $state.go in $stateChangeStart event. For your purposes, you'd better apply the state.go after setting a timeout

   $timeout($state.go.bind(null, 'Login'), 3000);


问:
css - @media isn't working
Okay, I found a solution: with @media I'm accessing the image's width and the bar separately and it's working but is there any shorter way codewise?

I searched the internet for a solution but none of what I found helped me so far.

I'm trying to make my header to be responsive to the browser's width but it isn't working.

I tried to make just the image responsive or just the top bar but nothing works...

Any ideas?

```<code><header class="header">
  <div class="top-bar">
    <div class="nav-container">
      <ul class="navbar">
        <li><a href="#החשבון שלי">החשבון שלי</a></li>
        <li><a href="#המתכונים שלי">המתכונים שלי</a></li>
        <li><a href="#אודות">אודות</a></li>
        <li class="last-btn"><a href="#צרו קשר">צרו קשר</a></li>
      </ul>
    </div>
  </div>
  <div class="banner">
    <a href="#banner"><img src="Images\maadanot_winter_banners.jpg" alt="אפייה חורפית"/></a>
  </div>
</header>
</code>```

and this is the css:

```<code>body {
margin: 0;
}

.top-bar {
    width: 100%;
    background-color: #404040;
    padding: 12px;
}

.nav-container {
    width: 68%;
    margin: auto;
}

.navbar {
    margin: 0;
    list-style-type: none;
    background-color: #404040;
    display: table;
    font-family: Helvetica;
    font-size: 14px;
}

.navbar li {
    display: table-cell;
    border-left: 1px solid white;
    padding: 0px 10px;
    overflow: hidden;
    width: 85px;
    text-align: center;
}

.navbar a {
    color: white;
    text-decoration: none;
}

.navbar a:hover {
    font-weight: bold;
}

@media screen and (max-width:900px) {
    .header {
        width: 100%;
    }
}

.banner {
    margin-top: 33px;
    width: 100%;
    text-align: center;
}
</code>```

答:
When you are working om Media Queries, You have to need change inherit property if you declare cascaded down.If you have set Backgruond images on the body, there is need a queries to cancel background images.

The keyword ‘only’ can also be used to hide style sheets from older user agents. User agents must process media queries starting with ‘only’ as if the ‘only’ keyword was not present.

Title: css - @media isn't working

Body:
Okay, I found a solution: with @media I'm accessing the image's width and the bar separately and it's working but is there any shorter way codewise?

I searched the internet for a solution but none of what I found helped me so far.

I'm trying to make my header to be responsive to the browser's width but it isn't working.

I tried to make just the image responsive or just the top bar but nothing works...

Any ideas?

החשבון שלי

המתכונים שלי

אודות

צרו קשר

and this is the css:

body {
margin: 0;
}

.top-bar {
    width: 100%;
    background-color: #404040;
    padding: 12px;
}

.nav-container {
    width: 68%;
    margin: auto;
}

.navbar {
    margin: 0;
    list-style-type: none;
    background-color: #404040;
    display: table;
    font-family: Helvetica;
    font-size: 14px;
}

.navbar li {
    display: table-cell;
    border-left: 1px solid white;
    padding: 0px 10px;
    overflow: hidden;
    width: 85px;
    text-align: center;
}

.navbar a {
    color: white;
    text-decoration: none;
}

.navbar a:hover {
    font-weight: bold;
}

@media screen and (max-width:900px) {
    .header {
        width: 100%;
    }
}

.banner {
    margin-top: 33px;
    width: 100%;
    text-align: center;
}


问:
overflow:hidden not working with border-radius in Chrome
I'm trying to make a circle-shaped image with an overlay that shows on hover. However, the "hitbox" of hovering (and clicking) is incorrect, as shown in the snippet below.

This issue seems to only occur in Chrome (not sure about Safari). I've found some fixes on the Internet, but none of them worked. JSFiddle for testing

$(document).ready(function() {
 $(".circle").click(function() {
  alert($(this).attr("id"));
 });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#canvas {
 width: 100%;
 padding-bottom: 75%;
 position: relative;
 overflow: hidden;
 background-color: #eee;
}
.circle {
 position: absolute;
 width: 25%;
 padding-bottom: 25%;
 border-radius: 50%;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 overflow: hidden;
 cursor: pointer;
 /*https://stackoverflow.com/a/32987370/5532169*/
 -webkit-backface-visibility: hidden;
 -moz-backface-visibility: hidden;
 /*https://stackoverflow.com/a/25206004/5532169*/
 z-index: 1;
 /*https://stackoverflow.com/a/10296258/5532169*/
 -webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC);
 /*https://stackoverflow.com/a/16878347/5532169*/
 -webkit-mask-image: -webkit-radial-gradient(circle, white, black);
}
.mid {
 width: 100%;
 height: 100%;
 position: absolute;
}
.inner {
 width: 100%;
 height: 100%;
 position: relative;
}
.inner>* {
 position: absolute;
 top: 0;
 bottom: 0;
 left: 0;
 right: 0;
 width: 100%;
 height: 100%;
}
.hover {
 background-color: rgba(255, 255, 255, 0.6);
 opacity: 0;
 transition: opacity 0.5s;
}
.hover:hover {
 opacity: 100;
 transition: opacity 0.5s;
}
span {
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 width: 72%;
 text-align: center;
 font-family: monospace;
 font-size: 2em;
 font-weight: bold;
 color: #08f;
}</code>```

    Hello World!

```

Edit: Tested in Firefox 57, works without problem. IE and Edge were tested already, so it's a Chrome-/webkit-specific issue.

答:
You can change only .circle class these properties:</p>

```<code>width: 26%;
padding-bottom: 26%;
border-radius: 50%;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
</code>```

Body:
I'm trying to make a circle-shaped image with an overlay that shows on hover. However, the "hitbox" of hovering (and clicking) is incorrect, as shown in the snippet below.

This issue seems to only occur in Chrome (not sure about Safari). I've found some fixes on the Internet, but none of them worked. JSFiddle for testing

$(document).ready(function() {
 $(".circle").click(function() {
  alert($(this).attr("id"));
 });
});

#canvas {
 width: 100%;
 padding-bottom: 75%;
 position: relative;
 overflow: hidden;
 background-color: #eee;
}
.circle {
 position: absolute;
 width: 25%;
 padding-bottom: 25%;
 border-radius: 50%;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 overflow: hidden;
 cursor: pointer;
 /*https://stackoverflow.com/a/32987370/5532169*/
 -webkit-backface-visibility: hidden;
 -moz-backface-visibility: hidden;
 /*https://stackoverflow.com/a/25206004/5532169*/
 z-index: 1;
 /*https://stackoverflow.com/a/10296258/5532169*/
 -webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC);
 /*https://stackoverflow.com/a/16878347/5532169*/
 -webkit-mask-image: -webkit-radial-gradient(circle, white, black);
}
.mid {
 width: 100%;
 height: 100%;
 position: absolute;
}
.inner {
 width: 100%;
 height: 100%;
 position: relative;
}
.inner>* {
 position: absolute;
 top: 0;
 bottom: 0;
 left: 0;
 right: 0;
 width: 100%;
 height: 100%;
}
.hover {
 background-color: rgba(255, 255, 255, 0.6);
 opacity: 0;
 transition: opacity 0.5s;
}
.hover:hover {
 opacity: 100;
 transition: opacity 0.5s;
}
span {
 position: absolute;
 top: 50%;
 left: 50%;
 transform: translate(-50%, -50%);
 width: 72%;
 text-align: center;
 font-family: monospace;
 font-size: 2em;
 font-weight: bold;
 color: #08f;
}

    Hello World!

Edit: Tested in Firefox 57, works without problem. IE and Edge were tested already, so it's a Chrome-/webkit-specific issue.

Body:
You can change only .circle class these properties:

width: 26%;
padding-bottom: 26%;
border-radius: 50%;
-moz-border-radius: 50%;
-webkit-border-radius: 50%;


问:
Kannel configuration for multiple smsc
I have created multiple SMSC SMPP connection.

after configuration i have send sms but sms is send with random smsc.

How can i control kannel to send sms with smpp which i want to send.

答:
You can specify what smsc to send through in the submission to the kannel server, for example:

```<code>GET /cgi-bin/sendsms?smsc=$smsc&username=$user&password=$password&to=$receipient&text=$text&dlr-mask=$dlrMask&dlr-url=$dlrUrl
</code>```

where $smsc should match a smsc-id you have in your kannel.conf

Documentation here, under "Table 6-16. SMS Push (send-sms) CGI Variables".

Title: Kannel configuration for multiple smsc

Body:
You can specify what smsc to send through in the submission to the kannel server, for example:

GET /cgi-bin/sendsms?smsc=$smsc&username=$user&password=$password&to=$receipient&text=$text&dlr-mask=$dlrMask&dlr-url=$dlrUrl

where $smsc should match a smsc-id you have in your kannel.conf

Documentation here, under "Table 6-16. SMS Push (send-sms) CGI Variables".


问:
how to use Intent to send 'event' between two classes?
I know how to add the data that i want to send to my Intent.

but i can't find any code example that send and receive the Intent that i defined.

I only finding example that do it with ActivityStart - but my classes that i want to use are not and activity - just a simple java class.

How can i do it ?

答:
Just make a method that has a Data parameter and send your data using it, intents doesn't send data between classes bro, take this example, here I want to send data from MainActivity, to class A:
** MainActivity:

```<code>ClassA a = new ClassA();
a.setData(data);
</code>```

** ClassA:

```<code>public void setData(Data data){
    this.data = data;
}
</code>```

Body:
Just make a method that has a Data parameter and send your data using it, intents doesn't send data between classes bro, take this example, here I want to send data from MainActivity, to class A:
** MainActivity:

ClassA a = new ClassA();
a.setData(data);

** ClassA:

public void setData(Data data){
    this.data = data;
}


问:
Save all email attachments in Outlook folder to Windows folder
I have about 80 emails, all with attachments which I would like to save to a folder on my hard drive.

How this can be done with a script?

答:
This subroutine will save all attachments found in a user specified Outlook folder to a user specified directory on the file system. It also updates each message with a link to the purged files.

It also contains extra comments to help highlight how the .Delete method will shrink Attachment containers dynamically (search for "~~" in the comments).

This macro is only tested on Outlook 2010.

```<code>' ------------------------------------------------------------
' Requires the following references:
'
' Visual Basic for Applications
' Microsoft Outlook 14.0 Object Library
' OLE Automation
' Microsoft Office 14.0 Object Library
' Microsoft Shell Controls and Automation
' ------------------------------------------------------------

Public Sub SaveOLFolderAttachments()

  ' Ask the user to select a file system folder for saving the attachments
  Dim oShell As Object
  Set oShell = CreateObject("Shell.Application")
  Dim fsSaveFolder As Object
  Set fsSaveFolder = oShell.BrowseForFolder(0, "Please Select a Save Folder:", 1)
  If fsSaveFolder Is Nothing Then Exit Sub
  ' Note:  BrowseForFolder doesn't add a trailing slash

  ' Ask the user to select an Outlook folder to process
  Dim olPurgeFolder As Outlook.MAPIFolder
  Set olPurgeFolder = Outlook.GetNamespace("MAPI").PickFolder
  If olPurgeFolder Is Nothing Then Exit Sub

  ' Iteration variables
  Dim msg As Outlook.MailItem
  Dim att As Outlook.attachment
  Dim sSavePathFS As String
  Dim sDelAtts

  For Each msg In olPurgeFolder.Items

    sDelAtts = ""

    ' We check each msg for attachments as opposed to using .Restrict("[Attachment] > 0")
    ' on our olPurgeFolder.Items collection.  The collection returned by the Restrict method
    ' will be dynamically updated each time we remove an attachment.  Each update will
    ' reindex the collection.  As a result, it does not provide a reliable means for iteration.
    ' This is why the For Each loops will not work.
    If msg.Attachments.Count > 0 Then

      ' This While loop is controlled via the .Delete method
      ' which will decrement msg.Attachments.Count by one each time.
      While msg.Attachments.Count > 0

        ' Save the file
        sSavePathFS = fsSaveFolder.Self.Path & "\" & msg.Attachments(1).FileName
        msg.Attachments(1).SaveAsFile sSavePathFS

        ' Build up a string to denote the file system save path(s)
        ' Format the string according to the msg.BodyFormat.
        If msg.BodyFormat <> olFormatHTML Then
            sDelAtts = sDelAtts & vbCrLf & "<file://" & sSavePathFS & ">"
        Else
            sDelAtts = sDelAtts & "<br>" & "<a href='file://" & sSavePathFS & "'>" & sSavePathFS & "</a>"
        End If

        ' Delete the current attachment.  We use a "1" here instead of an "i"
        ' because the .Delete method will shrink the size of the msg.Attachments
        ' collection for us.  Use some well placed Debug.Print statements to see
        ' the behavior.
        msg.Attachments(1).Delete

      Wend

      ' Modify the body of the msg to show the file system location of
      ' the deleted attachments.
      If msg.BodyFormat <> olFormatHTML Then
        msg.Body = msg.Body & vbCrLf & vbCrLf & "Attachments Deleted:  " & Date & " " & Time & vbCrLf & vbCrLf & "Saved To:  " & vbCrLf & sDelAtts
      Else
        msg.HTMLBody = msg.HTMLBody & "<p></p><p>" & "Attachments Deleted:  " & Date & " " & Time & vbCrLf & vbCrLf & "Saved To:  " & vbCrLf & sDelAtts & "</p>"
      End If

      ' Save the edits to the msg.  If you forget this line, the attachments will not be deleted.
      msg.Save

    End If

  Next

End Sub
</code>```

Body:
This subroutine will save all attachments found in a user specified Outlook folder to a user specified directory on the file system. It also updates each message with a link to the purged files.

It also contains extra comments to help highlight how the .Delete method will shrink Attachment containers dynamically (search for "~~" in the comments).

This macro is only tested on Outlook 2010.

' ------------------------------------------------------------
' Requires the following references:
'
' Visual Basic for Applications
' Microsoft Outlook 14.0 Object Library
' OLE Automation
' Microsoft Office 14.0 Object Library
' Microsoft Shell Controls and Automation
' ------------------------------------------------------------

Public Sub SaveOLFolderAttachments()

  ' Ask the user to select a file system folder for saving the attachments
  Dim oShell As Object
  Set oShell = CreateObject("Shell.Application")
  Dim fsSaveFolder As Object
  Set fsSaveFolder = oShell.BrowseForFolder(0, "Please Select a Save Folder:", 1)
  If fsSaveFolder Is Nothing Then Exit Sub
  ' Note:  BrowseForFolder doesn't add a trailing slash

  ' Ask the user to select an Outlook folder to process
  Dim olPurgeFolder As Outlook.MAPIFolder
  Set olPurgeFolder = Outlook.GetNamespace("MAPI").PickFolder
  If olPurgeFolder Is Nothing Then Exit Sub

  ' Iteration variables
  Dim msg As Outlook.MailItem
  Dim att As Outlook.attachment
  Dim sSavePathFS As String
  Dim sDelAtts

  For Each msg In olPurgeFolder.Items

    sDelAtts = ""

    ' We check each msg for attachments as opposed to using .Restrict("[Attachment] > 0")
    ' on our olPurgeFolder.Items collection.  The collection returned by the Restrict method
    ' will be dynamically updated each time we remove an attachment.  Each update will
    ' reindex the collection.  As a result, it does not provide a reliable means for iteration.
    ' This is why the For Each loops will not work.
    If msg.Attachments.Count > 0 Then

      ' This While loop is controlled via the .Delete method
      ' which will decrement msg.Attachments.Count by one each time.
      While msg.Attachments.Count > 0

        ' Save the file
        sSavePathFS = fsSaveFolder.Self.Path & "\" & msg.Attachments(1).FileName
        msg.Attachments(1).SaveAsFile sSavePathFS

        ' Build up a string to denote the file system save path(s)
        ' Format the string according to the msg.BodyFormat.
        If msg.BodyFormat <> olFormatHTML Then
            sDelAtts = sDelAtts & vbCrLf & "<file://" & sSavePathFS & ">"
        Else
            sDelAtts = sDelAtts & "<br>" & "<a href='file://" & sSavePathFS & "'>" & sSavePathFS & "</a>"
        End If

        ' Delete the current attachment.  We use a "1" here instead of an "i"
        ' because the .Delete method will shrink the size of the msg.Attachments
        ' collection for us.  Use some well placed Debug.Print statements to see
        ' the behavior.
        msg.Attachments(1).Delete

      Wend

      ' Modify the body of the msg to show the file system location of
      ' the deleted attachments.
      If msg.BodyFormat <> olFormatHTML Then
        msg.Body = msg.Body & vbCrLf & vbCrLf & "Attachments Deleted:  " & Date & " " & Time & vbCrLf & vbCrLf & "Saved To:  " & vbCrLf & sDelAtts
      Else
        msg.HTMLBody = msg.HTMLBody & "<p></p><p>" & "Attachments Deleted:  " & Date & " " & Time & vbCrLf & vbCrLf & "Saved To:  " & vbCrLf & sDelAtts & "</p>"
      End If

      ' Save the edits to the msg.  If you forget this line, the attachments will not be deleted.
      msg.Save

    End If

  Next

End Sub


问:
Retrofit - Change BaseUrl
I have a scenario where I have to call an API with the same base URL, e.g. www.myAPI.com but with a different baseUrl.

I have an instance of Retrofit 2 which is built via a Builder:

```<code>return new Retrofit.Builder()
    .baseUrl(FlavourConstants.BASE_URL)
    .addConverterFactory(GsonConverterFactory.create(gson))
    .client(okHttpClient)
    .build();
</code>```

The FlavourConstants.BASE_URL looks like this:

```<code>public static final String BASE_URL = "http://myApi.development:5000/api/v1/";
</code>```

For some WebRequests, I must call the same API but on others, I must call it from a completely different BaseUrl. How do I change the Retrofit instance to therefore point to a different URL during runtime?

The Retrofit instance doesn't have a .setBaseUrl or setter or anything similar as it's built via a Builder.

Any ideas?

答:
Ok , if I dont remember wrong the docs of Retrofit says you can point to another URL if you just simply add in your interface servicse the full url of the ws, that is different fomr the BASE_URL in Retrofit Builder. One example...</p>

```<code>public interface UserManager {
    @GET("put here ur entire url of the service")
    public Call<ResponseBody> getSomeStuff();
}
</code>```

Title: Retrofit - Change BaseUrl

Body:
I have a scenario where I have to call an API with the same base URL, e.g. www.myAPI.com but with a different baseUrl.

I have an instance of Retrofit 2 which is built via a Builder:

return new Retrofit.Builder()
    .baseUrl(FlavourConstants.BASE_URL)
    .addConverterFactory(GsonConverterFactory.create(gson))
    .client(okHttpClient)
    .build();

The FlavourConstants.BASE_URL looks like this:

public static final String BASE_URL = "http://myApi.development:5000/api/v1/";

For some WebRequests, I must call the same API but on others, I must call it from a completely different BaseUrl. How do I change the Retrofit instance to therefore point to a different URL during runtime?

The Retrofit instance doesn't have a .setBaseUrl or setter or anything similar as it's built via a Builder.

Any ideas?

Body:
Ok , if I dont remember wrong the docs of Retrofit says you can point to another URL if you just simply add in your interface servicse the full url of the ws, that is different fomr the BASE_URL in Retrofit Builder. One example...

public interface UserManager {
    @GET("put here ur entire url of the service")
    public Call<ResponseBody> getSomeStuff();
}


问:
Display IF output somewhere else PhP
So i have got this code:

```<code><?php
$host = "http://$_SERVER[HTTP_HOST]";
    $rd = "/beta/";
    $beta = "<font color='#6034b1'>BETA</font>";
    if(isset($_COOKIE["fg_beta_user"]) && $_COOKIE["fg_beta_user"]){
    header('Refresh:10;' . $host.$rd);
    echo "<center>You are member of the $beta Project<br>You will be redirected in:<div id='countdown'>10</div><br><progress value='0' max='9' id='progressBar'></progress></center>";}
        else {
    echo "<center>You are not a Member of our $beta Project!<br><a style='border-bottom:1px solid black;' href='switch-to-beta.php'>JOIN NOW</a>";
    }
    ?>
</code>```

Since I have to Place the PhP Script before my  tag so the header refresh works, the echo messages get displayed on the very top of the page ( Basically behind my Navbar).

So now my question, is there a way to display the output of this if statement via something like a variable somwhere else on the site?

答:
It is quite simple to display your message elsewhere on the page.

```<code><?php
$host = "http://$_SERVER[HTTP_HOST]";
$rd = "/beta/";
$beta = "<font color='#6034b1'>BETA</font>";
if(isset($_COOKIE["fg_beta_user"]) && $_COOKIE["fg_beta_user"]){
header('Refresh:10;' . $host.$rd);
$message = "<center>You are member of the " . $beta . " Project<br>You will be redirected in:<div id='countdown'>10</div><br><progress value='0' max='9' id='progressBar'></progress></center>";
}
    else {
$message = "<center>You are not a Member of our " . $beta . "Project!<br><a style='border-bottom:1px solid black;' href='switch-to-beta.php'>JOIN NOW</a>";
}
?>
</code>```

Then at where ever you want the message to appear add this line of code:

```<code><?php
  echo $message;
?>
</code>```

Title: Display IF output somewhere else PhP

Body:
So i have got this code:

<?php
$host = "http://$_SERVER[HTTP_HOST]";
    $rd = "/beta/";
    $beta = "BETA";
    if(isset($_COOKIE["fg_beta_user"]) && $_COOKIE["fg_beta_user"]){
    header('Refresh:10;' . $host.$rd);
    echo "You are member of the $beta Project
You will be redirected in:
10

<progress value='0' max='9' id='progressBar'></progress>";}
        else {
    echo "You are not a Member of our $beta Project!
JOIN NOW";
    }
    ?>

Since I have to Place the PhP Script before my  tag so the header refresh works, the echo messages get displayed on the very top of the page ( Basically behind my Navbar).

So now my question, is there a way to display the output of this if statement via something like a variable somwhere else on the site?

Body:
It is quite simple to display your message elsewhere on the page.

<?php
$host = "http://$_SERVER[HTTP_HOST]";
$rd = "/beta/";
$beta = "<font color='#6034b1'>BETA</font>";
if(isset($_COOKIE["fg_beta_user"]) && $_COOKIE["fg_beta_user"]){
header('Refresh:10;' . $host.$rd);
$message = "<center>You are member of the " . $beta . " Project<br>You will be redirected in:<div id='countdown'>10</div><br><progress value='0' max='9' id='progressBar'></progress></center>";
}
    else {
$message = "<center>You are not a Member of our " . $beta . "Project!<br><a style='border-bottom:1px solid black;' href='switch-to-beta.php'>JOIN NOW</a>";
}
?>

Then at where ever you want the message to appear add this line of code:

<?php
  echo $message;
?>


问:
Pod succesfully installed in my app but files are not imported
Pod succesfully installed in my app but files are not imported

Please kindly any one help me this .

Example: I installed SCLAlertView library in my app but not able to import files with XCode 9.

答:
If you are using public Pod and if some problem are coming then First update your Cocoapod in your System and follow below steps:

remove existing pod from your app from Build Phase tab (All Targets)

use pod init to create pod file

Add your pods for each target separately

pod install

pod update (if required)

I have faced pod problem while switching xcode 8.3.3 to XCode 9, and it helped me.


问:
NServiceBus MSDTC woes
I am writing this post here in hopes that someone can help me out.

I am trying to implement NServiceBus on an ASP.NET MVC application. I have gone through each and every step to ensure that everything is wired up right. I have an event that passes a Job Id to my handler which then performs a Linq-to-Sql query and looks up a job and then emails an alert. The process is very simple.

However, I cannot for the life of me get MSDTC to work. I keep on getting the following error:

Here is how I have my Bus configured:

```<code> Bus = NServiceBus.Configure.WithWeb()
            .Log4Net()
            .DefaultBuilder()
            .XmlSerializer()
            .MsmqTransport()
                .IsTransactional(false)
                .PurgeOnStartup(false)
            .UnicastBus()
                .ImpersonateSender(false)
            .CreateBus()
            .Start();
</code>```

I am not using Transactions so I know for a fact that MSDTC should not even be called.

My Handler code is as follows:

```<code>public void Handle(ApplyJobMessage message)
    {
        if (message != null)
        {
            using(var context = new MyContext())
            {
                JobPosting posting = (from c in context.JobPostings
                 where c.JobPostingId == message.JobId
                 select c).SingleOrDefault();
            }
</code>```

The endpoint is configured as follows:

```<code>public class MessageEndpoint : IConfigureThisEndpoint, AsA_Server, IWantToRunAtStartup
</code>```

Everything works great. The message arrives correctly when I do:

```<code>Bus.Send(message);
</code>```

However, the MSDTC error occurs as shown:

```<code>    2011-01-20 00:55:09,744 [Worker.5] ERROR NServiceBus.Unicast.UnicastBus [(null)]
 <(null)> - JobApplicationHandler Failed handling message.
System.Runtime.InteropServices.COMException (0x8004D02A): The MSDTC transaction
manager was unable to push the transaction to the destination transaction manage
r due to communication problems. Possible causes are: a firewall is present and
it doesn't have an exception for the MSDTC process, the two machines cannot find
 each other by their NetBIOS names, or the support for network transactions is n
ot enabled for one of the two transaction managers. (Exception from HRESULT: 0x8
004D02A)
   at **System.Transactions.Oletx.ITransactionShim.Export**(UInt32 whereaboutsSize,
Byte[] whereabouts, Int32& cookieIndex, UInt32& cookieSize, CoTaskMemHandle& coo
kieBuffer)
   at System.Transactions.TransactionInterop.GetExportCookie(Transaction transac
tion, Byte[] whereabouts)
2011-01-20 00:55:09,749 [Worker.5] WARN  NServiceBus.Unicast.Transport.Msmq.Msmq
Transport [(null)] <(null)> - Failed raising 'transport message received' event
for message with ID=9cb4b136-e110-4b87-81f6-ee4cd3fcaf46\6151
System.Reflection.TargetInvocationException: Exception has been thrown by the ta
rget of an invocation. ---> System.Transactions.TransactionManagerCommunicationE
xception: Communication with the underlying transaction manager has failed. --->
 System.Runtime.InteropServices.COMException (0x8004D02A): The MSDTC transaction
 manager was unable to push the transaction to the destination transaction manag
er due to communication problems. Possible causes are: a firewall is present and
 it doesn't have an exception for the MSDTC process, the two machines cannot fin
d each other by their NetBIOS names, or the support for network transactions is
not enabled for one of the two transaction managers. (Exception from HRESULT: 0x
8004D02A)
   at System.Transactions.Oletx.ITransactionShim.Export(UInt32 whereaboutsSize,
Byte[] whereabouts, Int32& cookieIndex, UInt32& cookieSize, CoTaskMemHandle& coo
kieBuffer)
   at System.Transactions.TransactionInterop.GetExportCookie(Transaction transac
tion, Byte[] whereabouts)
   --- End of inner exception stack trace ---
   at System.Transactions.TransactionInterop.GetExportCookie(Transaction transac
tion, Byte[] whereabouts)
   at System.Data.SqlClient.SqlInternalConnection.GetTransactionCookie(Transacti
on transaction, Byte[] whereAbouts)
   at System.Data.SqlClient.SqlInternalConnection.EnlistNonNull(Transaction tx)
   at System.Data.SqlClient.SqlInternalConnection.Enlist(Transaction tx)
   at System.Data.SqlClient.SqlInternalConnectionTds.Activate(Transaction transa
ction)
   at System.Data.ProviderBase.DbConnectionInternal.ActivateConnection(Transacti
on transaction)
   at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection ownin
gObject)
   at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection ow
ningConnection)
   at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection ou
terConnection, DbConnectionFactory connectionFactory)
   at System.Data.SqlClient.SqlConnection.Open()
   at System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionU
ser user)
   at System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe()
   at System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode()
   at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider
.Execute(Expression query)
   at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Express
ion expression)
   at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)
</code>```

I have tried DTC ping and it successfully works so I know for a fact that MSDTC isn't the issue. I have read that NHibernate had similar issues with NServiceBus but I haven't been able to draw any parallels on the same with LINQ to SQL.

Any help on this matter would be very appreciated.

答: What I notice is that you're configuring NServiceBus as a server, which means that it is transactional. I think what you have here is a non-transactional web app which is sending messages to a transactional server.

Title: NServiceBus MSDTC woes

Body:
I am writing this post here in hopes that someone can help me out.

I am trying to implement NServiceBus on an ASP.NET MVC application. I have gone through each and every step to ensure that everything is wired up right. I have an event that passes a Job Id to my handler which then performs a Linq-to-Sql query and looks up a job and then emails an alert. The process is very simple.

However, I cannot for the life of me get MSDTC to work. I keep on getting the following error:

Here is how I have my Bus configured:

 Bus = NServiceBus.Configure.WithWeb()
            .Log4Net()
            .DefaultBuilder()
            .XmlSerializer()
            .MsmqTransport()
                .IsTransactional(false)
                .PurgeOnStartup(false)
            .UnicastBus()
                .ImpersonateSender(false)
            .CreateBus()
            .Start();

I am not using Transactions so I know for a fact that MSDTC should not even be called.

My Handler code is as follows:

public void Handle(ApplyJobMessage message)
    {
        if (message != null)
        {
            using(var context = new MyContext())
            {
                JobPosting posting = (from c in context.JobPostings
                 where c.JobPostingId == message.JobId
                 select c).SingleOrDefault();
            }

The endpoint is configured as follows:

public class MessageEndpoint : IConfigureThisEndpoint, AsA_Server, IWantToRunAtStartup

Everything works great. The message arrives correctly when I do:

Bus.Send(message);

However, the MSDTC error occurs as shown:

    2011-01-20 00:55:09,744 [Worker.5] ERROR NServiceBus.Unicast.UnicastBus [(null)]
 <(null)> - JobApplicationHandler Failed handling message.
System.Runtime.InteropServices.COMException (0x8004D02A): The MSDTC transaction
manager was unable to push the transaction to the destination transaction manage
r due to communication problems. Possible causes are: a firewall is present and
it doesn't have an exception for the MSDTC process, the two machines cannot find
 each other by their NetBIOS names, or the support for network transactions is n
ot enabled for one of the two transaction managers. (Exception from HRESULT: 0x8
004D02A)
   at **System.Transactions.Oletx.ITransactionShim.Export**(UInt32 whereaboutsSize,
Byte[] whereabouts, Int32& cookieIndex, UInt32& cookieSize, CoTaskMemHandle& coo
kieBuffer)
   at System.Transactions.TransactionInterop.GetExportCookie(Transaction transac
tion, Byte[] whereabouts)
2011-01-20 00:55:09,749 [Worker.5] WARN  NServiceBus.Unicast.Transport.Msmq.Msmq
Transport [(null)] <(null)> - Failed raising 'transport message received' event
for message with ID=9cb4b136-e110-4b87-81f6-ee4cd3fcaf46\6151
System.Reflection.TargetInvocationException: Exception has been thrown by the ta
rget of an invocation. ---> System.Transactions.TransactionManagerCommunicationE
xception: Communication with the underlying transaction manager has failed. --->
 System.Runtime.InteropServices.COMException (0x8004D02A): The MSDTC transaction
 manager was unable to push the transaction to the destination transaction manag
er due to communication problems. Possible causes are: a firewall is present and
 it doesn't have an exception for the MSDTC process, the two machines cannot fin
d each other by their NetBIOS names, or the support for network transactions is
not enabled for one of the two transaction managers. (Exception from HRESULT: 0x
8004D02A)
   at System.Transactions.Oletx.ITransactionShim.Export(UInt32 whereaboutsSize,
Byte[] whereabouts, Int32& cookieIndex, UInt32& cookieSize, CoTaskMemHandle& coo
kieBuffer)
   at System.Transactions.TransactionInterop.GetExportCookie(Transaction transac
tion, Byte[] whereabouts)
   --- End of inner exception stack trace ---
   at System.Transactions.TransactionInterop.GetExportCookie(Transaction transac
tion, Byte[] whereabouts)
   at System.Data.SqlClient.SqlInternalConnection.GetTransactionCookie(Transacti
on transaction, Byte[] whereAbouts)
   at System.Data.SqlClient.SqlInternalConnection.EnlistNonNull(Transaction tx)
   at System.Data.SqlClient.SqlInternalConnection.Enlist(Transaction tx)
   at System.Data.SqlClient.SqlInternalConnectionTds.Activate(Transaction transa
ction)
   at System.Data.ProviderBase.DbConnectionInternal.ActivateConnection(Transacti
on transaction)
   at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection ownin
gObject)
   at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection ow
ningConnection)
   at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection ou
terConnection, DbConnectionFactory connectionFactory)
   at System.Data.SqlClient.SqlConnection.Open()
   at System.Data.Linq.SqlClient.SqlConnectionManager.UseConnection(IConnectionU
ser user)
   at System.Data.Linq.SqlClient.SqlProvider.get_IsSqlCe()
   at System.Data.Linq.SqlClient.SqlProvider.InitializeProviderMode()
   at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider
.Execute(Expression query)
   at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Express
ion expression)
   at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)

I have tried DTC ping and it successfully works so I know for a fact that MSDTC isn't the issue. I have read that NHibernate had similar issues with NServiceBus but I haven't been able to draw any parallels on the same with LINQ to SQL.

Any help on this matter would be very appreciated.