Question:
Executes the command.

@param InputInterface  $input  An InputInterface instance
@param OutputInterface $output An OutputInterface instance

@throws \RuntimeException

protected function execute(InputInterface $input, OutputInterface $output)
    {
        $questionHelper = $this->getQuestionHelper();

        if ($input->isInteractive()) {
            $confirmationQuestion = new ConfirmationQuestion($questionHelper->getQuestion('Do you confirm generation', 'yes', '?'), true);
            if (!$questionHelper->ask($input, $output, $confirmationQuestion)) {
                $output->writeln('<error>Command aborted</error>');

                return 1;
            }
        }

        GeneratorUtils::ensureOptionsProvided($input, array('namespace', 'dir'));

        $namespace = Validators::validateBundleNamespace($input->getOption('namespace'));
        if (!$bundle = $input->getOption('bundle-name')) {
            $bundle = strtr($namespace, array('\\' => ''));
        }
        $bundle = Validators::validateBundleName($bundle);
        $dir = $this::validateTargetDir($input->getOption('dir'), $bundle, $namespace);
        $format = 'yml';

        $questionHelper->writeSection($output, 'Bundle generation');

        if (!$this
            ->getContainer()
            ->get('filesystem')
            ->isAbsolutePath($dir)
        ) {
            $dir = getcwd() . '/' . $dir;
        }

        $generator = $this->getGenerator($this->getApplication()->getKernel()->getBundle('KunstmaanGeneratorBundle'));
        $generator->generate($namespace, $bundle, $dir, $format);

        $output->writeln('Generating the bundle code: <info>OK</info>');

        $errors = array();
        $runner = $questionHelper->getRunner($output, $errors);

        // check that the namespace is already autoloaded
        $runner($this->checkAutoloader($output, $namespace, $bundle));

        // register the bundle in the Kernel class
        $runner($this->updateKernel($questionHelper, $input, $output, $this->getContainer()->get('kernel'), $namespace, $bundle));

        // routing
        $runner($this->updateRouting($questionHelper, $input, $output, $bundle, $format));

        $questionHelper->writeGeneratorSummary($output, $errors);
    }

