Produce the isZombie method
497090
private function getIsZombieFunction()
    {

        // get primary key reference columns
        $zombieTests = $this->pgClass->getAttributes()->filter(
            function ($e) {
                return $e->isZombie();
            }
        )->map(
            function ($zombieCol) {
                return sprintf(
                    "( null === \$this->data['%s'] )",
                    addslashes( $zombieCol->name )
                );
            }
        );

        if( $zombieTests ) {

            $this->class->classComponents[] = new FunctionDeclaration(
                'data',
                new Sformatf( <<<'PHP'
                    /**
                     * Is a zombie object?
                     * @inheritDoc
                     */
                    public function isZombie()
                    {
                        return %s;
                    }
PHP
                    , implode( " or ", $zombieTests )
                )
            );
        }

    }
1354802
public static Set<String> buildProduces(Method method) {
		Set<String> produces = new LinkedHashSet<String>();
		Class<?> controller = method.getDeclaringClass();

		if(isAnnotated(controller, RequestMapping.class)) {
			RequestMapping requestMapping = getAnnotation(controller, RequestMapping.class);
			if(requestMapping.produces().length > 0) {
				produces.addAll(Arrays.asList(requestMapping.produces()));
			}
		}
		
		if(isAnnotated(method, RequestMapping.class)) {
			RequestMapping requestMapping = getAnnotation(method, RequestMapping.class);
			if(requestMapping.produces().length > 0) {
				produces.clear();
				produces.addAll(Arrays.asList(requestMapping.produces()));
			}
		}
		
		if(produces.isEmpty()) {
			produces.add(MediaType.APPLICATION_JSON_VALUE);
		}
		
		return produces;
	}
1318397
def run(self, mod):
        """"""
        if not mod.body:
            # Nothing to do.
            return
        # Insert some special imports at the top of the module but after any
        # docstrings and __future__ imports.
        aliases = [ast.alias(py.builtin.builtins.__name__, "@py_builtins"),
                   ast.alias("dessert.rewrite", "@dessert_ar")]
        expect_docstring = True
        pos = 0
        lineno = 0
        for item in mod.body:
            if (expect_docstring and isinstance(item, ast.Expr) and
                    isinstance(item.value, ast.Str)):
                doc = item.value.s
                if "PYTEST_DONT_REWRITE" in doc:
                    # The module has disabled assertion rewriting.
                    return
                lineno += len(doc) - 1
                expect_docstring = False
            elif (not isinstance(item, ast.ImportFrom) or item.level > 0 or
                  item.module != "__future__"):
                lineno = item.lineno
                break
            pos += 1
        imports = [ast.Import([alias], lineno=lineno, col_offset=0)
                   for alias in aliases]
        mod.body[pos:pos] = imports
        # Collect asserts.
        nodes = [mod]
        while nodes:
            node = nodes.pop()
            for name, field in ast.iter_fields(node):
                if isinstance(field, list):
                    new = []
                    for i, child in enumerate(field):
                        if isinstance(child, ast.Assert):
                            # Transform assert.
                            new.extend(self.visit(child))
                        else:
                            new.append(child)
                            if isinstance(child, ast.AST):
                                nodes.append(child)
                    setattr(node, name, new)
                elif (isinstance(field, ast.AST) and
                      # Don't recurse into expressions as they can't contain
                      # asserts.
                      not isinstance(field, ast.expr)):
                    nodes.append(field)
909416
private void generatePopulate(SQLiteDatabaseSchema schema, MethodSpec.Builder methodBuilder, boolean instance) {

		methodBuilder.beginControlFlow("try");
		methodBuilder.addStatement("instance.openWritableDatabase()");
		methodBuilder.addStatement("instance.close()");

		if ((instance && schema.configPopulatorClazz != null) || (!instance)) {
			methodBuilder.addComment("force database DDL run");
			methodBuilder.beginControlFlow("if (options.populator!=null && instance.justCreated)");
			methodBuilder.addComment("run populator only a time");
			methodBuilder.addStatement("instance.justCreated=false");

			// populator manage its connection
			// methodBuilder.beginControlFlow("try");
			// methodBuilder.addStatement("$T
			// currentDb=instance.openWritableDatabase()",
			// SQLiteDatabase.class);
			methodBuilder.addComment("run populator");
			methodBuilder.addStatement("options.populator.execute()");

			// methodBuilder.nextControlFlow("finally");
			// methodBuilder.addStatement("instance.close()");
			// methodBuilder.endControlFlow();

			methodBuilder.endControlFlow();
		}
		methodBuilder.nextControlFlow("catch($T e)", Throwable.class);
		methodBuilder.addStatement("$T.error(e.getMessage())", Logger.class);
		methodBuilder.addStatement("e.printStackTrace()");

		methodBuilder.endControlFlow();
	}
