Question:
// CounterClockwise the drone to spin in counter clockwise direction
// speed can be a value from `0.0` to `1.0`.

func (a *Driver) CounterClockwise(speed float64) {
	a.adaptor().drone.Counterclockwise(speed)
}

def is_correct(self):

        state = True

        # _internal_host_check is for having an host check result
        # without running a check plugin
        if self.command_name.startswith('_internal_host_check'):
            # Command line may contain: [state_id][;output]
            parameters = self.command_line.split(';')
            if len(parameters) < 2:
                self.command_name = "_internal_host_check;0;Host assumed to be UP"
                self.add_warning("[%s::%s] has no defined state nor output. Changed to %s"
                                 % (self.my_type, self.command_name, self.command_name))
            elif len(parameters) < 3:
                state = 3
                try:
                    state = int(parameters[1])
                except ValueError:
                    self.add_warning("[%s::%s] required a non integer state: %s. Using 3."
                                     % (self.my_type, self.command_name, parameters[1]))

                if state > 4:
                    self.add_warning("[%s::%s] required an impossible state: %d. Using 3."
                                     % (self.my_type, self.command_name, state))

                output = {0: "UP", 1: "DOWN", 2: "DOWN", 3: "UNKNOWN", 4: "UNREACHABLE", }[state]
                self.command_name = "_internal_host_check;Host assumed to be %s" % output

                self.add_warning("[%s::%s] has no defined output. Changed to %s"
                                 % (self.my_type, self.command_name, self.command_name))
            elif len(parameters) > 3:
                self.command_name = "%s;%s;%s" % (parameters[0], parameters[1], parameters[2])

                self.add_warning("[%s::%s] has too many parameters. Changed to %s"
                                 % (self.my_type, self.command_name, self.command_name))

        return super(Command, self).is_correct() and state

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


Question:
Run the migrations.

@return void

public function up()
    {
        Schema::table('asset_versions', function (Blueprint $table) {
            $table->float('aspect_ratio', 8, 3)
                ->nullable()
                ->default(null);
        });

        $versions = AssetVersion::all();

        foreach ($versions as $version) {
            $path = storage_path().'/boomcms/assets/'.$version->id;

            if (is_readable($path)) {
                $info = FileInfo::create(new File($path));

                $version->fill([
                    'aspect_ratio' => $info->getAspectRatio(),
                    'width'        => $info->getWidth(),
                    'height'       => $info->getHeight(),
                    'metadata'     => $info->getMetadata(),
                ])->save();
            }
        }
    }

func (md *RootMetadataV2) ClearForV4Migration() {
	md.WKeys = nil
	md.RKeys = nil
	md.Extra.UnresolvedWriters = nil
	md.UnresolvedReaders = nil
}

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


Question:
This function returns true if it can upgrade an assignment from the 2.2 module.

@param string $type The plugin type
@param int $version The plugin version
@return bool

public function can_upgrade($type, $version) {
        if ($type == 'offline' && $version >= 2011112900) {
            return true;
        }
        foreach ($this->submissionplugins as $plugin) {
            if ($plugin->can_upgrade($type, $version)) {
                return true;
            }
        }
        foreach ($this->feedbackplugins as $plugin) {
            if ($plugin->can_upgrade($type, $version)) {
                return true;
            }
        }
        return false;
    }

public static AddonDependencyEntry create(String name, VersionRange range)
   {
      return create(name, range, false, false);
   }

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


Question:
Return the `c:tx` element for this data label, with its `c:rich`
        child and descendants, newly created if not yet present.

def _get_or_add_tx_rich(self):

        dLbl = self._get_or_add_dLbl()

        # having a c:spPr or c:txPr when a c:tx is present causes the "can't
        # save" bug on bubble charts. Remove c:spPr and c:txPr when present.
        dLbl._remove_spPr()
        dLbl._remove_txPr()

        return dLbl.get_or_add_tx_rich()

def visit_Name(self, node, store_as_param=False, **kwargs):
        """"""
        if store_as_param or node.ctx == 'param':
            self.symbols.declare_parameter(node.name)
        elif node.ctx == 'store':
            self.symbols.store(node.name)
        elif node.ctx == 'load':
            self.symbols.load(node.name)

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


Question: Register the log filesystem.

private function registerFilesystem()
    {
        $this->singleton(Contracts\Utilities\Filesystem::class, function ($app) {
            /**
             * @var  \Illuminate\Config\Repository      $config
             * @var  \Illuminate\Filesystem\Filesystem  $files
             */
            $config     = $app['config'];
            $files      = $app['files'];
            $filesystem = new Utilities\Filesystem($files, $config->get('log-viewer.storage-path'));

            $pattern = $config->get('log-viewer.pattern', []);

            $filesystem->setPattern(
                Arr::get($pattern, 'prefix',    Utilities\Filesystem::PATTERN_PREFIX),
                Arr::get($pattern, 'date',      Utilities\Filesystem::PATTERN_DATE),
                Arr::get($pattern, 'extension', Utilities\Filesystem::PATTERN_EXTENSION)
            );

            return $filesystem;
        });
    }

func SyslogHandler(priority syslog.Priority, tag string, fmtr Format) (Handler, error) {
	wr, err := syslog.New(priority, tag)
	return sharedSyslog(fmtr, wr, err)
}

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


Question: // Load retrieve the RETS Compact metadata from the server

func (ic *IncrementalCompact) Load(ctx context.Context, sess rets.Requester, url string) error {
	// extract an id'd subesection of metadata
	get := func(id, mtype string) (*rets.CompactMetadata, error) {
		if id == "" {
			id = "0"
		}
		params := rets.MetadataParams{
			Format: "COMPACT",
			MType:  mtype,
			ID:     id,
		}
		req := rets.MetadataRequest{
			URL:            url,
			MetadataParams: params,
		}
		reader, er := rets.MetadataStream(rets.MetadataResponse(ctx, sess, req))
		if er != nil {
			return nil, er
		}
		return rets.ParseMetadataCompactResult(reader)
	}
	msys, err := get("", metadata.MISystem.Name)
	if err != nil {
		return err
	}
	ic.Response = msys.Response
	ic.MSystem = msys.MSystem
	ic.Elements = map[string][]rets.CompactData{}
	// fmt.Printf("compact system: %v\n", compact)
	cds, err := ic.extractChildren(get, []string{}, metadata.MISystem)
	if err != nil {
		return err
	}
	for _, cd := range cds {
		// extract children from this element and put in the system elem
		ic.Elements[cd.Element] = append(ic.Elements[cd.Element], cd)
	}
	return nil
}

def config_get(self, pattern='*'):

        result = {}
        for name, value in self.redis_config.items():
            if fnmatch.fnmatch(name, pattern):
                try:
                    result[name] = int(value)
                except ValueError:
                    result[name] = value
        return result

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


Question:
Encodes the column's type.

@param t {@code <T>}
@return {@code byte[]}

public byte[] encode(T t) {
        if (t == null) {
            if (!nullable) {
                throw new InvalidArgument("cannot encode a null type");
            }
            return getNullValue();
        }
        return encodeType(t);
    }

public void writeSuccessResult(int line) {
        logger.debug("Write Success result => line:{}", line);
        writeValue(resultColumnName, line, Messages.getMessage(Messages.SUCCESS_MESSAGE));
    }

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


Question: // SetCacheNodeType sets the CacheNodeType field's value.

func (s *CacheNodeTypeSpecificValue) SetCacheNodeType(v string) *CacheNodeTypeSpecificValue {
	s.CacheNodeType = &v
	return s
}

@Override
	public void clearCache() {
		entityCache.clearCache(CommerceShippingFixedOptionRelImpl.class);

		finderCache.clearCache(FINDER_CLASS_NAME_ENTITY);
		finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
		finderCache.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
	}

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


Question:
// Time converts the event's time into a string according to the given format.
// The format is the same as used by time.Format().

func (formatter *Formatter) Time(format string) string {
	return formatter.Event.Time.Format(format)
}

public function completed_at_datetimepicker()
    {
        if ($this->wrappedObject->completed_at) {
            return $this->dates->make($this->wrappedObject->completed_at)->format('Y-m-d H:i');
        }
    }

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


Question:
Return the output as array.

@return array

public function getStdOutAsArray() : array
    {
        if (null === $this->buffer) {
            $this->buffer = $this->textToBuffer();
        }
        return $this->buffer;
    }

public function showFinish()
    {
        $processingTime = $this->getFormatTime($this->diffBetweenStart());
        $message = "Finished after $processingTime\tHandled: $this->handled items";

        $this->stdout(PHP_EOL . $message . PHP_EOL, static::FG_GREEN);
        // Yii::$app->controller->stdout(PHP_EOL . $message . PHP_EOL, Console::FG_GREEN);
    }

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


Question:
Check if given scope descriptor contains given scope
@param  {ScopeDescriptor}  descriptor
@param  {String}  scope
@return {Boolean}

function hasScope(descriptor, scope) {
	for (let i = 0; i < descriptor.scopes.length; i++) {
		if (descriptor.scopes[i].includes(scope)) {
			return true;
		}
	}

	return false;
}

protected function getBodyParametersFromDocBlock(array $tags)
    {
        $parameters = collect($tags)
            ->filter(function ($tag) {
                return $tag instanceof Tag && $tag->getName() === 'bodyParam';
            })
            ->mapWithKeys(function ($tag) {
                preg_match('/(.+?)\s+(.+?)\s+(required\s+)?(.*)/', $tag->getContent(), $content);
                if (empty($content)) {
                    // this means only name and type were supplied
                    list($name, $type) = preg_split('/\s+/', $tag->getContent());
                    $required = false;
                    $description = '';
                } else {
                    list($_, $name, $type, $required, $description) = $content;
                    $description = trim($description);
                    if ($description == 'required' && empty(trim($required))) {
                        $required = $description;
                        $description = '';
                    }
                    $required = trim($required) == 'required' ? true : false;
                }

                $type = $this->normalizeParameterType($type);
                list($description, $example) = $this->parseDescription($description, $type);
                $value = is_null($example) ? $this->generateDummyValue($type) : $example;

                return [$name => compact('type', 'description', 'required', 'value')];
            })->toArray();

        return $parameters;
    }

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


