<commit_before>##############################################################################
#
# Copyright (c) 2004 TINY SPRL. (http://tiny.be) All Rights Reserved.
#                    Fabien Pinckaers <fp@tiny.Be>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

#
# TODO:
# cr.execute('delete from wkf_triggers where model=%s and res_id=%d', (res_type,res_id))
#

import netsvc
import instance

import wkf_expr
import wkf_logs

def create(cr, act_datas, inst_id, ident):
	for act in act_datas:
		cr.execute("select nextval('wkf_workitem_id_seq')")
		id_new = cr.fetchone()[0]
		cr.execute("insert into wkf_workitem (id,act_id,inst_id,state) values (%d,%s,%s,'active')", (id_new, act['id'], inst_id))
		cr.execute('select * from wkf_workitem where id=%d',(id_new,))
		res = cr.dictfetchone()
		wkf_logs.log(cr,ident,act['id'],'active')
		process(cr, res, ident)

def process(cr, workitem, ident, signal=None, force_running=False):
	cr.execute('select * from wkf_activity where id=%d', (workitem['act_id'],))
	activity = cr.dictfetchone()

	triggers = False
	if workitem['state']=='active':
		triggers = True
		if not _execute(cr, workitem, activity, ident):
			return False

	if workitem['state']=='running':
		pass

	if workitem['state']=='complete' or force_running:
		ok = _split_test(cr, workitem, activity['split_mode'], ident, signal)
		triggers = triggers and not ok

	if triggers:
		cr.execute('select * from wkf_transition where act_from=%d', (workitem['act_id'],))
		alltrans = cr.dictfetchall()
		for trans in alltrans:
			if trans['trigger_model']:
				ids = wkf_expr._eval_expr(cr,ident,workitem,trans['trigger_expr_id'])
				for id in ids:
					cr.execute('select nextval(\'wkf_workitem_id_seq\')')
					id =cr.fetchone()[0]
					cr.execute('insert into wkf_triggers (model,res_id,instance_id,workitem_id,id) values (%s,%d,%d,%d,%d)', (trans['trigger_model'],id,workitem['inst_id'], workitem['id'], id))

	return True

# ---------------------- PRIVATE FUNCS --------------------------------

def _state_set(cr, workitem, activity, state, ident):
	cr.execute('update wkf_workitem set state=%s where id=%d', (state,workitem['id']))
	workitem['state'] = state
	wkf_logs.log(cr,ident,activity['id'],state)

def _execute(cr, workitem, activity, ident):
	#
	# send a signal to parent workflow (signal: subflow.signal_name)
	#
	if (workitem['state']=='active') and activity['signal_send']:
		cr.execute("select i.id,w.osv,i.res_id from wkf_instance i left join wkf w on (i.wkf_id=w.id) where i.id in (select inst_id from wkf_workitem where subflow_id=%d)", (workitem['inst_id'],))
		for i in cr.fetchall():
			instance.validate(cr, i[0], (ident[0],i[1],i[2]), activity['signal_send'], force_running=True)

	if activity['kind']=='dummy':
		if workitem['state']=='active':
			_state_set(cr, workitem, activity, 'complete', ident)
	elif activity['kind']=='function':
		if workitem['state']=='active':
			_state_set(cr, workitem, activity, 'running', ident)
			wkf_expr.execute(cr, ident, workitem, activity)
			_state_set(cr, workitem, activity, 'complete', ident)
	elif activity['kind']=='stopall':
		if workitem['state']=='active':
			_state_set(cr, workitem, activity, 'running', ident)
			cr.execute('delete from wkf_workitem where inst_id=%d and id<>%d', (workitem['inst_id'], workitem['id']))
			if activity['action']:
				wkf_expr.execute(cr, ident, workitem, activity)
			_state_set(cr, workitem, activity, 'complete', ident)
	elif activity['kind']=='subflow':
		if workitem['state']=='active':
			_state_set(cr, workitem, activity, 'running', ident)
			if activity.get('action', False):
				id_new = wkf_expr.execute(cr, ident, workitem, activity)
				if not (id_new):
					cr.execute('delete from wkf_workitem where id=%s', (workitem['id'],))
					return False
				assert type(id_new)==type(1) or type(id_new)==type(1L), 'Wrong return value: '+str(id_new)+' '+str(type(id_new))
				cr.execute('select id from wkf_instance where res_id=%d and wkf_id=%d', (id_new,activity['subflow_id']))
				id_new = cr.fetchone()[0]
			else:
				id_new = instance.create(cr, ident, activity['subflow_id'])
			cr.execute('update wkf_workitem set subflow_id=%d where id=%s', (id_new, workitem['id']))
			workitem['subflow_id'] = id_new
		if workitem['state']=='running':
			cr.execute("select state from wkf_instance where id=%d", (workitem['subflow_id'],))
			state= cr.fetchone()[0]
			if state=='complete':
				_state_set(cr, workitem, activity, 'complete', ident)
	return True

def _split_test(cr, workitem, split_mode, ident, signal=None):
	cr.execute('select * from wkf_transition where act_from=%d', (workitem['act_id'],))
	test = False
	transitions = []
	alltrans = cr.dictfetchall()
	if split_mode=='XOR' or split_mode=='OR':
		for transition in alltrans:
			if wkf_expr.check(cr, workitem, ident, transition,signal):
				test = True
				transitions.append((transition['id'], workitem['inst_id']))
				if split_mode=='XOR':
					break
	else:
		test = True
		for transition in alltrans:
			if not wkf_expr.check(cr, workitem, ident, transition,signal):
				test = False
				break
			cr.execute('select count(*) from wkf_witm_trans where trans_id=%d and inst_id=%d', (transition['id'], workitem['inst_id']))
			if not cr.fetchone()[0]:
				transitions.append((transition['id'], workitem['inst_id']))
	if not test:
		pass
	if test and len(transitions):
		cr.executemany('insert into wkf_witm_trans (trans_id,inst_id) values (%d,%d)', transitions)
		cr.execute('delete from wkf_workitem where id=%d', (workitem['id'],))
		for t in transitions:
			_join_test(cr, t[0], t[1], ident)
		return True
	return False

def _join_test(cr, trans_id, inst_id, ident):
	cr.execute('select * from wkf_activity where id=(select act_to from wkf_transition where id=%d)', (trans_id,))
	activity = cr.dictfetchone()
	if activity['join_mode']=='XOR':
		create(cr,[activity], inst_id, ident)
		cr.execute('delete from wkf_witm_trans where inst_id=%d and trans_id=%d', (inst_id,trans_id))
	else:
		cr.execute('select id from wkf_transition where act_to=%d', (activity['id'],))
		trans_ids = cr.fetchall()
		ok = True
		for (id,) in trans_ids:
			cr.execute('select count(*) from wkf_witm_trans where trans_id=%d and inst_id=%d', (id,inst_id))
			res = cr.fetchone()[0]
			if not res:
				ok = False
				break
		if ok:
			for (id,) in trans_ids:
				cr.execute('delete from wkf_witm_trans where trans_id=%d and inst_id=%d', (id,inst_id))
			create(cr, [activity], inst_id, ident)
<commit_msg>kernel: fix workflow bug introduce by improvement<commit_after>##############################################################################
#
# Copyright (c) 2004 TINY SPRL. (http://tiny.be) All Rights Reserved.
#                    Fabien Pinckaers <fp@tiny.Be>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

#
# TODO:
# cr.execute('delete from wkf_triggers where model=%s and res_id=%d', (res_type,res_id))
#

import netsvc
import instance

import wkf_expr
import wkf_logs

def create(cr, act_datas, inst_id, ident):
	for act in act_datas:
		cr.execute("select nextval('wkf_workitem_id_seq')")
		id_new = cr.fetchone()[0]
		cr.execute("insert into wkf_workitem (id,act_id,inst_id,state) values (%d,%s,%s,'active')", (id_new, act['id'], inst_id))
		cr.execute('select * from wkf_workitem where id=%d',(id_new,))
		res = cr.dictfetchone()
		wkf_logs.log(cr,ident,act['id'],'active')
		process(cr, res, ident)

