<commit_before>from base64 import b64encode
from optparse import make_option
import json
import urllib
import urllib2
import argparse
import time

def make_request(url, params, auth=None):
    """
    Prepares a request from a url, params, and optionally authentication.
    """
    req = urllib2.Request(url + urllib.urlencode(params))

    if auth:
        req.add_header('AUTHORIZATION', 'Basic ' + auth)

    return urllib2.urlopen(req)

def beginTransaction(url, auth):
    print('Starting transaction...')
    params = {'output_format': 'JSON'}
    request = make_request(url=url+'beginTransaction.json?', params=params, auth=auth)

    if request.getcode() != 200:
        raise Exception("BeginTransaction failed: Status Code {0}".format(request.getcode()))

    response = json.loads(request.read())

    if not response['response']['success']:
        raise Exception("An error occurred on beginTransaction: {0}".format(response['response']['error']))

    print('Transaction started')
    transactionId = response['response']['Transaction']['ID']

    return transactionId;

def endTransaction(url, auth, cancel, transactionId):
    print('Ending transaction...')
    params = {'output_format': 'JSON', 'cancel': cancel, 'transactionId': transactionId}
    request = make_request(url=url+'endTransaction.json?', params=params, auth=auth)

    if request.getcode() != 200:
        raise Exception("EndTransaction failed: Status Code {0}".format(request.getcode()))

    response = json.loads(request.read())

    if not response['response']['success']:
        raise Exception("An error occurred on endTransaction: {0}".format(response['response']['error']))

def getTaskStatus(url, auth, taskID, printStatus):
    print('Downloading from OpenStreetMap ...')
    params = {}
    request = make_request(url=url+'/'+str(taskID)+'.json', params=params, auth=auth)

    if request.getcode() != 200:
        raise Exception("Get Task Status Failed: Status Code {0}".format(request.getcode()))

    response = json.loads(request.read())
    print response

    taskStatus = response['task']['status']

    if printStatus:
        print "++Task "+str(taskID)+" is "+taskStatus+"."

    return taskID;

def waitOnTask(url, auth, taskID):
    print "Waiting for task "+str(taskID)+"..."

    maxTime = 20
    timeSlept = 0
    sleepCycle = 2

    while timeSlept < maxTime and getTaskStatus(url, auth, taskID, True) in ['WAITING','RUNNING']:
        time.sleep(sleepCycle)
        timeSlept += sleepCycle

    print "Task "+str(taskID)+" is done"

def downloadFromOSM(url, auth, transactionId):
    print('Downloading from OpenStreetMap ...')
    params = {'output_format': 'JSON', 'update': 'true'}
    request = make_request(url=url+'osm/download.json?', params=params, auth=auth)

    if request.getcode() != 200:
        raise Exception("OSM Download failed: Status Code {0}".format(request.getcode()))

    response = json.loads(request.read())

    taskID = response['task']['id']

    #print response
    if response['task']['status'] == 'FAILED':
        raise Exception("An error occurred when pulling new data from OSM: {0}".format(response['task']['status']))

    if response['task']['status'] == 'WAITING':
        print('Download from OpenStreetMap is waiting to be processed.  Task ID is '+str(taskID)+'.')

    if response['task']['status'] == 'RUNNING':
        print('Download from OpenStreetMap is being processed.  Task ID is '+str(taskID)+'.')

    return taskID;

def parse_url(url):

    if (url is None) or len(url) == 0:
        return None

    index = url.rfind('/')

    if index != (len(url)-1):
        url += '/'

    return url

def run(args):
    #url = parse_url(args)
    #if url is None:
    #    print "Please specify a url"
    #    return 1

    geoserver = parse_url(args.geoserver)
    repo = args.repo
    url_repo = geoserver+'geogig/'+repo+'/'
    url_tasks = geoserver+'geogig/tasks'

    authorname = args.authorname
    authoremail = args.authoremail
    auth = None
    if args.username and args.password:
      auth = b64encode('{0}:{1}'.format(args.username, args.password))

    transID = -1
    try:
        transID = beginTransaction(url_repo, auth)
    except Exception:
        transID = -1
        raise

    if transID != -1:
        taskID = -1
        try:
            taskID = downloadFromOSM(url_repo, auth, transID)
        except Exception:
            taskID = -1
            endTransaction(url_repo, auth, True, transID)
            raise

        if taskID != -1:
            waitOnTask(url_tasks, auth, taskID)

    try:
        endTransaction(url_repo, auth, False, transID)
    except Exception:
        pass

parser = argparse.ArgumentParser(description='Synchronize GeoGig repository with OpenStreetMap (OSM)')
parser.add_argument("--geoserver", help="The url of the GeoServer servicing the GeoGig repository.")
parser.add_argument("--repo", help="The GeoServer id of the GeoGig repository you want to sync.")
parser.add_argument("--username", help="The username to use for basic auth requests.")
parser.add_argument("--password", help="The password to use for basic auth requests.")
parser.add_argument("--authorname", help="The author name to use when merging non-conflicting branches.")
parser.add_argument("--authoremail", help="The author email to use when merging non-conflicting branches.")

args = parser.parse_args()
run(args)
<commit_msg>Update geogig_sync_osm.py<commit_after>from base64 import b64encode
from optparse import make_option
import json
import urllib
import urllib2
import argparse
import time

def make_request(url, params, auth=None):
    """
    Prepares a request from a url, params, and optionally authentication.
    """
    req = urllib2.Request(url + urllib.urlencode(params))

    if auth:
        req.add_header('AUTHORIZATION', 'Basic ' + auth)

    return urllib2.urlopen(req)

def beginTransaction(url, auth):
    print('Starting transaction...')
    params = {'output_format': 'JSON'}
    request = make_request(url=url+'beginTransaction.json?', params=params, auth=auth)

    if request.getcode() != 200:
        raise Exception("BeginTransaction failed: Status Code {0}".format(request.getcode()))

    response = json.loads(request.read())

    if not response['response']['success']:
        raise Exception("An error occurred on beginTransaction: {0}".format(response['response']['error']))

    print('Transaction started')
    transactionId = response['response']['Transaction']['ID']

    return transactionId;

def endTransaction(url, auth, cancel, transactionId):
    print('Ending transaction...')
    params = {'output_format': 'JSON', 'cancel': cancel, 'transactionId': transactionId}
    request = make_request(url=url+'endTransaction.json?', params=params, auth=auth)

    if request.getcode() != 200:
        raise Exception("EndTransaction failed: Status Code {0}".format(request.getcode()))

    response = json.loads(request.read())

    if not response['response']['success']:
        raise Exception("An error occurred on endTransaction: {0}".format(response['response']['error']))

def getTaskStatus(url, auth, taskID, printStatus):
    print('Downloading from OpenStreetMap ...')
    params = {}
    request = make_request(url=url+'/'+str(taskID)+'.json', params=params, auth=auth)

    if request.getcode() != 200:
        raise Exception("Get Task Status Failed: Status Code {0}".format(request.getcode()))

    response = json.loads(request.read())

    taskStatus = response['task']['status']
    taskAmount = response['task']['amount']

    if printStatus:
        if taskStatus == "RUNNING":
            print "++Task "+str(taskID)+" is running and "+taskAmount+" percentage complete."
        else:
            print "++Task "+str(taskID)+" is "+taskStatus+"."

    return taskID;

def waitOnTask(url, auth, taskID):
    print "Waiting for task "+str(taskID)+"..."

    maxTime = 20
    timeSlept = 0
    sleepCycle = 2

    while timeSlept < maxTime and getTaskStatus(url, auth, taskID, True) in ['WAITING','RUNNING']:
        time.sleep(sleepCycle)
        timeSlept += sleepCycle

    print "Task "+str(taskID)+" is done"

def downloadFromOSM(url, auth, transactionId):
    print('Downloading from OpenStreetMap ...')
    params = {'output_format': 'JSON', 'update': 'true'}
    request = make_request(url=url+'osm/download.json?', params=params, auth=auth)

    if request.getcode() != 200:
        raise Exception("OSM Download failed: Status Code {0}".format(request.getcode()))

    response = json.loads(request.read())

    taskID = response['task']['id']

    #print response
    if response['task']['status'] == 'FAILED':
        raise Exception("An error occurred when pulling new data from OSM: {0}".format(response['task']['status']))

    if response['task']['status'] == 'WAITING':
        print('Download from OpenStreetMap is waiting to be processed.  Task ID is '+str(taskID)+'.')

    if response['task']['status'] == 'RUNNING':
        print('Download from OpenStreetMap is being processed.  Task ID is '+str(taskID)+'.')

    return taskID;

def parse_url(url):

    if (url is None) or len(url) == 0:
        return None

    index = url.rfind('/')

    if index != (len(url)-1):
        url += '/'

    return url

def run(args):
    #url = parse_url(args)
    #if url is None:
    #    print "Please specify a url"
    #    return 1

    geoserver = parse_url(args.geoserver)
    repo = args.repo
    url_repo = geoserver+'geogig/'+repo+'/'
    url_tasks = geoserver+'geogig/tasks'

    authorname = args.authorname
    authoremail = args.authoremail
    auth = None
    if args.username and args.password:
      auth = b64encode('{0}:{1}'.format(args.username, args.password))

    transID = -1
    try:
        transID = beginTransaction(url_repo, auth)
    except Exception:
        transID = -1
        raise

    if transID != -1:
        taskID = -1
        try:
            taskID = downloadFromOSM(url_repo, auth, transID)
        except Exception:
            taskID = -1
            endTransaction(url_repo, auth, True, transID)
            raise

        if taskID != -1:
            waitOnTask(url_tasks, auth, taskID)

    try:
        endTransaction(url_repo, auth, False, transID)
    except Exception:
        pass

parser = argparse.ArgumentParser(description='Synchronize GeoGig repository with OpenStreetMap (OSM)')
parser.add_argument("--geoserver", help="The url of the GeoServer servicing the GeoGig repository.")
parser.add_argument("--repo", help="The GeoServer id of the GeoGig repository you want to sync.")
parser.add_argument("--username", help="The username to use for basic auth requests.")
parser.add_argument("--password", help="The password to use for basic auth requests.")
parser.add_argument("--authorname", help="The author name to use when merging non-conflicting branches.")
parser.add_argument("--authoremail", help="The author email to use when merging non-conflicting branches.")

