Question: This method generates AbstractNamedEntity class js file.

def _write_abstract_named_entity(self):

        filename = "%sAbstractNamedEntity.js" % (self._class_prefix)

        superclass_name = "%sEntity" % (self._class_prefix)

        # write will write a file using a template.
        # mandatory params: destination directory, destination file name, template file name
        # optional params: whatever that is needed from inside the Jinja template

        self.write(destination = self.abstract_directory,
                    filename = filename,
                    template_name = "abstract_named_entity.js.tpl",
                    class_prefix = self._class_prefix,
                    superclass_name = superclass_name)

public static HtmlTree SCRIPT(String type, String src) {
        HtmlTree htmltree = new HtmlTree(HtmlTag.SCRIPT);
        htmltree.addAttr(HtmlAttr.TYPE, nullCheck(type));
        htmltree.addAttr(HtmlAttr.SRC, nullCheck(src));
        return htmltree;
    }

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


Question:
Generate a dict for this object's attributes.

        :return: A dict representing an :class:`Asset`

def to_dict(self):

        rv = {'code': self.code}
        if not self.is_native():
            rv['issuer'] = self.issuer
            rv['type'] = self.type
        else:
            rv['type'] = 'native'
        return rv

def get_samples_data(self):

        for obj in self.get_samples_from_request():
            yield {
                "obj": obj,
                "id": api.get_id(obj),
                "uid": api.get_uid(obj),
                "title": api.get_title(obj),
                "path": api.get_path(obj),
                "url": api.get_url(obj),
                "sample_type": obj.getSampleTypeTitle(),
                "client_title": obj.getClientTitle(),
                "date": ulocalized_time(obj.created(), long_format=True),
            }

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


Question:
Helper function to add all called methods to the class builder

@param  \Shmock\ClassBuilder\ClassBuilder $builder
@param  callable                          $resolveCall
@return \Shmock\ClassBuilder\ClassBuilder

protected function addMethodsToBuilder(ClassBuilder $builder, callable $resolveCall)
    {
        foreach (array_unique($this->expectedStaticMethodCalls) as $methodCall) {
            $inspector = new MethodInspector($this->className, $methodCall);
            $builder->addStaticMethod($methodCall, $resolveCall, $inspector->signatureArgs());
        }
        return $builder;
    }

def populate_class_members(self, element_cls, prop_name):

        super(OneAndOnlyOne, self).populate_class_members(
            element_cls, prop_name
        )
        self._add_getter()

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


Question: Parse the response of an RPC call into a dictionary with integer and buffer results

def _create_old_return_value(payload, num_ints, buff):
    """"""

    parsed = {'ints': payload[:num_ints], 'buffer': None, 'error': 'No Error',
              'is_error': False, 'return_value': 0}

    if buff:
        parsed['buffer'] = bytearray(payload[-1])

    return parsed

def encode_request(uuid, partition_id, interrupt):

    client_message = ClientMessage(payload_size=calculate_size(uuid, partition_id, interrupt))
    client_message.set_message_type(REQUEST_TYPE)
    client_message.set_retryable(RETRYABLE)
    client_message.append_str(uuid)
    client_message.append_int(partition_id)
    client_message.append_bool(interrupt)
    client_message.update_frame_length()
    return client_message

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


Question:
修改分组属性

        :param group_id: 商品分组ID
        :param group_properties: 商品分组属性
        :return: 返回的 JSON 数据包

def update_group_property(self, group_id, group_properties):

        group_properties['group_id'] = group_id
        return self._post(
            'merchant/group/propertymod',
            data=group_properties
        )

private static function _doResponse($type, $objects, $echoResponse, $format) {
        $ret = array();
        $ret['status'] = $type;
        if (is_array($objects)) {
            foreach ($objects as $k => $v) {
                $ret[$k] = $v;
            }
        } else {
            $ret[] = $objects;
        }

        switch ($format) {
            case 'xml':
                require_once 'XML/Serializer.php';
                $options = array(
                    "indent" => "    ",
                    "linebreak" => "\n",
                    "typeHints" => false,
                    "addDecl" => true,
                    "encoding" => "UTF-8",
                    "rootName" => "data",
//					"rootAttributes"  => array("version" => "0.91"),
                    "defaultTagName" => "item",
                    "attributesArray" => "_attributes"
                );

                $serializer = new \XML_Serializer($options);

                $rc = $serializer->serialize($ret);
                if ($rc !== TRUE) {

                }
                $ret = $serializer->getSerializedData();
                break;

            case 'json':
            default:
                $ret = json_encode($ret);
                break;
        }

        if ($echoResponse) {
            echo $ret;
        }
        return $ret;
    }

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


Question: Registers a call back function

def add_callback(self, func):

        if func is None: return
        func_list = to_list(func)

        if not hasattr(self, 'callback_list'):
            self.callback_list = func_list
        else:
            self.callback_list.extend(func_list)

func (c *ReactionsAddCall) Timestamp(timestamp string) *ReactionsAddCall {
	c.timestamp = timestamp
	return c
}

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


Question:
// initializeBlockHeight verifies that all blocks exist between 0 and the block
// height, and populates the lastHash

func (jl *jsonLedger) initializeBlockHeight() {
	infos, err := ioutil.ReadDir(jl.directory)
	if err != nil {
		logger.Panic(err)
	}
	nextNumber := uint64(0)
	for _, info := range infos {
		if info.IsDir() {
			continue
		}
		var number uint64
		_, err := fmt.Sscanf(info.Name(), blockFileFormatString, &number)
		if err != nil {
			continue
		}
		if number != nextNumber {
			logger.Panicf("Missing block %d in the chain", nextNumber)
		}
		nextNumber++
	}
	jl.height = nextNumber
	if jl.height == 0 {
		return
	}
	block, found := jl.readBlock(jl.height - 1)
	if !found {
		logger.Panicf("Block %d was in directory listing but error reading", jl.height-1)
	}
	if block == nil {
		logger.Panicf("Error reading block %d", jl.height-1)
	}
	jl.lastHash = block.Header.Hash()
}

def set_row(row, val)
      # Setter
      if !row.is_a?(String) || (!val.is_a?(Hash) && !val.is_a?(Array))
        raise ArgumentError, 'Illegal argument type'
      elsif val.is_a?(Array) && val.size != col_keys.size
        raise ArgumentError, 'Column size not match'
      end

      case val
      when Array
        if @row_keys[row]
          row = @row_keys[row]
          @content[row] = val
        else
          @row_keys[row] = @row_keys.size
          @content << val
        end
      when Hash
        unless @row_keys[row]
          @row_keys[row] = @row_keys.size
          @content << ([''] * @col_keys.size)
        end

        row = @row_keys[row]
        val.each do |k, v|
          col = @col_keys[k]
          @content[row][col] = v if col
        end
      end

      self
    end

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


Question: // argErr prints an err and usage to stderr and returns an exit code.

func (r *cmdRun) argErr(shortDesc, usageLine, format string, a ...interface{}) int {
	if format != "" {
		fmt.Fprintf(os.Stderr, format+"\n", a...)
	}
	fmt.Fprintln(os.Stderr, shortDesc)
	fmt.Fprintln(os.Stderr, usageLine)
	fmt.Fprintln(os.Stderr, "\nFlags:")
	r.Flags.PrintDefaults()
	return ecInvalidCommandLine
}

public static function hasError() {
		$error        = json_last_error();
		$errorMessage = array_key_exists($error, self::$errors) ? self::$errors[$error] : "Unknown error ({$error})";
		return $errorMessage;
	}

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


Question:
Replaces all placeholders with random numbers and letters.

        :param text: string to be parsed
        :returns: string with all numerical and letter placeholders filled in

def bothify(self, text='## ??', letters=string.ascii_letters):

        return self.lexify(self.numerify(text), letters=letters)

def get_clean_content(self):
        """"""
        fill_chars = {'BLANK_TEMPLATE': ' ', 'ECHO_TEMPLATE': '0'}
        for match in self.pattern.finditer(self.html_content):
            start, end = match.start(), match.end()
            tag = _get_tag(match)
            if tag == 'ECHO':
                self._write_content(start)
                self._index = start
                self._state = 'ECHO_TEMPLATE'
            elif tag == 'START':
                if self._index != start:
                    self._write_content(start)
                self._index = start
                self._state = 'BLANK_TEMPLATE'
            elif tag == 'END':
                if self._state not in ('BLANK_TEMPLATE', 'ECHO_TEMPLATE'):
                    # We got a closing tag but none was open. We decide to carry
                    # on as it may be the case that it was because of a closing
                    # dictionary in javascript like: var dict = {foo:{}}.
                    # See the note on the clean() function for more details.
                    continue
                fill_char = fill_chars[self._state]
                fill = fill_char * (end - self._index)
                if self._state == 'BLANK_TEMPLATE':
                    self._pending.append(fill)
                    self._pending_has_blank = True
                else:
                    assert not self._pending
                    self._output.write(fill)
                self._index = end
                self._state = 'HTML'
            elif tag == 'SPACES':
                self._pending.append(match.group('spaces'))
                self._index = end
            elif tag == 'NEWLINE':
                if self._state == 'HTML':
                    if self._index != start or not self._pending_has_blank:
                        self._write_content(start)
                    self._output.write(match.group('newline'))
                elif self._state == 'BLANK_TEMPLATE':
                    # We discard the content of this template and whatever is in
                    # self._pending.
                    self._output.write(match.group('newline'))
                elif self._state == 'ECHO_TEMPLATE':
                    assert False, 'Echo tags should be in just one line.'
                self._index = end
                self._reset_pending()

        assert self._state == 'HTML', 'Tag was not closed'
        if self._index != len(self.html_content) or not self._pending_has_blank:
            self._write_content()

        return self._output.getvalue()

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


Question: // SetDuration sets the Duration field's value.

func (s *Trace) SetDuration(v float64) *Trace {
	s.Duration = &v
	return s
}

func (s *LoadBalancerDescription) SetHealthCheck(v *HealthCheck) *LoadBalancerDescription {
	s.HealthCheck = v
	return s
}

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


Question:
@param string $columnName

@return string[]

public function getPropertiesRequiredFor(string $columnName) : array
    {
        $propertyNames = [];

        foreach ($this->propertyComponentIdMap as $propertyName => $componentId) {
            if ($this->getColumnNameFromComponentId($componentId) === $columnName) {
                $propertyNames[$propertyName] = $propertyName;
            }
        }

        return $propertyNames;
    }