def process(cr, workitem, ident, signal=None, force_running=False):
	cr.execute('select * from wkf_activity where id=%d', (workitem['act_id'],))
	activity = cr.dictfetchone()

	triggers = False
	if workitem['state']=='active':
		triggers = True
		if not _execute(cr, workitem, activity, ident):
			return False

	if workitem['state']=='running':
		pass

	if workitem['state']=='complete' or force_running:
		ok = _split_test(cr, workitem, activity['split_mode'], ident, signal)
		triggers = triggers and not ok

	if triggers:
		cr.execute('select * from wkf_transition where act_from=%d', (workitem['act_id'],))
		alltrans = cr.dictfetchall()
		for trans in alltrans:
			if trans['trigger_model']:
				ids = wkf_expr._eval_expr(cr,ident,workitem,trans['trigger_expr_id'])
				for res_id in ids:
					cr.execute('select nextval(\'wkf_triggers_id_seq\')')
					id =cr.fetchone()[0]
					cr.execute('insert into wkf_triggers (model,res_id,instance_id,workitem_id,id) values (%s,%d,%d,%d,%d)', (trans['trigger_model'],res_id,workitem['inst_id'], workitem['id'], id))

	return True

# ---------------------- PRIVATE FUNCS --------------------------------

def _state_set(cr, workitem, activity, state, ident):
	cr.execute('update wkf_workitem set state=%s where id=%d', (state,workitem['id']))
	workitem['state'] = state
	wkf_logs.log(cr,ident,activity['id'],state)

def _execute(cr, workitem, activity, ident):
	#
	# send a signal to parent workflow (signal: subflow.signal_name)
	#
	if (workitem['state']=='active') and activity['signal_send']:
		cr.execute("select i.id,w.osv,i.res_id from wkf_instance i left join wkf w on (i.wkf_id=w.id) where i.id in (select inst_id from wkf_workitem where subflow_id=%d)", (workitem['inst_id'],))
		for i in cr.fetchall():
			instance.validate(cr, i[0], (ident[0],i[1],i[2]), activity['signal_send'], force_running=True)

	if activity['kind']=='dummy':
		if workitem['state']=='active':
			_state_set(cr, workitem, activity, 'complete', ident)
	elif activity['kind']=='function':
		if workitem['state']=='active':
			_state_set(cr, workitem, activity, 'running', ident)
			wkf_expr.execute(cr, ident, workitem, activity)
			_state_set(cr, workitem, activity, 'complete', ident)
	elif activity['kind']=='stopall':
		if workitem['state']=='active':
			_state_set(cr, workitem, activity, 'running', ident)
			cr.execute('delete from wkf_workitem where inst_id=%d and id<>%d', (workitem['inst_id'], workitem['id']))
			if activity['action']:
				wkf_expr.execute(cr, ident, workitem, activity)
			_state_set(cr, workitem, activity, 'complete', ident)
	elif activity['kind']=='subflow':
		if workitem['state']=='active':
			_state_set(cr, workitem, activity, 'running', ident)
			if activity.get('action', False):
				id_new = wkf_expr.execute(cr, ident, workitem, activity)
				if not (id_new):
					cr.execute('delete from wkf_workitem where id=%s', (workitem['id'],))
					return False
				assert type(id_new)==type(1) or type(id_new)==type(1L), 'Wrong return value: '+str(id_new)+' '+str(type(id_new))
				cr.execute('select id from wkf_instance where res_id=%d and wkf_id=%d', (id_new,activity['subflow_id']))
				id_new = cr.fetchone()[0]
			else:
				id_new = instance.create(cr, ident, activity['subflow_id'])
			cr.execute('update wkf_workitem set subflow_id=%d where id=%s', (id_new, workitem['id']))
			workitem['subflow_id'] = id_new
		if workitem['state']=='running':
			cr.execute("select state from wkf_instance where id=%d", (workitem['subflow_id'],))
			state= cr.fetchone()[0]
			if state=='complete':
				_state_set(cr, workitem, activity, 'complete', ident)
	return True

def _split_test(cr, workitem, split_mode, ident, signal=None):
	cr.execute('select * from wkf_transition where act_from=%d', (workitem['act_id'],))
	test = False
	transitions = []
	alltrans = cr.dictfetchall()
	if split_mode=='XOR' or split_mode=='OR':
		for transition in alltrans:
			if wkf_expr.check(cr, workitem, ident, transition,signal):
				test = True
				transitions.append((transition['id'], workitem['inst_id']))
				if split_mode=='XOR':
					break
	else:
		test = True
		for transition in alltrans:
			if not wkf_expr.check(cr, workitem, ident, transition,signal):
				test = False
				break
			cr.execute('select count(*) from wkf_witm_trans where trans_id=%d and inst_id=%d', (transition['id'], workitem['inst_id']))
			if not cr.fetchone()[0]:
				transitions.append((transition['id'], workitem['inst_id']))
	if not test:
		pass
	if test and len(transitions):
		cr.executemany('insert into wkf_witm_trans (trans_id,inst_id) values (%d,%d)', transitions)
		cr.execute('delete from wkf_workitem where id=%d', (workitem['id'],))
		for t in transitions:
			_join_test(cr, t[0], t[1], ident)
		return True
	return False

def _join_test(cr, trans_id, inst_id, ident):
	cr.execute('select * from wkf_activity where id=(select act_to from wkf_transition where id=%d)', (trans_id,))
	activity = cr.dictfetchone()
	if activity['join_mode']=='XOR':
		create(cr,[activity], inst_id, ident)
		cr.execute('delete from wkf_witm_trans where inst_id=%d and trans_id=%d', (inst_id,trans_id))
	else:
		cr.execute('select id from wkf_transition where act_to=%d', (activity['id'],))
		trans_ids = cr.fetchall()
		ok = True
		for (id,) in trans_ids:
			cr.execute('select count(*) from wkf_witm_trans where trans_id=%d and inst_id=%d', (id,inst_id))
			res = cr.fetchone()[0]
			if not res:
				ok = False
				break
		if ok:
			for (id,) in trans_ids:
				cr.execute('delete from wkf_witm_trans where trans_id=%d and inst_id=%d', (id,inst_id))
			create(cr, [activity], inst_id, ident)
<|endoftext|>


<commit_before>from django.conf.urls import patterns, url, include
from surlex.dj import surl
from .views import (ProjectDetail, ProjectList, ManageProjectList, ManageProjectDetail, ProjectThemeList,
                    ProjectThemeDetail, ProjectPreviewList, ProjectPreviewDetail, ManageProjectBudgetLineList,
                    ManageProjectBudgetLineDetail)

urlpatterns = patterns('',
    url(r'^projects/$', ProjectList.as_view(), name='project-list'),
    surl(r'^projects/<slug:s>$', ProjectDetail.as_view(), name='project-detail'),

    url(r'^previews/$', ProjectPreviewList.as_view(), name='project-preview-list'),
    surl(r'^previews/<slug:s>$', ProjectPreviewDetail.as_view(), name='project-preview-detail'),

    surl(r'^themes/$', ProjectThemeList.as_view(), name='project-theme-list'),
    surl(r'^themes/<pk:#>$', ProjectThemeDetail.as_view(), name='project-theme-detail'),

    # Manage stuff
    url(r'^manage/$', ManageProjectList.as_view(), name='project-manage-list'),
    surl(r'^manage/<slug:s>$', ManageProjectDetail.as_view(), name='project-manage-detail'),

    url(r'^budgetlines/manage/$', ManageProjectBudgetLineList.as_view(), name='project-budgetline-manage-detail'),
    surl(r'^budgetlines/manage/<pk:#>$', ManageProjectBudgetLineDetail.as_view(), name='project-budgetline-manage-detail'),

)
<commit_msg>`projects` API URLs modified.<commit_after>from django.conf.urls import patterns, url, include
from surlex.dj import surl
from .views import (ProjectDetail, ProjectList, ManageProjectList, ManageProjectDetail, ProjectThemeList,
                    ProjectThemeDetail, ProjectPreviewList, ProjectPreviewDetail, ManageProjectBudgetLineList,
                    ManageProjectBudgetLineDetail)

urlpatterns = patterns('',
    url(r'^$', ProjectList.as_view(), name='project-list'),
    surl(r'^<slug:s>/$', ProjectDetail.as_view(), name='project-detail'),

    url(r'^previews/$', ProjectPreviewList.as_view(), name='project-preview-list'),
    surl(r'^previews/<slug:s>$', ProjectPreviewDetail.as_view(), name='project-preview-detail'),

    surl(r'^themes/$', ProjectThemeList.as_view(), name='project-theme-list'),
    surl(r'^themes/<pk:#>$', ProjectThemeDetail.as_view(), name='project-theme-detail'),

    # Manage stuff
    url(r'^manage/$', ManageProjectList.as_view(), name='project-manage-list'),
    surl(r'^manage/<slug:s>$', ManageProjectDetail.as_view(), name='project-manage-detail'),

    url(r'^budgetlines/manage/$', ManageProjectBudgetLineList.as_view(), name='project-budgetline-manage-detail'),
    surl(r'^budgetlines/manage/<pk:#>$', ManageProjectBudgetLineDetail.as_view(), name='project-budgetline-manage-detail'),

)
<|endoftext|>