args = parser.parse_args()
run(args)
<|endoftext|>


<commit_before>#!/usr/bin/env python

import base64
import json
import logging
import os
import random
import time

from roushclient.client import RoushEndpoint
from state import StateMachine, StateMachineState
from primitives import OrchestratorTasks

name = 'adventurator'
roush_endpoint = 'http://localhost:8080'

def setup(config={}):
    global roush_endpoint
    roush_endpoint = 'http://localhost:8080'

    if 'roush_endpoint' in config:
        roush_endpoint = config['roush_endpoint']

    LOG.debug('doing setup for %s handler' % name)
    register_action('adventurate', handle_adventurate)

def handle_adventurate(input_data):
    global roush_endpoint

    action = input_data['action']
    payload = input_data['payload']

    if not 'adventure' in payload:
        return _retval(1, friendly_str='no adventure specified in request')

    if not 'nodes' in payload:
        return _retval(1, friendly_str='no "nodes" list in request')

    ep = RoushEndpoint(self.roush_endpoint)

    adventure = payload['adventure']
    if 'initial_state' in payload:
        initial_state = payload['initial_state']
    else:
        initial_state = {}

    if not 'nodes' in initial_state:
        initial_state['nodes'] = payload['nodes']

    adventure_obj = ep.adventures[int(adventure)]

    if adventure_obj.language != 'json':
        return _retval(1, friendly_str='language %s not currently supported' % adventure_obj.language)

    ns = {}
    ns['LOG'] = LOG
    ns['StateMachine'] = StateMachine
    ns['StateMachineState'] = StateMachineState
    ns['tasks'] = OrchestratorTasks(endpoint=self.roush_endpoint)
    ns['input_data'] = initial_state
    ns['result_str'] = 'fail'
    ns['result_code'] = 254
    ns['result_data'] = {}
    ns['sm_description'] = json.dumps(adventure.dsl)

    exec '(result_data, _) = tasks.sm_eval(sm_description, input_data)' in ns, ns

    output_data = {'result_code': 1,
                   'result_str': 'no return data from adventure',
                   'result_data': {}}

    if 'result_data' in ns:
        output_data = ns['result_data']
    return output_data

def _retval(result_code, friendly_str=None, result_data={}):
    if not friendly_str:
        friendly_str = 'success' if result_code == 0 else 'fail'

    return {'result_code': result_code,
            'result_str': friendly_str,
            'result_data': result_data}
<commit_msg>fix for new namespacing<commit_after>#!/usr/bin/env python

import base64
import json
import logging
import os
import random
import time

from roushclient.client import RoushEndpoint
from state import StateMachine, StateMachineState
from primitives import OrchestratorTasks

name = 'adventurator'
roush_endpoint = 'http://localhost:8080'

def setup(config={}):
    global roush_endpoint
    roush_endpoint = 'http://localhost:8080'

    if 'roush_endpoint' in config:
        roush_endpoint = config['roush_endpoint']

    LOG.debug('doing setup for %s handler' % name)
    register_action('adventurate', handle_adventurate)

def handle_adventurate(input_data):
    global roush_endpoint

    action = input_data['action']
    payload = input_data['payload']

    if not 'adventure' in payload:
        return _retval(1, friendly_str='no adventure specified in request')

    if not 'nodes' in payload:
        return _retval(1, friendly_str='no "nodes" list in request')

    ep = RoushEndpoint(roush_endpoint)

    adventure = payload['adventure']
    if 'initial_state' in payload:
        initial_state = payload['initial_state']
    else:
        initial_state = {}

    if not 'nodes' in initial_state:
        initial_state['nodes'] = payload['nodes']

    adventure_obj = ep.adventures[int(adventure)]

    if adventure_obj.language != 'json':
        return _retval(1, friendly_str='language %s not currently supported' % adventure_obj.language)

    ns = {}
    ns['LOG'] = LOG
    ns['StateMachine'] = StateMachine
    ns['StateMachineState'] = StateMachineState
    ns['tasks'] = OrchestratorTasks(endpoint=roush_endpoint)
    ns['input_data'] = initial_state
    ns['result_str'] = 'fail'
    ns['result_code'] = 254
    ns['result_data'] = {}
    ns['sm_description'] = json.dumps(adventure.dsl)

    exec '(result_data, _) = tasks.sm_eval(sm_description, input_data)' in ns, ns

    output_data = {'result_code': 1,
                   'result_str': 'no return data from adventure',
                   'result_data': {}}

    if 'result_data' in ns:
        output_data = ns['result_data']
    return output_data

def _retval(result_code, friendly_str=None, result_data={}):
    if not friendly_str:
        friendly_str = 'success' if result_code == 0 else 'fail'

    return {'result_code': result_code,
            'result_str': friendly_str,
            'result_data': result_data}
<|endoftext|>


<commit_before>import neovim
import os
import subprocess
import json
import threading
import time
from functools import partial
from typing import List, Dict, Any  # noqa: F401

from . util import getRootPath, pathToURI, uriToPath, escape
from . logger import logger
from . RPC import RPC
from . TextDocumentItem import TextDocumentItem
from . Debounce import Debounce

