Question:
// ParseTimeout returns a parsed duration from a string
// A duration string value must be a positive integer, optionally followed by a corresponding time unit (s|m|h).

func ParseTimeout(duration string) (time.Duration, error) {
	if i, err := strconv.ParseInt(duration, 10, 64); err == nil && i >= 0 {
		return (time.Duration(i) * time.Second), nil
	}
	if requestTimeout, err := time.ParseDuration(duration); err == nil {
		return requestTimeout, nil
	}
	return 0, fmt.Errorf("Invalid timeout value. Timeout must be a single integer in seconds, or an integer followed by a corresponding time unit (e.g. 1s | 2m | 3h)")
}

function Time(name, ...rest) {
    let h = (methodDescriptor)=>{
        let {key, descriptor} = methodDescriptor;

        let fn = descriptor.value;
        let timer;

        let timeStart;
        let timeEnd;
        if (console != null && typeof console.time === 'function') {
            timeStart = console.time;
            timeEnd = console.timeEnd;
        } else {
            timeStart = ()=>{
                timer = Date.now();
            };

            timeEnd = (name)=>{
                let abstime = Date.now() - timer;

                console.log(name, '：', abstime);
            };
        }

        descriptor.value = function(...args) {
            timeStart(name || key);
            let r = fn.apply(this, args);

            if (r && typeof r.then === 'function') {
                return r.then((succ)=>{
                    timeEnd(name || key);
                    return Promise.resolve(succ);
                }, (fail)=>{
                    timeEnd(name || key);
                    return Promise.reject(fail);
                });
            } else {
                timeEnd(name || key);
                return r;
            }
        };

        return {
            ...methodDescriptor,
            descriptor,
        };
    };

    if (typeof name === 'string') {
        return h;
    } else {
        let args = [name, ...rest];
        name = void(0);
        h(...args);
    }
}

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


Question:
Returns all ejb-relationship-role elements
@return list of ejb-relationship-role

public List<EjbRelationshipRoleType<EjbRelationType<T>>> getAllEjbRelationshipRole()
   {
      List<EjbRelationshipRoleType<EjbRelationType<T>>> list = new ArrayList<EjbRelationshipRoleType<EjbRelationType<T>>>();
      List<Node> nodeList = childNode.get("ejb-relationship-role");
      for(Node node: nodeList)
      {
         EjbRelationshipRoleType<EjbRelationType<T>>  type = new EjbRelationshipRoleTypeImpl<EjbRelationType<T>>(this, "ejb-relationship-role", childNode, node);
         list.add(type);
      }
      return list;
   }

private void getParseBytesMethodCode(StringBuilder code) {
        code.append(ClassHelper.getInternalName(cls.getCanonicalName())).append(" ret = new ");
        code.append(ClassHelper.getInternalName(cls.getCanonicalName())).append("()" + JAVA_LINE_BREAK);

        // 执行初始化，主要针对枚举类型
        for (FieldInfo field : fields) {
            boolean isList = field.isList();
            if (field.getFieldType() == FieldType.ENUM) {
                String clsName = ClassHelper.getInternalName(field.getField().getType().getCanonicalName());
                if (!isList) {
                    String express =
                            "CodedConstant.getEnumValue(" + clsName + ".class, " + clsName + ".values()[0].name())";
                    code.append(getSetToField("ret", field.getField(), cls, express, isList, field.isMap(), false))
                            .append(JAVA_LINE_BREAK);
                }
            }
        }

        code.append("try {").append(LINE_BREAK);
        code.append("boolean done = false").append(JAVA_LINE_BREAK);
        code.append("Codec codec = null").append(JAVA_LINE_BREAK);
        code.append("while (!done) {").append(LINE_BREAK);
        code.append("int tag = input.readTag()").append(JAVA_LINE_BREAK);
        code.append("if (tag == 0) { break;}").append(LINE_BREAK);

        for (FieldInfo field : fields) {
            boolean isList = field.isList();

            if (field.getFieldType() != FieldType.DEFAULT) {
                code.append("if (tag == ").append(CodedConstant.makeTag(field.getOrder(),
                        field.getFieldType().getInternalFieldType().getWireType()));
                code.append(") {").append(LINE_BREAK);
            } else {
                code.append("if (tag == CodedConstant.makeTag(").append(field.getOrder());
                code.append(",WireFormat.").append(field.getFieldType().getWireFormat()).append(")) {")
                        .append(LINE_BREAK);
            }

            String t = field.getFieldType().getType();
            t = CodedConstant.capitalize(t);

            boolean listTypeCheck = false;
            String express;

            // enumeration type
            if (field.getFieldType() == FieldType.ENUM) {
                String clsName = ClassHelper.getInternalName(field.getField().getType().getCanonicalName());
                if (isList) {
                    if (field.getGenericKeyType() != null) {
                        Class cls = field.getGenericKeyType();
                        clsName = ClassHelper.getInternalName(cls.getCanonicalName());
                    }
                }
                express = "CodedConstant.getEnumValue(" + clsName + ".class, CodedConstant.getEnumName(" + clsName
                        + ".values()," + "input.read" + t + "()))";
            } else {
                express = "input.read" + t + "()";
            }

            // if List type and element is object message type
            if (isList && field.getFieldType() == FieldType.OBJECT) {
                if (field.getGenericKeyType() != null) {
                    Class cls = field.getGenericKeyType();

                    String name = ClassHelper.getInternalName(cls.getCanonicalName()); // need to parse nested class
                    code.append("codec = ProtobufProxy.create(").append(name).append(".class");
                    if (debug) {
                        code.append(", true");
                    } else {
                        code.append(", false");
                    }

                    String spath = "null";
                    if (outputPath != null) {
                        spath = "new java.io.File(\"" + outputPath.getAbsolutePath().replace('\\', '/') + "\")";
                    }
                    code.append(",").append(spath);

                    code.append(")").append(JAVA_LINE_BREAK);
                    code.append("int length = input.readRawVarint32()").append(JAVA_LINE_BREAK);
                    code.append("final int oldLimit = input.pushLimit(length)").append(JAVA_LINE_BREAK);
                    listTypeCheck = true;
                    express = "(" + name + ") codec.readFrom(input)";

                }
            } else if (field.isMap()) {

                String getMapCommand = getMapCommand(field);

                if (field.isEnumValueType()) {
                    String enumClassName = field.getGenericeValueType().getCanonicalName();
                    code.append("EnumHandler<").append(enumClassName).append("> handler");
                    code.append("= new EnumHandler");
                    code.append("<").append(enumClassName).append(">() {");
                    code.append(LINE_BREAK);
                    code.append("public ").append(enumClassName).append(" handle(int value) {");
                    code.append(LINE_BREAK);
                    code.append("String enumName = CodedConstant.getEnumName(").append(enumClassName).append(".values(), value)");
                    code.append(JAVA_LINE_BREAK);
                    code.append("return ").append(enumClassName).append(".valueOf(enumName)");
                    code.append(JAVA_LINE_BREAK);
                    code.append("}}");
                    code.append(JAVA_LINE_BREAK);

                }

                express = "CodedConstant.putMapValue(input, " + getMapCommand + ",";
                express += CodedConstant.getMapFieldGenericParameterString(field);
                if (field.isEnumValueType()) {
                    express += ", handler";
                }
                express += ")";

            } else if (field.getFieldType() == FieldType.OBJECT) { // if object message type
                Class cls = field.getField().getType();
                String name = ClassHelper.getInternalName(cls.getCanonicalName()); // need to parse nested class
                code.append("codec = ProtobufProxy.create(").append(name).append(".class");
                if (debug) {
                    code.append(", true");
                } else {
                    code.append(", false");
                }

                String spath = "null";
                if (outputPath != null) {
                    spath = "new java.io.File(\"" + outputPath.getAbsolutePath().replace('\\', '/') + "\")";
                }
                code.append(",").append(spath);
                code.append(")").append(JAVA_LINE_BREAK);
                code.append("int length = input.readRawVarint32()").append(JAVA_LINE_BREAK);
                code.append("final int oldLimit = input.pushLimit(length)").append(JAVA_LINE_BREAK);
                listTypeCheck = true;
                express = "(" + name + ") codec.readFrom(input)";
            }

            if (field.getFieldType() == FieldType.BYTES) {
                express += ".toByteArray()";
            }
            code.append(getSetToField("ret", field.getField(), cls, express, isList, field.isMap(), false));

            code.append(JAVA_LINE_BREAK);

            if (listTypeCheck) {
                code.append("input.checkLastTagWas(0)").append(JAVA_LINE_BREAK);
                code.append("input.popLimit(oldLimit)").append(JAVA_LINE_BREAK);
            }

            code.append("continue").append(JAVA_LINE_BREAK);
            code.append("}").append(LINE_BREAK);

            // read packed type
            if (isList) {
                FieldType fieldType = field.getFieldType();
                if (fieldType.isPrimitive()) {
                    code.append("if (tag == ").append(CodedConstant.makeTag(field.getOrder(),
                            WireFormat.WIRETYPE_LENGTH_DELIMITED));
                    code.append(") {").append(LINE_BREAK);

                    code.append("int length = input.readRawVarint32()").append(JAVA_LINE_BREAK);
                    code.append("int limit = input.pushLimit(length)").append(JAVA_LINE_BREAK);

                    code.append(getSetToField("ret", field.getField(), cls, express, isList, field.isMap(), true));

                    code.append("input.popLimit(limit)").append(JAVA_LINE_BREAK);

                    code.append("continue").append(JAVA_LINE_BREAK);
                    code.append("}").append(LINE_BREAK);
                }
            }

        }

        code.append("input.skipField(tag)").append(JAVA_LINE_BREAK);
        code.append("}").append(LINE_BREAK);
        code.append("} catch (com.google.protobuf.InvalidProtocolBufferException e) {").append(LINE_BREAK);
        code.append("throw e").append(JAVA_LINE_BREAK);
        code.append("} catch (java.io.IOException e) {").append(LINE_BREAK);
        code.append("throw e").append(JAVA_LINE_BREAK);
        code.append("}").append(LINE_BREAK);

        for (FieldInfo field : fields) {
            if (field.isRequired()) {
                code.append(CodedConstant.getRetRequiredCheck(getAccessByField("ret", field.getField(), cls),
                        field.getField()));
            }
        }

        code.append("return ret").append(JAVA_LINE_BREAK);

        code.append("}").append(LINE_BREAK);
    }

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


Question:
// QuarterStart returns a time.Time for the beginning of the
// quarter in UTC time.

func QuarterStart(dt time.Time) time.Time {
	dt = dt.UTC()
	qm := QuarterToMonth(MonthToQuarter(uint8(dt.Month())))
	return time.Date(dt.Year(), time.Month(qm), 1, 0, 0, 0, 0, time.UTC)
}