<commit_before>"""
Resampler layer initially implemented in
https://cmiclab.cs.ucl.ac.uk/CMIC/NiftyNet/blob/v0.2.0.post1/niftynet/layer/spatial_transformer.py
"""
from __future__ import absolute_import, division, print_function

import tensorflow as tf

from niftynet.layer.base_layer import Layer
from niftynet.layer.layer_util import infer_spatial_rank
from niftynet.utilities.util_common import look_up_operations

COORDINATES_TYPE = tf.int32
EPS = 1e-6

class ResamplerLayer(Layer):
    """
    resample inputs according to sample_coords
    """

    def __init__(self,
                 interpolation="LINEAR",
                 boundary="ZERO",
                 name="resampler"):
        super(ResamplerLayer, self).__init__(name=name)
        self.boundary = boundary.upper()
        self.boundary_func = look_up_operations(
            self.boundary, SUPPORTED_BOUNDARY)
        self.interpolation = look_up_operations(
            interpolation.upper(), SUPPORTED_INTERPOLATION)

        if self.boundary == 'ZERO' and self.interpolation == 'BSPLINE':
            tf.logging.fatal('Zero padding is not supported for BSPLINE mode')
            raise NotImplementedError

        if self.boundary == 'ZERO' and self.interpolation == 'IDW':
            tf.logging.fatal('Zero padding is not supported for IDW mode')
            raise NotImplementedError

    def layer_op(self, inputs, sample_coords):
        if inputs.dtype not in SUPPORTED_INPUT_DTYPE:
            # tf.logging.warning('input datatype should be in %s ',
            #                    SUPPORTED_INPUT_DTYPE)
            # raise TypeError
            inputs = tf.to_float(inputs)
        if sample_coords.dtype not in SUPPORTED_INPUT_DTYPE:
            sample_coords = tf.to_float(sample_coords)
        if self.interpolation == 'LINEAR':
            return self._resample_linear(inputs, sample_coords)
        if self.interpolation == 'NEAREST':
            return self._resample_nearest(inputs, sample_coords)
        if self.interpolation == 'BSPLINE':
            return self._resample_bspline(inputs, sample_coords)
        if self.interpolation == 'IDW':
            return self._resample_inv_dst_weighting(inputs, sample_coords)
        tf.logging.fatal('interpolation method not implmented')
        raise NotImplementedError

    def _resample_nearest(self, inputs, sample_coords):
        in_size = inputs.get_shape().as_list()
        in_spatial_size = in_size[1:-1]

        spatial_coords = self.boundary_func(
            tf.round(sample_coords), in_spatial_size)
        spatial_coords = tf.cast(spatial_coords, COORDINATES_TYPE)
        output = tf.stack([
            tf.gather_nd(img, coords) for (img, coords) in
            zip(tf.unstack(inputs), tf.unstack(spatial_coords))])

        if self.boundary == 'ZERO':
            scale = 1. / (tf.constant(in_spatial_size, dtype=tf.float32) - 1)
            mask = tf.logical_and(
                tf.reduce_all(sample_coords > 0,
                              axis=-1, keep_dims=True),
                tf.reduce_all(scale * sample_coords < 1,
                              axis=-1, keep_dims=True))
            return output * tf.to_float(mask)
        return output

    def _resample_linear(self, inputs, sample_coords):
        in_size = inputs.get_shape().as_list()
        in_spatial_size = in_size[1:-1]
        in_spatial_rank = infer_spatial_rank(inputs)
        batch_size = in_size[0]

        out_spatial_rank = infer_spatial_rank(sample_coords)
        out_spatial_size = sample_coords.get_shape().as_list()[1:-1]

        if in_spatial_rank == 2 and self.boundary == 'ZERO':
            inputs = tf.transpose(inputs, [0, 2, 1, 3])
            return tf.contrib.resampler.resampler(inputs, sample_coords)

        xy = tf.unstack(sample_coords, axis=-1)
        base_coords = [tf.floor(coords) for coords in xy]
        floor_coords = [
            tf.cast(self.boundary_func(x, in_spatial_size[idx]),
                    COORDINATES_TYPE)
            for (idx, x) in enumerate(base_coords)]
        ceil_coords = [
            tf.cast(self.boundary_func(x + 1.0, in_spatial_size[idx]),
                    COORDINATES_TYPE)
            for (idx, x) in enumerate(base_coords)]

        if self.boundary == 'ZERO':
            weight_0 = [tf.expand_dims(x - tf.cast(i, tf.float32), -1)
                        for (x, i) in zip(xy, floor_coords)]
            weight_1 = [tf.expand_dims(tf.cast(i, tf.float32) - x, -1)
                        for (x, i) in zip(xy, ceil_coords)]
        else:
            weight_0 = [tf.expand_dims(x - i, -1)
                        for (x, i) in zip(xy, base_coords)]
            weight_1 = [1.0 - w for w in weight_0]

        batch_ids = tf.reshape(
            tf.range(batch_size), [batch_size] + [1] * out_spatial_rank)
        batch_ids = tf.tile(batch_ids, [1] + out_spatial_size)
        sc = (floor_coords, ceil_coords)

        def get_knot(bc):
            coord = [sc[c][i] for i, c in enumerate(bc)]
            coord = tf.stack([batch_ids] + coord, -1)
            return tf.gather_nd(inputs, coord)

        def _pyramid_combination(samples, w_0, w_1):
            if len(w_0) == 1:
                return samples[0] * w_1[0] + samples[1] * w_0[0]
            f_0 = _pyramid_combination(samples[::2], w_0[:-1], w_1[:-1])
            f_1 = _pyramid_combination(samples[1::2], w_0[:-1], w_1[:-1])
            return f_0 * w_1[-1] + f_1 * w_0[-1]

        binary_neighbour_ids = [
            [int(c) for c in format(i, '0%ib' % in_spatial_rank)]
            for i in range(2 ** in_spatial_rank)]
        samples = [get_knot(bc) for bc in binary_neighbour_ids]
        return _pyramid_combination(samples, weight_0, weight_1)

    def _resample_bspline(self, inputs, sample_coords):
        in_size = inputs.get_shape().as_list()
        batch_size = in_size[0]
        in_spatial_size = in_size[1:-1]
        in_spatial_rank = infer_spatial_rank(inputs)

        out_spatial_rank = infer_spatial_rank(sample_coords)
        if in_spatial_rank == 2:
            raise NotImplementedError(
                'bspline interpolation not implemented for 2d yet')
        floor_coords = tf.floor(sample_coords)

        # Compute voxels to use for interpolation
        grid = tf.meshgrid([-1., 0., 1., 2.],
                           [-1., 0., 1., 2.],
                           [-1., 0., 1., 2.],
                           indexing='ij')
        offset_shape = [1, -1] + [1] * out_spatial_rank + [in_spatial_rank]
        offsets = tf.reshape(tf.stack(grid, 3), offset_shape)
        spatial_coords = offsets + tf.expand_dims(floor_coords, 1)
        spatial_coords = self.boundary_func(spatial_coords, in_spatial_size)
        spatial_coords = tf.cast(spatial_coords, COORDINATES_TYPE)
        knot_size = spatial_coords.get_shape().as_list()

        # Compute weights for each voxel
        def build_coef(u, d):
            coeff_list = [tf.pow(1 - u, 3),
                          3 * tf.pow(u, 3) - 6 * tf.pow(u, 2) + 4,
                          -3 * tf.pow(u, 3) + 3 * tf.pow(u, 2) + 3 * u + 1,
                          tf.pow(u, 3)]
            return tf.concat(coeff_list, d) / 6

        weight = tf.reshape(sample_coords - floor_coords, [batch_size, -1, 3])
        coef_shape = [batch_size, 1, 1, 1, -1]
        Bu = build_coef(tf.reshape(weight[:, :, 0], coef_shape), 1)
        Bv = build_coef(tf.reshape(weight[:, :, 1], coef_shape), 2)
        Bw = build_coef(tf.reshape(weight[:, :, 2], coef_shape), 3)
        all_weights = tf.reshape(Bu * Bv * Bw,
                                 [batch_size] + knot_size[1:-1] + [1])
        # Gather voxel values and compute weighted sum
        batch_coords = tf.reshape(
            tf.range(batch_size), [batch_size] + [1] * (len(knot_size) - 1))
        batch_coords = tf.tile(batch_coords, [1] + knot_size[1:-1] + [1])
        raw_samples = tf.gather_nd(
            inputs, tf.concat([batch_coords, spatial_coords], -1))
        return tf.reduce_sum(all_weights * raw_samples, reduction_indices=1)

    def _resample_inv_dst_weighting(self, inputs, sample_coords):
        in_size = inputs.get_shape().as_list()
        in_spatial_size = in_size[1:-1]
        in_spatial_rank = infer_spatial_rank(inputs)
        out_rank = len(sample_coords.get_shape().as_list())

        self.N = 2 ** in_spatial_rank
        binary_neighbour_ids = [
            [int(c) for c in format(i, '0%ib' % in_spatial_rank)]
            for i in range(self.N)]
        weight_id = [[[c, i] for i, c in enumerate(bc)]
                     for bc in binary_neighbour_ids]

        sample_coords = tf.transpose(
            sample_coords, [out_rank - 1, 0] + list(range(1, out_rank - 1)))
        # broadcasting input spatial size for boundary functions
        b_size = tf.reshape(in_spatial_size,
                            [len(in_spatial_size)] + [1] * (out_rank - 1))
        # find floor and ceil coordinates
        all_coords_f = tf.stack([
            self.boundary_func(tf.floor(sample_coords), b_size),
            self.boundary_func(tf.ceil(sample_coords), b_size)], axis=0)
        # find N weights associated to each output point
        diff = tf.stack(
            [tf.squared_difference(sample_coords - EPS, all_coords_f[0]),
             tf.squared_difference(sample_coords + EPS, all_coords_f[1])])

        # gather_nd for both matrix, the same as:
        # point_weights = tf.gather_nd(diff, weight_id)
        # knots_id = tf.gather_nd(all_coords_f, weight_id)
        n_val = tf.gather_nd(tf.stack([diff, all_coords_f], axis=-1), weight_id)
        n_val = tf.unstack(n_val, axis=-1)
        point_weights, knots_id = n_val[0], n_val[1]

        point_weights = tf.reduce_sum(point_weights, axis=1)
        # skip this as power = 2.0:
        # self.power = 1.0
        # point_weights = tf.pow(point_weights, self.power / 2.0)
        point_weights = tf.reciprocal(point_weights)
        point_weights = tf.expand_dims(point_weights, axis=-1)

        # find N neighbours associated to each output point
        knots_id = tf.transpose(tf.cast(knots_id, COORDINATES_TYPE),
                                [0] + list(range(2, out_rank + 1)) + [1])
        # get values of N neighbours
        samples = [
            tf.gather_nd(img, knots) for (img, knots) in
            zip(tf.unstack(inputs, axis=0), tf.unstack(knots_id, axis=1))]
        samples = tf.stack(samples, axis=1)

        # weighted average over N neighbours
        samples = tf.reduce_sum(samples * point_weights, axis=0)
        samples = samples / tf.reduce_sum(point_weights, axis=0)
        return samples