protected XmlElement buildSqlClause(IntrospectedTable introspectedTable) {

    XmlElement sql = new XmlElement("sql");
    sql.addAttribute(new Attribute("id", IDENTIFIERS_ARRAY_CONDITIONS));

    XmlElement foreach = new XmlElement("foreach");
    foreach.addAttribute(new Attribute("collection", "array"));
    foreach.addAttribute(new Attribute("item", "item"));
    foreach.addAttribute(new Attribute("index", "index"));
    foreach.addAttribute(new Attribute("separator", " and "));

    StringBuilder sb = new StringBuilder();
    for (IntrospectedColumn introspectedColumn : introspectedTable.getAllColumns()) {
      XmlElement isEqualElement = new XmlElement("if");
      sb.setLength(0);
      sb.append("item == \'");
      sb.append(introspectedColumn.getJavaProperty());
      sb.append("\'");
      isEqualElement.addAttribute(new Attribute("test", sb.toString()));
      foreach.addElement(isEqualElement);

      sb.setLength(0);
      sb.append(MyBatis3FormattingUtilities.getAliasedEscapedColumnName(introspectedColumn));
      sb.append(" = ");
      sb.append(MyBatis3FormattingUtilities.getParameterClause(introspectedColumn, PROPERTY_PREFIX));

      isEqualElement.addElement(new TextElement(sb.toString()));
    }

    sql.addElement(foreach);
    return sql;
  }

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


Question:
/*
OrderDelete deletes purchase order by ID

For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors
*/

func (a *Client) OrderDelete(ctx context.Context, params *OrderDeleteParams) (*OrderDeleteNoContent, error) {

	result, err := a.transport.Submit(&runtime.ClientOperation{
		ID:                 "OrderDelete",
		Method:             "DELETE",
		PathPattern:        "/store/order/{orderId}",
		ProducesMediaTypes: []string{"application/json"},
		ConsumesMediaTypes: []string{"application/json"},
		Schemes:            []string{"http"},
		Params:             params,
		Reader:             &OrderDeleteReader{formats: a.formats},
		AuthInfo:           a.authInfo,
		Context:            ctx,
		Client:             params.HTTPClient,
	})
	if err != nil {
		return nil, err
	}
	return result.(*OrderDeleteNoContent), nil

}

public ArrayList<Long> deposit_depositId_paidBills_billId_debt_operation_GET(String depositId, String billId, Long depositOrderId) throws IOException {
		String qPath = "/me/deposit/{depositId}/paidBills/{billId}/debt/operation";
		StringBuilder sb = path(qPath, depositId, billId);
		query(sb, "depositOrderId", depositOrderId);
		String resp = exec(qPath, "GET", sb.toString(), null);
		return convertTo(resp, t2);
	}

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


Question:
Builds and prints Graph Image.
@access		public
@static
@param		array		$config			Configuration Data
@param		array		$data			Graph Data
@return		void

public static function buildImage( $config, $data )
	{
		$graph	= self::buildGraph( $config, $data );
		$graph->stroke();
	}

public function toString()
    {
        $url = $this->scheme.':';
        if (trim($this->host) != '') {
            $url .= '//';
            if (trim($this->user) != '') {
                $url .= $this->user.((trim($this->pass) != '')?':'.$this->pass:'').'@';
            }
            $url .= $this->host;

            if (trim($this->port) != '') {
                $url .= ':'.$this->port;
            }
        }

        $url .= (trim($this->path) != '')?$this->path:'';
        $url .= (trim($this->query) != '')?'?'.$this->query:'';
        $url .= (trim($this->fragment) != '')?'#'.$this->fragment:'';

        if (!self::isValid($url)) {
            throw new RuntimeException('Built URL is not a valid one: '.$url);
        }

        return $url;
    }

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


Question:
Detects a hang in the underlying executor. When a hang is detected, increases the
poolSize in hopes of relieving the hang, unless poolSize has reached maxThreads.

@return true if action was taken to resolve a hang, or false otherwise

private boolean resolveHang(long tasksCompleted, boolean queueEmpty, int poolSize) {
        boolean actionTaken = false;
        if (tasksCompleted == 0 && !queueEmpty) {
            /**
             * When a hang is detected the controller enters hang resolution mode.
             * The controller will run on a shorter-than-usual cycle for hangResolutionCycles
             * from the last hang detection, to resolve hang situations more quickly.
             */
            if (hangResolutionCountdown == 0) {
                // cancel regular controller schedule
                activeTask.cancel();
                // restart with shortened interval for quicker hang resolution
                activeTask = new IntervalTask(this);
                timer.schedule(activeTask, hangInterval, hangInterval);
            }
            hangResolutionCountdown = hangResolutionCycles;
            controllerCyclesWithoutHang = 0;

            // if this is the first time we detected a given deadlock, record how many threads there are
            // and print a message
            if (poolSizeWhenHangDetected < 0) {
                poolSizeWhenHangDetected = poolSize;
                if (tc.isEventEnabled()) {
                    Tr.event(tc, "Executor hang detected at poolSize=" + poolSizeWhenHangDetected, threadPool);
                }
            } else if (tc.isEventEnabled()) {
                Tr.event(tc, "Executor hang continued at poolSize=" + poolSize, threadPool);
            }

            setPoolIncrementDecrement(poolSize);
            if (poolSize + poolIncrement <= maxThreads && poolSize < MAX_THREADS_TO_BREAK_HANG) {
                targetPoolSize = adjustPoolSize(poolSize, poolIncrement);
                // update the poolSize set to resolve the hang, plus a buffer amount
                int targetSize = poolSize + (compareRange * poolIncrement);
                if (hangBufferPoolSize < targetSize) {
                    hangBufferPoolSize = targetSize;
                }
                actionTaken = true;

            } else {
                // there's a hang, but we can't add any more threads...  emit a warning the first time this
                // happens for a given hang, but otherwise just bail
                if (hangMaxThreadsMessageEmitted == false && hangIntervalCounter > 0) {
                    if (tc.isWarningEnabled()) {
                        Tr.warning(tc, "unbreakableExecutorHang", poolSizeWhenHangDetected, poolSize);
                    }
                    hangMaxThreadsMessageEmitted = true;
                }
            }
            hangIntervalCounter++;
        } else {
            // no hang exists, so reset the appropriate variables that track hangs
            poolSizeWhenHangDetected = -1;
            hangIntervalCounter = 0;
            hangMaxThreadsMessageEmitted = false;
            // manage hang resolution mode
            if (hangResolutionCountdown > 0) {
                hangResolutionCountdown--;
                if (hangResolutionCountdown <= 0) {
                    // move out of hang resolution cycle time
                    activeTask.cancel();
                    // restart using regular cycle time
                    activeTask = new IntervalTask(this);
                    timer.schedule(activeTask, interval, interval);
                }
            }
            /**
             * if controller is running below hangResolutionPoolSize marker without hanging,
             * we can reduce that marker ... the workload must have changed, so prior hang
             * information is no longer valid. We will reduce it gradually, to maintain a
             * conservative stance toward avoiding hangs.
             */
            if (hangBufferPoolSize > coreThreads) {
                if (hangBufferPoolSize > poolSize) {
                    controllerCyclesWithoutHang++;
                    if (controllerCyclesWithoutHang > noHangCyclesThreshold) {
                        setPoolIncrementDecrement(poolSize);
                        hangBufferPoolSize -= poolDecrement;
                        controllerCyclesWithoutHang = 0;
                    }
                }
            }
        }
        return actionTaken;
    }

public void stop() {
		if (stopped) {
			return;
		}
		this.stopped = true;
		log.info("Stopping spidering process by request.");

		if (this.paused) {
			// Have to resume first or we get a deadlock
			this.resume();
		}

		// Issue the shutdown command
		this.threadPool.shutdown();
		try {
			if (!this.threadPool.awaitTermination(2, TimeUnit.SECONDS)) {
				log.warn("Failed to await for all spider threads to stop in the given time (2s)...");
				for (Runnable task : this.threadPool.shutdownNow()) {
					((SpiderTask) task).cleanup();
				}
			}
		} catch (InterruptedException ignore) {
			log.warn("Interrupted while awaiting for all spider threads to stop...");
		}
		if (httpSender != null) {
			this.getHttpSender().shutdown();
			httpSender = null;
		}

		// Notify the controller to clean up memory
		controller.reset();
		this.threadPool = null;

		// Notify the listeners -- in the meanwhile
		notifyListenersSpiderComplete(false);
	}

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


Question:
Sanitize a scalar or traversable value

@param   mixed   $value Value to be sanitized
@return  mixed   The sanitized value

public function sanitize($value)
    {
        foreach($this->_queue as $filter) {
            $value = $filter->sanitize($value);
        }

        return $value;
    }

def translated_attributes
      attributes = {}
      translations = []
      translations << { :var => 'client_id', :xml_var => 'ClientID' }
      translations << { :var => 'concat', :xml_var => 'Concat' }
      translations << { :var => 'from', :xml_var => 'From' }
      translations << { :var => 'invalid_char_action', :xml_var => 'InvalidCharAction' }
      translations << { :var => 'content', :xml_var => 'Content' }
      translations << { :var => 'to', :xml_var => 'To' }
      translations << { :var => 'truncate', :xml_var => 'Truncate' }
      translations << { :var => 'wrapper_id', :xml_var => 'WrapperID' }

      translations.each do |t|
        self.instance_variable_set( "@#{t[:var]}", @api.instance_variable_get( "@#{t[:var]}" ) ) if self.instance_variable_get( "@#{t[:var]}" ).nil?
        attributes[ t[:xml_var] ] = self.instance_variable_get( "@#{t[:var]}" ) unless self.instance_variable_get( "@#{t[:var]}" ).nil?
      end

      attributes
    end

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


Question:
gets rtf info part

@return string

protected function getInfoPart()
    {
        $part = '{\info'."\r\n";

        foreach ($this->_properties as $key => $value) {
            $value = PHPRtfLite_Utf8::getUnicodeEntities($value, $this->_charset);
            $part .= '{\\' . $key . ' ' . $value . '}'."\r\n";
        }

        $part .= '}'."\r\n";

        return $part;
    }

def to_s
      repr = ""
      repr += "id: #{id}\n" if id
      repr += "event: #{event}\n" if event
      if data.empty?
        repr += "data: \n"
      else
        data.split("\n").each { |l| repr += "data: #{l}\n" }
      end
      repr += "\n"
    end

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