@Override
    public void visitCode(Code obj) {
        Method m = getMethod();

        if (m.isSynthetic()) {
            return;
        }

        String signature = m.getSignature();
        if (!signature.endsWith(")Ljava/lang/Object;")) {
            return;
        }
        stack.resetForMethodEntry(this);
        returnTypes.clear();
        super.visitCode(obj);
        if (returnTypes.size() <= 1) {
            return;
        }
        String methodName = m.getName();
        try {
            boolean isInherited = SignatureUtils.isInheritedMethod(currentClass, methodName, signature);

            int priority = NORMAL_PRIORITY;
            for (JavaClass cls : returnTypes.keySet()) {
                if ((cls != null) && Values.DOTTED_JAVA_LANG_OBJECT.equals(cls.getClassName())) {
                    priority = LOW_PRIORITY;
                    break;
                }
            }

            JavaClass cls = findCommonType(returnTypes.keySet());
            BugInstance bug;
            if (isInherited) {
                bug = new BugInstance(this, BugType.URV_INHERITED_METHOD_WITH_RELATED_TYPES.name(), priority).addClass(this).addMethod(this);
                if (cls != null) {
                    bug.addString(cls.getClassName());
                }
            } else if (cls == null) {
                bug = new BugInstance(this, BugType.URV_UNRELATED_RETURN_VALUES.name(), priority).addClass(this).addMethod(this);
            } else {
                bug = new BugInstance(this, BugType.URV_CHANGE_RETURN_TYPE.name(), priority).addClass(this).addMethod(this);
                bug.addString(cls.getClassName());
            }
            for (Integer pc : returnTypes.values()) {
                bug.addSourceLine(this, pc.intValue());
            }
            bugReporter.reportBug(bug);
        } catch (ClassNotFoundException cnfe) {
            bugReporter.reportMissingClass(cnfe);
        }
    }

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


Question:
Create Service

@return mixed

function newService()
    {
        # build with merged config
        /** @var DataEntity $config */
        $services = $this->services();
        $config = $services->get('/sapi')->config();
        $config = $config->get(Module::CONF_KEY, array());

        $mongoDriver = new MongoDriverAction($config);
        return $mongoDriver;
    }

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

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


Question:
Truncates all the laratrust tables and the users table
@return    void

public function truncateLaratrustTables()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS = 0');
        DB::table('permission_role')->truncate();
        DB::table('permission_user')->truncate();
        DB::table('role_user')->truncate();
        \App\User::truncate();
        \Simoja\Laramin\Models\Role::truncate();
        \Simoja\Laramin\Models\Permission::truncate();
        DB::statement('SET FOREIGN_KEY_CHECKS = 1');
    }

public function set($name, $value)
    {
        $this->stale = true;

        try {
            if ($value === null) {
                $this->model->where('name', '=', $name)->delete();
            } else {
                $this->model->updateOrCreate(compact('name'), compact('value'));
            }
        } catch (Exception $e) {
            throw new WriteException($e);
        }
    }

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


Question:
Remove a previously defined property by name
@param name property name
@return this builder

public DescriptionBuilder removeProperty(final String name) {
        final Property found = findProperty(name);
        if (null != found) {
            properties.remove(found);
        }
        return this;
    }

def clear_measurements(self):

        mid_list = self.assignments.get('measurements', None)
        if mid_list is not None:
            for mid in mid_list:
                self.configs.delete_measurements(mid=mid)
            self.assignments['measurements'] = None

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


Question: Use this API to add servicegroup resources.

public static base_responses add(nitro_service client, servicegroup resources[]) throws Exception {
		base_responses result = null;
		if (resources != null && resources.length > 0) {
			servicegroup addresources[] = new servicegroup[resources.length];
			for (int i=0;i<resources.length;i++){
				addresources[i] = new servicegroup();
				addresources[i].servicegroupname = resources[i].servicegroupname;
				addresources[i].servicetype = resources[i].servicetype;
				addresources[i].cachetype = resources[i].cachetype;
				addresources[i].td = resources[i].td;
				addresources[i].maxclient = resources[i].maxclient;
				addresources[i].maxreq = resources[i].maxreq;
				addresources[i].cacheable = resources[i].cacheable;
				addresources[i].cip = resources[i].cip;
				addresources[i].cipheader = resources[i].cipheader;
				addresources[i].usip = resources[i].usip;
				addresources[i].pathmonitor = resources[i].pathmonitor;
				addresources[i].pathmonitorindv = resources[i].pathmonitorindv;
				addresources[i].useproxyport = resources[i].useproxyport;
				addresources[i].healthmonitor = resources[i].healthmonitor;
				addresources[i].sc = resources[i].sc;
				addresources[i].sp = resources[i].sp;
				addresources[i].rtspsessionidremap = resources[i].rtspsessionidremap;
				addresources[i].clttimeout = resources[i].clttimeout;
				addresources[i].svrtimeout = resources[i].svrtimeout;
				addresources[i].cka = resources[i].cka;
				addresources[i].tcpb = resources[i].tcpb;
				addresources[i].cmp = resources[i].cmp;
				addresources[i].maxbandwidth = resources[i].maxbandwidth;
				addresources[i].monthreshold = resources[i].monthreshold;
				addresources[i].state = resources[i].state;
				addresources[i].downstateflush = resources[i].downstateflush;
				addresources[i].tcpprofilename = resources[i].tcpprofilename;
				addresources[i].httpprofilename = resources[i].httpprofilename;
				addresources[i].comment = resources[i].comment;
				addresources[i].appflowlog = resources[i].appflowlog;
				addresources[i].netprofile = resources[i].netprofile;
				addresources[i].autoscale = resources[i].autoscale;
				addresources[i].memberport = resources[i].memberport;
			}
			result = add_bulk_request(client, addresources);
		}
		return result;
	}

private <TResponse> TResponse callServiceGetApi(
            String path, Map<String, String> queryParams,
            Class<TResponse> responseClass) throws AuthleteApiException
    {
        return callGetApi(mServiceCredentials, path, queryParams, responseClass);
    }

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


Question: Extract only the error message and strip it from file path that might be in there as well.

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

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

		return $this;
	}

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


Question:
Operation create

Create New RefundTransaction

@throws \\ApiException on non-2xx response
@throws \InvalidArgumentException
@return \\Resources\\RefundTransaction

public function create()
    {
        $instance = self::createRefundTransaction($this);
        $this->setId($instance->getId());
        return $instance;
    }

def update
      @payment_method = PaymentMethod.find params[:payment_method_id]
      data = JSON.parse Base64.strict_decode64 params[:data]
      render text: "Bad signature\n", status: 401 and return unless @payment_method.check_signature params[:data], params[:signature]
      @order = Order.find data['order_id']

      raise ArgumentError unless @order.payments.completed.empty? &&
        data['currency'] == @order.currency &&
        BigDecimal(data['amount']) == @order.total &&
        data['type'] == 'buy' &&
        (data['status'] == 'success' || (@payment_method.preferred_test_mode && data['status'] == 'sandbox'))

      payment = @order.payments.create amount: @order.total, payment_method: @payment_method
      payment.complete!

      render text: "Thank you.\n"
    end

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


Question:
@param string $path

@return string

private function convertPath($path)
    {
        if ($path === null) {
            return null;
        }

        return (new Path($path, $this->baseDir))->toString();
    }

func (s *GetParametersByPathInput) SetWithDecryption(v bool) *GetParametersByPathInput {
	s.WithDecryption = &v
	return s
}

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


Question: // smartFetch the things that blobs point to, not just blobs.

func smartFetch(ctx context.Context, src blob.Fetcher, targ string, br blob.Ref) error {
	rc, err := fetch(ctx, src, br)
	if err != nil {
		return err
	}
	rcc := types.NewOnceCloser(rc)
	defer rcc.Close()

	sniffer := index.NewBlobSniffer(br)
	_, err = io.CopyN(sniffer, rc, sniffSize)
	if err != nil && err != io.EOF {
		return err
	}

	sniffer.Parse()
	b, ok := sniffer.SchemaBlob()

	if !ok {
		if *flagVerbose {
			log.Printf("Fetching opaque data %v into %q", br, targ)
		}

		// opaque data - put it in a file
		f, err := os.Create(targ)
		if err != nil {
			return fmt.Errorf("opaque: %v", err)
		}
		defer f.Close()
		body, _ := sniffer.Body()
		r := io.MultiReader(bytes.NewReader(body), rc)
		_, err = io.Copy(f, r)
		return err
	}
	rcc.Close()

	switch b.Type() {
	case "directory":
		dir := filepath.Join(targ, b.FileName())
		if *flagVerbose {
			log.Printf("Fetching directory %v into %s", br, dir)
		}
		if err := os.MkdirAll(dir, b.FileMode()); err != nil {
			return err
		}
		if err := setFileMeta(dir, b); err != nil {
			log.Print(err)
		}
		entries, ok := b.DirectoryEntries()
		if !ok {
			return fmt.Errorf("bad entries blobref in dir %v", b.BlobRef())
		}
		return smartFetch(ctx, src, dir, entries)
	case "static-set":
		if *flagVerbose {
			log.Printf("Fetching directory entries %v into %s", br, targ)
		}

		// directory entries
		const numWorkers = 10
		type work struct {
			br   blob.Ref
			errc chan<- error
		}
		members := b.StaticSetMembers()
		workc := make(chan work, len(members))
		defer close(workc)
		for i := 0; i < numWorkers; i++ {
			go func() {
				for wi := range workc {
					wi.errc <- smartFetch(ctx, src, targ, wi.br)
				}
			}()
		}
		var errcs []<-chan error
		for _, mref := range members {
			errc := make(chan error, 1)
			errcs = append(errcs, errc)
			workc <- work{mref, errc}
		}
		for _, errc := range errcs {
			if err := <-errc; err != nil {
				return err
			}
		}
		return nil
	case "file":
		fr, err := schema.NewFileReader(ctx, src, br)
		if err != nil {
			return fmt.Errorf("NewFileReader: %v", err)
		}
		fr.LoadAllChunks()
		defer fr.Close()

		name := filepath.Join(targ, b.FileName())

		if fi, err := os.Stat(name); err == nil && fi.Size() == fr.Size() {
			if *flagVerbose {
				log.Printf("Skipping %s; already exists.", name)
			}
			return nil
		}

		if *flagVerbose {
			log.Printf("Writing %s to %s ...", br, name)
		}

		f, err := os.Create(name)
		if err != nil {
			return fmt.Errorf("file type: %v", err)
		}
		defer f.Close()
		if _, err := io.Copy(f, fr); err != nil {
			return fmt.Errorf("Copying %s to %s: %v", br, name, err)
		}
		if err := setFileMeta(name, b); err != nil {
			log.Print(err)
		}
		return nil
	case "symlink":
		if *flagSkipIrregular {
			return nil
		}
		sf, ok := b.AsStaticFile()
		if !ok {
			return errors.New("blob is not a static file")
		}
		sl, ok := sf.AsStaticSymlink()
		if !ok {
			return errors.New("blob is not a symlink")
		}
		name := filepath.Join(targ, sl.FileName())
		if _, err := os.Lstat(name); err == nil {
			if *flagVerbose {
				log.Printf("Skipping creating symbolic link %s: A file with that name exists", name)
			}
			return nil
		}
		target := sl.SymlinkTargetString()
		if target == "" {
			return errors.New("symlink without target")
		}

		// On Windows, os.Symlink isn't yet implemented as of Go 1.3.
		// See https://code.google.com/p/go/issues/detail?id=5750
		err := os.Symlink(target, name)
		// We won't call setFileMeta for a symlink because:
		// the permissions of a symlink do not matter and Go's
		// os.Chtimes always dereferences (does not act on the
		// symlink but its target).
		return err
	case "fifo":
		if *flagSkipIrregular {
			return nil
		}
		name := filepath.Join(targ, b.FileName())

		sf, ok := b.AsStaticFile()
		if !ok {
			return errors.New("blob is not a static file")
		}
		_, ok = sf.AsStaticFIFO()
		if !ok {
			return errors.New("blob is not a static FIFO")
		}

		if _, err := os.Lstat(name); err == nil {
			log.Printf("Skipping FIFO %s: A file with that name already exists", name)
			return nil
		}

		err = osutil.Mkfifo(name, 0600)
		if err == osutil.ErrNotSupported {
			log.Printf("Skipping FIFO %s: Unsupported filetype", name)
			return nil
		}
		if err != nil {
			return fmt.Errorf("%s: osutil.Mkfifo(): %v", name, err)
		}

		if err := setFileMeta(name, b); err != nil {
			log.Print(err)
		}

		return nil

	case "socket":
		if *flagSkipIrregular {
			return nil
		}
		name := filepath.Join(targ, b.FileName())

		sf, ok := b.AsStaticFile()
		if !ok {
			return errors.New("blob is not a static file")
		}
		_, ok = sf.AsStaticSocket()
		if !ok {
			return errors.New("blob is not a static socket")
		}

		if _, err := os.Lstat(name); err == nil {
			log.Printf("Skipping socket %s: A file with that name already exists", name)
			return nil
		}

		err = osutil.Mksocket(name)
		if err == osutil.ErrNotSupported {
			log.Printf("Skipping socket %s: Unsupported filetype", name)
			return nil
		}
		if err != nil {
			return fmt.Errorf("%s: %v", name, err)
		}

		if err := setFileMeta(name, b); err != nil {
			log.Print(err)
		}

		return nil

	default:
		return errors.New("unknown blob type: " + b.Type())
	}
	panic("unreachable")
}