public static void main( String [] args )
    {
        if ( args.length > 0 ) {
            String filename = args[0];

            String [] bshArgs;
            if ( args.length > 1 ) {
                bshArgs = new String [ args.length -1 ];
                System.arraycopy( args, 1, bshArgs, 0, args.length-1 );
            } else
                bshArgs = new String [0];

            try {
                Interpreter interpreter = new Interpreter();
                interpreter.setu( "bsh.args", bshArgs );
                Object result =
                    interpreter.source( filename, interpreter.globalNameSpace );
                if ( result instanceof Class )
                    try {
                        invokeMain( (Class<?>)result, bshArgs );
                    } catch ( Exception e )
                    {
                        Object o = e;
                        if ( e instanceof InvocationTargetException )
                            o = e.getCause();
                        System.err.println(
                            "Class: "+result+" main method threw exception:"+o);
                    }
            } catch ( FileNotFoundException e ) {
                System.err.println("File not found: "+e);
            } catch ( TargetError e ) {
                System.err.println("Script threw exception: "+e);
                if ( e.inNativeCode() )
                    e.printStackTrace( DEBUG.get(), System.err );
            } catch ( EvalError e ) {
                System.err.println("Evaluation Error: "+e);
            } catch ( IOException e ) {
                System.err.println("I/O Error: "+e);
            }
        } else {
            @SuppressWarnings("resource")
            Interpreter interpreter =
            new Interpreter(new CommandLineReader(
                new FileReader(System.in)),
                System.out, System.err, true );
            interpreter.run();
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get all file names in a given app's directory
@param appName
@param dir
@returns {*}

function getAppFileNames(appName, dir) {
    var partialsDir = this.pancakes.getRootDir() + delim + 'app' + delim + appName + delim + dir;
    return fs.existsSync(partialsDir) ? fs.readdirSync(partialsDir) : [];
}

public function parse($url, $cleanup = true)
  {
    if ($cleanup) {
      $this->removeArguments();
      $this->removeParameters();
      $this->setFileName(false);
      $this->setHost('localhost');
    }

    if (is_array($url)) {
      $this->addParameters($url);
    } else {

      if ($this->checkSchemeExists($url)) {
        $a = $this->mbParseUrl($url);

        if (!empty($a['host'])) {
          $this->setHost($a['host']);
        }
        if (!empty($a['scheme'])) {
          $this->setScheme($a['scheme']);
        }

        $url = $a['path'];
      }
      $url = trim($url, '/');
      $arr = array_filter(explode('/', urldecode($url)));

      if (empty($arr)) {
        return false;
      }

      $total = count($arr);
      foreach ($arr as $i => $str) {
        if (strpos($str, ':')) {
          $a = explode(':', $str, 2);
          if (count($a) == 2) {
            $this->addParameter($a[0], $a[1]);
          }
        } else {
          if ($total == $i + 1 && strpos($str, '.')) {
            $this->setFileName($str);
          } else {
            $this->addArgument($str);
          }
        }
      }
    }

    return $this;
  }

Instruction: Given a code description, retrieve the corresponding code.


Question: // Init initializes Encoder according to the codes provided.

func (pe *Encoder) Init(codes PrefixCodes) {
	// Handle special case trees.
	if len(codes) <= 1 {
		switch {
		case len(codes) == 0: // Empty tree (should error if used later)
			*pe = Encoder{chunks: pe.chunks[:0], NumSyms: 0}
		case len(codes) == 1 && codes[0].Len == 0: // Single code tree (bit-length of zero)
			pe.chunks = append(pe.chunks[:0], codes[0].Val<<countBits|0)
			*pe = Encoder{chunks: pe.chunks[:1], NumSyms: 1}
		default:
			panic("invalid codes")
		}
		return
	}
	if internal.Debug && !sort.IsSorted(prefixCodesBySymbol(codes)) {
		panic("input codes is not sorted")
	}
	if internal.Debug && !(codes.checkLengths() && codes.checkPrefixes()) {
		panic("detected incomplete or overlapping codes")
	}

	// Enough chunks to contain all the symbols.
	numChunks := 1
	for n := len(codes) - 1; n > 0; n >>= 1 {
		numChunks <<= 1
	}
	pe.NumSyms = uint32(len(codes))

retry:
	// Allocate and reset chunks.
	pe.chunks = allocUint32s(pe.chunks, numChunks)
	pe.chunkMask = uint32(numChunks - 1)
	for i := range pe.chunks {
		pe.chunks[i] = 0 // Logic below relies on zero value as uninitialized
	}

	// Insert each symbol, checking that there are no conflicts.
	for _, c := range codes {
		if pe.chunks[c.Sym&pe.chunkMask] > 0 {
			// Collision found our "hash" table, so grow and try again.
			numChunks <<= 1
			goto retry
		}
		pe.chunks[c.Sym&pe.chunkMask] = c.Val<<countBits | c.Len
	}
}

def run(self):

        for line in self.incoming:
            message = loads(line)
            result = self._evaluate(message)
            if result is self._SKIP:
                continue
            self.output.write(dumps(result, cls=_DatetimeJSONEncoder) + b"\n")

Instruction: Given a code description, retrieve the corresponding code.


Question: // GetEntries implements the ZooKeeper Client interface.

func (c *client) GetEntries(path string) ([]string, <-chan zk.Event, error) {
	// retrieve list of child nodes for given path and add watch to path
	znodes, _, eventc, err := c.ChildrenW(path)

	if err != nil {
		return nil, eventc, err
	}

	var resp []string
	for _, znode := range znodes {
		// retrieve payload for child znode and add to response array
		if data, _, err := c.Get(path + "/" + znode); err == nil {
			resp = append(resp, string(data))
		}
	}
	return resp, eventc, nil
}

def zendesk_ticket(self):

        if self.api and self.zendesk_ticket_id:
            return self.api._get_zendesk_ticket(self.zendesk_ticket_id)

Instruction: Given a code description, retrieve the corresponding code.


Question: Renders the project

def render!
      cmd = melt melt_args(options.merge(outfile: outfile)).join(' ')
      puts "Run: #{cmd}"
      puts

      run(cmd) do |_stdin, _stdout, stderr|
        stderr.each("\r") do |line|
          STDOUT.write "\r#{line}"
        end
      end
    end

function DisplayOTron(model) {
    if (!(this instanceof DisplayOTron)) {
        return new DisplayOTron(model);
    }

    this.model = model;

    this.pythonProcess = null;

    this.reset();

    events.EventEmitter.call(this);
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Return operation failed result, and logs with an info level

@param string|array $message
@param int $code
@param string $level
@return array

public function err($message, $code = -1, $level = 'info')
    {
        return $this->ret->err($message, $code, $level);
    }

public function err($text = '', $nl = true)
	{
		fwrite(STDERR, $this->processor->process($text) . ($nl ? "\n" : null));

		return $this;
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Adds the simple indices to the fields directly and returns the indices for multiple values.
@param DOMXPath $rootPath
@return array
@todo   Primary missing; Problems with m:ns.

protected function addIndicesToFields(DOMXPath $rootPath)
    {
        $fetchedNodes = [];
        $fields = $this->getFields();
        $multipleIndices = [];
        $idMap = array_flip(
            array_map(
                function (MigrationField $field) {
                    return $field->getId();
                },
                $fields
            )
        );

        /** @var MigrationField $field */
        foreach ($fields as $name => $field) {
            $usedId = $field->getId();
            $indexNodes = $rootPath->query(
                './value[@content-struct-name="db.mysql.Index" and @key="indices"]/' .
                'value[@type="object" and @struct-name="db.mysql.Index"]//' .
                'value[@type="object" and @struct-name="db.mysql.IndexColumn"]//' .
                'link[@type="object" and @struct-name="db.Column" and @key="referencedColumn" ' .
                'and text() = "' . $usedId . '"]/' .
                '../' .
                '../' .
                '..'
            );

            if ($indexNodes && $indexNodes->length) {
                $fks = $this->getForeignKeysForField($field, $rootPath);

                /** @var \DOMNode $indexNode */
                foreach ($indexNodes as $indexNode) {
                    if (in_array($nodeId = $indexNode->attributes->getNamedItem('id')->nodeValue, $fetchedNodes)) {
                        continue;
                    } // if

                    $fetchedNodes[] = $nodeId;

                    $indexColumns = $rootPath->query(
                        './/link[@type="object" and @struct-name="db.Column" and @key="referencedColumn"]',
                        $indexNode
                    );

                    $isSingleColumn = $indexColumns && $indexColumns->length <= 1;
                    $genericCall = !$isSingleColumn ? new Base() : null;

                    if ($rootPath->evaluate(
                        'boolean(./value[@type="int" and @key="unique" and number() = 1])',
                        $indexNode
                    )
                    ) {
                        if ($isSingleColumn) {
                            $field->addAdditionalOption('unique');
                        } // if
                        else {
                            $genericMethod = 'unique';
                        } // else
                    } // if

                    $hasIndex = $rootPath->evaluate(
                        'boolean(./value[@type="string" and @key="indexType" and text() = "INDEX"])',
                        $indexNode
                    );

                    if ($hasIndex && (!$fks || !$fks->length)) {
                        if ($isSingleColumn) {
                            $field->addAdditionalOption('index');
                        } // if
                        else {
                            $genericMethod = 'index';
                        } // else
                    } // if

                    if ($rootPath->evaluate(
                        'boolean(./value[@type="string" and @key="indexType" and text() = "PRIMARY"])',
                        $indexNode
                    )
                    ) {
                        if ($isSingleColumn) {
                            $field->addAdditionalOption('primary');
                        } // if
                        else {
                            $genericMethod = 'primary';
                        } // else
                    } // if

                    if ($genericCall && $genericMethod) {
                        $genericParams = [];
                        /** @var DOMNode $column */
                        foreach ($indexColumns as $column) {
                            $genericParams[] = $idMap[$column->nodeValue];
                        } // foreach

                        $this->addGenericCall(call_user_func_array(
                            [$genericCall, $genericMethod],
                            $genericParams ? [$genericParams] : []
                        ));
                    }
                }
            }
        }

        return array_unique($multipleIndices);
    }

public function fetch(ElementVersion $elementVersion, $language, TreeNodeInterface $node = null)
    {
        /* @var $links ElementLink[] */
        $links = $this->linkManager->findBy(['elementVersion' => $elementVersion, 'language' => $language]);

        if ($node) {
            foreach ($this->linkManager->findBy(['type' => 'link-internal', 'language' => $language, 'target' => $node->getId()]) as $link) {
                $incomingLink = clone $link;
                $incomingLink->setType('link-incoming');
                $links[] = $incomingLink;
            }
        }

        $results = array();

        foreach ($links as $link) {
            $data = [
                'id' => $link->getId(),
                'iconCls' => 'p-element-component-icon',
                'language' => $link->getLanguage(),
                'type' => $link->getType(),
                'title' => $link->getField(),
                'content' => $link->getTarget(),
                'link' => [],
                'raw' => $link->getTarget(),
                'payload' => [],
            ];

            $results[] = $this->linkTransformer->transform($link, $data);
        }

        return $results;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
View method

@param string|null $id Cms Term Relation id.
@return void
@throws \Cake\Network\Exception\NotFoundException When record not found.

public function view($id = null)
    {
        $cmsTermRelation = $this->CmsTermRelation->get($id, [
            'contain' => ['CmsTermTaxonomy', 'CmsContent']
        ]);
        $this->set('cmsTermRelation', $cmsTermRelation);
        $this->set('_serialize', ['cmsTermRelation']);
    }

def get_participant(participant_id):
    """"""
    try:
        ppt = models.Participant.query.filter_by(id=participant_id).one()
    except NoResultFound:
        return error_response(
            error_type="/participant GET: no participant found",
            status=403)

    # return the data
    return success_response(field="participant",
                            data=ppt.__json__(),
                            request_type="participant get")

Instruction: Given a code description, retrieve the corresponding code.


Question:
{@inheritDoc}

@see java.nio.file.spi.FileSystemProvider#newFileChannel(java.nio.file.Path, java.util.Set,
java.nio.file.attribute.FileAttribute<?>[])

@Override
    public FileChannel newFileChannel(Path path, Set<? extends OpenOption> options,
            FileAttribute<?>... attrs) throws IOException {
        return new ShrinkWrapFileChannel(newByteChannel(path, options, attrs));
    }

def _check_file_io(self):

        folder = 'Model' + str(self.flags['RUN_NUM']) + '/'
        folder_restore = 'Model' + str(self.flags['MODEL_RESTORE']) + '/'
        self.flags['RESTORE_DIRECTORY'] = self.flags['SAVE_DIRECTORY'] + self.flags[
            'MODEL_DIRECTORY'] + folder_restore
        self.flags['LOGGING_DIRECTORY'] = self.flags['SAVE_DIRECTORY'] + self.flags[
            'MODEL_DIRECTORY'] + folder
        self.make_directory(self.flags['LOGGING_DIRECTORY'])
        sys.stdout = Logger(self.flags['LOGGING_DIRECTORY'] + 'ModelInformation.log')
        print(self.flags)

Instruction: Given a code description, retrieve the corresponding code.


Question:
@param Date $object

@return bool

public function earlierThan($object)
    {
        if (!$this->sameTypeAs($object)) {
            throw new NotMatchTypeException($this);
        }

        return !$this->equalsTo($object) && !$this->laterThan($object);
    }

protected function parseCompositeValue( $compositeValue )
	{
		$time = false;

		try
		{
			$time = new RhubarbTime( $compositeValue );
		}
		catch( \Exception $er )
		{
		}

		if( $time === false )
		{
			$this->model->hours = "";
			$this->model->minutes = "";
		}
		else
		{
			$this->model->hours = $time->format( "H" );
			$this->model->minutes = $time->format( "i" );
		}
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Send Data to APM Service

@link https://github.com/philkra/elastic-apm-laravel/issues/22
@link https://github.com/philkra/elastic-apm-laravel/issues/26

@return bool

public function send() : bool
    {
        // Is the Agent enabled ?
        if ($this->config->get('active') === false) {
            return true;
        }

        $connector = new Connector($this->config);
        $status = true;

        // Commit the Errors
        if ($this->errorsStore->isEmpty() === false) {
            $status = $status && $connector->sendErrors($this->errorsStore);
            if ($status === true) {
                $this->errorsStore->reset();
            }
        }

        // Commit the Transactions
        if ($this->transactionsStore->isEmpty() === false) {
            $status = $status && $connector->sendTransactions($this->transactionsStore);
            if ($status === true) {
                $this->transactionsStore->reset();
            }
        }

        return $status;
    }

protected function checkEntry( array $list )
	{
		if( $this->getValue( $list, 'attribute.code' ) === null ) {
			return false;
		}

		if( ( $type = $this->getValue( $list, 'product.lists.type' ) ) && !isset( $this->listTypes[$type] ) )
		{
			$msg = sprintf( 'Invalid type "%1$s" (%2$s)', $type, 'product list' );
			throw new \Aimeos\Controller\Common\Exception( $msg );
		}

		if( ( $type = $this->getValue( $list, 'attribute.type' ) ) && !isset( $this->types[$type] ) )
		{
			$msg = sprintf( 'Invalid type "%1$s" (%2$s)', $type, 'attribute' );
			throw new \Aimeos\Controller\Common\Exception( $msg );
		}

		return true;
	}

Instruction: Given a code description, retrieve the corresponding code.


Question: // we can generate a config by `i.GenPasswordConfig()`

func (i *Instance) ReadPasswordWithConfig(cfg *Config) ([]byte, error) {
	return i.Operation.PasswordWithConfig(cfg)
}

protected function getPathToRecipe(string $recipe): string
    {
        $recipePaths = $this->buildRecipePaths($recipe);

        foreach ($recipePaths as $recipePath) {
            if (file_exists($recipePath)) {
                return $recipePath;
            }
        }

        throw new ConfigurationFileNotFoundException(
            sprintf(
                'Could not resolve path for your recipe. Check %s.',
                implode(', ', $recipePaths)
            )
        );
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns a list of nodes in some forward BFS order.

        Starting from the start node the breadth first search proceeds along
        outgoing edges.

def forw_bfs(self, start, end=None):

        return [node for node, step in self._iterbfs(start, end, forward=True)]

function walk (router, transform) {
  assert.equal(typeof router, 'function', 'wayfarer.walk: router should be an function')
  assert.equal(typeof transform, 'function', 'wayfarer.walk: transform should be a function')

  var trie = router._trie
  assert.equal(typeof trie, 'object', 'wayfarer.walk: trie should be an object')

  // (str, obj) -> null
  ;(function walk (route, trie) {
    if (trie.cb) {
      trie.cb = transform(route, trie.cb)
    }

    if (trie.nodes) {
      var nodes = trie.nodes
      Object.keys(nodes).forEach(function (key) {
        var node = nodes[key]
        var newRoute = (key === '$$')
          ? route + '/:' + trie.name
          : route + '/' + key
        walk(newRoute, node)
      })
    }
  })('', trie.trie)
}

Instruction: Given a code description, retrieve the corresponding code.


Question: Set the trigger_group_bit_mask for the current group/button.

def set_trigger_group_bit_mask(self, trigger_group_bit_mask):
        """"""
        set_cmd = self._create_set_property_msg("_trigger_group_bit_mask",
                                                0x0c, trigger_group_bit_mask)
        self._send_method(set_cmd, self._property_set)

public ImageButton getImageButton(int index) {
		if(config.commandLogging){
			Log.d(config.commandLoggingTag, "getImageButton("+index+")");
		}

		return getter.getView(ImageButton.class, index);
	}

Instruction: Given a code description, retrieve the corresponding code.


public function getCountCommonObjectsFromTrash($data = [])
    {
        if (!empty($data['keywords'])) {

            if (!isset($data['or_like'])) {

                $data['or_like'] = [];
            }

            $data['or_like'][] = [
                'column' => 'o.filename_display',
                'value'  => $data['keywords'],
            ];
        }

        $this->getCountCommon($data);
    }

def text message
      @suggested_w = @width || (FFI::NCurses.COLS * 0.80).floor
      @suggested_h = @height || (FFI::NCurses.LINES * 0.80).floor

      message_col = 3
      r = 2
      display_length = @suggested_w-4
      display_length -= message_col
      clr = @color || :white
      bgclr = @bgcolor || :black

      if message.is_a? Array
        l = longest_in_list message
        if l > @suggested_w
          if l < FFI::NCurses.COLS
            #@suggested_w = l
            @suggested_w = FFI::NCurses.COLS-2
          else
            @suggested_w = FFI::NCurses.COLS-2
          end
          display_length = @suggested_w-6
        end
        # reduce width and height if you can based on array contents
      else
        message = wrap_text(message, display_length).split("\n")
      end
      # now that we have moved to textpad that +8 was causing black lines to remain after the text
      message_height = message.size #+ 8
      # reduce if possible if its not required.
      #
      r1 = (FFI::NCurses.LINES-@suggested_h)/2
      r1 = r1.floor
      w = @suggested_w
      c1 = (FFI::NCurses.COLS-w)/2
      c1 = c1.floor
      @suggested_row = r1
      @suggested_col = c1
      brow = @button_row || @suggested_h-4
      available_ht = brow - r + 1
      message_height = [message_height, available_ht].min
      # replaced 2014-04-14 - 23:51
      message_label = Canis::TextPad.new @form, {:name=>"message_label", :text => message,
        :row => r, :col => message_col, :width => display_length, :suppress_borders => true,
        :height => message_height, :bgcolor => bgclr , :color => clr}
      #message_label.set_content message
      yield message_label if block_given?

    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
Sets the parameters attribute of the ElementRule object.

@param params          The new parameters value
@throws CDKException   Description of the Exception

@see                   #getParameters

@Override
    public void setParameters(Object[] params) throws CDKException {
        if (params.length != 1) throw new CDKException("ElementRule expects one parameters");

        if (!(params[0] == null || params[0] instanceof MolecularFormulaRange))
            throw new CDKException("The parameter must be of type MolecularFormulaExpand");

        mfRange = (MolecularFormulaRange) params[0];
    }

protected function process(array $config, ContainerBuilder $container)
    {
        $container->setParameter('qcm_core.website_name', $config['website_name']);
        $container->setParameter('qcm.model.user.class', $config['user_class']);
        $container->setParameter('qcm.configuration', $config['configuration']);
        $container->setParameter('qcm_core.statistics.class', $config['service']['statistics']['class']);
        $container->setParameter('qcm_core.template.class', $config['service']['statistics']['template']);

        $container->setAlias('qcm.configuration', $config['service']['configuration']);
        $container->setAlias('qcm.user_session_configuration', $config['service']['user_session_configuration']);

        return $config;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Create a less than expression
@param propertyName The propery name
@param value The value
@return The query expression

public QueryExpression lt(String propertyName,String value)
    {
        return new SimpleQueryExpression(propertyName, ComparisonOperator.LESS_THAN,wrap(value));
    }

protected void addCriteria(String column, String operator) {
    if (this.sbClause.length() == 0) {
      this.sbClause.append("WHERE");
    } else {
      this.sbClause.append(" AND");
    }
    this.sbClause.append(' ');
    this.sbClause.append(column);
    this.sbClause.append(' ');
    this.sbClause.append(operator);
    this.sbClause.append(" ?");
  }

Instruction: Given a code description, retrieve the corresponding code.


Question:
@param EntityManagerInterface $entityManager
@param string                 $entityName

@return ObjectRepository

protected function createRepository(EntityManagerInterface $entityManager, $entityName)
    {
        $metadata = $entityManager->getClassMetadata($entityName);
        $repository = $metadata->customRepositoryClassName;

        if ($repository === null) {
            $repository = $entityManager->getConfiguration()->getDefaultRepositoryClassName();
        }

        return $this->createResourceRepository(
            $repository,
            $entityManager,
            $metadata,
            $this->resolveResource($metadata->getName())
        );
    }

public function change($arg, $value = null) {
        $id = $this->getId();
        $this->reset();
        if (!$value) {
            if ($arg instanceof \stdClass) {
                $this->setEntity($arg);
            } else {
                if (!is_array($arg)) {
                    throw new InvalidArgumentException("values is not array");
                }
                foreach ($arg as $key_values) {
                    if (!is_array($key_values)) {
                        throw new InvalidArgumentException("values item must be [key, value]");
                        $this->set($key_values[0], $key_values[1]);
                    }
                };
            }
        } else {
            if (is_array($arg)) {
                $this->set($arg, $value);
            } else {
                $this->set([$arg], $value);
            }
        };
        $this->setId($id);
        return $this->partialUpdate(null);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
增加查询条件，指定聊天室的组员包含某些成员即可返回

@param peerIds
@return

public AVIMConversationsQuery containsMembers(List<String> peerIds) {
    conditions.addWhereItem(Conversation.MEMBERS, "$all", peerIds);
    return this;
  }

public function call($method, $parameters)
    {
        try {
            $ch = curl_init($this->base_url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->encode($method, $parameters));
            curl_setopt($ch, CURLOPT_TIMEOUT, 600);

            $response = curl_exec($ch);

            if ($response === false) {
                $e = new TransportException(curl_error($ch), curl_getinfo($ch, CURLINFO_HTTP_CODE));
                curl_close($ch);

                throw  $e;
            }

            curl_close($ch);

            return $this->decode($response);
        } catch (XmlrpcException $e) {
            throw new TransportException('XML parsing error', 0, $e);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Split a value into the path and object information
@param {string} sValue values like /test/test1.txt
@return {{path: string, obj: string}} Path object

function splitIntoPathAndObject(sValue) {
    var aValues = sValue.split('/');
    var sObject = aValues.pop();
    var sPath = aValues.join('/');
    if (sPath.length > 0 && sPath.charAt(0) !== '/') {
        sPath = '/' + sPath;
    }
    return {
        path: sPath,
        obj: sObject
    };
}

function extractMessage(error) {
	var {message} = error
	if (error.plugin === 'babel') {
		// Hey Babel, you're not helping!
		var filepath = error.id
		var message = error.message
		function stripFilePath() {
			var index = message.indexOf(filepath)
			console.log(index, filepath.length)
			message = message.slice(0, index) + message.slice(filepath.length + 1)
			message = message.trim()
		}
		if (message.includes(filepath)) {
			stripFilePath()
		} else {
			filepath = filepath.replace(/\\/g, '/')
			if (message.includes(filepath))
				stripFilePath()
		}
	}
	return message
}

Instruction: Given a code description, retrieve the corresponding code.


Question: Insert a calculation inside the database, if calc_id is not taken

def import_job(db, calc_id, calc_mode, description, user_name, status,
               hc_id, datadir):

    job = dict(id=calc_id,
               calculation_mode=calc_mode,
               description=description,
               user_name=user_name,
               hazard_calculation_id=hc_id,
               is_running=0,
               status=status,
               ds_calc_dir=os.path.join('%s/calc_%s' % (datadir, calc_id)))
    db('INSERT INTO job (?S) VALUES (?X)', job.keys(), job.values())

public function getBank($bankID)
    {
        if (! isset($this->instances[$bankID])) {
            $this->instances[$bankID] = $this->getNewBank($bankID);

        }
        return $this->instances[$bankID];
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Construction de la DataTable

{@inheritDoc}
@see \Sg\DatatablesBundle\Datatable\View\DatatableViewInterface::buildDatatable()

public function buildDatatable(array $options = array())
    {
        $this->entity = $options['entity'];

        $this->ajax->set(array(
            'url' => $this->router->generate('olix_security_manager_group_results'),
        ));

        // Déclarations des colonnes
        $this->getColumnBuilder()
            ->add('id', 'column', array(
                  'title' => 'Id',
                  'class' => 'text-center',
            ))
            ->add('name', 'column', array(
                  'title' => 'Nom',
            ))
            ->add('roles', 'column', array(
                  'title' => 'Rôles',
            ))
            // Boutons Actions
            ->add(null, 'action', array(
                'title' => '',
                'start_html' => '
',
                'end_html' => '
',
                'actions' => array(
                    array(
                        'route' => 'olix_security_manager_group_edit',
                        'route_parameters' => array('id' => 'id'),
                        'icon' => 'fa fa-edit fa-fw',
                        'attributes' => array(
                            'rel' => 'tooltip',
                            'title' => 'Modifier ce groupe',
                            'class' => 'btn btn-primary btn-xs btn-update',
                            'role' => 'button',
                        ),
                    ),
                    array(
                        'route' => 'olix_security_manager_group_delete',
                        'route_parameters' => array('id' => 'id'),
                        'icon' => 'fa fa-remove fa-fw',
                        'label' => '',
                        'attributes' => array(
                            'rel' => 'tooltip',
                            'title' => 'Supprimer ce groupe',
                            'class' => 'btn btn-danger btn-xs btn-delete',
                            'role' => 'button',
                            'onclick' => 'return olixAdminInterface.confirmDelete(this)',
                        ),
                    ),
                )
            ))
        ;
    }

public function insert($table, $columns)
    {
        $this->sql = 'INSERT INTO ' . $this->quoteTableName($table) . ' ';

        $columnNames = '(';
        $columnValues = '(';
        foreach($columns as $k => $v) {
            $columnNames .= $this->quoteColumnName($k) . ', ';
            $columnValues .= $this->quoteValue($v) . ', ';
        }

        $this->sql .= trim($columnNames, ', ') . ')';
        $this->sql .= ' VALUES ';
        $this->sql .= trim($columnValues, ', ') . ')';

        return $this;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Marshall the given parameter object.

public void marshall(NumberFilter numberFilter, ProtocolMarshaller protocolMarshaller) {

        if (numberFilter == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(numberFilter.getGte(), GTE_BINDING);
            protocolMarshaller.marshall(numberFilter.getLte(), LTE_BINDING);
            protocolMarshaller.marshall(numberFilter.getEq(), EQ_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
parse POJOService Config
@param pojoService Element
@param mps Map
@throws Exception

private void parsePOJOServiceConfig(Element pojoService, Map<String, TargetMetaDef> mps)
			throws Exception {
		String name = pojoService.getAttributeValue("name");
		String className = pojoService.getAttributeValue("class");
		Debug.logVerbose("[JdonFramework] pojoService/component name=" + name
				+ " class=" + className, module);

		if ((className == null) || (className.equals("")))
			throw new Exception("className is null ");

		List mappings = pojoService.getChildren("constructor");
		String[] constructors = null;
		if ((mappings != null) && (mappings.size() != 0)) {
			Debug.logVerbose("[JdonFramework] constructor parameters number:"
					+ mappings.size() + " for pojoservice " + name, module);
			constructors = new String[mappings.size()];
			int j = 0;
			Iterator i = mappings.iterator();
			while (i.hasNext()) {
				Element constructor = (Element) i.next();
				String value = constructor.getAttributeValue("value");
				Debug.logVerbose("[JdonFramework] pojoService constructor="
						+ value, module);
				constructors[j] = value;
				j++;
			}
		}

		POJOTargetMetaDef pojoMetaDef = null;
		if (constructors != null)
			pojoMetaDef = new POJOTargetMetaDef(name, className, constructors);
		else
			pojoMetaDef = new POJOTargetMetaDef(name, className);
		mps.put(name, pojoMetaDef);

	}

async def from_payload(cls, payload, endpoint, idgen, debug, force_protocol=None):
        """"""
        service_name = payload["service"]

        if "protocols" not in payload:
            raise SongpalException(
                "Unable to find protocols from payload: %s" % payload
            )

        protocols = payload["protocols"]
        _LOGGER.debug("Available protocols for %s: %s", service_name, protocols)
        if force_protocol and force_protocol.value in protocols:
            protocol = force_protocol
        elif "websocket:jsonizer" in protocols:
            protocol = ProtocolType.WebSocket
        elif "xhrpost:jsonizer" in protocols:
            protocol = ProtocolType.XHRPost
        else:
            raise SongpalException(
                "No known protocols for %s, got: %s" % (service_name, protocols)
            )
        _LOGGER.debug("Using protocol: %s" % protocol)

        service_endpoint = "%s/%s" % (endpoint, service_name)

        # creation here we want to pass the created service class to methods.
        service = cls(service_name, service_endpoint, protocol, idgen, debug)

        sigs = await cls.fetch_signatures(
            service_endpoint, protocol, idgen
        )

        if debug > 1:
            _LOGGER.debug("Signatures: %s", sigs)
        if "error" in sigs:
            _LOGGER.error("Got error when fetching sigs: %s", sigs["error"])
            return None

        methods = {}

        for sig in sigs["results"]:
            name = sig[0]
            parsed_sig = MethodSignature.from_payload(*sig)
            if name in methods:
                _LOGGER.debug("Got duplicate signature for %s, existing was %s. Keeping the existing one",
                              parsed_sig, methods[name])
            else:
                methods[name] = Method(service, parsed_sig, debug)

        service.methods = methods

        if "notifications" in payload and "switchNotifications" in methods:
            notifications = [
                Notification(
                    service_endpoint, methods["switchNotifications"], notification
                )
                for notification in payload["notifications"]
            ]
            service.notifications = notifications
            _LOGGER.debug("Got notifications: %s" % notifications)

        return service

Instruction: Given a code description, retrieve the corresponding code.


Question:
move all children to the parent node
 !!! need to perform validations here?

def move_children_to_parent
      children.each do |c|
        self.parent.children << c
        c.parent = self.parent  # is this necessary?
      end
    end

public static void replace(Tag src, Tag trg, boolean moveBody) {
	trg.setParent(src.getParent());

	Body p = (Body) src.getParent();
	List<Statement> stats = p.getStatements();
	Iterator<Statement> it = stats.iterator();
	Statement stat;
	int count = 0;

	while (it.hasNext()) {
	    stat = it.next();
	    if (stat == src) {
		if (moveBody && src.getBody() != null) src.getBody().setParent(trg);
		stats.set(count, trg);
		break;
	    }
	    count++;
	}
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: gets a parameter value

def getParameterValue(self, parameterName):

        if  self._results is None:
            self.__init()
        parameter = self._results[parameterName]
        return parameter

public String query(String paramName, String defaultValue) {
        return this.request.query(paramName, defaultValue);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Forwards to the first plugin of the first menu that the user can read since no menu path is
provided.

@SuppressWarnings("squid:S3752") // multiple methods required
  @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
  public String forwardDefaultMenuDefaultPlugin(Model model) {
    Menu menu =
        menuReaderService
            .getMenu()
            .orElseThrow(() -> new RuntimeException("main menu does not exist"));
    String menuId = menu.getId();
    model.addAttribute(KEY_MENU_ID, menuId);

    Optional<MenuItem> optionalActiveItem = menu.firstItem();
    if (!optionalActiveItem.isPresent()) {
      LOG.warn("main menu does not contain any (accessible) items");
      return "forward:/login";
    }
    MenuItem activeItem = optionalActiveItem.get();
    String pluginId = activeItem.getId();

    String contextUri = URI + '/' + menuId + '/' + pluginId;
    addModelAttributes(model, contextUri);

    return getForwardPluginUri(activeItem.getId(), null, getQueryString(activeItem));
  }

public function setupEnvironment($basePath, $application = 'site')
	{
		if ($application != 'site')
		{
			$basePath .= '/' . $application;
		}

		$server  = array(
			'HTTP_HOST'       => 'undefined',
			'HTTP_USER_AGENT' => 'undefined',
			'REQUEST_METHOD'  => 'GET',
		);
		$_SERVER = array_merge($_SERVER, $server);

		define('JPATH_BASE', $basePath);
		define('DS', DIRECTORY_SEPARATOR);

		require_once JPATH_BASE . '/includes/defines.php';
		require_once JPATH_LIBRARIES . '/loader.php';

		spl_autoload_register('__autoload');

		require_once JPATH_BASE . '/includes/framework.php';

		if ($application == 'administrator')
		{
			require_once JPATH_BASE . '/includes/helper.php';
			require_once JPATH_BASE . '/includes/toolbar.php';

			// JUri uses $_SERVER['HTTP_HOST'] without check
			$_SERVER['HTTP_HOST'] = 'CLI';
		}

		jimport('joomla.installer.installer');
		jimport('joomla.installer.helper');

		$mainframe = \JFactory::getApplication($application);
		$mainframe->initialise();
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
/*
@see org.eclipse.debug.core.IDebugEventSetListener#handleDebugEvents(org.eclipse .debug.core.DebugEvent[])

public void handleDebugEvents(DebugEvent[] events)
	{
		if (view == null)
		{
			return;
		}

		for (int i = 0; i < events.length; ++i)
		{
			DebugEvent event = events[i];

			append(new VdmDebugLogItem(Messages.ItemType_Event, getDebugEventKind(event)
					+ " from " + event.getSource().getClass().getName()));//$NON-NLS-1$

			if (event.getKind() == DebugEvent.CREATE)
			{
				handleCreateEvent(event);
			} else if (event.getKind() == DebugEvent.MODEL_SPECIFIC
					&& event.getDetail() == ExtendedDebugEventDetails.DGBP_NEW_CONNECTION)
			{
				if (event.getSource() instanceof IDbgpDebugingEngine)
				{
					((IDbgpDebugingEngine) event.getSource()).addRawListener(this);
				}
			} else if (event.getKind() == DebugEvent.TERMINATE)
			{
				handleTerminateEvent(event);
			}
		}
	}

public void marshall(EventSourceMappingConfiguration eventSourceMappingConfiguration, ProtocolMarshaller protocolMarshaller) {

        if (eventSourceMappingConfiguration == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(eventSourceMappingConfiguration.getUUID(), UUID_BINDING);
            protocolMarshaller.marshall(eventSourceMappingConfiguration.getBatchSize(), BATCHSIZE_BINDING);
            protocolMarshaller.marshall(eventSourceMappingConfiguration.getEventSourceArn(), EVENTSOURCEARN_BINDING);
            protocolMarshaller.marshall(eventSourceMappingConfiguration.getFunctionArn(), FUNCTIONARN_BINDING);
            protocolMarshaller.marshall(eventSourceMappingConfiguration.getLastModified(), LASTMODIFIED_BINDING);
            protocolMarshaller.marshall(eventSourceMappingConfiguration.getLastProcessingResult(), LASTPROCESSINGRESULT_BINDING);
            protocolMarshaller.marshall(eventSourceMappingConfiguration.getState(), STATE_BINDING);
            protocolMarshaller.marshall(eventSourceMappingConfiguration.getStateTransitionReason(), STATETRANSITIONREASON_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Raises a KeyError if the field doesn't exist.

def __check_field(self, key):
        """"""
        if not self._props.get(key):
            raise KeyError(
                'The field "%s" does not exist on "%s"' % (
                    key, self.__class__.__name__,
                ),
            )

def is_slug_available(self, slug, **kwargs):

        try:
            self.get(slug=slug, **kwargs)
            return False
        except self.model.DoesNotExist:
            return True

Instruction: Given a code description, retrieve the corresponding code.


Question: Marshall the given parameter object.

public void marshall(DescribeJobDefinitionsRequest describeJobDefinitionsRequest, ProtocolMarshaller protocolMarshaller) {

        if (describeJobDefinitionsRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(describeJobDefinitionsRequest.getJobDefinitions(), JOBDEFINITIONS_BINDING);
            protocolMarshaller.marshall(describeJobDefinitionsRequest.getMaxResults(), MAXRESULTS_BINDING);
            protocolMarshaller.marshall(describeJobDefinitionsRequest.getJobDefinitionName(), JOBDEFINITIONNAME_BINDING);
            protocolMarshaller.marshall(describeJobDefinitionsRequest.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(describeJobDefinitionsRequest.getNextToken(), NEXTTOKEN_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Once dict from source data is created, turn this into histogram.

    Parameters
    ----------
    data : dict
        Parsed JSON-like tree.

    Returns
    -------
    histogram : HistogramBase
        A histogram (of any dimensionality)

def create_from_dict(data: dict, format_name: str, check_version: bool = True) -> Union[HistogramBase, HistogramCollection]:

    # Version
    if check_version:
        compatible_version = data["physt_compatible"]
        require_compatible_version(compatible_version, format_name)

    # Construction
    histogram_type = data["histogram_type"]
    if histogram_type == "histogram_collection":
        klass = HistogramCollection
    else:
        klass = find_subclass(HistogramBase, histogram_type)
    return klass.from_dict(data)

def copy_ccube(ccube, outsrcmap, hpx_order):

        sys.stdout.write("  Copying counts cube from %s to %s\n" % (ccube, outsrcmap))
        try:
            hdulist_in = fits.open(ccube)
        except IOError:
            hdulist_in = fits.open("%s.gz" % ccube)

        hpx_order_in = hdulist_in[1].header['ORDER']

        if hpx_order_in > hpx_order:
            hpxmap = HpxMap.create_from_hdulist(hdulist_in)
            hpxmap_out = hpxmap.ud_grade(hpx_order, preserve_counts=True)
            hpxlist_out = hdulist_in
            #hpxlist_out['SKYMAP'] = hpxmap_out.create_image_hdu()
            hpxlist_out[1] = hpxmap_out.create_image_hdu()
            hpxlist_out[1].name = 'SKYMAP'
            hpxlist_out.writeto(outsrcmap)
            return hpx_order
        else:
            os.system('cp %s %s' % (ccube, outsrcmap))
            #os.system('cp %s.gz %s.gz' % (ccube, outsrcmap))
            #os.system('gunzip -f %s.gz' % (outsrcmap))
        return None

Instruction: Given a code description, retrieve the corresponding code.


Question: Called when a handler factory service is un/registered

def service_changed(self, event):
        # type: (ServiceEvent) -> None

        # Call sub-methods
        kind = event.get_kind()
        svc_ref = event.get_service_reference()

        if kind == ServiceEvent.REGISTERED:
            # Service coming
            with self.__instances_lock:
                self.__add_handler_factory(svc_ref)

        elif kind == ServiceEvent.UNREGISTERING:
            # Service gone
            with self.__instances_lock:
                self.__remove_handler_factory(svc_ref)

protected void activate(ComponentContext context) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
            Tr.event(this, tc, "activate", context);
        configAdminRef.activate(context);
        variableRegistryRef.activate(context);
        metaTypeServiceRef.activate(context);
        wsConfigurationHelperRef.activate(context);
        bundleContext = priv.getBundleContext(context);

    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetAuthorizerName sets the AuthorizerName field's value.

func (s *UpdateAuthorizerInput) SetAuthorizerName(v string) *UpdateAuthorizerInput {
	s.AuthorizerName = &v
	return s
}

public function isOwner(Model $Model) {
		if (!$Model->exists()) {
			return false;
		}

		if (!$owner = Hash::get($Model->data, $Model->alias . '.' . $this->settings[$Model->alias]['owner']['path'])) {
			$requireAuth = $Model->requireAuth;
			$Model->requireAuth = false;
			$owner = $Model->field(
				$this->settings[$Model->alias]['owner']['path'],
				array($Model->alias . '.' . $Model->primaryKey => $Model->getID())
			);
			$Model->requireAuth = $requireAuth;
		}

		return $this->getCurrentUser($Model, $this->settings[$Model->alias]['owner']['auth']) == $owner;
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
// IsFileModified returns whether the filepath specified is modified according
// to `git status`. A file is modified if it has uncommitted changes in the
// working copy or the index. This includes being untracked.

func IsFileModified(filepath string) (bool, error) {

	args := []string{
		"-c", "core.quotepath=false", // handle special chars in filenames
		"status",
		"--porcelain",
		"--", // separator in case filename ambiguous
		filepath,
	}
	cmd := git(args...)
	outp, err := cmd.StdoutPipe()
	if err != nil {
		return false, lfserrors.Wrap(err, "Failed to call git status")
	}
	if err := cmd.Start(); err != nil {
		return false, lfserrors.Wrap(err, "Failed to start git status")
	}
	matched := false
	for scanner := bufio.NewScanner(outp); scanner.Scan(); {
		line := scanner.Text()
		// Porcelain format is "<I><W> <filename>"
		// Where <I> = index status, <W> = working copy status
		if len(line) > 3 {
			// Double-check even though should be only match
			if strings.TrimSpace(line[3:]) == filepath {
				matched = true
				// keep consuming output to exit cleanly
				// will typically fall straight through anyway due to 1 line output
			}
		}
	}
	if err := cmd.Wait(); err != nil {
		return false, lfserrors.Wrap(err, "Git status failed")
	}

	return matched, nil
}

def set_monitoring(module):

    def monitoring(is_monitoring,
                   track_data=None,
                   track_grad=None,
                   track_update=None,
                   track_update_ratio=None):
        """
        Turn monitoring on or off. If any of the keyword arguments
        are not None, they will be overwritten.
        """
        module.is_monitoring = is_monitoring
        module.track_data = track_data if track_data is not None else module.track_data
        module.track_grad = track_grad if track_grad is not None else module.track_grad
        module.track_update = track_update if track_update is not None else module.track_update
        module.track_update_ratio = track_update_ratio if track_update_ratio is not None else module.track_update_ratio
    module.monitoring = monitoring

Instruction: Given a code description, retrieve the corresponding code.


Question:
/*
Get the parent node of a given node.

private Node getParent(Node n) {
        if (n.y_s == null) {
            return null;
        }
        Node c = n.y_s;
        if (c.o_c == n) {
            return c;
        }
        Node p1 = c.y_s;
        if (p1 != null && p1.o_c == n) {
            return p1;
        }
        return c;
    }

public function addChild(Step $step)
    {
        if (!$this->children->contains($step)) {
            $this->children->add($step);
            $step->setParent($this);
        }

        return $this;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Creates, updates or deletes zero or more pieces of content in the data store facades.

public static void updateAllForFacade(DataStore dataStore, Iterable<Update> updates) {
        updateAllForFacade(dataStore, updates.iterator());
    }

def del_node(self, char, node):
        """"""
        del self._real.character[char].node[node]
        for cache in (
                self._char_nodes_rulebooks_cache,
                self._node_stat_cache,
                self._node_successors_cache
        ):
            try:
                del cache[char][node]
            except KeyError:
                pass
        if char in self._char_nodes_cache and node in self._char_nodes_cache[char]:
            self._char_nodes_cache[char] = self._char_nodes_cache[char] - frozenset([node])
        if char in self._portal_stat_cache:
            portal_stat_cache_char = self._portal_stat_cache[char]
            if node in portal_stat_cache_char:
                del portal_stat_cache_char[node]
            for charo in portal_stat_cache_char.values():
                if node in charo:
                    del charo[node]
        if char in self._char_portals_rulebooks_cache:
            portal_rulebook_cache_char = self._char_portals_rulebooks_cache[char]
            if node in portal_rulebook_cache_char:
                del portal_rulebook_cache_char[node]
            for porto in portal_rulebook_cache_char.values():
                if node in porto:
                    del porto[node]

Instruction: Given a code description, retrieve the corresponding code.


Question:
// read reads events from an inotify file descriptor. It does not handle errors
// returned from read(2) function since they are not critical to watcher logic.

func (i *inotify) read() (es []*event) {
	n, err := unix.Read(int(i.fd), i.buffer[:])
	if err != nil || n < unix.SizeofInotifyEvent {
		return
	}
	var sys *unix.InotifyEvent
	nmin := n - unix.SizeofInotifyEvent
	for pos, path := 0, ""; pos <= nmin; {
		sys = (*unix.InotifyEvent)(unsafe.Pointer(&i.buffer[pos]))
		pos += unix.SizeofInotifyEvent
		if path = ""; sys.Len > 0 {
			endpos := pos + int(sys.Len)
			path = string(bytes.TrimRight(i.buffer[pos:endpos], "\x00"))
			pos = endpos
		}
		es = append(es, &event{
			sys: unix.InotifyEvent{
				Wd:     sys.Wd,
				Mask:   sys.Mask,
				Cookie: sys.Cookie,
			},
			path: path,
		})
	}
	return
}

def _worker_thread_disk(self):
        # type: (Downloader) -> None

        while not self.termination_check:
            try:
                dd, offsets, data = self._disk_queue.get(
                    block=False, timeout=0.1)
            except queue.Empty:
                continue
            try:
                self._process_data(dd, offsets, data)
            except Exception as e:
                with self._transfer_lock:
                    self._exceptions.append(e)

Instruction: Given a code description, retrieve the corresponding code.


Question:
@param string $string
@param int $options

@return IOutput

@see OutputVerbosity
@see OutputProcessing

public function write($string, $options = null) {
        if ($options === null) {
            $options = OutputVerbosity::NORMAL;
        }

        if ($this->is($options)) {
            $this->buffer->write($string);

            if ( ! $this->isBufferingEnabled()) {
                $this->flushBuffer();
            }
        }

        return $this;
    }

def parse_data_to_internal(self, data=None):

        if data is None:
            f = open(self.location_dat, "rb")
            data = {
                "PMCA SPECTRUM": {},
                "DATA": [],
                "DP5 CONFIGURATION": {},
                "DPP STATUS": {}
            }
            delimiter = {
                "PMCA SPECTRUM": " - ",
                "DP5 CONFIGURATION": "=",
                "DPP STATUS": ":"
            }
            comments = {
                "PMCA SPECTRUM": None,
                "DP5 CONFIGURATION": ";",
                "DPP STATUS": None
            }
            for e in f:
                if "<<" in e:
                    if "<<END>>" in e:
                        current = None
                    elif "<<PMCA SPECTRUM>>" in e:
                        current = "PMCA SPECTRUM"
                    elif "<<DATA>>" in e:
                        current = "DATA"
                    elif "<<DP5 CONFIGURATION>>" in e:
                        current = "DP5 CONFIGURATION"
                    elif "<<DPP STATUS>>" in e:
                        current = "DPP STATUS"
                    elif "<<ROI>>" in e:
                        current = "ROI"
                else:
                    if current == "DATA":
                        data["DATA"].append(float(e))
                    elif current == "ROI":
                        continue
                    elif current is not None:
                        e = e.split("\r\n")[0]
                        if comments[current] is not None:
                            e = e.split(comments[current], 1)[0]
                        e_list = e.split(delimiter[current], 1)
                        data[current][e_list[0]] = e_list[1]
            f.close()
        self.save_to_internal(data)

Instruction: Given a code description, retrieve the corresponding code.


Question: Reads GRR users with optional pagination, sorted by username.

def ReadGRRUsers(self, offset=0, count=None, cursor=None):
    """"""
    if count is None:
      count = 18446744073709551615  # 2^64-1, as suggested by MySQL docs

    cursor.execute(
        "SELECT username, password, ui_mode, canary_mode, user_type "
        "FROM grr_users ORDER BY username ASC "
        "LIMIT %s OFFSET %s", [count, offset])
    return [self._RowToGRRUser(row) for row in cursor.fetchall()]

def group_list
      page = 1
      not_done = true
      count = 0
      while not_done
        current_path = '/api/v1/groups?page=' << page.to_s
        res = @conn.get(current_path)
        if res['groups'] == []
          not_done = false
        elsif !res['message'].nil?
          return { 'message' => res['message'] }
        elsif page == 1
          count = res['count']
          groups = res['groups']
        else
          res['groups'].each do |group|
            groups << group
          end
        end
        page += 1
      end
      { 'count' => count, 'groups' => groups }
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
Retrieve all column names of type int for the current selected table.

@param GetPropertyOptionsEvent $event The event.

@return void

public function getIntColumnNames(GetPropertyOptionsEvent $event)
    {
        if (!$this->isBackendOptionRequestFor($event, ['tag_id'])) {
            return;
        }

        $result = $this->getColumnNamesFromTable(
            $event->getModel()->getProperty('tag_table'),
            [Type::INTEGER, Type::BIGINT, Type::SMALLINT]
        );

        $event->setOptions($result);
    }

func (d *dbBase) setColsValues(mi *modelInfo, ind *reflect.Value, cols []string, values []interface{}, tz *time.Location) {
	for i, column := range cols {
		val := reflect.Indirect(reflect.ValueOf(values[i])).Interface()

		fi := mi.fields.GetByColumn(column)

		field := ind.Field(fi.fieldIndex)

		value, err := d.convertValueFromDB(fi, val, tz)
		if err != nil {
			panic(fmt.Errorf("Raw value: `%v` %s", val, err.Error()))
		}

		_, err = d.setFieldValue(fi, value, field)

		if err != nil {
			panic(fmt.Errorf("Raw value: `%v` %s", val, err.Error()))
		}
	}
}

Instruction: Given a code description, retrieve the corresponding code.


Question: Get an sqlite3 connection, and initialize the package database if necessary

def init():
    '''

    '''
    if not os.path.exists(__opts__['spm_cache_dir']):
        log.debug('Creating SPM cache directory at %s', __opts__['spm_db'])
        os.makedirs(__opts__['spm_cache_dir'])

    if not os.path.exists(__opts__['spm_db']):
        log.debug('Creating new package database at %s', __opts__['spm_db'])

    sqlite3.enable_callback_tracebacks(True)
    conn = sqlite3.connect(__opts__['spm_db'], isolation_level=None)

    try:
        conn.execute('SELECT count(*) FROM packages')
    except OperationalError:
        conn.execute('''CREATE TABLE packages (
            package text,
            version text,
            release text,
            installed text,
            os text,
            os_family text,
            dependencies text,
            os_dependencies text,
            os_family_dependencies text,
            summary text,
            description text
        )''')

    try:
        conn.execute('SELECT count(*) FROM files')
    except OperationalError:
        conn.execute('''CREATE TABLE files (
            package text,
            path text,
            size real,
            mode text,
            sum text,
            major text,
            minor text,
            linkname text,
            linkpath text,
            uname text,
            gname text,
            mtime text
        )''')

    return conn

def setup(self):
        """"""
        for table_spec in self._table_specs:
            with self._conn:
                table_spec.setup(self._conn)

Instruction: Given a code description, retrieve the corresponding code.


Question: Returns list of directories, including intermediate.

def get_dirs_for_path(*paths):

    for path in paths:
        head = path
        while head:
            head, tail = os.path.split(head)
            if head:
                yield head
            else:
                # We don't need to yield empty path
                break

def iter_tex_documents(base_dir="."):
    """"""
    for path, dirlist, filelist in os.walk(base_dir):
        for name in fnmatch.filter(filelist, "*.tex"):
            yield os.path.join(path, name)

Instruction: Given a code description, retrieve the corresponding code.


@Override
    public void elementDecl(final String name, final String model)
            throws SAXException
    {
        LOG.trace("elementDecl:{},{}", name, model);
        this.context.addElementDoctype(name, model);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Representation of a stack trace.

Options:

- **guess**: Guess the names of anonymous functions.

@constructor
@param {Array} trace Array of traces.
@param {Object} err
@api private

function Stack(trace, options) {
  if (!(this instanceof Stack)) return new Stack(trace, options);

  if ('object' === typeof trace && !trace.length) {
    options = trace;
    trace = null;
  }

  options = options || {};
  options.guess = 'guess' in options ? options.guess : true;

  if (!trace) {
    var imp = new stacktrace.implementation()
      , err = options.error || options.err || options.e
      , traced;

    traced = imp.run(err);
    trace = options.guess ? imp.guessAnonymousFunctions(traced) : traced;
  }

  this.traces = this.parse(trace);
}

public void marshall(DescribeEventAggregatesRequest describeEventAggregatesRequest, ProtocolMarshaller protocolMarshaller) {

        if (describeEventAggregatesRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(describeEventAggregatesRequest.getFilter(), FILTER_BINDING);
            protocolMarshaller.marshall(describeEventAggregatesRequest.getAggregateField(), AGGREGATEFIELD_BINDING);
            protocolMarshaller.marshall(describeEventAggregatesRequest.getMaxResults(), MAXRESULTS_BINDING);
            protocolMarshaller.marshall(describeEventAggregatesRequest.getNextToken(), NEXTTOKEN_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Auto-load plugin event listeners.

@param CommonEventManager $manager Optional. Instance to use. Defaults to the global instance.
@param string $scope Optional. The scope of events to load.
@return CakeEventManager

public function loadListeners($manager = null, $scope = null) {
		if (!($manager instanceof CakeEventManager)) {
			$scope = $manager;
			$_this = $this;
		} else {
			$_this = $manager;
		}

		empty($_this->loadedListeners['Common'])
		&& $_this->loadedListeners['Common'] = new CommonEventListener();

		(empty($_this->loadedScopes['Common']) || !in_array($scope, (array) $_this->loadedScopes['Common']))
		&& $_this->loadedScopes['Common'][] = $scope
		&& $_this->attachByScope($_this->loadedListeners['Common'], $_this, $scope);

		$_this->implementedEvents['Common'] = array_keys($_this->loadedListeners['Common']->implementedEvents());

		foreach ($_this->listPlugins() as $plugin) {
			if (isset($_this->loadedListeners[$plugin])) {
				if (
					$_this->loadedListeners[$plugin]
					&& !empty($scope)
					&& !in_array($scope, (array) $_this->loadedScopes[$plugin])
				) {
					$_this->loadedScopes[$plugin][] = $scope;
					$_this->attachByScope($_this->loadedListeners[$plugin], $_this, $scope);
				}
				continue;
			}

			$class = $plugin . 'EventListener';

			if (ClassRegistry::isKeySet($class)) {
				$_this->loadedListeners[$plugin] = ClassRegistry::getObject($class);
			} else if (file_exists(CakePlugin::path($plugin) . 'Event' . DS . $class . '.php')) {
				App::uses($class, $plugin . '.Event');
				$_this->loadedListeners[$plugin] = new $class();
			} else {
				$_this->loadedListeners[$plugin] = false;
				continue;
			}

			$_this->loadedScopes[$plugin] = array();
			$_this->implementedEvents[$plugin] = array_keys($_this->loadedListeners[$plugin]->implementedEvents());

			if (empty($scope)) {
				$_this->attach($_this->loadedListeners[$plugin]);
			} else if (!in_array($scope, $_this->loadedScopes[$plugin])) {
				$_this->loadedScopes[$plugin][] = $scope;
				$_this->attachByScope($_this->loadedListeners[$plugin], $_this, $scope);
			}
		}

		if ((!Reveal::is('Page.test') || empty($_GET['plugin'])) && !isset($_this->loadedListeners['App'])) {
			if (file_exists(APP . 'Event' . DS . 'AppEventListener.php')) {
				App::uses('AppEventListener', 'Event');
				$_this->loadedListeners['App'] = new AppEventListener();
				$_this->loadedScopes['App'] = array();
				$_this->implementedEvents['App'] = array_keys($_this->loadedListeners['App']->implementedEvents());
				if (empty($scope)) {
					$_this->attach($_this->loadedListeners['App']);
				} else if (!in_array($scope, $_this->loadedScopes['App'])) {
					$_this->loadedScopes['App'][] = $scope;
					$_this->attachByScope($_this->loadedListeners['App'], $_this, $scope);
				}
			}
		} else if (
			isset($_this->loadedListeners['App'])
			&& $_this->loadedListeners['App']
			&& !empty($scope)
			&& !in_array($scope, $_this->loadedScopes['App'])
		) {
			$_this->loadedScopes['App'][] = $scope;
			$_this->attachByScope($_this->loadedListeners['App'], $_this, $scope);
		}

		return $_this;
	}

public function registerScopeMetaBox($postType, $choises)
    {
        if (!is_string($postType)) {
            return WP_Error("Post type variable must be of the type string.");
        }

        if (!is_array($choises)) {
            return WP_Error("Choises variable must be of the type assoc array.");
        }

        if (!function_exists('acf_add_local_field_group')) {
            return WP_Error("Could not find required ACF function acf_add_local_field_group.");
        }

        acf_add_local_field_group(array(
            'key' => 'group_' . substr(md5($postType . '_scope'), 0, 13),
            'title' => __('Scope styling', 'modularity'),
            'fields' => array(
                array(
                    'key' => 'field_' . substr(md5($postType . '_scope'), 0, 13),
                    'label' => __('Select an apperance for this instance of module', 'modularity'),
                    'name' => 'module_css_scope',
                    'type' => 'select',
                    'instructions' => __('By selecting a scope for this class, they will appear in a different way than the standard layout.', 'modularity'),
                    'required' => 0,
                    'conditional_logic' => 0,
                    'wrapper' => array(
                        'width' => '',
                        'class' => '',
                        'id' => '',
                    ),
                    'choices' => $choises,
                    'default_value' => array(
                    ),
                    'allow_null' => 1,
                    'multiple' => 0,
                    'ui' => 0,
                    'ajax' => 0,
                    'return_format' => 'value',
                    'placeholder' => '',
                ),
            ),
            'location' => array(
                array(
                    array(
                        'param' => 'post_type',
                        'operator' => '==',
                        'value' => $postType,
                    ),
                ),
            ),
            'menu_order' => 0,
            'position' => 'side',
            'style' => 'default',
            'label_placement' => 'top',
            'instruction_placement' => 'label',
            'hide_on_screen' => '',
            'active' => 1,
            'description' => '',
        ));

        return true;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Creates a query which uses paging from another query.<p>

@param select the base query
@param params the query parameters

@return the paged version of the query

protected CmsPair<String, List<Object>> makePaged(CmsSelectQuery select, CmsUserSearchParameters params) {

        CmsPagingQuery paging = new CmsPagingQuery(select);
        paging.setUseWindowFunctions(useWindowFunctionsForPaging());
        int page = params.getPage();
        int pageSize = params.getPageSize();
        paging.setNameSubquery(shouldNameSubqueries());
        paging.setPaging(pageSize, page);
        CmsStatementBuilder builder = new CmsStatementBuilder();
        paging.visit(builder);
        return CmsPair.create(builder.getQuery(), builder.getParameters());
    }

public final function LoadPage($name, $arg1 = null, $arg2 = null, $arg3 = null, $arg4 = null, $arg5 = null)
    {

        if (is_array($arg1) == false) {
            //$this->currentpage = new $name($arg1, $arg2, $arg3, $arg4, $arg5);
            $arg1 = func_get_args();
            $arg1 = array_slice($arg1, 1);
        }

        $classpage = new \ReflectionClass($name);
        $this->currentpage = $classpage->newInstanceArgs($arg1);

        $this->currentpage->args = $arg1; //запоминаем аргументы страницы

        $this->response->setPageIndex($this->getPageManager()->putPage($this->currentpage));
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Help add a pre-built edge.

def _help_add_edge(self, u: BaseEntity, v: BaseEntity, attr: Mapping) -> str:
        """"""
        self.add_node_from_data(u)
        self.add_node_from_data(v)

        return self._help_add_edge_helper(u, v, attr)

def start_block(self,stylestack=None):

        if self.dirty:
            self.escpos._raw('\n')
            self.dirty = False
        self.stack.append('block')
        if stylestack:
            self.style(stylestack)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Set the prepared size of this object. This method also handles min and max
size

@param aPreparedSize
Prepared size without padding and margin.

private void _setPreparedSize (@Nonnull final SizeSpec aPreparedSize)
  {
    ValueEnforcer.notNull (aPreparedSize, "PreparedSize");

    m_bPrepared = true;
    m_aPreparedSize = aPreparedSize;
    m_aRenderSize = getRenderSize (aPreparedSize);

    if (PLDebugLog.isDebugPrepare ())
    {
      String sSuffix = "";
      if (this instanceof IPLHasMarginBorderPadding <?>)
      {
        sSuffix = " with " +
                  PLDebugLog.getXMBP ((IPLHasMarginBorderPadding <?>) this) +
                  " and " +
                  PLDebugLog.getYMBP ((IPLHasMarginBorderPadding <?>) this);
      }
      PLDebugLog.debugPrepare (this,
                               "Prepared object: " +
                                     PLDebugLog.getWH (aPreparedSize) +
                                     sSuffix +
                                     "; Render size: " +
                                     PLDebugLog.getWH (m_aRenderSize));
    }
  }

public void marshall(Tape tape, ProtocolMarshaller protocolMarshaller) {

        if (tape == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(tape.getTapeARN(), TAPEARN_BINDING);
            protocolMarshaller.marshall(tape.getTapeBarcode(), TAPEBARCODE_BINDING);
            protocolMarshaller.marshall(tape.getTapeCreatedDate(), TAPECREATEDDATE_BINDING);
            protocolMarshaller.marshall(tape.getTapeSizeInBytes(), TAPESIZEINBYTES_BINDING);
            protocolMarshaller.marshall(tape.getTapeStatus(), TAPESTATUS_BINDING);
            protocolMarshaller.marshall(tape.getVTLDevice(), VTLDEVICE_BINDING);
            protocolMarshaller.marshall(tape.getProgress(), PROGRESS_BINDING);
            protocolMarshaller.marshall(tape.getTapeUsedInBytes(), TAPEUSEDINBYTES_BINDING);
            protocolMarshaller.marshall(tape.getKMSKey(), KMSKEY_BINDING);
            protocolMarshaller.marshall(tape.getPoolId(), POOLID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: A dict of dicts parsed from the response 'Link' header (if set).

def links(self):
        """"""
        # <https://example.com/?page=2>; rel="next", <https://example.com/?page=34>; rel="last"'
        # becomes
        # {
        #     'last': {'rel': 'last', 'url': 'https://example.com/?page=34'},
        #     'next': {'rel': 'next', 'url': 'https://example.com/?page=2'},
        # },
        result = {}
        if 'Link' in self.headers:
            value = self.headers['Link']

            for part in re.split(r', *<', value):
                link = {}
                vs = part.split(';')

                # First section is always an url.
                link['url'] = vs.pop(0).strip('\'" <>')

                for v in vs:
                    if '=' in v:
                        key, v = v.split('=')
                        link[key.strip('\'" ')] = v.strip('\'" ')

                rkey = link.get('rel') or link['url']
                result[rkey] = link

        return result

def get_csv_from_json(d):

    logger_jsons.info("enter get_csv_from_json")
    csv_data = OrderedDict()

    if "paleoData" in d:
        csv_data = _get_csv_from_section(d, "paleoData", csv_data)

    if "chronData" in d:
        csv_data = _get_csv_from_section(d, "chronData", csv_data)

    logger_jsons.info("exit get_csv_from_json")
    return csv_data

Instruction: Given a code description, retrieve the corresponding code.


Question:
Appends the given $nodePathSegment to the $nodePath

@param string $nodePath Absolute node path
@param string $nodePathSegment Usually a nodeName but could also be a relative node path.
@return string

public static function addNodePathSegment($nodePath, $nodePathSegment)
    {
        $nodePath = rtrim($nodePath, '/');
        if ($nodePathSegment !== '' || $nodePath === '') {
            $nodePath .= '/' . trim($nodePathSegment, '/');
        }

        return $nodePath;
    }

function stem(tree, depth) {
  // First we break out the tree into a complete list of root to leaf paths
  var paths = rootToLeaf(tree);
  var stemmedRevs;

  var result;
  for (var i = 0, len = paths.length; i < len; i++) {
    // Then for each path, we cut off the start of the path based on the
    // `depth` to stem to, and generate a new set of flat trees
    var path = paths[i];
    var stemmed = path.ids;
    var node;
    if (stemmed.length > depth) {
      // only do the stemming work if we actually need to stem
      if (!stemmedRevs) {
        stemmedRevs = {}; // avoid allocating this object unnecessarily
      }
      var numStemmed = stemmed.length - depth;
      node = {
        pos: path.pos + numStemmed,
        ids: pathToTree(stemmed, numStemmed)
      };

      for (var s = 0; s < numStemmed; s++) {
        var rev = (path.pos + s) + '-' + stemmed[s].id;
        stemmedRevs[rev] = true;
      }
    } else { // no need to actually stem
      node = {
        pos: path.pos,
        ids: pathToTree(stemmed, 0)
      };
    }

    // Then we remerge all those flat trees together, ensuring that we dont
    // connect trees that would go beyond the depth limit
    if (result) {
      result = doMerge(result, node, true).tree;
    } else {
      result = [node];
    }
  }

  // this is memory-heavy per Chrome profiler, avoid unless we actually stemmed
  if (stemmedRevs) {
    traverseRevTree(result, function (isLeaf, pos, revHash) {
      // some revisions may have been removed in a branch but not in another
      delete stemmedRevs[pos + '-' + revHash];
    });
  }

  return {
    tree: result,
    revs: stemmedRevs ? Object.keys(stemmedRevs) : []
  };
}

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetUserId sets the UserId field's value.

func (s *DescribeActivitiesInput) SetUserId(v string) *DescribeActivitiesInput {
	s.UserId = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

    if (isLog(4)) {
      log("change getfield " + owner + " name:" + name);
    }
    typeQueryUser = true;
  }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Authorize a payment for future capture

@var Object $payment
@var Float $amount

public function authorize($payment, $amount)
        {
            $error = false;

            // check for payment
            if($amount > 0) {

                $payment->setAmount($amount);

                // Map magento keys to moneris way
                $transaction = $this->_build($payment, self::TRANSACTION_PREAUTH);
                $response = $this->_send($transaction);

                $payment->setCcApproval($response->getReceiptId())
                    ->setLastTransId($response->getReceiptId())
                    ->setCcTransId($response->getTxnNumber())
                    ->setCcAvsStatus($response->getAuthCode())
                    ->setCcCidStatus($response->getResponseCode());

                if($response->getResponseCode() > 0 && $response->getResponseCode() <= self::ERROR_CODE_LIMIT) {
                    $payment->setStatus(self::STATUS_APPROVED);
                } else if($response->getResponseCode() > self::ERROR_CODE_LIMIT && $response->getResponseCode() < self::ERROR_CODE_UPPER_LIMIT) {
                    $error = $this->_errors[$response->getResponseCode()];
                } else {
                    $error = 'Incomplete transaction.';
                }
            } else {
                $error = 'Invalid amount for authorization.';
            }

            // we've got something bad here.
            if ($error !== false) {
                $this->_log($error);
            }
            return $this;
        }

func (r Virtual_Guest_Block_Device_Template_Group) CreatePublicArchiveTransaction(groupName *string, summary *string, note *string, locations []datatypes.Location) (resp int, err error) {
	params := []interface{}{
		groupName,
		summary,
		note,
		locations,
	}
	err = r.Session.DoRequest("SoftLayer_Virtual_Guest_Block_Device_Template_Group", "createPublicArchiveTransaction", params, &r.Options, &resp)
	return
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Converts the inputted python object to JSON format.

    :param      py_obj | <variant>

def py2json(py_obj):

    method = getattr(py_obj, '__json__', None)

    if method:
        return method()
    elif type(py_obj) == datetime.datetime:
        return py_obj.isoformat()
    elif type(py_obj) == datetime.date:
        return py_obj.isoformat()
    elif type(py_obj) == datetime.time:
        return py_obj.isoformat()
    elif type(py_obj) == set:
        return list(py_obj)
    elif type(py_obj) == decimal.Decimal:
        return str(py_obj)
    else:
        # look through custom plugins
        for encoder in _encoders:
            success, value = encoder(py_obj)
            if success:
                return value

        opts = (py_obj, type(py_obj))
        raise TypeError('Unserializable object {} of type {}'.format(*opts))

def to_dict(self):

        return {
            'model_type': 'segmented_discretechoice',
            'name': self.name,
            'segmentation_col': self.segmentation_col,
            'sample_size': self.sample_size,
            'probability_mode': self.probability_mode,
            'choice_mode': self.choice_mode,
            'choosers_fit_filters': self.choosers_fit_filters,
            'choosers_predict_filters': self.choosers_predict_filters,
            'alts_fit_filters': self.alts_fit_filters,
            'alts_predict_filters': self.alts_predict_filters,
            'interaction_predict_filters': self.interaction_predict_filters,
            'estimation_sample_size': self.estimation_sample_size,
            'prediction_sample_size': self.prediction_sample_size,
            'choice_column': self.choice_column,
            'default_config': {
                'model_expression': self.default_model_expr,
            },
            'remove_alts': self.remove_alts,
            'fitted': self.fitted,
            'models': {
                yamlio.to_scalar_safe(name):
                    self._process_model_dict(m.to_dict())
                for name, m in self._group.models.items()
            }
        }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Convert a loglevel description to a loglevel constant.

@param  string $value - loglevel description

@return int|null - loglevel constant or NULL, if $value is not a valid loglevel description

public static function logLevelToId($value) {
        if (!is_string($value)) throw new IllegalTypeException('Illegal type of parameter $value: '.gettype($value));

        switch (strtolower($value)) {
            case 'debug' : return L_DEBUG;
            case 'info'  : return L_INFO;
            case 'notice': return L_NOTICE;
            case 'warn'  : return L_WARN;
            case 'error' : return L_ERROR;
            case 'fatal' : return L_FATAL;
            default:
                return null;
        }
    }

def check_option!(name, definition)
      case name
      when :values
        raise AttributorException, "Allowed set of values requires an array. Got (#{definition})" unless definition.is_a? ::Array
      when :default
        raise AttributorException, "Default value doesn't have the correct attribute type. Got (#{definition.inspect})" unless type.valid_type?(definition) || definition.is_a?(Proc)
        options[:default] = load(definition) unless definition.is_a?(Proc)
      when :description
        raise AttributorException, "Description value must be a string. Got (#{definition})" unless definition.is_a? ::String
      when :required
        raise AttributorException, 'Required must be a boolean' unless definition == true || definition == false
        raise AttributorException, 'Required cannot be enabled in combination with :default' if definition == true && options.key?(:default)
      when :required_if
        raise AttributorException, 'Required_if must be a String, a Hash definition or a Proc' unless definition.is_a?(::String) || definition.is_a?(::Hash) || definition.is_a?(::Proc)
        raise AttributorException, 'Required_if cannot be specified together with :required' if options[:required]
      when :example
        unless definition.is_a?(::Regexp) || definition.is_a?(::String) || definition.is_a?(::Array) || definition.is_a?(::Proc) || definition.nil? || type.valid_type?(definition)
          raise AttributorException, "Invalid example type (got: #{definition.class.name}). It must always match the type of the attribute (except if passing Regex that is allowed for some types)"
        end
      when :custom_data
        raise AttributorException, "custom_data must be a Hash. Got (#{definition})" unless definition.is_a?(::Hash)
      else
        return :unknown # unknown option
      end

      :ok # passes
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
Determine if the action is routing to a controller.

@param  array  $action
@return bool

protected function routingToController($action)
	{
		if ($action instanceof Closure) return false;

		return is_string($action) || is_string(array_get($action, 'uses'));
	}

function setActionParameter( $parameterName, $parameterValue, $view = '' )
    {
        if ( $view == '' )
            $view = self::currentView();
        $this->ViewActionParameters[$view][$parameterName] = $parameterValue;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
jQuery validate requires that the value of the option does not contain
the actual value of the input.

@return ArrayList

public function getOptions()
    {
        $options = parent::getOptions();

        foreach ($options as $option) {
            $option->Name = "{$this->name}[]";
        }

        return $options;
    }

public void setMatchReturnValue(String filterReturnValue) {
    if (filterReturnValue.equalsIgnoreCase("accept")) {
      matchReturnValue = ACCEPT;
    } else if (filterReturnValue.equalsIgnoreCase("deny")) {
      matchReturnValue = DENY;
    } else if (filterReturnValue.equalsIgnoreCase("neutral")) {
      matchReturnValue = NEUTRAL;
    } else {
      LogLog.error("invalid matchReturnValue: " + filterReturnValue);
    }
  }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Shortcut of PUT request
@param string|Request $url request URL string, or request object.
@param string $content content to be put.
@return Response result response object.

public function put($url, $content = '')
    {
        $req = $url instanceof Request ? $url : $this->buildRequest('PUT', $url);
        $req->setBody($content);
        return $this->exec($req);
    }

def get_item_api(self, resource):

        parameters = self.get_item_parameters(resource)

        get_item_api = {
            'path': '/%s/{id}' % resource.get_api_name(),
            'description': 'Operations on %s' % resource.model.__name__,
            'operations': [
                {
                    'httpMethod': 'GET',
                    'nickname': 'get%s' % resource.model.__name__,
                    'summary': 'Get %s by its unique ID' %
                               resource.model.__name__,
                    'parameters': parameters,
                }
            ]
        }

        return get_item_api

Instruction: Given a code description, retrieve the corresponding code.


Question:
@param $url
@param $data
@param array $headers

@return bool

protected function request($url, $data, array $headers = array())
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        curl_exec($ch);
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return floor($statusCode / 100) == 2;
    }

protected function prepareCurl()
    {
        $this->curl = curl_init();
        $this->complete = Complete::factory(function() {
            if ($this->curl) {
                curl_close($this->curl);
            }
            $this->curl     = null;
            $this->complete = null;
        });

        foreach(self::$curlOptions as $option => $value) {
            curl_setopt($this->curl, $option, $value);
        }
        if ($this->method === HttpMethods::POST) {
            curl_setopt($this->curl, CURLOPT_POST, true);
        }
        if (!empty($this->auth)) {
            curl_setopt($this->curl, CURLOPT_USERPWD, sprintf(
                "%s:%s",
                $this->auth["user"],
                $this->auth["pass"]
            ));
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// parseTxAcceptedNtfnParams parses out the transaction hash and total amount
// from the parameters of a txaccepted notification.

func parseTxAcceptedNtfnParams(params []json.RawMessage) (*chainhash.Hash,
	btcutil.Amount, error) {

	if len(params) != 2 {
		return nil, 0, wrongNumParams(len(params))
	}

	// Unmarshal first parameter as a string.
	var txHashStr string
	err := json.Unmarshal(params[0], &txHashStr)
	if err != nil {
		return nil, 0, err
	}

	// Unmarshal second parameter as a floating point number.
	var famt float64
	err = json.Unmarshal(params[1], &famt)
	if err != nil {
		return nil, 0, err
	}

	// Bounds check amount.
	amt, err := btcutil.NewAmount(famt)
	if err != nil {
		return nil, 0, err
	}

	// Decode string encoding of transaction sha.
	txHash, err := chainhash.NewHashFromStr(txHashStr)
	if err != nil {
		return nil, 0, err
	}

	return txHash, amt, nil
}

func (h *handlerManager) DryUplink(ctx context.Context, in *pb.DryUplinkMessage) (*pb.DryUplinkResult, error) {
	app := in.App

	flds := ""
	valid := true
	var logs []*pb.LogEntry
	var decoder PayloadDecoder
	switch application.PayloadFormat(app.PayloadFormat) {
	case "", application.PayloadFormatCustom:
		decoder = &CustomUplinkFunctions{
			Decoder:   app.Decoder,
			Converter: app.Converter,
			Validator: app.Validator,
			Logger:    functions.NewEntryLogger(),
		}
	case application.PayloadFormatCayenneLPP:
		decoder = &cayennelpp.Decoder{}
	default:
		return nil, errors.NewErrInvalidArgument("App", "unknown payload format")
	}

	fields, val, err := decoder.Decode(in.Payload, uint8(in.Port))
	if err != nil {
		return nil, err
	}

	valid = val
	logs = decoder.Log()

	marshalled, err := json.Marshal(fields)
	if err != nil {
		return nil, err
	}

	flds = string(marshalled)

	return &pb.DryUplinkResult{
		Payload: in.Payload,
		Fields:  flds,
		Valid:   valid,
		Logs:    logs,
	}, nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Set an Insight console to direct all logging calls to

@param object $console The console object to log to
@return void

public function setLogToInsightConsole($console)
    {
        if(is_string($console)) {
            if(get_class($this)!='FirePHP_Insight' && !is_subclass_of($this, 'FirePHP_Insight')) {
                throw new Exception('FirePHP instance not an instance or subclass of FirePHP_Insight!');
            }
            $this->logToInsightConsole = $this->to('request')->console($console);
        } else {
            $this->logToInsightConsole = $console;
        }
    }

function(result, raw_block) {

		/** @type {_cView} */
		var config = {
				type: 'view',
				"class": null
			},
			i = 0,
			count;

		if (Lava.schema.parsers.PRESERVE_VIEW_NAME) {
			config.view_name = raw_block.name;
		}

		if ('arguments' in raw_block) {

			if (Lava.schema.DEBUG && raw_block.arguments.length > 1) Lava.t('Block may have no more than one argument');
			if (raw_block.arguments.length) {
				config.argument = raw_block.arguments[0];
			}

		}

		if ('class_locator' in raw_block) {
			config.class_locator = raw_block.class_locator;
			config.real_class = raw_block.real_class;
			config['class'] = Lava.schema.view.DEFAULT_CLASS_LOCATOR_GATEWAY;
		} else {
			config['class'] = this._viewNameToClass(raw_block.name);
		}

		if (raw_block.prefix == '$') {
			config.container = {type: 'Morph'};
		}

		this._parseViewHash(config, raw_block.hash); // before content, so directives could be parsed into the config

		if ('content' in raw_block) {
			config.template = this.compileTemplate(raw_block.content, config);
		} else {
			config.template = [];
		}

		if ('else_content' in raw_block) {
			config.else_template = this.compileTemplate(raw_block.else_content);
		}

		if ('elseif_arguments' in raw_block) {
			config.elseif_arguments = raw_block.elseif_arguments;
			config.elseif_templates = [];
			for (count = raw_block.elseif_content.length; i < count; i++) {
				config.elseif_templates.push(this.compileTemplate(raw_block.elseif_content[i]));
			}
		}

		result.push(config);

	}

Instruction: Given a code description, retrieve the corresponding code.


Question: This method initializes this

private void initialize() {
        this.setContentPane(getJPanel());
        this.setVisible(false);
        this.setTitle(Constant.messages.getString("history.filter.title"));
        if (Model.getSingleton().getOptionsParam().getViewParam().getWmUiHandlingOption() == 0) {
        	this.setSize(600, 300);
        }
        centreDialog();
        this.getRootPane().setDefaultButton(btnApply);
        this.pack();
	}

def _init_humidity(self):

        if not self._humidity_init:
            self._humidity_init = self._humidity.humidityInit()
            if not self._humidity_init:
                raise OSError('Humidity Init Failed')

Instruction: Given a code description, retrieve the corresponding code.


Question:
/* (non-Javadoc)
@see com.ibm.ws.sib.msgstore.cache.links.LinkOwner#loadOwnedLinks()

public final boolean loadOwnedLinks() throws SevereMessageStoreException
    {
        boolean loaded = false;
        if (null == _items)
        {
            _items();
            loaded = true;
        }
        return loaded;
    }

def send_comment_email(email, package_owner, package_name, commenter):
    """"""
    link = '{CATALOG_URL}/package/{owner}/{pkg}/comments'.format(
        CATALOG_URL=CATALOG_URL, owner=package_owner, pkg=package_name)
    subject = "New comment on {package_owner}/{package_name}".format(
        package_owner=package_owner, package_name=package_name)
    html = render_template('comment_email.html', commenter=commenter, link=link)
    body = render_template('comment_email.txt', commenter=commenter, link=link)
    send_email(recipients=[email], sender=DEFAULT_SENDER, subject=subject,
               html=html, body=body)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Change the data set in the Somoclu object. It is useful when the
        data is updated and the training should continue on the new data.

        :param data: The training data.
        :type data: 2D numpy.array of float32.

def update_data(self, data):

        oldn_dim = self.n_dim
        if data.dtype != np.float32:
            print("Warning: data was not float32. A 32-bit copy was made")
            self._data = np.float32(data)
        else:
            self._data = data
        self.n_vectors, self.n_dim = data.shape
        if self.n_dim != oldn_dim and oldn_dim != 0:
            raise Exception("The dimension of the new data does not match!")
        self.bmus = np.zeros(self.n_vectors * 2, dtype=np.intc)

def to_dict(self):

        return {
            'model_type': 'segmented_discretechoice',
            'name': self.name,
            'segmentation_col': self.segmentation_col,
            'sample_size': self.sample_size,
            'probability_mode': self.probability_mode,
            'choice_mode': self.choice_mode,
            'choosers_fit_filters': self.choosers_fit_filters,
            'choosers_predict_filters': self.choosers_predict_filters,
            'alts_fit_filters': self.alts_fit_filters,
            'alts_predict_filters': self.alts_predict_filters,
            'interaction_predict_filters': self.interaction_predict_filters,
            'estimation_sample_size': self.estimation_sample_size,
            'prediction_sample_size': self.prediction_sample_size,
            'choice_column': self.choice_column,
            'default_config': {
                'model_expression': self.default_model_expr,
            },
            'remove_alts': self.remove_alts,
            'fitted': self.fitted,
            'models': {
                yamlio.to_scalar_safe(name):
                    self._process_model_dict(m.to_dict())
                for name, m in self._group.models.items()
            }
        }

Instruction: Given a code description, retrieve the corresponding code.