@neovim.plugin
class LanguageClient:
    def __init__(self, nvim):
        logger.info('__init__')
        self.nvim = nvim
        self.server = None
        self.capabilities = {}
        self.textDocuments = {}  # type: Dict[str, TextDocumentItem]

    def asyncEval(self, expr: str) -> None:
        self.nvim.async_call(lambda: self.nvim.eval(expr))

    def asyncCommand(self, cmds: str) -> None:
        self.nvim.async_call(lambda: self.nvim.command(cmds))

    def asyncEcho(self, message: str) -> None:
        message = escape(message)
        self.asyncCommand("echo '{}'".format(message))

    def getPos(self, mark=".") -> List[int]:
        _, line, character, _ = self.nvim.call("getpos", mark)
        return [line - 1, character - 1]

    def getArgs(self, argsL: List, keys: List) -> List:
        if len(argsL) == 0:
            args = {}  # type: Dict[str, Any]
        else:
            args = argsL[0]

        pos = []  # type: List[int]

        res = []
        for k in keys:
            if k == "uri":
                v = args.get("uri", pathToURI(self.nvim.current.buffer.name))
            elif k == "line":
                pos = self.getPos()
                v = args.get("line", pos[0])
            elif k == "character":
                v = args.get("character", pos[1])
            else:
                v = args.get(k, None)
            res.append(v)

        return res

    def applyChanges(self, changes: Dict, curPos: Dict) -> None:
        for uri, edits in changes.items():
            self.asyncCommand("edit {}".format(uriToPath(uri)))
            for edit in edits:
                line = edit['range']['start']['line'] + 1
                character = edit['range']['start']['character'] + 1
                newText = edit['newText']
                cmd = "normal! {}G{}|cw{}".format(line, character, newText)
                self.asyncCommand(cmd)
        self.asyncCommand("edit {}".format(uriToPath(curPos["uri"])))
        line = curPos["line"] + 1
        character = curPos["character"] + 1
        self.asyncCommand("normal! {}G{}|".format(line, character))

    def alive(self, warn=True) -> bool:
        if self.server is None or self.server.poll() is not None:
            if warn:
                self.asyncEcho("Language client is not running. Try :LanguageClientStart")  # noqa: E501
            return False
        return True

    @neovim.command('LanguageClientStart')
    def start(self) -> None:
        if self.alive(warn=False):
            return

        logger.info('start')

        filetype = self.nvim.eval('&filetype')
        commands = self.nvim.eval('g:LanguageClient_serverCommands')
        if not filetype or filetype not in commands:
            self.asyncEcho("No language server commmand found for type: {}.".format(filetype))  # noqa: E501
            return
        command = commands[filetype]

        self.server = subprocess.Popen(
            # ["/bin/bash", "/opt/rls/wrapper.sh"],
            command,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True)
        self.rpc = RPC(
            self.server.stdout, self.server.stdin,
            self.handleRequestOrNotification,
            self.handleRequestOrNotification,
            self.handleError)
        threading.Thread(
                target=self.rpc.serve, name="RPC Server", daemon=True).start()
        time.sleep(0.5)

        self.initialize([])
        self.textDocument_didOpen([])

    @neovim.function('LanguageClient_initialize')
    def initialize(self, args: List) -> None:
        # {rootPath?: str, cb?}
        if not self.alive():
            return

        logger.info('initialize')

        rootPath, cb = self.getArgs(args, ["rootPath", "cb"])
        if rootPath is None:
            rootPath = getRootPath(self.nvim.current.buffer.name)
        if cb is None:
            cb = self.handleInitializeResponse

        self.rpc.call('initialize', {
            "processId": os.getpid(),
            "rootPath": rootPath,
            "rootUri": pathToURI(rootPath),
            "capabilities": {},
            "trace": "verbose"
            }, cb)

    def handleInitializeResponse(self, result: Dict) -> None:
        self.capabilities = result['capabilities']
        self.asyncEcho("LanguageClient initialization finished.")

    @neovim.function('LanguageClient_textDocument_didOpen')
    def textDocument_didOpen(self, args: List) -> None:
        # {uri?: str}
        if not self.alive():
            return

        logger.info('textDocument/didOpen')

        uri, = self.getArgs(args, ["uri"])
        languageId = self.nvim.eval('&filetype')
        text = str.join(
                "",
                [l + "\n" for l in self.nvim.call("getline", 1, "$")])

        textDocumentItem = TextDocumentItem(uri, languageId, text)
        self.textDocuments[uri] = textDocumentItem

        self.rpc.notify('textDocument/didOpen', {
            "textDocument": {
                "textDocument": textDocumentItem.__dict__
                }
            })

    @neovim.function('LanguageClient_textDocument_didClose')
    def textDocument_didClose(self, args: List) -> None:
        # {uri?: str}
        if not self.alive():
            return

        logger.info('textDocument/didClose')

        uri, = self.getArgs(args, ["uri"])
        del self.textDocuments[uri]

        self.rpc.notify('textDocument/didClose', {
            "textDocument": {
                "uri": uri
                }
            })

    @neovim.function('LanguageClient_textDocument_hover')
    def textDocument_hover(self, args: List) -> None:
        # {uri?: str, line?: int, character?: int, cb?}
        if not self.alive():
            return

        logger.info('textDocument/hover')

        uri, line, character, cb = self.getArgs(
            args, ["uri", "line", "character", "cb"])
        if cb is None:
            cb = self.handleTextDocumentHoverResponse

        self.rpc.call('textDocument/hover', {
            "textDocument": {
                "uri": uri
                },
            "position": {
                "line": line,
                "character": character
                }
            }, cb)

    def markedStringToString(self, s: Any) -> str:
        if isinstance(s, str):
            return s
        else:
            return s["value"]

    def handleTextDocumentHoverResponse(self, result: Dict) -> None:
        contents = result["contents"]
        value = ''
        if isinstance(contents, list):
            for markedString in result['contents']:
                value += self.markedStringToString(markedString)
        else:
            value += self.markedStringToString(contents)
        self.asyncEcho(value)

    # TODO
    # textDocument/completion
    # completionItem/resolve
    # textDocument/signatureHelp
    # textDocument/references
    # textDocument/codeAction

    @neovim.function('LanguageClient_textDocument_definition')
    def textDocument_definition(self, args: List) -> None:
        # {uri?: str, line?: int, character?: int, cb?}
        if not self.alive():
            return

        logger.info('textDocument/definition')

        uri, line, character, cb = self.getArgs(
            args, ["uri", "line", "character", "cb"])
        if cb is None:
            cb = self.handleTextDocumentDefinitionResponse

        self.rpc.call('textDocument/definition', {
            "textDocument": {
                "uri": uri
                },
            "position": {
                "line": line,
                "character": character
                }
            }, cb)

    def handleTextDocumentDefinitionResponse(self, result: List) -> None:
        if len(result) > 1:
            logger.warn(
                "Handling multiple definition are not implemented yet.")

        defn = result[0]
        self.asyncCommand("edit {}".format(uriToPath(defn["uri"])))
        line = defn['range']['start']['line'] + 1
        character = defn['range']['start']['character'] + 1
        self.asyncCommand("normal! {}G{}|".format(line, character))

    @neovim.function('LanguageClient_textDocument_rename')
    def textDocument_rename(self, args: List) -> None:
        # {uri?: str, line?: int, character?: int, newName?: str, cb?}
        if not self.alive():
            return

        logger.info('textDocument/rename')

        uri, line, character, newName, cb = self.getArgs(
            args, ["uri", "line", "character", "newName", "cb"])
        if newName is None:
            self.nvim.call("inputsave")
            newName = self.nvim.call("input", "Rename to: ")
            self.nvim.call("inputrestore")
        if cb is None:
            cb = partial(
                    self.handleTextDocumentRenameResponse,
                    curPos={"line": line, "character": character, "uri": uri})

        self.rpc.call('textDocument/rename', {
            "textDocument": {
                "uri": uri
                },
            "position": {
                "line": line,
                "character": character,
                },
            "newName": newName
            }, cb)

    def handleTextDocumentRenameResponse(
            self, result: Dict, curPos: Dict) -> None:
        changes = result['changes']
        self.applyChanges(changes, curPos)

    @neovim.function('LanguageClient_textDocument_documentSymbol')
    def textDocument_documentSymbol(self, args: List) -> None:
        # {uri?: str, cb?}
        if not self.alive():
            return

        logger.info('textDocument/documentSymbol')

        uri, cb = self.getArgs(args, ["uri", "cb"])
        if cb is None:
            if self.nvim.eval("get(g:, 'loaded_fzf', 0)") == 1:
                cb = self.handleTextDocumentDocumentSymbolResponse
            else:
                logger.warn("FZF not loaded.")

        self.rpc.call('textDocument/documentSymbol', {
            "textDocument": {
                "uri": uri
                }
            }, cb)

    def handleTextDocumentDocumentSymbolResponse(self, symbols: List) -> None:
        opts = {
            "source": [],
            "sink": "LanguageClientFZFSink"
            }  # type: Dict[str, Any]
        for sb in symbols:
            name = sb["name"]
            start = sb["location"]["range"]["start"]
            line = start["line"] + 1
            character = start["character"] + 1
            entry = "{}:{}:\t{}".format(line, character, name)
            opts["source"].append(entry)
        self.asyncCommand(
                "call fzf#run(fzf#wrap({}))"
                .format(json.dumps(opts)))
        self.nvim.async_call(lambda: self.nvim.feedkeys("i"))

    @neovim.command('LanguageClientFZFSink', nargs='*')
    def fzfSink(self, args: List) -> None:
        splitted = args[0].split(":")
        line = int(splitted[0])
        character = int(splitted[1])
        self.asyncCommand("normal! {}G{}|".format(line, character))

    @neovim.function('LanguageClient_workspace_symbol')
    def workspace_symbol(self, args: List) -> None:
        if not self.alive():
            return
        logger.info("workspace/symbol")

        query, cb = self.getArgs(args, ["query", "cb"])
        if cb is None:
            cb = self.handleWorkspaceSymbolResponse

        self.rpc.call('workspace/symbol', {
            "query": query
            }, cb)

    def handleWorkspaceSymbolResponse(self, result: list) -> None:
        self.asyncEcho("{} symbols".format(len(result)))

    @neovim.function("LanguageClient_textDocument_didChange")
    @Debounce(1)
    def textDocument_didChange(self, args: List) -> None:
        # {uri?: str, contentChanges?: []}
        if not self.alive(warn=False):
            return
        logger.info("textDocument/didChange")

        uri, contentChanges = self.getArgs(
                args, ["uri", "contentChanges"])

        newText = str.join(
                "",
                [l + "\n" for l in self.nvim.call("getline", 1, "$")])
        version, changes = self.textDocuments[uri].change(newText)

        self.rpc.notify("textDocument/didChange", {
            "textDocument": {
                "uri": uri,
                "version": version
                },
            "contentChanges": changes
            })

    @neovim.function("LanguageClient_textDocument_didSave")
    def textDocument_didSave(self, args: List) -> None:
        # {uri?: str}
        if not self.alive(warn=False):
            return
        logger.info("textDocument/didSave")

        uri, = self.getArgs(args, ["uri"])

        self.rpc.notify("textDocument/didSave", {
            "textDocument": {
                "uri": uri
                }
            })

    # FIXME: python infinite loop after this call.
    @neovim.function("LanguageClient_exit")
    def exit(self, args: List) -> None:
        # {uri?: str}
        if not self.alive():
            return
        logger.info("exit")

        self.rpc.notify("exit", {})

    def textDocument_publishDiagnostics(self, params) -> None:
        for diagnostic in params['diagnostics']:
            message = diagnostic['message'].replace("\n", ". ")
            self.asyncEcho(message)

    def handleRequestOrNotification(self, message) -> None:
        method = message['method'].replace('/', '_')
        if hasattr(self, method):
            try:
                getattr(self, method)(message['params'])
            except:
                logger.exception("Exception in handle.")
        else:
            logger.warn('no handler implemented for ' + method)

    def handleError(self, message) -> None:
        self.asyncEcho(json.dumps(message))
<commit_msg>Warn when running LanguageClientStart multiple times.<commit_after>import neovim
import os
import subprocess
import json
import threading
import time
from functools import partial
from typing import List, Dict, Any  # noqa: F401

from . util import getRootPath, pathToURI, uriToPath, escape
from . logger import logger
from . RPC import RPC
from . TextDocumentItem import TextDocumentItem
from . Debounce import Debounce