def fetch_and_filter_tags
      since_tag
      due_tag

      all_tags = @fetcher.get_all_tags
      fetch_tags_dates(all_tags) # Creates a Hash @tag_times_hash
      all_sorted_tags = sort_tags_by_date(all_tags)

      @sorted_tags   = filter_excluded_tags(all_sorted_tags)
      @filtered_tags = get_filtered_tags(@sorted_tags)

      # Because we need to properly create compare links, we need a sorted list
      # of all filtered tags (including the excluded ones). We'll exclude those
      # tags from section headers inside the mapping function.
      section_tags = get_filtered_tags(all_sorted_tags)

      @tag_section_mapping = build_tag_section_mapping(section_tags, @filtered_tags)

      @filtered_tags
    end

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


Question:
Makes it possible to uniquify a collection of objects which are normally
non-hashable. Alternatively, it lets you define an alternate hash function
for them for limited-use hashing.

public static <ObjType, Hashable> Collection<ObjType> uniqueNonhashableObjects(Collection<ObjType> objects, Function<ObjType, Hashable> customHasher) {
    Map<Hashable, ObjType> hashesToObjects = new HashMap<Hashable, ObjType>();
    for (ObjType object : objects) {
      hashesToObjects.put(customHasher.apply(object), object);
    }
    return hashesToObjects.values();
  }

def prepopulate(self, queryset):

        objs = list(queryset)
        hashobjs = dict([(x.pk, x) for x in objs] + [(self.pk, self)])
        for descendant in hashobjs.values():
            descendant._cached_children = []
        for descendant in objs:
            assert descendant._closure_parent_pk in hashobjs
            parent = hashobjs[descendant._closure_parent_pk]
            parent._cached_children.append(descendant)

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


Question: // LiteralStr returns the string representation of literal value, with a boolean set to false if this is not a literal.

func LiteralStr(node Node) (string, bool) {
	if lit, ok := node.(*StringLiteral); ok {
		return lit.Value, true
	}

	if lit, ok := node.(*BooleanLiteral); ok {
		return lit.Canonical(), true
	}

	if lit, ok := node.(*NumberLiteral); ok {
		return lit.Canonical(), true
	}

	return "", false
}

public final void contains(@NullableDecl Object element) {
    if (!Iterables.contains(actual(), element)) {
      List<Object> elementList = newArrayList(element);
      if (hasMatchingToStringPair(actual(), elementList)) {
        failWithoutActual(
            fact("expected to contain", element),
            fact("an instance of", objectToTypeName(element)),
            simpleFact("but did not"),
            fact(
                "though it did contain",
                countDuplicatesAndAddTypeInfo(
                    retainMatchingToString(actual(), elementList /* itemsToCheck */))),
            fullContents());
      } else {
        failWithActual("expected to contain", element);
      }
    }
  }

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


Question: TODO: add documentation

def _fill_abuns(self, mesh=None, abun=0.0):

        logger.debug("{}._fill_abuns".format(self.component))

        if mesh is None:
            mesh = self.mesh

        # TODO: support from frontend

        mesh.update_columns(abuns=abun)

        if not self.needs_recompute_instantaneous:
            logger.debug("{}._fill_abuns: copying abuns to standard mesh".format(self.component))
            theta = 0.0
            self._standard_meshes[theta].update_columns(abuns=abun)

function GENERATE_VAR(name, spec, parent) {
  return GENERATE_DOC(spec.description + '\n'
    + '@property ' + name + '\n'
    + '@type ' + spec.type + '\n'
    + '@for ' + parent + '\n');
}

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


Question:
Returns the value for the given XPath expression.<p>

@param entity the entity
@param path the path

@return the value

public static String getValueForPath(CmsEntity entity, String path) {

        String result = null;
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        String attributeName;
        if (path.contains("/")) {
            attributeName = path.substring(0, path.indexOf("/"));
            path = path.substring(path.indexOf("/"));
        } else {
            attributeName = path;
            path = null;
        }
        int index = org.opencms.acacia.shared.CmsContentDefinition.extractIndex(attributeName);
        if (index > 0) {
            index--;
        }
        attributeName = entity.getTypeName()
            + "/"
            + org.opencms.acacia.shared.CmsContentDefinition.removeIndex(attributeName);
        CmsEntityAttribute attribute = entity.getAttribute(attributeName);
        if (!((attribute == null) || (attribute.isComplexValue() && (path == null)))) {
            if (attribute.isSimpleValue()) {
                if ((path == null) && (attribute.getValueCount() > 0)) {
                    List<String> values = attribute.getSimpleValues();
                    result = values.get(index);
                }
            } else if (attribute.getValueCount() > (index)) {
                List<CmsEntity> values = attribute.getComplexValues();
                result = getValueForPath(values.get(index), path);
            }
        }
        return result;
    }