Question: Returns a nested array containing only the leaf concepts, at their actual depths in the tree of nodes.

function getNestedNodes(concept, condition) {
  if (condition(concept)) {
    return concept;
  }
  if (!concept.items) {
    return [];
  }
  return concept.items.map(child => getNestedNodes(child, condition));
}

func (that *JSONNode) DebugProspect(indentlevel int, indentchar string) {
	switch that.t {
	case TypeValue:
		that.debugProspectValue(indentlevel, indentchar)
	case TypeMap:
		that.debugProspectMap(indentlevel, indentchar)
	case TypeArray:
		that.debugProspectArray(indentlevel, indentchar)
	case TypeUndefined:
		printfindent(indentlevel, indentchar, "Is of Type: TypeUndefined\n")
	}
}

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


Question: Returns the map with a marker to the default map

def marker_(self, lat, long, text, pmap, color=None, icon=None):

        try:
            xmap = self._marker(lat, long, text, pmap, color, icon)
            return xmap
        except Exception as e:
            self.err(e, self.marker_, "Can not get marker")

function mark (instance) {
  if (!instanceMap.has(instance.__VUE_DEVTOOLS_UID__)) {
    instanceMap.set(instance.__VUE_DEVTOOLS_UID__, instance)
    instance.$on('hook:beforeDestroy', function () {
      instanceMap.delete(instance.__VUE_DEVTOOLS_UID__)
    })
  }
}

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


Question:
设置session_id，每次请求都设置，以更新session过期时间
@param string $sessionId
@return bool|string

private static function setSessionId($sessionId){
        $sessionId = trim($sessionId);

        // 非法字符处理
        if (!$sessionId || preg_match("/[^0-9a-z_\\-\\,]/i", $sessionId)) {
            return false;
        }

        $sessionId = substr($sessionId, 0, 40);
        session_id($sessionId);

        return $sessionId;
    }

public function setToken($token) {

		// Token is Array('secret','options')
		if (is_array($token) && isset($token['secret']) && isset($token['options'])) {
			// Generate Firebase JSON Web Token
			$FirebaseToken 	= new FirebaseToken($token['secret']);
			$FirebaseData	= $token['data'] ?: [];
			$LocalData	    = [
				'user'	=> App::environment()
			];

			// Set Token
			$this->token = $FirebaseToken->create($LocalData + $FirebaseData, $token['options']);

		} elseif (is_string($token)) {
			// Token is a string secret
			$this->token = $token;
		} else {
			throw new \UnexpectedValueException('Token was not a valid configuration array (secret, options[, data]) or string');
		}
	}

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


Question:
See: https://wakatime.com/developers#summaries for details.

@param $startDate
@param $endDate
@param null $project
@param null|string $branches
@return mixed

public function summaries($startDate, $endDate, $project = null, $branches = null)
    {
        if ($project !== null) {
            $project = "&project={$project}";
        }
        if ($branches !== null) {
            $branches = "&branches={$branches}";
        }

        return $this->makeRequest("users/current/summaries?start={$startDate}&end={$endDate}" . $project . $branches);
    }

public static final TimeUnit getTimeUnit(int value)
   {
      TimeUnit result = null;

      switch (value)
      {
         case 1:
         {
            // Appears to mean "use the document format"
            result = TimeUnit.ELAPSED_DAYS;
            break;
         }

         case 2:
         {
            result = TimeUnit.HOURS;
            break;
         }

         case 4:
         {
            result = TimeUnit.DAYS;
            break;
         }

         case 6:
         {
            result = TimeUnit.WEEKS;
            break;
         }

         case 8:
         case 10:
         {
            result = TimeUnit.MONTHS;
            break;
         }

         case 12:
         {
            result = TimeUnit.YEARS;
            break;
         }

         default:
         {
            break;
         }
      }

      return result;
   }

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


Question:
Checks the response from settlement request.
No sign check on settlement response because DataTrans do not send sign in settlement response.

@param $sResponse

@return bool

protected function SettlementResponseSuccess($sResponse)
    {
        $bSettlementResponseSuccess = true;
        $sRefNo = $this->GetRefNoParameter(false);
        $oXML = simplexml_load_string($sResponse);
        if (isset($oXML->body->transaction->response)) {
            TTools::WriteLogEntrySimple('Payment DataTrans: Erfoglreiche XML Settlement Response for transaction'.$this->sTransactionId.'and reference number '.$sRefNo, 3, __FILE__, __LINE__);
        } else {
            if (isset($oXML->body->transaction->error)) {
                $sErrorCode = '';
                $sErrorMessage = '';
                if (isset($oXML->body->transaction->error->errorCode)) {
                    $sErrorCode = strval($oXML->body->transaction->error->errorCode);
                }
                if (isset($oXML->body->transaction->error->errorDetail)) {
                    $sErrorMessage = strval($oXML->body->transaction->error->errorDetail);
                }
                if (isset($oXML->body->transaction->error->errorMessage)) {
                    $sErrorMessage .= strval($oXML->body->transaction->error->errorMessage);
                }
                TTools::WriteLogEntrySimple('Payment DataTrans: Fehlerhafte XML Settlement Response for transaction'.$this->sTransactionId.'and reference number '.$sRefNo.'. CODE('.$sErrorCode.') MESSAGE('.$sErrorMessage.')'.' response: '.$sResponse, 1, __FILE__, __LINE__);
            } else {
                TTools::WriteLogEntrySimple('Payment DataTrans: Fehlerhafte XML Settlement Response for transaction'.$this->sTransactionId.'and reference number '.$sRefNo.' response: '.$sResponse, 1, __FILE__, __LINE__);
            }
            $bSettlementResponseSuccess = false;
        }

        return $bSettlementResponseSuccess;
    }

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: Removes a view from the DOM. A view is a DocumentFragment, so `remove()` returns all its nodes to itself.

function() {
    var node = this.firstViewNode;
    var next;

    if (node.parentNode !== this) {
      // Remove all the nodes and put them back into this fragment
      while (node) {
        next = (node === this.lastViewNode) ? null : node.nextSibling;
        this.appendChild(node);
        node = next;
      }
    }

    this.detached();
  }

function cleanTree (oSymbol) {
			delete oSymbol.treeName;
			delete oSymbol.parent;
			if (oSymbol.children) {
				oSymbol.children.forEach(o => cleanTree(o));
			}
		}

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


function createPHPClass (className, baseClass, body, methods) {

    const baseFolder = (baseClass == 'Exchange') ? 'base/' : ''
    const baseFile =  baseFolder + baseClass + '.php'

    const header = [
        "<?php\n",
        "namespace ccxt;\n",
        "// PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:",
        "// https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code\n",
        "use \Exception as Exception; // a common import\n",
        'class ' + className + ' extends ' + baseClass + ' {'    ,
    ]

    let bodyAsString = body.join ("\n")

    for (let method of methods) {
        const regex = new RegExp ('this->(' + method + ')\\s*\\(', 'g')
        bodyAsString = bodyAsString.replace (regex,
            (match, p1) => ('this->' + unCamelCase (p1) + ' ('))
    }

    const footer =[
        "}\n",
    ]

    const result = header.join ("\n") + "\n" + bodyAsString + "\n" + footer.join ('\n')
    return result
}

@Override
    protected void paintComponent(java.awt.Graphics g) {
        if (!isInitialized()) {
            return;
        }

        final java.awt.Graphics2D G2 = (java.awt.Graphics2D) g.create();

        CENTER.setLocation(getGaugeBounds().getCenterX(), getGaugeBounds().getCenterX());

        G2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_NORMALIZE);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Translate the coordinate system related to the insets
        G2.translate(getFramelessOffset().getX(), getFramelessOffset().getY());

        final java.awt.geom.AffineTransform OLD_TRANSFORM = G2.getTransform();
        final java.awt.Shape OLD_CLIP = G2.getClip();

        // Draw the horizon
        G2.setClip(CLIP);

        // Rotate around roll
        G2.rotate(-Math.toRadians(roll), CENTER.getX(), CENTER.getY());

        // Translate about dive
        G2.translate(0, -(pitch * pitchPixel) - getFramelessOffset().getY());

        // Draw horizon
        G2.drawImage(horizonImage, 0, (int) ((getHeight() - horizonImage.getHeight()) / 2.0), null);

        // Draw the scale and angle indicator
        G2.translate(-getFramelessOffset().getX(), (pitch * pitchPixel) + getFramelessOffset().getY());
        G2.drawImage(horizonForegroundImage, (int) (getWidth() * 0.5 - horizonForegroundImage.getWidth() / 2.0), (int) (getWidth() * 0.10747663551401869), null);

        G2.setTransform(OLD_TRANSFORM);
        G2.setClip(OLD_CLIP);

        // Draw combined background image
        G2.drawImage(bImage, 0, 0, null);

        // Draw combined foreground image
        G2.drawImage(fImage, 0, 0, null);

        if (!isEnabled()) {
            G2.drawImage(disabledImage, 0, 0, null);
        }

        G2.dispose();
    }

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


Question: // printKeyStatus prints the KeyStatus response from the API.

func printKeyStatus(ks *api.KeyStatus) string {
	return columnOutput([]string{
		fmt.Sprintf("Key Term | %d", ks.Term),
		fmt.Sprintf("Install Time | %s", ks.InstallTime.UTC().Format(time.RFC822)),
	}, nil)
}

static function OutputHeaders($realm = "Login Required", $terminate = true)
	{
		header("WWW-Authenticate: Basic realm=\"".$realm."\"");
		header("Status: 401 Unauthorized");
		header("HTTP-Status: 401 Unauthorized");
		if ($terminate) die();
	}

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


Question: // Perm returns a pseudo-random permutation of n integers in [0, n).

func (r *Rand) Perm(n int) []int {
	r.Lock()
	perm := r.rand.Perm(n)
	r.Unlock()
	return perm
}

public function swap(int $current, int $parent): void {
        $tmp = $this->heap[$current];
        $this->heap[$current] = $this->heap[$parent];
        $this->heap[$parent] = $tmp;
    }

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


Question: // String implements the Stringer interface.

func (datr DataRate) String() string {
	return fmt.Sprintf("SF%dBW%d", datr.SpreadingFactor, datr.Bandwidth)
}