@neovim.plugin
class LanguageClient:
    def __init__(self, nvim):
        logger.info('__init__')
        self.nvim = nvim
        self.server = None
        self.capabilities = {}
        self.textDocuments = {}  # type: Dict[str, TextDocumentItem]

    def asyncEval(self, expr: str) -> None:
        self.nvim.async_call(lambda: self.nvim.eval(expr))

    def asyncCommand(self, cmds: str) -> None:
        self.nvim.async_call(lambda: self.nvim.command(cmds))

    def asyncEcho(self, message: str) -> None:
        message = escape(message)
        self.asyncCommand("echo '{}'".format(message))

    def getPos(self, mark=".") -> List[int]:
        _, line, character, _ = self.nvim.call("getpos", mark)
        return [line - 1, character - 1]

    def getArgs(self, argsL: List, keys: List) -> List:
        if len(argsL) == 0:
            args = {}  # type: Dict[str, Any]
        else:
            args = argsL[0]

        pos = []  # type: List[int]

        res = []
        for k in keys:
            if k == "uri":
                v = args.get("uri", pathToURI(self.nvim.current.buffer.name))
            elif k == "line":
                pos = self.getPos()
                v = args.get("line", pos[0])
            elif k == "character":
                v = args.get("character", pos[1])
            else:
                v = args.get(k, None)
            res.append(v)

        return res

    def applyChanges(self, changes: Dict, curPos: Dict) -> None:
        for uri, edits in changes.items():
            self.asyncCommand("edit {}".format(uriToPath(uri)))
            for edit in edits:
                line = edit['range']['start']['line'] + 1
                character = edit['range']['start']['character'] + 1
                newText = edit['newText']
                cmd = "normal! {}G{}|cw{}".format(line, character, newText)
                self.asyncCommand(cmd)
        self.asyncCommand("edit {}".format(uriToPath(curPos["uri"])))
        line = curPos["line"] + 1
        character = curPos["character"] + 1
        self.asyncCommand("normal! {}G{}|".format(line, character))

    def alive(self, warn=True) -> bool:
        if self.server is None or self.server.poll() is not None:
            if warn:
                self.asyncEcho("Language client is not running. Try :LanguageClientStart")  # noqa: E501
            return False
        return True

    @neovim.command('LanguageClientStart')
    def start(self) -> None:
        if self.alive(warn=False):
            self.asyncEcho("Language client has already started.")
            return

        logger.info('start')

        filetype = self.nvim.eval('&filetype')
        commands = self.nvim.eval('g:LanguageClient_serverCommands')
        if not filetype or filetype not in commands:
            self.asyncEcho("No language server commmand found for type: {}.".format(filetype))  # noqa: E501
            return
        command = commands[filetype]

        self.server = subprocess.Popen(
            # ["/bin/bash", "/opt/rls/wrapper.sh"],
            command,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            universal_newlines=True)
        self.rpc = RPC(
            self.server.stdout, self.server.stdin,
            self.handleRequestOrNotification,
            self.handleRequestOrNotification,
            self.handleError)
        threading.Thread(
                target=self.rpc.serve, name="RPC Server", daemon=True).start()
        time.sleep(0.5)

        self.initialize([])
        self.textDocument_didOpen([])

    @neovim.function('LanguageClient_initialize')
    def initialize(self, args: List) -> None:
        # {rootPath?: str, cb?}
        if not self.alive():
            return

        logger.info('initialize')

        rootPath, cb = self.getArgs(args, ["rootPath", "cb"])
        if rootPath is None:
            rootPath = getRootPath(self.nvim.current.buffer.name)
        if cb is None:
            cb = self.handleInitializeResponse

        self.rpc.call('initialize', {
            "processId": os.getpid(),
            "rootPath": rootPath,
            "rootUri": pathToURI(rootPath),
            "capabilities": {},
            "trace": "verbose"
            }, cb)

    def handleInitializeResponse(self, result: Dict) -> None:
        self.capabilities = result['capabilities']
        self.asyncEcho("LanguageClient initialization finished.")

    @neovim.function('LanguageClient_textDocument_didOpen')
    def textDocument_didOpen(self, args: List) -> None:
        # {uri?: str}
        if not self.alive():
            return

        logger.info('textDocument/didOpen')

        uri, = self.getArgs(args, ["uri"])
        languageId = self.nvim.eval('&filetype')
        text = str.join(
                "",
                [l + "\n" for l in self.nvim.call("getline", 1, "$")])

        textDocumentItem = TextDocumentItem(uri, languageId, text)
        self.textDocuments[uri] = textDocumentItem

        self.rpc.notify('textDocument/didOpen', {
            "textDocument": {
                "textDocument": textDocumentItem.__dict__
                }
            })

    @neovim.function('LanguageClient_textDocument_didClose')
    def textDocument_didClose(self, args: List) -> None:
        # {uri?: str}
        if not self.alive():
            return

        logger.info('textDocument/didClose')

        uri, = self.getArgs(args, ["uri"])
        del self.textDocuments[uri]

        self.rpc.notify('textDocument/didClose', {
            "textDocument": {
                "uri": uri
                }
            })

    @neovim.function('LanguageClient_textDocument_hover')
    def textDocument_hover(self, args: List) -> None:
        # {uri?: str, line?: int, character?: int, cb?}
        if not self.alive():
            return

        logger.info('textDocument/hover')

        uri, line, character, cb = self.getArgs(
            args, ["uri", "line", "character", "cb"])
        if cb is None:
            cb = self.handleTextDocumentHoverResponse

        self.rpc.call('textDocument/hover', {
            "textDocument": {
                "uri": uri
                },
            "position": {
                "line": line,
                "character": character
                }
            }, cb)

    def markedStringToString(self, s: Any) -> str:
        if isinstance(s, str):
            return s
        else:
            return s["value"]

    def handleTextDocumentHoverResponse(self, result: Dict) -> None:
        contents = result["contents"]
        value = ''
        if isinstance(contents, list):
            for markedString in result['contents']:
                value += self.markedStringToString(markedString)
        else:
            value += self.markedStringToString(contents)
        self.asyncEcho(value)

    # TODO
    # textDocument/completion
    # completionItem/resolve
    # textDocument/signatureHelp
    # textDocument/references
    # textDocument/codeAction

    @neovim.function('LanguageClient_textDocument_definition')
    def textDocument_definition(self, args: List) -> None:
        # {uri?: str, line?: int, character?: int, cb?}
        if not self.alive():
            return

        logger.info('textDocument/definition')

        uri, line, character, cb = self.getArgs(
            args, ["uri", "line", "character", "cb"])
        if cb is None:
            cb = self.handleTextDocumentDefinitionResponse

        self.rpc.call('textDocument/definition', {
            "textDocument": {
                "uri": uri
                },
            "position": {
                "line": line,
                "character": character
                }
            }, cb)

    def handleTextDocumentDefinitionResponse(self, result: List) -> None:
        if len(result) > 1:
            logger.warn(
                "Handling multiple definition are not implemented yet.")

        defn = result[0]
        self.asyncCommand("edit {}".format(uriToPath(defn["uri"])))
        line = defn['range']['start']['line'] + 1
        character = defn['range']['start']['character'] + 1
        self.asyncCommand("normal! {}G{}|".format(line, character))

    @neovim.function('LanguageClient_textDocument_rename')
    def textDocument_rename(self, args: List) -> None:
        # {uri?: str, line?: int, character?: int, newName?: str, cb?}
        if not self.alive():
            return

        logger.info('textDocument/rename')

        uri, line, character, newName, cb = self.getArgs(
            args, ["uri", "line", "character", "newName", "cb"])
        if newName is None:
            self.nvim.call("inputsave")
            newName = self.nvim.call("input", "Rename to: ")
            self.nvim.call("inputrestore")
        if cb is None:
            cb = partial(
                    self.handleTextDocumentRenameResponse,
                    curPos={"line": line, "character": character, "uri": uri})

        self.rpc.call('textDocument/rename', {
            "textDocument": {
                "uri": uri
                },
            "position": {
                "line": line,
                "character": character,
                },
            "newName": newName
            }, cb)

    def handleTextDocumentRenameResponse(
            self, result: Dict, curPos: Dict) -> None:
        changes = result['changes']
        self.applyChanges(changes, curPos)

    @neovim.function('LanguageClient_textDocument_documentSymbol')
    def textDocument_documentSymbol(self, args: List) -> None:
        # {uri?: str, cb?}
        if not self.alive():
            return

        logger.info('textDocument/documentSymbol')

        uri, cb = self.getArgs(args, ["uri", "cb"])
        if cb is None:
            if self.nvim.eval("get(g:, 'loaded_fzf', 0)") == 1:
                cb = self.handleTextDocumentDocumentSymbolResponse
            else:
                logger.warn("FZF not loaded.")

        self.rpc.call('textDocument/documentSymbol', {
            "textDocument": {
                "uri": uri
                }
            }, cb)

    def handleTextDocumentDocumentSymbolResponse(self, symbols: List) -> None:
        opts = {
            "source": [],
            "sink": "LanguageClientFZFSink"
            }  # type: Dict[str, Any]
        for sb in symbols:
            name = sb["name"]
            start = sb["location"]["range"]["start"]
            line = start["line"] + 1
            character = start["character"] + 1
            entry = "{}:{}:\t{}".format(line, character, name)
            opts["source"].append(entry)
        self.asyncCommand(
                "call fzf#run(fzf#wrap({}))"
                .format(json.dumps(opts)))
        self.nvim.async_call(lambda: self.nvim.feedkeys("i"))

    @neovim.command('LanguageClientFZFSink', nargs='*')
    def fzfSink(self, args: List) -> None:
        splitted = args[0].split(":")
        line = int(splitted[0])
        character = int(splitted[1])
        self.asyncCommand("normal! {}G{}|".format(line, character))

    @neovim.function('LanguageClient_workspace_symbol')
    def workspace_symbol(self, args: List) -> None:
        if not self.alive():
            return
        logger.info("workspace/symbol")

        query, cb = self.getArgs(args, ["query", "cb"])
        if cb is None:
            cb = self.handleWorkspaceSymbolResponse

        self.rpc.call('workspace/symbol', {
            "query": query
            }, cb)

    def handleWorkspaceSymbolResponse(self, result: list) -> None:
        self.asyncEcho("{} symbols".format(len(result)))

    @neovim.function("LanguageClient_textDocument_didChange")
    @Debounce(1)
    def textDocument_didChange(self, args: List) -> None:
        # {uri?: str, contentChanges?: []}
        if not self.alive(warn=False):
            return
        logger.info("textDocument/didChange")

        uri, contentChanges = self.getArgs(
                args, ["uri", "contentChanges"])

        newText = str.join(
                "",
                [l + "\n" for l in self.nvim.call("getline", 1, "$")])
        version, changes = self.textDocuments[uri].change(newText)

        self.rpc.notify("textDocument/didChange", {
            "textDocument": {
                "uri": uri,
                "version": version
                },
            "contentChanges": changes
            })

    @neovim.function("LanguageClient_textDocument_didSave")
    def textDocument_didSave(self, args: List) -> None:
        # {uri?: str}
        if not self.alive(warn=False):
            return
        logger.info("textDocument/didSave")

        uri, = self.getArgs(args, ["uri"])

        self.rpc.notify("textDocument/didSave", {
            "textDocument": {
                "uri": uri
                }
            })

    # FIXME: python infinite loop after this call.
    @neovim.function("LanguageClient_exit")
    def exit(self, args: List) -> None:
        # {uri?: str}
        if not self.alive():
            return
        logger.info("exit")

        self.rpc.notify("exit", {})

    def textDocument_publishDiagnostics(self, params) -> None:
        for diagnostic in params['diagnostics']:
            message = diagnostic['message'].replace("\n", ". ")
            self.asyncEcho(message)

    def handleRequestOrNotification(self, message) -> None:
        method = message['method'].replace('/', '_')
        if hasattr(self, method):
            try:
                getattr(self, method)(message['params'])
            except:
                logger.exception("Exception in handle.")
        else:
            logger.warn('no handler implemented for ' + method)

    def handleError(self, message) -> None:
        self.asyncEcho(json.dumps(message))
<|endoftext|>


<commit_before># -*- encoding: utf-8 -*-
#################################################################################
#                                                                               #
#    sale_automatic_workflow for OpenERP                                        #
#    Copyright (C) 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com>   #
#                                                                               #
#    This program is free software: you can redistribute it and/or modify       #
#    it under the terms of the GNU Affero General Public License as             #
#    published by the Free Software Foundation, either version 3 of the         #
#    License, or (at your option) any later version.                            #
#                                                                               #
#    This program is distributed in the hope that it will be useful,            #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of             #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              #
#    GNU Affero General Public License for more details.                        #
#                                                                               #
#    You should have received a copy of the GNU Affero General Public License   #
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.      #
#                                                                               #
#################################################################################