def _boundary_replicate(sample_coords, input_size):
    sample_coords, input_size = _param_type_and_shape(sample_coords, input_size)
    return tf.maximum(tf.minimum(sample_coords, input_size - 1), 0)

def _boundary_circular(sample_coords, input_size):
    sample_coords, input_size = _param_type_and_shape(sample_coords, input_size)
    return tf.mod(tf.mod(sample_coords, input_size) + input_size, input_size)

def _boundary_symmetric(sample_coords, input_size):
    sample_coords, input_size = _param_type_and_shape(sample_coords, input_size)
    circular_size = input_size + input_size - 2
    return (input_size - 1) - tf.abs(
        (input_size - 1) - _boundary_circular(sample_coords, circular_size))

def _param_type_and_shape(sample_coords, input_size):
    # sample_coords = tf.cast(sample_coords, COORDINATES_TYPE)
    try:
        input_size = tf.constant(input_size, dtype=tf.float32)
    except TypeError:
        pass
    try:
        input_size = tf.to_float(input_size)
    except TypeError:
        pass
    return sample_coords, input_size

@tf.RegisterGradient('FloorMod')
def _floormod_grad(op, grad):
    return [None, None]

SUPPORTED_INTERPOLATION = {'BSPLINE', 'LINEAR', 'NEAREST', 'IDW'}

SUPPORTED_BOUNDARY = {
    'ZERO': _boundary_replicate,
    'REPLICATE': _boundary_replicate,
    'CIRCULAR': _boundary_circular,
    'SYMMETRIC': _boundary_symmetric}

SUPPORTED_INPUT_DTYPE = {tf.float32}
<commit_msg>more resampler docs<commit_after>"""
Resampler layer initially implemented in
https://cmiclab.cs.ucl.ac.uk/CMIC/NiftyNet/blob/v0.2.0.post1/niftynet/layer/spatial_transformer.py
"""
from __future__ import absolute_import, division, print_function

import tensorflow as tf

from niftynet.layer.base_layer import Layer
from niftynet.layer.layer_util import infer_spatial_rank
from niftynet.utilities.util_common import look_up_operations

COORDINATES_TYPE = tf.int32
EPS = 1e-6