Question:
// CanRemoveMember checks if a member can be removed from
// the context of the current node.

func (n *Node) CanRemoveMember(id uint64) bool {
	members := n.cluster.Members()
	nreachable := 0 // reachable managers after removal

	for _, m := range members {
		if m.RaftID == id {
			continue
		}

		// Local node from where the remove is issued
		if m.RaftID == n.Config.ID {
			nreachable++
			continue
		}

		if n.transport.Active(m.RaftID) {
			nreachable++
		}
	}

	nquorum := (len(members)-1)/2 + 1

	return nreachable >= nquorum
}

public function moveAction(Request $request)
    {
        $id = $request->get('id');
        $targetId = $request->get('target');

        $treeManager = $this->get('phlexible_tree.tree_manager');
        $tree = $treeManager->getByNodeId($id);
        $node = $tree->get($id);

        $targetTree = $treeManager->getByNodeId($targetId);
        $targetNode = $tree->get($targetId);

        if ($id === $targetId) {
            return new ResultResponse(false, 'source_id === target_id');
        }

        $tree->move($node, $targetNode, $this->getUser()->getId());

        return new ResultResponse(true, 'Element moved.', ['id' => $id, 'parent_id' => $targetId]);
    }

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


Question: // Resolve returns a dummy ComponentMatch for any value input.

func (r PipelineResolver) Resolve(value string) (*ComponentMatch, error) {
	return &ComponentMatch{
		Value:     value,
		LocalOnly: true,
	}, nil
}

func (nr *nameResolver) Enter(inNode ast.Node) (ast.Node, bool) {
	return inNode, false
}

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


Question:
Starts the instance.

        :raises RuntimeError: has been already started.
        :raises TypeError: :meth:`run` is not canonical.

def start(self, *args, **kwargs):

        if self.is_running():
            raise RuntimeError('Already started')
        self._running = self.run(*args, **kwargs)
        try:
            yielded = next(self._running)
        except StopIteration:
            raise TypeError('run() must yield just one time')
        if yielded is not None:
            raise TypeError('run() must yield without value')

def stop(self):
        """"""
        stopped = []
        for interface_id, proxy in self.proxies.items():
            if interface_id in self.failed_inits:
                LOG.warning("ServerThread.stop: Not performing de-init for %s" % interface_id)
                continue
            if proxy._callbackip and proxy._callbackport:
                callbackip = proxy._callbackip
                callbackport = proxy._callbackport
            else:
                callbackip = proxy._localip
                callbackport = self._localport
            remote = "http://%s:%i" % (callbackip, callbackport)
            LOG.debug("ServerThread.stop: init('%s')" % remote)
            if not callbackip in stopped:
                try:
                    proxy.init(remote)
                    stopped.append(callbackip)
                    LOG.info("Proxy de-initialized: %s" % remote)
                except Exception as err:
                    LOG.debug("proxyInit: Exception: %s" % str(err))
                    LOG.warning("Failed to de-initialize proxy")
        self.proxies.clear()
        LOG.info("Shutting down server")
        self.server.shutdown()
        LOG.debug("ServerThread.stop: Stopping ServerThread")
        self.server.server_close()
        LOG.info("Server stopped")

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


Question:
Decode Variable Header

@param string & $packet_data
@param int    & $pos
@return bool
@throws Exception

protected function decodeVariableHeader(& $packet_data, & $pos)
    {
        $this->session_present = ord($packet_data[2]) & 0x01;

        $this->return_code = ord($packet_data[3]);

        if ($this->return_code != 0) {
            $error = isset(self::$connect_errors[$this->return_code]) ? self::$connect_errors[$this->return_code] : 'Unknown error';
            Debug::Log(
                Debug::ERR,
                sprintf(
                    "Connection failed! (Error: 0x%02x 0x%02x|%s)",
                    ord($packet_data[2]),
                    $this->return_code,
                    $error
                )
            );

            /*
             If a server sends a CONNACK packet containing a non-zero return code it MUST
             then close the Network Connection [MQTT-3.2.2-5]
             */
            throw new Exception\ConnectError($error);
        }

        if ($this->session_present) {
            Debug::Log(Debug::DEBUG, "CONNACK: Session Present Flag: ON");
        } else {
            Debug::Log(Debug::DEBUG, "CONNACK: Session Present Flag: OFF");
        }
    }

public function check()
    {
        $this->pingBinFactory();

        $ipAddress = ip_address_from_hostname($this->target->hostname);

        $latency = $this->ping($ipAddress);

        $latencyFormatted = $latency ? "{$latency}ms" : 'error!';

        $this->target->setDisplay(
            "{$this->target->name} ({$latencyFormatted})"
        );

        if ($latency === false || $latency > $this->target->acceptedLatency) {
            $result = $this->makeResult(
                false,
                sprintf(
                    $this->target->getErrorMessage(),
                    $this->hosnameAndIp($this->target->hostname, $ipAddress),
                    $latency === false ? '[ping error]' : $latency,
                    $this->target->acceptedLatency
                )
            );
        } else {
            $result = $this->makeHealthyResult();
        }

        return $result->setValue($latency)->setValueHuman("{$latency}ms");
    }

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


Question:
Sets the host to connect to.

@param host the host to connect to. Parameter value must be non-null.
@throws IllegalStateException if the connection is already open

public void setHost(String host) throws IllegalStateException {
        if (host == null) {
            throw new IllegalArgumentException("host parameter is null");
        }
        assertNotOpen();
        hostName = host;
    }

public SipServletRequest createRequest(SipApplicationSession sipAppSession,
			String method, Address from, Address to, String handler, String originalCallId, String fromTagToUse) {
		if (logger.isDebugEnabled()) {
			logger
					.debug("Creating new SipServletRequest for SipApplicationSession["
							+ sipAppSession
							+ "] METHOD["
							+ method
							+ "] FROM_A[" + from + "] TO_A[" + to + "]");
		}

		validateCreation(method, sipAppSession);

		try {
			//javadoc specifies that a copy of the address should be done hence the clone
			return createSipServletRequest(sipAppSession, method, (Address)from.clone(), (Address)to.clone(), handler, originalCallId, fromTagToUse);
		} catch (ServletParseException e) {
			logger.error("Error creating sipServletRequest", e);
			return null;
		}
	}

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


Question: // String returns a string representation of the rwSetKey

func (k *rwSetKey) String() string {
	return fmt.Sprintf("txID: %s, seq: %d, namespace: %s, collection: %s, hash: %s", k.txID, k.seqInBlock, k.namespace, k.collection, k.hash)
}

def Parse(self, stat, unused_knowledge_base):
    """"""
    value = stat.registry_data.GetValue()

    if not str(value).isdigit() or int(value) > 999 or int(value) < 0:
      raise parser.ParseError(
          "Invalid value for CurrentControlSet key %s" % value)
    yield rdfvalue.RDFString(
        "HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet%03d" % int(value))

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