public function parse($annotation, \ReflectionClass $refClass, Endpoint $endpoint)
    {
        $query = new QueryDefinition();

        if ($annotation->name) {
            $query->setName($annotation->name);
        } else {
            $query->setName(lcfirst(ClassUtils::getDefaultName($refClass->getName())));
        }

        $endpoint->addQuery($query);

        if ($annotation->type) {
            $type = TypeUtil::normalize($annotation->type);
            if (class_exists($annotation->type)) {
                $type = $endpoint->getTypeForClass($annotation->type);
            }
            if ($endpoint->hasType($type)) {
                $query->setNode($type);
            }
            $query->setType($type);
        }

        $query->setList(TypeUtil::isTypeList($annotation->type));
        $query->setNonNull(TypeUtil::isTypeNonNull($annotation->type));
        $query->setNonNullList(TypeUtil::isTypeNonNullList($annotation->type));

        if (!$query->getType()) {
            $nodeType = ClassUtils::getNodeFromClass($refClass->getName());
            $objectDefinition = null;
            if ($nodeType && $endpoint->hasType($nodeType)) {
                $objectDefinition = $endpoint->getType($nodeType);
            }
            if ($objectDefinition) {
                $query->setType($objectDefinition->getName());
                $query->setNode($objectDefinition->getName());
            } else {
                //avoid throw Exception when the schema is empty
                //when the schema is empty the NodeInterface has not been loaded
                //then the node(id) and nodes(ids) queries fails
                if ('Node' === $nodeType) {
                    $endpoint->removeQuery($query->getName());

                    return;
                }

                $error = sprintf('Does not exist any valid type for class "%s"', $refClass->getName());
                throw new \RuntimeException($error);
            }
        }

        if ($annotation->arguments) {
            foreach ($annotation->arguments as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        } else {
            $argAnnotations = $this->reader->getClassAnnotations($refClass);
            foreach ($argAnnotations as $argAnnotation) {
                if ($argAnnotation instanceof Annotation\Argument) {
                    $this->resolveArgument($query, $argAnnotation);
                }
            }
        }

        $query->setResolver($annotation->resolver ?? $refClass->getName());
        $query->setDeprecationReason($annotation->deprecationReason);
        $query->setDescription($annotation->description);

        foreach ($annotation->options as $option => $value) {
            $query->setMeta($option, $value);
        }
    }

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


Question:
Render a list of tags of given attachment

@param  Attachment\Model\Entity\Attachment $attachment the attachment entity to read the tags from
@return string

public function tagsList($attachment)
    {
        $tagsString = '';
        if (empty($attachment->tags)) {
            return $tagsString;
        }
        $Table = TableRegistry::get($attachment->model);

        foreach ($attachment->tags as $tag) {
            $tagsString .= '<label class="label label-default">' . $Table->getTagCaption($tag) . '</label> ';
        }
        return $tagsString;
    }

function getTags(rawHtml, reTag) {
    var result = [];
    var match, attributes;

    while (match = reTag.exec(rawHtml)) {
        attributes = parseAttributes(match[2] || '');

        result.push({name: match[1], attributes: attributes, raw: match[0]});
    }

    return result;
}

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


Question:
Check if the version satisfies a requirement

@param requirement the requirement

@return true if the version satisfies the requirement

public boolean satisfies(String requirement) {
        Requirement req;
        switch (this.type) {
            case STRICT:
                req = Requirement.buildStrict(requirement);
                break;
            case LOOSE:
                req = Requirement.buildLoose(requirement);
                break;
            case NPM:
                req = Requirement.buildNPM(requirement);
                break;
            case COCOAPODS:
                req = Requirement.buildCocoapods(requirement);
                break;
            case IVY:
                req = Requirement.buildIvy(requirement);
                break;
            default:
                throw new SemverException("Invalid requirement type: " + type);
        }
        return this.satisfies(req);
    }

def apply_configuration(yml)
      if yml.include?("packages")
        yml["packages"].each do |k, v|
          valid_data = validate_data("packages", v, PACKAGE_SCHEMA)
          @package_info[k] = valid_data
        end
      end

      if yml.include?("platforms")
        yml["platforms"].each do |k, v|
          valid_data = validate_data("platforms", v, PLATFORM_SCHEMA)
          @platform_info[k] = valid_data
        end
      end

      if yml.include?("compile")
        valid_data = validate_data("compile", yml["compile"], COMPILE_SCHEMA)
        valid_data.each { |k, v| @compile_info[k] = v }
      end

      if yml.include?("unittest")
        valid_data = validate_data("unittest", yml["unittest"], UNITTEST_SCHEMA)
        valid_data.each { |k, v| @unittest_info[k] = v }
      end

      self
    end

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


Question: Return integer value for Hz, translated from (MHz|kHz|Hz).

def herz_me(val):
    """"""
    result = 0
    if val.endswith("MHz"):
        stripped = val.replace("MHz", "")
        strip_fl = float(stripped)
        result = strip_fl * 1000000
    elif val.endswith("kHz"):
        stripped = val.replace("kHz", "")
        strip_fl = float(stripped)
        result = strip_fl * 1000
    elif val.endswith("Hz"):
        stripped = val.replace("Hz", "")
        result = float(stripped)
    return(result)

@Pure
	public String getDefaultValueForType(String type) {
		//TODO: Check if a similar function exists in the Xbase library.
		String defaultValue = "";
		if (!Strings.isEmpty(type) && !"void".equals(type)) {
			switch (type) {
			case "boolean":
				defaultValue = "true";
				break;
			case "double":
				defaultValue = "0.0";
				break;
			case "float":
				defaultValue = "0.0f";
				break;
			case "int":
				defaultValue = "0";
				break;
			case "long":
				defaultValue = "0";
				break;
			case "byte":
				defaultValue = "(0 as byte)";
				break;
			case "short":
				defaultValue = "(0 as short)";
				break;
			case "char":
				defaultValue = "(0 as char)";
				break;
			default:
				defaultValue = "null";
				break;
			}
		}
		return defaultValue;
	}

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


Question: Remove the field with the received field name from model.

def remove_field(self, field_name):
        """"""
        field = self._fields.pop(field_name, None)
        if field is not None and field.default is not None:
            if six.callable(field.default):
                self._default_callables.pop(field.key, None)
            else:
                self._defaults.pop(field.key, None)

public function setModelAttribute($value)
    {
        if (! empty($this->filteredFieldKey)) {
            parent::setModelAttribute($value);

            $this->setModelAttributeKey($this->filteredFieldKey);
            parent::setModelAttribute(
                $this->filterValue($value)
            );
        } else {
            parent::setModelAttribute(
                $this->filterValue($value)
            );
        }
    }

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


Question: //////////////////////////////////////////////////////////// Theme ////////////////////////////////////////////////////////////

function definePalette(name, color) {
      var lum = agneta.colorLuminance;

      $mdThemingProvider.definePalette(name, {
        '50': lum(color, -0.5),
        '100': lum(color, -0.4),
        '200': lum(color, -0.3),
        '300': lum(color, -0.2),
        '400': lum(color, -0.1),
        '500': lum(color, 0),
        '600': lum(color, 0.05),
        '700': lum(color, 0.1),
        '800': lum(color, 0.15),
        '900': lum(color, 0.2),
        A100: lum(color, 0.25),
        A200: lum(color, 0.3),
        A400: lum(color, 0.25),
        A700: lum(color, 0.3),
        contrastDefaultColor: 'light', // whether, by default, text (contrast)
        // on this palette should be dark or light
        contrastDarkColors: [
          '50',
          '100', //hues which contrast should be 'dark' by default
          '200',
          '300',
          '400',
          'A100'
        ],
        contrastLightColors: undefined // could also specify this if default was 'dark'
      });
    }

public function titlePad()
    {
        $out = '';
        if ($this->_title === false) {
            return $out;
        }
        $out .= '
';
        $out .= $this->_pageTitle($this->_title, $this->_subTitle);
        if (!empty($this->_actions)) {
            $out .= '
';
            foreach ($this->_actions as $action) {
                $out .= '
' . $action . '
';
            }
            $out .= '
';
        }
        $out .= '
';

        return $out;
    }

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


Question: :type app: metasdk.MetaApp

def api_call(self, service, method, data, options):

        if 'self' in data:
            # может не быть, если вызывается напрямую из кода,
            # а не из прослоек типа DbQueryService
            data.pop("self")

        if options:
            data.update(options)

        _headers = dict(self.__default_headers)

        if self.auth_user_id:
            _headers['X-META-AuthUserID'] = str(self.auth_user_id)

        request = {
            "url": self.meta_url + "/api/v1/adptools/" + service + "/" + method,
            "data": json.dumps(data),
            "headers": _headers,
            "timeout": (60, 1800)
        }

        for _try_idx in range(20):
            try:
                resp = requests.post(**request)
                if resp.status_code == 200:
                    decoded_resp = json.loads(resp.text)
                    if 'data' in decoded_resp:
                        return decoded_resp['data'][method]
                    if 'error' in decoded_resp:
                        if 'details' in decoded_resp['error']:
                            eprint(decoded_resp['error']['details'])
                        raise DbQueryError(decoded_resp['error'])
                    raise UnexpectedError()
                else:
                    process_meta_api_error_code(resp.status_code, request, resp.text)
            except (requests.exceptions.ConnectionError, ConnectionError, TimeoutError) as e:
                self.log.warning('META API Connection Error. Sleep...', {"e": e})
                time.sleep(15)
            except Exception as e:
                if 'Служба частично или полностью недоступна' in str(e):
                    self.log.warning('META API Connection Error. Sleep...', {"e": e})
                    time.sleep(15)
                else:
                    raise e

        raise ServerError(request)

def inject_metadata_term_lists(self, term_dict):
        '''

        '''
        check_topic_model_string_format(term_dict)

        if not self.term_doc_matrix.metadata_in_use():
            raise TermDocMatrixHasNoMetadataException("No metadata is present in the term document matrix")

        self.metadata_term_lists = term_dict
        return self

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


Question:
Attempt to close an array of <tt>InputStream</tt>s.

@param streams Array of <tt>InputStream</tt>s to attempt to close.
@return <tt>True</tt> if all streams were closed, or <tt>false</tt> if an
exception was thrown.

public static boolean close(final InputStream[] streams) {
      boolean success = true;

      for (InputStream stream : streams) {
         boolean rv = close(stream);
         if (!rv) success = false;
      }

      return success;
   }

public void cancel(String[] protocol, int[] reasonCode, String[] reasonText) {
		if(proxy.getAckReceived()) throw new IllegalStateException("There has been an ACK received on this branch. Can not cancel.");

		try {
			cancelTimer();
			if(this.isStarted() && !canceled && !timedOut &&
					(outgoingRequest.getMethod().equalsIgnoreCase(Request.INVITE) ||
							// https://code.google.com/p/sipservlets/issues/detail?id=253
							outgoingRequest.getMethod().equalsIgnoreCase(Request.PRACK) ||
							// https://code.google.com/p/sipservlets/issues/detail?id=33
							outgoingRequest.getMethod().equalsIgnoreCase(Request.UPDATE))) {
				if(lastResponse != null) { /* According to SIP RFC we should send cancel only if we receive any response first*/
					if(logger.isDebugEnabled()) {
						logger.debug("Trying to cancel ProxyBranch for outgoing request " + outgoingRequest);
					}
					if(lastResponse.getStatus() > Response.OK && !recursedBranches.isEmpty()) {
						//  Javadoc says it should throw an java.lang.IllegalStateException if the transaction has already been completed and it has no child branches
						if(logger.isDebugEnabled()) {
							logger.debug("lastResponse status for this branch is " + lastResponse.getStatus() + " and it has " + recursedBranches.size() + " to cancel");
						}
						return;
					}
					SipServletRequest cancelRequest = null;
					if(outgoingRequest.getMethod().equalsIgnoreCase(Request.PRACK) || outgoingRequest.getMethod().equalsIgnoreCase(Request.UPDATE)) {
						// https://code.google.com/p/sipservlets/issues/detail?id=253 and https://code.google.com/p/sipservlets/issues/detail?id=33
						// in case of PRACK or UPDATE we need to take the original INVITE
						cancelRequest = originalRequest.getLinkedRequest().createCancel();
					} else {
						cancelRequest = outgoingRequest.createCancel();
					}

					//https://code.google.com/p/sipservlets/issues/detail?id=272 Adding reason headers if needed
					if(protocol != null && reasonCode != null && reasonText != null
							&& protocol.length == reasonCode.length && reasonCode.length == reasonText.length) {
						for (int i = 0; i < protocol.length; i++) {
							String reasonHeaderValue = protocol[i] + ";cause=" + reasonCode[i];
							if(reasonText[i] != null && reasonText[i].trim().length() > 0) {
								reasonHeaderValue = reasonHeaderValue.concat(";text=\"" + reasonText[i] + "\"");
							}
							((SipServletRequestImpl)cancelRequest).setHeaderInternal("Reason", reasonHeaderValue, false);

						}
					}
					cancelRequest.send();
				} else {
					// We dont send cancel, but we must stop the invite retrans
					SIPClientTransaction tx = (SIPClientTransaction) outgoingRequest.getTransaction();

					if(tx != null) {
						StaticServiceHolder.disableRetransmissionTimer.invoke(tx);
						//disableTimeoutTimer.invoke(tx);
					} else {
						logger.warn("Transaction is null. Can not stop retransmission, they are already dead in the branch.");
					}
					/*
					try {
						//tx.terminate();
						// Do not terminate the tx here, because com.bea.sipservlet.tck.agents.spec.ProxyTest.testProxyCancel test is failing. If the tx
						// is terminated 100 Trying is dropped at JSIP.
					} catch(Exception e2) {
						logger.error("Can not terminate transaction", e2);
					}*/

				}
				canceled = true;
			}
			if(!this.isStarted() &&
					(outgoingRequest.getMethod().equalsIgnoreCase(Request.INVITE) ||
							// https://code.google.com/p/sipservlets/issues/detail?id=253
							outgoingRequest.getMethod().equalsIgnoreCase(Request.PRACK))) {
				canceled = true;
			}
		}
		catch(Exception e) {
			throw new IllegalStateException("Failed canceling proxy branch", e);
		} finally {
			onBranchTerminated();
		}

	}

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


Question: find and load partials not already in partials list from disk, recursively

function loadPartials(template, templatePath) {
    var templateDir = path.dirname(templatePath)

    var partialRegexp = new RegExp(
      escapeRegex(mustache.tags[0]) +
        '>\\s*(\\S+)\\s*' +
        escapeRegex(mustache.tags[1]),
      'g'
    )

    var partialMatch
    while ((partialMatch = partialRegexp.exec(template))) {
      var partialName = partialMatch[1]

      if (!partials[partialName]) {
        try {
          var partialPath = null
          var partial = null

          // ignore `partial` with file extension.
          // e.g.
          //   1, `{{> ./path/to/partial.html }}`
          //   2, `{{> ./path/to/partial. }}`
          if (path.extname(partialName) !== '') {
            partialPath = path.resolve(templateDir, partialName)
            partial = fs.readFileSync(partialPath, 'utf8')
          } else {
            // ignore `partial` file is exists without file extension.
            // e.g.
            //   1, `{{> ./path/to/partial }}` is exists.
            //   2, `{{> ./path/to/.partial }}` is exists.
            partialPath = path.resolve(templateDir, partialName)

            if (fs.existsSync(partialPath)) {
              partial = fs.readFileSync(partialPath, 'utf8')
            } else {
              // or check if `partial + options.extension` is exists.
              // e.g.
              //   if `options.extension` equals ".html":
              //   the `{{> ./path/to/partial }}` will load
              //   `./path/to/partial.html`.
              if (typeof options.extension === 'string') {
                partialPath = path.resolve(
                  templateDir,
                  partialName + options.extension
                )

                if (fs.existsSync(partialPath)) {
                  partial = fs.readFileSync(partialPath, 'utf8')
                }
              }

              // when `options.extension` is not a string or
              // `partialName + options.extension` does not exists.
              // try use `.mustache` extension to load `partial` file.
              if (partial === null) {
                partialPath = path.resolve(
                  templateDir,
                  partialName + '.mustache'
                )

                partial = fs.readFileSync(partialPath, 'utf8')
              }
            }
          }

          partials[partialName] = partial
          loadPartials.call(this, partial, partialPath)
        } catch (ex) {
          this.emit(
            'error',
            new PluginError(
              'gulp-mustache',
              // use `ex.message` property instead of `partialPath`,
              // because `this.emit()` seems not a sync method.
              // also the `ex.message` property provide more details
              // about error information.
              'Unable to load partial file: ' + ex.message
            )
          )
        }
      }
    }
  }

def components(self):
        '''

        '''
        with self._mutex:
            if not self._components:
                self._components = [c for c in self.children if c.is_component]
        return self._components

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


Question: // SetDetectorId sets the DetectorId field's value.

func (s *UnarchiveFindingsInput) SetDetectorId(v string) *UnarchiveFindingsInput {
	s.DetectorId = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question:
Generate a textual (horizontal) bar graph of this histogram.

@param maxBarLength the maximum bar length, or 0 if the bar length is to represent actual counts
@return the strings that make up the histogram

public List<String> getTextGraph( int maxBarLength ) {
        compute();
        if (maxBarLength < 1) maxBarLength = (int)this.getMaximumCount();
        final float barLengthForHundredPercent = this.buckets.isEmpty() ? maxBarLength : 100.0f * maxBarLength
                                                                                / getMaximumPercentage();
        final String fullLengthBar = StringUtil.createString('*', (int)barLengthForHundredPercent);
        List<String> result = new LinkedList<String>();
        // First calculate the labels and the max length ...
        int maxLowerBoundLength = 0;
        int maxUpperBoundLength = 0;
        for (Bucket bucket : this.buckets) {
            maxLowerBoundLength = Math.max(bucket.getLowerBound().toString().length(), maxLowerBoundLength);
            maxUpperBoundLength = Math.max(bucket.getUpperBound().toString().length(), maxUpperBoundLength);
        }

        // Create the header ...
        int rangeWidth = 1 + maxLowerBoundLength + 3 + maxUpperBoundLength + 1;
        int barWidth = maxBarLength + 20;
        result.add(StringUtil.justifyLeft("Ranges", rangeWidth, ' ') + " Distribution");
        result.add(StringUtil.createString('-', rangeWidth) + ' ' + StringUtil.createString('-', barWidth));
        for (Bucket bucket : this.buckets) {
            float percent = bucket.getPercentageOfValues();
            long number = bucket.getNumberOfValues();
            StringBuilder sb = new StringBuilder();
            sb.append("[");
            sb.append(StringUtil.justifyLeft(bucket.getLowerBound().toString(), maxLowerBoundLength, ' '));
            sb.append(" - ");
            sb.append(StringUtil.justifyLeft(bucket.getUpperBound().toString(), maxUpperBoundLength, ' '));
            sb.append("] ");
            int barLength = Math.max((int)(barLengthForHundredPercent * percent / 100.0f), 0);
            if (barLength == 0 && number != 0) barLength = 1; // make sure there is a bar for all non-zero buckets
            sb.append(fullLengthBar.substring(0, barLength));
            if (number != 0) {
                sb.append(" ");
                sb.append(number);
                sb.append(" (");
                sb.append(new DecimalFormat("###.#").format(percent));
                sb.append("%)");
            }
            result.add(sb.toString());
        }
        return result;
    }

protected void validate(String operationType) throws Exception
	{
		super.validate(operationType);

		MPSDouble br_cpu_usage_validator = new MPSDouble();
		br_cpu_usage_validator.validate(operationType, br_cpu_usage, "\"br_cpu_usage\"");

		MPSDouble br_memory_usage_validator = new MPSDouble();
		br_memory_usage_validator.validate(operationType, br_memory_usage, "\"br_memory_usage\"");

		MPSDouble wan_out_validator = new MPSDouble();
		wan_out_validator.validate(operationType, wan_out, "\"wan_out\"");

		MPSDouble lan_out_validator = new MPSDouble();
		lan_out_validator.validate(operationType, lan_out, "\"lan_out\"");

		MPSString upsince_validator = new MPSString();
		upsince_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 128);
		upsince_validator.setConstraintMinStrLen(MPSConstants.GENERIC_CONSTRAINT, 1);
		upsince_validator.validate(operationType, upsince, "\"upsince\"");

		MPSString ha_peer_state_validator = new MPSString();
		ha_peer_state_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 32);
		ha_peer_state_validator.setConstraintMinStrLen(MPSConstants.GENERIC_CONSTRAINT, 1);
		ha_peer_state_validator.validate(operationType, ha_peer_state, "\"ha_peer_state\"");

		MPSString ha_state_validator = new MPSString();
		ha_state_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 32);
		ha_state_validator.setConstraintMinStrLen(MPSConstants.GENERIC_CONSTRAINT, 1);
		ha_state_validator.validate(operationType, ha_state, "\"ha_state\"");

		MPSIPAddress ha_peer_ip_address_validator = new MPSIPAddress();
		ha_peer_ip_address_validator.validate(operationType, ha_peer_ip_address, "\"ha_peer_ip_address\"");

		MPSDouble ha_peer_id_validator = new MPSDouble();
		ha_peer_id_validator.validate(operationType, ha_peer_id, "\"ha_peer_id\"");

		MPSString operation_status_validator = new MPSString();
		operation_status_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 128);
		operation_status_validator.validate(operationType, operation_status, "\"operation_status\"");

		MPSString bypass_validator = new MPSString();
		bypass_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 128);
		bypass_validator.validate(operationType, bypass, "\"bypass\"");

		MPSString bandwidth_mode_validator = new MPSString();
		bandwidth_mode_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 128);
		bandwidth_mode_validator.validate(operationType, bandwidth_mode, "\"bandwidth_mode\"");

		MPSDoubleLong bandwidth_limit_validator = new MPSDoubleLong();
		bandwidth_limit_validator.validate(operationType, bandwidth_limit, "\"bandwidth_limit\"");

		MPSIPAddress havmip_validator = new MPSIPAddress();
		havmip_validator.validate(operationType, havmip, "\"havmip\"");

		MPSString acl_connections_validator = new MPSString();
		acl_connections_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 32);
		acl_connections_validator.validate(operationType, acl_connections, "\"acl_connections\"");

		MPSString unacl_connections_validator = new MPSString();
		unacl_connections_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 32);
		unacl_connections_validator.validate(operationType, unacl_connections, "\"unacl_connections\"");

		MPSString connected_plugins_validator = new MPSString();
		connected_plugins_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 32);
		connected_plugins_validator.validate(operationType, connected_plugins, "\"connected_plugins\"");

		MPSString max_plugins_validator = new MPSString();
		max_plugins_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 32);
		max_plugins_validator.validate(operationType, max_plugins, "\"max_plugins\"");

		MPSDouble wan_in_validator = new MPSDouble();
		wan_in_validator.validate(operationType, wan_in, "\"wan_in\"");

		MPSDouble lan_in_validator = new MPSDouble();
		lan_in_validator.validate(operationType, lan_in, "\"lan_in\"");

		MPSDouble wan_out_prev_validator = new MPSDouble();
		wan_out_prev_validator.validate(operationType, wan_out_prev, "\"wan_out_prev\"");

		MPSDouble lan_out_prev_validator = new MPSDouble();
		lan_out_prev_validator.validate(operationType, lan_out_prev, "\"lan_out_prev\"");

		MPSDouble wan_in_prev_validator = new MPSDouble();
		wan_in_prev_validator.validate(operationType, wan_in_prev, "\"wan_in_prev\"");

		MPSDouble lan_in_prev_validator = new MPSDouble();
		lan_in_prev_validator.validate(operationType, lan_in_prev, "\"lan_in_prev\"");

		MPSDouble prev_poll_time_validator = new MPSDouble();
		prev_poll_time_validator.validate(operationType, prev_poll_time, "\"prev_poll_time\"");

		MPSIPAddress apa_ip_address_validator = new MPSIPAddress();
		apa_ip_address_validator.setConstraintIsReq(MPSConstants.ADD_CONSTRAINT, true);
		apa_ip_address_validator.validate(operationType, apa_ip_address, "\"apa_ip_address\"");

		MPSIPAddress apa_netmask_validator = new MPSIPAddress();
		apa_netmask_validator.setConstraintIsReq(MPSConstants.ADD_CONSTRAINT, true);
		apa_netmask_validator.validate(operationType, apa_netmask, "\"apa_netmask\"");

		MPSIPAddress apa_gateway_validator = new MPSIPAddress();
		apa_gateway_validator.setConstraintIsReq(MPSConstants.ADD_CONSTRAINT, true);
		apa_gateway_validator.validate(operationType, apa_gateway, "\"apa_gateway\"");

		MPSIPAddress plugin_ip_address_validator = new MPSIPAddress();
		plugin_ip_address_validator.setConstraintIsReq(MPSConstants.ADD_CONSTRAINT, true);
		plugin_ip_address_validator.validate(operationType, plugin_ip_address, "\"plugin_ip_address\"");

		MPSDouble system_load_validator = new MPSDouble();
		system_load_validator.validate(operationType, system_load, "\"system_load\"");

		MPSDouble active_connections_validator = new MPSDouble();
		active_connections_validator.validate(operationType, active_connections, "\"active_connections\"");

		MPSIPAddress mgmt_ip_address_validator = new MPSIPAddress();
		mgmt_ip_address_validator.validate(operationType, mgmt_ip_address, "\"mgmt_ip_address\"");

		MPSString license_validator = new MPSString();
		license_validator.setConstraintMaxStrLen(MPSConstants.GENERIC_CONSTRAINT, 64);
		license_validator.setConstraintMinStrLen(MPSConstants.GENERIC_CONSTRAINT, 1);
		license_validator.validate(operationType, license, "\"license\"");

	}

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


