Question:
Traverses a set of nested attributes and truncates the value on an object

    :param mixed obj: The object to set the attribute on
    :param tuple path: The path to the attribute on the object

    :rtype None:

def truncate_attr_at_path( obj, path ):

    target = obj
    last_attr = path[-1]
    message = []

    if type(last_attr) == tuple:
        last_attr = last_attr[-1]
    for attr in path[0:-1]:
        try:
            if type(attr) in ( str, unicode ) and target and hasattr( target, attr ) and hasattr( target, '__getitem__' ):
                target = getattr( target, attr )
            elif target:
                try: target = target[attr]
                except: target = eval( "target." + str( attr ) )
        except:
            pass
        try:
            if not target: return
        except: return
        if isinstance( target, ( tuple, list ) ): target = list(target) # Tuples are immutable. Need to be able to manipulate.

    try:
        del_statement = "del target." + str( last_attr )
        eval( del_statement )
        return
    except: pass

    if type( last_attr ) in ( str, unicode ) and target and hasattr( target, last_attr ):
        try: delattr( target, last_attr )
        except: message.append("Failed to delete attribute" + str(last_attr) + "on target" + str(target) )
    elif type(target) == list:
        try: target.pop(last_attr)
        except: message.append( "Failed to delete value on list" + str(target) + "at index" + str(last_attr) )
    else:
        try: del target[str(last_attr)]
        except: message.append( "failed to delete attribute on subscriptable object" )

def _build_tree_by_level(self, time_qualifier, collection_name, since):

        invalid_tree_records = dict()
        invalid_tq_records = dict()

        try:
            job_records = self.job_dao.get_all(collection_name, since)
            for job_record in job_records:
                tree = self.get_tree(job_record.process_name)
                if tree is None:
                    utils.increment_family_property(job_record.process_name, invalid_tree_records)
                    continue

                job_time_qualifier = context.process_context[job_record.process_name].time_qualifier
                if time_qualifier != job_time_qualifier:
                    utils.increment_family_property(job_record.process_name, invalid_tq_records)
                    continue

                tree.update_node(job_record)

        except LookupError:
            self.logger.warning('No job records in {0}.'.format(collection_name))

        for name, counter in invalid_tree_records.items():
            self.logger.warning('Skipping {0} job records for {1} since no tree is handling it.'
                                .format(counter, name))

        for name, counter in invalid_tq_records.items():
            self.logger.warning('Skipping {0} job records for {1} since the process has different time qualifier.'
                                .format(counter, name))

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


Question: // AddModule registers a new module to current vm.

func (m *Motto) AddModule(id string, l ModuleLoader) {
	m.modulesMu.Lock()
	m.modules[id] = l
	m.modulesMu.Unlock()
}

def create(self):

        steps = [
            (self.create_role, (), {}),
            (self.create_vpc, (), {}),
            (self.create_cluster, (), {}),
            (self.create_node_group, (), {}),
            (self.create_spot_nodes, (), {}),
            (self.create_utilities, (), {}),
        ]
        # Execute creation.
        for step in tqdm.tqdm(steps, ncols=70):
            method, args, kwargs = step
            method(*args, **kwargs)

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


Question:
Construct Sidenav instance and set up overlay
@constructor
@param {Element} el
@param {Object} options

function Sidenav(el, options) {
      _classCallCheck(this, Sidenav);

      var _this31 = _possibleConstructorReturn(this, (Sidenav.__proto__ || Object.getPrototypeOf(Sidenav)).call(this, Sidenav, el, options));

      _this31.el.M_Sidenav = _this31;
      _this31.id = _this31.$el.attr('id');

      /**
       * Options for the Sidenav
       * @member Sidenav#options
       * @prop {String} [edge='left'] - Side of screen on which Sidenav appears
       * @prop {Boolean} [draggable=true] - Allow swipe gestures to open/close Sidenav
       * @prop {Number} [inDuration=250] - Length in ms of enter transition
       * @prop {Number} [outDuration=200] - Length in ms of exit transition
       * @prop {Function} onOpenStart - Function called when sidenav starts entering
       * @prop {Function} onOpenEnd - Function called when sidenav finishes entering
       * @prop {Function} onCloseStart - Function called when sidenav starts exiting
       * @prop {Function} onCloseEnd - Function called when sidenav finishes exiting
       */
      _this31.options = $.extend({}, Sidenav.defaults, options);

      /**
       * Describes open/close state of Sidenav
       * @type {Boolean}
       */
      _this31.isOpen = false;

      /**
       * Describes if Sidenav is fixed
       * @type {Boolean}
       */
      _this31.isFixed = _this31.el.classList.contains('sidenav-fixed');

      /**
       * Describes if Sidenav is being draggeed
       * @type {Boolean}
       */
      _this31.isDragged = false;

      // Window size variables for window resize checks
      _this31.lastWindowWidth = window.innerWidth;
      _this31.lastWindowHeight = window.innerHeight;

      _this31._createOverlay();
      _this31._createDragTarget();
      _this31._setupEventHandlers();
      _this31._setupClasses();
      _this31._setupFixed();

      Sidenav._sidenavs.push(_this31);
      return _this31;
    }

func (s *Service) AddDashboardCell(ctx context.Context, id platform.ID, cell *platform.Cell, opts platform.AddDashboardCellOptions) error {
	op := OpPrefix + platform.OpAddDashboardCell
	d, err := s.FindDashboardByID(ctx, id)
	if err != nil {
		return &platform.Error{
			Err: err,
			Op:  op,
		}
	}
	cell.ID = s.IDGenerator.ID()
	if err := s.createCellView(ctx, cell); err != nil {
		return &platform.Error{
			Err: err,
			Op:  op,
		}
	}

	d.Cells = append(d.Cells, cell)
	if err = s.PutDashboardWithMeta(ctx, d); err != nil {
		return &platform.Error{
			Err: err,
			Op:  op,
		}
	}
	return nil
}

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


Question: Returns the abbreviated git id or {@code null}.

@Nullable
  private static String getShortGitId() {
    try {
      InputStream in = JLanguageTool.class.getClassLoader().getResourceAsStream("git.properties");
      if (in != null) {
        Properties props = new Properties();
        props.load(in);
        return props.getProperty("git.commit.id.abbrev");
      }
      return null;
    } catch (IOException e) {
      throw new RuntimeException("Could not get git id from 'git.properties'", e);
    }
  }

func (r *rest) GetById(c *gin.Context) {
	userId, err := strconv.Atoi(c.Param("userId"))
	if err != nil {
		c.JSON(apihelper.BuildRequestError(err))
	}
	if resDTO, err := r.service.RetrieveUserInfoByUserId(uint(userId)); err != nil {
		c.JSON(apihelper.BuildResponseError(err))
	} else {
		c.JSON(http.StatusOK, resDTO)
	}
}

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


Question:
Zkontroluje opravneni a pokud je nema, ukonci aplikaci
@param bool $ajax
@throws AbortException

private function checkHandlerPermission(bool $ajax = true): void
	{
		if (!isset($this->allowedHandler[$this->presenter->getSignal()[1]])) {
			$this->presenter->terminate();
		}
		if ($ajax && !$this->presenter->isAjax()) {
			$this->presenter->terminate();
		}
	}

public static function create($template = 'Response') {
	    $return = null;

	    switch ($template) {
            case 'Discovery':
                $return = new AlexaResponse(
                    new Response(
                        new Event(
                            new Header(),
                            new Payload()
                        )
                    )
                );
            break;

            case 'StateReport':
                $return = new AlexaResponse(
                    new Response(
                        new Event(
                            new Header(),
                            new Payload(),
                            new Endpoint()
                        ),
	                    new Context()
                    )
                );
            break;

            case 'Response':
                $return = new AlexaResponse(
                    new Response(
                        new Event(
                            new Header(),
                            new Payload(),
                            new Endpoint()
                        ),
	                    new Context()
                    )
                );
            break;

		    case 'Authorization':
			    $return = new AlexaResponse(
				    new Response(
					    new Event(
						    new Header(),
						    new Payload()
					    )
				    )
			    );
		    break;

		    case 'Error':
			    $return = new AlexaResponse(
				    new Response(
					    new Event(
						    new Header(),
						    new Payload()
					    )
				    )
			    );
		    break;

            default:
                throw new InvalidArgumentException('Unsupported AlexaResponse template: ' . $template);
            break;
        }

        return $return;
	}

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


Question:
Get an API connection instance.

@param  string  $name
@return ConnectionInterface

public function connection($name = null)
    {
        if (is_null($name)) {
            $name = $this->getDefaultConnection();
        }

        if (! isset($this->connections[$name])) {
            throw new InvalidArgumentException("Connection [{$name}] is not registered.");
        }

        return $this->connections[$name];
    }

func (_class PCIClass) GetAllRecords(sessionID SessionRef) (_retval map[PCIRef]PCIRecord, _err error) {
	_method := "PCI.get_all_records"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg)
	if _err != nil {
		return
	}
	_retval, _err = convertPCIRefToPCIRecordMapToGo(_method + " -> ", _result.Value)
	return
}

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


Question:
// route sends a single htlcPacket through the switch and synchronously awaits a
// response.

func (s *Switch) route(packet *htlcPacket) error {
	command := &plexPacket{
		pkt: packet,
		err: make(chan error, 1),
	}

	select {
	case s.htlcPlex <- command:
	case <-s.quit:
		return ErrSwitchExiting
	}

	select {
	case err := <-command.err:
		return err
	case <-s.quit:
		return ErrSwitchExiting
	}
}

public function any($pattern, $handler, array $requirements = [], array $defaults = [])
    {
        $this->addRoute('GET|HEAD|POST|PUT|PATCH|DELETE', $pattern, $handler, $requirements, $defaults);
    }

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


Question:
Return a 1 or 2 letter String for use as a weekday label

@param day The day for which to generate a label
@return The weekday label

