Get or create a Plan.
179389
def get_or_create(cls, **kwargs):
		

		try:
			return Plan.objects.get(id=kwargs["id"]), False
		except Plan.DoesNotExist:
			return cls.create(**kwargs), True
1015469
def perform_get_or_create(self, request, *args, **kwargs):
        """"""
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        process = serializer.validated_data.get('process')
        process_input = request.data.get('input', {})

        fill_with_defaults(process_input, process.input_schema)

        checksum = get_data_checksum(process_input, process.slug, process.version)
        data_qs = Data.objects.filter(
            checksum=checksum,
            process__persistence__in=[Process.PERSISTENCE_CACHED, Process.PERSISTENCE_TEMP],
        )
        data_qs = get_objects_for_user(request.user, 'view_data', data_qs)
        if data_qs.exists():
            data = data_qs.order_by('created').last()
            serializer = self.get_serializer(data)
            return Response(serializer.data)
323539
def goal_create(self, data, **kwargs):
        ""
        api_path = "/api/v2/goals"
        return self.call(api_path, method="POST", data=data, **kwargs)
507130
def get_plan(self, plan_code):
        
        return self.client._get(self.url + 'plans/{}'.format(plan_code), headers=self.get_headers())
571737
public static function create_plan($plan) {
        global $PAGE;

        $params = self::validate_parameters(self::create_plan_parameters(), array('plan' => $plan));
        $params = $params['plan'];

        $context = context_user::instance($params['userid']);
        self::validate_context($context);
        $output = $PAGE->get_renderer('core');

        $params = (object) $params;

        $result = api::create_plan($params);
        $exporter = new plan_exporter($result, array('template' => null));
        return $exporter->export($output);
    }
923781
def set_plan(self, total):
        """"""
        self.plan = total
        if self.streaming:
            # This will only write the plan if we haven't written it
            # already but we want to check if we already wrote a
            # test out (in which case we can't just write the plan out
            # right here).
            if not self.combined_test_cases_seen:
                self._write_plan(self.stream)
        elif not self.combined:
            raise ValueError(
                "set_plan can only be used with combined or streaming output"
            )
938605
def _copy_plans(self, branch_from, turn_from, tick_from):
        """"""
        plan_ticks = self._plan_ticks
        plan_ticks_uncommitted = self._plan_ticks_uncommitted
        time_plan = self._time_plan
        plans = self._plans
        branch = self.branch
        where_cached = self._where_cached
        last_plan = self._last_plan
        turn_end_plan = self._turn_end_plan
        for plan_id in self._branches_plans[branch_from]:
            _, start_turn, start_tick = plans[plan_id]
            if start_turn > turn_from or (start_turn == turn_from and start_tick > tick_from):
                continue
            incremented = False
            for turn, ticks in list(plan_ticks[plan_id].items()):
                if turn < turn_from:
                    continue
                for tick in ticks:
                    if turn == turn_from and tick < tick_from:
                        continue
                    if not incremented:
                        self._last_plan = last_plan = last_plan + 1
                        incremented = True
                        plans[last_plan] = branch, turn, tick
                    for cache in where_cached[branch_from, turn, tick]:
                        data = cache.settings[branch_from][turn][tick]
                        value = data[-1]
                        key = data[:-1]
                        args = key + (branch, turn, tick, value)
                        if hasattr(cache, 'setdb'):
                            cache.setdb(*args)
                        cache.store(*args, planning=True)
                        plan_ticks[last_plan][turn].append(tick)
                        plan_ticks_uncommitted.append((last_plan, turn, tick))
                        time_plan[branch, turn, tick] = last_plan
                        turn_end_plan[branch, turn] = tick
141962
def get_or_create(cls, subscriber, livemode=djstripe_settings.STRIPE_LIVE_MODE):
		

		try:
			return Customer.objects.get(subscriber=subscriber, livemode=livemode), False
		except Customer.DoesNotExist:
			action = "create:{}".format(subscriber.pk)
			idempotency_key = djstripe_settings.get_idempotency_key("customer", action, livemode)
			return cls.create(subscriber, idempotency_key=idempotency_key), True
52384
def get_or_create(self, **kwargs):
        
        assert kwargs, \
                'get_or_create() must be passed at least one keyword argument'
        defaults = kwargs.pop('defaults', {})
        lookup = kwargs.copy()
        #TODO: check fields
        try:
            return self.get(**lookup), False
        except self.model.DoesNotExist:
            params = dict([(k, v) for k, v in kwargs.items() if '__' not in k])
            params.update(defaults)
            obj = self.model(**params)
            meta = obj.get_meta()
            meta.connection = get_es_connection(self.es_url, self.es_kwargs)
            meta.index=self.index
            meta.type=self.type
            obj.save(force=True)
            return obj, True
369977
def get(self):
        """"""
        # set 'loaded' first ... so if we have to bail, we know we tried.
        self.loaded = True
        if not hasattr(self.manager, "get"):
            return
        if not self.get_details:
            return
        new = self.manager.get(self)
        if new:
            self._add_details(new._info)