public static void write(final Iterable<HighScoringPair> hsps, final PrintWriter writer) {
        checkNotNull(hsps);
        checkNotNull(writer);
        for (HighScoringPair hsp : hsps) {
            writer.println(hsp.toString());
        }
    }

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


Question: returns the results

def results(self):

        self.__init()
        for k,v in self._results.items():
            param = self._get_json(v['paramUrl'])
            if param['dataType'] == "GPFeatureRecordSetLayer":
                self._results[k] = GPFeatureRecordSetLayer.fromJSON(json.dumps(param))
            elif param['dataType'].lower().find('gpmultivalue') > -1:
                self._results[k] = GPMultiValue.fromJSON(json.dumps(param))
            elif param['dataType'] == "GPString":
                self._results[k] = GPString.fromJSON(json.dumps(param))
            elif param['dataType'] == "GPLong":
                self._results[k] = GPLong.fromJSON(json.dumps(param))
            elif param['dataType'] == "GPDouble":
                self._results[k] = GPDouble.fromJSON(json.dumps(param))
            elif param['dataType'] == "GPDate":
                self._results[k] = GPDate.fromJSON(json.dumps(param))
            elif param['dataType'] == "GPBoolean":
                self._results[k] = GPBoolean.fromJSON(json.dumps(param))
            elif param['dataType'] == "GPDataFile":
                self._results[k] = GPDataFile.fromJSON(json.dumps(param))
            elif param['dataType'] == "GPLinearUnit":
                self._results[k] = GPLinearUnit.fromJSON(json.dumps(param))
            elif param['dataType'] == "GPMultiValue":
                self._results[k] = GPMultiValue.fromJSON(json.dumps(param))
            elif param['dataType'] == "GPRasterData":
                self._results[k] = GPRasterData.fromJSON(json.dumps(param))
            elif param['dataType'] == "GPRasterDataLayer":
                self._results[k] = GPRasterDataLayer.fromJSON(json.dumps(param))
            elif param['dataType'] == "GPRecordSet":
                self._results[k] = GPRecordSet.fromJSON(json.dumps(param))
        return self._results

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

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


Question: // Matcher is a JSON Matcher.

func Matcher(p rpc.ReadPeeker) bool {
	b, err := p.Peek(1)
	return err == nil && b[0] == '{'
}

func (m *Client) MarshalBinary() ([]byte, error) {
	if m == nil {
		return nil, nil
	}
	return swag.WriteJSON(m)
}

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


Question: Auto Generated Code

def vcs_rbridge_config_input_rbridge_id(self, **kwargs):

        config = ET.Element("config")
        vcs_rbridge_config = ET.Element("vcs_rbridge_config")
        config = vcs_rbridge_config
        input = ET.SubElement(vcs_rbridge_config, "input")
        rbridge_id = ET.SubElement(input, "rbridge-id")
        rbridge_id.text = kwargs.pop('rbridge_id')

        callback = kwargs.pop('callback', self._callback)
        return callback(config)

private function populateAvailableTypes($onlyAutowiringTypes = false)
    {
        $this->types = array();
        if (!$onlyAutowiringTypes) {
            $this->ambiguousServiceTypes = array();
        }

        foreach ($this->container->getDefinitions() as $id => $definition) {
            $this->populateAvailableType($id, $definition, $onlyAutowiringTypes);
        }
    }

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


Question:
Everyone do the Fisher-Yates shuffle now -_(*-*)_-

@param {Array|String} data An array of characters or a character string
whose index values to shuffle
@returns {String} The shuffled data

function shuffle(data) {
    // Convert the string to an array
    var content = (typeof data === 'string' ? data.split('') : data);

    // Perform the shuffle on the array
    for (var length = content.length - 1; length > 0; length--) {
      var index = Math.floor(Math.random() * (length + 1));
      var temp = content[length];
      content[length] = content[index];
      content[index] = temp;
    }

    return content.join('');
  }

private static List<ParameterFiller> parseParameters(List<String> parameters) {
    List<ParameterFiller> parameterFillers = new ArrayList<>(parameters.size());
    for (String parameter : parameters) {
      ParameterFiller parameterFiller = parseParameter(parameter);
      if (parameterFiller != null) {
        parameterFillers.add(parameterFiller);
      }
    }
    return parameterFillers;
  }

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


Question:
Подставляет значения макросов

@param string $text

@return string

public function replaceMacros($text)
    {
        $result = str_replace(
            array(
                '$(httpHost)',
                '$(httpPath)',
                '$(httpRoot)',
                '$(styleRoot)',
                '$(dataRoot)',

                '$(siteName)',
                '$(siteTitle)',
                '$(siteKeywords)',
                '$(siteDescription)',
            ),
            array(
                httpHost,
                httpPath,
                Eresus_CMS::getLegacyKernel()->root,
                styleRoot,
                dataRoot,

                siteName,
                siteTitle,
                siteKeywords,
                siteDescription,
            ),
            $text
        );
        $result = preg_replace_callback('/\$\(const:(.*?)\)/i', '__macroConst', $result);
        $result = preg_replace_callback('/\$\(var:(([\w]*)(\[.*?\]){0,1})\)/i', '__macroVar', $result);
        $result = preg_replace('/\$\(\w+(:.*?)*?\)/', '', $result);
        return $result;
    }

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

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


Question:
Creates producer with given producer id, category and subsystem and register it in producer registry.

@param producerId id of the producer
@param category   name of the category
@param subsystem  name of the subsystem
@return PageInBrowserStats producer

private OnDemandStatsProducer<PageInBrowserStats> createProducer(final String producerId, final String category, final String subsystem) {
		OnDemandStatsProducer<PageInBrowserStats> producer = limit == -1 ? new OnDemandStatsProducer<PageInBrowserStats>(producerId, category, subsystem, new PageInBrowserStatsFactory()) :
				new EntryCountLimitedOnDemandStatsProducer<PageInBrowserStats>(producerId, category, subsystem, new PageInBrowserStatsFactory(), limit);

		ProducerRegistryFactory.getProducerRegistryInstance().registerProducer(producer);
		return producer;
	}

def _parse_caps_cpu(node):
    '''

    '''
    result = {}
    for mode in node.findall('mode'):
        if not mode.get('supported') == 'yes':
            continue

        name = mode.get('name')
        if name == 'host-passthrough':
            result[name] = True

        elif name == 'host-model':
            host_model = {}
            model_node = mode.find('model')
            if model_node is not None:
                model = {
                    'name': model_node.text
                }

                vendor_id = model_node.get('vendor_id')
                if vendor_id:
                    model['vendor_id'] = vendor_id

                fallback = model_node.get('fallback')
                if fallback:
                    model['fallback'] = fallback
                host_model['model'] = model

            vendor = mode.find('vendor').text if mode.find('vendor') is not None else None
            if vendor:
                host_model['vendor'] = vendor

            features = {feature.get('name'): feature.get('policy') for feature in mode.findall('feature')}
            if features:
                host_model['features'] = features

            result[name] = host_model

        elif name == 'custom':
            custom_model = {}
            models = {model.text: model.get('usable') for model in mode.findall('model')}
            if models:
                custom_model['models'] = models
            result[name] = custom_model

    return result

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


Question: Ensure a given position is not inside an atomic range.

function skipAtomic(doc, pos, bias, mayClear) {
    var flipped = false, curPos = pos;
    var dir = bias || 1;
    doc.cantEdit = false;
    search: for (;;) {
      var line = getLine(doc, curPos.line);
      if (line.markedSpans) {
        for (var i = 0; i < line.markedSpans.length; ++i) {
          var sp = line.markedSpans[i], m = sp.marker;
          if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) &&
              (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) {
            if (mayClear) {
              signal(m, "beforeCursorEnter");
              if (m.explicitlyCleared) {
                if (!line.markedSpans) break;
                else {--i; continue;}
              }
            }
            if (!m.atomic) continue;
            var newPos = m.find(dir < 0 ? -1 : 1);
            if (cmp(newPos, curPos) == 0) {
              newPos.ch += dir;
              if (newPos.ch < 0) {
                if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1));
                else newPos = null;
              } else if (newPos.ch > line.text.length) {
                if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0);
                else newPos = null;
              }
              if (!newPos) {
                if (flipped) {
                  // Driven in a corner -- no valid cursor position found at all
                  // -- try again *with* clearing, if we didn't already
                  if (!mayClear) return skipAtomic(doc, pos, bias, true);
                  // Otherwise, turn off editing until further notice, and return the start of the doc
                  doc.cantEdit = true;
                  return Pos(doc.first, 0);
                }
                flipped = true; newPos = pos; dir = -dir;
              }
            }
            curPos = newPos;
            continue search;
          }
        }
      }
      return curPos;
    }
  }

public static int checkBetween(int value, int min, int max) {
		if (value < min || value > max) {
			throw new IllegalArgumentException(StrUtil.format("Length must be between {} and {}.", min, max));
		}
		return value;
	}

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


Question: Prompt the user for input.

def ask(self, question, default=None):

        if isinstance(question, Question):
            return self._io.ask_question(question)

        return self._io.ask(question, default)

def create_uinput_device(mapping):
    """"""
    if mapping not in _mappings:
        raise DeviceError("Unknown device mapping: {0}".format(mapping))

    try:
        mapping = _mappings[mapping]
        device = UInputDevice(mapping)
    except UInputError as err:
        raise DeviceError(err)

    return device

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


Question:
// CombinedOutput runs the command on the remote and returns its combined
// standard output and standard error.

func (s *SSHRunner) CombinedOutput(cmd string) (string, error) {
	glog.Infoln("Run with output:", cmd)
	sess, err := s.c.NewSession()
	if err != nil {
		return "", errors.Wrap(err, "NewSession")
	}
	defer sess.Close()

	var combined singleWriter
	err = teeSSH(sess, cmd, &combined, &combined)
	out := combined.b.String()
	if err != nil {
		return out, err
	}
	return out, nil
}

def build(check, sdist):
    """"""
    if check in get_valid_checks():
        check_dir = os.path.join(get_root(), check)
    else:
        check_dir = resolve_path(check)
        if not dir_exists(check_dir):
            abort('`{}` is not an Agent-based Integration or Python package'.format(check))

        check = basepath(check_dir)

    echo_waiting('Building `{}`...'.format(check))

    dist_dir = os.path.join(check_dir, 'dist')
    remove_path(dist_dir)

    result = build_package(check_dir, sdist)
    if result.code != 0:
        abort(result.stdout, result.code)

    echo_info('Build done, artifact(s) in: {}'.format(dist_dir))
    echo_success('Success!')

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