from openerp.osv import orm, fields

class sale_workflow_process(orm.Model):
    _name = "sale.workflow.process"
    _description = "sale workflow process"

    _columns = {
        'name': fields.char('Name', size=64),
        'picking_policy': fields.selection([('direct', 'Partial Delivery'),
                                            ('one', 'Complete Delivery')],
                                           string='Packing Policy'),
        'order_policy': fields.selection([
            ('prepaid', 'Payment Before Delivery'),
            ('manual', 'Shipping & Manual Invoice'),
            ('postpaid', 'Invoice on Order After Delivery'),
            ('picking', 'Invoice from the Packing'),
        ], 'Shipping Policy'),
        'invoice_quantity': fields.selection([('order', 'Ordered Quantities'),
                                              ('procurement', 'Shipped Quantities')],
                                             string='Invoice on'),
        'validate_order': fields.selection([('always', 'Always'),
                                            ('if_paid', 'Only If Paid'),
                                            ('never', 'Never')],
                                           'Validate Order'),
        'create_invoice': fields.boolean('Create Invoice'),
        'validate_invoice': fields.boolean('Validate Invoice'),
        'validate_picking': fields.boolean('Validate Picking'),
        # TODO not implemented actually
        # 'validate_manufactoring_order': fields.boolean('Validate Manufactoring Order'),
        'days_before_order_cancel': fields.integer(  # XXX part of the workflow?
            'Days Delay before Cancel',
            help='number of days before an unpaid order will be cancelled '
                 'at next status update from Magento'),
        'invoice_date_is_order_date': fields.boolean(
            'Force Invoice Date',
            help="When checked, the invoice date will be "
                 "the same than the order's date"),
    }

    _defaults = {
        'picking_policy': 'direct',
        'order_policy': 'manual',
        'invoice_quantity': 'order',
        'validate_invoice': False,
        'days_before_order_cancel': 30,
    }
<commit_msg>[IMP] sale_automatic_workflow: use the same words than openerp for order_policy, remove the 'postpaid' removed in openerp<commit_after># -*- encoding: utf-8 -*-
#################################################################################
#                                                                               #
#    sale_automatic_workflow for OpenERP                                        #
#    Copyright (C) 2011 Akretion Sébastien BEAU <sebastien.beau@akretion.com>   #
#                                                                               #
#    This program is free software: you can redistribute it and/or modify       #
#    it under the terms of the GNU Affero General Public License as             #
#    published by the Free Software Foundation, either version 3 of the         #
#    License, or (at your option) any later version.                            #
#                                                                               #
#    This program is distributed in the hope that it will be useful,            #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of             #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              #
#    GNU Affero General Public License for more details.                        #
#                                                                               #
#    You should have received a copy of the GNU Affero General Public License   #
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.      #
#                                                                               #
#################################################################################

from openerp.osv import orm, fields

class sale_workflow_process(orm.Model):
    _name = "sale.workflow.process"
    _description = "sale workflow process"

    _columns = {
        'name': fields.char('Name', size=64),
        'picking_policy': fields.selection([('direct', 'Partial Delivery'),
                                            ('one', 'Complete Delivery')],
                                           string='Packing Policy'),
        'order_policy': fields.selection([
            ('prepaid', 'Before Delivery'),
            ('manual', 'On Demand'),
            # https://bugs.launchpad.net/openobject-addons/+bug/1160835
            # ('postpaid', 'Invoice on Order After Delivery'),
            ('picking', 'On Delivery Order'),
        ], 'Shipping Policy'),
        'invoice_quantity': fields.selection([('order', 'Ordered Quantities'),
                                              ('procurement', 'Shipped Quantities')],
                                             string='Invoice on'),
        'validate_order': fields.selection([('always', 'Always'),
                                            ('if_paid', 'Only If Paid'),
                                            ('never', 'Never')],
                                           'Validate Order'),
        'create_invoice': fields.boolean('Create Invoice'),
        'validate_invoice': fields.boolean('Validate Invoice'),
        'validate_picking': fields.boolean('Validate Picking'),
        # TODO not implemented actually
        # 'validate_manufactoring_order': fields.boolean('Validate Manufactoring Order'),
        'days_before_order_cancel': fields.integer(  # XXX part of the workflow?
            'Days Delay before Cancel',
            help='number of days before an unpaid order will be cancelled '
                 'at next status update from Magento'),
        'invoice_date_is_order_date': fields.boolean(
            'Force Invoice Date',
            help="When checked, the invoice date will be "
                 "the same than the order's date"),
    }

    _defaults = {
        'picking_policy': 'direct',
        'order_policy': 'manual',
        'invoice_quantity': 'order',
        'validate_invoice': False,
        'days_before_order_cancel': 30,
    }
<|endoftext|>


<commit_before>#
# Copyright 2012 John Whitlock
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__version__ = '0.2.4'
<commit_msg>Version bump 0.2.5<commit_after>#
# Copyright 2012 John Whitlock
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__version__ = '0.2.5'
<|endoftext|>


<commit_before>def main():
    import argparse
    from unittest import TestProgram
    from multitest import MultiprocessTestRunner
    from multitest.runner import DEFAULT_TIMEOUT, DEFAULT_WORKERS

    prog = 'python -m multitest'
    parser = argparse.ArgumentParser(
        prog=prog,
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description='Accepts the same arguments as the unittest program with the additions below.\n'
                    'see: python -m unittest --help',
        epilog='examples:\n'
               '%(prog)s test_module --multitest-timeout 60          - run tests from test_module with 60s timeout\n'
               '%(prog)s discover --multitest-workers 8 -s test    - run tests from test directory using 8 workers'
               % {'prog': prog})
    parser.add_argument('--multitest-workers', type=int, default=DEFAULT_WORKERS, dest='workers',
                        help='Number of worker process (default %s)' % DEFAULT_WORKERS)
    parser.add_argument('--multitest-timeout', type=int, default=DEFAULT_TIMEOUT, dest='timeout',
                        help='Test timeout in seconds (default %s)' % DEFAULT_TIMEOUT)
    parsed = parser.parse_known_args()[0]

    class _MultiTestProgram(TestProgram):
        USAGE = ''

    class _MultiprocessTestRunner(MultiprocessTestRunner):
        def __init__(self, *args, **kwargs):
            kwargs['workers'] = parsed.workers
            kwargs['timeout'] = parsed.timeout
            super(_MultiprocessTestRunner, self).__init__(*args, **kwargs)

    _MultiTestProgram(module=None, testRunner=_MultiprocessTestRunner)

if __name__ == '__main__':
    main()
<commit_msg>Edge cases.<commit_after>def main():
    import argparse
    import sys
    from unittest import TestProgram
    from multitest import MultiprocessTestRunner
    from multitest.runner import DEFAULT_TIMEOUT, DEFAULT_WORKERS

    sys.argv[0] = 'python -m multitest'
    parser = argparse.ArgumentParser(
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description='Accepts the same arguments as the unittest program with the additions below.\n'
                    'see: python -m unittest --help',
        epilog='examples:\n'
               '%(prog)s test_module --multitest-timeout 60          - run tests from test_module with 60s timeout\n'
               '%(prog)s discover --multitest-workers 8 -s test    - run tests from test directory using 8 workers'
               % {'prog': sys.argv[0]})
    parser.add_argument('--multitest-workers', type=int, default=DEFAULT_WORKERS, dest='workers',
                        help='Number of worker process (default %s)' % DEFAULT_WORKERS)
    parser.add_argument('--multitest-timeout', type=int, default=DEFAULT_TIMEOUT, dest='timeout',
                        help='Test timeout in seconds (default %s)' % DEFAULT_TIMEOUT)
    parsed = parser.parse_known_args()[0]

    def remove_arg(arg, n):
        try:
            idx = sys.argv.index(arg)
            for _ in xrange(n):
                sys.argv.pop(idx)
        except ValueError:
            pass

    remove_arg('--multitest-workers', 2)
    remove_arg('--multitest-timeout', 2)

    class _MultiTestProgram(TestProgram):
        USAGE = ''

    class _MultiprocessTestRunner(MultiprocessTestRunner):
        def __init__(self, *args, **kwargs):
            kwargs['workers'] = parsed.workers
            kwargs['timeout'] = parsed.timeout
            super(_MultiprocessTestRunner, self).__init__(*args, **kwargs)

    _MultiTestProgram(module=None, testRunner=_MultiprocessTestRunner)

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>from django.contrib import admin
from django.contrib.admin import SimpleListFilter
from django.contrib.comments.models import Comment
from django.contrib.comments.admin import CommentsAdmin as DjangoCommentsAdmin
from django.core.urlresolvers import reverse
from django.template import defaultfilters
from moderator import constants
from moderator.models import CannedReply, CommentReply

class ClassificationListFilter(SimpleListFilter):
    title = "classification"
    parameter_name = "classification"

    def lookups(self, request, model_admin):
        return constants.CLASS_CHOICES

    def queryset(self, request, queryset):
        """
        Returns queryset filtered on categories and primary_category.
        """
        if self.value():
            return queryset.filter(classifiedcomment__cls=self.value())

class CommentReplyInline(admin.StackedInline):
    extra = 0
    exclude = ['reply_comment', ]
    model = CommentReply
    fk_name = 'replied_to_comment'

class CommentAdmin(DjangoCommentsAdmin):
    list_display = ('comment_text', 'content', 'user', 'submit_date',
                    'classification', 'moderator_replied',)
    list_filter = ('submit_date', ClassificationListFilter)
    inlines = [
        CommentReplyInline,
    ]

    def content(self, obj):
        content = obj.content_object
        content_type = obj.content_type
        url = reverse('admin:%s_%s_change' % (content_type.app_label,
                                              content_type.model),
                      args=(content.id,))

        return '%s' % (url, content)
    content.allow_tags = True

    def moderator_replied(self, obj):
        return bool(obj.replied_to_comment_set.all())
    moderator_replied.boolean = True

    def comment_text(self, obj):
        return defaultfilters.linebreaks(obj.comment)
    comment_text.short_description = 'Comment'
    comment_text.allow_tags = True

    def classification(self, obj):
        return obj.classifiedcomment_set.get().cls.title()

    def queryset(self, request):
        qs = super(CommentAdmin, self).queryset(request)
        return qs.filter(reply_comment_set__isnull=True)