Question:
Handle an exception that was thrown from inside
{@link PubSubListener#onMessage(String,String)}.

@param channel
the name of the channel that was being processed when the
exception was thrown
@param e
the exception that was thrown

protected void recoverFromException(final String channel, final Exception e) {
        final RecoveryStrategy recoveryStrategy = this.exceptionHandlerRef.get().onException(this, e, channel);
        switch (recoveryStrategy) {
        case RECONNECT:
            LOG.info("Ignoring RECONNECT strategy in response to exception because this is a pool", e);
            break;
        case TERMINATE:
            LOG.warn("Terminating in response to exception", e);
            end(false);
            break;
        case PROCEED:
            break;
        default:
            LOG.error("Unknown RecoveryStrategy: " + recoveryStrategy
                    + " while attempting to recover from the following exception; Admin proceeding...", e);
            break;
        }
    }

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:
Try to identify the file where a hook is defined
@param     array     $hooks
@param     string    $type
@param     string    $file
@param     string    $class
@param     string    $method
@return    string                 File Name

public function findHookInDefinition(array $hooksDef, $type, $file, $class, $method)
    {
        foreach ($hooksDef as $defFile => $hooks) {
            if (!array_key_exists($type, $hooks)) {
                continue;
            }

            // Find a hook
            foreach ($hooks[$type] as $hook) {
                if ($hook[2] == $file && $hook[3] == $class && $hook[4] == $method) {
                    return $defFile;
                }
            }
        }
    }

public function setWebHook($url)
    {
        $this->data->notification = new stdClass;
        $this->data->notification->webhook = new stdClass;
        $this->data->notification->webhook->url = $url;

        return $this;
    }

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


Question:
Gets all user rule directories. This includes both the ones that they specify (eg, /path/to/rules) as well as ones that Windup provides by
default (eg, WINDUP_HOME/rules and ~/.windup/rules).

public Iterable<Path> getAllUserRulesDirectories()
    {
        Set<Path> results = new HashSet<>();
        results.addAll(getDefaultUserRulesDirectories());

        Collection<File> userSpecifiedFiles = getOptionValue(UserRulesDirectoryOption.NAME);
        if (userSpecifiedFiles != null && !userSpecifiedFiles.isEmpty())
        {
            userSpecifiedFiles.stream().forEach(file -> {
                results.add(file.toPath());
            });
        }
        return results;
    }

public static function generate($args, $opts, $console)
    {
        $checklist = new ConsoleKit\Widgets\Checklist($console);
        foreach ($args as $action) {
            $console->writeln("Generating '$action'");
            $filename = ltrim($action, '/') . '.php';

            $actionsDir = (array) Atomik::get('atomik.dirs.actions');
            $actionsDir = array_shift($actionsDir);
            $checklist->step("Creating action file in $actionsDir", function() use ($actionsDir, $filename) {
                return ConsoleKit\FileSystem::touch(ConsoleKit\FileSystem::join($actionsDir, $filename),
                    "<?php\n\n// Logic goes here\n");
            });

            $viewsDir = (array) Atomik::get('atomik.dirs.views');
            $viewsDir = array_shift($viewsDir);
            $checklist->step("Creating view file in $viewsDir", function() use ($viewsDir, $filename) {
                return ConsoleKit\FileSystem::touch(ConsoleKit\FileSystem::join($viewsDir, $filename));
            });

            Atomik::fireEvent('Console::Generate', array($action));
        }
    }

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


Question: Reallocate and rehash the hash set.

private void expandAndRehash() {
    final int[] newHashSet = new int[hashSet.length * 2];
    final int bucketMask = (newHashSet.length - 1);

    for (int j = 0; j < hashSet.length; j++) {
      final int state = hashSet[j];
      if (state > 0) {
        int slot = hash(state, stateLength(state)) & bucketMask;
        for (int i = 0; newHashSet[slot] > 0;) {
          slot = (slot + (++i)) & bucketMask;
        }
        newHashSet[slot] = state;
      }
    }
    this.hashSet = newHashSet;
  }

public void resetRunningTasks(TaskType type) {
    Map<String, Integer> runningMap = (type == TaskType.MAP ?
                                       poolRunningMaps : poolRunningReduces);
    for (String poolName : runningMap.keySet()) {
      runningMap.put(poolName, 0);
    }
  }

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


Question:
I2OSP function
@param {Number} x - Number to be encoded to byte array in network byte order.
@param {Number} len - Length of byte array
@return {Uint8Array} - Encoded number.

function i2osp(x, len){
  const r = new Uint8Array(len);
  r.forEach( (elem, idx) => {
    const y = 0xFF & (x >> (idx*8));
    r[len - idx - 1] = y;
  });
  return r;
}

func (s *StableBloomFilter) ReadFrom(stream io.Reader) (int64, error) {
	var m, p, k, bufferLen uint64
	var max uint8
	err := binary.Read(stream, binary.BigEndian, &m)
	if err != nil {
		return 0, err
	}
	err = binary.Read(stream, binary.BigEndian, &p)
	if err != nil {
		return 0, err
	}
	err = binary.Read(stream, binary.BigEndian, &k)
	if err != nil {
		return 0, err
	}
	err = binary.Read(stream, binary.BigEndian, &max)
	if err != nil {
		return 0, err
	}
	err = binary.Read(stream, binary.BigEndian, &bufferLen)
	if err != nil {
		return 0, err
	}
	indexBuffer := make([]uint, bufferLen)
	var index uint64
	for i := range indexBuffer {
		err = binary.Read(stream, binary.BigEndian, &index)
		if err != nil {
			return 0, err
		}
		indexBuffer[i] = uint(index)
	}
	s.m = uint(m)
	s.p = uint(p)
	s.k = uint(k)
	s.max = max
	s.indexBuffer = indexBuffer

	n, err := s.cells.ReadFrom(stream)
	if err != nil {
		return 0, err
	}
	return int64((3+len(s.indexBuffer))*binary.Size(uint64(0))) +
		int64(1*binary.Size(uint8(0))) + int64(1*binary.Size(int64(0))) + n, nil
}

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


Question: Returns the previous command, if any.

def scroll_up(self):

        self._index += 1
        nb_commands = len(self._history)
        if self._index >= nb_commands:
            self._index = nb_commands - 1
        try:
            return self._history[self._index]
        except IndexError:
            return ''

function (cmd) {
			self.alreadyProcessedTraces[cmd.modelElement.path()] = self.alreadyProcessedTraces[cmd.modelElement.path()] || {};
			self.alreadyProcessedTraces[cmd.modelElement.path()][cmd.toString()] = cmd;
		}

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


Question:
/* --- Utility functions --- */
// Create a byte slice from an uint64

func byteID(x uint64) []byte {
	b := make([]byte, 8)
	binary.BigEndian.PutUint64(b, x)
	return b
}

@Nonnull
	public static <T> LTieByteFunctionBuilder<T> tieByteFunction(Consumer<LTieByteFunction<T>> consumer) {
		return new LTieByteFunctionBuilder(consumer);
	}

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


Question:
Pattern for detecting two EntityReferences are controlling consecutive reactions, where
output of one reaction is input to the other.

@param blacklist to detect ubiquitous small molecules
@return the pattern

public static Pattern catalysisPrecedes(Blacklist blacklist)
	{
		Pattern p = new Pattern(SequenceEntityReference.class, "first ER");
		p.add(linkedER(true), "first ER", "first generic ER");
		p.add(erToPE(), "first generic ER", "first simple controller PE");
		p.add(linkToComplex(), "first simple controller PE", "first controller PE");
		p.add(peToControl(), "first controller PE", "first Control");
		p.add(controlToConv(), "first Control", "first Conversion");
		p.add(new Participant(RelType.OUTPUT, blacklist, true), "first Control", "first Conversion", "linker PE");
		p.add(new NOT(new ConstraintChain(new ConversionSide(ConversionSide.Type.OTHER_SIDE), linkToSpecific())), "linker PE", "first Conversion", "linker PE");
		p.add(type(SmallMolecule.class), "linker PE");
		p.add(new ParticipatesInConv(RelType.INPUT, blacklist), "linker PE", "second Conversion");
		p.add(new NOT(new ConstraintChain(new ConversionSide(ConversionSide.Type.OTHER_SIDE), linkToSpecific())), "linker PE", "second Conversion", "linker PE");
		p.add(equal(false), "first Conversion", "second Conversion");

		// make sure that conversions are not replicates or reverse of each other
		// and also outward facing sides of reactions contain at least one non ubique
		p.add(new ConstraintAdapter(3, blacklist)
		{
			@Override
			public boolean satisfies(Match match, int... ind)
			{
				Conversion cnv1 = (Conversion) match.get(ind[0]);
				Conversion cnv2 = (Conversion) match.get(ind[1]);
				SmallMolecule linker = (SmallMolecule) match.get(ind[2]);

				Set<PhysicalEntity> input1 = cnv1.getLeft().contains(linker) ? cnv1.getRight() : cnv1.getLeft();
				Set<PhysicalEntity> input2 = cnv2.getLeft().contains(linker) ? cnv2.getLeft() : cnv2.getRight();
				Set<PhysicalEntity> output1 = cnv1.getLeft().contains(linker) ? cnv1.getLeft() : cnv1.getRight();
				Set<PhysicalEntity> output2 = cnv2.getLeft().contains(linker) ? cnv2.getRight() : cnv2.getLeft();

				if (input1.equals(input2) && output1.equals(output2)) return false;
				if (input1.equals(output2) && output1.equals(input2)) return false;

				if (blacklist != null)
				{
					Set<PhysicalEntity> set = new HashSet<PhysicalEntity>(input1);
					set = blacklist.getNonUbiques(set, RelType.INPUT);
					set.removeAll(output2);
					if (set.isEmpty())
					{
						set.addAll(output2);
						set = blacklist.getNonUbiques(set, RelType.OUTPUT);
						set.removeAll(input1);

						if (set.isEmpty()) return false;
					}
				}
				return true;
			}
		}, "first Conversion", "second Conversion", "linker PE");

		p.add(new RelatedControl(RelType.INPUT, blacklist), "linker PE", "second Conversion", "second Control");
		p.add(controllerPE(), "second Control", "second controller PE");
		p.add(new NOT(compToER()), "second controller PE", "first ER");
		p.add(linkToSpecific(), "second controller PE", "second simple controller PE");
		p.add(type(SequenceEntity.class), "second simple controller PE");
		p.add(peToER(), "second simple controller PE", "second generic ER");
		p.add(linkedER(false), "second generic ER", "second ER");
		p.add(equal(false), "first ER", "second ER");
		return p;
	}

func (ac *APIController) NetworkDelete(network *contivModel.Network) error {
	log.Infof("Received NetworkDelete: %+v", network)

	// Find the tenant
	tenant := contivModel.FindTenant(network.TenantName)
	if tenant == nil {
		return core.Errorf("Tenant not found")
	}

	// if the network has associated epgs, fail the delete
	epgCount := len(network.LinkSets.EndpointGroups)
	if epgCount != 0 {
		return core.Errorf("cannot delete %s has %d endpoint groups",
			network.NetworkName, epgCount)
	}

	svcCount := len(network.LinkSets.Servicelbs)
	if svcCount != 0 {
		return core.Errorf("cannot delete %s has %d services ",
			network.NetworkName, svcCount)
	}

	// In swarm-mode work-flow, if this is mapped to a docker network, reject delete
	if master.GetClusterMode() == core.SwarmMode {
		docknet, err := docknet.GetDocknetState(network.TenantName, network.NetworkName, "")
		if err == nil {
			return fmt.Errorf("cannot delete network %s mapped to docker network %s",
				network.NetworkName, docknet.DocknetUUID)
		}
		if !strings.Contains(strings.ToLower(err.Error()), "key not found") {
			log.Errorf("Error getting docknet state for %s.%s. (retval = %s)",
				network.TenantName, network.NetworkName, err.Error())
			return err
		}
		log.Infof("No docknet state for %s.%s. (retval = %s)",
			network.TenantName, network.NetworkName, err.Error())
	}

	// Remove link
	modeldb.RemoveLinkSet(&tenant.LinkSets.Networks, network)

	// Get the state driver
	stateDriver, err := utils.GetStateDriver()
	if err != nil {
		return err
	}

	// Delete the network
	networkID := network.NetworkName + "." + network.TenantName
	err = master.DeleteNetworkID(stateDriver, networkID)
	if err != nil {
		log.Errorf("Error deleting network %s. Err: %v", network.NetworkName, err)
		return err
	}

	// Save the tenant too since we removed the links
	return tenant.Write()
}

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


Question:
Transform client/server model to a database model

@param comment - client/server model to transform
@return the database model

public DbComment getDbComment(final Comment comment) {
        final DbComment dbComment = new DbComment();
        dbComment.setEntityId(comment.getEntityId());
        dbComment.setEntityType(comment.getEntityType());
        dbComment.setAction(comment.getAction());
        dbComment.setDbCommentText(comment.getCommentText());
        dbComment.setDbCommentedBy(comment.getCommentedBy());
        dbComment.setDbCreatedDateTime(comment.getCreatedDateTime());

        return dbComment;
    }

public void marshall(DescribeMLModelsRequest describeMLModelsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeMLModelsRequest.getFilterVariable(), FILTERVARIABLE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getEQ(), EQ_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGT(), GT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLT(), LT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGE(), GE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLE(), LE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNE(), NE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getPrefix(), PREFIX_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getSortOrder(), SORTORDER_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLimit(), LIMIT_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.


def group_memberships_create_many(self, data, **kwargs):
        ""
        api_path = "/api/v2/group_memberships/create_many.json"
        return self.call(api_path, method="POST", data=data, **kwargs)

public function registerMenu($top_menu_slug)
    {
        if (!isset($this->toolInfo['settings']))
            return;

	    if ($this->only_when_enabled && (!$this->enabled())) {
		    return;
	    }

        $settings=$this->toolInfo['settings'];
        add_submenu_page( $top_menu_slug, $settings['title'], $settings['menu'], 'manage_options', $this->options_page, [$this,'renderSettings']);

        foreach($this->batchTools as $batchTool) {
            if ($batchTool->enabled()) {
                add_submenu_page($top_menu_slug, $batchTool->pageTitle(), $batchTool->menuTitle(), $batchTool->capabilityRequirement(), $batchTool->menuSlug(), [
                    $batchTool,
                    'renderBatchTool'
                ]);
            }
        }
    }

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


Question:
Like :func:`getref` but print results to screen instead of returning
    a dictionary.

def showref():

    refdata = getref()
    for k, v in refdata.items():
        print("%10s: %s" % (k,v))

def git_status_all_repos(cat, hard=True, origin=False, clean=True):

    log = cat.log
    log.debug("gitter.git_status_all_repos()")

    all_repos = cat.PATHS.get_all_repo_folders()
    for repo_name in all_repos:
        log.info("Repo in: '{}'".format(repo_name))
        # Get the initial git SHA
        sha_beg = get_sha(repo_name)
        log.debug("Current SHA: '{}'".format(sha_beg))

        log.info("Fetching")
        fetch(repo_name, log=cat.log)

        git_comm = ["git", "status"]
        _call_command_in_repo(
            git_comm, repo_name, cat.log, fail=True, log_flag=True)

        sha_end = get_sha(repo_name)
        if sha_end != sha_beg:
            log.info("Updated SHA: '{}'".format(sha_end))

    return

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


Question:
Creates and yields a new layer object, then adds that layer to the map's
 collection of layers. If the srs is not provided in the initial call,
 it will need to be provided in the block.
 @return [Mapnik::Layer]

def layer(name, srs = nil)
      layer = Mapnik::Layer.new(name, srs)
      layer.map = self
      yield layer
      layers << layer
    end

def load_strain(self, strain_id, strain_genome_file):

        # logging.disable(logging.WARNING)
        strain_gp = GEMPRO(gem_name=strain_id, genome_path=strain_genome_file, write_protein_fasta_files=False)
        # logging.disable(logging.NOTSET)

        self.strains.append(strain_gp)
        return self.strains.get_by_id(strain_id)

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


Question: // ViewAndRotateKEK re-encrypts the key with a new KEK

func (k *KeyReadWriter) ViewAndRotateKEK(cb func(KEKData, PEMKeyHeaders) (KEKData, PEMKeyHeaders, error)) error {
	k.mu.Lock()
	defer k.mu.Unlock()

	updatedKEK, updatedHeaderObj, err := cb(k.kekData, k.headersObj)
	if err != nil {
		return err
	}

	keyBlock, err := k.readKey()
	if err != nil {
		return err
	}

	return k.writeKey(keyBlock, updatedKEK, updatedHeaderObj)
}

private long rotateMapWidth(long width, long height) {
    if (rotation != null && (rotation == ROTATE_90 || rotation == ROTATE_270)) {
      return height;
    }
    else {
      return width;
    }
  }

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


Question:
// Initiate is used to initiate an SA. This is the
// equivalent of `swanctl --initiate -c childname`

func (c *ClientConn) Initiate(child string, ike string) (err error) {
	inMap := map[string]interface{}{}
	if child != "" {
		inMap["child"] = child
	}
	if ike != "" {
		inMap["ike"] = ike
	}
	msg, err := c.Request("initiate", inMap)
	if err != nil {
		return err
	}
	if msg["success"] != "yes" {
		return fmt.Errorf("unsuccessful Initiate: %v", msg["errmsg"])
	}
	return nil
}

def invoke(tasks)
      remote_shell do |shell|
        # setup the deployment repository
        invoke_task(:setup,shell) if tasks.include?(:setup)

        # cd into the deployment repository
        shell.cd(shell.uri.path)

        # update the deployment repository
        invoke_task(:update,shell) if tasks.include?(:update)

        # framework tasks
        invoke_task(:install,shell) if tasks.include?(:install)
        invoke_task(:migrate,shell) if tasks.include?(:migrate)

        # server tasks
        if tasks.include?(:config)
          invoke_task(:config,shell)
        elsif tasks.include?(:start)
          invoke_task(:start,shell)
        elsif tasks.include?(:stop)
          invoke_task(:stop,shell)
        elsif tasks.include?(:restart)
          invoke_task(:restart,shell)
        end
      end

      return true
    end

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


Question:
mark the transaction as prepared (the validation was finished) and notify a possible pending commit or rollback
command

public synchronized void prepared() {
      if (trace) {
         log.tracef("[%s] Current status is %s, setting status to: PREPARED", globalTransaction.globalId(),
                    transactionState);
      }
      transactionState.add(State.PREPARED);
      notifyAll();
   }

public function saveCurrent()
    {
        if ($this->saveEnabled() && $this->isViewValid() && $this->isViewUnique())
        {
            $success = $this->saveCurrentModel();

            // Keep on only if the model save has succeeded
            if ($success)
            {
                $this->storeCurrentHash();

                $this->saveTrackables(
                    $this->getCurrent(),
                    $success
                );
            }

            return $success;
        }

        return false;
    }

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


Question:
// UploadBundleWithRevision takes a bundle's formal identifier (its URL)
// and its contents and a revision number, then uploads it into the
// store for other clients to download.

func (c FakeClient) UploadBundleWithRevision(id *charm.URL, bundleData charm.Bundle, promulgatedRevision int) error {
	return c.repo.UploadBundleWithRevision(id, bundleData, promulgatedRevision)
}

def verify_version
      app_version = options[:app_version]
      UI.message("Making sure the latest version on App Store Connect matches '#{app_version}' from the ipa file...")

      changed = options[:app].ensure_version!(app_version, platform: options[:platform])

      if changed
        UI.success("Successfully set the version to '#{app_version}'")
      else
        UI.success("'#{app_version}' is the latest version on App Store Connect")
      end
    end

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


Question:
{@inheritdoc}

@param \Ems\Contracts\Mail\MailConfig $config
@param \DateTime                      $plannedSendDate (optional)

@return \Ems\Contracts\Mail\MailContent

public function contentsFor(MailConfig $config, DateTime $plannedSendDate = null)
    {
        return $this->model->where($this->configForeignKey, $config->getId())->first();
    }

function namedParameterList()
    {
        return array( $this->AttributeName => array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 2 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ),
                      $this->DumpName =>      array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "show" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 1 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ) );
    }

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


