问:
UIScrollView is eating up my swipe gestures Swift
I have the below code that sets up a vertical scrollview My question is that the views within the view controllers do not respond accurately to swipe gestures. For example in this scrollview, bottomVc contains swipe gestures for left and right swipes. When this view controller is isolated in another project it works flawlessly, but the swipe gestures don't work when it is within the scrollview below. I was wondering how I could fix this issue so that my viewconttollers can handle swipe gestures while being in the scrollview. Also FYI, the code that controls the other view controllers are in separate files along with the swipe gestures.
The code:

    import UIKit

```<code>class VerticalScrollViewController: UIViewController, SnapContainerViewControllerDelegate {

var topVc: UIViewController!
var middleVc: UIViewController!
var bottomVc: UIViewController!
var scrollView: UIScrollView!

class func verticalScrollVcWith(middleVc: UIViewController,
                                topVc: UIViewController?=nil,
                                bottomVc: UIViewController?=nil) -> VerticalScrollViewController {
    let middleScrollVc = VerticalScrollViewController()

    middleScrollVc.topVc = topVc
    middleScrollVc.middleVc = middleVc
    middleScrollVc.bottomVc = bottomVc

    return middleScrollVc
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view:
    setupScrollView()
}

func setupScrollView() {
    scrollView = UIScrollView()
    scrollView.isPagingEnabled = true
    scrollView.showsVerticalScrollIndicator = false
    scrollView.bounces = false

    let view = (
        x: self.view.bounds.origin.x,
        y: self.view.bounds.origin.y,
        width: self.view.bounds.width,
        height: self.view.bounds.height
    )

    scrollView.frame = CGRect(x: view.x, y: view.y, width: view.width, height: view.height)
    self.view.addSubview(scrollView)

    let scrollWidth: CGFloat  = view.width
    var scrollHeight: CGFloat

    if topVc != nil && bottomVc != nil {
        scrollHeight  = 3 * view.height
        middleVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
        topVc.view.frame = CGRect(x: 0, y: view.height, width: view.width, height: view.height)
        bottomVc.view.frame = CGRect(x: 0, y: 2 * view.height, width: view.width, height: view.height)

        addChildViewController(topVc)
        addChildViewController(middleVc)
        addChildViewController(bottomVc)

        scrollView.addSubview(topVc.view)
        scrollView.addSubview(middleVc.view)
        scrollView.addSubview(bottomVc.view)

        topVc.didMove(toParentViewController: self)
        middleVc.didMove(toParentViewController: self)
        bottomVc.didMove(toParentViewController: self)

        //scrollView.contentOffset.y = middleVc.view.frame.origin.y
        scrollView.contentOffset.y = topVc.view.frame.origin.y

    } else if topVc == nil {
        scrollHeight  = 2 * view.height
        middleVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
        bottomVc.view.frame = CGRect(x: 0, y: view.height, width: view.width, height: view.height)

        addChildViewController(middleVc)
        addChildViewController(bottomVc)

        scrollView.addSubview(middleVc.view)
        scrollView.addSubview(bottomVc.view)

        middleVc.didMove(toParentViewController: self)
        bottomVc.didMove(toParentViewController: self)

        scrollView.contentOffset.y = 0

    } else if bottomVc == nil {
        scrollHeight  = 2 * view.height
        topVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
        middleVc.view.frame = CGRect(x: 0, y: view.height, width: view.width, height: view.height)

        addChildViewController(topVc)
        addChildViewController(middleVc)

        scrollView.addSubview(topVc.view)
        scrollView.addSubview(middleVc.view)

        topVc.didMove(toParentViewController: self)
        middleVc.didMove(toParentViewController: self)

        scrollView.contentOffset.y = middleVc.view.frame.origin.y

    } else {
        scrollHeight  = view.height
        middleVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)

        addChildViewController(middleVc)
        scrollView.addSubview(middleVc.view)
        middleVc.didMove(toParentViewController: self)
    }

    scrollView.contentSize = CGSize(width: scrollWidth, height: scrollHeight)
    scrollView.delaysContentTouches = false

}

func outerScrollViewShouldScroll() -> Bool {
    if scrollView.contentOffset.y < middleVc.view.frame.origin.y || scrollView.contentOffset.y > middleVc.view.frame.origin.y {

        return false

    } else {

        return true
    }

}

}
</code>```

答:
Try adding the UIGestureRecognizerDelegate protocol to your class, then adding this method to return true :

```<code>    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }
</code>```

Should work, unless your controller setup is somehow preventing proper touch recognition..

Body:
I have the below code that sets up a vertical scrollview My question is that the views within the view controllers do not respond accurately to swipe gestures. For example in this scrollview, bottomVc contains swipe gestures for left and right swipes. When this view controller is isolated in another project it works flawlessly, but the swipe gestures don't work when it is within the scrollview below. I was wondering how I could fix this issue so that my viewconttollers can handle swipe gestures while being in the scrollview. Also FYI, the code that controls the other view controllers are in separate files along with the swipe gestures.
The code:

    import UIKit

class VerticalScrollViewController: UIViewController, SnapContainerViewControllerDelegate {

var topVc: UIViewController!
var middleVc: UIViewController!
var bottomVc: UIViewController!
var scrollView: UIScrollView!

class func verticalScrollVcWith(middleVc: UIViewController,
                                topVc: UIViewController?=nil,
                                bottomVc: UIViewController?=nil) -> VerticalScrollViewController {
    let middleScrollVc = VerticalScrollViewController()

    middleScrollVc.topVc = topVc
    middleScrollVc.middleVc = middleVc
    middleScrollVc.bottomVc = bottomVc

    return middleScrollVc
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view:
    setupScrollView()
}

func setupScrollView() {
    scrollView = UIScrollView()
    scrollView.isPagingEnabled = true
    scrollView.showsVerticalScrollIndicator = false
    scrollView.bounces = false

    let view = (
        x: self.view.bounds.origin.x,
        y: self.view.bounds.origin.y,
        width: self.view.bounds.width,
        height: self.view.bounds.height
    )

    scrollView.frame = CGRect(x: view.x, y: view.y, width: view.width, height: view.height)
    self.view.addSubview(scrollView)

    let scrollWidth: CGFloat  = view.width
    var scrollHeight: CGFloat

    if topVc != nil && bottomVc != nil {
        scrollHeight  = 3 * view.height
        middleVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
        topVc.view.frame = CGRect(x: 0, y: view.height, width: view.width, height: view.height)
        bottomVc.view.frame = CGRect(x: 0, y: 2 * view.height, width: view.width, height: view.height)

        addChildViewController(topVc)
        addChildViewController(middleVc)
        addChildViewController(bottomVc)

        scrollView.addSubview(topVc.view)
        scrollView.addSubview(middleVc.view)
        scrollView.addSubview(bottomVc.view)

        topVc.didMove(toParentViewController: self)
        middleVc.didMove(toParentViewController: self)
        bottomVc.didMove(toParentViewController: self)

        //scrollView.contentOffset.y = middleVc.view.frame.origin.y
        scrollView.contentOffset.y = topVc.view.frame.origin.y

    } else if topVc == nil {
        scrollHeight  = 2 * view.height
        middleVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
        bottomVc.view.frame = CGRect(x: 0, y: view.height, width: view.width, height: view.height)

        addChildViewController(middleVc)
        addChildViewController(bottomVc)

        scrollView.addSubview(middleVc.view)
        scrollView.addSubview(bottomVc.view)

        middleVc.didMove(toParentViewController: self)
        bottomVc.didMove(toParentViewController: self)

        scrollView.contentOffset.y = 0

    } else if bottomVc == nil {
        scrollHeight  = 2 * view.height
        topVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)
        middleVc.view.frame = CGRect(x: 0, y: view.height, width: view.width, height: view.height)

        addChildViewController(topVc)
        addChildViewController(middleVc)

        scrollView.addSubview(topVc.view)
        scrollView.addSubview(middleVc.view)

        topVc.didMove(toParentViewController: self)
        middleVc.didMove(toParentViewController: self)

        scrollView.contentOffset.y = middleVc.view.frame.origin.y

    } else {
        scrollHeight  = view.height
        middleVc.view.frame = CGRect(x: 0, y: 0, width: view.width, height: view.height)

        addChildViewController(middleVc)
        scrollView.addSubview(middleVc.view)
        middleVc.didMove(toParentViewController: self)
    }

    scrollView.contentSize = CGSize(width: scrollWidth, height: scrollHeight)
    scrollView.delaysContentTouches = false

}

func outerScrollViewShouldScroll() -> Bool {
    if scrollView.contentOffset.y < middleVc.view.frame.origin.y || scrollView.contentOffset.y > middleVc.view.frame.origin.y {

        return false

    } else {

        return true
    }

}

}

Body:
Try adding the UIGestureRecognizerDelegate protocol to your class, then adding this method to return true :

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }

Should work, unless your controller setup is somehow preventing proper touch recognition..


来源: stackexchange

问:
Deploying project in Docker with Angular 4, Django and postgresql
I am trying to deploy on Heroku my project in Docker with Angular 4 frontend with Django backend and postgresql database. At this moment my files look as shown below. I am note sure if this is done properly? I pushed it using heroku container:push web --app myproject but it doesn't work (Logs). I assume that if I use Docker I don't have to create Procfile etc.? May the error be caused by lack of migration of database?

I have no idea that I'm moving into the right direction but I'm trying to migrate my database. Maybe my error is caused by lack of db?

When I run heroku run python manage.py migrate, I get:

django.db.utils.OperationalError: could not translate host name "db"
  to address: Name or service not known

Logs:

```<code>2017-07-07T10:27:30.448951+00:00 heroku[web.1]: State changed from crashed to starting
2017-07-07T10:27:30.436282+00:00 heroku[web.1]: Process exited with status 0
2017-07-07T10:27:50.846928+00:00 heroku[web.1]: Starting process with command `python3`
2017-07-07T10:27:53.350381+00:00 heroku[web.1]: Process exited with status 0
2017-07-07T10:27:53.365013+00:00 heroku[web.1]: State changed from starting to crashed
2017-07-07T10:27:53.876208+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=e1f8edfc-7dc4-4bd3-91be-0a853e948452 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:28:43.444860+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=361846d1-41cd-403a-989f-4c29a0d1179e fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:28:43.984059+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host= myproject.herokuapp.com request_id=658795c8-0ba7-4988-9d39-34601b1334c7 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:28:44.673789+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=63fbabdc-7ba7-4997-81be-c601a0d83368 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:29:53.091547+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=a3943544-9dc4-44f0-b788-a462cdfba7d0 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:29:54.419623+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=eb5191e2-21d9-410c-823e-c57bb0fb7fa4 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
</code>```

Project tree:

```<code>├── Backend
│   ├── AI
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── __init__.cpython-36.pyc
│   │   │   ├── settings.cpython-36.pyc
│   │   │   ├── urls.cpython-36.pyc
│   │   │   └── wsgi.cpython-36.pyc
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py
│   └── manage.py
├── Dockerfile
├── init.sql
├── Frontend
│   └── angularProject
        ├── Dockerfile
│       └── all files in my angular project
├── docker-compose.yml
└── requirements.txt
</code>```

Frontend's Dockerfile:

```<code># Create image based on the official Node 6 image from dockerhub
FROM node:6

# Create a directory where our app will be placed
RUN mkdir -p /usr/src/app

# Change directory so that our commands run inside this new directory
WORKDIR /usr/src/app

# Copy dependency definitions
COPY package.json /usr/src/app

# Install dependecies
RUN npm install

# Get all the code needed to run the app
COPY . /usr/src/app

# Expose the port the app runs in
EXPOSE 4200

# Serve the app
CMD ["npm", "start"]
</code>```

Main directory's Dockerfile:

```<code>FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/
</code>```

docker-compose.yml:

```<code>version: '3'

services:
  db:
    image: postgres
    environment:
      POSTGRES_USER: aso
      POSTGRES_PASSWORD: somepass
  django:
    build: .
    command: python3 MainDirectory/backend/myProject/manage.py runserver 0.0.0.0:8001
    volumes:
      - .:/code
    ports:
      - "8001:8001"
    depends_on:
      - db
  angular:
    build: MainDirectory/frontend
    ports:
      - "4200:4200"
    depends_on:
      - django
</code>```

init.sql:

```<code>CREATE USER myUser;
CREATE DATABASE myProject;
GRANT ALL PRIVILEGES ON DATABASE myProject TO myUser;
</code>```

答:
You should use docker networks to link the containers together.

Something like this:

```<code>version: '3'

services:
    db:
        image: postgres
        environment:
            POSTGRES_USER: aso
            POSTGRES_PASSWORD: somepass
        networks:
            - app
    django:
        build: .
        command: python3 MainDirectory/backend/myProject/manage.py runserver 0.0.0.0:8001
        volumes:
            - .:/code
        ports:
            - "8001:8001"
        networks:
            - app
        depends_on:
            - db
    angular:
        build: MainDirectory/frontend
        ports:
            - "4200:4200"
        networks:
            - app
        depends_on:
            - django
networks:
    app:
</code>```

This allows you to more easily add and remove containers and services that need to communicate than links.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to deploy on Heroku my project in Docker with Angular 4 frontend with Django backend and postgresql database. At this moment my files look as shown below. I am note sure if this is done properly? I pushed it using heroku container:push web --app myproject but it doesn't work (Logs). I assume that if I use Docker I don't have to create Procfile etc.? May the error be caused by lack of migration of database?

I have no idea that I'm moving into the right direction but I'm trying to migrate my database. Maybe my error is caused by lack of db?

When I run heroku run python manage.py migrate, I get:

django.db.utils.OperationalError: could not translate host name "db"
  to address: Name or service not known

Logs:

2017-07-07T10:27:30.448951+00:00 heroku[web.1]: State changed from crashed to starting
2017-07-07T10:27:30.436282+00:00 heroku[web.1]: Process exited with status 0
2017-07-07T10:27:50.846928+00:00 heroku[web.1]: Starting process with command `python3`
2017-07-07T10:27:53.350381+00:00 heroku[web.1]: Process exited with status 0
2017-07-07T10:27:53.365013+00:00 heroku[web.1]: State changed from starting to crashed
2017-07-07T10:27:53.876208+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=e1f8edfc-7dc4-4bd3-91be-0a853e948452 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:28:43.444860+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=361846d1-41cd-403a-989f-4c29a0d1179e fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:28:43.984059+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host= myproject.herokuapp.com request_id=658795c8-0ba7-4988-9d39-34601b1334c7 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:28:44.673789+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=63fbabdc-7ba7-4997-81be-c601a0d83368 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:29:53.091547+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=a3943544-9dc4-44f0-b788-a462cdfba7d0 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https
2017-07-07T10:29:54.419623+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=eb5191e2-21d9-410c-823e-c57bb0fb7fa4 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https

Project tree:

├── Backend
│   ├── AI
│   │   ├── __init__.py
│   │   ├── __pycache__
│   │   │   ├── __init__.cpython-36.pyc
│   │   │   ├── settings.cpython-36.pyc
│   │   │   ├── urls.cpython-36.pyc
│   │   │   └── wsgi.cpython-36.pyc
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py
│   └── manage.py
├── Dockerfile
├── init.sql
├── Frontend
│   └── angularProject
        ├── Dockerfile
│       └── all files in my angular project
├── docker-compose.yml
└── requirements.txt

Frontend's Dockerfile:

# Create image based on the official Node 6 image from dockerhub
FROM node:6

# Create a directory where our app will be placed
RUN mkdir -p /usr/src/app

# Change directory so that our commands run inside this new directory
WORKDIR /usr/src/app

# Copy dependency definitions
COPY package.json /usr/src/app

# Install dependecies
RUN npm install

# Get all the code needed to run the app
COPY . /usr/src/app

# Expose the port the app runs in
EXPOSE 4200

# Serve the app
CMD ["npm", "start"]

Main directory's Dockerfile:

FROM python:3.6.1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
ADD requirements.txt /code/
RUN pip3 install -r requirements.txt
ADD . /code/

docker-compose.yml:

version: '3'

services:
  db:
    image: postgres
    environment:
      POSTGRES_USER: aso
      POSTGRES_PASSWORD: somepass
  django:
    build: .
    command: python3 MainDirectory/backend/myProject/manage.py runserver 0.0.0.0:8001
    volumes:
      - .:/code
    ports:
      - "8001:8001"
    depends_on:
      - db
  angular:
    build: MainDirectory/frontend
    ports:
      - "4200:4200"
    depends_on:
      - django

init.sql:

CREATE USER myUser;
CREATE DATABASE myProject;
GRANT ALL PRIVILEGES ON DATABASE myProject TO myUser;

Body:
You should use docker networks to link the containers together.

Something like this:

version: '3'

services:
    db:
        image: postgres
        environment:
            POSTGRES_USER: aso
            POSTGRES_PASSWORD: somepass
        networks:
            - app
    django:
        build: .
        command: python3 MainDirectory/backend/myProject/manage.py runserver 0.0.0.0:8001
        volumes:
            - .:/code
        ports:
            - "8001:8001"
        networks:
            - app
        depends_on:
            - db
    angular:
        build: MainDirectory/frontend
        ports:
            - "4200:4200"
        networks:
            - app
        depends_on:
            - django
networks:
    app:

This allows you to more easily add and remove containers and services that need to communicate than links.


问:
JSON-RPC - Cannot retrieve correct POST data response from a logged in site with Python Requests library
Setup: Python 2.7.10, Requests library, Windows 8.1

I am new to json-rpc and need to set up automation tests for sending POST requests and checking the response. I am having difficulty accessing the data after logging in. I need to log in to the system first with a POST request ("method": "identity.authenticate"), and then the test after that is also a POST request that should return data after I have been logged in.