admin.site.register(CannedReply)
admin.site.unregister(Comment)
admin.site.register(Comment, CommentAdmin)
<commit_msg>now allows for classification inline<commit_after>from django.contrib import admin
from django.contrib.admin import SimpleListFilter
from django.contrib.comments.models import Comment
from django.contrib.comments.admin import CommentsAdmin as DjangoCommentsAdmin
from django.core.urlresolvers import reverse
from django.forms.models import BaseInlineFormSet
from django.template import defaultfilters
from moderator import constants
from moderator.models import CannedReply, ClassifiedComment, CommentReply
from moderator import utils

class ClassificationListFilter(SimpleListFilter):
    title = "classification"
    parameter_name = "classification"

    def lookups(self, request, model_admin):
        return constants.CLASS_CHOICES

    def queryset(self, request, queryset):
        """
        Returns queryset filtered on categories and primary_category.
        """
        if self.value():
            return queryset.filter(classifiedcomment__cls=self.value())

class CommentReplyInline(admin.StackedInline):
    extra = 0
    exclude = ['reply_comment', ]
    model = CommentReply
    fk_name = 'replied_to_comment'

class ClassifiedCommentInlineFormSet(BaseInlineFormSet):
    def save_existing(self, form, instance, commit=True):
        utils.classify_comment(instance.comment, instance.cls)

class ClassifiedCommentInline(admin.StackedInline):
    formset = ClassifiedCommentInlineFormSet
    extra = 0
    model = ClassifiedComment

    def has_add_permission(self, request):
        return False

class CommentAdmin(DjangoCommentsAdmin):
    list_display = ('comment_text', 'content', 'user', 'submit_date',
                    'classification', 'moderator_replied',)
    list_filter = ('submit_date', ClassificationListFilter)
    inlines = [
        ClassifiedCommentInline,
        CommentReplyInline,
    ]

    def content(self, obj):
        content = obj.content_object
        content_type = obj.content_type
        url = reverse('admin:%s_%s_change' % (content_type.app_label,
                                              content_type.model),
                      args=(content.id,))

        return '%s' % (url, content)
    content.allow_tags = True

    def moderator_replied(self, obj):
        return bool(obj.replied_to_comment_set.all())
    moderator_replied.boolean = True

    def comment_text(self, obj):
        return defaultfilters.linebreaks(obj.comment)
    comment_text.short_description = 'Comment'
    comment_text.allow_tags = True

    def classification(self, obj):
        try:
            cls = obj.classifiedcomment_set.get().cls
        except ClassifiedComment.DoesNotExist:
            cls = utils.classify_comment(obj).cls
        return cls.title()
        return obj.classifiedcomment_set.get().cls.title()

    def queryset(self, request):
        qs = super(CommentAdmin, self).queryset(request)
        return qs.filter(reply_comment_set__isnull=True)

admin.site.register(CannedReply)
admin.site.unregister(Comment)
admin.site.register(Comment, CommentAdmin)
<|endoftext|>


<commit_before>suite = {
    "mxversion" : "5.70.2",
    "name" : "java-llvm-ir-builder",
    "versionConflictResolution" : "latest",

    "imports" : {
        "suites" : [
            {
                "name" : "sulong",
                "version" : "be6e1e731747b8fe36392435eaf7b3f340261c94",
                "urls" : [
                    {
                        "url" : "https://github.com/graalvm/sulong",
                        "kind" : "git"
                    },
                ]
            },
        ],
    },

    "javac.lint.overrides" : "none",

    "projects" : {
        "at.pointhi.irbuilder.irwriter" : {
            "subDir" : "projects",
            "sourceDirs" : ["src"],
            "dependencies" : [
                "sulong:SULONG",
            ],
            "checkstyle" : "at.pointhi.irbuilder.irwriter",
            "javaCompliance" : "1.8",
            "license" : "BSD-new",
        },

        "at.pointhi.irbuilder.test": {
            "subDir": "projects",
            "sourceDirs": ["src"],
            "dependencies": [
                "at.pointhi.irbuilder.irwriter",
                "sulong:SULONG",
                "sulong:SULONG_TEST",
                "mx:JUNIT",
            ],
            "checkstyle": "at.pointhi.irbuilder.irwriter",
            "javaCompliance": "1.8",
            "license": "BSD-new",
        },
    },

    "distributions" : {
        "IRWRITER" : {
            "path" : "build/irwriter.jar",
            "subDir" : "graal",
            "sourcesPath" : "build/irbuilder.src.zip",
            "mainClass" : "at.pointhi.irbuilder.irwriter.SourceParser",
            "dependencies" : [
                "at.pointhi.irbuilder.irwriter"
            ],
            "distDependencies" : [
                "sulong:SULONG",
            ]
        },

        "IRWRITER_TEST" : {
            "path" : "build/irwriter_test.jar",
            "subDir" : "graal",
            "sourcesPath" : "build/irwriter_test.src.zip",
            "dependencies" : [
                "at.pointhi.irbuilder.test"
            ],
            "exclude" : [
                "mx:JUNIT"
            ],
            "distDependencies" : [
                "IRWRITER",
                "sulong:SULONG",
                "sulong:SULONG_TEST",
            ]
        },
    }
}
<commit_msg>Use personal repository for sulong<commit_after>suite = {
    "mxversion" : "5.70.2",
    "name" : "java-llvm-ir-builder",
    "versionConflictResolution" : "latest",

    "imports" : {
        "suites" : [
            {
                "name" : "sulong",
                "version" : "a9b3b4e6636ee830317e5106f2c1a2db7144d5ca",
                "urls" : [
                    {
                        "url" : "https://github.com/pointhi/sulong",
                        "kind" : "git"
                    },
                ]
            },
        ],
    },

    "javac.lint.overrides" : "none",

    "projects" : {
        "at.pointhi.irbuilder.irwriter" : {
            "subDir" : "projects",
            "sourceDirs" : ["src"],
            "dependencies" : [
                "sulong:SULONG",
            ],
            "checkstyle" : "at.pointhi.irbuilder.irwriter",
            "javaCompliance" : "1.8",
            "license" : "BSD-new",
        },

        "at.pointhi.irbuilder.test": {
            "subDir": "projects",
            "sourceDirs": ["src"],
            "dependencies": [
                "at.pointhi.irbuilder.irwriter",
                "sulong:SULONG",
                "sulong:SULONG_TEST",
                "mx:JUNIT",
            ],
            "checkstyle": "at.pointhi.irbuilder.irwriter",
            "javaCompliance": "1.8",
            "license": "BSD-new",
        },
    },

    "distributions" : {
        "IRWRITER" : {
            "path" : "build/irwriter.jar",
            "subDir" : "graal",
            "sourcesPath" : "build/irbuilder.src.zip",
            "mainClass" : "at.pointhi.irbuilder.irwriter.SourceParser",
            "dependencies" : [
                "at.pointhi.irbuilder.irwriter"
            ],
            "distDependencies" : [
                "sulong:SULONG",
            ]
        },

        "IRWRITER_TEST" : {
            "path" : "build/irwriter_test.jar",
            "subDir" : "graal",
            "sourcesPath" : "build/irwriter_test.src.zip",
            "dependencies" : [
                "at.pointhi.irbuilder.test"
            ],
            "exclude" : [
                "mx:JUNIT"
            ],
            "distDependencies" : [
                "IRWRITER",
                "sulong:SULONG",
                "sulong:SULONG_TEST",
            ]
        },
    }
}
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
###############################################################################
#
#    Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
#    Original module for stock.move from:
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################

import os
import sys
import logging
import openerp
from openerp import netsvc
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv, expression, orm
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from openerp import SUPERUSER_ID
from openerp import tools
from openerp.tools.translate import _
from openerp.tools.float_utils import float_round as round
from openerp.tools import (DEFAULT_SERVER_DATE_FORMAT,
    DEFAULT_SERVER_DATETIME_FORMAT,
    DATETIME_FORMATS_MAP,
    float_compare)

_logger = logging.getLogger(__name__)

class product_product(osv.osv):
    _inherit = 'product.product'

    _order = 'default_code, name'

    # Override sale_stock procurement procedure!
    def need_procurement(self, cr, uid, ids, context=None):
        return False