Question: check database connection based on provided setting

public function checkConnection()
    {
        $success = false;
        $message = '';
        $config  = $this->getPostConfiguration();

        try{
            $this->makeConnection($config);

            /**
             * Just trying to show tables with current connection
             */
            switch ($config['driver']) {
                case 'mysql':
                    $tables = Capsule::select('show tables');
                    break;

                case 'sqlite':
                    $tables = Capsule::select("SELECT * FROM sqlite_master WHERE type='table'");
                    break;

                case 'sqlsrv':
                    $tables = Capsule::select("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'");
                    break;

                case 'pgsql':
                    $tables = Capsule::select("SELECT * FROM pg_catalog.pg_tables");
                    break;
            }

            $success = true;
            $message = 'Successfully connected!';

        }catch(Exception $e){
            $success = false;
            $message = $e->getMessage();
        }

        Response::headers()->set('Content-Type', 'application/json');
        Response::setBody(json_encode(
            array(
                'success' => $success,
                'message' => $message,
                'config'  => $config
            )
        ));
    }

public function getConnection()
    {
        if (null === $this->_conn && null !== $this->_tableName) {

            $this->_conn = \Doctrine::getConnectionByTableName($this->_tableName);
        }

        return $this->_conn;
    }

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


Question: Increase: 任意の箇所のバイト列と それより大きなサイズの任意のバイト列と入れ換える

def increase(self, infile):
        '''
        '''
        gf = infile[31:]
        index = gf.index(random.choice(gf))
        index_len = len(gf[index])
        large_size_index = random.choice([gf.index(g) for g in gf if len(g) > index_len])
        gf[index], gf[large_size_index] = gf[large_size_index], gf[index]
        return infile[:31] + gf

protected function execute(InputInterface $input, OutputInterface $output)
  {
    $downLocal = ModulusCLI::$appdir . 'storage' . DIRECTORY_SEPARATOR . 'framework';
    $down = $downLocal . DIRECTORY_SEPARATOR . 'down';

    $message = $input->getOption('message');
    $allow   = $input->getOption('allow') !== null ? $input->getOption('allow') : "[]";

    $downcontent = Template::asset('down_template');

    ModulusCLI::_dir($downLocal);

    if (str_contains($allow, ',')) {
      $allow = str_replace(',', '","', $allow);
      $allow = '["' . $allow . '"]';
    } elseif ($allow == "[]") {
      $allow = "[]";
    } else {
      $allow = '["' . $allow . '"]';
    }

    $downcontent = str_replace('{time}', time(), $downcontent);
    $downcontent = str_replace('{message}', $message == null ? 'null' : "\"{$message}\"", $downcontent);
    $downcontent = str_replace('{allowed}', $allow, $downcontent);

    file_put_contents($down, $downcontent);

    if (file_exists($down)) {
      return $output->writeln('<info>Application is now in maintenance mode.</info>');
    }

    $output->writeln('Failed to put application in maintenance mode.');
  }

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