Question: Send the entire media stream in a single request.

def __SendMediaBody(self, start, additional_headers=None):
        """"""
        self.EnsureInitialized()
        if self.total_size is None:
            raise exceptions.TransferInvalidError(
                'Total size must be known for SendMediaBody')
        body_stream = stream_slice.StreamSlice(
            self.stream, self.total_size - start)

        request = http_wrapper.Request(url=self.url, http_method='PUT',
                                       body=body_stream)
        request.headers['Content-Type'] = self.mime_type
        if start == self.total_size:
            # End of an upload with 0 bytes left to send; just finalize.
            range_string = 'bytes */%s' % self.total_size
        else:
            range_string = 'bytes %s-%s/%s' % (start, self.total_size - 1,
                                               self.total_size)

        request.headers['Content-Range'] = range_string
        if additional_headers:
            request.headers.update(additional_headers)

        return self.__SendMediaRequest(request, self.total_size)

protected function processAllFiles($models)
    {
        foreach ($models as $model) {
            foreach ($model->getMediaFiles() as $file) {
                $file->reprocess();
            }
        }
    }

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


Question:
Enables resource duplication via new form.

 - Adds a duplicate action button.
 - Preloads a duplicated resource on `:new` to pre-fill the form fields.

 No return.

def enable_resource_duplication_via_form
      action_item(*compatible_action_item_parameters) do
        if controller.action_methods.include?('new') && authorized?(ActiveAdmin::Auth::CREATE, active_admin_config.resource_class)
          link_to(I18n.t(:duplicate_model, default: "Duplicate %{model}", scope: [:active_admin], model: active_admin_config.resource_label), action: :new, _source_id: resource.id)
        end
      end

      controller do
        before_action only: :new do
          if !params[:_source_id].blank?
            source = resource_class.find(params[:_source_id])
            @resource ||= source.amoeba_dup if source
          end
        end
      end
    end

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

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