private String getWeekDayLabel(Calendar day) {
        Locale locale = mController.getLocale();

        // Localised short version of the string is not available on API < 18
        if (Build.VERSION.SDK_INT < 18) {
            String dayName = new SimpleDateFormat("E", locale).format(day.getTime());
            String dayLabel = dayName.toUpperCase(locale).substring(0, 1);

            // Chinese labels should be fetched right to left
            if (locale.equals(Locale.CHINA) || locale.equals(Locale.CHINESE) || locale.equals(Locale.SIMPLIFIED_CHINESE) || locale.equals(Locale.TRADITIONAL_CHINESE)) {
                int len = dayName.length();
                dayLabel = dayName.substring(len - 1, len);
            }

            // Most hebrew labels should select the second to last character
            if (locale.getLanguage().equals("he") || locale.getLanguage().equals("iw")) {
                if (mDayLabelCalendar.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) {
                    int len = dayName.length();
                    dayLabel = dayName.substring(len - 2, len - 1);
                } else {
                    // I know this is duplication, but it makes the code easier to grok by
                    // having all hebrew code in the same block
                    dayLabel = dayName.toUpperCase(locale).substring(0, 1);
                }
            }

            // Catalan labels should be two digits in lowercase
            if (locale.getLanguage().equals("ca"))
                dayLabel = dayName.toLowerCase().substring(0, 2);

            // Correct single character label in Spanish is X
            if (locale.getLanguage().equals("es") && day.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY)
                dayLabel = "X";

            return dayLabel;
        }
        // Getting the short label is a one liner on API >= 18
        if (weekDayLabelFormatter == null) {
            weekDayLabelFormatter = new SimpleDateFormat("EEEEE", locale);
        }
        return weekDayLabelFormatter.format(day.getTime());
    }

public Object getDefaultValue(Parameter parameter) {
    Class<?> type = parameter.getType();

    if (TypeUtils.isaString(type)) {
      return getStringDefaultValue(parameter);
    }

    if (TypeUtils.isaByte(type)) {
      return getByteDefaultValue(parameter);
    }

    if (TypeUtils.isaShort(type)) {
      return getShortDefaultValue(parameter);
    }

    if (TypeUtils.isaInteger(type)) {
      return getIntegerDefaultValue(parameter);
    }

    if (TypeUtils.isaLong(type)) {
      return getLongDefaultValue(parameter);
    }

    if (TypeUtils.isaFloat(type)) {
      return getFloatDefaultValue(parameter);
    }

    if (TypeUtils.isaDouble(type)) {
      return getDoubleDefaultValue(parameter);
    }

    if (TypeUtils.isaCharacter(type)) {
      return getCharacterDefaultValue(parameter);
    }

    if (TypeUtils.isaBoolean(type)) {
      return getBooleanDefaultValue(parameter);
    }

    return null;
  }

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


Question:
Erzeugt den Header des Buchungstages.

@param tag der Tag.
@return der Header des Buchungstages.
@throws Exception

private AccountReport22 createDay(BTag tag) throws Exception {
        AccountReport22 report = new AccountReport22();

        if (tag != null) {
            report.getBal().add(this.createSaldo(tag.start, true));
            report.getBal().add(this.createSaldo(tag.end, false));
        }

        if (tag != null && tag.my != null) {
            CashAccount36 acc = new CashAccount36();
            AccountIdentification4Choice id = new AccountIdentification4Choice();
            id.setIBAN(tag.my.iban);
            acc.setId(id);

            acc.setCcy(tag.my.curr);

            BranchAndFinancialInstitutionIdentification5 svc = new BranchAndFinancialInstitutionIdentification5();
            FinancialInstitutionIdentification8 inst = new FinancialInstitutionIdentification8();
            svc.setFinInstnId(inst);
            inst.setBICFI(tag.my.bic);
            report.setAcct(acc);
        }

        return report;
    }

public function parse(Twig_Token $token)
    {
        $parser = $this->parser;
        $stream = $parser->getStream();

        $view = $parser->getExpressionParser()->parseExpression();

        $variablesOverride = new Twig_Node_Expression_Array(array(), $token->getLine());
        if ($stream->test(Twig_Token::NAME_TYPE, 'with')) {
            $stream->next();

            $variablesOverride->addElement($this->parser->getExpressionParser()->parseExpression());
        }

        $stream->expect(Twig_Token::BLOCK_END_TYPE);

        $viewTemplateExpr = new Twig_Node_Expression_MethodCall(
            $view,
            'getTemplateFile',
            new Twig_Node_Expression_Array(array(), $token->getLine()),
            $token->getLine()
        );

        $variablesExpr = new Twig_Node_Expression_MethodCall(
            $view,
            'getTemplateVars',
            $variablesOverride,
            $token->getLine()
        );

        return new Twig_Node_Include(
            $viewTemplateExpr,
            $variablesExpr,
            $only = false,
            $ignoreMissing = false,
            $token->getLine()
        );
    }

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


Question:
Format the message

@param string $level The LogLevel
@param string $message The message to log
@param array $context Additional data
@return string The formatted log message

public function format(string $level, string $message, array $context)
    {
        $search = [
            '%MODULE%' => $context['_module'] ?? "",
            '%LEVEL%' => strtoupper($level),
            '%MESSAGE%' => Logger::fillPlaceholders($message, $context),
            '%DATE%' => date($this->date_format)
        ];

        return str_replace(array_keys($search), array_values($search), $this->format);
    }

public static function url($identifier, $data = null, $domain = null) {

		if(false === is_string($identifier)) {
			return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($identifier)), E_USER_ERROR);
		}

		if(false === static :: routeExists($identifier)) {
			return trigger_error(sprintf('Route identifier "%s" not found in routes.php', $identifier), E_USER_ERROR);
		}

		if(null !== $data && false === is_string($data) && false === is_array($data)) {
			return trigger_error(sprintf('Argument 2 passed to %s() must be of the type array or string, "%s" given', __METHOD__, gettype($data)), E_USER_ERROR);
		}

		if(null !== $domain && false === is_string($domain)) {
			return trigger_error(sprintf('Argument 3 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($domain)), E_USER_ERROR);
		}

		if(true === is_string($data)) {
			$data = [$data];
		}

		if(null === $data) {
			$data = [];
		}

		$route 		= static :: getRoute($identifier);
		$url 		= $route -> getUrl();
		$parameters = 0;
		$optionals  = 0;

		if(preg_match_all('#\{(.*?)(\?)?\}#i', $url, $matches)) {

			foreach($matches[2] as $optional) {

				if('?' === $optional) {

					$optionals++;
					continue;
				}

				$parameters++;
			}

			if(count($data) < $parameters) {
				return trigger_error(sprintf('Incorrect number of parameters given for Router url with identifier "%s". Expecting %s, got %s with %s optional', $route -> getIdentifier(), count($matches[2]), count($data), $optionals), E_USER_ERROR);
			}

			foreach($matches[0] as $index => $match) {

				$match 		= $matches[0][$index];
				$type 		= $matches[1][$index];
				$optional 	= $matches[2][$index];
				$where 		= $route -> getWhere();
				$replace 	= static :: $types['string'];

				if(true === isset(static :: $types[$type])) {
					$replace = static :: $types[$type];
				}

				if(true === is_array($where)) {

					foreach($where as $key => $regex) {

						if($key === $type) {

							$replace =$regex;
							break;
						}
					}
				}

				if(true === isset($data[$index])) {

					if(false === is_string($data[$index]) && false === is_numeric($data[$index])) {
						return trigger_error(sprintf('Router url width id "%s" expects parameters to be a String', $route -> getIdentifier()));
					}

					if(preg_match('#' . $replace . '#i', $data[$index])) {
						$url = preg_replace('#'. preg_quote($match) .'#i', $data[$index], $url, 1);
					}
					else {
						return trigger_error(sprintf('Parameters given to router url width id "%s" do not match. Trying to match regular expression pattern "%s" with "%s" as subject', $route -> getIdentifier(), $replace, $data[$index]));
					}
				}
				elseif('' !== $optional) {
					$url = preg_replace('#'. '/?' . preg_quote($match) .'#i', '', $url, 1);
				}
			}
		}

		if(null !== $domain && false === static :: domainExists($domain)) {
			return trigger_error(sprintf('Domain "%s" does not exists in routes.php', $domain), E_USER_ERROR);
		}

		//Check if routes has a prefix and add it if it does
		$prefix = $route -> getPrefix();

		if(true === isset($prefix['url'])) {
			$url = $prefix['url'] . $url;
		}

		return (null !== $domain ? rtrim($domain, '/') . '/' : '') . $url;
	}

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


Question: // XXX_OneofFuncs is for the internal use of the proto package.

func (*WorkflowTemplatePlacement) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
	return _WorkflowTemplatePlacement_OneofMarshaler, _WorkflowTemplatePlacement_OneofUnmarshaler, _WorkflowTemplatePlacement_OneofSizer, []interface{}{
		(*WorkflowTemplatePlacement_ManagedCluster)(nil),
		(*WorkflowTemplatePlacement_ClusterSelector)(nil),
	}
}

private void createFunction(String name, GeometryFunction function) {
		try {
			Function.create(getGeoPackage().getConnection().getConnection(),
					name, function);
		} catch (SQLException e) {
			log.log(Level.SEVERE, "Failed to create function: " + name, e);
		}
	}

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


Question: // HTTPClientTrace enables OpenCensus tracing of a Go kit HTTP transport client.

func HTTPClientTrace(options ...TracerOption) kithttp.ClientOption {
	cfg := TracerOptions{}

	for _, option := range options {
		option(&cfg)
	}

	if !cfg.Public && cfg.HTTPPropagate == nil {
		cfg.HTTPPropagate = &b3.HTTPFormat{}
	}

	clientBefore := kithttp.ClientBefore(
		func(ctx context.Context, req *http.Request) context.Context {
			var name string

			if cfg.Name != "" {
				name = cfg.Name
			} else {
				// OpenCensus states Path being default naming for a client span
				name = req.Method + " " + req.URL.Path
			}

			ctx, span := trace.StartSpan(
				ctx,
				name,
				trace.WithSampler(cfg.Sampler),
				trace.WithSpanKind(trace.SpanKindClient),
			)

			span.AddAttributes(
				trace.StringAttribute(ochttp.HostAttribute, req.URL.Host),
				trace.StringAttribute(ochttp.MethodAttribute, req.Method),
				trace.StringAttribute(ochttp.PathAttribute, req.URL.Path),
				trace.StringAttribute(ochttp.UserAgentAttribute, req.UserAgent()),
			)

			if !cfg.Public {
				cfg.HTTPPropagate.SpanContextToRequest(span.SpanContext(), req)
			}

			return ctx
		},
	)

	clientAfter := kithttp.ClientAfter(
		func(ctx context.Context, res *http.Response) context.Context {
			if span := trace.FromContext(ctx); span != nil {
				span.SetStatus(ochttp.TraceStatus(res.StatusCode, http.StatusText(res.StatusCode)))
				span.AddAttributes(
					trace.Int64Attribute(ochttp.StatusCodeAttribute, int64(res.StatusCode)),
				)
			}
			return ctx
		},
	)

	clientFinalizer := kithttp.ClientFinalizer(
		func(ctx context.Context, err error) {
			if span := trace.FromContext(ctx); span != nil {
				if err != nil {
					span.SetStatus(trace.Status{
						Code:    trace.StatusCodeUnknown,
						Message: err.Error(),
					})
				}
				span.End()
			}
		},
	)

	return func(c *kithttp.Client) {
		clientBefore(c)
		clientAfter(c)
		clientFinalizer(c)
	}
}