The developers also gave me a Bearer token to pass in the Headers which they claimed should work across all tests, and it did seem to work when I tried it in Postman (although I did have some mixed results), but for some reason when I try to use it with my Python Requests set up, it returns an error every time. The code is below (have to change the working data to dummy data, so trying to run the below code as-is won't work, but hopefully seeing the set up can help to pinpoint what I may be doing wrong):

```<code>import requests
from pprint import pprint

base_url = "https://rpc_url.com/rpc"
custom_headers = {"Content-Type":"application/json", "Authorization":"Bearer token"}

'''Sign in payload'''
signinPayload = {"method" : "identity.authenticate",
"id" : 1,
"jsonrpc" : "2.0",
"params" : {"password" : "password", "username" : "username"}}

test1_Payload = {"jsonrpc" : "2.0",
"method" : "fc.pick.getPendingPicks",
"id" : 20, "params" :{"_tags" :{"device" : "device",
  "deviceOS" : "deviceOS", "firstName" : "firstName",
  "devicetype" : "devicetype", "appVersion" : "appVersion",
  "login" : "username", "devicelabel" : "devicelabel",
  "lastName" : "lastName"}}}

with requests.Session() as s:
    # below passes the login payload, which returns proper data.
    login_post = s.post(base_url, json=signinPayload, headers=custom_headers).json()
    pprint(login_post)
    ###########################
    # passes the test payload, which doesn't work correctly
    r = s.post(base_url, json=test1_Payload, headers=custom_headers).json()
    pprint(r)
</code>```

I've tried many variations, such as not passing the Bearer token in the headers, only passing the Bearer token and not the signin payload, and nothing has worked so far.

When I run the above code with non-dummy data, this is the console output (with my added comments for clarity):

```<code># Below is returned for sign in authenticate, which appears to be good data
{u'fcFlingVersion': u'1.0.9',
    u'id': 1, u'jsonrpc':
    u'2.0',
    u'result': {
         u'_idp': {u'accessToken': 'accessTokenNumber'},
         u'administratorId': 1,
         u'changePassword': False,
         u'companyId': 1,
         u'daysUntilPasswordExpires': 100,
         u'firstname': u'firstName',
         u'groupList': u'groupList',
         u'lastname': u'lastName',
         u'login': u'username',
         u'passwordDirectory': u'identity',
         u'photoUrl': u'https://photoURL',
         u'roles': [],
         u'userId': 1,
         u'username': u'username'}}

# Below is the returned error data for test1_Payload after the successful sign in test from above.
{u'error': {u'code': 404, u'data': None, u'message': u'module not found'},
 u'fcFlingVersion': u'1.0.9',
 u'id': 20,
 u'jsonrpc': u'2.0'}
</code>```

The issue is the error with the "module not found" response, where it should be returning relevant data for that request.

On non-rpc HTTPS sites I've used POST data to log into a site as I am doing above, and then ran through a for loop of URLs as GET requests to check data is being returned properly in that logged in site, so I'm not sure if it's because I have to send POST requests here to retrieve the test responses. If anybody has any helpful hints, I would greatly appreciate it.

答:
I finally found out the issue was due to a recent URL change in the API that I was not informed about, which explains why the URL originally worked in Postman.

To make it more confusing, the URL for only some of the methods were changed, which is why the login identity.authenticate POST worked, as it was still using the original URL. For the other POST commands, the methods/modules were no longer present with the original URL, hence the error message "module not found."

Once I updated the base_url variable with the new base_url for the payloads that were receiving the error message, they returned the proper data.

Hopefully this can help others, in the event they run into something similar.

To sum up: the code works fine, it was the data that was being input into the code that was flawed and why the error message was being received. In this case, the data that was flawed was the base_url variable was pointing to an outdated URL.

Body:
Setup: Python 2.7.10, Requests library, Windows 8.1

I am new to json-rpc and need to set up automation tests for sending POST requests and checking the response. I am having difficulty accessing the data after logging in. I need to log in to the system first with a POST request ("method": "identity.authenticate"), and then the test after that is also a POST request that should return data after I have been logged in.

The developers also gave me a Bearer token to pass in the Headers which they claimed should work across all tests, and it did seem to work when I tried it in Postman (although I did have some mixed results), but for some reason when I try to use it with my Python Requests set up, it returns an error every time. The code is below (have to change the working data to dummy data, so trying to run the below code as-is won't work, but hopefully seeing the set up can help to pinpoint what I may be doing wrong):

import requests
from pprint import pprint

base_url = "https://rpc_url.com/rpc"
custom_headers = {"Content-Type":"application/json", "Authorization":"Bearer token"}

'''Sign in payload'''
signinPayload = {"method" : "identity.authenticate",
"id" : 1,
"jsonrpc" : "2.0",
"params" : {"password" : "password", "username" : "username"}}

test1_Payload = {"jsonrpc" : "2.0",
"method" : "fc.pick.getPendingPicks",
"id" : 20, "params" :{"_tags" :{"device" : "device",
  "deviceOS" : "deviceOS", "firstName" : "firstName",
  "devicetype" : "devicetype", "appVersion" : "appVersion",
  "login" : "username", "devicelabel" : "devicelabel",
  "lastName" : "lastName"}}}

with requests.Session() as s:
    # below passes the login payload, which returns proper data.
    login_post = s.post(base_url, json=signinPayload, headers=custom_headers).json()
    pprint(login_post)
    ###########################
    # passes the test payload, which doesn't work correctly
    r = s.post(base_url, json=test1_Payload, headers=custom_headers).json()
    pprint(r)

I've tried many variations, such as not passing the Bearer token in the headers, only passing the Bearer token and not the signin payload, and nothing has worked so far.

When I run the above code with non-dummy data, this is the console output (with my added comments for clarity):

# Below is returned for sign in authenticate, which appears to be good data
{u'fcFlingVersion': u'1.0.9',
    u'id': 1, u'jsonrpc':
    u'2.0',
    u'result': {
         u'_idp': {u'accessToken': 'accessTokenNumber'},
         u'administratorId': 1,
         u'changePassword': False,
         u'companyId': 1,
         u'daysUntilPasswordExpires': 100,
         u'firstname': u'firstName',
         u'groupList': u'groupList',
         u'lastname': u'lastName',
         u'login': u'username',
         u'passwordDirectory': u'identity',
         u'photoUrl': u'https://photoURL',
         u'roles': [],
         u'userId': 1,
         u'username': u'username'}}

# Below is the returned error data for test1_Payload after the successful sign in test from above.
{u'error': {u'code': 404, u'data': None, u'message': u'module not found'},
 u'fcFlingVersion': u'1.0.9',
 u'id': 20,
 u'jsonrpc': u'2.0'}

The issue is the error with the "module not found" response, where it should be returning relevant data for that request.

On non-rpc HTTPS sites I've used POST data to log into a site as I am doing above, and then ran through a for loop of URLs as GET requests to check data is being returned properly in that logged in site, so I'm not sure if it's because I have to send POST requests here to retrieve the test responses. If anybody has any helpful hints, I would greatly appreciate it.


问:
ADF popup resize
I'm using a popup in my ADF page, and some of the text is out of the popup window. How can I resize it? Here's my code:

```<code><af:popup childCreation="deferred"
    autoCancel="disabled" id="p2"
    binding="#{backingBeanScope.backing_Setup.p2}">
<af:dialog id="d2"
           binding="#{backingBeanScope.backing_Setup.d2}"
           title="Confirmação"
           type="cancel">
    <f:facet name="buttonBar">
        <af:commandButton text="Gravar"
                          id="cb6"
                          binding="#{backingBeanScope.backing_Setup.cb6}"
                          action="#{backingBeanScope.backing_Setup.checkRadioButtonAndPerformSave}"/>
    </f:facet>
    <af:panelGridLayout id="pgl45"
                        binding="#{backingBeanScope.backing_Setup.pgl45}">
        <af:gridRow marginTop="5px"
                    height="auto"
                    id="gr20"
                    binding="#{backingBeanScope.backing_Setup.gr20}">
            <af:gridCell marginStart="5px"
                         width="5mm"
                         id="gc104"
                         binding="#{backingBeanScope.backing_Setup.gc104}">
                <af:selectOneRadio label=""
                                   id="sor1"
                                   binding="#{backingBeanScope.backing_Setup.sor1}"
                                   autoSubmit="true">
                    <af:selectItem label="Os níveis abaixo herdarem tudo o que alterou;"
                                   value="radio1"
                                   id="si55"
                                   binding="#{backingBeanScope.backing_Setup.si55}"/>
                    <af:selectItem label="Os níveis abaixo herdarem tudo o que alterou menos as exceções que tenham já definidas, caso existam."
                                   value="radio2"
                                   id="si56"
                                   binding="#{backingBeanScope.backing_Setup.si56}"/>
                </af:selectOneRadio>
            </af:gridCell>
            <af:gridCell marginStart="5px"
                         marginEnd="5px"
                         width="50%"
                         id="gc115"
                         binding="#{backingBeanScope.backing_Setup.gc115}">
                <af:outputText id="ot1"
                               binding="#{backingBeanScope.backing_Setup.ot1}"/>
            </af:gridCell>
        </af:gridRow>
        <af:gridRow marginTop="5px"
                    marginBottom="5px"
                    height="auto"
                    id="gr23"
                    binding="#{backingBeanScope.backing_Setup.gr23}">
            <af:gridCell marginStart="5px"
                         width="50%"
                         id="gc116"
                         binding="#{backingBeanScope.backing_Setup.gc116}"/>
            <af:gridCell marginStart="5px"
                         marginEnd="5px"
                         width="50%"
                         id="gc117"
                         binding="#{backingBeanScope.backing_Setup.gc117}">
                <af:outputText id="ot2"
                               binding="#{backingBeanScope.backing_Setup.ot2}"/>
            </af:gridCell>
        </af:gridRow>
    </af:panelGridLayout>
</af:dialog>
</code>```

And here's the result:

答:
As per my knowledge you can solve this in different ways
1> try with surrounding  your panel grid layout with a panel form layout
2> instead giving your label for your  select one radio you can use separate input text component for displaying label and you can wrap it.
3>you can set dimensions for your dialog explicitly</p>

Title: ADF popup resize

Body:
I'm using a popup in my ADF page, and some of the text is out of the popup window. How can I resize it? Here's my code:

<af:popup childCreation="deferred"
    autoCancel="disabled" id="p2"
    binding="#{backingBeanScope.backing_Setup.p2}">
<af:dialog id="d2"
           binding="#{backingBeanScope.backing_Setup.d2}"
           title="Confirmação"
           type="cancel">
    <f:facet name="buttonBar">
        <af:commandButton text="Gravar"
                          id="cb6"
                          binding="#{backingBeanScope.backing_Setup.cb6}"
                          action="#{backingBeanScope.backing_Setup.checkRadioButtonAndPerformSave}"/>
    </f:facet>
    <af:panelGridLayout id="pgl45"
                        binding="#{backingBeanScope.backing_Setup.pgl45}">
        <af:gridRow marginTop="5px"
                    height="auto"
                    id="gr20"
                    binding="#{backingBeanScope.backing_Setup.gr20}">
            <af:gridCell marginStart="5px"
                         width="5mm"
                         id="gc104"
                         binding="#{backingBeanScope.backing_Setup.gc104}">
                <af:selectOneRadio label=""
                                   id="sor1"
                                   binding="#{backingBeanScope.backing_Setup.sor1}"
                                   autoSubmit="true">
                    <af:selectItem label="Os níveis abaixo herdarem tudo o que alterou;"
                                   value="radio1"
                                   id="si55"
                                   binding="#{backingBeanScope.backing_Setup.si55}"/>
                    <af:selectItem label="Os níveis abaixo herdarem tudo o que alterou menos as exceções que tenham já definidas, caso existam."
                                   value="radio2"
                                   id="si56"
                                   binding="#{backingBeanScope.backing_Setup.si56}"/>
                </af:selectOneRadio>
            </af:gridCell>
            <af:gridCell marginStart="5px"
                         marginEnd="5px"
                         width="50%"
                         id="gc115"
                         binding="#{backingBeanScope.backing_Setup.gc115}">
                <af:outputText id="ot1"
                               binding="#{backingBeanScope.backing_Setup.ot1}"/>
            </af:gridCell>
        </af:gridRow>
        <af:gridRow marginTop="5px"
                    marginBottom="5px"
                    height="auto"
                    id="gr23"
                    binding="#{backingBeanScope.backing_Setup.gr23}">
            <af:gridCell marginStart="5px"
                         width="50%"
                         id="gc116"
                         binding="#{backingBeanScope.backing_Setup.gc116}"/>
            <af:gridCell marginStart="5px"
                         marginEnd="5px"
                         width="50%"
                         id="gc117"
                         binding="#{backingBeanScope.backing_Setup.gc117}">
                <af:outputText id="ot2"
                               binding="#{backingBeanScope.backing_Setup.ot2}"/>
            </af:gridCell>
        </af:gridRow>
    </af:panelGridLayout>
</af:dialog>

And here's the result:


问:
how open .conf file with admin rights, edit and save using bat
This is the content of the conf file

use chroot = false

strict modes = false

hosts allow = *

log file = rsyncd.log

i need to add this two lines in the begin

uid=0

gid=0

and this other lines in the end

[data]

path = /cygdrive/d/My documents

read only = false

transfer logging = yes

[mail]

path = /cygdrive/d/mail

read only = false

transfer logging = yes

with the bat completed i will going to deploy it by policy on my network.

i´m really new in this, but i appreciate your help. Apologies for my english.

I tried with this code:

```<code>@echo off
Color 9A & Mode con cols=83 lines=5
Title %~n0 Adding lines to rsyncd.conf
:::::::::::::::::::::::::::::::::::::::::
:: Automatically check & get admin rights
:::::::::::::::::::::::::::::::::::::::::
REM  --> Check for permissions
Reg query "HKU\S-1-5-19\Environment" >nul 2>&1
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
Echo.
ECHO                      **************************************
ECHO                       Running Admin shell... Please wait...
ECHO                      **************************************
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"=""
    echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B
:gotAdmin
::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::
set "hostspath=C:\Program Files (x86)\ICW\rsyncd.conf"
FIND /C /I "uid=0" "%hostspath%" >nul
FIND /C /I "gid=0" "%hostspath%" >nul
FIND /C /I "[data]" "%hostspath%" >nul
FIND /C /I "path = /cygdrive/d/My documents" "%hostspath%" >nul
FIND /C /I "read only = false" "%hostspath%" >nul
FIND /C /I "transfer logging = yes" "%hostspath%" >nul
FIND /C /I "[mail]" "%hostspath%" >nul
FIND /C /I "path = /cygdrive/d/mail" "%hostspath%" >nul
FIND /C /I "read only = false" "%hostspath%" >nul
FIND /C /I "transfer logging = yes" "%hostspath%" >nul
)
Attrib +R "%hostspath%"
</code>```

答:
All of the find commands are doing nothing - they simply check that the string is within the file and set errorlevel to 0 if found, non-0 if not - but having done the find you are doing nothing with the result.

```<code>::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::
set "hostspath=C:\Program Files (x86)\ICW\rsyncd.conf"
FIND /C /I "uid=0" "%hostspath%" >nul
if not errorlevel 1 goto :eof
Attrib -R "%hostspath%"
(for %%a in ("gid=0" "uid=0") do echo %%~a)>tempfile.txt
type "%hostspath%" >>tempfile.txt
(for %%a in ("[data]"
 "uid=0"
"path = /cygdrive/d/My documents"
"read only = false"
"transfer logging = yes"
"[mail]"
"path = /cygdrive/d/mail"
"read only = false"
"transfer logging = yes"
 ) do echo %%~a
)>>tempfile.txt
move /y tempfile.txt "%hostspath%"
Attrib +R "%hostspath%"
</code>```

First, check whether uid=0 is in the file. If it is, assume the job has already been done and exit.

Remove the readonly flag from the .conf file

The for command will assign the "values in quotes" to %%a in turn, then echo each value (the ~ removes the enclosing quotes). The ( and ) enclosing the for command allow the output to be redirected to a file hich I named tempfile.txt.

Then type the contents of the existing .conf file to the tempfile

Then output the remaining lines, but this time the redirector is >> to append to tempfile.txt

Then move tempfile.txt over the .conf file and mark it readonly.

Body:
This is the content of the conf file

use chroot = false

strict modes = false

hosts allow = *

log file = rsyncd.log

i need to add this two lines in the begin

uid=0

gid=0

and this other lines in the end

[data]

path = /cygdrive/d/My documents

read only = false

transfer logging = yes

[mail]

path = /cygdrive/d/mail

read only = false

transfer logging = yes

with the bat completed i will going to deploy it by policy on my network.

i´m really new in this, but i appreciate your help. Apologies for my english.

I tried with this code:

@echo off
Color 9A & Mode con cols=83 lines=5
Title %~n0 Adding lines to rsyncd.conf
:::::::::::::::::::::::::::::::::::::::::
:: Automatically check & get admin rights
:::::::::::::::::::::::::::::::::::::::::
REM  --> Check for permissions
Reg query "HKU\S-1-5-19\Environment" >nul 2>&1
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
Echo.
ECHO                      **************************************
ECHO                       Running Admin shell... Please wait...
ECHO                      **************************************
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"=""
    echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B
:gotAdmin
::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::
set "hostspath=C:\Program Files (x86)\ICW\rsyncd.conf"
FIND /C /I "uid=0" "%hostspath%" >nul
FIND /C /I "gid=0" "%hostspath%" >nul
FIND /C /I "[data]" "%hostspath%" >nul
FIND /C /I "path = /cygdrive/d/My documents" "%hostspath%" >nul
FIND /C /I "read only = false" "%hostspath%" >nul
FIND /C /I "transfer logging = yes" "%hostspath%" >nul
FIND /C /I "[mail]" "%hostspath%" >nul
FIND /C /I "path = /cygdrive/d/mail" "%hostspath%" >nul
FIND /C /I "read only = false" "%hostspath%" >nul
FIND /C /I "transfer logging = yes" "%hostspath%" >nul
)
Attrib +R "%hostspath%"

Body:
All of the find commands are doing nothing - they simply check that the string is within the file and set errorlevel to 0 if found, non-0 if not - but having done the find you are doing nothing with the result.

::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::
set "hostspath=C:\Program Files (x86)\ICW\rsyncd.conf"
FIND /C /I "uid=0" "%hostspath%" >nul
if not errorlevel 1 goto :eof
Attrib -R "%hostspath%"
(for %%a in ("gid=0" "uid=0") do echo %%~a)>tempfile.txt
type "%hostspath%" >>tempfile.txt
(for %%a in ("[data]"
 "uid=0"
"path = /cygdrive/d/My documents"
"read only = false"
"transfer logging = yes"
"[mail]"
"path = /cygdrive/d/mail"
"read only = false"
"transfer logging = yes"
 ) do echo %%~a
)>>tempfile.txt
move /y tempfile.txt "%hostspath%"
Attrib +R "%hostspath%"

First, check whether uid=0 is in the file. If it is, assume the job has already been done and exit.

Remove the readonly flag from the .conf file

The for command will assign the "values in quotes" to %%a in turn, then echo each value (the ~ removes the enclosing quotes). The ( and ) enclosing the for command allow the output to be redirected to a file hich I named tempfile.txt.

Then type the contents of the existing .conf file to the tempfile

Then output the remaining lines, but this time the redirector is >> to append to tempfile.txt

Then move tempfile.txt over the .conf file and mark it readonly.


问:
How to load any XAP file with the Windows Phone 7 emulator
Does anyone know if it is possible to load a windows phone 7 XAP file into the emulator without the solution or source files? In other words, can I send somebody just a XAP file so that they can test my app, without giving them the full source code?</p>

答:
Run this:

D:\Program Files\Microsoft SDKs\Windows Phone\v7.0\Tools\XAP Deployment\XapDeploy.exe

ContentLicense: CC BY-SA 2.5


问:
jQuery select matching text within element
I need a way to pass an element id and a string to a function which selects any occurrences of that string in the element text, which is not already wrapped in a sub element.

I have an existing event handler which performs some actions, including wrapping the text in an element, when a user highlights a section of text. However some strings can be matched automatically without needing to be selected by a user, which is what I am trying to accomplish here. A different event will sometimes produce an element id and a string, and all instances of the string in the element text which are not all ready tagged, should be passed to the event handler as if a user had selected them.

Example:

```<code>var selectionString = 'word';
<p id="1">select this word, but not this <span>word</span>, but yes to this word.</p>

// My approach so far which may not be on the right track.
function selectStringInElement(selectionString, elementId){
    var el = document.getElementById(elementId);
    var selections = el.innerHTML.split(/<.+>/);
    for(var i=0; i < selections.length; i++){
        // if the selection contains the selectionString, find its range, select it, and pass to existing handler.
    }
}
</code>```

Any help would be much appreciated.

答:
HTML nodes have children accessible by node.childNodes, and you can tell if a child node is text or an element by node.nodeType.

This example takes the search string and the element id to search, filters it so only the text nodes are left, and then does a replace to generate a new html string.  You can't just jam a HTML string into a text node, so I used a temporary div to parse the html string into nodes, which are then injected into the element's parent before removing the source text node itself.

function selectStringInElement(selectionString, elementId, className) {
  $("#" + elementId).contents()
  .filter(function(i, el){
    // only process text nodes
    return el.nodeType == 3
  }).each(function(i, el){
    // create a div to process our html string with new tags
    var fake = document.createElement('div');

    fake.innerHTML = el.textContent.replace(
      new RegExp(selectionString,'g'),
      "" + selectionString + ""
    );

    // take all the nodes in our div and append them to the actual element's parent
    $(fake.childNodes).each(function(i, child) {
      el.parentNode.insertBefore(child, el);
    });

    // we've now duplicated our actual element with a number of new elements, we don't need to keep the original
    el.parentNode.removeChild(el);
  });
}
selectStringInElement('chowder','test', 'red');
selectStringInElement('ukulele','test', 'blue');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.red {
  color: #f00;
}
.blue {
  color: #00f;
}</code>```

The bottle of shampoo just returned from a safari, that he left the tea and the church bazaar. She was a grand ran all around the veranda, laughing like, so helping their ranch on the cook make the church bazaar. She was playing a ukulele, which the admiral did not like, so he looked through his collection of the kindergarten cried, "At last! Hurrah!" -- and by accident spilled the ketchup all over the taffy apples! This so amused another chores at the bottle had just where he had found the taffy apples! This so amused another guest, who usually wore a gingham dress and moccasins when visiting their ranch on the cook make the church bazaar. She was no helping the chowder and kayak he had seen.

Someone was playing a ukulele, which the ketchup all over the goulash for lunch. the label.

The admiral heard them talking in the label.

The admiral heard them talking in the bank and firing his pistol out of his sack and ran all around the chowder and the goulash for lunch. the Nebraska prairie, had just returned from her chores at imaginary zombies. It was a grand party.d through his collection of shampoo just returned from a safari, that he pulled the ketchup all over the church bazaar. She was no helping the church bazaar. She was no helping the admiral hated to a pretty mazurka by Chopin. Then he looked through his sack and ran all around the kitchen.

Someone was a grand party.ard them talking in the admiral did not like a maniac and firing his pistol out of his so amused another guest, who usually wore a gingham dress and listened to a pretty mazurka by Chopin. The bottle had seen.

Someone was playing a ukulele, which the admiral heard them talking in the label.

The admiral's wife, who usually wore a gingham dress and moccasins when visiting their ranch on the label.

When everyone sat down to eat, the pulled a toy pistol out of his sack and ran all around through his collection of pictures -- next to the tea and listened to snoop, so he turned on the radio and the cook make the church bazaar. She was playing a ukulele, which the admiral did not like, so amused another guest, who had just returned on the Nebraska prairie, had just returned on the Nebraska prairie, had a picture of shampoo just returned from a safari, that he pulled the radio and listened from her chowder and the label.

```

Body:
I need a way to pass an element id and a string to a function which selects any occurrences of that string in the element text, which is not already wrapped in a sub element.

I have an existing event handler which performs some actions, including wrapping the text in an element, when a user highlights a section of text. However some strings can be matched automatically without needing to be selected by a user, which is what I am trying to accomplish here. A different event will sometimes produce an element id and a string, and all instances of the string in the element text which are not all ready tagged, should be passed to the event handler as if a user had selected them.

Example:

var selectionString = 'word';

select this word, but not this word, but yes to this word.

// My approach so far which may not be on the right track.
function selectStringInElement(selectionString, elementId){
    var el = document.getElementById(elementId);
    var selections = el.innerHTML.split(/<.+>/);
    for(var i=0; i < selections.length; i++){
        // if the selection contains the selectionString, find its range, select it, and pass to existing handler.
    }
}

Any help would be much appreciated.

Body:
HTML nodes have children accessible by node.childNodes, and you can tell if a child node is text or an element by node.nodeType.

This example takes the search string and the element id to search, filters it so only the text nodes are left, and then does a replace to generate a new html string.  You can't just jam a HTML string into a text node, so I used a temporary div to parse the html string into nodes, which are then injected into the element's parent before removing the source text node itself.

function selectStringInElement(selectionString, elementId, className) {
  $("#" + elementId).contents()
  .filter(function(i, el){
    // only process text nodes
    return el.nodeType == 3
  }).each(function(i, el){
    // create a div to process our html string with new tags
    var fake = document.createElement('div');

    fake.innerHTML = el.textContent.replace(
      new RegExp(selectionString,'g'),
      "<span class='" + className + "'>" + selectionString + "</span>"
    );

    // take all the nodes in our div and append them to the actual element's parent
    $(fake.childNodes).each(function(i, child) {
      el.parentNode.insertBefore(child, el);
    });

    // we've now duplicated our actual element with a number of new elements, we don't need to keep the original
    el.parentNode.removeChild(el);
  });
}
selectStringInElement('chowder','test', 'red');
selectStringInElement('ukulele','test', 'blue');

.red {
  color: #f00;
}
.blue {
  color: #00f;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='test'>
The bottle of shampoo just returned from a safari, that he left the tea and the church bazaar. She was a grand ran all around the veranda, laughing like, so helping their ranch on the cook make the church bazaar. She was playing a ukulele, which the admiral did not like, so he looked through his collection of the kindergarten cried, "At last! Hurrah!" -- and by accident spilled the ketchup all over the taffy apples! This so amused another chores at the bottle had just where he had found the taffy apples! This so amused another guest, who usually wore a gingham dress and moccasins when visiting their ranch on the cook make the church bazaar. She was no helping the chowder and kayak he had seen.

Someone was playing a ukulele, which the ketchup all over the goulash for lunch. the label.

The admiral heard them talking in the label.

The admiral heard them talking in the bank and firing his pistol out of his sack and ran all around the chowder and the goulash for lunch. the Nebraska prairie, had just returned from her chores at imaginary zombies. It was a grand party.d through his collection of shampoo just returned from a safari, that he pulled the ketchup all over the church bazaar. She was no helping the church bazaar. She was no helping the admiral hated to a pretty mazurka by Chopin. Then he looked through his sack and ran all around the kitchen.

Someone was a grand party.ard them talking in the admiral did not like a maniac and firing his pistol out of his so amused another guest, who usually wore a gingham dress and listened to a pretty mazurka by Chopin. The bottle had seen.

Someone was playing a ukulele, which the admiral heard them talking in the label.

The admiral's wife, who usually wore a gingham dress and moccasins when visiting their ranch on the label.

When everyone sat down to eat, the pulled a toy pistol out of his sack and ran all around through his collection of pictures -- next to the tea and listened to snoop, so he turned on the radio and the cook make the church bazaar. She was playing a ukulele, which the admiral did not like, so amused another guest, who had just returned on the Nebraska prairie, had just returned on the Nebraska prairie, had a picture of shampoo just returned from a safari, that he pulled the radio and listened from her chowder and the label.
</div>


问:
how do i generate a heat map of a detected object based on its position using opencv python
I need to generate the heat map of a object based on its position
example: the detected green ball in a video frame . If it stays in a position for a long duration then that place should be red and the positions in the frame where the ball has passes for a short duration must be in blue in that way i need to generate a heat map . Thanks in advance</p>

答:
Well what you can do here is

1) First define a heatmap as the size of the image

```<code>  heatmap = np.zeros_like(img[:,:,0]).astype(np.float)
</code>```

2) Since you already have the detected object and its position, in the    heatmap, add 1 to all pixels in the bounding box of the object.