class ResamplerLayer(Layer):
    """
    resample inputs according to sample_coords
    """

    def __init__(self,
                 interpolation="LINEAR",
                 boundary="ZERO",
                 name="resampler"):
        super(ResamplerLayer, self).__init__(name=name)
        self.boundary = boundary.upper()
        self.boundary_func = look_up_operations(
            self.boundary, SUPPORTED_BOUNDARY)
        self.interpolation = look_up_operations(
            interpolation.upper(), SUPPORTED_INTERPOLATION)

        if self.boundary == 'ZERO' and self.interpolation == 'BSPLINE':
            tf.logging.fatal('Zero padding is not supported for BSPLINE mode')
            raise NotImplementedError

        if self.boundary == 'ZERO' and self.interpolation == 'IDW':
            tf.logging.fatal('Zero padding is not supported for IDW mode')
            raise NotImplementedError

    def layer_op(self, inputs, sample_coords):
        if inputs.dtype not in SUPPORTED_INPUT_DTYPE:
            # tf.logging.warning('input datatype should be in %s ',
            #                    SUPPORTED_INPUT_DTYPE)
            # raise TypeError
            inputs = tf.to_float(inputs)
        if sample_coords.dtype not in SUPPORTED_INPUT_DTYPE:
            sample_coords = tf.to_float(sample_coords)
        if self.interpolation == 'LINEAR':
            return self._resample_linear(inputs, sample_coords)
        if self.interpolation == 'NEAREST':
            return self._resample_nearest(inputs, sample_coords)
        if self.interpolation == 'BSPLINE':
            return self._resample_bspline(inputs, sample_coords)
        if self.interpolation == 'IDW':
            return self._resample_inv_dst_weighting(inputs, sample_coords)
        tf.logging.fatal('interpolation method not implmented')
        raise NotImplementedError

    def _resample_nearest(self, inputs, sample_coords):
        in_size = inputs.get_shape().as_list()
        in_spatial_size = in_size[1:-1]

        # This is forward only as no gradient for tf.round
        spatial_coords = self.boundary_func(
            tf.round(sample_coords), in_spatial_size)
        spatial_coords = tf.cast(spatial_coords, COORDINATES_TYPE)
        output = tf.stack([
            tf.gather_nd(img, coords) for (img, coords) in
            zip(tf.unstack(inputs), tf.unstack(spatial_coords))])

        if self.boundary == 'ZERO':
            scale = 1. / (tf.constant(in_spatial_size, dtype=tf.float32) - 1)
            mask = tf.logical_and(
                tf.reduce_all(sample_coords > 0,
                              axis=-1, keep_dims=True),
                tf.reduce_all(scale * sample_coords < 1,
                              axis=-1, keep_dims=True))
            return output * tf.to_float(mask)
        return output

    def _resample_linear(self, inputs, sample_coords):
        in_size = inputs.get_shape().as_list()
        in_spatial_size = in_size[1:-1]
        in_spatial_rank = infer_spatial_rank(inputs)
        batch_size = in_size[0]

        out_spatial_rank = infer_spatial_rank(sample_coords)
        out_spatial_size = sample_coords.get_shape().as_list()[1:-1]

        if in_spatial_rank == 2 and self.boundary == 'ZERO':
            inputs = tf.transpose(inputs, [0, 2, 1, 3])
            return tf.contrib.resampler.resampler(inputs, sample_coords)

        xy = tf.unstack(sample_coords, axis=-1)
        base_coords = [tf.floor(coords) for coords in xy]
        floor_coords = [
            tf.cast(self.boundary_func(x, in_spatial_size[idx]),
                    COORDINATES_TYPE)
            for (idx, x) in enumerate(base_coords)]
        ceil_coords = [
            tf.cast(self.boundary_func(x + 1.0, in_spatial_size[idx]),
                    COORDINATES_TYPE)
            for (idx, x) in enumerate(base_coords)]

        if self.boundary == 'ZERO':
            weight_0 = [tf.expand_dims(x - tf.cast(i, tf.float32), -1)
                        for (x, i) in zip(xy, floor_coords)]
            weight_1 = [tf.expand_dims(tf.cast(i, tf.float32) - x, -1)
                        for (x, i) in zip(xy, ceil_coords)]
        else:
            weight_0 = [tf.expand_dims(x - i, -1)
                        for (x, i) in zip(xy, base_coords)]
            weight_1 = [1.0 - w for w in weight_0]

        batch_ids = tf.reshape(
            tf.range(batch_size), [batch_size] + [1] * out_spatial_rank)
        batch_ids = tf.tile(batch_ids, [1] + out_spatial_size)
        sc = (floor_coords, ceil_coords)

        def get_knot(bc):
            coord = [sc[c][i] for i, c in enumerate(bc)]
            coord = tf.stack([batch_ids] + coord, -1)
            return tf.gather_nd(inputs, coord)

        def _pyramid_combination(samples, w_0, w_1):
            if len(w_0) == 1:
                return samples[0] * w_1[0] + samples[1] * w_0[0]
            f_0 = _pyramid_combination(samples[::2], w_0[:-1], w_1[:-1])
            f_1 = _pyramid_combination(samples[1::2], w_0[:-1], w_1[:-1])
            return f_0 * w_1[-1] + f_1 * w_0[-1]

        binary_neighbour_ids = [
            [int(c) for c in format(i, '0%ib' % in_spatial_rank)]
            for i in range(2 ** in_spatial_rank)]
        samples = [get_knot(bc) for bc in binary_neighbour_ids]
        return _pyramid_combination(samples, weight_0, weight_1)

    def _resample_bspline(self, inputs, sample_coords):
        in_size = inputs.get_shape().as_list()
        batch_size = in_size[0]
        in_spatial_size = in_size[1:-1]
        in_spatial_rank = infer_spatial_rank(inputs)

        out_spatial_rank = infer_spatial_rank(sample_coords)
        if in_spatial_rank == 2:
            raise NotImplementedError(
                'bspline interpolation not implemented for 2d yet')
        floor_coords = tf.floor(sample_coords)

        # Compute voxels to use for interpolation
        grid = tf.meshgrid([-1., 0., 1., 2.],
                           [-1., 0., 1., 2.],
                           [-1., 0., 1., 2.],
                           indexing='ij')
        offset_shape = [1, -1] + [1] * out_spatial_rank + [in_spatial_rank]
        offsets = tf.reshape(tf.stack(grid, 3), offset_shape)
        spatial_coords = offsets + tf.expand_dims(floor_coords, 1)
        spatial_coords = self.boundary_func(spatial_coords, in_spatial_size)
        spatial_coords = tf.cast(spatial_coords, COORDINATES_TYPE)
        knot_size = spatial_coords.get_shape().as_list()

        # Compute weights for each voxel
        def build_coef(u, d):
            coeff_list = [tf.pow(1 - u, 3),
                          3 * tf.pow(u, 3) - 6 * tf.pow(u, 2) + 4,
                          -3 * tf.pow(u, 3) + 3 * tf.pow(u, 2) + 3 * u + 1,
                          tf.pow(u, 3)]
            return tf.concat(coeff_list, d) / 6

        weight = tf.reshape(sample_coords - floor_coords, [batch_size, -1, 3])
        coef_shape = [batch_size, 1, 1, 1, -1]
        Bu = build_coef(tf.reshape(weight[:, :, 0], coef_shape), 1)
        Bv = build_coef(tf.reshape(weight[:, :, 1], coef_shape), 2)
        Bw = build_coef(tf.reshape(weight[:, :, 2], coef_shape), 3)
        all_weights = tf.reshape(Bu * Bv * Bw,
                                 [batch_size] + knot_size[1:-1] + [1])
        # Gather voxel values and compute weighted sum
        batch_coords = tf.reshape(
            tf.range(batch_size), [batch_size] + [1] * (len(knot_size) - 1))
        batch_coords = tf.tile(batch_coords, [1] + knot_size[1:-1] + [1])
        raw_samples = tf.gather_nd(
            inputs, tf.concat([batch_coords, spatial_coords], -1))
        return tf.reduce_sum(all_weights * raw_samples, reduction_indices=1)

    def _resample_inv_dst_weighting(self, inputs, sample_coords):
        in_size = inputs.get_shape().as_list()
        in_spatial_size = in_size[1:-1]
        in_spatial_rank = infer_spatial_rank(inputs)
        out_rank = len(sample_coords.get_shape().as_list())

        self.N = 2 ** in_spatial_rank
        binary_neighbour_ids = [
            [int(c) for c in format(i, '0%ib' % in_spatial_rank)]
            for i in range(self.N)]
        weight_id = [[[c, i] for i, c in enumerate(bc)]
                     for bc in binary_neighbour_ids]

        sample_coords = tf.transpose(
            sample_coords, [out_rank - 1, 0] + list(range(1, out_rank - 1)))
        # broadcasting input spatial size for boundary functions
        b_size = tf.reshape(in_spatial_size,
                            [len(in_spatial_size)] + [1] * (out_rank - 1))
        # find floor and ceil coordinates
        all_coords_f = tf.stack([
            self.boundary_func(tf.floor(sample_coords), b_size),
            self.boundary_func(tf.ceil(sample_coords), b_size)])
        # find N weights associated to each output point
        diff = tf.stack(
            [tf.squared_difference(sample_coords - EPS, all_coords_f[0]),
             tf.squared_difference(sample_coords + EPS, all_coords_f[1])])

        # gather_nd for both matrices, the same as:
        # point_weights = tf.gather_nd(diff, weight_id)
        # knots_id = tf.gather_nd(all_coords_f, weight_id)
        n_val = tf.gather_nd(tf.stack([diff, all_coords_f], axis=-1), weight_id)
        n_val = tf.unstack(n_val, axis=-1)
        point_weights, knots_id = n_val[0], n_val[1]

        # inverse distance weighting
        # sum_i (w_i*p_i/(sum_j w_j)) w_i = 1/((p-p_i)^2)
        # point_weights shape:
        # `[N, input_rank, b, sp_dim_0, ..., sp_dim_K]`
        # where:
        #  `N` is 2**source data spatial rank
        #  `b` is batch size,
        #  `sp_dim_0` is the output spatial output 0,
        #
        # `point_weights` represents (p - p_i)^2
        #      with i= 0...2**source_rank neighbours
        # (to do: these operations could be refactored as a resampling kernel)
        point_weights = tf.reduce_sum(point_weights, axis=1)
        # skip this as power = 2.0:
        # self.power = 1.0
        # point_weights = tf.pow(point_weights, self.power / 2.0)
        point_weights = tf.reciprocal(point_weights)
        point_weights = point_weights / tf.reduce_sum(point_weights, axis=0)

        # find N neighbours associated to each output point
        knots_id = tf.transpose(tf.cast(knots_id, COORDINATES_TYPE),
                                [0] + list(range(2, out_rank + 1)) + [1])
        # get values of N neighbours
        samples = [
            tf.gather_nd(img, knots) for (img, knots) in
            zip(tf.unstack(inputs, axis=0), tf.unstack(knots_id, axis=1))]
        samples = tf.stack(samples, axis=1)

        # weighted average over N neighbours
        return tf.reduce_sum(
            samples * tf.expand_dims(point_weights, axis=-1), axis=0)

def _boundary_replicate(sample_coords, input_size):
    sample_coords, input_size = _param_type_and_shape(sample_coords, input_size)
    return tf.maximum(tf.minimum(sample_coords, input_size - 1), 0)