class StockPicking(orm.Model):
    ''' Add alternative method for picking creation
    '''
    _inherit = 'stock.picking'

    # DDT button:
    def link_sale_id(self, cr, uid, ids, context=None):
        ''' Link sale_id depend on origin fields
        '''
        order_pool = self.pool.get('sale.order')

        origin = self.browse(cr, uid, ids, context=context)[0].origin
        sale_ids = order_pool.search(cr, uid, [
            ('name', '=', origin)], context=context)
        if sale_ids and len(sale_ids) == 1:
            self.write(cr, uid, ids, {
                'sale_id': sale_ids[0],
                }, context=context)
        return True

    def open_ddt_report(self, cr, uid, ids, context=None):
        ''' Open DDT form if present
        '''
        assert len(ids) == 1, 'Only one picking!'

        pick_proxy = self.browse(cr, uid, ids, context=context)[0]
        if not pick_proxy.ddt_id:
            return {} # raise error (never pass here!)

        ctx = context.copy()
        ctx.update({
            #'active_model': 'stock.picking',
            #'params': {},
            #'search_disable_custom_filters': True,
            'active_ids': [pick_proxy.ddt_id.id],
            'active_id': pick_proxy.ddt_id.id,
            })
        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'custom_ddt_report',
            #'datas': datas,
            'context': ctx,
            }
        #return self.pool.get('stock.ddt').open_ddt_report(
        #    cr, uid, [pick_proxy.ddt_id.id], context=context)

    def open_ddt_form(self, cr, uid, ids, context=None):
        ''' Open DDT report directly if present
        '''
        assert len(ids) == 1, 'Only one picking!'

        pick_proxy = self.browse(cr, uid, ids, context=context)[0]
        if not pick_proxy.ddt_id:
            return {} # TODO error?

        return {
            'name': 'DdT',
            'view_type': 'form',
            'view_mode': 'form,tree',
            'res_model': 'stock.ddt',
            'res_id': pick_proxy.ddt_id.id,
            'view_id': False,
            #'views': [(form_id, 'form'), (tree_id, 'tree')],
            'type': 'ir.actions.act_window',
            }

    # Invoice button:
    def open_invoice_report(self, cr, uid, ids, context=None):
        ''' Open DDT form if present
        '''
        assert len(ids) == 1, 'Only one picking!'

        pick_proxy = self.browse(cr, uid, ids, context=context)[0]
        if not pick_proxy.invoice_id:
            return {} # raise error (never pass here!)

        ctx = context.copy()
        ctx.update({
            'active_ids': [pick_proxy.invoice_id.id],
            'active_id': pick_proxy.invoice_id.id,
            })
        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'custom_mx_invoice_report',
            'context': ctx,
            }

    def open_invoice_form(self, cr, uid, ids, context=None):
        ''' Open DDT report directly if present
        '''
        assert len(ids) == 1, 'Only one picking!'

        # TODO view: account.invoice_form
        pick_proxy = self.browse(cr, uid, ids, context=context)[0]
        if not pick_proxy.invoice_id:
            return {} # TODO error?

        return {
            'name': 'DdT',
            'view_type': 'form',
            'view_mode': 'form,tree',
            'res_model': 'account.invoice',
            'res_id': pick_proxy.invoice_id.id,
            'view_id': False,
            #'views': [(form_id, 'form'), (tree_id, 'tree')],
            'type': 'ir.actions.act_window',
            }

    _columns = {
        'sale_id': fields.many2one('sale.order', 'Sale order'),
        }

class ResPartner(orm.Model):
    ''' Extra field for partner
    '''
    _inherit = 'res.partner'

    _columns = {
        'incoterm_id':fields.many2one(
            'stock.incoterms', 'Default incoterm', ondelete='set null'),
        }

class SaleOrder(orm.Model):
    ''' Extra field for order
    '''
    _inherit = 'sale.order'

    # -------------------------------------------------------------------------
    #                                  Button events:
    # -------------------------------------------------------------------------
    def button_force_all_deadline_date(self, cr, uid, ids, context=None):
        ''' Force sale order date on all lines
        '''
        order_proxy = self.browse(cr, uid, ids, context=context)[0]

        line_ids = [line.id for line in order_proxy.order_line]
        self.pool.get('sale.order.line').write(cr, uid, line_ids, {
            'date_deadline': order_proxy.date_deadline,
            }, context=context)

        return True

    # -------------------------------------------------------------------------
    #                                  Override:
    # -------------------------------------------------------------------------
    # onchange:
    def onchange_partner_id(self, cr, uid, ids, partner_id, context=None):
        ''' Override standard procedure for add extra account field:
        '''
        # Call original procedure:
        res = super(SaleOrder, self).onchange_partner_id(
            cr, uid, ids, partner_id, context=context)
        if 'value' not in res:
            res['value'] = {}

        # Append extra value:
        if not partner_id: # reset:
            res['value'].update({
                'incoterm': False,
                'carrier_id': False,
                'carriage_condition_id': False,
                'goods_description_id': False,
                'transportation_reason_id': False,
                # TODO remove:
                'payment_term_id': False,
                'payment_term': False,
                'bank_account_id': False,
                })
            return res

        partner_pool = self.pool.get('res.partner')
        partner_proxy = partner_pool.browse(cr, uid, partner_id,
            context=context)

        res['value'].update({
            'incoterm': partner_proxy.incoterm_id.id,
            'carrier_id': partner_proxy.default_carrier_id.id,
            'carriage_condition_id': partner_proxy.carriage_condition_id.id,
            'goods_description_id': partner_proxy.goods_description_id.id,
            'transportation_reason_id':
                partner_proxy.transportation_reason_id.id,

            # TODO remove:
            'payment_term_id': partner_proxy.property_payment_term.id,
            'payment_term': partner_proxy.property_payment_term.id,
            })
        # Set default account for partner
        if partner_proxy.bank_ids:
            res['value']['bank_account_id'] = partner_proxy.bank_ids[0].id

        return res

    _columns = {
        # QUOTATION:
        'date_valid': fields.date('Validity date',
            help='Max date for validity of offer'),

        # ORDER:
        'date_confirm': fields.date('Date confirm',
            help='Order confirm by the customer'), # TODO yet present in order?
        'date_deadline': fields.date('Order deadline',
            help='Delivery term for customer'),
        # Fixed by delivery team:
        'date_booked': fields.date('Booked date',
            help='Delivery was booked and fixed!'),
        'date_booked_confirmed': fields.boolean('Booked confirmed',
            help='Booked confirmed for this date'),
        'date_delivery': fields.date('Load / Availability',
            help='For ex works is availability date, other clause is '
                'load date'),
        'date_delivery_confirmed': fields.boolean('Delivery confirmed',
            help='Delivery confirmed, product available '
                '(2 cases depend on incoterms)'),
        # TODO used?
        #'date_previous_deadline': fields.date(
        #    'Previous deadline',
        #    help="If during sync deadline is modified this field contain old "
        #        "value before update"),
        # TODO remove:
        # Replaced with date_booked!!!
        #'date_delivery': fields.date('Delivery',
        #    help='Contain delivery date, when present production plan work '
        #        'with this instead of deadline value, if forced production '
        #        'cannot be moved'),

        # Account extra field saved in sale.order:
        'default_carrier_id': fields.many2one('delivery.carrier', 'Carrier',
            domain=[('is_vector', '=', True)]),
        'carriage_condition_id': fields.many2one(
            'stock.picking.carriage_condition', 'Carriage condition'),
        'goods_description_id': fields.many2one(
            'stock.picking.goods_description', 'Goods description'),
        'transportation_reason_id': fields.many2one(
            'stock.picking.transportation_reason', 'Transportation reason'),
        # TODO remove:
        'payment_term_id': fields.many2one(
            'account.payment.term', 'Payment term'),
        'bank_account_id': fields.many2one(
            'res.partner.bank', 'Partner bank account'),
        'bank_account_company_id': fields.many2one(
            'res.partner.bank', 'Company bank account'),

        # Alert:
        'uncovered_payment': fields.boolean('Uncovered payment'),
        'uncovered_alert': fields.char('Alert', size=64, readonly=True),

        # TODO not used picking_ids!!!
        'stock_picking_ids': fields.one2many(
            'stock.picking', 'sale_id', 'Delivery'),
        }

    _defaults = {
        'uncovered_alert': lambda *x: 'Alert: Uncovered payment!!!',
        'date_valid': lambda *x: (
            datetime.now() + timedelta(days=15)).strftime(
                DEFAULT_SERVER_DATE_FORMAT),
        }

class SaleOrderLine(orm.Model):
    ''' Extra field for order line
    '''
    _inherit = 'sale.order.line'

    # ----------------
    # Function fields:
    # ----------------
    def _function_get_delivered(self, cr, uid, ids, fields, args,
            context=None):
        ''' Fields function for calculate delivered elements in picking orders
        '''
        res = {}
        move_pool = self.pool.get('stock.move')

        for line in self.browse(cr, uid, ids, context=context):
            res[line.id] = 0.0
            move_ids = move_pool.search(cr, uid, [
                ('sale_line_id', '=', line.id),
                ], context=context)
            for move in move_pool.browse(cr, uid, move_ids, context=context):
                # TODO jump picking for virtual count!!!!!!!!!!!!!!!!!!!!!!!!!!
                #if move.picking_id.ddt_number: # was marked as DDT
                # TODO check UOM!!! for
                res[line.id] += move.product_uos_qty
        return res

    _columns = {
        'gr_weight': fields.float('Gross weight'),
        'colls': fields.integer('Colls'),
        #states={'draft': [('readonly', False)]}),

        'date_deadline': fields.date('Deadline'),
        'date_delivery': fields.related( # TODO use booked!!!!
            'order_id', 'date_delivery', type='date', string='Date delivery'),

        'alias_id':fields.many2one(
            'product.product', 'Marked as product', ondelete='set null'),

        'delivered_qty': fields.function(
            _function_get_delivered, method=True, type='float', readonly=True,
            string='Delivered', store=False,
            help='Quantity delivered with DDT out'),
        # TODO add to delivery qty

        # Order ref:
        'client_order_ref': fields.related('order_id',
            'client_order_ref', type='char', string='Client order ref.'),
        }

    _defaults = {
        'colls': lambda *x: 1,
        }

class StockMove(orm.Model):
    ''' Extra field for order line
    '''
    _inherit = 'stock.move'

    _columns = {
        'sale_line_id': fields.many2one('sale.order.line', 'Sale line'),
        }
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<commit_msg>relink button for more picking not only one<commit_after># -*- coding: utf-8 -*-
###############################################################################
#
#    Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
#    Original module for stock.move from:
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################

import os
import sys
import logging
import openerp
from openerp import netsvc
import openerp.addons.decimal_precision as dp
from openerp.osv import fields, osv, expression, orm
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from openerp import SUPERUSER_ID
from openerp import tools
from openerp.tools.translate import _
from openerp.tools.float_utils import float_round as round
from openerp.tools import (DEFAULT_SERVER_DATE_FORMAT,
    DEFAULT_SERVER_DATETIME_FORMAT,
    DATETIME_FORMATS_MAP,
    float_compare)

_logger = logging.getLogger(__name__)

class product_product(osv.osv):
    _inherit = 'product.product'

    _order = 'default_code, name'

    # Override sale_stock procurement procedure!
    def need_procurement(self, cr, uid, ids, context=None):
        return False