Question:
Returns a literal for a bit value that can be safely used in SQL statements.

@param string|null $bits The bit value.

@return string

public static function quoteBit(?string $bits): string
  {
    if ($bits===null || $bits==='')
    {
      return 'null';
    }

    return "b'".self::$mysqli->real_escape_string($bits)."'";
  }

function read_extension()
	{
    	$this->getbytes(1);
    	switch($this->buffer[0])
    	{
			case 0xf9:
				if($this->debug) print "Skipping Graphic Control Extension.\n
";
	    		$this->getbytes(6);
	   			break;
			case 0xfe:
				if($this->debug) print "Skipping Comment Extension.\n
";
	    		for (;;)
	    		{
					$this->getbytes(1);
                	if (($u = $this->buffer[0]) == 0)
		    			break;
					$this->getbytes($u);
	    		}
	    		break;
			case 0x01:
				if($this->debug) print "Skipping Plain Text Extension.\n
";
	    		$this->getbytes(13);
	    		for (;;)
	    		{
					$this->getbytes(0);
                	if (($u = $this->buffer[0]) == 0)
		    			break;
					$this->getbytes($u);
	    		}
				break;
       		case 0xff:
				if($this->debug) print "Skipping Application Extension.\n
";
	    		$this->getbytes(9);
	    		$this->getbytes(3);
	    		for (;;)
	    		{
					$this->getbytes(1);
                	if (!$this->buffer[0])
                		break;
                	$this->getbytes($this->buffer[0]);
            	}
				break;
			default:
				if($this->debug) print "Skipping unrecognized extension.\n
";
	    		for (;;)
	    		{
					$this->getbytes(1);
        			if(!$this->buffer[0])
        				break;
					$this->getbytes($this->buffer[0]);
				}
    	}
	}

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


Question:
启动服务

@return $this

public function start()
    {
        if (!$this->httpEnable) {
            parent::start();
            return $this;
        }

        if (static::mode == 'console') {
            $this->beforeSwooleStart();
            $this->onWorkerStart(null, null);
        } else {
            //开启一个http服务器
            $mode = $this->config->get('server.mode', SWOOLE_PROCESS);
            $this->server = new \swoole_http_server($this->httpSocketName, $this->httpPort, $mode);
            $this->server->on('Start', [$this, 'onStart']);
            $this->server->on('WorkerStart', [$this, 'onWorkerStart']);
            $this->server->on('WorkerStop', [$this, 'onWorkerStop']);
            $this->server->on('Task', [$this, 'onTask']);
            $this->server->on('Finish', [$this, 'onFinish']);
            $this->server->on('PipeMessage', [$this, 'onPipeMessage']);
            $this->server->on('WorkerError', [$this, 'onWorkerError']);
            $this->server->on('ManagerStart', [$this, 'onManagerStart']);
            $this->server->on('ManagerStop', [$this, 'onManagerStop']);
            $this->server->on('request', [$this, 'onRequest']);
            $this->server->on('Shutdown', [$this, 'onShutdown']);
            $set = $this->setServerSet();
            $set['daemonize'] = self::$daemonize ? 1 : 0;
            $this->server->set($set);
            $this->beforeSwooleStart();
            $this->server->start();
        }

        return $this;
    }

public function api(array $attributes, Closure $callback)
    {
        $attributes['prefix'] = array_key_exists('prefix', $attributes) ? sprintf('%s/%s', 'api', $attributes['prefix']) : 'api';
        parent::group($attributes, $callback);
    }

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


Question:
执行该Action

@param string $action 操作名称
@param string $callback 回调方法
@return string|array

public function run($action, $callback = null)
    {
        if ($action == 'config') {
            $result = $this->options;
        } else if (in_array($action, ['upload-file', 'upload-image'])) {
            $result = $this->upload($action);
        } else if (in_array($action, ['list-image', 'list-file'])) {
            $result = $this->lists($action);
        } else if ($action == 'catch-image') {
            $result = $this->uploadCrawler();
        } else if ($action == 'upload-scrawl') {//涂鸦上传
            $result = $this->uploadScrawl();
        } else {
            $result = ['state' => 'Request address error'];
        }
        if (is_null($callback)) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return $result;
        } else {
            Yii::$app->response->format = Response::FORMAT_JSONP;
            return ['callback' => $callback, 'data' => $result];
        }
    }

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

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


Question:
Returns a DevInfo instance, a named tuple with the following items:
        - bustype: one of BUS_USB, BUS_HIL, BUS_BLUETOOTH or BUS_VIRTUAL
        - vendor: device's vendor number
        - product: device's product number

def getInfo(self):

        devinfo = _hidraw_devinfo()
        self._ioctl(_HIDIOCGRAWINFO, devinfo, True)
        return DevInfo(devinfo.bustype, devinfo.vendor, devinfo.product)

def get_version() :
    ""
    major = ct.c_int()
    minor = ct.c_int()
    micro = ct.c_int()
    dbus.dbus_get_version(ct.byref(major), ct.byref(minor), ct.byref(micro))
    return \
        (major.value, minor.value, micro.value)

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


Question:
Eagerly load the relationship on a set of models.

@param  array     $models
@param  string    $name
@param  \Closure  $constraints
@return array

protected function loadRelation(array $models, $name, Closure $constraints)
    {
        $relation = $this->getRelation($name);

        $relation->addEagerConstraints($models);

        call_user_func($constraints, $relation);

        $models = $relation->initRelation($models, $name);

        $results = $relation->getEager();

        return $relation->match($models, $results, $name);
    }

public function prepareLinks() {
		$this[ Argument::LINKS ] = $this->doReplacements( $this[ Argument::LINKS ] );

		return $this;
	}

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


Question: this function will setup a new pump as a daemon

function (emit) {
    ipc.send({
      cmd : 'setup',
      emit: emit,
      daemon: process.pid,
      message: errorBuffer === "" ? null : errorBuffer
    });
  }

func (pin Pin) DutyCycle(dutyLen, cycleLen uint32) {
	SetDutyCycle(pin, dutyLen, cycleLen)
}

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


Question:
Multiply
@param YearMonthDurationValue $a
@param double $b
@return YearMonthDurationValue

public static function Multiply( $a, $b )
	{
		if ( ! is_numeric( $b ) )
			throw new \InvalidArgumentException( "Division denominator is not a number" );

		if ( is_nan( $b ) )
			throw XPath2Exception::withErrorCode( "FOCA0005", Resources::FOCA0005 );

		if ( $b == INF || $b == -INF )
			throw XPath2Exception::withErrorCode( "FODT0002", Resources::FODT0002 );

		if ( ! $a instanceof YearMonthDurationValue )
			throw new ArgumentException("$a");

		// Create a new interval with the multiplied days. ->days is created by the ->diff function to hold the total days.
		$totalMonths = floor( 0.5 + ( $a->getTotalMonths() * $b ) );
		$invert = 0 > $totalMonths;
		$totalMonths = abs( $totalMonths );
		$years = intval( $totalMonths / 12 );
		$months = $totalMonths % 12;

		$di = new \DateInterval( sprintf( "P%02sY%02sM", $years, $months ) );
		$di->hasValue = $totalMonths != 0;
		$di->invert = $invert;
		$di->microseconds = 0;

		return new YearMonthDurationValue( $di );
	}