def _boundary_circular(sample_coords, input_size):
    sample_coords, input_size = _param_type_and_shape(sample_coords, input_size)
    return tf.mod(tf.mod(sample_coords, input_size) + input_size, input_size)

def _boundary_symmetric(sample_coords, input_size):
    sample_coords, input_size = _param_type_and_shape(sample_coords, input_size)
    circular_size = input_size + input_size - 2
    return (input_size - 1) - tf.abs(
        (input_size - 1) - _boundary_circular(sample_coords, circular_size))

def _param_type_and_shape(sample_coords, input_size):
    # sample_coords = tf.cast(sample_coords, COORDINATES_TYPE)
    try:
        input_size = tf.constant(input_size, dtype=tf.float32)
    except TypeError:
        pass
    try:
        input_size = tf.to_float(input_size)
    except TypeError:
        pass
    return sample_coords, input_size

@tf.RegisterGradient('FloorMod')
def _floormod_grad(op, grad):
    return [None, None]

SUPPORTED_INTERPOLATION = {'BSPLINE', 'LINEAR', 'NEAREST', 'IDW'}

SUPPORTED_BOUNDARY = {
    'ZERO': _boundary_replicate,
    'REPLICATE': _boundary_replicate,
    'CIRCULAR': _boundary_circular,
    'SYMMETRIC': _boundary_symmetric}

SUPPORTED_INPUT_DTYPE = {tf.float32}
<|endoftext|>


<commit_before>from functools import wraps
import requests

class OutpanException(Exception):
    """Exception raised when a requests fails."""

def check_request_status(func):
    """Decorator for OutpanAPI method to check if an error occured.

    Args:
        func -- the function to be decorated
    """
    @wraps(func)
    def decorated(*args, **kwargs):
        response = func(*args, **kwargs)
        if not response.content:
            # Some method return an empty string we just return None
            return None
        try:
            data = response.json()
        except ValueError:
            # We couldn't decode a json object we just return the
            # response object
            return response
        else:
            # We raise if an error occurred, if not we return the json data
            if "error" in data:
                raise OutpanException("%(message)s - code: %(code)s"
                                      % data["error"])
            return data
    return decorated

class OutpanApi(object):
    """Access the Outpan API.

    Usage:
        from outpan import OutpanAPI
        api = OutpanAPI(<you_api_key>)
        api.get_product("0078915030900")
    """

    _API_URL = "http://www.outpan.com/api"

    def __init__(self, api_key):
        """
        Args:
            api_key -- the api key provided by outpan when you register
        """
        self._api_key = api_key

    def _get_params(self, params):
        """Returns the given parameters extend with the api key parameter.

        Args:
            params -- parameters of the request you want to extend
        """
        params.update({"apikey": self._api_key})
        return params

    def _get_url(self, resource):
        """Return the full URL for the given resource

        Args:
            resource -- path to the resource you want to query
        """
        return "%s/%s" % (self.__class__._API_URL, resource)

    @check_request_status
    def get_product(self, barcode):
        """Returns the product data specified by the barcode.

        Args:
            barcode -- the barcode you are looking for
        Returns:
            A dictionary contains the product data. It could be mostly empty
            if outpan doesn't have data for the product
        """
        params = self._get_params({"barcode": barcode})
        full_url = self._get_url("get-product.php")
        return requests.get(full_url, params=params)

    @check_request_status
    def add_edit_product_name(self, barcode, name):
        """Add or Edit the name of the product specify by the barcode.

        Args:
            barcode -- the barcode of the product you want to add/edit
            name -- name of the product you want to add/edit
        Note:
            Whether the barcode has already a name associateed with it or not,
            it will be replaced with the new name submitted by the API request.
            If the barcode exists the name will be replaced.
        Returns:
            Because the content of the request is empty the decorator used on
            this method will return None
        """
        params = self._get_params({"barcode": barcode, "name": name})
        full_url = self._get_url("edit-name.php")
        return requests.get(full_url, params=params)

    @check_request_status
    def add_edit_product_attribute(self, barcode, attr_name, attr_value):
        """Add or edit an attribute to the product defined by the barcode.

        Args:
            barcode -- barcode of the object you want to edit
            attr_name -- name of the attribute to add/edit
            attr_value -- value of the attribute to add/edit
        Note:
            If the attribute already exists its value will be replaced
        """
        params = self._get_params({"barcode": barcode, "attr_name": attr_name,
                                   "attr_value": attr_value})
        full_url = self._get_url("edit-attr.php")
        return requests.get(full_url, params=params)

<commit_msg>Fix typos in comments<commit_after>from functools import wraps
import requests

class OutpanException(Exception):
    """Exception raised when a requests fails."""

def check_request_status(func):
    """Decorator for OutpanAPI method to check if an error occured.

    Args:
        func -- the function to be decorated
    """
    @wraps(func)
    def decorated(*args, **kwargs):
        response = func(*args, **kwargs)
        if not response.content:
            # Some method return an empty string we just return None
            return None
        try:
            data = response.json()
        except ValueError:
            # We couldn't decode a json object we just return the
            # response object
            return response
        else:
            # We raise if an error occurred, if not we return the json data
            if "error" in data:
                raise OutpanException("%(message)s - code: %(code)s"
                                      % data["error"])
            return data
    return decorated

class OutpanApi(object):
    """Access the Outpan API.

    Usage:
        from outpan import OutpanAPI
        api = OutpanAPI(<you_api_key>)
        api.get_product("0078915030900")
    """

    _API_URL = "http://www.outpan.com/api"

    def __init__(self, api_key):
        """
        Args:
            api_key -- the api key provided by outpan when you register
        """
        self._api_key = api_key

    def _get_params(self, params):
        """Returns the given parameters extended with the api key parameter.

        Args:
            params -- parameters of the request you want to extend
        """
        params.update({"apikey": self._api_key})
        return params

    def _get_url(self, resource):
        """Return the full URL for the given resource

        Args:
            resource -- path to the resource you want to query
        """
        return "%s/%s" % (self.__class__._API_URL, resource)

    @check_request_status
    def get_product(self, barcode):
        """Returns the product data specified by the barcode.

        Args:
            barcode -- the barcode you are looking for
        Returns:
            A dictionary containing the product data. It could be mostly empty
            if outpan doesn't have data for the product, it is up to the caller
            to verify the data
        """
        params = self._get_params({"barcode": barcode})
        full_url = self._get_url("get-product.php")
        return requests.get(full_url, params=params)

    @check_request_status
    def add_edit_product_name(self, barcode, name):
        """Add or Edit the name of the product specify by the barcode.

        Args:
            barcode -- the barcode of the product you want to add/edit
            name -- name of the product you want to add/edit
        Note:
            Whether the barcode has already a name associateed with it or not,
            it will be replaced with the new name submitted by the API request.
            If the barcode exists the name will be replaced.
        Returns:
            Because the content of the request is empty the decorator used on
            this method will return None
        """
        params = self._get_params({"barcode": barcode, "name": name})
        full_url = self._get_url("edit-name.php")
        return requests.get(full_url, params=params)

    @check_request_status
    def add_edit_product_attribute(self, barcode, attr_name, attr_value):
        """Add or edit an attribute to the product defined by the barcode.

        Args:
            barcode -- barcode of the object you want to edit
            attr_name -- name of the attribute to add/edit
            attr_value -- value of the attribute to add/edit
        Note:
            If the attribute already exists its value will be replaced
        Returns:
            Because the content of the request is empty the decorated used on
            this method will return None
        """
        params = self._get_params({"barcode": barcode, "attr_name": attr_name,
                                   "attr_value": attr_value})
        full_url = self._get_url("edit-attr.php")
        return requests.get(full_url, params=params)

<|endoftext|>


<commit_before>""" Dynamic C++ bindings generator.
"""

import sys, string

### helper to get the version number from root-config
def get_version():
   try:
      import commands
      stat, output = commands.getstatusoutput("root-config --version")
      if stat == 0:
         return output
   except Exception:
      pass
   # semi-sensible default in case of failure ...
   return "6.03/XY"