Question:
Register the bindings for the JSON Web Token provider.

@return void

protected function registerJWTProvider()
    {
        $this->app->singleton('tymon.jwt.provider.jwt', function ($app) {
            $provider = $this->config('providers.jwt');

            return new $provider(
                $this->config('secret'),
                $this->config('algo'),
                $this->config('keys')
            );
        });
    }

func NewMockTokenEndpointHandler(ctrl *gomock.Controller) *MockTokenEndpointHandler {
	mock := &MockTokenEndpointHandler{ctrl: ctrl}
	mock.recorder = &MockTokenEndpointHandlerMockRecorder{mock}
	return mock
}

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


Question: Returns a map view of the given counter.

public static <E> Map<E, Double> asMap(final Counter<E> counter) {
    return new AbstractMap<E, Double>() {
      @Override
      public int size() {
        return counter.size();
      }

      @Override
      public Set<Entry<E, Double>> entrySet() {
        return counter.entrySet();
      }

      @Override
      @SuppressWarnings("unchecked")
      public boolean containsKey(Object key) {
        return counter.containsKey((E) key);
      }

      @Override
      @SuppressWarnings("unchecked")
      public Double get(Object key) {
        return counter.getCount((E) key);
      }

      @Override
      public Double put(E key, Double value) {
        double last = counter.getCount(key);
        counter.setCount(key, value);
        return last;
      }

      @Override
      @SuppressWarnings("unchecked")
      public Double remove(Object key) {
        return counter.remove((E) key);
      }

      @Override
      public Set<E> keySet() {
        return counter.keySet();
      }
    };
  }

protected function setPathInfo($path)
    {
        $key = 'urlMapper.' . ltrim($this->request->getBaseUrl(), '/') . $this->request->getPathInfo();
        $this->request->setPathInfo($path);
        $this->statsD->increment($key);
    }

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


Question: // SetBackupPlanId sets the BackupPlanId field's value.

func (s *RecoveryPointCreator) SetBackupPlanId(v string) *RecoveryPointCreator {
	s.BackupPlanId = &v
	return s
}

func (c *ClientsetSecretStore) createSecret(s *fi.Secret, name string, replace bool) (*kops.Keyset, error) {
	keyset := &kops.Keyset{}
	keyset.Name = NamePrefix + name
	keyset.Spec.Type = kops.SecretTypeSecret

	t := time.Now().UnixNano()
	id := pki.BuildPKISerial(t)

	keyset.Spec.Keys = append(keyset.Spec.Keys, kops.KeysetItem{
		Id:              id.String(),
		PrivateMaterial: s.Data,
	})

	if replace {
		return c.clientset.Keysets(c.namespace).Update(keyset)
	}
	return c.clientset.Keysets(c.namespace).Create(keyset)
}

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


Question:
// prepareStreamingRequest - prepares a request with appropriate
// headers before computing the seed signature.

func prepareStreamingRequest(req *http.Request, sessionToken string, dataLen int64, timestamp time.Time) {
	// Set x-amz-content-sha256 header.
	req.Header.Set("X-Amz-Content-Sha256", streamingSignAlgorithm)
	if sessionToken != "" {
		req.Header.Set("X-Amz-Security-Token", sessionToken)
	}

	req.Header.Set("X-Amz-Date", timestamp.Format(iso8601DateFormat))
	// Set content length with streaming signature for each chunk included.
	req.ContentLength = getStreamLength(dataLen, int64(payloadChunkSize))
	req.Header.Set("x-amz-decoded-content-length", strconv.FormatInt(dataLen, 10))
}

public function generate_head_object_url($bucket, $object, $opt = array()) {
		$this->assertParameterArray ( $opt );
		return $this->generate_user_url ( "HEAD", $bucket, $object, $opt );
	}

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


Question:
// Go invokes the streaming function asynchronously.  It returns the Call structure representing
// the invocation.

func (client *Client) StreamGo(serviceMethod string, args interface{}, replyStream interface{}) *Call {
	// first check the replyStream object is a stream of pointers to a data structure
	typ := reflect.TypeOf(replyStream)
	// FIXME: check the direction of the channel, maybe?
	if typ.Kind() != reflect.Chan || typ.Elem().Kind() != reflect.Ptr {
		log.Panic("rpc: replyStream is not a channel of pointers")
		return nil
	}

	call := new(Call)
	call.ServiceMethod = serviceMethod
	call.Args = args
	call.Reply = replyStream
	call.Stream = true
	call.sent = make(chan struct{})
	call.client = client
	client.send(call)
	return call
}

func (c *Config) Pipeline(spec *yaml.Config) *Pipeline {

	pipeline := Pipeline{
		engine: c.Engine,
		pipe:   make(chan *Line, c.Buffer),
		next:   make(chan error),
		done:   make(chan error),
	}

	var containers []*yaml.Container
	containers = append(containers, spec.Services...)
	containers = append(containers, spec.Pipeline...)

	for _, c := range containers {
		if c.Disabled {
			continue
		}
		next := &element{Container: c}
		if pipeline.head == nil {
			pipeline.head = next
			pipeline.tail = next
		} else {
			pipeline.tail.next = next
			pipeline.tail = next
		}
	}

	go func() {
		pipeline.next <- nil
	}()

	return &pipeline
}

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


Question:
Checks if another statement is equal.

Two statements are equal if and only if all of their properties are equal.

public function equals(Statement $statement): bool
    {
        if (null !== $this->id xor null !== $statement->id) {
            return false;
        }

        if (null !== $this->id && null !== $statement->id && !$this->id->equals($statement->id)) {
            return false;
        }

        if (!$this->actor->equals($statement->actor)) {
            return false;
        }

        if (!$this->verb->equals($statement->verb)) {
            return false;
        }

        if (!$this->object->equals($statement->object)) {
            return false;
        }

        if (null === $this->result && null !== $statement->result) {
            return false;
        }

        if (null !== $this->result && null === $statement->result) {
            return false;
        }

        if (null !== $this->result && !$this->result->equals($statement->result)) {
            return false;
        }

        if (null === $this->authority && null !== $statement->authority) {
            return false;
        }

        if (null !== $this->authority && null === $statement->authority) {
            return false;
        }

        if (null !== $this->authority && !$this->authority->equals($statement->authority)) {
            return false;
        }

        if ($this->created != $statement->created) {
            return false;
        }

        if (null !== $this->context xor null !== $statement->context) {
            return false;
        }

        if (null !== $this->context && null !== $statement->context && !$this->context->equals($statement->context)) {
            return false;
        }

        if (null !== $this->attachments xor null !== $statement->attachments) {
            return false;
        }

        if (null !== $this->attachments && null !== $statement->attachments) {
            if (count($this->attachments) !== count($statement->attachments)) {
                return false;
            }

            foreach ($this->attachments as $key => $attachment) {
                if (!$attachment->equals($statement->attachments[$key])) {
                    return false;
                }
            }
        }

        return true;
    }

def __label_cmp(self, other):

        if other is None:
            return -1

        label_name = strip_accents(self.name).lower()
        other_name = strip_accents(other.name).lower()
        if label_name < other_name:
            return -1
        elif label_name == other_name:
            return 0
        else:
            return 1

        if self.get_color_str() < other.get_color_str():
            return -1
        elif self.get_color_str() == other.get_color_str():
            return 0
        else:
            return 1

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


Question:
Handle an incoming request.

@param \Illuminate\Http\Request $request
@param \Closure $next
@return mixed

public function handle( $request, Closure $next )
    {
        if( !$this->sentinel->check() )
        {
            return $this->denied( $request );
        }

        return $next( $request );
    }

public function initializeArguments()
    {
        parent::initializeArguments();
        $this->registerArgument('results', '\Solarium\QueryType\Select\Result\Result', 'Query results', true);
        $this->registerArgument('document', '\Solarium\QueryType\Select\Result\Document', 'Result document to work on',
            true);
        $this->registerArgument('field', 'string', 'name of field in document to highlight', true);
        $this->registerArgument('alternateField', 'string',
            'name of alternate field in document to use for highlighting', false, null);
        $this->registerArgument('index', 'int', 'if the field is an array: index of the single element to highlight',
            false);
        $this->registerArgument('idKey', 'string', 'name of the field in document that is its ID', false, 'id');
        $this->registerArgument('highlightTagOpen', 'string', 'opening tag to insert to begin highlighting', false,
            '');
        $this->registerArgument('highlightTagClose', 'string', 'closing tag to insert to end highlighting', false,
            '');
        $this->registerArgument('raw', 'boolean', 'whether to not HTML escape the output', false, false);
    }

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


Question: // SetApiId sets the ApiId field's value.

func (s *DeleteDataSourceInput) SetApiId(v string) *DeleteDataSourceInput {
	s.ApiId = &v
	return s
}

def classify_identifier(did):

    if _is_unused_did(did):
        return 'unused on this Member Node'
    elif is_sid(did):
        return 'a Series ID (SID) of a revision chain'
    elif is_local_replica(did):
        return 'a Persistent ID (PID) of a local replica'
    elif is_unprocessed_local_replica(did):
        return (
            'a Persistent ID (PID) of an accepted but not yet processed local replica'
        )
    elif is_archived(did):
        return 'a Persistent ID (PID) of a previously archived local object'
    elif is_obsoleted(did):
        return 'a Persistent ID (PID) of a previously updated (obsoleted) local object'
    elif is_resource_map_db(did):
        return 'a Persistent ID (PID) of a local resource map'
    elif is_existing_object(did):
        return 'a Persistent ID (PID) of an existing local object'
    elif is_revision_chain_placeholder(did):
        return (
            'a Persistent ID (PID) of a remote or non-existing revision of a local '
            'replica'
        )
    elif is_resource_map_member(did):
        return (
            'a Persistent ID (PID) of a remote or non-existing object aggregated in '
            'a local Resource Map'
        )
    logger.warning('Unable to classify known identifier. did="{}"'.format(did))
    return '<UNKNOWN>'

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