func (pt *pollingTrackerBase) initPollingMethod() error {
	if ao, err := getURLFromAsyncOpHeader(pt.resp); err != nil {
		return err
	} else if ao != "" {
		pt.URI = ao
		pt.Pm = PollingAsyncOperation
		return nil
	}
	if lh, err := getURLFromLocationHeader(pt.resp); err != nil {
		return err
	} else if lh != "" {
		pt.URI = lh
		pt.Pm = PollingLocation
		return nil
	}
	// it's ok if we didn't find a polling header, this will be handled elsewhere
	return nil
}

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


Question:
Recursively filter slashes in array

@param mixed $value
@return array

public function filter($value)
    {
        return is_array($value) ? array_map(array($this, __FUNCTION__), $value) : stripslashes($value);
    }

public function setRule($rule)
    {
        if ('$' == substr($rule, -1, 1)) {
            // 是否完整匹配
            $rule = substr($rule, 0, -1);

            $this->option['complete_match'] = true;
        }

        $rule = '/' != $rule ? ltrim($rule, '/') : '';

        if ($this->parent && $prefix = $this->parent->getFullName()) {
            $rule = $prefix . ($rule ? '/' . ltrim($rule, '/') : '');
        }

        if (false !== strpos($rule, ':')) {
            $this->rule = preg_replace(['/\[\:(\w+)\]/', '/\:(\w+)/'], ['<\1?>', '<\1>'], $rule);
        } else {
            $this->rule = $rule;
        }

        // 生成路由标识的快捷访问
        $this->setRuleName();
    }

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


Question:
Adds the method that fetches fkey-related (referencing) objects but also joins in data from another table.
@param string     &$script The script will be modified in this method.
@param ForeignKey $refFK

protected function addRefFKGetJoinMethods(&$script, ForeignKey $refFK)
    {
        $table = $this->getTable();
        $tblFK = $refFK->getTable();
        $joinBehavior = $this->getBuildProperty('generator.objectModel.useLeftJoinsInDoJoinMethods') ? 'Criteria::LEFT_JOIN' : 'Criteria::INNER_JOIN';

        $fkQueryClassName = $this->getClassNameFromBuilder($this->getNewStubQueryBuilder($refFK->getTable()));
        $relCol = $this->getRefFKPhpNameAffix($refFK, $plural = true);

        $className = $this->getClassNameFromTable($tblFK);

        foreach ($tblFK->getForeignKeys() as $fk2) {

            $tblFK2 = $fk2->getForeignTable();
            $doJoinGet = !$tblFK2->isForReferenceOnly();

            // it doesn't make sense to join in rows from the current table, since we are fetching
            // objects related to *this* table (i.e. the joined rows will all be the same row as current object)
            if ($this->getTable()->getPhpName() == $tblFK2->getPhpName()) {
                $doJoinGet = false;
            }

            $relCol2 = $this->getFKPhpNameAffix($fk2, false);

            if ( $this->getRelatedBySuffix($refFK) != "" &&
                ($this->getRelatedBySuffix($refFK) == $this->getRelatedBySuffix($fk2))) {
                $doJoinGet = false;
            }

            if ($doJoinGet) {
                $script .= "

    /**
     * If this collection has already been initialized with
     * an identical criteria, it returns the collection.
     * Otherwise if this ".$table->getPhpName()." is new, it will return
     * an empty collection; or if this ".$table->getPhpName()." has previously
     * been saved, it will retrieve related $relCol from storage.
     *
     * This method is protected by default in order to keep the public
     * api reasonable.  You can provide public methods for those you
     * actually need in ".$table->getPhpName().".
     *
     * @param      Criteria \$criteria optional Criteria object to narrow the query
     * @param      ConnectionInterface \$con optional connection object
     * @param      string \$joinBehavior optional join type to use (defaults to $joinBehavior)
     * @return ObjectCollection|{$className}[] List of $className objects
     */
    public function get".$relCol."Join".$relCol2."(Criteria \$criteria = null, ConnectionInterface \$con = null, \$joinBehavior = $joinBehavior)
    {";
                $script .= "
        \$query = $fkQueryClassName::create(null, \$criteria);
        \$query->joinWith('" . $this->getFKPhpNameAffix($fk2, false) . "', \$joinBehavior);

        return \$this->get". $relCol . "(\$query, \$con);
    }
";
            } /* end if ($doJoinGet) */

        } /* end foreach ($tblFK->getForeignKeys() as $fk2) { */

    }

public function setModel($model, $foreignKey, $foreignKeyIds)
    {
        $this->model = $model;
        $this->foreignKey = $foreignKey;
        $this->foreignKeyIds = array_wrap($foreignKeyIds);

        $this->message = "Integrity constraint violation [{$model}] where $foreignKey in (".implode(', ', $foreignKeyIds).')';

        return $this;
    }

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


Question:
scan file from namespaces
return all files list
example [file1,file2,file3]
@throws AnnotationException
@return void

public function scanNamespacesFiles() {
        $psrList = ServiceFactory::getInstance(AnnotationConfigServiceImpl::class)->getConfig()['scanNamespace'];
        foreach ($psrList as $nameSpace){
            $path = ServiceFactory::getInstance(AnnotationConfigServiceImpl::class)->getConfig()['appPath'] . '/' . str_replace('\\' , '/' , $nameSpace);
            if ( !is_dir($path)) throw new AnnotationException('dir not found' . $path);
            $tempFileList = $this->scanFile($path);
            // parse file and writing
            foreach ($tempFileList as $file){
                // compress , encode file and  build file
                if ( strpos($file , self::FILE_SUF ) === false) continue;
                $outPutArr = $this->encodeFile($file);
                !empty($outPutArr['output']) && $this->write($this->compress($outPutArr));
            }
        }
    }

def process_file_object(file_obj, importer, progress):
    """"""

    logging.info("Processing schedule data.")

    try:
        handler = XmlCallbacks(importer, progress)
        parser = sax.make_parser()
        parser.setContentHandler(handler)
        parser.setErrorHandler(handler)
        parser.parse(file_obj)
    except:
        logging.exception("Parse failed.")
        raise

    logging.info("Schedule data processed.")

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


Question:
Send digits in this call

@param $digits
@param null $leg

public function dtmf($digits, $leg = null)
    {
        $this->proxyToInterface()->dtmf(
            $this->id, $digits, $leg);
    }