### PyPy has 'cppyy' builtin (if enabled, that is)
if 'cppyy' in sys.builtin_module_names:
   _builtin_cppyy = True

   import imp
   sys.modules[ __name__ ] = \
      imp.load_module( 'cppyy', *(None, 'cppyy', ('', '', imp.C_BUILTIN) ) )
   del imp

   _thismodule = sys.modules[ __name__ ]
   _backend = _thismodule.gbl
   _thismodule._backend = _backend

   # custom behavior that is not yet part of PyPy's cppyy
   def _CreateScopeProxy( self, name ):
      return getattr( self, name )
   type(_backend).CreateScopeProxy = _CreateScopeProxy

   def _LookupCppEntity( self, name ):
      return getattr( self, name )
   type(_backend).LookupCppEntity = _LookupCppEntity

   class _Double(float): pass
   type(_backend).Double = _Double

   def _AddressOf( self, obj ):
      import array
      return array.array('L', [_thismodule.addressof( obj )] )
   type(_backend).AddressOf = _AddressOf

   del _AddressOf, _Double, _LookupCppEntity, _CreateScopeProxy

else:
   _builtin_cppyy = False

   # load PyROOT C++ extension module, special case for linux and Sun
   needsGlobal =  ( 0 <= sys.platform.find( 'linux' ) ) or\
                  ( 0 <= sys.platform.find( 'sunos' ) )
   if needsGlobal:
      # change dl flags to load dictionaries from pre-linked .so's
      dlflags = sys.getdlopenflags()
      sys.setdlopenflags( 0x100 | 0x2 )    # RTLD_GLOBAL | RTLD_NOW

   import libPyROOT as _backend

   # reset dl flags if needed
   if needsGlobal:
      sys.setdlopenflags( dlflags )
   del needsGlobal

# PyCintex tests rely on this, but they should not:
sys.modules[ __name__ ].libPyROOT = _backend

if not _builtin_cppyy:
   _backend.SetMemoryPolicy( _backend.kMemoryStrict )

### -----------------------------------------------------------------------------
### -- metaclass helper from six ------------------------------------------------
### -- https://bitbucket.org/gutworth/six/src/8a545f4e906f6f479a6eb8837f31d03731597687/six.py?at=default#cl-800
#
# Copyright (c) 2010-2015 Benjamin Peterson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

def with_metaclass(meta, *bases):
    """Create a base class with a metaclass."""
    # This requires a bit of explanation: the basic idea is to make a dummy
    # metaclass for one level of class instantiation that replaces itself with
    # the actual metaclass.
    class metaclass(meta):

        def __new__(cls, name, this_bases, d):
            return meta(name, bases, d)
    return type.__new__(metaclass, 'temporary_class', (), {})

### -----------------------------------------------------------------------------

### template support ------------------------------------------------------------
if not _builtin_cppyy:
   class Template:
      def __init__( self, name ):
         self.__name__ = name

      def __repr__(self):
         return "<cppyy.Template '%s' object at %s>" % (self.__name__, hex(id(self)))

      def __call__( self, *args ):
         newargs = [ self.__name__[ 0 <= self.__name__.find( 'std::' ) and 5 or 0:] ]
         for arg in args:
            if type(arg) == str:
               arg = ','.join( map( lambda x: x.strip(), arg.split(',') ) )
            newargs.append( arg )
         result = _backend.MakeRootTemplateClass( *newargs )

       # special case pythonization (builtin_map is not available from the C-API)
         if 'push_back' in result.__dict__:
            def iadd( self, ll ):
               [ self.push_back(x) for x in ll ]
               return self

            result.__iadd__ = iadd

         return result

   _backend.Template = Template

#--- LoadDictionary function and aliases -----------------------------
def loadDictionary(name):
   # prepend "lib"
   if sys.platform != 'win32' and name[:3] != 'lib':
       name = 'lib' + name
   sc = _backend.gSystem.Load(name)
   if sc == -1: raise RuntimeError("Error Loading dictionary")
loadDict = loadDictionary

def load_reflection_info(name):
   sc = _backend.gSystem.Load(name)

#--- Other functions needed -------------------------------------------
if not _builtin_cppyy:
   class _ns_meta( type ):
      def __getattr__( cls, name ):
         try:
            attr = _backend.LookupCppEntity( name )
         except TypeError as e:
            raise AttributeError(str(e))
         if type(attr) is _backend.PropertyProxy:
            setattr( cls.__class__, name, attr )
            return attr.__get__(cls)
         setattr( cls, name, attr )
         return attr

   class _stdmeta( type ):
      def __getattr__( cls, name ):   # for non-templated classes in std
         try:
            klass = _backend.CreateScopeProxy( name, cls )
         except TypeError as e:
            raise AttributeError(str(e))
         setattr( cls, name, klass )
         return klass

   class _global_cpp( with_metaclass( _ns_meta ) ):
      class std( with_metaclass( _stdmeta, object ) ):
         stlclasses = ( 'complex', 'pair', \
            'deque', 'list', 'queue', 'stack', 'vector', 'map', 'multimap', 'set', 'multiset' )

         for name in stlclasses:
            locals()[ name ] = Template( 'std::%s' % name )

         string = _backend.CreateScopeProxy( 'string' )

   def addressOf( obj ) :                  # Cintex-style
      return _backend.AddressOf( obj )[0]
   addressof = _backend.addressof          # cppyy-style

else:
   _global_cpp = _backend

def Namespace( name ):
   if not name:
      return _global_cpp
   try:
      return _backend.LookupCppEntity( name )
   except AttributeError:
      pass
 # to help auto-loading, simply declare the namespace
   _backend.gInterpreter.Declare( 'namespace %s {}' % name )
   return _backend.LookupCppEntity( name )
makeNamespace = Namespace

def makeClass( name ) :
   return _backend.CreateScopeProxy( name )

def getAllClasses() :
   TClassTable = makeClass( 'TClassTable' )
   TClassTable.Init()
   classes = []
   while True :
      c = TClassTable.Next()
      if c : classes.append( c )
      else : break
   return classes

def add_smart_pointer(typename):
   """Add a smart pointer to the list of known smart pointer types.
   """
   _backend.AddSmartPtrType(typename)

#--- Global namespace and global objects -------------------------------
gbl  = _global_cpp
sys.modules['cppyy.gbl'] = gbl
NULL = 0
class double(float): pass
class short(int): pass
class long_int(int): pass
class unsigned_short(int): pass
class unsigned_int(int): pass
class unsigned_long(int): pass

#--- Copy over locally defined names ------------------------------------
if _builtin_cppyy:
   for name in dir():
      if name[0] != '_': setattr( _thismodule, name, eval(name) )

#--- Compatibility ------------------------------------------------------
if not _builtin_cppyy:
   bind_object = _backend.BindObject
   nullptr = _backend.nullptr

#--- Pythonization factories --------------------------------------------
import _pythonization
_pythonization._set_backend( _backend )
from _pythonization import *
del _pythonization

#--- CFFI style ---------------------------------------------------------
def cppdef( src ):
   _backend.gInterpreter.Declare( src )

<commit_msg>[PyROOT] Make pythonization functions accessible via cppyy.py<commit_after>""" Dynamic C++ bindings generator.
"""

import sys, string

### helper to get the version number from root-config
def get_version():
   try:
      import commands
      stat, output = commands.getstatusoutput("root-config --version")
      if stat == 0:
         return output
   except Exception:
      pass
   # semi-sensible default in case of failure ...
   return "6.03/XY"

### PyPy has 'cppyy' builtin (if enabled, that is)
if 'cppyy' in sys.builtin_module_names:
   _builtin_cppyy = True

   import imp
   sys.modules[ __name__ ] = \
      imp.load_module( 'cppyy', *(None, 'cppyy', ('', '', imp.C_BUILTIN) ) )
   del imp

   _thismodule = sys.modules[ __name__ ]
   _backend = _thismodule.gbl
   _thismodule._backend = _backend

   # custom behavior that is not yet part of PyPy's cppyy
   def _CreateScopeProxy( self, name ):
      return getattr( self, name )
   type(_backend).CreateScopeProxy = _CreateScopeProxy

   def _LookupCppEntity( self, name ):
      return getattr( self, name )
   type(_backend).LookupCppEntity = _LookupCppEntity

   class _Double(float): pass
   type(_backend).Double = _Double

   def _AddressOf( self, obj ):
      import array
      return array.array('L', [_thismodule.addressof( obj )] )
   type(_backend).AddressOf = _AddressOf

   del _AddressOf, _Double, _LookupCppEntity, _CreateScopeProxy

else:
   _builtin_cppyy = False

   # load PyROOT C++ extension module, special case for linux and Sun
   needsGlobal =  ( 0 <= sys.platform.find( 'linux' ) ) or\
                  ( 0 <= sys.platform.find( 'sunos' ) )
   if needsGlobal:
      # change dl flags to load dictionaries from pre-linked .so's
      dlflags = sys.getdlopenflags()
      sys.setdlopenflags( 0x100 | 0x2 )    # RTLD_GLOBAL | RTLD_NOW

   import libPyROOT as _backend

   # reset dl flags if needed
   if needsGlobal:
      sys.setdlopenflags( dlflags )
   del needsGlobal