318341
def build_payload(cls, method, args):
        
        ref = str(uuid.uuid4())
        return (method, args, ref)
496434
def _GenerateNonImplementedMethod(self, method):
    
    return lambda inst, rpc_controller, request, callback: (
        self._NonImplementedMethod(method.name, rpc_controller, callback))
307786
def method_missing(method, *args, &block)
      raise Checky::Exception unless methods.include?("populate_#{method}".to_sym)
      @storage.send("#{method}=", send("populate_#{method}", *args, &block))
      @storage.checky_blocks[method.to_sym] = block if block_given?
    rescue Checky::Exception
      @self_before_instance_eval.send method, *args, &block if @self_before_instance_eval.present?
    end
837674
def make(base_classes=(), have_mt=False):
        """"""

        good_bc = ModelFactory.__fix_bases(base_classes, have_mt)
        print "Base classes are:", good_bc
        key = "".join(map(str, good_bc))
        if key in ModelFactory.__memoized:
            return ModelFactory.__memoized[key]

        cls = new.classobj('', good_bc, {'__module__': '__main__', '__doc__': None})
        ModelFactory.__memoized[key] = cls
        return cls
1079044
def _RunMethod(self, method_config, request, global_params=None,
                   upload=None, upload_config=None, download=None):
        """"""
        if upload is not None and download is not None:
            # TODO(craigcitro): This just involves refactoring the logic
            # below into callbacks that we can pass around; in particular,
            # the order should be that the upload gets the initial request,
            # and then passes its reply to a download if one exists, and
            # then that goes to ProcessResponse and is returned.
            raise exceptions.NotYetImplementedError(
                'Cannot yet use both upload and download at once')

        http_request = self.PrepareHttpRequest(
            method_config, request, global_params, upload, upload_config,
            download)

        # TODO(craigcitro): Make num_retries customizable on Transfer
        # objects, and pass in self.__client.num_retries when initializing
        # an upload or download.
        if download is not None:
            download.InitializeDownload(http_request, client=self.client)
            return

        http_response = None
        if upload is not None:
            http_response = upload.InitializeUpload(
                http_request, client=self.client)
        if http_response is None:
            http = self.__client.http
            if upload and upload.bytes_http:
                http = upload.bytes_http
            opts = {
                'retries': self.__client.num_retries,
                'max_retry_wait': self.__client.max_retry_wait,
            }
            if self.__client.check_response_func:
                opts['check_response_func'] = self.__client.check_response_func
            if self.__client.retry_func:
                opts['retry_func'] = self.__client.retry_func
            http_response = http_wrapper.MakeRequest(
                http, http_request, **opts)

        return self.ProcessHttpResponse(method_config, http_response, request)