func createFromSource(prSpec plan.ProcedureSpec, dsid execute.DatasetID, a execute.Administration) (execute.Source, error) {
	spec := prSpec.(*inputs.FromProcedureSpec)
	var w execute.Window
	bounds := a.StreamContext().Bounds()
	if bounds == nil {
		return nil, errors.New("nil bounds passed to from")
	}

	if spec.WindowSet {
		w = execute.Window{
			Every:  execute.Duration(spec.Window.Every),
			Period: execute.Duration(spec.Window.Period),
			Round:  execute.Duration(spec.Window.Round),
			Start:  bounds.Start,
		}
	} else {
		duration := execute.Duration(bounds.Stop) - execute.Duration(bounds.Start)
		w = execute.Window{
			Every:  duration,
			Period: duration,
			Start:  bounds.Start,
		}
	}
	currentTime := w.Start + execute.Time(w.Period)

	deps := a.Dependencies()[inputs.FromKind].(storage.Dependencies)
	req := query.RequestFromContext(a.Context())
	if req == nil {
		return nil, errors.New("missing request on context")
	}
	orgID := req.OrganizationID

	var bucketID platform.ID
	// Determine bucketID
	switch {
	case spec.Bucket != "":
		b, ok := deps.BucketLookup.Lookup(orgID, spec.Bucket)
		if !ok {
			return nil, fmt.Errorf("could not find bucket %q", spec.Bucket)
		}
		bucketID = b
	case len(spec.BucketID) != 0:
		err := bucketID.DecodeFromString(spec.BucketID)
		if err != nil {
			return nil, err
		}
	}

	return storage.NewSource(
		dsid,
		deps.Reader,
		storage.ReadSpec{
			OrganizationID:  orgID,
			BucketID:        bucketID,
			Predicate:       spec.Filter,
			PointsLimit:     spec.PointsLimit,
			SeriesLimit:     spec.SeriesLimit,
			SeriesOffset:    spec.SeriesOffset,
			Descending:      spec.Descending,
			OrderByTime:     spec.OrderByTime,
			GroupMode:       storage.ToGroupMode(spec.GroupMode),
			GroupKeys:       spec.GroupKeys,
			AggregateMethod: spec.AggregateMethod,
		},
		*bounds,
		w,
		currentTime,
	), nil
}

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


Question: // Delete takes name of the replicationController and deletes it. Returns an error if one occurs.

func (c *FakeReplicationControllers) Delete(name string, options *v1.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewDeleteAction(replicationcontrollersResource, c.ns, name), &corev1.ReplicationController{})

	return err
}

public function getDeleteRequest($ids)
    {
        return new StorageDataRequest(
            [$this->sourceDataAdapter, $this->cacheDataAdapter, $ids],
            function (DataAdapterInterface $sourceData, DataAdapterInterface $cacheData, $ids) {
                $request = $sourceData->getDeleteRequest($ids);
                $request->send();
                $result = $request->fetch();
                $cacheData->getDeleteRequest($ids)->send();

                return $result;
            }
        );
    }

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


Question:
Converts the response to given type. Currently just
`array` is supported.

@param string $type
@return mixed

public function to($type) {
		if ($type === 'array') {
			$result = [];

			foreach (['status', 'message', 'data', 'code'] as $field) {
				if ($this->{"_{$field}"} !== null || $field === 'data') {
					$result[$field] = $this->{"_{$field}"};
				}
			}
			return $result;
		}
		throw new Exception("Cannot convert to type `{$type}`.");
	}

public static function SelectValuesWithParamAndResolver( $xpath, $resolver, $vars )
	{
		/**
		 * @var XPath2NodeIterator $iter
		 */
		$iter = XPath2NodeIterator::Create( Compile( $xpath, $resolver )->EvaluateWithVars( null, $vars ) );
		while ( $iter->MoveNext() )
		{
			yield $iter->getCurrent()->GetTypedValue();
		}
	}

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


Question:
Get a single wallet.

        @param the name of the wallet.
        @return the wallet's total.
        @raise ServerError

def get_wallet(self, wallet_name):

        response = make_request(
            '{}wallet/{}'.format(self.url, wallet_name),
            timeout=self.timeout,
            client=self._client)
        try:
            total = response['total']
            return {
                'credit': response['credit'],
                'limit': response['limit'],
                'total': WalletTotal(
                    limit=total['limit'],
                    budgeted=total['budgeted'],
                    available=total['available'],
                    unallocated=total['unallocated'],
                    usage=total['usage'],
                    consumed=total['consumed'])
            }
        except Exception as exc:
            log.error(
                'cannot get wallet from server: {!r}'.format(exc))
            raise ServerError(
                'unable to get list of wallets: {!r}'.format(exc))

def submit_query_request(end_point, *args, **kwargs):
    """"""
    ev_limit = kwargs.pop('ev_limit', 10)
    best_first = kwargs.pop('best_first', True)
    tries = kwargs.pop('tries', 2)
    # This isn't handled by requests because of the multiple identical agent
    # keys, e.g. {'agent': 'MEK', 'agent': 'ERK'} which is not supported in
    # python, but is allowed and necessary in these query strings.
    # TODO because we use the API Gateway, this feature is not longer needed.
    # We should just use the requests parameters dict.
    query_str = '?' + '&'.join(['%s=%s' % (k, v) for k, v in kwargs.items()
                                if v is not None]
                               + list(args))
    return submit_statement_request('get', end_point, query_str,
                                    ev_limit=ev_limit, best_first=best_first,
                                    tries=tries)

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


Question: Name the queue with the given string

public function withName(string $name): self
    {
        $self = clone $this;
        $self->name = $name;

        return $self;
    }

def populate_event_que(self, que_obj):

        for ip in self.obj_dict:
            drvr_obj = self.obj_dict.get(ip).get('drvr_obj')
            drvr_obj.populate_event_que(que_obj)

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


Question:
Iterates over an array of children collections, creates them.
This function is recursive!

@param $children
@param $userId
@param null $parent
@param string $namespace

@return array

private function iterateOverCollections($children, $userId, $parent = null, $namespace = '')
    {
        $format = ('' !== $namespace ? '%s.%s' : '%s%s');
        $collections = [];
        foreach ($children as $collectionKey => $collectionItem) {
            $key = sprintf($format, $namespace, $collectionKey);
            $collections[$key] = $this->getOrCreateCollection(
                $key,
                $collectionItem['meta_title'],
                $userId,
                $parent
            )->getId();

            if (array_key_exists('collections', $collectionItem)) {
                $childCollections = $this->iterateOverCollections(
                    $collectionItem['collections'],
                    $userId,
                    $collections[$key],
                    $key
                );
                $collections = array_merge($collections, $childCollections);
            }
        }

        return $collections;
    }

public function previous(callable $callback = NULL) {
    $matches = [];
    foreach ($this->nodes as $node) {
      if ($match = $node->previous($callback)) {
        $matches[] = $match;
      }
    }
    return new NodeCollection($matches);
  }

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


Question:
Get the basket.

@throws \Exception|\RuntimeException

@return \Sonata\Component\Basket\BasketInterface

public function getBasket()
    {
        if (!$this->basket) {
            try {
                $this->basket = $this->basketFactory->load($this->customerSelector->get());
            } catch (\Exception $e) {
                // something went wrong while loading the basket
                throw $e;
            }
        }

        return $this->basket;
    }

def get_interface_detail_output_interface_ifHCInErrors(self, **kwargs):

        config = ET.Element("config")
        get_interface_detail = ET.Element("get_interface_detail")
        config = get_interface_detail
        output = ET.SubElement(get_interface_detail, "output")
        interface = ET.SubElement(output, "interface")
        interface_type_key = ET.SubElement(interface, "interface-type")
        interface_type_key.text = kwargs.pop('interface_type')
        interface_name_key = ET.SubElement(interface, "interface-name")
        interface_name_key.text = kwargs.pop('interface_name')
        ifHCInErrors = ET.SubElement(interface, "ifHCInErrors")
        ifHCInErrors.text = kwargs.pop('ifHCInErrors')

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

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