class StockPicking(orm.Model):
    ''' Add alternative method for picking creation
    '''
    _inherit = 'stock.picking'

    # Relink button:
    def link_sale_id(self, cr, uid, ids, context=None):
        ''' Link sale_id depend on origin fields (multi ids)
        '''
        order_pool = self.pool.get('sale.order')
        for picking in self.browse(cr, uid, ids, context=context):
            origin = picking.origin
            sale_ids = order_pool.search(cr, uid, [
                ('name', '=', origin)], context=context)
            if sale_ids and len(sale_ids) == 1:
                self.write(cr, uid, ids, {
                    'sale_id': sale_ids[0],
                    }, context=context)
        return True

    # DDT button:
    def open_ddt_report(self, cr, uid, ids, context=None):
        ''' Open DDT form if present
        '''
        assert len(ids) == 1, 'Only one picking!'

        pick_proxy = self.browse(cr, uid, ids, context=context)[0]
        if not pick_proxy.ddt_id:
            return {} # raise error (never pass here!)

        ctx = context.copy()
        ctx.update({
            #'active_model': 'stock.picking',
            #'params': {},
            #'search_disable_custom_filters': True,
            'active_ids': [pick_proxy.ddt_id.id],
            'active_id': pick_proxy.ddt_id.id,
            })
        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'custom_ddt_report',
            #'datas': datas,
            'context': ctx,
            }
        #return self.pool.get('stock.ddt').open_ddt_report(
        #    cr, uid, [pick_proxy.ddt_id.id], context=context)

    def open_ddt_form(self, cr, uid, ids, context=None):
        ''' Open DDT report directly if present
        '''
        assert len(ids) == 1, 'Only one picking!'

        pick_proxy = self.browse(cr, uid, ids, context=context)[0]
        if not pick_proxy.ddt_id:
            return {} # TODO error?

        return {
            'name': 'DdT',
            'view_type': 'form',
            'view_mode': 'form,tree',
            'res_model': 'stock.ddt',
            'res_id': pick_proxy.ddt_id.id,
            'view_id': False,
            #'views': [(form_id, 'form'), (tree_id, 'tree')],
            'type': 'ir.actions.act_window',
            }

    # Invoice button:
    def open_invoice_report(self, cr, uid, ids, context=None):
        ''' Open DDT form if present
        '''
        assert len(ids) == 1, 'Only one picking!'

        pick_proxy = self.browse(cr, uid, ids, context=context)[0]
        if not pick_proxy.invoice_id:
            return {} # raise error (never pass here!)

        ctx = context.copy()
        ctx.update({
            'active_ids': [pick_proxy.invoice_id.id],
            'active_id': pick_proxy.invoice_id.id,
            })
        return {
            'type': 'ir.actions.report.xml',
            'report_name': 'custom_mx_invoice_report',
            'context': ctx,
            }

    def open_invoice_form(self, cr, uid, ids, context=None):
        ''' Open DDT report directly if present
        '''
        assert len(ids) == 1, 'Only one picking!'

        # TODO view: account.invoice_form
        pick_proxy = self.browse(cr, uid, ids, context=context)[0]
        if not pick_proxy.invoice_id:
            return {} # TODO error?

        return {
            'name': 'DdT',
            'view_type': 'form',
            'view_mode': 'form,tree',
            'res_model': 'account.invoice',
            'res_id': pick_proxy.invoice_id.id,
            'view_id': False,
            #'views': [(form_id, 'form'), (tree_id, 'tree')],
            'type': 'ir.actions.act_window',
            }

    _columns = {
        'sale_id': fields.many2one('sale.order', 'Sale order'),
        }

class ResPartner(orm.Model):
    ''' Extra field for partner
    '''
    _inherit = 'res.partner'

    _columns = {
        'incoterm_id':fields.many2one(
            'stock.incoterms', 'Default incoterm', ondelete='set null'),
        }

class SaleOrder(orm.Model):
    ''' Extra field for order
    '''
    _inherit = 'sale.order'

    # -------------------------------------------------------------------------
    #                                  Button events:
    # -------------------------------------------------------------------------
    def button_force_all_deadline_date(self, cr, uid, ids, context=None):
        ''' Force sale order date on all lines
        '''
        order_proxy = self.browse(cr, uid, ids, context=context)[0]

        line_ids = [line.id for line in order_proxy.order_line]
        self.pool.get('sale.order.line').write(cr, uid, line_ids, {
            'date_deadline': order_proxy.date_deadline,
            }, context=context)

        return True

    # -------------------------------------------------------------------------
    #                                  Override:
    # -------------------------------------------------------------------------
    # onchange:
    def onchange_partner_id(self, cr, uid, ids, partner_id, context=None):
        ''' Override standard procedure for add extra account field:
        '''
        # Call original procedure:
        res = super(SaleOrder, self).onchange_partner_id(
            cr, uid, ids, partner_id, context=context)
        if 'value' not in res:
            res['value'] = {}

        # Append extra value:
        if not partner_id: # reset:
            res['value'].update({
                'incoterm': False,
                'carrier_id': False,
                'carriage_condition_id': False,
                'goods_description_id': False,
                'transportation_reason_id': False,
                # TODO remove:
                'payment_term_id': False,
                'payment_term': False,
                'bank_account_id': False,
                })
            return res

        partner_pool = self.pool.get('res.partner')
        partner_proxy = partner_pool.browse(cr, uid, partner_id,
            context=context)

        res['value'].update({
            'incoterm': partner_proxy.incoterm_id.id,
            'carrier_id': partner_proxy.default_carrier_id.id,
            'carriage_condition_id': partner_proxy.carriage_condition_id.id,
            'goods_description_id': partner_proxy.goods_description_id.id,
            'transportation_reason_id':
                partner_proxy.transportation_reason_id.id,

            # TODO remove:
            'payment_term_id': partner_proxy.property_payment_term.id,
            'payment_term': partner_proxy.property_payment_term.id,
            })
        # Set default account for partner
        if partner_proxy.bank_ids:
            res['value']['bank_account_id'] = partner_proxy.bank_ids[0].id

        return res

    _columns = {
        # QUOTATION:
        'date_valid': fields.date('Validity date',
            help='Max date for validity of offer'),

        # ORDER:
        'date_confirm': fields.date('Date confirm',
            help='Order confirm by the customer'), # TODO yet present in order?
        'date_deadline': fields.date('Order deadline',
            help='Delivery term for customer'),
        # Fixed by delivery team:
        'date_booked': fields.date('Booked date',
            help='Delivery was booked and fixed!'),
        'date_booked_confirmed': fields.boolean('Booked confirmed',
            help='Booked confirmed for this date'),
        'date_delivery': fields.date('Load / Availability',
            help='For ex works is availability date, other clause is '
                'load date'),
        'date_delivery_confirmed': fields.boolean('Delivery confirmed',
            help='Delivery confirmed, product available '
                '(2 cases depend on incoterms)'),
        # TODO used?
        #'date_previous_deadline': fields.date(
        #    'Previous deadline',
        #    help="If during sync deadline is modified this field contain old "
        #        "value before update"),
        # TODO remove:
        # Replaced with date_booked!!!
        #'date_delivery': fields.date('Delivery',
        #    help='Contain delivery date, when present production plan work '
        #        'with this instead of deadline value, if forced production '
        #        'cannot be moved'),

        # Account extra field saved in sale.order:
        'default_carrier_id': fields.many2one('delivery.carrier', 'Carrier',
            domain=[('is_vector', '=', True)]),
        'carriage_condition_id': fields.many2one(
            'stock.picking.carriage_condition', 'Carriage condition'),
        'goods_description_id': fields.many2one(
            'stock.picking.goods_description', 'Goods description'),
        'transportation_reason_id': fields.many2one(
            'stock.picking.transportation_reason', 'Transportation reason'),
        # TODO remove:
        'payment_term_id': fields.many2one(
            'account.payment.term', 'Payment term'),
        'bank_account_id': fields.many2one(
            'res.partner.bank', 'Partner bank account'),
        'bank_account_company_id': fields.many2one(
            'res.partner.bank', 'Company bank account'),

        # Alert:
        'uncovered_payment': fields.boolean('Uncovered payment'),
        'uncovered_alert': fields.char('Alert', size=64, readonly=True),

        # TODO not used picking_ids!!!
        'stock_picking_ids': fields.one2many(
            'stock.picking', 'sale_id', 'Delivery'),
        }

    _defaults = {
        'uncovered_alert': lambda *x: 'Alert: Uncovered payment!!!',
        'date_valid': lambda *x: (
            datetime.now() + timedelta(days=15)).strftime(
                DEFAULT_SERVER_DATE_FORMAT),
        }

class SaleOrderLine(orm.Model):
    ''' Extra field for order line
    '''
    _inherit = 'sale.order.line'

    # ----------------
    # Function fields:
    # ----------------
    def _function_get_delivered(self, cr, uid, ids, fields, args,
            context=None):
        ''' Fields function for calculate delivered elements in picking orders
        '''
        res = {}
        move_pool = self.pool.get('stock.move')

        for line in self.browse(cr, uid, ids, context=context):
            res[line.id] = 0.0
            move_ids = move_pool.search(cr, uid, [
                ('sale_line_id', '=', line.id),
                ], context=context)
            for move in move_pool.browse(cr, uid, move_ids, context=context):
                # TODO jump picking for virtual count!!!!!!!!!!!!!!!!!!!!!!!!!!
                #if move.picking_id.ddt_number: # was marked as DDT
                # TODO check UOM!!! for
                res[line.id] += move.product_uos_qty
        return res

    _columns = {
        'gr_weight': fields.float('Gross weight'),
        'colls': fields.integer('Colls'),
        #states={'draft': [('readonly', False)]}),

        'date_deadline': fields.date('Deadline'),
        'date_delivery': fields.related( # TODO use booked!!!!
            'order_id', 'date_delivery', type='date', string='Date delivery'),

        'alias_id':fields.many2one(
            'product.product', 'Marked as product', ondelete='set null'),

        'delivered_qty': fields.function(
            _function_get_delivered, method=True, type='float', readonly=True,
            string='Delivered', store=False,
            help='Quantity delivered with DDT out'),
        # TODO add to delivery qty

        # Order ref:
        'client_order_ref': fields.related('order_id',
            'client_order_ref', type='char', string='Client order ref.'),
        }

    _defaults = {
        'colls': lambda *x: 1,
        }

class StockMove(orm.Model):
    ''' Extra field for order line
    '''
    _inherit = 'stock.move'

    _columns = {
        'sale_line_id': fields.many2one('sale.order.line', 'Sale line'),
        }
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
<|endoftext|>