1133570
static void generateLogForContentProviderBeginning(SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {
		if (method.getParent().isLogEnabled()) {
			methodBuilder.addStatement("$T.info($S, uri.toString())", Logger.class, "Execute " + method.jql.operationType + " for URI %s");
		}

	}
1312614
def run(self):
        
        builder = self.workflow.builder

        image = builder.image.to_str()
        # TODO: directly invoke go imagebuilder library in shared object via python module
        kwargs = dict(stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
        encoding_params = dict(encoding='utf-8', errors='replace')
        if not PY2:
            kwargs.update(encoding_params)

        allow_repo_dir_in_dockerignore(builder.df_dir)
        ib_process = subprocess.Popen(['imagebuilder', '-t', image, builder.df_dir], **kwargs)

        self.log.debug('imagebuilder build has begun; waiting for it to finish')
        output = []
        while True:
            poll = ib_process.poll()
            out = ib_process.stdout.readline()
            out = out.decode(**encoding_params) if PY2 else out
            if out:
                self.log.info('%s', out.rstrip())
                output.append(out)
            elif poll is not None:
                break

        if ib_process.returncode != 0:
            # in the case of an apparent failure, single out the last line to
            # include in the failure summary.
            err = output[-1] if output else "<imagebuilder had bad exit code but no output>"
            return BuildResult(
                logs=output,
                fail_reason="image build failed (rc={}): {}".format(ib_process.returncode, err),
            )

        image_id = builder.get_built_image_info()['Id']
        if ':' not in image_id:
            # Older versions of the daemon do not include the prefix
            image_id = 'sha256:{}'.format(image_id)

        # since we need no squash, export the image for local operations like squash would have
        self.log.info("fetching image %s from docker", image)
        output_path = os.path.join(self.workflow.source.workdir, EXPORTED_SQUASHED_IMAGE_NAME)
        try:
            # docker-py 1.x
            with open(output_path, "w") as image_file:
                image_file.write(self.tasker.d.get_image(image).data)
        except AttributeError:
            # docker-py 3.x
            with open(output_path, "wb") as image_file:
                for chunk in self.tasker.d.get_image(image):
                    image_file.write(chunk)

        img_metadata = get_exported_image_metadata(output_path, IMAGE_TYPE_DOCKER_ARCHIVE)
        self.workflow.exported_image_sequence.append(img_metadata)

        return BuildResult(logs=output, image_id=image_id, skip_layer_squash=True)
327872
def method_missing(name, *args, &block)
      result = @dataset.send(name, *args, &block)
      if result.kind_of?(Sequel::Dataset)
        new_object = clone
        new_object.send(:obj=, result)
        new_object
      else
        result
      end
    end
1011490
def _RunMethod(dev, args, extra):
    """"""
    logging.info('%s(%s)', args.method.__name__, ', '.join(args.positional))
    result = args.method(dev, *args.positional, **extra)
    if result is not None:
        if isinstance(result, io.StringIO):
            sys.stdout.write(result.getvalue())
        elif isinstance(result, (list, types.GeneratorType)):
            r = ''
            for r in result:
                r = str(r)
                sys.stdout.write(r)
            if not r.endswith('\n'):
                sys.stdout.write('\n')
        else:
            result = str(result)
            sys.stdout.write(result)
            if not result.endswith('\n'):
                sys.stdout.write('\n')
    return 0
297408
def pso(self, n_particles=10, n_iterations=10, lowerLimit=-0.2, upperLimit=0.2, threadCount=1, mpi=False, print_key='default'):
        
        init_pos = self.chain.get_args(self.chain.kwargs_data_init)
        num_param = self.chain.num_param
        lowerLimit = [lowerLimit] * num_param
        upperLimit = [upperLimit] * num_param
        if mpi is True:
            pso = MpiParticleSwarmOptimizer(self.chain, lowerLimit, upperLimit, n_particles, threads=1)
        else:
            pso = ParticleSwarmOptimizer(self.chain, lowerLimit, upperLimit, n_particles, threads=threadCount)
        if not init_pos is None:
            pso.gbest.position = init_pos
            pso.gbest.velocity = [0]*len(init_pos)
            pso.gbest.fitness, _ = self.chain.likelihood(init_pos)
        X2_list = []
        vel_list = []
        pos_list = []
        time_start = time.time()
        if pso.isMaster():
            print('Computing the %s ...' % print_key)
        num_iter = 0
        for swarm in pso.sample(n_iterations):
            X2_list.append(pso.gbest.fitness*2)
            vel_list.append(pso.gbest.velocity)
            pos_list.append(pso.gbest.position)
            num_iter += 1
            if pso.isMaster():
                if num_iter % 10 == 0:
                    print(num_iter)
        if not mpi:
            result = pso.gbest.position
        else:
            result = MpiUtil.mpiBCast(pso.gbest.position)
        kwargs_data = self.chain.update_data(result)
        if mpi is True and not pso.isMaster():
            pass
        else:
            time_end = time.time()
            print("Shifts found: ", result)
            print(time_end - time_start, 'time used for PSO', print_key)
        return kwargs_data, [X2_list, pos_list, vel_list, []]
294497
def generate_by_hash(hashcode):
    """"""
    img = Image.new(IMAGE_MODE, IMAGE_SIZE, BACKGROUND_COLOR)
    if len(hashcode) < 32:
        print ("hashcode must have lenght >= 32, %s" % hashcode)
        raise FalseHashError

    allowed = "0123456789abcdef"
    hashcheck = [c in allowed for c in hashcode]
    if False in hashcheck:
        print ("hashcode has not allowed structure %s" % hashcode)
        raise FalseHashError

    pixelmap = setup_pixelmap(hashcode)
    draw_image(pixelmap, img)
    return img
332743
protected MethodSpec.Builder generateMethodBuilder(SQLiteModelMethod method) {
		MethodSpec.Builder methodBuilder;
		if (method.hasLiveData()) {
			methodBuilder = MethodSpec.methodBuilder(method.getName() + LIVE_DATA_PREFIX).addModifiers(Modifier.PROTECTED);
		} else {
			methodBuilder = MethodSpec.methodBuilder(method.getName()).addAnnotation(Override.class).addModifiers(Modifier.PUBLIC);
		}

		return methodBuilder;
	}
224493
public function batchRun($is_hook, $method_name, array $params = NULL)
    {
        // Prevents annoying notices.
		if($params == NULL) {
			$params = array();
		}

        // We collect the results into an array.
        $results = array();
        if(!$this->modules) $this->modules = array();
        foreach($this->modules as $name => $module) {
            if(method_exists($module, $method_name)) {
                $result = call_user_func_array(array($module, $method_name), $params);
                if($is_hook) { // Hooks are pre-emptive if they return something.
                    if($result) {
                        return $result;
                    }
                } else { // Collecting
                    $results[$name] = $result;
                }
            }
		}

        return $is_hook? false : $results;
    }