```<code>heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1
</code>```

3) you can than apply thresholding by setting all pixels which are below a threshold value in the heatmap to be 0. You can choose the threshold value to be 1 so that the region inside your bounding box remains in the heatmap

```<code>heatmap[heatmap <= threshold] = 0
</code>```

Body:
Well what you can do here is

1) First define a heatmap as the size of the image

  heatmap = np.zeros_like(img[:,:,0]).astype(np.float)

2) Since you already have the detected object and its position, in the    heatmap, add 1 to all pixels in the bounding box of the object.

heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1

3) you can than apply thresholding by setting all pixels which are below a threshold value in the heatmap to be 0. You can choose the threshold value to be 1 so that the region inside your bounding box remains in the heatmap

heatmap[heatmap <= threshold] = 0


问:
Fiscal position implementation in odoo
I have seen one option in odoo accounting "Fiscal Position" under

Accounting => Configuration => Accounting => Fiscal Position

I have checked it's features but I am not really getting at which point of time it's really useful or we can implement it where.

Features are very useful that all about tax and account mapping.

I would like to know it's importance, because I think so it's useful feature in odoo.

答:
Like @CZoellner said.

it's a way to configure odoo to change the taxs automaticly for a partner.

for example by default our taxes 19% but when we deal with import && export partner the taxes are not applicable so instead of removing this taxes manually because as you know when you select a product the taxes are loaded,