Question:
Looks for the description of a specific child resource.
@param type The type of the child resource
@param name The name of the instance
@return the description of the specific child resource or {@link #EMPTY} if no such resource exists.

public ResourceDescription getChildDescription(String type, String name) {
        if (hasChildrenDefined()) {
            List<Property> children = get("children").asPropertyList();
            for (Property child : children) {
                if (type.equals(child.getName()) && child.getValue().hasDefined(MODEL_DESCRIPTION)) {
                    List<Property> modelDescriptions = child.getValue().get(MODEL_DESCRIPTION).asPropertyList();
                    for (Property modelDescription : modelDescriptions) {
                        if (name.equals(modelDescription.getName())) {
                            return new ResourceDescription(modelDescription.getValue());
                        }
                    }
                }
            }
        }
        return EMPTY;
    }

public void marshall(DeviceDescription deviceDescription, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(deviceDescription.getArn(), ARN_BINDING);
            protocolMarshaller.marshall(deviceDescription.getAttributes(), ATTRIBUTES_BINDING);
            protocolMarshaller.marshall(deviceDescription.getDeviceId(), DEVICEID_BINDING);
            protocolMarshaller.marshall(deviceDescription.getEnabled(), ENABLED_BINDING);
            protocolMarshaller.marshall(deviceDescription.getRemainingLife(), REMAININGLIFE_BINDING);
            protocolMarshaller.marshall(deviceDescription.getType(), TYPE_BINDING);
            protocolMarshaller.marshall(deviceDescription.getTags(), TAGS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Add a new selector into this container.

@param FileSelector $selector new selector to add

@throws BuildException

@return void

public function appendSelector(FileSelector $selector)
    {
        if ($this->isReference()) {
            throw $this->noChildrenAllowed();
        }
        $this->selectorsList[] = $selector;
        $this->directoryScanner = null;
        $this->setChecked(false);
    }

func (m *Manager) loadImages() error {
	loadedImages := make(map[string]bool)
	for _, c := range m.services {
		exists, err := m.imageExists(c.Repo, c.Tag)
		if err != nil {
			return err
		}
		if exists {
			log.WithFields(logrus.Fields{
				"isvc": c.Name,
				"repo": c.Repo,
				"tag":  c.Tag,
			}).Debug("Found image for internal service")
			continue
		}
		localTar := path.Join(m.imagesDir, c.Repo, c.Tag+".tar.gz")
		imageRepoTag := c.Repo + ":" + c.Tag
		log := log.WithFields(logrus.Fields{
			"image": imageRepoTag,
		})
		if _, exists := loadedImages[imageRepoTag]; exists {
			continue
		}
		if _, err := os.Stat(localTar); err == nil {
			if err := docker.ImportImage(imageRepoTag, localTar); err != nil {
				return err
			}
			loadedImages[imageRepoTag] = true
			log.WithFields(logrus.Fields{
				"tarball": localTar,
			}).Debug("Loaded image from local tarball")
		} else {
			log.Debug("Pulling image")
			if err := docker.PullImage(imageRepoTag); err != nil {
				return fmt.Errorf("Failed to pull image %s: %s", imageRepoTag, err)
			}
			loadedImages[imageRepoTag] = true
			log.Info("Pulled image")
		}
	}
	return nil
}

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


Question:
Resets all benchmarks in the suite.

@name reset
@memberOf Benchmark.Suite
@returns {Object} The suite instance.

function resetSuite() {
      var event,
          suite = this,
          aborting = calledBy.abortSuite;

      if (suite.running && !aborting) {
        // No worries, `resetSuite()` is called within `abortSuite()`.
        calledBy.resetSuite = true;
        suite.abort();
        delete calledBy.resetSuite;
      }
      // Reset if the state has changed.
      else if ((suite.aborted || suite.running) &&
          (suite.emit(event = Event('reset')), !event.cancelled)) {
        suite.aborted = suite.running = false;
        if (!aborting) {
          invoke(suite, 'reset');
        }
      }
      return suite;
    }

def cast_out(self, klass):
        """"""
        if _debug: Any._debug("cast_out %r", klass)
        global _sequence_of_classes, _list_of_classes

        # check for a sequence element
        if (klass in _sequence_of_classes) or (klass in _list_of_classes):
            # build a sequence helper
            helper = klass()

            # make a copy of the tag list
            t = TagList(self.tagList[:])

            # let it decode itself
            helper.decode(t)

            # make sure everything was consumed
            if len(t) != 0:
                raise DecodingError("incomplete cast")

            # return what was built
            return helper.value

        # check for an array element
        elif klass in _array_of_classes:
            # build a sequence helper
            helper = klass()

            # make a copy of the tag list
            t = TagList(self.tagList[:])

            # let it decode itself
            helper.decode(t)

            # make sure everything was consumed
            if len(t) != 0:
                raise DecodingError("incomplete cast")

            # return what was built with Python list semantics
            return helper.value[1:]

        elif issubclass(klass, (Atomic, AnyAtomic)):
            # make sure there's only one piece
            if len(self.tagList) == 0:
                raise DecodingError("missing cast component")
            if len(self.tagList) > 1:
                raise DecodingError("too many cast components")

            if _debug: Any._debug("    - building helper: %r", klass)

            # a helper cooperates between the atomic value and the tag
            helper = klass(self.tagList[0])

            # return the value
            return helper.value

        else:
            if _debug: Any._debug("    - building value: %r", klass)

            # build an element
            value = klass()

            # make a copy of the tag list
            t = TagList(self.tagList[:])

            # let it decode itself
            value.decode(t)

            # make sure everything was consumed
            if len(t) != 0:
                raise DecodingError("incomplete cast")

            # return what was built
            return value

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


Question:
Returns the ContainsAll condition represented by the given JSON object or an empty
value if no such condition is found.

private static Optional<ICondition> asContainsAll( JsonObject json)
    {
    return
      json.containsKey( HAS_ALL_KEY)
      ? Optional.of( new ContainsAll( toIdentifiers( json.getJsonArray( HAS_ALL_KEY))))
      : Optional.empty();
    }

public void setDeserialization(Map<DeserializationFeature, Boolean> deserialization) {
        if (CollectionUtils.isNotEmpty(deserialization)) {
            this.deserialization = deserialization;
        }
    }

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


Question: Create an instance of {@link JAXBElement }{@code <}{@link MrowType }{@code >}}

@XmlElementDecl(namespace = "http://www.w3.org/1998/Math/MathML", name = "mrow")
    public JAXBElement<MrowType> createMrow(MrowType value) {
        return new JAXBElement<MrowType>(_Mrow_QNAME, MrowType.class, null, value);
    }

public void add(Collection<NrqlAlertCondition> conditions)
    {
        for(NrqlAlertCondition condition : conditions)
            this.conditions.put(condition.getId(), condition);
    }

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


Question:
Disconnects signals.
            Is called by self.finalize when the cti is deleted.

def _closeResources(self):

        self.viewBox.sigRangeChangedManually.disconnect(self.setAutoRangeOff)
        self.viewBox.sigRangeChanged.disconnect(self.refreshMinMax)

private function unlisten(string $channel): Promise
    {
        \assert(isset($this->listeners[$channel]), "Not listening on that channel");

        $emitter = $this->listeners[$channel];
        unset($this->listeners[$channel]);

        if (!$this->handle) {
            $promise = new Success; // Connection already closed.
        } else {
            $promise = new Coroutine($this->send([$this->handle, "unlistenAsync"], $channel));
        }

        $promise->onResolve([$emitter, "complete"]);
        return $promise;
    }

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


Question:
Reads header of object container
@throws AvroDataIOException if the file is not an Avro data file.

private function read_header()
  {
    $this->seek(0, AvroIO::SEEK_SET);

    $magic = $this->read(AvroDataIO::magic_size());

    if (strlen($magic) < AvroDataIO::magic_size())
      throw new AvroDataIOException(
        'Not an Avro data file: shorter than the Avro magic block');

    if (AvroDataIO::magic() != $magic)
      throw new AvroDataIOException(
        sprintf('Not an Avro data file: %s does not match %s',
                $magic, AvroDataIO::magic()));

    $this->metadata = $this->datum_reader->read_data(AvroDataIO::metadata_schema(),
                                                     AvroDataIO::metadata_schema(),
                                                     $this->decoder);
    $this->sync_marker = $this->read(AvroDataIO::SYNC_SIZE);
  }

func confLoader(serverType string) (caddy.Input, error) {
	if conf == "" {
		return nil, nil
	}

	if conf == "stdin" {
		return caddy.CaddyfileFromPipe(os.Stdin, serverType)
	}

	var contents []byte
	if strings.Contains(conf, "*") {
		// Let caddyfile.doImport logic handle the globbed path
		contents = []byte("import " + conf)
	} else {
		var err error
		contents, err = ioutil.ReadFile(conf)
		if err != nil {
			return nil, err
		}
	}

	return caddy.CaddyfileInput{
		Contents:       contents,
		Filepath:       conf,
		ServerTypeName: serverType,
	}, nil
}

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


Question:
create address from google maps api result

@param object $googleData Google single result
@return Address

public static function create(object $googleData) : Address
    {
        $build = new self($googleData);
        $address = $build->createAddressFromComponents();

        return $address;
    }

private function parseOptions(array $options): array
    {
        $child = $options['child'] ?? [];

        if (isset($options['header'])) {
            $options['extras'] = $options['extras'] ?? [];
            $options['extras'] = array_merge($options['extras'], ['header' => $options['header']]);
        }

        if (isset($options['divider'])) {
            $options['extras'] = $options['extras'] ?? [];
            $options['extras'] = array_merge($options['extras'], ['divider' => true]);
        }

        if (isset($options['icon'])) {
            $options['extras'] = $options['extras'] ?? [];
            $options['extras'] = array_merge($options['extras'], ['icon' => $options['icon']]);
        }

        if (isset($options['route']) && is_array($options['route'])) {
            $options['routeParameters'] = $options['route']['[parameters'] ?? [];
            $options['route'] = $options['route']['name'];
        }

        foreach ($this->parsers as $parser) {
            if ($result = $parser($options)) {
                $options = $result;
            }
        }

        unset($options['child']);

        return [
            'options' => $options,
            'child' => $child,
        ];
    }

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


Question:
// NewImageStreamTagEvaluator computes resource usage of ImageStreamsTags. Its sole purpose is to handle
// UPDATE admission operations on imageStreamTags resource.

func NewImageStreamTagEvaluator(store imagev1lister.ImageStreamLister, istGetter imagev1typedclient.ImageStreamTagsGetter) kquota.Evaluator {
	return &imageStreamTagEvaluator{
		store:     store,
		istGetter: istGetter,
	}
}

def update_function_configuration(self, vpc_config):

        LOG.info('Updating configuration for lambda function: %s', self.app_name)

        try:
            self.lambda_client.update_function_configuration(
                Environment=self.lambda_environment,
                FunctionName=self.app_name,
                Runtime=self.runtime,
                Role=self.role_arn,
                Handler=self.handler,
                Description=self.description,
                Timeout=int(self.timeout),
                MemorySize=int(self.memory),
                VpcConfig=vpc_config)

            if self.concurrency_limit:
                self.lambda_client.put_function_concurrency(
                    FunctionName=self.app_name,
                    ReservedConcurrentExecutions=self.concurrency_limit
                )
            else:
                self.lambda_client.delete_function_concurrency(FunctionName=self.app_name)

        except boto3.exceptions.botocore.exceptions.ClientError as error:
            if 'CreateNetworkInterface' in error.response['Error']['Message']:
                message = '{0} is missing "ec2:CreateNetworkInterface"'.format(self.role_arn)
                LOG.debug(message)
                raise SystemExit(message)

            raise
        LOG.info('Updating Lambda function tags')

        lambda_arn = get_lambda_arn(self.app_name, self.env, self.region)
        self.lambda_client.tag_resource(Resource=lambda_arn, Tags={'app_group': self.group, 'app_name': self.app_name})

        LOG.info("Successfully updated Lambda configuration.")

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


Question:
Return the found in use vars in tpl.

@param $template_identifier
@return array

private function _getRequiredVars( $template_identifier )
	{
		if ( !( isset( $this->_available_templates[$template_identifier] ) ) )
		{
			trigger_error( "Template identifier not found.", E_USER_ERROR );
		}

		$template_path = ROOT_PATH.'/'.$this->_available_templates[$template_identifier];

		if ( !( $template_source = file_get_contents( $template_path ) ) )
		{
			trigger_error( "{$template_path} not found.", E_USER_ERROR );
		}

		if ( !( preg_match_all( '/{.*\$([a-z_\-]*).*}/', $template_source, $matchs) ) )
		{
			trigger_error( "Not found in use vars in the tpl source.", E_USER_WARNING );
		}

		$required_vars = array_unique( $matchs[1] );

		// Remove url.
		unset( $required_vars[array_search( 'url', $required_vars )] );

		return $required_vars;
	}

protected static function addPullClass(&$htmlOptions)
    {
        $pull = TbArray::popValue('pull', $htmlOptions);
        if (!empty($pull)) {
            self::addCssClass('pull-' . $pull, $htmlOptions);
        }
    }

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