Question: :type items: list of ProtocolTreeItem

def move_to_group(self, items, new_group_id: int):

        group = self.rootItem.child(new_group_id)
        for item in items:
            group.appendChild(item)
        self.controller.refresh()

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

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


Question: // Resets the password for virtual machine. The virtual machine must be in a "Stopped" state and the template must already support this feature for this command to take effect. [async]

func (s *VirtualMachineService) ResetPasswordForVirtualMachine(p *ResetPasswordForVirtualMachineParams) (*ResetPasswordForVirtualMachineResponse, error) {
	resp, err := s.cs.newRequest("resetPasswordForVirtualMachine", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r ResetPasswordForVirtualMachineResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	// If we have a async client, we need to wait for the async result
	if s.cs.async {
		b, err := s.cs.GetAsyncJobResult(r.JobID, s.cs.timeout)
		if err != nil {
			if err == AsyncTimeoutErr {
				return &r, err
			}
			return nil, err
		}

		b, err = getRawValue(b)
		if err != nil {
			return nil, err
		}

		if err := json.Unmarshal(b, &r); err != nil {
			return nil, err
		}
	}

	return &r, nil
}

def generate_answers
      masterless = @options[:masterless]
      return super if masterless

      dashboard = only_host_with_role(@hosts, 'dashboard')
      database = only_host_with_role(@hosts, 'database')
      master = only_host_with_role(@hosts, 'master')

      the_answers = super
      if dashboard != master
        # in 3.2, dashboard needs the master certname
        the_answers[dashboard.name][:q_puppetmaster_certname] = master.to_s
      end

      # do we want to check for updates?
      pe_check_for_updates = answer_for(@options, :q_pe_check_for_updates, 'n')
      the_answers[dashboard.name][:q_pe_check_for_updates] = pe_check_for_updates
      the_answers[master.name][:q_pe_check_for_updates] = pe_check_for_updates

      if @options[:type] == :upgrade && dashboard != database
        # In a split configuration, there is no way for the upgrader
        # to know how much disk space is available for the database
        # migration. We tell it to continue on, because we're
        # awesome.
        the_answers[dashboard.name][:q_upgrade_with_unknown_disk_space] = 'y'
      end
      @hosts.each do |h|
        h[:answers] = the_answers[h.name]
      end
      return the_answers
    end

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


Question:
Copies a {@link Claim}.

@param object
object to copy
@return copied object

public Claim copy(Claim object) {
		return dataObjectFactory.getClaim(
				(EntityIdValue) visit(object.getSubject()),
				copy(object.getMainSnak()),
				copy(object.getQualifiers()));
	}

func trackSyncPtrChangesInCreate(
	mostRecentTargetPtr data.BlockPointer, unmergedChain *crChain,
	unmergedChains *crChains, toName string) {
	targetChain, ok := unmergedChains.byMostRecent[mostRecentTargetPtr]
	var refs, unrefs []data.BlockPointer
	if ok && targetChain.isFile() {
		// The create op also needs to reference the child block ptrs
		// created by any sync ops (and not unreferenced by future
		// ones).
		for _, op := range targetChain.ops {
			syncOp, ok := op.(*syncOp)
			if !ok {
				continue
			}
			for _, ref := range op.Refs() {
				if !unmergedChains.isDeleted(ref) {
					refs = append(refs, ref)
				}
			}
			for _, unref := range op.Unrefs() {
				unrefs = append(unrefs, unref)
			}
			// Account for the file ptr too, if it's the most recent.
			filePtr := syncOp.File.Ref
			_, isMostRecent := unmergedChains.byMostRecent[filePtr]
			if isMostRecent && !unmergedChains.isDeleted(filePtr) {
				refs = append(refs, filePtr)
			}
		}
	}
	if len(refs) > 0 {
		for _, uop := range unmergedChain.ops {
			cop, ok := uop.(*createOp)
			if !ok || cop.NewName != toName {
				continue
			}
			for _, ref := range refs {
				cop.AddRefBlock(ref)
			}
			for _, unref := range unrefs {
				cop.AddUnrefBlock(unref)
			}
			break
		}
	}
}

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


Question:
:param model:
        :param fields_convert_map: it's different from ListView
        :param kwargs:
        :return:

def _select_list_view(self, model, **kwargs):

        from uliweb import request

        # add download fields process
        fields = kwargs.pop('fields', None)
        meta = kwargs.pop('meta', 'Table')
        if 'download' in request.GET:
            if 'download_fields' in kwargs:
                fields = kwargs.pop('download_fields', fields)
            if 'download_meta' in kwargs:
                meta = kwargs.pop('download_meta')
            else:
                if hasattr(model, 'Download'):
                    meta = 'Download'
                else:
                    meta = meta

        view = functions.SelectListView(model, fields=fields, meta=meta, **kwargs)
        return view

def to_array(self):

        array = super(InlineQueryResultLocation, self).to_array()
        # 'type' and 'id' given by superclass
        array['latitude'] = float(self.latitude)  # type float
        array['longitude'] = float(self.longitude)  # type float
        array['title'] = u(self.title)  # py2: type unicode, py3: type str
        if self.live_period is not None:
            array['live_period'] = int(self.live_period)  # type int
        if self.reply_markup is not None:
            array['reply_markup'] = self.reply_markup.to_array()  # type InlineKeyboardMarkup
        if self.input_message_content is not None:
            array['input_message_content'] = self.input_message_content.to_array()  # type InputMessageContent
        if self.thumb_url is not None:
            array['thumb_url'] = u(self.thumb_url)  # py2: type unicode, py3: type str
        if self.thumb_width is not None:
            array['thumb_width'] = int(self.thumb_width)  # type int
        if self.thumb_height is not None:
            array['thumb_height'] = int(self.thumb_height)  # type int
        return array

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


Question:
@param array $amazonRequest

@return PlaybackState

public static function fromAmazonRequest(array $amazonRequest): self
    {
        $playbackState = new self();

        $playbackState->token                = isset($amazonRequest['token']) ? $amazonRequest['token'] : null;
        $playbackState->offsetInMilliseconds = isset($amazonRequest['offsetInMilliseconds']) ? $amazonRequest['offsetInMilliseconds'] : null;
        $playbackState->playerActivity       = isset($amazonRequest['playerActivity']) ? $amazonRequest['playerActivity'] : null;

        return $playbackState;
    }

def list_streams(self, types=[], inactive=False):
        '''  '''
        req_hook = 'pod/v1/streams/list'
        json_query = {
                       "streamTypes": types,
                       "includeInactiveStreams": inactive
                     }
        req_args = json.dumps(json_query)
        status_code, response = self.__rest__.POST_query(req_hook, req_args)
        self.logger.debug('%s: %s' % (status_code, response))
        return status_code, response

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


Question:
The time of day to complete firing at the given interval.

@param \DateTime $startTimeOfDay only time part is relevant

public function setStartTimeOfDay(\DateTime $startTimeOfDay)
    {
        $startTimeOfDay = clone $startTimeOfDay;
        $startTimeOfDay->setDate(1970, 1, 1); // zero date

        if ($this->getEndTimeOfDay() && $this->getEndTimeOfDay() < $startTimeOfDay) {
            throw new \InvalidArgumentException('End time of day cannot be before start time of day');
        }

        $this->setValue('startTimeOfDay', $startTimeOfDay);
    }

public function run(string $name, $parameters = null)
    {
        if ($this->enabled && $this->has($name)) {
            $this->getSwoole()->task([
                'name' => $name,
                'parameters' => $parameters
            ]);
        }
    }

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


Question:
Get an object in this tree.

@param string $path The path to an object in the tree.

@return Blob|Tree|false
A Blob or Tree object, or false if the object does not exist.

public function getObject($path)
    {
        if ($path === '' || $path === '.') {
            return $this;
        }
        $data = $this->getObjectData($path);
        if ($data === false) {
            return false;
        }

        if ($data['type'] === 'blob') {
            return Blob::fromSha($data['sha'], $this->getUri(), $this->client);
        } elseif ($data['type'] === 'tree') {
            return Tree::fromSha($data['sha'], $this->getUri(), $this->client);
        }

        throw new \RuntimeException('Unrecognised object type: ' . $data['type']);
    }

private function parseModel($definition, $xml = true) {
        $model = strpos($definition, '\\') === false ?
            $this->modelsNamespace . '\\' . $definition :
            $definition;

        if (!is_subclass_of($model, ApiModel::class)) {
            throw new Exception("The model definition for $model was not found", 501);
        }

        $ret = [
            'type' => 'object',
        ];

        $class = new ReflectionClass($model);

        $properties =  $this->parseProperties($class);
        foreach ($properties as $name => &$property) {
            if (isset($property['required'])) {
                unset($property['required']);
                if (!isset($ret['required'])) {
                    $ret['required'] = [];
                }
                $ret['required'][] = $name;
            }
        }
        $ret['properties'] = $properties;

        if ($xml) {
            $ret['xml'] = ['name' => $definition];
        }

        return $ret;
    }

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


Question: // Log logs a message with the given priority.

func (lo Logger) Log(pr Priority, me ...interface{}) {
	logMessage(lo, pr, me)
}

boolean hasTransformation() {

        String transformationPath = getTransformationPath();
        boolean result = (transformationPath != null) && new File(transformationPath).exists();
        if (result) {
            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_XSLT_CONFIG_ENABLED_1, transformationPath));
        } else {
            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_XSLT_CONFIG_DISABLED_0));
        }
        return result;
    }

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


Question:
Returns a parent directory, n places above the input filepath.

    Equivalent to something like: '/home/user/dir'.split('/')[-2] if n=2.

def fetch_parent_dir(filepath, n=1):
    '''
    '''
    filepath = os.path.realpath(filepath)
    for i in range(n):
        filepath = os.path.dirname(filepath)
    return os.path.basename(filepath)

def extract_all_snow_tweets_from_disk_generator(json_folder_path):

    # Get a generator with all file paths in the folder
    json_file_path_generator = (json_folder_path + "/" + name for name in os.listdir(json_folder_path))

    for path in json_file_path_generator:
        for tweet in extract_snow_tweets_from_file_generator(path):
            yield tweet

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


Question: // GetCharset returns a normalised charset string extracted from the meta tags