by defining the Fiscal position of partner this is don automaticly by odoo (19% tax --> 0% tax).

Title: Fiscal position implementation in odoo


问:
Why doesn't the additive constant in Big-O notation matter?
In definition of Big-O notation we care only about C coefficient:

```<code>f(n) ≤ Cg(n) for all n ≥ k
</code>```

Why don't we care about A as well:

```<code>f(n) ≤ Cg(n) + A for all n ≥ k
</code>```

答:
A is constant in this case, thus it will not affect much the complexity when the size of the problem grows very much.

When you have a cost of 1 million, you do not care if you add up a constant factor of 100 for example. You care for how this 1 million grows (resulting from Cg(n)); whether it becomes 2 millions for example if the size of the problem grows a bit. However, your constant will still be 100, so it doesn't really affect the overall complexity.

Body:
In definition of Big-O notation we care only about C coefficient:

f(n) ≤ Cg(n) for all n ≥ k

Why don't we care about A as well:

f(n) ≤ Cg(n) + A for all n ≥ k


问:
JQuery Context-menu assimilation with FullCalendar
I'm dealing with Martin Wendt's jQuery Context-menu plugin and I'm trying to integrate it in my FullCalendar plugin. The issue is that nothing happens on right-clicking on the event. So, no context-menu pops-out.

I got the following jquery code in my default.html file that displays the calendar:

```<code>        $('#calendar').fullCalendar({
            eventRender: function(event, element) {
                var originalClass = element[0].className;
                element[0].className = originalClass + ' hasmenu';
            },
            //
        });

        $('#calendar').contextmenu({
            delegate: '.hasmenu',
            menu: [
                {title: 'Copy', cmd: 'copy', uiIcon: 'ui-icon-copy'},
                {title: '----'},
                {title: 'More', children: [
                    {title: 'Sub 1', cmd: 'sub1'},
                    {title: 'Sub 2', cmd: 'sub1'}
                    ]}
                ],
            select: function(event, ui) {
                alert('select ' + ui.cmd + ' on ' + ui.target.text());
            }
        });
</code>```

As you can see, it seems like there's nothing wrong with the code since I completely followed the procedures to enable the jquery context-menu to pop-out when right-clicking on an event. Here are also the dependencies required for the context-menu plugin:

```<code><link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"
    rel="stylesheet" />
<script src="//code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="assets/jquery.ui-contextmenu.min.js"></script>
</code>```

In order to fulfill it, in the beginning of my  section, I included the dependencies for FullCalendar and the Contextmenu :

```<code><link href='//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css' rel='stylesheet' />
<link href='../fullcalendar.min.css' rel='stylesheet' />
<link href='../fullcalendar.print.min.css' rel='stylesheet' media='print' />
<script src='../lib/moment.min.js'></script>
<script src='../lib/jquery.min.js'></script>
<script src='../fullcalendar.min.js'></script>
<script src='//code.jquery.com/jquery-1.11.3.min.js'></script>
<script src='//code.jquery.com/ui/1.11.4/jquery-ui.min.js'></script>
<script src='../jquery.ui-contextmenu.min.js'></script>
</code>```

The jquery.ui-contextmenu.min.js file got bumped up to the main folder where my fullcalendar.min.js is present as you can notice.

答:
I made a fiddle based on the above code where the context menu does appear but gets displayed behind bits of the calendar and is inaccessible.

https://jsfiddle.net/xc7styt5/

If you change the z-index of class ui-contextmenu it should function.

https://jsfiddle.net/p52gohwn/

```<code>.ui-contextmenu {
  z-index: 1;
}
</code>```

(there may be a better way)

Body:
I'm dealing with Martin Wendt's jQuery Context-menu plugin and I'm trying to integrate it in my FullCalendar plugin. The issue is that nothing happens on right-clicking on the event. So, no context-menu pops-out.

I got the following jquery code in my default.html file that displays the calendar:

        $('#calendar').fullCalendar({
            eventRender: function(event, element) {
                var originalClass = element[0].className;
                element[0].className = originalClass + ' hasmenu';
            },
            //
        });

        $('#calendar').contextmenu({
            delegate: '.hasmenu',
            menu: [
                {title: 'Copy', cmd: 'copy', uiIcon: 'ui-icon-copy'},
                {title: '----'},
                {title: 'More', children: [
                    {title: 'Sub 1', cmd: 'sub1'},
                    {title: 'Sub 2', cmd: 'sub1'}
                    ]}
                ],
            select: function(event, ui) {
                alert('select ' + ui.cmd + ' on ' + ui.target.text());
            }
        });

As you can see, it seems like there's nothing wrong with the code since I completely followed the procedures to enable the jquery context-menu to pop-out when right-clicking on an event. Here are also the dependencies required for the context-menu plugin:

<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"
    rel="stylesheet" />

In order to fulfill it, in the beginning of my  section, I included the dependencies for FullCalendar and the Contextmenu :

<link href='//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css' rel='stylesheet' />
<link href='../fullcalendar.min.css' rel='stylesheet' />
<link href='../fullcalendar.print.min.css' rel='stylesheet' media='print' />

The jquery.ui-contextmenu.min.js file got bumped up to the main folder where my fullcalendar.min.js is present as you can notice.

Body:
I made a fiddle based on the above code where the context menu does appear but gets displayed behind bits of the calendar and is inaccessible.

https://jsfiddle.net/xc7styt5/

If you change the z-index of class ui-contextmenu it should function.

https://jsfiddle.net/p52gohwn/

.ui-contextmenu {
  z-index: 1;
}

(there may be a better way)