# PyCintex tests rely on this, but they should not:
sys.modules[ __name__ ].libPyROOT = _backend

if not _builtin_cppyy:
   _backend.SetMemoryPolicy( _backend.kMemoryStrict )

### -----------------------------------------------------------------------------
### -- metaclass helper from six ------------------------------------------------
### -- https://bitbucket.org/gutworth/six/src/8a545f4e906f6f479a6eb8837f31d03731597687/six.py?at=default#cl-800
#
# Copyright (c) 2010-2015 Benjamin Peterson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

def with_metaclass(meta, *bases):
    """Create a base class with a metaclass."""
    # This requires a bit of explanation: the basic idea is to make a dummy
    # metaclass for one level of class instantiation that replaces itself with
    # the actual metaclass.
    class metaclass(meta):

        def __new__(cls, name, this_bases, d):
            return meta(name, bases, d)
    return type.__new__(metaclass, 'temporary_class', (), {})

### -----------------------------------------------------------------------------

### template support ------------------------------------------------------------
if not _builtin_cppyy:
   class Template:
      def __init__( self, name ):
         self.__name__ = name

      def __repr__(self):
         return "<cppyy.Template '%s' object at %s>" % (self.__name__, hex(id(self)))

      def __call__( self, *args ):
         newargs = [ self.__name__[ 0 <= self.__name__.find( 'std::' ) and 5 or 0:] ]
         for arg in args:
            if type(arg) == str:
               arg = ','.join( map( lambda x: x.strip(), arg.split(',') ) )
            newargs.append( arg )
         result = _backend.MakeRootTemplateClass( *newargs )

       # special case pythonization (builtin_map is not available from the C-API)
         if 'push_back' in result.__dict__:
            def iadd( self, ll ):
               [ self.push_back(x) for x in ll ]
               return self

            result.__iadd__ = iadd

         return result

   _backend.Template = Template

#--- LoadDictionary function and aliases -----------------------------
def loadDictionary(name):
   # prepend "lib"
   if sys.platform != 'win32' and name[:3] != 'lib':
       name = 'lib' + name
   sc = _backend.gSystem.Load(name)
   if sc == -1: raise RuntimeError("Error Loading dictionary")
loadDict = loadDictionary

def load_reflection_info(name):
   sc = _backend.gSystem.Load(name)

#--- Other functions needed -------------------------------------------
if not _builtin_cppyy:
   class _ns_meta( type ):
      def __getattr__( cls, name ):
         try:
            attr = _backend.LookupCppEntity( name )
         except TypeError as e:
            raise AttributeError(str(e))
         if type(attr) is _backend.PropertyProxy:
            setattr( cls.__class__, name, attr )
            return attr.__get__(cls)
         setattr( cls, name, attr )
         return attr

   class _stdmeta( type ):
      def __getattr__( cls, name ):   # for non-templated classes in std
         try:
            klass = _backend.CreateScopeProxy( name, cls )
         except TypeError as e:
            raise AttributeError(str(e))
         setattr( cls, name, klass )
         return klass

   class _global_cpp( with_metaclass( _ns_meta ) ):
      class std( with_metaclass( _stdmeta, object ) ):
         stlclasses = ( 'complex', 'pair', \
            'deque', 'list', 'queue', 'stack', 'vector', 'map', 'multimap', 'set', 'multiset' )

         for name in stlclasses:
            locals()[ name ] = Template( 'std::%s' % name )

         string = _backend.CreateScopeProxy( 'string' )

   def addressOf( obj ) :                  # Cintex-style
      return _backend.AddressOf( obj )[0]
   addressof = _backend.addressof          # cppyy-style

else:
   _global_cpp = _backend

def Namespace( name ):
   if not name:
      return _global_cpp
   try:
      return _backend.LookupCppEntity( name )
   except AttributeError:
      pass
 # to help auto-loading, simply declare the namespace
   _backend.gInterpreter.Declare( 'namespace %s {}' % name )
   return _backend.LookupCppEntity( name )
makeNamespace = Namespace

def makeClass( name ) :
   return _backend.CreateScopeProxy( name )

def getAllClasses() :
   TClassTable = makeClass( 'TClassTable' )
   TClassTable.Init()
   classes = []
   while True :
      c = TClassTable.Next()
      if c : classes.append( c )
      else : break
   return classes

def add_smart_pointer(typename):
   """Add a smart pointer to the list of known smart pointer types.
   """
   _backend.AddSmartPtrType(typename)

#--- Global namespace and global objects -------------------------------
gbl  = _global_cpp
sys.modules['cppyy.gbl'] = gbl
NULL = 0
class double(float): pass
class short(int): pass
class long_int(int): pass
class unsigned_short(int): pass
class unsigned_int(int): pass
class unsigned_long(int): pass

#--- Copy over locally defined names ------------------------------------
if _builtin_cppyy:
   for name in dir():
      if name[0] != '_': setattr( _thismodule, name, eval(name) )

#--- Compatibility ------------------------------------------------------
if not _builtin_cppyy:
   bind_object = _backend.BindObject
   nullptr = _backend.nullptr

#--- Pythonization factories --------------------------------------------
import _pythonization
py = _pythonization
_pythonization._set_backend( _backend )
from _pythonization import *
del _pythonization

#--- CFFI style ---------------------------------------------------------
def cppdef( src ):
   _backend.gInterpreter.Declare( src )

<|endoftext|>


<commit_before># Copyright 2018 Google LLC
#
# 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.

"""This script is used to synthesize generated parts of this library."""
import re

from synthtool.languages import python

import synthtool as s
import synthtool.gcp as gcp
import logging

logging.basicConfig(level=logging.DEBUG)

common = gcp.CommonTemplates()

default_version = "v1"

for library in s.get_staging_dirs(default_version):
    excludes = [
        "README.rst",
        "docs/index.rst",
        "setup.py",
        "scripts/fixup_documentai_v*",  # this library was always generated with the microgenerator
    ]

    s.move(library, excludes=excludes)

s.remove_staging_dirs()

# ----------------------------------------------------------------------------
# Add templated files
# ----------------------------------------------------------------------------
templated_files = common.py_library(
    cov_level=99, microgenerator=True, samples=False, # set to true if there are samples
)

s.move(
    templated_files,
    excludes=[".coveragerc"],  # microgenerator has a good .coveragerc file
)

python.py_samples(skip_readmes=True)

s.shell.run(["nox", "-s", "blacken"], hide_output=False)

# ----------------------------------------------------------------------------
# Main Branch migration
# ----------------------------------------------------------------------------

s.replace(
  "*.rst",
  "master",
  "main"
)

s.replace(
  "README.rst",
  "google-cloud-python/blob/main/README.rst",
  "google-cloud-python/blob/master/README.rst"
)

s.replace(
  "CONTRIBUTING.rst",
  "kubernetes/community/blob/main",
  "kubernetes/community/blob/master"
)

s.replace(
  "docs/conf.py",
  "master",
  "main"
)

s.replace(
  "docs/conf.py",
  "main_doc",
  "root_doc"
)

s.replace(
  ".kokoro/*",
  "master",
  "main"
)

<commit_msg>chore: revert owlbot main branch templates (#207)<commit_after># Copyright 2018 Google LLC
#
# 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.

"""This script is used to synthesize generated parts of this library."""
import re

from synthtool.languages import python

import synthtool as s
import synthtool.gcp as gcp
import logging

logging.basicConfig(level=logging.DEBUG)

common = gcp.CommonTemplates()

default_version = "v1"

for library in s.get_staging_dirs(default_version):
    excludes = [
        "README.rst",
        "docs/index.rst",
        "setup.py",
        "scripts/fixup_documentai_v*",  # this library was always generated with the microgenerator
    ]

    s.move(library, excludes=excludes)

s.remove_staging_dirs()

# ----------------------------------------------------------------------------
# Add templated files
# ----------------------------------------------------------------------------
templated_files = common.py_library(
    cov_level=99, microgenerator=True, samples=False, # set to true if there are samples
)

s.move(
    templated_files,
    excludes=[".coveragerc"],  # microgenerator has a good .coveragerc file
)

python.py_samples(skip_readmes=True)

s.shell.run(["nox", "-s", "blacken"], hide_output=False)

<|endoftext|>