func (c Crawler) GetCharset(document *goquery.Document) string {
	// manually-provided charset (from HTTP headers?) takes priority
	if "" != c.Charset {
		return c.Charset
	}

	// <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	ct := c.GetContentType(document)
	if "" != ct && strings.Contains(strings.ToLower(ct), "charset") {
		return getCharsetFromContentType(ct)
	}

	// <meta charset="utf-8">
	selection := document.Find("meta").EachWithBreak(func(i int, s *goquery.Selection) bool {
		_, exists := s.Attr("charset")
		return !exists
	})

	if selection != nil {
		cs, _ := selection.Attr("charset")
		return NormaliseCharset(cs)
	}

	return ""
}

public static function registerAllSeoMeta(Component $model)
	{
		self::registerMetaTitle($model);
		self::registerMetaKeywords($model);
		self::registerMetaDescription($model);
	}

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


Question:
/*
(non-Javadoc)

@see example.webapp.dao.interfaces.Dao#load(java.io.Serializable)

public Location load(Serializable id) {
		String sql = "select * from Location where id = ?";
		return getSimpleJdbcTemplate().queryForObject(sql, new LocationMapper(), id);
	}

public static String getMapperSql(SqlSession session, String fullMapperMethodName, Object... args) {
        if (args == null || args.length == 0) {
            return getNamespaceSql(session, fullMapperMethodName, null);
        }
        String methodName = fullMapperMethodName.substring(fullMapperMethodName.lastIndexOf('.') + 1);
        Class<?> mapperInterface = null;
        try {
            mapperInterface = Class.forName(fullMapperMethodName.substring(0, fullMapperMethodName
                    .lastIndexOf('.')));
            return getMapperSql(session, mapperInterface, methodName, args);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("参数" + fullMapperMethodName + "无效！");
        }
    }

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


Question:
Adding for select control.
    :param sig_dic:
        html_media_type = {
        'en': 'tag_media_type',
        'zh': 'Media_type',
        'dic': {1: 'Document', 2: 'Data', 3: 'Program'},
        'type': 'select',
        }

def gen_select_add(sig_dic):
    '''

    '''

    option_str = ''

    for key, val in sig_dic['dic'].items():
        tmp_str = '''<option value="{0}">{1}</option>'''.format(key, val)
        option_str += tmp_str

    return '''

    {sig_zh}

<select id="{sig_en}" name="{sig_en}" class="form-control">
    {option_str}</select>

    '''.format(sig_en=sig_dic['en'], sig_zh=sig_dic['zh'], option_str=option_str)

protected function initializeConverterHolder(ConverterHolder $converter_holder)
    {
        $converter_holder
            ->registerConverter('Array', new Converter\PgArray(), ['array'], false)
            ->registerConverter(
                'Boolean',
                new Converter\PgBoolean(),
                [
                    'bool',
                    'pg_catalog.bool',
                    'boolean',
                ],
                false
            )
            ->registerConverter(
                'Number',
                new Converter\PgNumber(),
                [
                    'int2', 'pg_catalog.int2',
                    'int4', 'pg_catalog.int4', 'int', 'integer',
                    'int8', 'pg_catalog.int8',
                    'numeric', 'pg_catalog.numeric',
                    'float4', 'pg_catalog.float4', 'float',
                    'float8', 'pg_catalog.float8',
                    'oid', 'pg_catalog.oid',
                ],
                false
            )
            ->registerConverter(
                'String',
                new Converter\PgString(),
                [
                    'varchar', 'pg_catalog.varchar',
                    'char', 'pg_catalog.char',
                    'text', 'pg_catalog.text',
                    'citext', 'public.citext',
                    'uuid', 'pg_catalog.uuid',
                    'tsvector', 'pg_catalog.tsvector',
                    'xml', 'pg_catalog.xml',
                    'bpchar', 'pg_catalog.bpchar',
                    'name', 'pg_catalog.name',
                    'character varying',
                    'regclass', 'pg_catalog.regclass',
                    'regproc', 'pg_catalog.regproc',
                    'regprocedure', 'pg_catalog.regprocedure',
                    'regoper', 'pg_catalog.regoper',
                    'regoperator', 'pg_catalog.regoperator',
                    'regtype', 'pg_catalog.regtype',
                    'regrole', 'pg_catalog.regrole',
                    'regnamespace', 'pg_catalog.regnamespace',
                    'regconfig', 'pg_catalog.regconfig',
                    'regdictionary', 'pg_catalog.regdictionary',
                    'inet', 'pg_catalog.inet',
                    'cidr', 'pg_catalog.cidr',
                    'macaddr', 'pg_catalog.macaddr',
                ],
                false
            )
            ->registerConverter(
                'Timestamp',
                new Converter\PgTimestamp(),
                [
                    'timestamp', 'pg_catalog.timestamp',
                    'date', 'pg_catalog.date',
                    'time', 'pg_catalog.time',
                    'timestamptz', 'pg_catalog.timestamptz',
                ],
                false
            )
            ->registerConverter('Interval', new Converter\PgInterval(), ['interval', 'pg_catalog.interval'], false)
            ->registerConverter('Binary', new Converter\PgBytea(), ['bytea', 'pg_catalog.bytea'], false)
            ->registerConverter('Point', new Converter\Geometry\PgPoint(), ['point', 'pg_catalog.point'], false)
            ->registerConverter('Circle', new Converter\Geometry\PgCircle(), ['circle', 'pg_catalog.circle'], false)
            ->registerConverter('Box', new Converter\Geometry\PgBox(), ['box', 'pg_catalog.box'], false)
            ->registerConverter(
                'JSON',
                new Converter\PgJson(),
                [
                    'json',
                    'jsonb',
                    'pg_catalog.json',
                    'pg_catalog.jsonb'
                ],
                false
            )
            ->registerConverter(
                'NumberRange',
                new Converter\PgNumRange(),
                [
                    'int4range', 'pg_catalog.int4range',
                    'int8range', 'pg_catalog.int8range',
                    'numrange', 'pg_catalog.numrange',
                ],
                false
            )
            ->registerConverter(
                'TsRange',
                new Converter\PgTsRange(),
                [
                    'tsrange',
                    'pg_catalog.tsrange',
                    'daterange',
                    'pg_catalog.daterange',
                    'tstzrange',
                    'pg_catalog.tstzrange',
                ],
                false
            )
            ;

        return $this;
    }

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


Question: read message from server

def _read_msg(self):
        """"""

        #
        # NOTE:
        # '_recv_socket(nbytes)' was implemented as
        # 'socket.recv(nbytes, socket.MSG_WAITALL)'
        # but socket.MSG_WAITALL proved not reliable
        #

        def _recv_socket(nbytes):
            """read nbytes bytes from self.socket"""

            #
            # code below is written under the assumption that
            # 'nbytes' is smallish so that the 'while len(buf) < nbytes' loop
            # is entered rarerly
            #
            try:
                buf = self.socket.recv(nbytes)
            except IOError as err:
                raise ConnError(*err.args)

            if not buf:
                raise ShortRead(0, nbytes)

            while len(buf) < nbytes:
                try:
                    tmp = self.socket.recv(nbytes - len(buf))
                except IOError as err:
                    raise ConnError(*err.args)

                if not tmp:
                    if self.verbose:
                        print('ee', repr(buf))
                    raise ShortRead(len(buf), nbytes)

                buf += tmp

            assert len(buf) == nbytes, (buf, len(buf), nbytes)
            return buf

        data = _recv_socket(_FromServerHeader.header_size)
        header = _FromServerHeader(data)
        if self.verbose:
            print('<-', repr(header))

        # error conditions
        if header.version != 0:
            raise MalformedHeader('bad version', header)
        if header.payload > MAX_PAYLOAD:
            raise MalformedHeader('huge payload, unwilling to read', header)

        if header.payload > 0:
            payload = _recv_socket(header.payload)
            if self.verbose:
                print('..', repr(payload))
            assert header.size <= header.payload
            payload = payload[:header.size]
        else:
            payload = bytes()
        return header, payload

public String getMessage(String id, String defaultMsg) {
    return getMessage(id, lang, defaultMsg);
  }

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


Question: // NewGetStorageReport returns a new GetStorageReport instance

func NewGetStorageReport(StartDate string, TotalUsage []uint64, SharedUsage []uint64, UnsharedUsage []uint64, SharedFolders []uint64, MemberStorageMap [][]*StorageBucket) *GetStorageReport {
	s := new(GetStorageReport)
	s.StartDate = StartDate
	s.TotalUsage = TotalUsage
	s.SharedUsage = SharedUsage
	s.UnsharedUsage = UnsharedUsage
	s.SharedFolders = SharedFolders
	s.MemberStorageMap = MemberStorageMap
	return s
}

def handle_single_message(self, msg):

        job_id = msg.message['job_id']
        actual_msg = msg.message
        if msg.type == MessageType.JOB_UPDATED:
            progress = actual_msg['progress']
            total_progress = actual_msg['total_progress']
            self.storage_backend.update_job_progress(job_id, progress,
                                                     total_progress)
        elif msg.type == MessageType.JOB_COMPLETED:
            self.storage_backend.complete_job(job_id)
        elif msg.type == MessageType.JOB_FAILED:
            exc = actual_msg['exception']
            trace = actual_msg['traceback']
            self.storage_backend.mark_job_as_failed(job_id, exc, trace)
        elif msg.type == MessageType.JOB_CANCELED:
            self.storage_backend.mark_job_as_canceled(job_id)
        else:
            self.logger.error("Unknown message type: {}".format(msg.type))

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


Question:
Delete target from user's block list.

@param string $user   Username
@param string $target Target's username
@param string $token  Twitch token

@return JSON Request result

public function deleteBlock($user, $target, $token = null)
    {
        return $this->sendRequest('DELETE', 'users/'.$user.'/blocks/'.$target, $this->getToken($token));
    }

public function putGuests($id, array $guests): array
    {
        $options = ['json' => compact('id', 'guests')];

        /** @var JsonStream $stream */
        $stream = $this->client
            ->put(KintoneApi::generateUrl('space/guests.json', $id), $options)
            ->getBody();

        return $stream->jsonSerialize();
    }

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


Question: Marshall the given parameter object.