问:
Braintree PayPal checkout component throwing "e.client.getVersion is not a function"
I'm struggling to understand what I'm doing wrong here:

```<code> braintree.client.create({
     authorization: res.clientToken // this is the token, I know it is correct
 }, (err, client) => {
    if (err) { ... }
    braintree.paypalCheckout.create({ client }, (err, paypalInstance) => {
        if (...) { ... }
    })
 });
</code>```

When calling braintree.paypalCheckout.create, an error is called synchronously:

Uncaught TypeError: e.client.getVersion is not a function

Indeed, the client object doesn't have such a method. I followed the code from this page and this page (pretty much the same thing).

How to fix the problem? The PayPal Checkout component is loaded and appended to the braintree object.

答:
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.

getVersion is a method of the client class as of version 3.16.0 of braintree-web. Update the version of braintree-web you're using to 3.16.0+.

Body:
I'm struggling to understand what I'm doing wrong here:

 braintree.client.create({
     authorization: res.clientToken // this is the token, I know it is correct
 }, (err, client) => {
    if (err) { ... }
    braintree.paypalCheckout.create({ client }, (err, paypalInstance) => {
        if (...) { ... }
    })
 });

When calling braintree.paypalCheckout.create, an error is called synchronously:

Uncaught TypeError: e.client.getVersion is not a function

Indeed, the client object doesn't have such a method. I followed the code from this page and this page (pretty much the same thing).

How to fix the problem? The PayPal Checkout component is loaded and appended to the braintree object.


问:
Running django in virtualenv - ImportError: No module named django.core.management?
I have installed Django after activating my virtualenv but still I am getting following error</p>

```<code>from django.core.management import execute_from_command_line
ImportError: No module named django.core.management
</code>```

答:
I found that I could import the django module from the python interpreter, but django-admin.py could not import it when run from the command line.

I confirmed that I was using the python interpreter in my virtual environment.

I was using a 64-bit version of python. Uninstalling, and installing the 32-bit version, then re-creating my venv solved this for me.

Body:
I have installed Django after activating my virtualenv but still I am getting following error

from django.core.management import execute_from_command_line
ImportError: No module named django.core.management


问:
preg_replace not doing what I expect
I have the following paterns in a paragraph of text and I need to replace it with nothing, so that it disappears from the paragraph.

The sendtence contains CONSULTANTS [45416,2010-05-11] I need to remove the [] and everything within these [] , not the characters within the [] could be anything

I tried the below but this only removes the []

```<code>$par = preg_replace('/[\[*\]]/','',$par);
</code>```

答:
Roland,

What you are trying to match is:

```<code>[\[*\]]
</code>```

Which is any of the '[', '*', ']' chars. What you really want is a pattern starting with '[' and ending with ']'. There can be any non-']' char in between. So the correct pattern would be:

```<code>\[[^\]]*\]
</code>```

So this:

```<code>$par = preg_replace("/\[[^\]]*\]/", "", $par);
</code>```

should work.

Thanks.

Title: preg_replace not doing what I expect

Body:
I have the following paterns in a paragraph of text and I need to replace it with nothing, so that it disappears from the paragraph.

The sendtence contains CONSULTANTS [45416,2010-05-11] I need to remove the [] and everything within these [] , not the characters within the [] could be anything

I tried the below but this only removes the []

$par = preg_replace('/[\[*\]]/','',$par);

Body:
Roland,

What you are trying to match is:

[\[*\]]

Which is any of the '[', '*', ']' chars. What you really want is a pattern starting with '[' and ending with ']'. There can be any non-']' char in between. So the correct pattern would be:

\[[^\]]*\]

So this:

$par = preg_replace("/\[[^\]]*\]/", "", $par);

should work.

Thanks.


问:
compare 2 strings, subtract the same characters and return the new values
i have two strings, it can be more then two may be 5 or 6

```<code> $a =  2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=123
 $b =  2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=12352015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000
</code>```

i need help i need a function or any way that when i compare $a with $b it should only returns me string like below

```<code>$remaining = '2015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000';
</code>```