def parse_command_line
      begin
        opts = GetoptLong.new(
          [ '--tag', '-t', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--tag-use-and', '-a', GetoptLong::NO_ARGUMENT ],
          [ '--tag-use-or', '-o', GetoptLong::NO_ARGUMENT ],
          [ '--array', '-r', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--deployment', '-e', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--script', '-s', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--ssh', '-x', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--input', '-i', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--set-template', '-m', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--set-tag', '-w', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--report', '-b', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--progress', '-p', GetoptLong::NO_ARGUMENT ],
          [ '--verbose', '-v', GetoptLong::NO_ARGUMENT ],
          [ '--quiet', '-q', GetoptLong::NO_ARGUMENT ],
          [ '--noprompt', '-z', GetoptLong::NO_ARGUMENT ],
          [ '--concurrency', '-c', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--delay', '-d', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--retry', '-y', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--hold', '-7', GetoptLong::NO_ARGUMENT ],
          [ '--dry-run', '-n', GetoptLong::NO_ARGUMENT ],
          [ '--limit', '-l', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--version', '-1', GetoptLong::NO_ARGUMENT ],
          [ '--chimpd', '-f', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--chimpd-wait-until-done', '-j', GetoptLong::NO_ARGUMENT ],
          [ '--dont-check-templates', '-0', GetoptLong::NO_ARGUMENT ],
          [ '--ignore-errors', '-9', GetoptLong::NO_ARGUMENT ],
          [ '--ssh-user', '-u', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
          [ '--group', '-g', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--group-type', '-2', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--group-concurrency', '-3', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--timing-log', '-4', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--timeout', '-5',  GetoptLong::REQUIRED_ARGUMENT ],
          [ '--noverify', '-6', GetoptLong::NO_ARGUMENT ],
          [ '--exact-matching', '-8', GetoptLong::NO_ARGUMENT ],
          [ '--job-notes', '-k', GetoptLong::OPTIONAL_ARGUMENT ]
        )

        opts.each do |opt, arg|
          case opt
            when '--help', '-h'
              help
              exit 0
            when '--tag', '-t'
              @tags << arg
            when '--tag-use-and', '-a'
              @match_all = true
            when '--tag-use-or', '-o'
              @match_all = false
            when '--array', '-a'
              @array_names << arg
            when '--deployment', '-e'
              @deployment_names << arg
            when '--template', '-m'
              @template = arg
            when '--script', '-s'
              set_action(:action_rightscript)
              if arg == ""
                # Empty but not nil means show list of operational scripts to choose from
                @script = ""
              else
                @script = arg
              end
            when '--ssh', '-x'
              set_action(:action_ssh)
              @break_array_into_instances = true
              if arg == ""
                print "Enter SSH command line to execute: "
                @ssh = gets.chomp
              else
                @ssh = arg
              end
            when '--ssh-user', '-u'
              @ssh_user = arg
            when '--input', '-i'
              arg =~ /(.+)=(.+)/
              @inputs[$1]=$2
            when '--set-template', '-m'
              set_action(:action_set)
              @template = arg
            when '--set-tag', '-w'
              set_action(:action_set)
              @set_tags << arg
            when '--report', '-b'
              set_action(:action_report)
              @report = arg
              @@verbose = false
              @@quiet = true
              @break_array_into_instances = true
              @concurrency = 5 if @concurrency == 1
            when '--progress', '-p'
              @progress = @progress ? false : true
            when '--noprompt', '-z'
              @prompt = false
            when '--concurrency', '-c'
              @concurrency = arg.to_i
            when '--delay', '-d'
              @delay = arg.to_i
            when '--hold', '-7'
              @hold = true
            when '--retry', '-y'
              @retry_count = arg.to_i
            when '--limit', '-l'
              @limit_start, @limit_end = arg.split(',')
            when '--verbose', '-v'
              @@verbose = true
              Log.threshold = Logger::DEBUG
            when '--quiet', '-q'
              @@quiet = true
            when '--dont-check-templates', '-0'
              @dont_check_templates_for_script = true
            when '--version'
              puts VERSION
              exit 0
            when '--chimpd'
              @use_chimpd = true
              unless arg.empty?
                if arg =~ /[\d]+\.[\d]+\.[\d]+\.[\d]+:[\d]+/
                  @chimpd_host, @chimpd_port = arg.split(':')
                  @chimpd_port = @chimpd_port.to_i
                else
                  @chimpd_port = arg.to_i
                end
              end
            when '--chimpd-wait-until-done'
              @use_chimpd = true
              @chimpd_wait_until_done = true
            when '--dry-run', '-n'
              @dry_run = true
            when '--ignore-errors', '-9'
              @ignore_errors = true
            when '--group', '-g'
              @group = arg.to_sym
            when '--group-type'
              @group_type = arg.to_sym
            when '--group-concurrency'
              @group_concurrency = arg.to_i
            when '--job-notes'
              @job_notes = arg
            when '--timing-log'
              @timing_log = arg
            when '--timeout'
              @timeout = arg
            when '--noverify'
              @verify = false
            when '--exact-matching'
              @exact = true
          end
        end

        if @use_chimpd && ( @script.nil? || @script.empty? )
          if @chimpd_wait_until_done == false
            puts "#######################################################"
            puts "ERROR: --script cannot be empty when sending to chimpd"
            puts "#######################################################"
            exit 1
          end
        end

      rescue GetoptLong::InvalidOption => ex
        help
        exit 1
      end

      #
      # Before we're totally done parsing command line options,
      # let's make sure that a few things make sense
      #
      if @group_concurrency > @concurrency
        @concurrency = @group_concurrency
      end
    end

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


Question:
Gets the row schema for this model.

@return Schema Returns a schema.

final public function getSchema() {
        if ($this->schema === null) {
            $this->schema = $this->fetchSchema();
        }
        return $this->schema;
    }

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

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

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

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

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

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

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

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

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

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


Question:
Up vote a +voteable+.
 Raises an AlreadyVotedError if the voter already up voted the voteable.
 Changes a down vote to an up vote if the the voter already down voted the voteable.

def up_vote(voteable)
      check_voteable(voteable)

      voting = fetch_voting(voteable)

      if voting
        if voting.up_vote
          raise Exceptions::AlreadyVotedError.new(true)
        else
          voting.up_vote = true
          voteable.down_votes -= 1
          self.down_votes -= 1 if has_attribute?(:down_votes)
        end
      else
        voting = Voting.create(:voteable => voteable, :voter_id => self.id, :voter_type => self.class.to_s, :up_vote => true)
      end

      voteable.up_votes += 1
      self.up_votes += 1 if has_attribute?(:up_votes)

      Voting.transaction do
        save
        voteable.save
        voting.save
      end

      true
    end

func (b *BottleController) Update(ctx *app.UpdateBottleContext) error {
	bottle, ok := b.db.GetBottle(ctx.AccountID, ctx.BottleID)
	if !ok {
		return ctx.NotFound()
	}
	payload := ctx.Payload
	if payload.Name != nil {
		bottle.Name = *payload.Name
	}
	if payload.Vintage != nil {
		bottle.Vintage = *payload.Vintage
	}
	if payload.Vineyard != nil {
		bottle.Vineyard = *payload.Vineyard
	}
	if payload.Varietal != nil {
		bottle.Varietal = *payload.Varietal
	}
	if payload.Color != nil {
		bottle.Color = *payload.Color
	}
	if payload.Sweetness != nil {
		bottle.Sweetness = payload.Sweetness
	}
	if payload.Country != nil {
		bottle.Country = payload.Country
	}
	if payload.Region != nil {
		bottle.Region = payload.Region
	}
	if payload.Review != nil {
		bottle.Review = payload.Review
	}
	bottle.UpdatedAt = time.Now()

	b.db.SaveBottle(bottle)
	return ctx.NoContent()
}

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


Question:
@param $targetEntityType

@throws \InvalidArgumentException

@return $this

public function setTargetEntityType($targetEntityType)
    {
        if (!$this->supportsTargetEntity()) {
            throw new \InvalidArgumentException(sprintf('Event of type `%s` does not support setting a target entity',
                    $this->getEventType()
                )
            );
        }
        $this->targetEntityType = $targetEntityType;

        return $this;
    }

public function buildInsertQuery($entity) {

        $mapper = MapperBuilder::buildFromMapping($this->mapping, get_class($entity));
        $fields = "";
        $values = "";
        foreach ($mapper->getPropertys() as $property) {
            if ($property->getColumn() != "id") {
                $method = "get" . $property->getName();
                $entity->$method();
                $fields .= "`" . $property->getColumn() . "`, ";
                $values .= "'" . $entity->$method() . "', ";
            }
        }

        $fields = substr_replace($fields, "", -2);
        $values = substr_replace($values, "", -2);

        $query = "INSERT INTO `" . $mapper->getTable() . "` (" . $fields . ") VALUES (" . $values . ");";

        return $query;
    }

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


Question: Add a single-valued attribute.

public void addAttribute(String name, String value) {
        checkType(name, String.class);
        attributes.put(name, value);
    }

public static String getAttributeString(Tag tag, String attrName, String defaultValue) {
	Literal lit = getAttributeLiteral(tag, attrName, null);
	if (lit == null) return defaultValue;
	return lit.getString();
    }

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


public void init(Database database, String host, String port) throws DevFailed {
        super.init(database, host, port);
    }

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

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

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

    end

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


Question:
Reindexes an item from an old key to a new key. If there was no such
item, does nothing. Returns 0 if successful, else -1.

def rename(self, old_key, new_key):

        return lib.zhashx_rename(self._as_parameter_, old_key, new_key)

function setColumn($index, $params)
	{
		if (isset($this->columns[$index])) $this->columns[$index] = array_merge($this->columns[$index], $params);
		else $this->columns[$index] = $params;
	}

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


Question:
v(im)
    switch to debugging with vimpdb

def do_vim(self, arg):
        """"""
        self.vimpdb = make_instance()
        self.vimpdb.set_trace_without_step(self.botframe)
        if self.has_gone_up():
            self.vimpdb.update_state(self)
            self.vimpdb.cmdloop()
        else:
            self.vimpdb.interaction(self.curframe, None)
        return 1

def verbose(self):

        enabled = self.lib.iperf_get_verbose(self._test)

        if enabled:
            self._verbose = True
        else:
            self._verbose = False

        return self._verbose

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


Question:
/*
(non-Javadoc)

@see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)

public void contextInitialized(ServletContextEvent servletContextEvent) {
		ServletContext servletContext = servletContextEvent.getServletContext();

		File tempWriteDir = (File) servletContext
				.getAttribute("javax.servlet.context.tempdir");
		servletContext.setAttribute("audioFilePath", FILE_PROTOCOL + tempWriteDir
				.getAbsolutePath() + File.separatorChar);
		// map acting as a registrar
		servletContext.setAttribute("registeredUsersMap", new HashMap<String, String>());
	}

public static EventLoopGroup getServerIoEventLoopGroup(ServerTransportConfig config) {
        String type = config.getProtocolType();
        EventLoopGroup ioGroup = serverIoGroups.get(type);
        if (ioGroup == null) {
            synchronized (NettyHelper.class) {
                ioGroup = serverIoGroups.get(config.getProtocolType());
                if (ioGroup == null) {
                    int ioThreads = config.getIoThreads();
                    ioThreads = ioThreads <= 0 ? Math.max(8, SystemInfo.getCpuCores() + 1) : ioThreads;
                    NamedThreadFactory threadName =
                            new NamedThreadFactory("SEV-IO-" + config.getPort(), config.isDaemon());
                    ioGroup = config.isUseEpoll() ?
                        new EpollEventLoopGroup(ioThreads, threadName) :
                        new NioEventLoopGroup(ioThreads, threadName);
                    serverIoGroups.put(type, ioGroup);
                    refCounter.putIfAbsent(ioGroup, new AtomicInteger(0));
                }
            }
        }
        refCounter.get(ioGroup).incrementAndGet();
        return ioGroup;
    }

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


Question:
// WatchActionNotifications returns a StringsWatcher for observing the
// ids of Actions added to the Unit. The initial event will contain the
// ids of any Actions pending at the time the Watcher is made.

func (u *Unit) WatchActionNotifications() (watcher.StringsWatcher, error) {
	var results params.StringsWatchResults
	args := params.Entities{
		Entities: []params.Entity{{Tag: u.tag.String()}},
	}
	err := u.st.facade.FacadeCall("WatchActionNotifications", args, &results)
	if err != nil {
		return nil, err
	}
	if len(results.Results) != 1 {
		return nil, errors.Errorf("expected 1 result, got %d", len(results.Results))
	}
	result := results.Results[0]
	if result.Error != nil {
		return nil, result.Error
	}
	w := apiwatcher.NewStringsWatcher(u.st.facade.RawAPICaller(), result)
	return w, nil
}

def _notify_listeners(self, sender, message):

        uid = message['uid']
        msg_topic = message['topic']

        self._ack(sender, uid, 'fire')

        all_listeners = set()
        for lst_topic, listeners in self.__listeners.items():
            if fnmatch.fnmatch(msg_topic, lst_topic):
                all_listeners.update(listeners)

        self._ack(sender, uid, 'notice', 'ok' if all_listeners else 'none')

        try:
            results = []
            for listener in all_listeners:
                result = listener.handle_message(sender,
                                                 message['topic'],
                                                 message['content'])
                if result:
                    results.append(result)

            self._ack(sender, uid, 'send', json.dumps(results))
        except:
            self._ack(sender, uid, 'send', "Error")

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


Question: Get the stage that is the first necessary stage

public function getCurrentStage(string $name): StageInterface
    {
        // compute the stageClass from Request parameter
        $stageClass = $this->getStageClassName($name);

        // loop each stage until finds the first that is necessary

        do {
            $useCurrentStage = false;
            /** @var StageInterface $currentStage */
            if (!isset($currentStage)) {
                $currentStage = $this->getStageInstance($stageClass);
            }
            $this->currentStageName = $currentStage->getName();
            try {
                $isNecessary = $currentStage->isNecessary();
            } catch (AbortStageException $e) {
                $this->warning = $e->getMessage();
                $isNecessary = true;
            }
            if ($isNecessary) {
                $useCurrentStage = true;
            } else {
                $currentStage = $this->getNextStage();
            }
        } while (false === $useCurrentStage);

        return $currentStage;
    }

def create_main_target (self, name):

        assert isinstance(name, basestring)
        if not self.built_main_targets_:
            self.build_main_targets ()

        return self.main_targets_.get (name, None)

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


Question: Return a MATCH (SQL) string representing the given argument value.

def _safe_match_argument(expected_type, argument_value):
    """"""
    if GraphQLString.is_same_type(expected_type):
        return _safe_match_string(argument_value)
    elif GraphQLID.is_same_type(expected_type):
        # IDs can be strings or numbers, but the GraphQL library coerces them to strings.
        # We will follow suit and treat them as strings.
        if not isinstance(argument_value, six.string_types):
            if isinstance(argument_value, bytes):  # should only happen in py3
                argument_value = argument_value.decode('utf-8')
            else:
                argument_value = six.text_type(argument_value)
        return _safe_match_string(argument_value)
    elif GraphQLFloat.is_same_type(expected_type):
        return represent_float_as_str(argument_value)
    elif GraphQLInt.is_same_type(expected_type):
        # Special case: in Python, isinstance(True, int) returns True.
        # Safeguard against this with an explicit check against bool type.
        if isinstance(argument_value, bool):
            raise GraphQLInvalidArgumentError(u'Attempting to represent a non-int as an int: '
                                              u'{}'.format(argument_value))
        return type_check_and_str(int, argument_value)
    elif GraphQLBoolean.is_same_type(expected_type):
        return type_check_and_str(bool, argument_value)
    elif GraphQLDecimal.is_same_type(expected_type):
        return _safe_match_decimal(argument_value)
    elif GraphQLDate.is_same_type(expected_type):
        return _safe_match_date_and_datetime(expected_type, (datetime.date,), argument_value)
    elif GraphQLDateTime.is_same_type(expected_type):
        return _safe_match_date_and_datetime(expected_type,
                                             (datetime.datetime, arrow.Arrow), argument_value)
    elif isinstance(expected_type, GraphQLList):
        return _safe_match_list(expected_type.of_type, argument_value)
    else:
        raise AssertionError(u'Could not safely represent the requested GraphQL type: '
                             u'{} {}'.format(expected_type, argument_value))

def dump_mismatch_diffs(field)
      mismatch_diffs = diffs_by_field_type(field, TYPE_MISMATCH)

      if mismatch_diffs.length > 0
        header = "Table #{@table_name} has mismatched #{field}:\n"
        diff_str = mismatch_diffs.map do |diff|
          "actual:    #{dump_single(field, diff[:db_generator], diff[:db_elem])}\n\t" +
          "expected:  #{dump_single(field, diff[:exp_generator], diff[:exp_elem])}"
        end.join("\n\n\t")

        "#{header}\n\t#{diff_str}\n"
      end
    end

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


Question:
Detect source type.

@param element the element
@param adapterClazz the adapter clazz
@return the string

public static String detectSourceType(Element element, String adapterClazz) {
		TypeElement a = BaseProcessor.elementUtils.getTypeElement(adapterClazz);
		for (Element i : BaseProcessor.elementUtils.getAllMembers(a)) {
			if (i.getKind() == ElementKind.METHOD && "toJava".equals(i.getSimpleName().toString())) {
				ExecutableElement method = (ExecutableElement) i;
				return TypeUtility.typeName(method.getReturnType()).toString();
			}
		}

		AssertKripton.fail("In '%s', class '%s' can not be used as type adapter", element, adapterClazz);
		return null;
	}

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:
Format a value so that it can be used in "default" clauses.

@param  mixed   $value
@return string

protected function getDefaultValue($value)
	{
		if ($value instanceof Expression) return $value;

		if (is_bool($value)) return "'".intval($value)."'";

		return "'".strval($value)."'";
	}

public Object getDefaultValue(Parameter parameter) {
    Class<?> type = parameter.getType();

    if (TypeUtils.isaString(type)) {
      return getStringDefaultValue(parameter);
    }

    if (TypeUtils.isaByte(type)) {
      return getByteDefaultValue(parameter);
    }

    if (TypeUtils.isaShort(type)) {
      return getShortDefaultValue(parameter);
    }

    if (TypeUtils.isaInteger(type)) {
      return getIntegerDefaultValue(parameter);
    }

    if (TypeUtils.isaLong(type)) {
      return getLongDefaultValue(parameter);
    }

    if (TypeUtils.isaFloat(type)) {
      return getFloatDefaultValue(parameter);
    }

    if (TypeUtils.isaDouble(type)) {
      return getDoubleDefaultValue(parameter);
    }

    if (TypeUtils.isaCharacter(type)) {
      return getCharacterDefaultValue(parameter);
    }

    if (TypeUtils.isaBoolean(type)) {
      return getBooleanDefaultValue(parameter);
    }

    return null;
  }

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


Question:
Sets the TimeInterpolator for all current {@link #getChildAnimations() child animations}
of this AnimatorSet.

@param interpolator the interpolator to be used by each child animation of this AnimatorSet

@Override
    public void setInterpolator(/*Time*/Interpolator interpolator) {
        for (Node node : mNodes) {
            node.animation.setInterpolator(interpolator);
        }
    }

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:
From some file path, input stream, or URL, construct and return
    an HTML tree.

def get_html_tree(filename_url_or_filelike):

    try:
        handler = (
            HTTPSHandler
                if filename_url_or_filelike.lower().startswith('https')
                else HTTPHandler
        )
        cj = CookieJar()
        opener = build_opener(handler)
        opener.add_handler(HTTPCookieProcessor(cj))

        resp = opener.open(filename_url_or_filelike)
    except(AttributeError):
        content = filename_url_or_filelike.read()
        encoding = chardet.detect(content)['encoding']

        parsed_html = html.parse(BytesIO(content),
                                 html.HTMLParser(encoding=encoding,
                                                 remove_blank_text=True))

        return parsed_html
    except(ValueError):
        content = filename_url_or_filelike
        encoding = chardet.detect(content)['encoding']

        parsed_html = html.parse(BytesIO(content),
                                 html.HTMLParser(encoding=encoding,
                                                 remove_blank_text=True))

        return parsed_html

    try:
        content = resp.read()
    finally:
        resp.close()

    encoding = chardet.detect(content)['encoding']

    parsed_html = html.parse(BytesIO(content),
                             html.HTMLParser(encoding=encoding,
                                             remove_blank_text=True))

    return parsed_html

public void showDialog(boolean showRoot, String panel) {
        expandRoot();

        try {
            DefaultMutableTreeNode node = null;
            if (panel != null) {
                node = getTreeNodeFromPanelName(panel);
            }

            if (node == null) {
                if (nameLastSelectedPanel != null) {
                    node = getTreeNodeFromPanelName(nameLastSelectedPanel);

                } else if (showRoot) {
                    node = (DefaultMutableTreeNode) getTreeModel().getRoot();

                } else if (((DefaultMutableTreeNode) getTreeModel().getRoot()).getChildCount() > 0) {
                    node = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) getTreeModel().getRoot()).getChildAt(0);
                }
            }

            if (node != null) {
                showParamPanel(node.toString());
            }

        } catch (Exception e) {
            // ZAP: log errors
            log.error(e.getMessage(), e);
        }
    }

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


Question:
<p>
onDouble.
</p>

@param floating
a {@link java.lang.Double} object.
@param fieldName
a {@link java.lang.String} object.
@param jp
a {@link org.codehaus.jackson.JsonParser} object.

protected void onDouble(Double floating, String fieldName, JsonParser jp) {
		log.trace(fieldName + " " + floating);
	}

public Value get(String name) {
        if (name.length() > 1) {
            int dot;
            if (name.charAt(0) == LPAREN) {
                int start = name.indexOf(RPAREN);
                dot = name.indexOf(DOT, start);
            } else {
                dot = name.indexOf(DOT);
            }
            if (dot > 0) {
                String fieldName = name.substring(0, dot);
                String rest = name.substring(dot + 1);
                Key key = createKey(fieldName);
                Value value = fields.get(key);
                if (!value.isMessageType()) {
                    throw new ParserException("Invalid option name: %s", name);
                }
                DynamicMessage msg = value.getMessage();
                return msg.get(rest);
            } else {
                Key key = createKey(name);
                return fields.get(key);
            }
        } else {
            Key key = Key.field(name);
            return fields.get(key);
        }
    }

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


Question:
设置角度
@memberOf PhysicsViewMixin
@param {Number} rotation 单位角度制

function(rotation){
            this.body.setAngle(rotation * DEG2RAD);
            if(this.body.isStaticBody){
                this.space.needReindexStatic = true;
            }
        }

def serialize(self):
        """"""
        if self.mate_chrom is None:
            remote_tag = "."
        else:
            if self.within_main_assembly:
                mate_chrom = self.mate_chrom
            else:
                mate_chrom = "<{}>".format(self.mate_chrom)
            tpl = {FORWARD: "[{}:{}[", REVERSE: "]{}:{}]"}[self.mate_orientation]
            remote_tag = tpl.format(mate_chrom, self.mate_pos)
        if self.orientation == FORWARD:
            return remote_tag + self.sequence
        else:
            return self.sequence + remote_tag

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


Question:
Previously this printed a chunk as a full line, I've modified it to print on
  one line. This can be used for running text.
  NOTE 2013-03-08 - 17:02 added width so we don't overflow
  NOTE 2014-05-11 - textpad has its own version, so does not call this.

def show_colored_chunks(chunks, defcolor = nil, defattr = nil, wid = 999, pcol = 0)
      return unless visible?
      ww = 0
      chunks.each_with_color do |text, color, attrib|

        ## 2013-03-08 - 19:11 take care of scrolling by means of pcol
        if pcol > 0
          if pcol > text.length
            # ignore entire chunk and reduce pcol
            pcol -= text.length
            next
          else
            # print portion of chunk and zero pcol
            text = text[pcol..-1]
            pcol = 0
          end
        end
        oldw = ww
        ww += text.length
        if ww > wid
          # if we are exceeding the width then by howmuch
          rem = wid - oldw
          if rem > 0
            # take only as much as we are allowed
            text = text[0,rem]
          else
            break
          end
        end

        color ||= defcolor
        attrib ||= defattr

        cc, bg = ColorMap.get_colors_for_pair color
        #$log.debug "XXX: CHUNK window #{text}, cp #{color} ,  attrib #{attrib}. #{cc}, #{bg} "
        color_set(color,nil) if color
        wattron(attrib) if attrib
        #print(text)
        waddnstr(text.to_s, @width) # changed 2014-04-22 - 11:59  to reduce a function
        wattroff(attrib) if attrib
      end
    end

def split(self, N, force=False):

        mode = self.mode
        assert mode in ("batch", "cycle", "optimal")
        logging.debug("set split mode=%s" % mode)

        self.names = self.__class__.get_names(self.filename, N)
        if self.outputdir:
            self.names = [op.join(self.outputdir, x) for x in self.names]

        if not need_update(self.filename, self.names) and not force:
            logging.error("file %s already existed, skip file splitting" % \
                    self.names[0])
            return

        filehandles = [open(x, "w") for x in self.names]

        if mode == "batch":
            for batch, fw in zip(self._batch_iterator(N), filehandles):
                count = self.write(fw, batch)
                logging.debug("write %d records to %s" % (count, fw.name))

        elif mode == "cycle":
            handle = self._open(self.filename)
            for record, fw in zip(handle, cycle(filehandles)):
                count = self.write(fw, [record])

        elif mode == "optimal":
            """
            This mode is based on Longest Processing Time (LPT) algorithm:

            A simple, often-used algorithm is the LPT algorithm (Longest
            Processing Time) which sorts the jobs by its processing time and
            then assigns them to the machine with the earliest end time so far.
            This algorithm achieves an upper bound of 4/3 - 1/(3m) OPT.

            Citation: <http://en.wikipedia.org/wiki/Multiprocessor_scheduling>
            """
            endtime = [0] * N
            handle = self._open(self.filename)
            for record in handle:
                mt, mi = min((x, i) for (i, x) in enumerate(endtime))
                fw = filehandles[mi]
                count = self.write(fw, [record])
                endtime[mi] += len(record)

        for fw in filehandles:
            fw.close()

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


Question:
// GetUint64Default returns the entry's value as uint64, based on its key.
// If not found returns "def".

func (r *Store) GetUint64Default(key string, def uint64) uint64 {
	if v, err := r.GetUint64(key); err == nil {
		return v
	}

	return def
}

func (p Packet) ValueNames() []string {
	r := make([]string, len(p.DataTypes))
	for i := range p.DataTypes {
		name := p.Name()
		var valueName string
		switch {
		case p.Plugin == "df" && i == 0:
			valueName = ""
		case p.Plugin == "memory" && i == 0:
			valueName = ""
		case p.Plugin == "interface" && i == 0:
			valueName = "tx"
		case p.Plugin == "interface" && i == 1:
			valueName = "rx"
		case p.Plugin == "load" && i == 0:
			valueName = "1"
		case p.Plugin == "load" && i == 1:
			valueName = "5"
		case p.Plugin == "load" && i == 2:
			valueName = "15"
		default:
			valueName = strconv.FormatInt(int64(i), 10)
		}
		if valueName == "" {
			r[i] = name
		} else {
			r[i] = fmt.Sprintf("%s_%s", name, valueName)
		}
	}
	return r
}

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


Question:
Check to see if a pool exists

    CLI Examples:

    .. code-block:: bash

        salt-run f5.check_pool load_balancer pool_name

def check_pool(lb, name):
    '''

    '''
    if __opts__['load_balancers'].get(lb, None):
        (username, password) = list(__opts__['load_balancers'][lb].values())
    else:
        raise Exception('Unable to find `{0}` load balancer'.format(lb))
    F5 = F5Mgmt(lb, username, password)
    return F5.check_pool(name)

public static PowerShellResponse executeSingleCommand(String command) {
        PowerShellResponse response = null;

        try (PowerShell session = PowerShell.openSession()) {
            response = session.executeCommand(command);
        } catch (PowerShellNotAvailableException ex) {
            logger.log(Level.SEVERE, "PowerShell not available", ex);
        }

        return response;
    }

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


Question:
// NewRequestFailure returns a new request error wrapper for the given Error
// provided.

func NewRequestFailure(err Error, statusCode int, reqID string) RequestFailure {
	return newRequestError(err, statusCode, reqID)
}

func (r *Router) NotFound(mc MiddlewareChain, h Handler) {
	handle := r.adapt(mc, h, "")
	r.hrouter.NotFound = http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		handle(rw, req, nil)
	})
}

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