Question:
Sets data

@param mixed $value The initial set to modify

@return Eden_Array_Index

public function set($value = null)
    {
        if (is_null($value)) {
            $value = array();
        }

        if (!is_array($value)) {
            $value = func_get_args();
        }

        $this->__construct($value);

        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: Download-URL from Maven

def maven_url(self):
        '''

        '''
        return '{prefix}/{path}/{artifact}/{version}/{filename}'.format(
            prefix   = MAVEN_PREFIX,
            path     = '/'.join(self.group.split('.')),
            artifact = self.artifact,
            version  = self.version,
            filename = self.filename)

void register(ResourceMonitorImpl monitorImpl) throws IOException
   {
      Path path = monitorImpl.getResourcePath();
      registerAll(path, monitorImpl);
   }

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


Question: // SetRequestId sets the RequestId field's value.

func (s *DescribeGroupOutput) SetRequestId(v string) *DescribeGroupOutput {
	s.RequestId = &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: The wait is over ...

function done(error) {
      global.clearTimeout(timer);
      eventLoop.removeListener('tick', ontick);
      eventLoop.removeListener('idle', done);
      eventLoop.browser.removeListener('error', done);

      --eventLoop.waiting;
      try {
        callback(error);
      } catch (error) {
        // If callback makes an assertion that fails, we end here.
        // If we throw error synchronously, it gets swallowed.
        setImmediate(function() {
          throw error;
        });
      }
    }

public function getWaiting(TemplateInterface $template, MediaType $mediaType, $createOnDemand = true)
    {
        $filename = $this->worker->getWaitingFilename($template, $mediaType);

        if (file_exists($filename)) {
            return $filename;
        }

        if (!$createOnDemand) {
            return null;
        }

        $this->worker->write($mediaType, $template);

        return $filename;
    }

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


Question:
Destroy/end a session

@return void

public function destroy(): void
    {
        if (!$this->cookieExists() || !$this->sessionExists()) {
            return;
        }

        session_destroy();

        // send expire cookies
        $this->expireSessionCookie();

        // clear session data
        unset($_SESSION[$this->getNamespace()]);
    }

public function route_logout($args) {
		$retval = $this->adm_logout($args);
		if ($retval[0] === 0)
			$this->core->send_cookie(
				$this->adm_get_token_name(), '',
				time() - (3600 * 48), '/');
		return $this->core->pj($retval);
	}

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


Question:
Reverse a buffer
@param {Buffer} param
@return {Buffer}

function reverse(param) {
    var ret = new buffer.Buffer(param.length);
    for (var i = 0; i < param.length; i++) {
      ret[i] = param[param.length - i - 1];
    }
    return ret;
  }

public function rewind()
    {
        $uri = $this->xmlFileUri;

        if ($this->options["utf8Filter"]) {
            $uri = "php://filter/read=xmlutf8/resource=" . $uri;
        }

        if (!$this->reader
            ->open(
                $uri,
                $this->options["encoding"],
                $this->options["readerOptions"]
            )
        ) {
            throw new \Exception("$this->xmlFileUri cannot be opened");
        }

        // move to the first element
        while ($this->reader->read() && $this->reader->name !== $this->delimiterTagName) {
            // intentionally empty
        }
    }

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


Question: a font glyph to character map,  needed for unicode fonts

protected function  o_fontGIDtoCIDMap($id, $action, $options = '') {
    if  ($action !== 'new') {
      $o = & $this->objects[$id];
    }

    switch  ($action) {
    case  'new':
      $this->objects[$id] =  array('t'=>'fontGIDtoCIDMap', 'info'=>$options);
      break;

    case  'out':
      $res = "\n$id 0 obj\n";
      $fontFileName = $o['info']['fontFileName'];
      $tmp = $this->fonts[$fontFileName]['CIDtoGID'] = base64_decode($this->fonts[$fontFileName]['CIDtoGID']);

      $compressed = isset($this->fonts[$fontFileName]['CIDtoGID_Compressed']) &&
                    $this->fonts[$fontFileName]['CIDtoGID_Compressed'];

      if  (!$compressed && isset($o['raw'])) {
        $res.= $tmp;
      } else {
        $res.=  "<<";

        if  (!$compressed && $this->compressionReady && $this->options['compression']) {
          // then implement ZLIB based compression on this content stream
          $compressed = true;
          $tmp =  gzcompress($tmp,  6);
        }
        if ($compressed) {
          $res.= "\n/Filter /FlateDecode";
        }

        $res.= "\n/Length ".mb_strlen($tmp, '8bit') .">>\nstream\n$tmp\nendstream";
      }

      $res.= "\nendobj";
      return  $res;
    }
  }

def _clean_text(self, text):

        clean = []
        for char in text:
            if char in self.punc_stops:
                clean += '.'
            elif char not in self.punc:
                clean += char
            else:
                pass
        return (''.join(clean)).lower()

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


Question:
Performs the adapter's initialization.

It will ensure the root directory exists

protected function initialize()
    {
        if ($this->initialized) {
            return;
        }

        $this->ensureDirectoryExists($this->directory, $this->create);
        $this->initialized = true;
    }

def start
      mutex.synchronize do
        check_process!
        return if connection.running?

        log(:debug) { "Start on #{uri}..." }

        @routes << config[:routing_file] if config[:routing_file].present?
        @routes.reload
        connection.bind(@routes)
      end
    end

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


Question:
Return inner classes within this class.

@param filter include only the included inner classes if filter==true.
@return an array of ClassDocImpl for representing the visible
classes defined in this class. Anonymous and local classes
are not included.

public ClassDoc[] innerClasses(boolean filter) {
        ListBuffer<ClassDocImpl> innerClasses = new ListBuffer<ClassDocImpl>();
        for (Scope.Entry e = tsym.members().elems; e != null; e = e.sibling) {
            if (e.sym != null && e.sym.kind == Kinds.TYP) {
                ClassSymbol s = (ClassSymbol)e.sym;
                if ((s.flags_field & Flags.SYNTHETIC) != 0) continue;
                if (!filter || env.isVisible(s)) {
                    innerClasses.prepend(env.getClassDoc(s));
                }
            }
        }
        //### Cache classes here?
        return innerClasses.toArray(new ClassDocImpl[innerClasses.length()]);
    }

public function getController(Request $request)
    {
        $controller = $request->attributes->get('controller');

        if($request->attributes->has('_sub_request') && $request->attributes->get('_sub_request'))
        {
            $controller = $request->attributes->get('_controller');
        }

        if (!$controller)
        {
            if (null !== $this->logger)
            {
                $this->logger->warning('Unable to look for the controller as the "_controller" parameter is missing');
            }

            return false;
        }

        if(is_array($controller))
        {
            return $controller;
        }

        if(is_object($controller))
        {
            if (method_exists($controller, '__invoke'))
            {
                return $controller;
            }

            throw new \InvalidArgumentException(sprintf('Controller "%s" for URI "%s" is not callable.', get_class($controller), $request->getPathInfo()));
        }

        $prepare = $this->prepare($request->attributes->all());

        $request->attributes->set('_bundle', $prepare['bundle']);
        $request->attributes->set('_controller', strtolower($prepare['parts'][1]));
        $request->attributes->set('_action', strtolower($prepare['parts'][2]));

        $callable = array($this->instantiateController($prepare['controller']), $prepare['action']);

        $request->attributes->set('_callable', $callable);

        if (!is_callable($callable))
        {
            throw new \InvalidArgumentException(sprintf('Controller "%s" for URI "%s" is not callable.', $controller, $request->getPathInfo()));
        }

        return $callable;
    }

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


Question: Initialize the Business Logic model and set it on driver

function initBLModel(soajs, cb) {
    let modelName = driverConfig.model;
    if (soajs.servicesConfig && soajs.servicesConfig.model) {
        modelName = soajs.servicesConfig.model;
    }
    if (process.env.SOAJS_TEST && soajs.inputmaskData && soajs.inputmaskData.model) {
        modelName = soajs.inputmaskData.model;
    }

    let modelPath = __dirname + "/model/" + modelName + ".js";
    return requireModel(modelPath, cb);

    /**
     * checks if model file exists, requires it and returns it.
     * @param filePath
     * @param cb
     */
    function requireModel(filePath, cb) {
        //check if file exist. if not return error
        fs.exists(filePath, function (exists) {
            if (!exists) {
                soajs.log.error('Requested Model Not Found!');
                return cb(601);
            }

            driver.model = require(filePath);
            return cb();
        });
    }

}

def _load_all_link_database(self):
        """"""
        _LOGGER.debug("Starting: _load_all_link_database")
        self.devices.state = 'loading'
        self._get_first_all_link_record()
        _LOGGER.debug("Ending: _load_all_link_database")

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


Question:
Store a local metadata

@param key   of the metadata
@param value of the metadata
@return the previous value of metadata if existed or null

public Object setMetadata(ITree node, String key, Object value) {
        if (node == null)
            return setMetadata(key, value);
        else {
            Object res = node.setMetadata(key, value);
            if (res == null)
                return getMetadata(key);
            return res;
        }
    }

public function getMetas(): string
    {
        $str = '';

        if(isset($this->metas))
            foreach($this->metas as $meta)
                if(isset($meta['name']))
                    $str .= '<meta name="'.$meta['name'].'" content="'.$meta['content'].'">';
                else
                    $str .= $meta['raw'];

        return $str;
    }

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


Question: // Users runs the user search action.

func (c *SearchController) Users(ctx *app.UsersSearchContext) error {
	return proxy.RouteHTTP(ctx, c.configuration.GetAuthShortServiceHostName())
}

func (u *UpdateCheckRunOptions) GetHeadBranch() string {
	if u == nil || u.HeadBranch == nil {
		return ""
	}
	return *u.HeadBranch
}

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


Question:
Mark offer as lose

        :param offer_id: the offer id
        :return Response

def mark_offer_as_lose(self, offer_id):

        return self._create_put_request(
            resource=OFFERS,
            billomat_id=offer_id,
            command=LOSE,
        )

def addReplaceDBPage( dbid, pageid, pagename, pagetype, pagebody, ignoreError = nil )

      @dbid, @pageid, @pagename, @pagetype, @pagebody, @ignoreError = dbid, pageid, pagename, pagetype, pagebody, ignoreError

      if pageid
         xmlRequestData = toXML( :pageid, @pageid )
      elsif pagename
         xmlRequestData = toXML( :pagename, @pagename )
      else
         raise "addReplaceDBPage: missing pageid or pagename"
      end

      xmlRequestData << toXML( :pagetype, @pagetype )
      xmlRequestData << toXML( :pagebody, encodeXML( @pagebody ) )
      xmlRequestData << toXML( :ignoreError, "1" ) if @ignoreError

      sendRequest( :addReplaceDBPage, xmlRequestData )

      @pageid = getResponseValue( :pageid )
      @pageid ||= getResponseValue( :pageID ) # temporary

      return self if @chainAPIcalls
      @pageid
    end

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


Question:
do the parsing on an JSONObject, assumes that the json is hierarchical
ordered, so all shapes are reachable over child relations
@param json hierarchical JSON object
@return Model with all shapes defined in JSON
@throws org.json.JSONException

public static Diagram parseJson(JSONObject json,
                                    Boolean keepGlossaryLink) throws JSONException {
        ArrayList<Shape> shapes = new ArrayList<Shape>();
        HashMap<String, JSONObject> flatJSON = flatRessources(json);
        for (String resourceId : flatJSON.keySet()) {
            parseRessource(shapes,
                           flatJSON,
                           resourceId,
                           keepGlossaryLink);
        }
        String id = "canvas";

        if (json.has("resourceId")) {
            id = json.getString("resourceId");
            shapes.remove(new Shape(id));
        }
        ;
        Diagram diagram = new Diagram(id);

        // remove Diagram
        // (Diagram)getShapeWithId(json.getString("resourceId"), shapes);
        parseStencilSet(json,
                        diagram);
        parseSsextensions(json,
                          diagram);
        parseStencil(json,
                     diagram);
        parseProperties(json,
                        diagram,
                        keepGlossaryLink);
        parseChildShapes(shapes,
                         json,
                         diagram);
        parseBounds(json,
                    diagram);
        diagram.setShapes(shapes);
        return diagram;
    }

public void marshall(AddThingToThingGroupRequest addThingToThingGroupRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(addThingToThingGroupRequest.getThingGroupName(), THINGGROUPNAME_BINDING);
            protocolMarshaller.marshall(addThingToThingGroupRequest.getThingGroupArn(), THINGGROUPARN_BINDING);
            protocolMarshaller.marshall(addThingToThingGroupRequest.getThingName(), THINGNAME_BINDING);
            protocolMarshaller.marshall(addThingToThingGroupRequest.getThingArn(), THINGARN_BINDING);
            protocolMarshaller.marshall(addThingToThingGroupRequest.getOverrideDynamicGroups(), OVERRIDEDYNAMICGROUPS_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:
生成函数

@return void

private function generateFunctions()
    {
        $result = '<?php' . PHP_EOL;
        foreach($this->ref->getFunctions() as $function)
        {
            $args = [];
            $comments = [];
            foreach($function->getParameters() as $param)
            {
                // 方法参数定义
                $args[] = $this->getMethodParamDefine($param);
                $comments[] = '@var ' . ($param->getType() ?? 'mixed') . ' $' . $param->name;
            }
            $return = $function->getReturnType();
            if(null !== $return)
            {
                $comments[] = '@return ' . $return;
            }
            $args = implode(', ', $args);
            if([] === $comments)
            {
                $comment = '';
            }
            else
            {
                $comment = implode(PHP_EOL . ' * ', $comments);
                $comment = <<<COMMENT

/**
 * {$comment}
 */
COMMENT;
            }
            $result .= <<<CODE
{$comment}
function {$function->name}({$args}){}

CODE;
        }
        file_put_contents($this->savePath . '/functions.php', $result);
    }

func (self *simplePBundle) SetReturnHeader(k string, v string) {
	self.out[k] = v
}

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


Question:
execute a command

@param string      $cmd the command
@param bool        $git prepend git to the command
@param null|string $cwd directory where the command should be executed

@return CallerInterface

public function execute($cmd, $git = true, $cwd = null)
    {
        if ($git) {
            $cmd = $this->getBinaryPath() . ' ' . $cmd;
        }
        $stream = ssh2_exec($this->resource, $cmd);
        stream_set_blocking($stream, 1);
        $data = stream_get_contents($stream);
        fclose($stream);
        // rtrim values
        $values = array_map('rtrim', explode(PHP_EOL, $data));
        $this->outputLines = $values;

        return $this;
    }

func (cli *Client) ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) {
	var repository, tag string
	if options.Reference != "" {
		ref, err := reference.ParseNormalizedNamed(options.Reference)
		if err != nil {
			return types.IDResponse{}, err
		}

		if _, isCanonical := ref.(reference.Canonical); isCanonical {
			return types.IDResponse{}, errors.New("refusing to create a tag with a digest reference")
		}
		ref = reference.TagNameOnly(ref)

		if tagged, ok := ref.(reference.Tagged); ok {
			tag = tagged.Tag()
		}
		repository = reference.FamiliarName(ref)
	}

	query := url.Values{}
	query.Set("container", container)
	query.Set("repo", repository)
	query.Set("tag", tag)
	query.Set("comment", options.Comment)
	query.Set("author", options.Author)
	for _, change := range options.Changes {
		query.Add("changes", change)
	}
	if !options.Pause {
		query.Set("pause", "0")
	}

	var response types.IDResponse
	resp, err := cli.post(ctx, "/commit", query, options.Config, nil)
	defer ensureReaderClosed(resp)
	if err != nil {
		return response, err
	}

	err = json.NewDecoder(resp.body).Decode(&response)
	return response, err
}

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


Question:
Convert a Graph node field name to a database column name

@param string $field

@return string

public static function fieldToColumnName($field)
    {
        $model_name = get_class(new static());
        if (property_exists($model_name, 'graph_node_field_aliases')
            && isset(static::$graph_node_field_aliases[$field])) {
            return static::$graph_node_field_aliases[$field];
        }

        return $field;
    }

public static void setIdFieldValue(ODocument document, String value) {
        setFieldValue(document, OGraphDatabase.LABEL, value);
    }

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


Question:
/*
@return string

public function getPhpPrototypeFunction(): string
    {
        if ($this->method->getFunctionName()) {
            return 'function '.$this->method->getFunctionName().'('.$this->displayParamsWithType($this->method->getParams()).')'.': '.$this->method->getReturnType().'{}';
        }
        return '';
    }

function yy_r130()
    {
        $this->_retvalue = '[' . $this->compiler->compileTag('private_special_variable', array(), '[\'section\'][\'' .
                                                                                $this->yystack[ $this->yyidx +
                                                                                - 1 ]->minor .
                                                                                '\'][\'index\']') . ']';
    }

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


Question: Lists experiments in the directory subtree.

def list_experiments(project_path, sort, output, filter_op, columns):
    """"""
    if columns:
        columns = columns.split(",")
    commands.list_experiments(project_path, sort, output, filter_op, columns)

def find_classes_in_module(module, clstypes):

    classes = []
    for item in dir(module):
        item = getattr(module, item)
        try:
            for cls in clstypes:
                if issubclass(item, cls) and item != cls:
                    classes.append(item)
        except Exception as e:
            pass
    return classes

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


Question:
Lieft das Waehrungssymbol der uebergebenen Waehrungseinheit.

@param cu Waehrungseinheit
@return z.B. das Euro-Zeichen

public static String getSymbol(CurrencyUnit cu) {
        try {
            return Waehrung.of(cu).getSymbol();
        } catch (IllegalArgumentException ex) {
            LOG.log(Level.WARNING, "Cannot get symbol for '" + cu + "':", ex);
            return cu.getCurrencyCode();
        }
    }

function renderSimpleRuby( $ruby ) {
  var frag = $.create( '!' )
  var clazz = $ruby.classList
  var $rb, $ru

  frag.appendChild( $.clone( $ruby ))

  $
  .tag( 'rt', frag.firstChild )
  .forEach(function( $rt ) {
    var $rb = $.create( '!' )
    var airb = []
    var irb

    // Consider the previous nodes the implied
    // ruby base
    do {
      irb = ( irb || $rt ).previousSibling
      if ( !irb || irb.nodeName.match( /((?:h\-)?r[ubt])/i ))  break

      $rb.insertBefore( $.clone( irb ), $rb.firstChild )
      airb.push( irb )
    } while ( !irb.nodeName.match( /((?:h\-)?r[ubt])/i ))

    // Create a real `<h-ru>` to append.
    $ru = clazz.contains( 'zhuyin' ) ? createZhuyinRu( $rb, $rt ) : createNormalRu( $rb, $rt )

    // Replace the ruby text with the new `<h-ru>`,
    // and remove the original implied ruby base(s)
    try {
      $rt.parentNode.replaceChild( $ru, $rt )
      airb.map( $.remove )
    } catch ( e ) {}
  })
  return createCustomRuby( frag )
}

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


Question: // IdentityManager returns the organization's identity manager

func (p *MSPProvider) IdentityManager(orgName string) (msp.IdentityManager, bool) {
	im, ok := p.identityManager[strings.ToLower(orgName)]
	if !ok {
		return nil, false
	}
	return im, true
}

protected function _afterControllerGet()
    {
        if ($this->_mixer->isIdentifiable() && $this->isDispatched()) {
            $item = $this->_mixer->getItem();
            $scope = $this->_mixer->getIdentifier()->package.'.'.$this->_mixer->getIdentifier()->name;
            $scope = $this->getService('com:components.domain.entityset.scope')->find($scope);

            if ($scope) {
                $this->getService()->set('com:search.scope', $scope);
            }

            if ($item && $item->persisted() && $item->inherits('ComActorsDomainEntityActor')) {
                $this->getService()->set('com:search.owner', $item);
                $this->getService()->set('com:components.scope', null);
            } elseif ($this->getRepository()->isOwnable() && $this->actor) {
                $this->getService()->set('com:search.owner', $this->actor);
            }
        }
    }

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


Question: // New creates a new *Corpus

func New() *Corpus {
	c := &Corpus{
		words:       make([]string, 0),
		frequencies: make([]int, 0),
		ids:         make(map[string]int),
	}

	// add some default words
	c.Add("") // aka NULL - when there are no words
	c.Add("-UNKNOWN-")
	c.Add("-ROOT-")
	c.maxWordLength = 0 // specials don't have lengths

	return c
}

func newSegment(ctx context.Context, traceID, name string, req *http.Request, c net.Conn) *Segment {
	var (
		spanID   = middleware.ContextSpanID(ctx)
		parentID = middleware.ContextParentSpanID(ctx)
	)

	s := NewSegment(name, traceID, spanID, c)
	s.RecordRequest(req, "")

	if parentID != "" {
		s.ParentID = parentID
	}

	return s
}

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


Question: // SetReward sets the Reward field's value.

func (s *CreateHITTypeInput) SetReward(v string) *CreateHITTypeInput {
	s.Reward = &v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

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


Question: Marshall the given parameter object.

public void marshall(Computer computer, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(computer.getComputerId(), COMPUTERID_BINDING);
            protocolMarshaller.marshall(computer.getComputerName(), COMPUTERNAME_BINDING);
            protocolMarshaller.marshall(computer.getComputerAttributes(), COMPUTERATTRIBUTES_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: Sets the header of the collection component.

public void setHeader(String header) {
        headerLabel.getElement().setInnerSafeHtml(SafeHtmlUtils.fromString(header));
        addStyleName(CssName.WITH_HEADER);
        ListItem item = new ListItem(headerLabel);
        UiHelper.addMousePressedHandlers(item);
        item.setStyleName(CssName.COLLECTION_HEADER);
        insert(item, 0);
    }

public static <Head, Tail extends HList> Lens.Simple<HCons<Head, ? extends Tail>, Head> head() {
        return simpleLens(HCons::head, (hCons, newHead) -> cons(newHead, hCons.tail()));
    }

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


Question:
Merges the existing attributes with the new ones

@param    mixed   Array of attribute 'name' => 'value' pairs or HTML attribute string
@return   HTML_Common2

public function mergeAttributes($attributes)
    {
        $attributes = self::prepareAttributes($attributes);
        foreach ($this->watchedAttributes as $watchedKey) {
            if (isset($attributes[$watchedKey])) {
                $this->onAttributeChange($watchedKey, $attributes[$watchedKey]);
                unset($attributes[$watchedKey]);
            }
        }
        $this->attributes = array_merge($this->attributes, $attributes);
        return $this;
    }

protected function displayCombinedAssets($type, $files)
    {
        $isValid = $this->validateTypeCache($type, $files);

        // If the cache isn't valid, we build the cache
        $result = $isValid;
        if (!$isValid) {
            $result = $this->buildTypeCache($type, $files);
        }

        // If the cache is valid, load the file
        if ($result) {
            $hash = $this->getTypeHash($type);
            $cachedFile = $this->cachedFiles[$hash]['file'];

            echo $this->generateHtmlCode($type, $cachedFile);
        }
    }

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


Question: Find handle closest to a certain percentage on the slider

function getClosestHandle ( proposal ) {

            var closest = 100;
            var handleNumber = false;

            scope_Handles.forEach(function(handle, index){

                // Disabled handles are ignored
                if ( handle.hasAttribute('disabled') ) {
                    return;
                }

                var pos = Math.abs(scope_Locations[index] - proposal);

                if ( pos < closest ) {
                    handleNumber = index;
                    closest = pos;
                }
            });

            return handleNumber;
        }

function (v) {
            this._scrollDistance = Math.max(0, Math.min(this._getMaxScrollDistance(), v));
            // Mark that the scroll distance has changed so that after the view is checked, the CSS
            // transformation can move the header.
            this._scrollDistanceChanged = true;
            this._checkScrollingControls();
        }

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


Question: Md5 value of a file.

def md5_of_file(abspath):

    chunk_size = 1024 * 1024
    m = hashlib.md5()
    with open(abspath, "rb") as f:
        while True:
            data = f.read(chunk_size)
            if not data:
                break
            m.update(data)
    return m.hexdigest()

public function isMadaBin($bin) {
        // Set the root path
        $csvPath = $this->directoryReader->getModuleDir('', 'CheckoutCom_Magento2')  . '/' . $this->config->getMadaBinsPath();

        // Get the data
        $csvData = $this->csvParser->getData($csvPath);

        // Remove the first row of csv columns
        unset($csvData[0]);

        // Build the MADA BIN array
        $binArray = [];
        foreach ($csvData as $row) {
            $binArray[] = $row[1];
        }

        return in_array($bin, $binArray);
    }

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


Question: Delegate to the appropriate method of the underlying logger.

public void error(Marker marker, String format, Object arg1, Object arg2) {
        if (!logger.isErrorEnabled(marker))
            return;
        if (instanceofLAL) {
            String formattedMessage = MessageFormatter.format(format, arg1, arg2).getMessage();
            ((LocationAwareLogger) logger).log(marker, fqcn, LocationAwareLogger.ERROR_INT, formattedMessage, new Object[] { arg1, arg2 }, null);
        } else {
            logger.error(marker, format, arg1, arg2);
        }
    }

public void trace(Object message) {
        doLog(Level.TRACE, FQCN, message, null, null);
    }

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


Question: // Flush flushes both data received but not read, and data written but not transmitted.

func (t *Term) Flush() error {
	return termios.Tcflush(uintptr(t.fd), termios.TCIOFLUSH)
}

public function doFlush()
    {
        while ($unit = array_shift($this->unitOfWork)) {
            while ($operations = array_shift($unit)) {
                while ($callback = array_shift($operations)) {
                    call_user_func($callback, $this->fileManager);
                }
            }
        }
    }

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


Question:
Called to reinitialize this instance, most importantly after it has been serialized/deserialized.

@param servletContext the current ServletContext.

protected void reinit( ServletContext servletContext )
    {
        super.reinit( servletContext );
        if ( _rch == null )  _rch = Handlers.get( servletContext ).getReloadableClassHandler();
    }

def service_restarted(self, sentry_unit, service, filename,
                          pgrep_full=None, sleep_time=20):

        # /!\ DEPRECATION WARNING (beisner):
        # This method is prone to races in that no before-time is known.
        # Use validate_service_config_changed instead.

        # NOTE(beisner) pgrep_full is no longer implemented, as pidof is now
        # used instead of pgrep.  pgrep_full is still passed through to ensure
        # deprecation WARNS.  lp1474030
        self.log.warn('DEPRECATION WARNING:  use '
                      'validate_service_config_changed instead of '
                      'service_restarted due to known races.')

        time.sleep(sleep_time)
        if (self._get_proc_start_time(sentry_unit, service, pgrep_full) >=
                self._get_file_mtime(sentry_unit, filename)):
            return True
        else:
            return False

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


Question: // Set adds SET clauses to the query.

func (b *UpdateBuilder) Set(columns ...string) *UpdateBuilder {
	for _, c := range columns {
		b.assignments = append(b.assignments, assignment{
			column: c,
			value:  param(c),
		})
	}

	return b
}

public static function table($table, $isQuery = false) {
        $new_self = new self();

        if ($isQuery) {
            $new_self->_table = '(' . $table . ')';
        } else {
            $new_self->_table = $table;
        }

        return $new_self;
    }

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


Question:
The UNC mount point for this path.
        This is empty for paths on local drives.

def uncshare(self):

        unc, r = self.module.splitunc(self)
        return self._next_class(unc)

public static TemplatePathInfo forPage(@NotNull Page page, @NotNull TemplatePathInfo @NotNull... templates) {
    if (page == null || templates == null) {
      return null;
    }
    String templatePath = page.getProperties().get(NameConstants.PN_TEMPLATE, String.class);
    return forTemplatePath(templatePath, templates);
  }

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


Question:
Returns the timestamp (in seconds) of the last time the run() method has been called.
Returns null if this did not happen so far.
Note: If the cache is reset, this timestamp will be reset as well!

@return int|null

public function lastRunAt()
    {
        if ($this->cache->has($this->cacheKey)) {
            $executedAt = $this->cache->get($this->cacheKey);

            return $executedAt;
        } else {
            return null;
        }
    }

public static void main(String[] args) {
		// manager with two stopwatches is created
		Manager manager = new EnabledManager();
		Stopwatch sw1 = manager.getStopwatch("org.javasimon.examples.stopwatch1");
		Stopwatch sw2 = manager.getStopwatch("other.stopwatch2");

		// simple callback printing actions to the stdout is created and installed
		Callback stdoutCallback = new CallbackSkeleton() {
			@Override
			public void onStopwatchStart(Split split) {
				System.out.println("Starting " + split.getStopwatch().getName());
			}

			@Override
			public void onStopwatchStop(Split split, StopwatchSample sample) {
				System.out.println("Stopped " + split.getStopwatch().getName() + " (" + SimonUtils.presentNanoTime(split.runningFor()) + ")");
			}
		};
		manager.callback().addCallback(stdoutCallback);

		// prints start/stop for both stopwatches
		sw1.start().stop();
		sw2.start().stop();
		System.out.println();

		// we need to remove old callback
		manager.callback().removeCallback(stdoutCallback);
		// alternatively you can call this if you want to remove all callbacks
		SimonManager.callback().removeAllCallbacks();

		// filter callback is created
		CompositeFilterCallback filter = new CompositeFilterCallback();
		// rule to filter out all Simons matching pattern "other.*" is added
		filter.addRule(FilterRule.Type.MUST_NOT, null, "other.*");
		// original callback is added after this callback
		filter.addCallback(stdoutCallback);

		// filter callback is installed to the manager (with printing callback behind)
		manager.callback().addCallback(filter);

		// start/stop is printed only for sw1 because sw2 matches other.* pattern that is excluded (MUST_NOT)
		sw1.start().stop();
		sw2.start().stop();
	}

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