i tried this function with no luck if (strcmp($var1, $var2) === 0) {

答:
It might not seem obvious the way you're thinking of it, but str_replace should work for this.

```<code>$remaining = str_replace($a, '', $b);
</code>```

If $a is found in $b then $remaining will be $b with the characters of $a removed from it, otherwise $remaining will be the unchanged value of $b.

Body:
i have two strings, it can be more then two may be 5 or 6

 $a =  2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=123
 $b =  2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=12352015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000

i need help i need a function or any way that when i compare $a with $b it should only returns me string like below

$remaining = '2015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000';

i tried this function with no luck if (strcmp($var1, $var2) === 0) {

Body:
It might not seem obvious the way you're thinking of it, but str_replace should work for this.

$remaining = str_replace($a, '', $b);

If $a is found in $b then $remaining will be $b with the characters of $a removed from it, otherwise $remaining will be the unchanged value of $b.


问:
Error GRPC Spanner Google Cloud With PHP
I'm using PHP to try using the Google Cloud Spanner. I already did the gCloud settings and everything, and that's right. Now I need to make the connection via PHP to do a CRUD with the database that is in Spanner, but the code below always returns the error:

PHP Fatal error:  Undefined constant 'Grpc\STATUS_UNKNOWN' in
  /xxx/xxxx/www/vendor/google/cloud-spanner/Connection/Grpc.php on line
  129

The code I have is:

```<code><?php
require 'vendor/autoload.php';

use Google\Cloud\Spanner\SpannerClient;

/* Error start here */
$spanner = new SpannerClient([
    'projectId' => 'my-project-id'
]);

$db = $spanner->connect('instance', 'database');

$userQuery = $db->execute('SELECT * FROM usuario WHERE login = @login', [
    'parameters' => [
        'login' => 'devteam'
    ]
]);

$user = $userQuery->rows()->current();

echo 'Hello ' . $user['login'];
</code>```

The requirements I use in the composer are:

```<code>"require": {
        "google/cloud": "^0.32.1",
        "google/cloud-spanner": "^0.2.2"
}
</code>```

I noticed that if I enter through the browser, the error presented above continues to appear. If I run the command php teste.php on the terminal, it runs the script correctly, ie, the terminal works and the browser does not.

答:
Since you mentioned that it works on CLI but not on browser, I can say that you need to enable the grpc extension on your php web server config.

E.g. Add
extension=grpc.so to your /etc/php/5.6/apache2/php.ini

Body:
I'm using PHP to try using the Google Cloud Spanner. I already did the gCloud settings and everything, and that's right. Now I need to make the connection via PHP to do a CRUD with the database that is in Spanner, but the code below always returns the error:

PHP Fatal error:  Undefined constant 'Grpc\STATUS_UNKNOWN' in
  /xxx/xxxx/www/vendor/google/cloud-spanner/Connection/Grpc.php on line
  129

The code I have is:

<?php
require 'vendor/autoload.php';

use Google\Cloud\Spanner\SpannerClient;

/* Error start here */
$spanner = new SpannerClient([
    'projectId' => 'my-project-id'
]);

$db = $spanner->connect('instance', 'database');

$userQuery = $db->execute('SELECT * FROM usuario WHERE login = @login', [
    'parameters' => [
        'login' => 'devteam'
    ]
]);

$user = $userQuery->rows()->current();

echo 'Hello ' . $user['login'];

The requirements I use in the composer are:

"require": {
        "google/cloud": "^0.32.1",
        "google/cloud-spanner": "^0.2.2"
}

I noticed that if I enter through the browser, the error presented above continues to appear. If I run the command php teste.php on the terminal, it runs the script correctly, ie, the terminal works and the browser does not.


问:
Disable pop-up calendar when clicking date picker in javafx
I am developing program on javafx and i use datepicker. I want to disable pop-up calendar when i click the calendar image. Dont advice that just use textfield instead of datepicker and parse it </p>

答:
```<code>datePicker.setEditable(false);

datePicker.setOnMouseClicked(e -> {
     if(!datePicker.isEditable())
         datePicker.hide();
});
</code>```


问:
rails - adding html div tags while looping through array
I'm trying to display a conversation in my html.erb file.

I'm using a specific template and want to copy their chat section.

Here's the chat section:

http://webapplayers.com/inspinia_admin-v2.7.1/chat_view.html

I noticed that their chat "bubbles" are just different divs.

Like this:

```<code> <div class="chat-message left">
    <img class="message-avatar" src="<%= image_path('a1.jpg') %>" alt="">
    <div class="message">
        <a class="message-author" href="#"> Michael Smith </a>
        <span class="message-date"> Mon Jan 26 2015 - 18:39:23 </span>
            <span class="message-content">
                Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.
            </span>
    </div>
</div>

<div class="chat-message right">
    <img class="message-avatar" src="<%= image_path('a4.jpg') %>" alt="">
    <div class="message">
        <a class="message-author" href="#"> Karl Jordan </a>
        <span class="message-date">  Fri Jan 25 2015 - 11:12:36 </span>
            <span class="message-content">
                Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover.
            </span>
    </div>
</div>
</code>```

If i have an array of @messages in my html.erb file, how can I traverse the array and for every message add one of those div sections in order to make my chat view?

Alternatively, I will have to put it in some sort of table with each row styled depending on whether the message is incoming or outbound.

答: You can do this by just iterating @messages with @messages.each do |message|...end and then within the block have your divs with the message contents. A cleaner way might be to set up a _chat_view.html.erb partial with these divs and then in your main html.erb file you can do render partial: 'chat_view', collection: @messages and you still get the message object in the partial that you can use.

Body:
I'm trying to display a conversation in my html.erb file.

I'm using a specific template and want to copy their chat section.

Here's the chat section:

http://webapplayers.com/inspinia_admin-v2.7.1/chat_view.html

I noticed that their chat "bubbles" are just different divs.

Like this:

    <img class="message-avatar" src="<%= image_path('a1.jpg') %>" alt="">

         Michael Smith
         Mon Jan 26 2015 - 18:39:23

                Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.

    <img class="message-avatar" src="<%= image_path('a4.jpg') %>" alt="">

         Karl Jordan
          Fri Jan 25 2015 - 11:12:36

                Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover.

If i have an array of @messages in my html.erb file, how can I traverse the array and for every message add one of those div sections in order to make my chat view?

Alternatively, I will have to put it in some sort of table with each row styled depending on whether the message is incoming or outbound.


问:
Change the main image in bulk
I have this code:

```<code><div class="product-image-gallery">
    <img id="image-main" class="gallery-image visible" src="http://classyeyewear.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/9/3/9306abca7f8f0f2361dcba0aa50171db_4.JPG" alt="Prada SPR52Q SL3-4M1 Ruthenium Frame Brown Sunglasses 57mm SPR 52Q SL3 4M1" title="Prada SPR52Q SL3-4M1 Ruthenium Frame Brown Sunglasses 57mm SPR 52Q SL3 4M1">
    <img id="image-0" class="gallery-image" alt="Prada SPR52Q SL3-4M1 Ruthenium Frame Brown Sunglasses 57mm SPR 52Q SL3 4M1" src="http://classyeyewear.com/media/catalog/product/cache/1/image/1800x/040ec09b1e35df139433887a97daa66f/4/2/42fd546e1ab67968e56999444d140483_3.JPG" data-zoom-image="http://classyeyewear.com/media/catalog/product/cache/1/image/1800x/040ec09b1e35df139433887a97daa66f/4/2/42fd546e1ab67968e56999444d140483_3.JPG">
    <img id="image-1" class="gallery-image" alt="Prada SPR52Q SL3-4M1 Ruthenium Frame Brown Sunglasses 57mm SPR 52Q SL3 4M1" src="http://classyeyewear.com/media/catalog/product/cache/1/image/1800x/040ec09b1e35df139433887a97daa66f/5/8/586be5d8ae054ce28e8e778988a6c3ea_3.JPG" data-zoom-image="http://classyeyewear.com/media/catalog/product/cache/1/image/1800x/040ec09b1e35df139433887a97daa66f/5/8/586be5d8ae054ce28e8e778988a6c3ea_3.JPG">
    <img id="image-2" class="gallery-image" alt="Prada SPR52Q SL3-4M1 Ruthenium Frame Brown Sunglasses 57mm SPR 52Q SL3 4M1" src="http://classyeyewear.com/media/catalog/product/cache/1/image/1800x/040ec09b1e35df139433887a97daa66f/8/0/80083f5efe19a54f290be7f40568f2f3_3.JPG" data-zoom-image="http://classyeyewear.com/media/catalog/product/cache/1/image/1800x/040ec09b1e35df139433887a97daa66f/8/0/80083f5efe19a54f290be7f40568f2f3_3.JPG">
    <img id="image-3" class="gallery-image" alt="Prada SPR52Q SL3-4M1 Ruthenium Frame Brown Sunglasses 57mm SPR 52Q SL3 4M1" src="http://classyeyewear.com/media/catalog/product/cache/1/image/1800x/040ec09b1e35df139433887a97daa66f/9/3/9306abca7f8f0f2361dcba0aa50171db_4.JPG" data-zoom-image="http://classyeyewear.com/media/catalog/product/cache/1/image/1800x/040ec09b1e35df139433887a97daa66f/9/3/9306abca7f8f0f2361dcba0aa50171db_4.JPG">
    <img id="image-4" class="gallery-image" alt="Prada SPR52Q SL3-4M1 Ruthenium Frame Brown Sunglasses 57mm SPR 52Q SL3 4M1" src="http://classyeyewear.com/media/catalog/product/cache/1/image/1800x/040ec09b1e35df139433887a97daa66f/8/4/84cd379f607b2e158765a5153e3dca31_3.JPG" data-zoom-image="http://classyeyewear.com/media/catalog/product/cache/1/image/1800x/040ec09b1e35df139433887a97daa66f/8/4/84cd379f607b2e158765a5153e3dca31_3.JPG">
</div>
</code>```

I want id="image-0" to be the main image. How can I do it using CSS?

Thanks

答:
Short answer: You can't. CSS doesn't allow dynamic class changing.

Long answer: You can't, but there's always JavaScript (aka jQuery in my case):

```<code>$(".product-image-gallery img").removeClass("visible"); // remove visible class from all elements
$("#image-0").addClass("visible");
</code>```

Title: Change the main image in bulk

Body:
I have this code:

I want id="image-0" to be the main image. How can I do it using CSS?

Thanks

Body:
Short answer: You can't. CSS doesn't allow dynamic class changing.

Long answer: You can't, but there's always JavaScript (aka jQuery in my case):

$(".product-image-gallery img").removeClass("visible"); // remove visible class from all elements
$("#image-0").addClass("visible");


问:
Swift perform segue without clicking button
I'm making a small game in SpriteKit where I have a bool value stored that checks if it's the first time the user plays my game. If it is, I want the app to redirect him to another viewcontroller where he enters his character-name.

However, I'm having trouble getting my app to do so.

In my "GameViewController.swift" I have this code:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    checkGame()

    if let view = self.view as! SKView? {

        // Load the SKScene from 'GameScene.sks'
        if let scene = SKScene(fileNamed: "GameScene") {
            // Set the scale mode to scale to fit the window
            scene.scaleMode = .aspectFill

            // Present the scene
            view.presentScene(scene)
        }

        view.ignoresSiblingOrder = true

        view.showsFPS = true
        view.showsNodeCount = true
    }
}

func checkGame() {
    //Check game
    let firstPlay:Bool = appData.bool(forKey: "\(GameData.firstPlay)")
    print(firstPlay)

    if firstPlay == false {
        print("Heading for setup")
        self.performSegue(withIdentifier: "GoToSetup", sender: nil)
    }
}
</code>```

However, the "setup viewcontroller" isn't loaded. I can manage to tricker the segue with a button-click, but that's not what I want. I want it to happen as soon as the view is loaded.

Any ideas?

答:
You can programmatically call a segue with the following:</p>

```<code> self.performSegueWithIdentifier("segueId", sender: self);
</code>```

Body:
I'm making a small game in SpriteKit where I have a bool value stored that checks if it's the first time the user plays my game. If it is, I want the app to redirect him to another viewcontroller where he enters his character-name.

However, I'm having trouble getting my app to do so.

In my "GameViewController.swift" I have this code:

override func viewDidLoad() {
    super.viewDidLoad()

    checkGame()

    if let view = self.view as! SKView? {

        // Load the SKScene from 'GameScene.sks'
        if let scene = SKScene(fileNamed: "GameScene") {
            // Set the scale mode to scale to fit the window
            scene.scaleMode = .aspectFill

            // Present the scene
            view.presentScene(scene)
        }

        view.ignoresSiblingOrder = true

        view.showsFPS = true
        view.showsNodeCount = true
    }
}

func checkGame() {
    //Check game
    let firstPlay:Bool = appData.bool(forKey: "\(GameData.firstPlay)")
    print(firstPlay)

    if firstPlay == false {
        print("Heading for setup")
        self.performSegue(withIdentifier: "GoToSetup", sender: nil)
    }
}

However, the "setup viewcontroller" isn't loaded. I can manage to tricker the segue with a button-click, but that's not what I want. I want it to happen as soon as the view is loaded.

Any ideas?

Body:
You can programmatically call a segue with the following:

 self.performSegueWithIdentifier("segueId", sender: self);


问:
How to get the current session user in Jenkins on a Groovy parameter
I need get the current log in user in Jenkins, I am using a Groovy parameter but I don't know how to get that,

Thanks,

答: def user = build.causes[0].userId</p>

Body: def user = build.causes[0].userId


问:
How to reload scene after changing its physics world gravity based on user input?
I want to allow the user to change gravity based on their input in gravity text field and pass the input from view controller to a SKScene (PhysicsScene) but I don't know how to reload scene so that it would use the custom gravity by the user instead of its default value.

view of simulator

```<code>class SimulationViewController: UIViewController, UITextFieldDelegate {

    var sceneNode : PhysicsScene?

    @IBOutlet weak var heightTextField: UITextField!
    @IBOutlet weak var massTextField: UITextField!
    @IBOutlet weak var gravityTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        sceneNode = PhysicsScene(size: view.frame.size)
        gravityTextField.delegate = self
        if let view = self.view as! SKView? {
            view.presentScene(sceneNode)
            view.ignoresSiblingOrder = true
            view.showsPhysics = true
        }
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.tag == 0 {
            if let text = textField.text {
                sceneNode?.customGravity = Double(text)!
                print(text)
            }
        }
        return true
    }
</code>```

Please help! Thank you!

答:
You have 2 options, make a property in your PhysicsScene class

```<code>  var customGravity : Double = 0{ didSet { physicsWorld.gravity = {CGPoint(x:0 y:CGFloat(customGravity)}}
</code>```

or drop custom gravity and set it directly

```<code> func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.tag == 0 {
            if let text = textField.text {
                sceneNode?.customGravity = physicsWorld.gravity = {CGPoint(x:0 y:CGFloat(Double(text)!)}
                print(text)
            }
        }
        return true
    }
</code>```

I do not have XCode available to check my typos, you may have to unwrap some variables

Body:
I want to allow the user to change gravity based on their input in gravity text field and pass the input from view controller to a SKScene (PhysicsScene) but I don't know how to reload scene so that it would use the custom gravity by the user instead of its default value.

view of simulator

class SimulationViewController: UIViewController, UITextFieldDelegate {

    var sceneNode : PhysicsScene?

    @IBOutlet weak var heightTextField: UITextField!
    @IBOutlet weak var massTextField: UITextField!
    @IBOutlet weak var gravityTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        sceneNode = PhysicsScene(size: view.frame.size)
        gravityTextField.delegate = self
        if let view = self.view as! SKView? {
            view.presentScene(sceneNode)
            view.ignoresSiblingOrder = true
            view.showsPhysics = true
        }
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.tag == 0 {
            if let text = textField.text {
                sceneNode?.customGravity = Double(text)!
                print(text)
            }
        }
        return true
    }

Please help! Thank you!

Body:
You have 2 options, make a property in your PhysicsScene class

  var customGravity : Double = 0{ didSet { physicsWorld.gravity = {CGPoint(x:0 y:CGFloat(customGravity)}}

or drop custom gravity and set it directly

 func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.tag == 0 {
            if let text = textField.text {
                sceneNode?.customGravity = physicsWorld.gravity = {CGPoint(x:0 y:CGFloat(Double(text)!)}
                print(text)
            }
        }
        return true
    }

I do not have XCode available to check my typos, you may have to unwrap some variables


问:
How can I execute ssh command in linux with specific flags without the need of an alias
I would like to use this ssh command with those flags every time I want to connect via ssh to a host since they will create an ssh session with stronger cipher and compression to make sessions faster and stronger.

Obviously I would like to save some typing and not have to type all the long command every time I want to connect to a host:

```<code>ssh -4 -C -c blowfish-cbc user@hostname
</code>```

Could anyone tell me how can I execute the command without the need to create an alias?

答:
This can all be set in your ssh config file. Which should be placed in ~/.ssh/config. For local users, /etc/ssh/ssh_config for global users.

Example of a configuration that is for a specific connection.

```<code>Host foo
    User myusername
    HostName mycomputer.com
    Port 22
    Ciphers blowfish-cbc
    Compression yes
    AddressFamily inet
</code>```

Example of a configuration that will work for everything you try to connect to (unless overridden).

```<code>Host *
    Port 22
    Ciphers blowfish-cbc
    Compression yes
    AddressFamily inet
</code>```

The first example is accessed by calling ssh foo. The configuration settings only effect that machine. This allows you to have a lot less hassle when you use multiple keys

The second example will apply settings to all hosts (note the *), unless they're overwritten by either a command or a different configuration.

Body:
I would like to use this ssh command with those flags every time I want to connect via ssh to a host since they will create an ssh session with stronger cipher and compression to make sessions faster and stronger.

Obviously I would like to save some typing and not have to type all the long command every time I want to connect to a host:

ssh -4 -C -c blowfish-cbc user@hostname

Could anyone tell me how can I execute the command without the need to create an alias?

Body:
This can all be set in your ssh config file. Which should be placed in ~/.ssh/config. For local users, /etc/ssh/ssh_config for global users.

Example of a configuration that is for a specific connection.

Host foo
    User myusername
    HostName mycomputer.com
    Port 22
    Ciphers blowfish-cbc
    Compression yes
    AddressFamily inet

Example of a configuration that will work for everything you try to connect to (unless overridden).

Host *
    Port 22
    Ciphers blowfish-cbc
    Compression yes
    AddressFamily inet

The first example is accessed by calling ssh foo. The configuration settings only effect that machine. This allows you to have a lot less hassle when you use multiple keys

The second example will apply settings to all hosts (note the *), unless they're overwritten by either a command or a different configuration.


问:
PHP7 installed by Homebrew doesn't work with Apache on macOS
I am trying to upgrade to php7 which I installed via homebrew.

In CLI php -v returns

```<code>PHP 7.0.10 (cli) (built: Aug 21 2016 19:14:33) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies
</code>```

But for localhost, firefox pops up a problem loading page, and I can't view a localhost/phpinfo.php; if I swap the module lines out back to php5 it works fine.

Here's a pastebin http://pastebin.com/950yC7wA of my apache2/httpd.conf, I have no idea how to go about fixing this.

osx version El Capitan 10.11

答:
Make sure that:

You've followed the instructions from brew info php@7.1:

```<code>==> Caveats
To enable PHP in Apache add the following to httpd.conf and restart Apache:
    LoadModule php7_module /usr/local/opt/php@7.1/lib/httpd/modules/libphp7.so

    <FilesMatch \.php$>
        SetHandler application/x-httpd-php
    </FilesMatch>

Finally, check DirectoryIndex includes index.php
    DirectoryIndex index.php index.html
</code>```

You restarted Apache via sudo apachectl restart.

For step by step tutorial, see: Setup Apache, MySQL and PHP using Homebrew on macOS Sierra.

Troubleshooting

When something doesn't work, check the logs in real-time via:

```<code>tail -f /usr/local/var/log/apache2/*error*
</code>```

Then start/restart the server.

Note: When finished, hit Control-C to quit tail.

Body:
I am trying to upgrade to php7 which I installed via homebrew.

In CLI php -v returns

PHP 7.0.10 (cli) (built: Aug 21 2016 19:14:33) ( NTS )
Copyright (c) 1997-2016 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2016 Zend Technologies

But for localhost, firefox pops up a problem loading page, and I can't view a localhost/phpinfo.php; if I swap the module lines out back to php5 it works fine.

Here's a pastebin http://pastebin.com/950yC7wA of my apache2/httpd.conf, I have no idea how to go about fixing this.

osx version El Capitan 10.11

Body:
Make sure that:

You've followed the instructions from brew info php@7.1:

==> Caveats
To enable PHP in Apache add the following to httpd.conf and restart Apache:
    LoadModule php7_module /usr/local/opt/php@7.1/lib/httpd/modules/libphp7.so

    <FilesMatch \.php$>
        SetHandler application/x-httpd-php
    </FilesMatch>

Finally, check DirectoryIndex includes index.php
    DirectoryIndex index.php index.html

You restarted Apache via sudo apachectl restart.

For step by step tutorial, see: Setup Apache, MySQL and PHP using Homebrew on macOS Sierra.

Troubleshooting

When something doesn't work, check the logs in real-time via:

tail -f /usr/local/var/log/apache2/*error*

Then start/restart the server.

Note: When finished, hit Control-C to quit tail.

ContentLicense: CC BY-SA 4.0


问:
What is a monad?
Having briefly looked at Haskell recently, what would be a brief, succinct, practical explanation as to what a monad essentially is?

I have found most explanations I've come across to be fairly inaccessible and lacking in practical detail.

答:
A monad is a thing used to encapsulate objects that have changing state. It is most often encountered in languages that otherwise do not allow you to have modifiable state (e.g., Haskell).

An example would be for file I/O.

You would be able to use a monad for file I/O to isolate the changing state nature to just the code that used the Monad. The code inside the Monad can effectively ignore the changing state of the world outside the Monad - this makes it a lot easier to reason about the overall effect of your program.

OwnerDisplayName: kronoz

Title: What is a monad?

LastEditorDisplayName: IainMH

OwnerDisplayName: 1800 INFORMATION


问:
Where can I find Android source code online?
Where can I browse the source code for any Android Open Source Project (AOSP) application (for example the Contacts application)? Is the only way to clone the entire source repository for all of AOSP?</p>

答:
Everything is mirrored on omapzoom.org. Some of the code is also mirrored on github.

Contacts is here for example.

Since December 2019, you can use the new official public code search tool for AOSP: cs.android.com. There's also the
Android official source browser (based on Gitiles) has a web view of many of the different parts that make up android. Some of the projects (such as Kernel) have been removed and it now only points you to clonable git repositories.

To get all the code locally, you can use the repo helper program, or you can just clone individual repositories.

And others:

Downloading the Source Tree

OwnerDisplayName: J. Pablo Fernández

OwnerDisplayName: rq


答:
You can use str_replace and replace with nothing:

```<code>$a =  "2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=123";
$b =  "2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=12352015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000";

Echo str_replace($a, "", $b);
</code>```

https://3v4l.org/KiZLN

Title: compare 2 strings, subtract the same characters and return the new values

Body:
You can use str_replace and replace with nothing:

$a =  "2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=123";
$b =  "2012-05-18 usr abc removed device id=858 sn=abc cmmac=000 drumac=12352015-03-26 usr mabdel001c removed device id=814 sn=abcd cmmac=1234 drumac=000";

Echo str_replace($a, "", $b);

https://3v4l.org/KiZLN


问:
Why using a non-returned method treats different?
Here is a simplified of my code:

```<code>class myclass{

    public function one($called_from = null){
        if ( $called_from != 'two'){
            return $this->two();
        }
        echo 'done';
    }

    public function two(){
        return $this->one(__FUNCTION__);
    }
}

$obj = new myclass;
$obj->one();
</code>```

Now I want to add another method to do that comparison (I'm talking about that if statement into myclass::one). So here is the new code:

```<code>class myclass{

    public function one($called_from = null){
        $this->three($called_from);
        echo 'done';
    }

    public function two(){
        return $this->one(__FUNCTION__);
    }

    public function three($called_from){
        if ( $called_from != 'two'){
            return $this->two();
        }
    }
}

$obj = new myclass;
$obj->one();
</code>```

But it treats different than the first version of the code. Why? I cannot explain what's the different, because it needs to show my other codes which are exists in reality.

Anyway, do you have any idea how can I do that comparison (into myclass::one) by another method with keeping the exact behavior in the whole process?

Also for my information (not related to the question), do you know why that line will be executed twice in this code? I expect it should be executed once.

答:
Here's the sequence of operations in the second code:

Call one() with no argument, so $called_from = null.

Call three(null).

In three, the if succeeds, so it calls two().

Call one("two").

Call three("two")

The if fails, so three just returns.

Echo "done".

Echo "done"

Since one is called twice, it echoes done twice.

Body:
Here is a simplified of my code:

class myclass{

    public function one($called_from = null){
        if ( $called_from != 'two'){
            return $this->two();
        }
        echo 'done';
    }

    public function two(){
        return $this->one(__FUNCTION__);
    }
}

$obj = new myclass;
$obj->one();

Now I want to add another method to do that comparison (I'm talking about that if statement into myclass::one). So here is the new code:

class myclass{

    public function one($called_from = null){
        $this->three($called_from);
        echo 'done';
    }

    public function two(){
        return $this->one(__FUNCTION__);
    }

    public function three($called_from){
        if ( $called_from != 'two'){
            return $this->two();
        }
    }
}

$obj = new myclass;
$obj->one();

But it treats different than the first version of the code. Why? I cannot explain what's the different, because it needs to show my other codes which are exists in reality.

Anyway, do you have any idea how can I do that comparison (into myclass::one) by another method with keeping the exact behavior in the whole process?

Also for my information (not related to the question), do you know why that line will be executed twice in this code? I expect it should be executed once.


问:
Error while uploading .xlsx file using ExcelDataReader
I am working on asp.net MVC project.

I use ExcelDataReader component to read excel file records.

Now when I published my project to server and upload a .xlsx file with uploader I get below mentioned exception message. There are no errors with local deployment but server.

Access to the path '\Microsoft Corporation\Internet Information
  Services\7.5.7600.16385' is denied.

and code where I am getting error is:

```<code>if (personsFile.FileExtension == ".xls")
{
     Stream st = new MemoryStream(personsFile.FileArray);
     reader = ExcelReaderFactory.CreateBinaryReader(st);
}
else if (personsFile.FileExtension == ".xlsx")
{
     Stream st = new MemoryStream(personsFile.FileArray);
     //exception occured on under line
     reader = ExcelReaderFactory.CreateOpenXmlReader(st);
}
</code>```

But when I upload a .xls file, I dont have any error.

How to resolve issue with .xlsx extenstion?

答: This is most likely due to ExcelDataReader 2.x extracting the xlsx archive to %TEMP% before processing it. The current pre-alpha of 3.0 no longer does this. See https://github.com/ExcelDataReader/ExcelDataReader/releases. </p>

Body:
I am working on asp.net MVC project.

I use ExcelDataReader component to read excel file records.

Now when I published my project to server and upload a .xlsx file with uploader I get below mentioned exception message. There are no errors with local deployment but server.

Access to the path '\Microsoft Corporation\Internet Information
  Services\7.5.7600.16385' is denied.

and code where I am getting error is:

if (personsFile.FileExtension == ".xls")
{
     Stream st = new MemoryStream(personsFile.FileArray);
     reader = ExcelReaderFactory.CreateBinaryReader(st);
}
else if (personsFile.FileExtension == ".xlsx")
{
     Stream st = new MemoryStream(personsFile.FileArray);
     //exception occured on under line
     reader = ExcelReaderFactory.CreateOpenXmlReader(st);
}

But when I upload a .xls file, I dont have any error.

How to resolve issue with .xlsx extenstion?