Question:
gc
可全量gc或某个会话
@param int $maxLifeTime
@param string $sessionId
@return mixed

public function gc(int $maxLifeTime, string $sessionId = '')
    {
        if ($sessionId) {
            $file = "{$this->savePath}/{$this->sessionName}_{$sessionId}";
            if (file_exists($file) && (filemtime($file) + $maxLifeTime < time())) {
                unlink($file);
            }
            return true;
        }

        foreach (glob("{$this->savePath}/{$this->sessionName}_*") as $file) {
            if (file_exists($file) && (filemtime($file) + $maxLifeTime < time())) {
                unlink($file);
            }
        }

        return true;
    }

func (user *User) Add(message newMessage) error {
	switch message.(type) {
	case *UserPost:
		post := message.(*UserPost)
		if post.To == 0 {
			post.To = user.ID()
		}
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *ProjectPost:
		post := message.(*ProjectPost)
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *UserPostComment:
		comment := message.(*UserPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *ProjectPostComment:
		comment := message.(*ProjectPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *Pm:
		pm := message.(*Pm)
		if err := createMessage(pm, user.ID(), pm.To, pm.Text(), pm.Language()); err != nil {
			return err
		}
		return Db().Create(pm)
	}

	return fmt.Errorf("Invalid parameter type: %s", reflect.TypeOf(message))
}

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


Question:
@param SecurityToken $assertToken

@return string

protected function generateAssertTokenRequest( $assertToken ) {
        $credentials = $this->getTokenCredentials( 'sts' );

        $loginSoapRequest = new DOMDocument();
        $loginEnvelope    = $loginSoapRequest->appendChild( $loginSoapRequest->createElementNS( 'http://www.w3.org/2003/05/soap-envelope', 's:Envelope' ) );
        $loginEnvelope->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:a', 'http://www.w3.org/2005/08/addressing' );
        $loginEnvelope->setAttributeNS( 'http://www.w3.org/2000/xmlns/', 'xmlns:u', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd' );
        $loginHeader = $loginEnvelope->appendChild( $loginSoapRequest->createElement( 's:Header' ) );
        $loginHeader->appendChild( $loginSoapRequest->createElement( 'a:Action', 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue' ) )->setAttribute( 's:mustUnderstand', "1" );
        $loginHeader->appendChild( $loginSoapRequest->createElement( 'a:MessageId', 'urn:uuid:' . Client::getUuid() ) );
        $loginHeader->appendChild( $loginSoapRequest->createElement( 'a:ReplyTo' ) )->appendChild( $loginSoapRequest->createElement( 'a:Address', 'http://www.w3.org/2005/08/addressing/anonymous' ) );
        $loginHeader->appendChild( $loginSoapRequest->createElement( 'a:To', $credentials['server'] ) )->setAttribute( 's:mustUnderstand', "1" );
        $loginSecurity = $loginHeader->appendChild( $loginSoapRequest->createElementNS( 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd', 'o:Security' ) );
        $loginSecurity->setAttribute( 's:mustUnderstand', "1" );
        $loginTimestamp = $loginSecurity->appendChild( $loginSoapRequest->createElement( 'u:Timestamp' ) );
        $loginTimestamp->setAttribute( 'u:Id', '_0' );
        $loginTimestamp->appendChild( $loginSoapRequest->createElement( 'u:Created', Client::getCurrentTime() . 'Z' ) );
        $loginTimestamp->appendChild( $loginSoapRequest->createElement( 'u:Expires', Client::getExpiryTime() . 'Z' ) );

        $assert = $loginSoapRequest->createDocumentFragment();
        $assert->appendXML( $assertToken->securityToken );
        $loginSecurity->appendChild( $assert );

        $loginBody              = $loginEnvelope->appendChild( $loginSoapRequest->createElementNS( 'http://www.w3.org/2003/05/soap-envelope', 's:Body' ) );
        $loginRST               = $loginBody->appendChild( $loginSoapRequest->createElementNS( 'http://schemas.xmlsoap.org/ws/2005/02/trust', 't:RequestSecurityToken' ) );
        $loginAppliesTo         = $loginRST->appendChild( $loginSoapRequest->createElementNS( 'http://schemas.xmlsoap.org/ws/2004/09/policy', 'wsp:AppliesTo' ) );
        $loginEndpointReference = $loginAppliesTo->appendChild( $loginSoapRequest->createElement( 'a:EndpointReference' ) );
        $loginEndpointReference->appendChild( $loginSoapRequest->createElement( 'a:Address', "urn:" . $credentials['endpoint'] ) );
        $loginRST->appendChild( $loginSoapRequest->createElement( 't:RequestType', 'http://schemas.xmlsoap.org/ws/2005/02/trust/Issue' ) );

        return $loginSoapRequest->saveXML( $loginEnvelope );
    }

def get_token(self):
        """"""
        signed_headers = self._get_v4_signed_headers()
        for header in self.HEADERS:
            signed_headers[header] = self.HEADERS[header]

        resp = post_with_retry(self.cerberus_url + '/v2/auth/sts-identity', headers=signed_headers)
        throw_if_bad_response(resp)

        token = resp.json()['client_token']
        iam_principal_arn = resp.json()['metadata']['aws_iam_principal_arn']
        if self.verbose:
            print('Successfully authenticated with Cerberus as {}'.format(iam_principal_arn), file=sys.stderr)
        logger.info('Successfully authenticated with Cerberus as {}'.format(iam_principal_arn))

        return token

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


Question:
// Xor computes `a XOR b`, as defined by RFC 4493. dst, a, and b must all have
// the same length.

func Xor(dst []byte, a []byte, b []byte) {
	// TODO(jacobsa): Consider making this a helper function with known sizes
	// where it is most hot, then even trying to inline it entirely.

	if len(dst) != len(a) || len(a) != len(b) {
		log.Panicf("Bad buffer lengths: %d, %d, %d", len(dst), len(a), len(b))
	}

	for i, _ := range a {
		dst[i] = a[i] ^ b[i]
	}
}

def zip(what, archive_zip='', risk_file=''):

    if os.path.isdir(what):
        oqzip.zip_all(what)
    elif what.endswith('.xml') and '<logicTree' in open(what).read(512):
        # hack to see if the NRML file is of kind logicTree
        oqzip.zip_source_model(what, archive_zip)
    elif what.endswith('.xml') and '<exposureModel' in open(what).read(512):
        # hack to see if the NRML file is of kind exposureModel
        oqzip.zip_exposure(what, archive_zip)
    elif what.endswith('.ini'):  # a job.ini
        oqzip.zip_job(what, archive_zip, risk_file)
    else:
        sys.exit('Cannot zip %s' % what)

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


Question: /* eslint no-param-reassign: 0

function convertInterpolation(options) {

  options.interpolation = {
    unescapeSuffix: 'HTML'
  };

  options.interpolation.prefix = options.interpolationPrefix || '__';
  options.interpolation.suffix = options.interpolationSuffix || '__';
  options.interpolation.escapeValue = options.escapeInterpolation || false;

  options.interpolation.nestingPrefix = options.reusePrefix || '$t(';
  options.interpolation.nestingSuffix = options.reuseSuffix || ')';

  return options;
}

func (p *Parameters) Normalize() (err error) {
	if err = p.Scheduling.Normalize(); err != nil {
		return
	}
	if err = p.Meta.Normalize(); err != nil {
		return
	}
	if err = p.Job.Normalize(); err != nil {
		return
	}
	return
}

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


Question: List active mounts on Mac OS systems

def _active_mounts_darwin(ret):
    '''

    '''
    for line in __salt__['cmd.run_stdout']('mount').split('\n'):
        comps = re.sub(r"\s+", " ", line).split()
        parens = re.findall(r'\((.*?)\)', line, re.DOTALL)[0].split(", ")
        ret[comps[2]] = {'device': comps[0],
                         'fstype': parens[0],
                         'opts': _resolve_user_group_names(parens[1:])}
    return ret

def absolute_info_plist_paths
      info_plist_paths.map do |path|
        absolute_project_file_path(path)
      end.select do |path|
        if path.to_s.include?('$')
          warn "Couldn't resolve all placeholders in INFOPLIST_FILE %s.", path.to_s
          false
        else
          true
        end
      end
    end

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


Question: // Collect implements Collector.

func (c *ScribeCollector) Collect(s *zipkincore.Span) error {
	select {
	case c.spanc <- s:
		// Accepted.
	case <-c.quit:
		// Collector concurrently closed.
	}
	return nil
}

protected Channel getConsumerChannel() throws IOException, TimeoutException {
        if (consumerChannel == null) {
            synchronized (this) {
                if (consumerChannel == null) {
                    consumerChannel = createChannel();
                }
            }
        }
        return consumerChannel;
    }

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


Question:
Save Property Dropdown Field options

@param \AvoRed\Framework\Models\Database\Property $proerty
@param \AvoRed\Ecommerce\Http\Request\PropertyRequest $request

@return void

private function _saveDropdownOptions($property, $request)
    {
        if (null !== $request->get('dropdown-options')) {
            $property->propertyDropdownOptions()->delete();

            foreach ($request->get('dropdown-options') as $key => $val) {
                if ($key == '__RANDOM_STRING__') {
                    continue;
                }

                $property->propertyDropdownOptions()->create($val);
            }
        }
    }

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

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


Question:
Test if the data in the array is pure ASCII
@param data data to check
@return true if there are only ASCII characters

public static boolean isPureAscii(byte[] data) {
		if (data == null) {
			return false;
		}
		for (byte b : data) {
			if (b < 0x20) {
				return false;
			}
		}
		return true;
	}

def validate_credentials!
      credentials.each do |credential, value|
        next if value.nil?

        unless value.is_a?(String) || value.is_a?(::Symbol)
          raise(Error::ConfigurationError, "Invalid #{credential} specified: #{value} must be a string or symbol.")
        end
      end
    end

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


Question:
Read from a file one line at a time.

@test
@param $fileName
@param callable|null $formatter - the default is a string.
@return \Generator|string|object

private function fileLineGenerator(string $fileName, callable $formatter = null)
    {
        $f = fopen($fileName, 'r');
        try {
            while ($line = fgets($f)) {
                if(!is_null($formatter)){
                    yield call_user_func($formatter, $line);
                }
                else {
                    yield $line;
                }
            }
        } finally {
            fclose($f);
        }
    }

public static BufferedReader newBufferedReader(Path path, Charset charset) throws IOException {
        return new BufferedReader(new InputStreamReader(newInputStream(path), charset));
    }

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


Question:
Forces a redirect back to the non-published
version of a uri

@param {Number} code
@returns {Function}

function forceEditableInstance(code = 303) {
  return (req, res) => {
    res.redirect(code, `${res.locals.site.protocol}://${req.uri.replace('@published', '')}`);
  };
}

func (s *AccountTakeoverActionsType) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "AccountTakeoverActionsType"}
	if s.HighAction != nil {
		if err := s.HighAction.Validate(); err != nil {
			invalidParams.AddNested("HighAction", err.(request.ErrInvalidParams))
		}
	}
	if s.LowAction != nil {
		if err := s.LowAction.Validate(); err != nil {
			invalidParams.AddNested("LowAction", err.(request.ErrInvalidParams))
		}
	}
	if s.MediumAction != nil {
		if err := s.MediumAction.Validate(); err != nil {
			invalidParams.AddNested("MediumAction", err.(request.ErrInvalidParams))
		}
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

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


Question: // PrettyPrintGetMilesResponse prints a GetMilesResponse in readable format.

func PrettyPrintGetMilesResponse(w io.Writer, response *GetMilesResponse) error {
	for _, segment := range response.Segment {
		fmt.Fprintf(w, "%s-%s %dmi", strings.ToUpper(segment.SourceAirportId), strings.ToUpper(segment.DestinationAirportId), segment.Miles)
		if segment.Miles != segment.ActualMiles {
			fmt.Fprintf(w, " (%dmi actual)", segment.ActualMiles)
		}
		fmt.Fprintln(w)
	}
	fmt.Fprintln(w)
	fmt.Fprintf(w, "%dmi", response.TotalMiles)
	if response.TotalMiles != response.TotalActualMiles {
		fmt.Fprintf(w, " (%dmi actual)", response.TotalActualMiles)
	}
	fmt.Fprintln(w)
	return nil
}

def _pprint(params):
    """"""
    params_list = list()
    line_sep = ','
    for i, (k, v) in enumerate(sorted(params.iteritems())):
        if type(v) is float:
            # use str for representing floating point numbers
            # this way we get consistent representation across
            # architectures and versions.
            this_repr = '%s=%.10f' % (k, v)
        else:
            # use repr of the rest
            this_repr = '%s=%r' % (k, v)
        params_list.append(this_repr)

    lines = ','.join(params_list)
    return lines

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


Question:
对 input 值的自定义校验，支持调用多次

@param string|\Closure $validator
@param bool            $condition

@return $this

public function validator($validator, $condition = true)
    {
        if (!$condition) {
            return $this;
        }

        if ($validator instanceof \Closure) {
            $this->validators[] = $validator;
        } else {
            $this->rule($validator);
        }

        return $this;
    }

def is_in(property_name, set_values, *, present_optional=False, message=None):
    """"""
    def check(val):
      """Checks that a value is contained within a scope-enclosed set."""
      if val is None:
        return present_optional
      else:
        return val in set_values

    return Validation(check, property_name, message)

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


Question:
Get the target DOM element of the mouse event.

@param event
The mouse event itself.
@return Returns the DOM element or null if something went wrong.

public static Element getTarget(DomEvent<?> event) {
		EventTarget target = event.getNativeEvent().getEventTarget();
		if (Element.is(target)) {
			return Element.as(target);
		}
		return null;
	}

protected function setNode(\DOMElement $node)
    {
        $this->button = $node;
        if ('button' === $node->nodeName || ('input' === $node->nodeName && \in_array(strtolower($node->getAttribute('type')), ['submit', 'button', 'image']))) {
            if ($node->hasAttribute('form')) {
                // if the node has the HTML5-compliant 'form' attribute, use it
                $formId = $node->getAttribute('form');
                $form = $node->ownerDocument->getElementById($formId);
                if (null === $form) {
                    throw new \LogicException(sprintf('The selected node has an invalid form attribute (%s).', $formId));
                }
                $this->node = $form;

                return;
            }
            // we loop until we find a form ancestor
            do {
                if (null === $node = $node->parentNode) {
                    throw new \LogicException('The selected node does not have a form ancestor.');
                }
            } while ('form' !== $node->nodeName);
        } elseif ('form' !== $node->nodeName) {
            throw new \LogicException(sprintf('Unable to submit on a "%s" tag.', $node->nodeName));
        }

        $this->node = $node;
    }

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


Question:
Throw an InvalidArgumentException depending on a given qti:baseType
and an in-memory PHP value.

@param int $baseType A value from the BaseType enumeration.
@param mixed $value A given PHP primitive value.
@throws \InvalidArgumentException In any case.

static public function throwBaseTypeTypingError($baseType, $value)
    {
        $givenValue = (gettype($value) == 'object') ? get_class($value) : gettype($value) . ':' . $value;
        $acceptedTypes = BaseType::getNameByConstant($baseType);
        $msg = "The value '${givenValue}' is not compliant with the '${acceptedTypes}' baseType.";
        throw new InvalidArgumentException($msg);
    }

public function build(ResultSpec $result): string
    {
        $response = [];
        $units = $result->getResults();

        foreach ($units as $unit) {
            /** @var AbstractResult $unit */
            if ($unit instanceof Result) {
                /** @var Result $unit */
                $response[] = [
                    'jsonrpc' => '2.0',
                    'result' => $this->preBuild($unit->getResult()),
                    'id'     => $unit->getId()
                ];
            } elseif ($unit instanceof Error) {
                /** @var Error $unit */
                $baseException = $unit->getBaseException();
                $response[] = [
                    'jsonrpc' => '2.0',
                    'error' => [
                        'code'    => $baseException->getJsonRpcCode(),
                        'message' => $this->getErrorMessage($baseException->getJsonRpcCode()),
                        'data'    => $baseException->getJsonRpcData()
                    ],
                    'id' => $unit->getId()
                ];
            }
        }

        if (empty($response)) {
            return '';
        }

        if ($result->isSingleResult()) {
            return json_encode($response[0]);
        }

        return json_encode($response);
    }

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


Question:
Se ejecuta antes de serializar los datos

 @param [Object] value valor del objeto a serializar original

 @return [Array] nuevo valor del objeto a serializar

def before_dump(value)
      self.value = value if !value.nil?
      if !@block.nil?
        value = @parent.instance_exec( self, :dump, &@block )
      end
      self.value = value if !value.nil?
    end

@Override
    @Path("/{dataType}")
    public JSONObject get(String path, Map<String,String> headers) throws ServiceException, JSONException {
        String dataType = getSegment(path, 1);
        if (dataType == null)
            throw new ServiceException("Missing path segment: {dataType}");
        try {
            BaselineData baselineData = DataAccess.getBaselineData();
            if (dataType.equals("VariableTypes")) {
                List<VariableType> variableTypes = baselineData.getVariableTypes();
                JSONArray jsonArray = new JSONArray();
                for (VariableType variableType : variableTypes)
                    jsonArray.put(variableType.getJson());
                return new JsonArray(jsonArray).getJson();
            }
            else if (dataType.equals("TaskCategories")) {
                List<TaskCategory> taskCats = new ArrayList<TaskCategory>();
                taskCats.addAll(baselineData.getTaskCategories().values());
                Collections.sort(taskCats);
                JSONArray jsonArray = new JSONArray();
                for (TaskCategory taskCat : taskCats)
                    jsonArray.put(taskCat.getJson());
                return new JsonArray(jsonArray).getJson();
            }
            else {
                throw new ServiceException("Unsupported dataType: " + dataType);
            }
        }
        catch (Exception ex) {
            throw new ServiceException(ex.getMessage(), ex);
        }
    }

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


Question: link common dependencies between project & given directory/monorepo

function linkIfExists(pkgs) {
  const sharedDepsDirs = getSharedDepDirs(pkgs, packageHash);

  if (sharedDepsDirs.length) {
    logPkgsMsg('Linking', sharedDepsDirs);
    linkPackages(sharedDepsDirs);
  } else {
    log('No shared dependencies found');
  }
}

private void fillIn(PackageSymbol p) throws IOException {
        if (p.members_field == null)
            p.members_field = WriteableScope.create(p);

        ModuleSymbol msym = p.modle;

        Assert.checkNonNull(msym, p::toString);

        msym.complete();

        if (msym == syms.noModule) {
            preferCurrent = false;
            if (userPathsFirst) {
                scanUserPaths(p, true);
                preferCurrent = true;
                scanPlatformPath(p);
            } else {
                scanPlatformPath(p);
                scanUserPaths(p, true);
            }
        } else if (msym.classLocation == StandardLocation.CLASS_PATH) {
            scanUserPaths(p, msym.sourceLocation == StandardLocation.SOURCE_PATH);
        } else {
            scanModulePaths(p, msym);
        }
    }

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


Question:
Set the edit mode.
@param mode the edit mode to set.
@return flag, indicating if the mode could be changed.

public boolean setEditMode(CmsMessageBundleEditorTypes.EditMode mode) {

        try {
            if ((mode == CmsMessageBundleEditorTypes.EditMode.MASTER) && (null == m_descFile)) {
                m_descFile = LockedFile.lockResource(m_cms, m_desc);
            }
            m_editMode = mode;
        } catch (CmsException e) {
            return false;
        }
        return true;
    }

def _init_metadata(self):
        """"""

        # pylint: disable=attribute-defined-outside-init
        # this method is called from descendent __init__
        self._mdata.update(default_mdata.get_osid_form_mdata())
        update_display_text_defaults(self._mdata['journal_comment'], self._locale_map)
        for element_name in self._mdata:
            self._mdata[element_name].update(
                {'element_id': Id(self._authority,
                                  self._namespace,
                                  element_name)})
        self._journal_comment_default = self._mdata['journal_comment']['default_string_values'][0]
        self._validation_messages = {}

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


Question:
Sets form model and adds form fields.

@param \atk4\data\Model $model
@param array|null       $fields

@return \atk4\data\Model

public function setModel(\atk4\data\Model $model, $fields = null)
    {
        parent::setModel($model);

        if ($fields === false) {
            return $model;
        }

        if ($fields === null) {
            $fields = $this->getModelFields($model);
        }

        // prepare array of fields - check if fields are editable or read_only/disabled
        $add_fields = [];
        foreach ($fields as $field) {
            $f = $model->getElement($field);

            if ($f->isEditable()) {
                $add_fields[] = [$f->short_name];
            } elseif ($f->isVisible()) {
                $add_fields[] = [$f->short_name, ['readonly'=>true]];
            }
        }

        if (is_array($add_fields)) {
            foreach ($add_fields as $field) {
                call_user_func_array([$this, 'addField'], $field);
            }
        } else {
            throw new Exception(['Incorrect value for $fields', 'fields' => $add_fields]);
        }

        return $model;
    }

function _fillMissingFields(attrs) {
  var attr;
  for(var i = 0; i < attrs.length; ++i) {
    attr = attrs[i];

    // populate missing name
    if(typeof(attr.name) === 'undefined') {
      if(attr.type && attr.type in pki.oids) {
        attr.name = pki.oids[attr.type];
      } else if(attr.shortName && attr.shortName in _shortNames) {
        attr.name = pki.oids[_shortNames[attr.shortName]];
      }
    }

    // populate missing type (OID)
    if(typeof(attr.type) === 'undefined') {
      if(attr.name && attr.name in pki.oids) {
        attr.type = pki.oids[attr.name];
      } else {
        var error = new Error('Attribute type not specified.');
        error.attribute = attr;
        throw error;
      }
    }

    // populate missing shortname
    if(typeof(attr.shortName) === 'undefined') {
      if(attr.name && attr.name in _shortNames) {
        attr.shortName = _shortNames[attr.name];
      }
    }

    if(typeof(attr.value) === 'undefined') {
      var error = new Error('Attribute value not specified.');
      error.attribute = attr;
      throw error;
    }
  }
}

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


Question:
// SetVersionPriority allows specifying a precise order of priority. All specified versions must be in the same group,
// and the specified order overwrites any previously specified order for this group

func (s *Scheme) SetVersionPriority(versions ...schema.GroupVersion) error {
	groups := sets.String{}
	order := []string{}
	for _, version := range versions {
		if len(version.Version) == 0 || version.Version == APIVersionInternal {
			return fmt.Errorf("internal versions cannot be prioritized: %v", version)
		}

		groups.Insert(version.Group)
		order = append(order, version.Version)
	}
	if len(groups) != 1 {
		return fmt.Errorf("must register versions for exactly one group: %v", strings.Join(groups.List(), ", "))
	}

	s.versionPriority[groups.List()[0]] = order
	return nil
}

public function insert($document)
    {
        $class     = $this->dm->getClassMetadata(get_class($document));
        $changeset = $this->uow->getDocumentChangeSet($document);
        $qb        = $this->dm->createQueryBuilder($this->class->name);

        foreach ($class->propertyMetadata as $mapping) {
            $new = isset($changeset[$mapping->name][1]) ? $changeset[$mapping->name][1] : null;

            if (($new === null && !$mapping->nullable) || $mapping->isInverseSide) {
                continue;
            }

            if ($mapping->isMany()) {
                if ($mapping->strategy === PropertyMetadata::STORAGE_STRATEGY_ADD_TO_SET || $new->isEmpty()) {
                    continue;
                }

                $this->uow->unscheduleCollectionDeletion($new);
                $this->uow->unscheduleCollectionUpdate($new);
            }

            $qb->attr($mapping->name)->put($new);
        }

        //add a conditional preventing the resulting PutItem from overwriting
        //an existing record with the same primary key
        $class->createIdentifier($document)->addNotExistsToQueryCondition($qb->expr);

        $qb->getQuery()->execute();
    }

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


Question:
Joins given tag into single, unary tag
@param  {TextEditor} editor
@param  {Node}       node
@param  {String}     syntax Host document syntax, defines how self-closing tag
should be displayed

function joinTag(editor, node, syntax) {
	// Remove everything between the end of opening tag and the end of closing tag
	const open = getText(editor, node.open);
	const m = open.match(/\s*>$/);
	const start = node.open.end.translate([0, m ? -m[0].length : 0]);
	editor.setTextInBufferRange(new Range(start, node.end),
		selfClosingStyle[syntax] || selfClosingStyle.xhtml);
}

def write_title_rich(title, horiz = nil, layout = nil, overlay = nil) # :nodoc:
      @writer.tag_elements('c:title') do
        # Write the c:tx element.
        write_tx_rich(title, horiz)
        # Write the c:layout element.
        write_layout(layout, 'text')
        # Write the c:overlay element.
        write_overlay if overlay
      end
    end

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