753757
def create(provider, names, opts=None, **kwargs):
    '''
    
    '''
    client = _get_client()
    if isinstance(opts, dict):
        client.opts.update(opts)
    info = client.create(provider, names, **kwargs)
    return info
732281
def _create_service(self, parameters={}, **kwargs):
        
        logging.debug("_create_service()")
        logging.debug(str.join(',', [self.service_name, self.plan_name,
            self.name, str(parameters)]))

        return self.service.create_service(self.service_name, self.plan_name,
                self.name, parameters, **kwargs)
214432
def get_or_create(self, um_from_user, um_to_user, message):
        
        created = False
        try:
            contact = self.get(Q(um_from_user=um_from_user, um_to_user=um_to_user) |
                               Q(um_from_user=um_to_user, um_to_user=um_from_user))

        except self.model.DoesNotExist:
            created = True
            contact = self.create(um_from_user=um_from_user,
                                  um_to_user=um_to_user,
                                  latest_message=message)

        return (contact, created)
84331
def get_or_create(self, request, *args, **kwargs):
        """"""
        kwargs['get_or_create'] = True
        return self.create(request, *args, **kwargs)
1034376
public CompiledPlan plan() throws PlanningErrorException {
        // reset any error message
        m_recentErrorMsg = null;

        // what's going to happen next:
        //  If a parameterized statement exists, try to make a plan with it
        //  On success return the plan.
        //  On failure, try the plan again without parameterization

        if (m_paramzInfo != null) {
            try {
                // compile the plan with new parameters
                CompiledPlan plan = compileFromXML(m_paramzInfo.getParameterizedXmlSQL(),
                                                   m_paramzInfo.getParamLiteralValues());
                if (plan != null) {
                    if (plan.extractParamValues(m_paramzInfo)) {
                        return plan;
                    }
                }
                else if (DEBUGGING_STATIC_MODE_TO_RETRY_ON_ERROR) {
                    compileFromXML(m_paramzInfo.getParameterizedXmlSQL(),
                                   m_paramzInfo.getParamLiteralValues());
                }
                // fall through to try replan without parameterization.
            }
            catch (Exception | StackOverflowError e) {
                // ignore any errors planning with parameters
                // fall through to re-planning without them
                m_hasExceptionWhenParameterized = true;

                // note, expect real planning errors ignored here to be thrown again below
                m_recentErrorMsg = null;
                m_partitioning.resetAnalysisState();
            }
        }

        // if parameterization isn't requested or if it failed, plan here
        CompiledPlan plan = compileFromXML(m_xmlSQL, null);
        if (plan == null) {
            if (DEBUGGING_STATIC_MODE_TO_RETRY_ON_ERROR) {
                plan = compileFromXML(m_xmlSQL, null);
            }
            throw new PlanningErrorException(m_recentErrorMsg);
        }

        return plan;
    }
611555
def plans
      service = args.shift
      raise CommandFailed.new("Missing add-on service") if service.nil?

      service = get_service!(service)
      display_header("#{service['human_name']} Plans")

      plans = get_plans(:service => service['id'])

      plans = plans.sort_by { |p| [(!p['default']).to_s, p['price']['cents']] }.map do |plan|
        {
          "default"    => ('default' if plan['default']),
          "name"       => plan["name"],
          "human_name" => plan["human_name"],
          "price"      => format_price(plan["price"])
        }
      end

      display_table(plans, %w[default name human_name price], [nil, 'Slug', 'Name', 'Price'])
    end
464473
def plan
      # si el usuario no tiene plan_id en su modelo, se le asigna el plan_id seleccionado en el formulario
      # recordar que ese plan_id llega en los params del contexto y por tanto tenemos acceso a el
      # como variable de clase @plan_id

      if @current_user.plan_id.nil?
        if @plan_id.nil?
          raise StandardError, 'Error creando plan, plan_id null'
        end
        # se almacena en el user
        @current_user.update_attribute(:plan_id, @plan_id)
        # despues de tenerlo almacenado en la bd, llamamos nuevamente este metodo plan
        plan
      else
        # el usuario tiene un plan_id asignado, se le actualiza el plan_id en caso de que haya seleccionado uno
        # diferente al que tiene actualmente
        @current_user.update_attribute(:plan_id, @plan_id)
        # obtener informacion del plan de la BD
        plan_db = @current_user.plan
        #
        # NOTA: los planes deben tener un plan_code es OBLIGATORIO para el buen funcionamiento
        #
        if plan_db.plan_code.nil? || plan_db.plan_code.empty?
          raise StandardError, 'Error creando plan, code null'
        end
        # con el plan_code lo buscamos en payu
        plan_payu = PayuLatam::Plan.new(plan_db.plan_code)
        # si existe?
        if plan_payu.success?
          # llenar la variable plan con la instancia de clase PayuLatam:Plan
          @plan = plan_payu
        else
          # si no existe en pyu, crearlo con el metodo del modelo plan
          plan_db.create_payu_plan
          # llamado recursivo
          plan
        end
      end
    end