public void marshall(RegisterDeviceRequest registerDeviceRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(registerDeviceRequest.getIdentityPoolId(), IDENTITYPOOLID_BINDING);
            protocolMarshaller.marshall(registerDeviceRequest.getIdentityId(), IDENTITYID_BINDING);
            protocolMarshaller.marshall(registerDeviceRequest.getPlatform(), PLATFORM_BINDING);
            protocolMarshaller.marshall(registerDeviceRequest.getToken(), TOKEN_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: Do the pulling if necessary

def update(self):

        # Fetch remotes, so we know we're dealing with latest remote
        yield from self.update_remotes()

        # Rename local untracked files that might be overwritten by pull
        yield from self.rename_local_untracked()

        # Reset local files that have been deleted. We don't actually expect users to
        # delete something that's present upstream and expect to keep it. This prevents
        # unnecessary conflicts, and also allows users to click the link again to get
        # a fresh copy of a file they might have screwed up.
        yield from self.reset_deleted_files()

        # If there are local changes, make a commit so we can do merges when pulling
        # We also allow empty commits. On NFS (at least), sometimes repo_is_dirty returns a false
        # positive, returning True even when there are no local changes (git diff-files seems to return
        # bogus output?). While ideally that would not happen, allowing empty commits keeps us
        # resilient to that issue.
        if self.repo_is_dirty():
            yield from self.ensure_lock()
            yield from execute_cmd(['git', 'commit', '-am', 'WIP', '--allow-empty'], cwd=self.repo_dir)

        # Merge master into local!
        yield from self.ensure_lock()
        yield from execute_cmd(['git', 'merge', '-Xours', 'origin/{}'.format(self.branch_name)], cwd=self.repo_dir)

def save_excursion
      old_point = new_mark
      old_mark = @mark&.dup
      old_column = @goal_column
      begin
        yield
      ensure
        point_to_mark(old_point)
        old_point.delete
        if old_mark
          @mark.location = old_mark.location
          old_mark.delete
        end
        @goal_column = old_column
      end
    end

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


Question:
Calculate the number of visible layers in the legend.

        .. versionadded: 3.1

        :returns: Count of layers that are actually visible.
        :rtype: int

def _visible_layers_count(self):

        treeroot = QgsProject.instance().layerTreeRoot()
        return len([lyr for lyr in treeroot.findLayers() if lyr.isVisible()])

func Unary(op syntax.Token, x Value) (Value, error) {
	switch op {
	case syntax.MINUS:
		switch x := x.(type) {
		case Int:
			return zero.Sub(x), nil
		case Float:
			return -x, nil
		}
	case syntax.PLUS:
		switch x.(type) {
		case Int, Float:
			return x, nil
		}
	case syntax.TILDE:
		if xint, ok := x.(Int); ok {
			return xint.Not(), nil
		}
	case syntax.NOT:
		return !x.Truth(), nil
	}
	return nil, fmt.Errorf("unknown unary op: %s %s", op, x.Type())
}

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


Question:
// Equal returns true if the given option is equal to the instance one. In case
// the given option is nil, we checked the instance one is set to the default
// value of the option.

func (o *InsideBoundingBoxOption) Equal(o2 *InsideBoundingBoxOption) bool {
	if o2 == nil {
		return len(o.boxes) == 0 && len(o.coordinates) == 0
	}
	return reflect.DeepEqual(o, o2)
}

def parse_files(*files)
      require 'ox'
      @tests = []
      failed_tests = []

      Array(files).flatten.each do |file|
        raise "No JUnit file was found at #{file}" unless File.exist? file

        xml_string = File.read(file)
        doc = Ox.parse(xml_string)

        suite_root = doc.nodes.first.value == 'testsuites' ? doc.nodes.first : doc
        @tests += suite_root.nodes.map(&:nodes).flatten.select { |node| node.kind_of?(Ox::Element) && node.value == 'testcase' }

        failed_suites = suite_root.nodes.select { |suite| suite[:failures].to_i > 0 || suite[:errors].to_i > 0 }
        failed_tests += failed_suites.map(&:nodes).flatten.select { |node| node.kind_of?(Ox::Element) && node.value == 'testcase' }
      end

      @failures = failed_tests.select do |test|
        test.nodes.count > 0
      end.select do |test|
        node = test.nodes.first
        node.kind_of?(Ox::Element) && node.value == 'failure'
      end

      @errors = failed_tests.select do |test|
        test.nodes.count > 0
      end.select do |test|
        node = test.nodes.first
        node.kind_of?(Ox::Element) && node.value == 'error'
      end

      @skipped = tests.select do |test|
        test.nodes.count > 0
      end.select do |test|
        node = test.nodes.first
        node.kind_of?(Ox::Element) && node.value == 'skipped'
      end

      @passes = tests - @failures - @errors - @skipped
    end

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


Question: Returns text color rgb tuple of right line

def _get_text_color(self):
        """"""

        color = self.code_array.cell_attributes[self.key]["textcolor"]
        return tuple(c / 255.0 for c in color_pack2rgb(color))

def drawImage(self, image):

        padding = image.width() % 4
        for i in range(0, image.height()):
            tmp = image.copy(0, i, image.width() + padding, 1)
            #in RDP image or bottom top encoded
            ptr = tmp.bits()
            ptr.setsize(tmp.byteCount())
            self._controller.sendUpdate(self._dx, i + self._dy, image.width() + self._dx - 1, i + self._dy, tmp.width(), tmp.height(), self._colorDepth, False, ptr.asstring())

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


Question:
This method returns the HELM notation for nucleotide linker

@return linker notation

public String getLinkerNotation() {
    String pSymbol = getPhosphateSymbol();
    String result = null;
    if (null == pSymbol || pSymbol.length() == 0) {
      result = "";
    } else {
      if (pSymbol.length() > 1)
        result = "[" + pSymbol + "]";
      else
        result = pSymbol;
    }
    return result;
  }

def _endpoint_chain
      chain = []
      node = self
      while node.is_a?(BaseEndpoint)
        chain << node
        node = node.parent
      end
      chain.reverse
    end

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


Question: // Returns true if ips contains IPv6 addresses.

func includesIPv6(ips []net.IP) bool {
	for _, ip := range ips {
		if ip.To4() == nil && ip.To16() != nil {
			return true
		}
	}

	return false
}

func (b *serverBuilder) AddExistsSwitchConnectedNICWithDisplayIP(switchID, displayIP string) {
	b.nicConnections = append(b.nicConnections, switchID)
	b.displayIPAddresses = append(b.displayIPAddresses, displayIP)
}

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


Question: Returns a copy of the currently registered keys.

@SuppressWarnings("unchecked")
	public static Map<String, ConfigurationKey<?>> registeredKeys() {
		synchronized (registeredKeys) {
			if (copy == null) copy = Collections.unmodifiableMap((Map<String, ConfigurationKey<?>>) registeredKeys.clone());
			return copy;
		}
	}

func (in *EnvVarSource) DeepCopyInto(out *EnvVarSource) {
	*out = *in
	if in.FieldRef != nil {
		in, out := &in.FieldRef, &out.FieldRef
		*out = new(ObjectFieldSelector)
		**out = **in
	}
	if in.ResourceFieldRef != nil {
		in, out := &in.ResourceFieldRef, &out.ResourceFieldRef
		*out = new(ResourceFieldSelector)
		(*in).DeepCopyInto(*out)
	}
	if in.ConfigMapKeyRef != nil {
		in, out := &in.ConfigMapKeyRef, &out.ConfigMapKeyRef
		*out = new(ConfigMapKeySelector)
		(*in).DeepCopyInto(*out)
	}
	if in.SecretKeyRef != nil {
		in, out := &in.SecretKeyRef, &out.SecretKeyRef
		*out = new(SecretKeySelector)
		(*in).DeepCopyInto(*out)
	}
	return
}

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


Question:
// Error can be either of the following types:
//
//   - InvalidObjectFault
//   - RuntimeFault

func (service *VboxPortType) IGuestSessionStateChangedEventgetError(request *IGuestSessionStateChangedEventgetError) (*IGuestSessionStateChangedEventgetErrorResponse, error) {
	response := new(IGuestSessionStateChangedEventgetErrorResponse)
	err := service.client.Call("", request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

public function get($tag)
    {
        if (!isset($this->styles[$tag])) {
            throw new OutOfBoundsException(sprintf(
                'The style tag "%s" does not exist.',
                $tag
            ));
        }

        return $this->styles[$tag];
    }

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


Question:
Input channel creation callback
        Queue declaration done here

        Args:
            channel: input channel

def on_channel_open(self, channel):

        self.in_channel.exchange_declare(exchange='input_exc', type='topic', durable=True)
        channel.queue_declare(callback=self.on_input_queue_declare, queue=self.INPUT_QUEUE_NAME)

def help
      puts
      puts  "chimpd -- a RightScale Platform command-line tool"
      puts
      puts  "Syntax: chimpd [--logfile=<name>] [--concurrency=<c>] [--delay=<d>] [--retry=<r>] [--port=<p>] [--bind-address=<addr> ] [--verbose]"
      puts
      puts  "Options:"
      puts
      puts  " --logfile=<name>            Specifiy the desired log location"
      puts  " --concurrency=<n>           Specify the level of concurrent actions"
      puts  " --delay=<n>                 Specify the number of seconds to wait before executing the action"
      puts  " --retry=<r>                 Specify the number of times chimpd should retry executing the action"
      puts
      puts  " --verbose                   Run chimpd in verbose mode."
      puts  " --quiet                     Supress non-essential output"
      puts
      puts  " --port=<port>               Specify the port number for chimpd to listen on (default: 9055)"
      puts  " --bind-address=<addr>       Specify an interface address for chimpd to bind to.  0.0.0.0 allows all, default is 'localhost'"
      puts
      puts  " --help                      Displays this menu"
      puts
      exit 0
    end

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


Question:
// GetIAMPolicy fetches an IAM policy of a resource.
//
// On non-success HTTP status codes returns googleapi.Error.

func (cl *Client) GetIAMPolicy(c context.Context, resource string) (*Policy, error) {
	response := &Policy{}
	if err := cl.iamAPIRequest(c, resource, "getIamPolicy", nil, response); err != nil {
		return nil, err
	}
	return response, nil
}

func (service *VboxPortType) IMachinegetCPUStatus(request *IMachinegetCPUStatus) (*IMachinegetCPUStatusResponse, error) {
	response := new(IMachinegetCPUStatusResponse)
	err := service.client.Call("", request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

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


Question:
Add the following actions to the report:
following pages, downloads, outlinks

@param LogAggregator $logAggregator
@param $report
@param $idaction
@param string $actionType
@param $limitBeforeGrouping
@param boolean $includeLoops

private function addFollowingActions($logAggregator, &$report, $idaction, $actionType, $limitBeforeGrouping, $includeLoops = false)
    {
        $data = $this->queryFollowingActions(
            $idaction, $actionType, $logAggregator, $limitBeforeGrouping, $includeLoops);

        foreach ($data as $tableName => $table) {
            $report[$tableName] = $table;
        }
    }

public function evaluate(FlowQuery $flowQuery, array $arguments)
    {
        if (!isset($arguments[0]) || empty($arguments[0])) {
            return;
        }
        if (!is_string($arguments[0])) {
            throw new FizzleException('filter operation expects string argument', 1332489625);
        }
        $filter = $arguments[0];

        $parsedFilter = FizzleParser::parseFilterGroup($filter);

        $filteredContext = [];
        $context = $flowQuery->getContext();
        foreach ($context as $element) {
            if ($this->matchesFilterGroup($element, $parsedFilter)) {
                $filteredContext[] = $element;
            }
        }
        $flowQuery->setContext($filteredContext);
    }

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


Question:
Delegator
@param logicalAddress The logical address
@param address The address

public void addWorkManager(org.ironjacamar.core.spi.workmanager.Address logicalAddress, org.jgroups.Address address)
   {
      super.localWorkManagerAdd(logicalAddress, address);
   }

def attach_lb(kwargs=None, call=None):
    '''

    '''
    if call != 'function':
        raise SaltCloudSystemExit(
            'The attach_lb function must be called with -f or --function.'
        )

    if not kwargs or 'name' not in kwargs:
        log.error(
            'A load-balancer name must be specified.'
        )
        return False
    if 'member' not in kwargs:
        log.error(
            'A node name name must be specified.'
        )
        return False

    conn = get_conn()
    node = conn.ex_get_node(kwargs['member'])

    lb_conn = get_lb_conn(conn)
    lb = lb_conn.get_balancer(kwargs['name'])

    __utils__['cloud.fire_event'](
        'event',
        'attach load_balancer',
        'salt/cloud/loadbalancer/attaching',
        args=kwargs,
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )

    result = lb_conn.balancer_attach_compute_node(lb, node)

    __utils__['cloud.fire_event'](
        'event',
        'attached load_balancer',
        'salt/cloud/loadbalancer/attached',
        args=kwargs,
        sock_dir=__opts__['sock_dir'],
        transport=__opts__['transport']
    )
    return _expand_item(result)

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


Question: Re-write an input file with contigs matching the correct reference.

def _write_newname_file(in_file, out_file, mappings):

    with utils.open_gzipsafe(in_file) as in_handle:
        with open(out_file, "w") as out_handle:
            for line in in_handle:
                if line.startswith("#"):
                    out_handle.write(line)
                else:
                    parts = line.split("\t")
                    new_contig = mappings.get(parts[0])
                    if new_contig:
                        parts[0] = new_contig
                        out_handle.write("\t".join(parts))

function (fileObj) {
            if (typeof fileObj === "string") {
                fileObj = new java.io.File(fileObj);
            }
            return (fileObj.getCanonicalPath() + "").replace(file.backSlashRegExp, "/");
        }

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


Question:
Execute the importing of several children

@param DataObjectSet $children
@param SiteTree $parent

protected function importChildren($children, $parent, $includeChildren, $duplicateStrategy) {
		if (!$children) {
			return;
		}

		// get the importer to use, import, then see if there's any
		foreach ($children as $child) {
			$pageType = $this->getExternalType($child);
			if (isset($this->contentTransforms[$pageType])) {
				$transformer = $this->contentTransforms[$pageType];
				$result = $transformer->transform($child, $parent, $duplicateStrategy);

				$this->extend('onAfterImport', $result);

				// if there's more, then transform them
				if ($includeChildren && $result && $result->children && count($result->children)) {
					// import the children
					$this->importChildren($result->children, $result->page, $includeChildren, $duplicateStrategy);
				}
			}
		}
	}

def load_and_parse(self, package_name, root_dir, relative_dirs, tags=None):
        """"""

        extension = "[!.#~]*.csv"
        if dbt.flags.STRICT_MODE:
            dbt.contracts.project.ProjectList(**self.all_projects)

        file_matches = dbt.clients.system.find_matching(
            root_dir,
            relative_dirs,
            extension)

        # we only want to parse seeds if we're inside 'dbt seed'
        should_parse = self.root_project_config.args.which == 'seed'

        result = {}
        for file_match in file_matches:
            node, agate_table = self.parse_seed_file(file_match, root_dir,
                                                     package_name,
                                                     should_parse)
            node_path = self.get_path(NodeType.Seed, package_name, node.name)
            parsed = self.parse_node(node, node_path,
                                     self.all_projects.get(package_name),
                                     tags=tags, agate_table=agate_table)
            result[node_path] = parsed

        return result

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


Question:
// kvPaths is used to test CRUD and List operations. It is a simplified
// version of the passthrough backend that only accepts string values.

func kvPaths(b *backend) []*framework.Path {
	return []*framework.Path{
		&framework.Path{
			Pattern: "kv/?",
			Callbacks: map[logical.Operation]framework.OperationFunc{
				logical.ListOperation: b.pathKVList,
			},
		},
		&framework.Path{
			Pattern: "kv/" + framework.GenericNameRegex("key"),
			Fields: map[string]*framework.FieldSchema{
				"key":     &framework.FieldSchema{Type: framework.TypeString},
				"value":   &framework.FieldSchema{Type: framework.TypeString},
				"version": &framework.FieldSchema{Type: framework.TypeInt},
			},
			ExistenceCheck: b.pathExistenceCheck,
			Callbacks: map[logical.Operation]framework.OperationFunc{
				logical.ReadOperation:   b.pathKVRead,
				logical.CreateOperation: b.pathKVCreateUpdate,
				logical.UpdateOperation: b.pathKVCreateUpdate,
				logical.DeleteOperation: b.pathKVDelete,
			},
		},
	}
}

public function need($path, array $data = [])
    {
        $this->needData = [
            'path' => Container::get('config')->get('app_full_path') . '/views/' . $path . '.html',
            'data' => $data,
        ];
        unset($path, $data);
        extract($this->needData['data']);
        include $this->needData['path'];
    }

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


Question:
Collect request information to log it. This can help to solve a problem later.

@return string Requets information, for logging

protected function getRequestInformation() {
		$postdata = '';

		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			// build a request string
			$t = array();

			foreach ($_POST as $k => $v) {
				$t[] = $k . '=' . $v;
			}

			// make a one line string
			$postdata = preg_replace('![\n\r]!',"",implode('&',$t));

			// truncate if too long
			if (strlen($postdata) > 250) {
				$postdata = substr($postdata,0,250);
			}
		}

		// build a string with information about a request
		$requestinfo = ' '.getmypid() . "; " .
			basename($_SERVER['SCRIPT_FILENAME']) . "; " .
			$_SERVER['REMOTE_ADDR'] . "; " .
			$_SERVER['REQUEST_METHOD'] . "; " .
			$_SERVER['QUERY_STRING'] . "; " .
			$postdata . "; " .
			$_SERVER['HTTP_USER_AGENT'] . "; " .
			$_SERVER['HTTP_REFERER'];
		return $requestinfo;
	}

def _run__http(self, action, replace):
        """"""

        query = action['query']
#        self._debug = True
        url = '{type}://{host}{path}'.format(path=query['path'], **action)
        content = None
        method = query.get('method', "get").lower()
        self.debug("{} {} url={}\n", action['type'], method, url)
        if method == "post":
            content = query['content']
        headers = query.get('headers', {})

        if replace and action.get('template'):
            self.rfxcfg.macro_expand(url, replace)
            if content:
                if isinstance(content, dict):
                    for key, value in content.items():
                        content[key] = self.rfxcfg.macro_expand(value, replace)
                else:
                    content = self.rfxcfg.macro_expand(content, replace)

            newhdrs = dict()
            for key, value in headers.items():
                newhdrs[key.lower()] = self.rfxcfg.macro_expand(value, replace)
            headers = newhdrs

        self.debug("{} headers={}\n", action['type'], headers)
        self.debug("{} content={}\n", action['type'], content)

        if content and isinstance(content, dict):
            content = json.dumps(content)

        self.logf("Action {name} {type}\n", **action)
        result = getattr(requests, method)(url, headers=headers, data=content, timeout=action.get('timeout', 5))
        expect = action.get('expect', {})
        expected_codes = expect.get("response-codes", (200, 201, 202, 204))
        self.debug("{} expect codes={}\n", action['type'], expected_codes)
        self.debug("{} status={} content={}\n", action['type'], result.status_code, result.text)
        if result.status_code not in expected_codes:
            self.die("Unable to make {} call, unexpected result ({})",
                     action['type'], result.status_code)

        if 'content' in expect:
            self.debug("{} expect content={}\n", action['type'], expect['content'])
            if expect['content'] not in result.text:
                self.die("{} call to {} failed\nExpected: {}\nReceived:\n{}",
                         action['type'], url, expect['content'], result.text)

        if 'regex' in expect:
            self.debug("{} expect regex={}\n", action['type'], expect['regex'])
            if not re.search(expect['regex'], result.text):
                self.die("{} call to {} failed\nRegex: {}\nDid not match:\n{}",
                         action['type'], url, expect['regex'], result.text)

        self.log(result.text, level=common.log_msg)

        self.logf("Success, status={}\n", result.status_code, level=common.log_good)
        return True

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


Question:
Get the translation data.

@param MutableBag $tr

@return array

private function getTranslationData(MutableBag $tr)
    {
        $translation = new TranslationFile($this->app, $tr->get('domain'), $tr->get('locale'));

        list($tr['path'], $tr['shortPath']) = $translation->path();
        $tr->set('writeallowed', $translation->isWriteAllowed());

        $this->app['logger.system']->info('Editing translation: ' . $tr->get('shortPath'), ['event' => 'translation']);

        return ['contents' => $translation->content()];
    }

public static MultivaluedMap<String, String> getStructuredParams(String query,
                                                                     String sep,
                                                                     boolean decode,
                                                                     boolean decodePlus) {
        MultivaluedMap<String, String> map = new MetadataMap<>(new LinkedHashMap<String, List<String>>());

        getStructuredParams(map, query, sep, decode, decodePlus);

        return map;
    }

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