Question: Read worldist object from cldf dataset.

def _cldf2wordlist(dataset, row='parameter_id', col='language_id'):
    """"""
    return lingpy.Wordlist(_cldf2wld(dataset), row=row, col=col)

def crl_distribution_points(self):

        if self._crl_distribution_points is None:
            self._crl_distribution_points = self._get_http_crl_distribution_points(self.crl_distribution_points_value)
        return self._crl_distribution_points

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


Question: Create 1d-array containing all disctinct models from ``tasklist``.

def _flatten_models(tasklist):
        "  "
        ans = gvar.BufferDict()
        for task, mlist in tasklist:
            if task != 'fit':
                continue
            for m in mlist:
                id_m = id(m)
                if id_m not in ans:
                    ans[id_m] = m
        return ans.buf.tolist()

def to_json(self, incl_uniqueid=False):

        lst = []
        for context in _contexts:
            lst += [v.to_json(incl_uniqueid=incl_uniqueid)
                    for v in self.filter(context=context,
                                         check_visible=False,
                                         check_default=False).to_list()]
        return lst

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


Question: // Slug returns the slug format for this BuildConfig (User/Name)

func (b *BuildConfig) Slug() string {
	return fmt.Sprintf("%s/%s", b.User, b.Name)
}

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:
Open a panel
@method openPanel
@param {Integer} nIndex The position of the Panel.
@return {Boolean} whether action resulted in opening a panel
that was previously closed

function(nIndex) {
            var ePanelNode = this._panels[nIndex];
            if(!ePanelNode) {return false;} // invalid node
            if(YUD.hasClass(ePanelNode.firstChild, this.CLASSES.ACTIVE)) {return false;} // already open
            this._onClick(ePanelNode.firstChild);
            return true;
        }

def _set_menu_toggles(self):
        """"""

        toggles = [
            (self.main_toolbar, "main_window_toolbar", _("Main toolbar")),
            (self.macro_toolbar, "macro_toolbar", _("Macro toolbar")),
            (self.macro_panel, "macro_panel", _("Macro panel")),
            (self.attributes_toolbar, "attributes_toolbar",
             _("Format toolbar")),
            (self.find_toolbar, "find_toolbar", _("Find toolbar")),
            (self.widget_toolbar, "widget_toolbar", _("Widget toolbar")),
            (self.entry_line_panel, "entry_line_panel", _("Entry line")),
            (self.table_list_panel, "table_list_panel", _("Table list")),
        ]

        for toolbar, pane_name, toggle_label in toggles:
            # Get pane from aui manager
            pane = self._mgr.GetPane(pane_name)

            # Get menu item to toggle
            toggle_id = self.menubar.FindMenuItem(_("View"), toggle_label)
            if toggle_id != -1:
                # Check may fail if translation is incomplete
                toggle_item = self.menubar.FindItemById(toggle_id)

                # Adjust toggle to pane visibility
                toggle_item.Check(pane.IsShown())

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


Question:
判断部署次数，并进行初始化目录
@param dir
@param callBack

function getBaesVsersion(dir, callBack) {
        fs.readdir(`${dir}/`, (err, files) => {
            let dirList = [],
                baseVersion;
            if (err) {
                console.log('第一次部署中...');
                fs.mkdir(dir, () => {
                    callBack([1, 1, 1]);
                });
            } else {
                if (files.length == 0) {
                    files = ['1.1.1'];
                }
                console.log('部署目标已存在，正在更新中...');
                files.forEach((v)=> {
                    let intV = v.replace(/\./g, '');
                    if (!!parseInt(intV)) {
                        dirList.push(intV);
                    }
                });
                baseVersion = Math.max.apply(null, dirList).toString().split('');
                callBack(baseVersion);
            }
        });
    }

func (sw *SyslogHandler) dial() error {
	if sw.syslogProtocol == "" || sw.syslogProtocol == "unix" {
		logTypes := []string{"unixgram", "unix"}
		var logPaths []string
		if sw.syslogAddr != "" {
			logPaths = []string{sw.syslogAddr}
		} else {
			logPaths = []string{"/dev/log", "/var/run/syslog", "/var/run/log"}
		}
		for _, network := range logTypes {
			for _, path := range logPaths {
				conn, err := net.Dial(network, path)
				if err != nil {
					continue
				}
				sw.syslogConnection = conn
				return nil
			}
		}
		return fmt.Errorf("Could not find listening syslog daemon")
	}

	connection, err := net.Dial(sw.syslogProtocol, sw.syslogAddr)
	if err != nil {
		return err
	}
	sw.syslogConnection = connection
	return nil
}

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


Question: // For the common "repo doesn't exist" case, use the error type that the client can recognize.

func castNoSuchNameError(err error, repoName string) error {
	switch errors.Cause(err).(type) {
	case idutil.NoSuchNameError:
		return libkb.RepoDoesntExistError{
			Name: repoName,
		}
	default:
		return err
	}
}

public static function UrlExsist ($url, $timeout = 30, $protocol_version = self::VERSION_1_1) {
		$result = static::HeadRequest($url, $timeout, $protocol_version);
		return isset($result['http']['status']['code']) && $result['http']['status']['code'] !== '404';
	}

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


Question:
Execute the command.

@param InputInterface $input
@param OutputInterface $output

@return void

protected function execute(InputInterface $input, OutputInterface $output)
    {
        $siteBuilder = new SiteBuilder(
            $this->filesystem,
            $this->viewFactory,
            $input->getOption('env'),
            $input->getOption('force')
        );

        $siteBuilder->build();

        $output->writeln("<info>Site was generated successfully.</info>");
    }

private boolean handleCommandImpl(String[] args) throws IOException, SQLException, Throwable {
		try {
			// Fork to background task
			if(args.length>0 && "&".equals(args[args.length-1])) {
				String[] newArgs;
				if(args.length==1) {
					newArgs = AoArrays.EMPTY_STRING_ARRAY;
				} else {
					newArgs = new String[args.length-1];
					System.arraycopy(args, 0, newArgs, 0, args.length-1);
				}
				ShellInterpreter shell=newShellInterpreter(in, out, err, newArgs);
				shell.parent=this;
				synchronized(jobs) {
					jobs.add(shell);
					if(isInteractive) {
						out.print('[');
						out.print(jobs.size());
						out.print("] ");
						out.println(shell.pid);
						out.flush();
					}
					shell.start();
				}
				return true;
			} else {
				return handleCommand(args);
			}
		} catch(ThreadDeath TD) {
			throw TD;
		} catch(Throwable T) {
			if(isInteractive) {
				ErrorPrinter.printStackTraces(T, err);
				err.flush();
				return true;
			} else throw T;
		}
	}

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


Question:
// FileCacheWithFormat creates a FileCache that uses a format string to generate
// filenames

func FileCacheWithFormat(dirname string, format string) Cache {
	return FileCacheWithNameFn(dirname, func(key string) string {
		return fmt.Sprintf(format, key)
	})
}

def sql_key(self, generation, sql, params, order, result_type,
                using='default'):

        # these keys will always look pretty opaque
        suffix = self.keygen.gen_key(sql, params, order, result_type)
        using = settings.DB_CACHE_KEYS[using]
        return '%s_%s_query_%s.%s' % (self.prefix, using, generation, suffix)

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


Question:
read a one-line value from a file with a similar name

@return value if successfull or null if not

public static function rolv($similarFileName, $match = "//", $replace = "")
    {
        $filename = preg_replace($match, $replace, $similarFileName);
        if (CommonFunctions::fileexists($filename) && CommonFunctions::rfts($filename, $buf, 1, 4096, false) && (($buf=trim($buf)) != "")) {
            return $buf;
        } else {
            return null;
        }
    }

public void moveThisFile(LineNumberReader reader, File fileDestDir, String strDestName)
    {
        try {
            File fileDest = new File(fileDestDir, strDestName);
            fileDest.createNewFile();
            FileOutputStream fileOut = new FileOutputStream(fileDest);
            m_writer = new PrintWriter(fileOut);

            this.moveSourceToDest(reader, m_writer);

            m_writer.close();
            fileOut.close();

        } catch (FileNotFoundException ex)  {
            ex.printStackTrace();
        } catch (IOException ex)    {
            ex.printStackTrace();
        }
    }

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


Question: Save `self.items` to `fn` in `self.path`.

def to_text(self, fn:str):
        ""
        with open(self.path/fn, 'w') as f: f.writelines([f'{o}\n' for o in self._relative_item_paths()])

func (c *Custom) Parse(files *map[string]*file.File, dirs **dir.Dir, config *SharedConfig) error {
	to := *files
	dirList := *dirs

	var newList []string
	for _, customFile := range c.Files {
		// get files from glob
		list, err := doublestar.Glob(customFile)
		if err != nil {
			return err
		}

		// insert files from glob into the new list
		newList = append(newList, list...)
	}

	// copy new list
	c.Files = newList

	// 0 files in the list
	if len(c.Files) == 0 {
		return errors.New("No files found")
	}

	// loop through files from glob
	for _, customFile := range c.Files {
		// gives error when file doesn't exist
		if !utils.Exists(customFile) {
			return fmt.Errorf("File [%s] doesn't exist", customFile)
		}

		cb := func(fpath string, d *godirwalk.Dirent) error {
			if config.Updater.Empty && !config.Updater.IsUpdating {
				log.Println("empty mode")
				return nil
			}

			// only files will be processed
			if d != nil && d.IsDir() {
				return nil
			}

			originalPath := fpath
			fpath = utils.FixPath(fpath)

			var fixedPath string
			if c.Prefix != "" || c.Base != "" {
				c.Base = strings.TrimPrefix(c.Base, "./")

				if strings.HasPrefix(fpath, c.Base) {
					fixedPath = c.Prefix + fpath[len(c.Base):]
				} else {
					if c.Base != "" {
						fixedPath = c.Prefix + fpath
					}
				}

				fixedPath = utils.FixPath(fixedPath)
			} else {
				fixedPath = utils.FixPath(fpath)
			}

			// check for excluded files
			for _, excludedFile := range c.Exclude {
				m, err := doublestar.Match(c.Prefix+excludedFile, fixedPath)
				if err != nil {
					return err
				}

				if m {
					return nil
				}
			}

			info, err := os.Stat(fpath)
			if err != nil {
				return err
			}

			if info.Name() == config.Output {
				return nil
			}

			// get file's content
			content, err := ioutil.ReadFile(fpath)
			if err != nil {
				return err
			}

			replaced := false

			// loop through replace list
			for _, r := range c.Replace {
				// check if path matches the pattern from property: file
				matched, err := doublestar.Match(c.Prefix+r.File, fixedPath)
				if err != nil {
					return err
				}

				if matched {
					for pattern, word := range r.Replace {
						content = []byte(strings.Replace(string(content), pattern, word, -1))
						replaced = true
					}
				}
			}

			// compress the content
			if config.Compression.Options != nil {
				content, err = config.Compression.Compress(content)
				if err != nil {
					return err
				}
			}

			dst := make([]byte, len(content)*4)
			for i := 0; i < len(content); i++ {
				dst[i*4] = byte('\\')
				dst[i*4+1] = byte('x')
				dst[i*4+2] = hextable[content[i]>>4]
				dst[i*4+3] = hextable[content[i]&0x0f]
			}

			f := file.NewFile()
			f.OriginalPath = originalPath
			f.ReplacedText = replaced
			f.Data = `[]byte("` + string(dst) + `")`
			f.Name = info.Name()
			f.Path = fixedPath
			f.Tags = c.Tags
			f.Base = c.Base
			f.Prefix = c.Prefix
			f.Modified = info.ModTime().String()

			if _, ok := to[fixedPath]; ok {
				f.Tags = to[fixedPath].Tags
			}

			// insert dir to dirlist so it can be created on b0x's init()
			dirList.Insert(path.Dir(fixedPath))

			// insert file into file list
			to[fixedPath] = f
			return nil
		}

		customFile = utils.FixPath(customFile)

		// unlike filepath.walk, godirwalk will only walk dirs
		f, err := os.Open(customFile)
		if err != nil {
			return err
		}

		defer f.Close()

		fs, err := f.Stat()
		if err != nil {
			return err
		}

		if fs.IsDir() {
			if err := godirwalk.Walk(customFile, &godirwalk.Options{
				Unsorted: true,
				Callback: cb,
			}); err != nil {
				return err
			}

		} else {
			if err := cb(customFile, nil); err != nil {
				return err
			}
		}
	}

	return nil
}

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


Question: // OpenIndex opens an index.

func (c *Client) OpenIndex(name string) *OpenIndexService {
	builder := NewOpenIndexService(c)
	builder.Index(name)
	return builder
}

func (ix *Reindexer) ScanFields(scanFields ...string) *Reindexer {
	ix.scanFields = scanFields
	return ix
}

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


Question: :meth:`WCacheStorage.get_cache` method implementation

def get_cache(self, decorated_function, *args, **kwargs):

		has_value = self.has(decorated_function, *args, **kwargs)
		cached_value = None
		if has_value is True:
			cached_value = self.get_result(decorated_function, *args, **kwargs)
		return WCacheStorage.CacheEntry(has_value=has_value, cached_value=cached_value)

public function storeImage(ImageInterface $image, ImagePathInterface $path) {
		$this->optimizerImageManipulator->manipulateImage($image, $path);
		$this->writeImageFile($image, $path);
	}

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


Question:
Stripped-down variant of awaitJoin used by timed joins. Tries
to help join only while there is continuous progress. (Caller
will then enter a timed wait.)

@param joiner the joining worker
@param task the task
@return task status on exit

final int helpJoinOnce(WorkQueue joiner, ForkJoinTask<?> task) {
        int s;
        while ((s = task.status) >= 0 &&
               (joiner.isEmpty() ?
                tryHelpStealer(joiner, task) :
                joiner.tryRemoveAndExec(task)) != 0)
            ;
        return s;
    }

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

        invalid_tree_records = dict()
        invalid_tq_records = dict()

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

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

                tree.update_node(job_record)

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

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

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

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


Question:
reload
@param $node_name

public function my_reload($node_name)
    {
        if ($node_name == getNodeName()) {
            get_instance()->server->reload();
        } else {
            if (array_key_exists($node_name, $this->client)) {
                $this->client[$node_name]->reload();
            }
        }
    }

func (s *DescribeNodeAssociationStatusInput) SetServerName(v string) *DescribeNodeAssociationStatusInput {
	s.ServerName = &v
	return s
}

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


Question: Try and find a package for the match

function findPackage(config, match) {
  var map = getPackageMap(config.relativeTo, config.packages);

  return _.reduce(map, function (prev, pkg) {

    // Resolve using last priority. Priority:
    // 1. package is a file
    // 2. package granularity (done by file depth)
    if (pkg.regexp.test(match) && (!prev || (pkg.dir && prev.dir && pkg.depth >= pkg.depth) || pkg.file)) {
      return pkg;
    } else {
      return prev;
    }

  }, null);
}

@SuppressWarnings("unchecked")
	public EList<IfcDocumentInformation> getRelatedDocuments() {
		return (EList<IfcDocumentInformation>) eGet(
				Ifc2x3tc1Package.Literals.IFC_DOCUMENT_INFORMATION_RELATIONSHIP__RELATED_DOCUMENTS, true);
	}

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


Question:
From JMS to semileptonic Fierz basis for Class V.
    `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.

def JMS_to_Fierz_nunu(C, ddll):
    """"""
    s = dflav[ddll[0]]
    b = dflav[ddll[1]]
    l = lflav[ddll[4:ddll.find('n')]]
    lp = lflav[ddll[ddll.find('_',5)+1:len(ddll)]]
    ind = ddll.replace('l_','').replace('nu_','')
    return {
        'F' + ind + 'nu' : C["VnudLL"][l, lp, s, b],
        'F' + ind + 'nup' : C["VnudLR"][l, lp, s, b]
        }

def get_schema_object(self, fully_qualified_name: str) -> 'BaseSchema':

        if fully_qualified_name not in self._schema_cache:
            spec = self.get_schema_spec(fully_qualified_name)

            if spec:
                try:
                    self._schema_cache[fully_qualified_name] = TypeLoader.load_schema(
                        spec.get(ATTRIBUTE_TYPE, None))(fully_qualified_name, self)
                except TypeLoaderError as err:
                    self.add_errors(
                        InvalidTypeError(fully_qualified_name, spec, ATTRIBUTE_TYPE,
                                         InvalidTypeError.Reason.TYPE_NOT_LOADED,
                                         err.type_class_name))

        return self._schema_cache.get(fully_qualified_name, None)

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


Question:
Generates training/dev data.

    Args:
      data_dir: a string
      tmp_dir: a string
      task_id: an optional integer
    Returns:
      shard or shards for which data was generated.

def generate_data(self, data_dir, tmp_dir, task_id=-1):

    tf.logging.info("generate_data task_id=%s" % task_id)
    encoder = self.get_or_create_vocab(data_dir, tmp_dir)
    assert task_id >= 0 and task_id < self.num_generate_tasks
    if task_id < self.num_train_shards:
      out_file = self.training_filepaths(
          data_dir, self.num_train_shards, shuffled=False)[task_id]
    else:
      out_file = self.dev_filepaths(
          data_dir, self.num_dev_shards,
          shuffled=False)[task_id - self.num_train_shards]
    generator_utils.generate_files(
        self.example_generator(encoder, tmp_dir, task_id), [out_file])
    generator_utils.shuffle_dataset([out_file])

def tar(self, appname, appversion):

        name_tmpl = '%(app)s-%(version)s-%(time)s.tar.bz2'
        time = utc.now()
        name = name_tmpl % {'app': appname,
                            'version': appversion,
                            'time': time.strftime('%Y-%m-%dT%H-%M')}

        if not os.path.exists(TARBALL_HOME):
            os.mkdir(TARBALL_HOME)
        tarball = os.path.join(TARBALL_HOME, name)
        tar_params = {'filename': tarball, 'folder': self.folder}
        tar_result = run('tar -C %(folder)s -cjf %(filename)s .' % tar_params)
        tar_result.raise_for_status()
        return Build(appname, appversion, time, tarball)

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


Question: Verify that an IP address is owned by GitHub.

def is_github_ip(ip_str):
    """"""
    if isinstance(ip_str, bytes):
        ip_str = ip_str.decode()

    ip = ipaddress.ip_address(ip_str)
    if ip.version == 6 and ip.ipv4_mapped:
        ip = ip.ipv4_mapped

    for block in load_github_hooks():
        if ip in ipaddress.ip_network(block):
            return True
    return False

func (r Network_Storage_Allowed_Host_IpAddress) GetResource() (resp datatypes.Network_Subnet_IpAddress, err error) {
	err = r.Session.DoRequest("SoftLayer_Network_Storage_Allowed_Host_IpAddress", "getResource", nil, &r.Options, &resp)
	return
}

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


Question:
Creates a number binding that computes the minimum value amongst elements.

@param numbers  the observable list of numbers.
@param supplier a {@code Supplier} whose result is returned if no value is present.

@return a number binding

public static NumberBinding min(final ObservableList<? extends Number> numbers, final Supplier<? extends Number> supplier) {
        return Bindings.createDoubleBinding(() -> numbers.stream().mapToDouble(Number::doubleValue).min().orElse(supplier.get().doubleValue()), numbers);
    }

func (w *HubWatcher) Watch(collection string, id interface{}, ch chan<- Change) {
	if id == nil {
		panic("watcher: cannot watch a document with nil id")
	}
	// We use a value of -2 to indicate that we don't know the state of the document.
	// -1 would indicate that we think the document is deleted (and won't trigger
	// a change event if the document really is deleted).
	w.sendAndWaitReq(reqWatch{
		key:          watchKey{collection, id},
		info:         watchInfo{ch, -2, nil},
		registeredCh: make(chan error),
	})
}

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


Question: // SetMaxResults sets the MaxResults field's value.

func (s *ListWorkGroupsInput) SetMaxResults(v int64) *ListWorkGroupsInput {
	s.MaxResults = &v
	return s
}

public void dataToField(ComponentCache componentCache, int iRowIndex, int iColumnIndex)
    {
        if (componentCache.m_rgcompoments[iColumnIndex] != null)
        {
            String string = null;
            if (componentCache.m_rgcompoments[iColumnIndex] instanceof JTextComponent)
                string = ((JTextComponent)componentCache.m_rgcompoments[iColumnIndex]).getText();
            if (componentCache.m_rgcompoments[iColumnIndex] instanceof JCheckBox)
                if (((JCheckBox)componentCache.m_rgcompoments[iColumnIndex]).isSelected())
                    string = "1";
            //xif (string != null) if (string.length() > 0)
            this.getModel().setValueAt(string, iRowIndex, iColumnIndex);
        }
    }

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


Question:
// NewPlugin takes a value that implements LoggerPlugin and wraps it with
// the appropriate methods to satisfy the OsqueryPlugin interface. Use this to
// easily create plugins implementing osquery loggers.

func NewPlugin(name string, fn LogFunc) *Plugin {
	return &Plugin{name: name, logFn: fn}
}

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

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

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


Question:
@param Contribution $contribution

@return array - The serialized representation of a contribution

public function serialize(Contribution $contribution)
    {
        $contributor = $contribution->getContributor();

        return [
            'id' => $contribution->getUuid(),
            'title' => $contribution->getTitle(),
            'text' => $contribution->getText(),
            'meta' => [
                'createdAt' => $contribution->getCreationDate()->format('Y-m-d H:i'),
                'creator' => null === $contributor ?
                    null :
                    $this->userSerializer->serialize($contributor, [Options::SERIALIZE_MINIMAL]),
            ],
        ];
    }

public function addParticipation($testIdentifier, $variationIdentifier)
    {
        Assert::string($testIdentifier, 'Test identifier must be a string');
        Assert::string($variationIdentifier, 'Variation name must be a string');

        $this->participations[$testIdentifier] = $variationIdentifier;
    }

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


Question:
Checks the config to see if you can collect certain information
@param  string $type the config value you want to check
@return boolean

private function canCollect($type) {
        if (!empty($this->config) && !empty($this->config['collect']) && !empty($this->config['collect'][$type])) {
            return $this->config['collect'][$type] === true;
        }
        return false;
    }

public function getSelector()
	{
		$direct_settings = array(
			'className', 'css', 'id', 'linkText', 'name', 'partialLinkText', 'tagName', 'xpath', 'label',
		);

		foreach ( $direct_settings as $direct_setting ) {
			if ( $this->$direct_setting ) {
				return array($direct_setting => $this->$direct_setting);
			}
		}

		if ( $this->how && $this->using ) {
			if ( !in_array($this->how, $direct_settings) ) {
				throw new AnnotationException(
					"FindBy annotation expects 'how' to be one of \\QATools\\QATools\\PageObject\\How class constants",
					AnnotationException::TYPE_INCORRECT_USAGE
				);
			}

			return array($this->how => $this->using);
		}

		throw new AnnotationException(
			sprintf(
				"FindBy annotation requires one of '%s' or both 'how' and 'using' parameters specified",
				implode("', '", $direct_settings)
			),
			AnnotationException::TYPE_INCORRECT_USAGE
		);
	}

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


Question:
Writes the bean to the {@code OutputStream}.
<p>
The type of the bean will be set in the message.

@param bean  the bean to output, not null
@param output  the output stream, not null
@throws IOException if an error occurs

public void write(Bean bean, OutputStream output) throws IOException {
        write(bean, true, output);
    }

private synchronized Collection<IResult> valuesToParameters(Process process, ValueMap<Output, OWLValue> values) throws NotYetImplementedException, OWLTranslationException
    {
        if (values.isEmpty())
        {
            return null;
        }
        Collection<IResult> parameters = new ArrayList<IResult>();
        Iterator<Entry<Output, OWLValue>> valuesIterator = values.iterator();
        while (valuesIterator.hasNext())
        {
            Entry<Output, OWLValue> valuesEntry = valuesIterator.next();
            final OWLSParameter parameter
                    = new OWLSParameter(
                            process.getOntology(),
                            valuesEntry.getKey().getName(),
                            valuesEntry.getValue());
            parameters.add(new IOutputValue()
            {
                @Override
                public IOutput getOutput()
                {
                    try
                    {
                        return output(parameter.name());
                    } catch (ModelException ex)
                    {
                        return null;
                    }
                }

                @Override
                public Object object() throws ModelException
                {
                    return parameter.object();
                }

                @Override
                public ISemanticIdentifier getSemanticAnnotation()
                {
                    return parameter.getSemanticAnnotation();
                }

                @Override
                public ISubject value() throws ModelException
                {
                    if (null != functionalityGrounding)
                    {
                        return functionalityGrounding.createOutput(parameter.object(), OWLSAtomicService.this).value();
                    }
                    throw new UnsupportedOperationException("Not supported yet.");
                }
            });
        }
        return parameters;
    }

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


Question:
Performs waiting using current callback.

@return $this
@throws WebDriver_Exception

public function execute()
    {
        $locator = $this->element->getLocator();
        if (null === $this->callback) {
            throw new WebDriver_Exception("Wait callback is undefined for element '{$locator}''");
        }
        for ($i = 0; $i < $this->timeout; $i++) {
            if (call_user_func($this->callback, $this->element())) {
                return $this;
            }
            sleep(1);
        }
        $message = "Provided state of element '{$locator}' is not reached after timeout";
        $message = ($this->errorMessage == null) ? $message : "{$message} with error: {$this->errorMessage}";
        throw new WebDriver_Exception($message);
    }

func (c *Client) WatchRetryStrategy(agentTag names.Tag) (watcher.NotifyWatcher, error) {
	var results params.NotifyWatchResults
	args := params.Entities{
		Entities: []params.Entity{{Tag: agentTag.String()}},
	}
	err := c.facade.FacadeCall("WatchRetryStrategy", args, &results)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if len(results.Results) != 1 {
		return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results))
	}
	result := results.Results[0]
	if result.Error != nil {
		return nil, errors.Trace(result.Error)
	}
	w := apiwatcher.NewNotifyWatcher(c.facade.RawAPICaller(), result)
	return w, nil
}

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


Question:
Concatenate multiple shell commands via logical implication ( && )
@return Shell The concatenated shell command

public static function sequence(...$items){
        $cmd = [];
        foreach ($items as $item) {
            $cmd[] = ($item instanceof static)?$item->getShellCommand():$item;
        }
        return new static(implode(' && ',$cmd));
    }

def capture_output(self, with_hook=True):
        """"""
        self.hooked = ''

        def display_hook(obj):
            # That's some dirty hack
            self.hooked += self.safe_better_repr(obj)
            self.last_obj = obj

        stdout, stderr = sys.stdout, sys.stderr
        if with_hook:
            d_hook = sys.displayhook
            sys.displayhook = display_hook

        sys.stdout, sys.stderr = StringIO(), StringIO()
        out, err = [], []
        try:
            yield out, err
        finally:
            out.extend(sys.stdout.getvalue().splitlines())
            err.extend(sys.stderr.getvalue().splitlines())
            if with_hook:
                sys.displayhook = d_hook

            sys.stdout, sys.stderr = stdout, stderr

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


Question:
/*
Given a segment, fetch its SegmentRange.
- If segment is part of startStreamCut / endStreamCut update startOffset and endOffset accordingly.
- If segment is not part of the streamCuts fetch the data using SegmentMetadataClient.

private SegmentRange getSegmentRange(final Segment segment, final StreamCut startStreamCut,
                                         final StreamCut endStreamCut) {
        SegmentRangeImpl.SegmentRangeImplBuilder segmentRangeBuilder = SegmentRangeImpl.builder()
                                                                                .segment(segment);
        if (startStreamCut.asImpl().getPositions().containsKey(segment) && endStreamCut.asImpl().getPositions().containsKey(segment)) {
            //use the meta data present in startStreamCut and endStreamCuts.
            segmentRangeBuilder.startOffset(startStreamCut.asImpl().getPositions().get(segment))
                               .endOffset(endStreamCut.asImpl().getPositions().get(segment));
        } else {
            //use segment meta data client to fetch the segment offsets.
            SegmentInfo r = segmentToInfo(segment);
            segmentRangeBuilder.startOffset(startStreamCut.asImpl().getPositions().getOrDefault(segment, r.getStartingOffset()))
                               .endOffset(endStreamCut.asImpl().getPositions().getOrDefault(segment, r.getWriteOffset()));
        }
        return segmentRangeBuilder.build();
    }

func IsChaincodeDeployed(chainid, ccName, ccVersion string, ccHash []byte, sccp sysccprovider.SystemChaincodeProvider) (bool, error) {
	qe, err := sccp.GetQueryExecutorForLedger(chainid)
	if err != nil {
		return false, fmt.Errorf("Could not retrieve QueryExecutor for channel %s, error %s", chainid, err)
	}
	defer qe.Done()

	// XXX We are leaking details of the LSCC table structure to other parts of the code, and this is terrible
	chaincodeDataBytes, err := qe.GetState("lscc", ccName)
	if err != nil {
		return false, fmt.Errorf("Could not retrieve state for chaincode %s on channel %s, error %s", ccName, chainid, err)
	}

	if chaincodeDataBytes == nil {
		return false, nil
	}

	chaincodeData := &ChaincodeData{}
	err = proto.Unmarshal(chaincodeDataBytes, chaincodeData)
	if err != nil {
		return false, fmt.Errorf("Unmarshalling ChaincodeQueryResponse failed, error %s", err)
	}
	return chaincodeData.CCVersion() == ccVersion && bytes.Equal(chaincodeData.Hash(), ccHash), nil
}

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


Question:
// ServiceName returns the context's service name. This value is valid for
// contexts created on both the client and the server. On the server this
// value is subject to the same restrictions as listed in the Service function.

func ServiceName(ctx context.Context) (string, bool) {
	v, ok := stringValue(ctx, ServiceKey)
	if !ok {
		v, ok = stringValue(ctx, StorageServiceKey)
	}
	return v, ok
}

func (_m *DBClient) AddDeviceService(ds models.DeviceService) (string, error) {
	ret := _m.Called(ds)

	var r0 string
	if rf, ok := ret.Get(0).(func(models.DeviceService) string); ok {
		r0 = rf(ds)
	} else {
		r0 = ret.Get(0).(string)
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(models.DeviceService) error); ok {
		r1 = rf(ds)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

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


Question:
likeExpression ::= identificationVariable ["NOT"] "LIKE" stringExpression

@return LikeExpressionNode

public function likeExpression()
    {
        $stringExpr = $this->identificationVariable();
        $not = false;

        if ($this->lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $not = true;
        }

        $this->match(Lexer::T_LIKE);

        $stringPattern = $this->stringExpression();

        $likeExpr = new LikeExpressionNode($stringExpr, $stringPattern);
        $likeExpr->setNot($not);

        return $likeExpr;
    }

def njsd(network, ref_gene_expression_dict, query_gene_expression_dict, gene_set):

    gene_jsd_dict = dict()
    reference_genes = ref_gene_expression_dict.keys()
    assert len(reference_genes) != 'Reference gene expression profile should have > 0 genes.'

    for gene in gene_set:
        if gene not in network.nodes:
            continue

        neighbors = find_neighbors(network, gene)

        query_expression_vec = get_neighbor_expression_vector(neighbors, query_gene_expression_dict)
        ref_expression_vec = get_neighbor_expression_vector(neighbors, ref_gene_expression_dict)
        assert len(query_expression_vec) == len(ref_expression_vec), 'Topology of reference network and query network differs. Please check.'

        # A gene which has non-expressed neighbors is ignored.
        if np.sum(query_expression_vec) == 0 and np.sum(ref_expression_vec) == 0:
            continue

        query_p_vec = exp2prob(query_expression_vec)
        ref_p_vec = exp2prob(ref_expression_vec)

        gene_jsd_dict[gene] = jsd(query_p_vec, ref_p_vec)

    return np.mean(list(gene_jsd_dict.values()))

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


Question:
// Name converts the cgroup to the driver specific value in cgroupfs form.
// This always returns a valid cgroupfs path even when systemd driver is in use!

func (m *cgroupManagerImpl) Name(name CgroupName) string {
	if m.adapter.cgroupManagerType == libcontainerSystemd {
		return name.ToSystemd()
	}
	return name.ToCgroupfs()
}

def _init_config(self):

        system = platform.system().lower()
        leveldb_fallback_dir = os.path.expanduser("~")
        if system.startswith("darwin"):
            leveldb_fallback_dir = os.path.join(
                leveldb_fallback_dir, "Library", "Ethereum"
            )
        elif system.startswith("windows"):
            leveldb_fallback_dir = os.path.join(
                leveldb_fallback_dir, "AppData", "Roaming", "Ethereum"
            )
        else:
            leveldb_fallback_dir = os.path.join(leveldb_fallback_dir, ".ethereum")
        leveldb_fallback_dir = os.path.join(leveldb_fallback_dir, "geth", "chaindata")

        if not os.path.exists(self.config_path):
            log.info("No config file found. Creating default: " + self.config_path)
            open(self.config_path, "a").close()

        config = ConfigParser(allow_no_value=True)
        config.optionxform = str
        config.read(self.config_path, "utf-8")
        if "defaults" not in config.sections():
            self._add_default_options(config)

        if not config.has_option("defaults", "leveldb_dir"):
            self._add_leveldb_option(config, leveldb_fallback_dir)

        if not config.has_option("defaults", "dynamic_loading"):
            self._add_dynamic_loading_option(config)

        with codecs.open(self.config_path, "w", "utf-8") as fp:
            config.write(fp)

        leveldb_dir = config.get(
            "defaults", "leveldb_dir", fallback=leveldb_fallback_dir
        )
        return os.path.expanduser(leveldb_dir)

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


Question: // GetAll returns a slice of *Route for the entire RouteFileStore

func (fs RouteFileStore) GetAll() ([]*Route, error) {
	files, err := ioutil.ReadDir(string(fs))
	if err != nil {
		return nil, err
	}
	var routes []*Route
	for _, file := range files {
		fileparts := strings.Split(file.Name(), ".")
		if len(fileparts) > 1 && fileparts[1] == "json" {
			route, err := fs.Get(fileparts[0])
			if err == nil {
				routes = append(routes, route)
			}
		}
	}
	return routes, nil
}

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

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


Question: Builds a list of python modules in the current directory.

def _build_module_list(source_module, index_filename, ignore_modules):
    ''''''
    out = []
    dirs_with_init = set()
    module_prefix = '' if source_module == '.' else source_module

    for root, _, filenames in walk('.'):
        root = root[2:]
        module_root = root.replace('/', '.')
        file_names = [filename[:-3] for filename in filenames if filename.endswith('.py')]

        for filename in file_names:
            if filename == '__init__':
                dirs_with_init.add(root)
                module_name = '.'.join([module_prefix, module_root]) if module_root else source_module
            elif not root:
                module_name = '.'.join([module_prefix, filename])
            else:
                module_name = '.'.join([module_prefix, root.replace('/', '.'), filename])

            if module_name.startswith('.'):
                module_name = module_name[1:]

            if module_name in ignore_modules:
                print 'Ignored file: {}{}.py'.format('{}/'.format(root), filename)
                continue

            if root and root not in dirs_with_init:
                print 'No __init__.py, skipping: {}{}.py'.format('{}/'.format(root), filename)
                continue

            source_name = '{}.py'.format(filename)
            if root:
                source_name = '{}/{}'.format(root, source_name)

            if filename == '__init__':
                output_name = '{}.md'.format(index_filename)
            else:
                output_name = '{}.md'.format(filename)
            if root:
                output_name = '{}/{}'.format(root, output_name)

            out.append({
                'directory': root,
                'file': filename,
                'module': module_name,
                'output': output_name,
                'source': source_name
            })

    return out

def available_ports(self):

        from mbuild.port import Port
        return [port for port in self.labels.values()
                if isinstance(port, Port) and not port.used]

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


Question:
// validateInvoice does a sanity check of the provided Invoice, making sure it
// has all the necessary fields set for it to be considered valid by BOLT-0011.

func validateInvoice(invoice *Invoice) error {
	// The net must be set.
	if invoice.Net == nil {
		return fmt.Errorf("net params not set")
	}

	// Ensure that if there is an amount set, it is not negative.
	if invoice.MilliSat != nil && *invoice.MilliSat < 0 {
		return fmt.Errorf("negative amount: %v", *invoice.MilliSat)
	}

	// The invoice must contain a payment hash.
	if invoice.PaymentHash == nil {
		return fmt.Errorf("no payment hash found")
	}

	// Either Description or DescriptionHash must be set, not both.
	if invoice.Description != nil && invoice.DescriptionHash != nil {
		return fmt.Errorf("both description and description hash set")
	}
	if invoice.Description == nil && invoice.DescriptionHash == nil {
		return fmt.Errorf("neither description nor description hash set")
	}

	// We'll restrict invoices to include up to 20 different private route
	// hints. We do this to avoid overly large invoices.
	if len(invoice.RouteHints) > 20 {
		return fmt.Errorf("too many private routes: %d",
			len(invoice.RouteHints))
	}

	// Each route hint can have at most 20 hops.
	for i, routeHint := range invoice.RouteHints {
		if len(routeHint) > 20 {
			return fmt.Errorf("route hint %d has too many extra "+
				"hops: %d", i, len(routeHint))
		}
	}

	// Check that we support the field lengths.
	if len(invoice.PaymentHash) != 32 {
		return fmt.Errorf("unsupported payment hash length: %d",
			len(invoice.PaymentHash))
	}

	if invoice.DescriptionHash != nil && len(invoice.DescriptionHash) != 32 {
		return fmt.Errorf("unsupported description hash length: %d",
			len(invoice.DescriptionHash))
	}

	if invoice.Destination != nil &&
		len(invoice.Destination.SerializeCompressed()) != 33 {
		return fmt.Errorf("unsupported pubkey length: %d",
			len(invoice.Destination.SerializeCompressed()))
	}

	return nil
}

public function plugin($md, $ruleName, $tokenType, $iteartor)
    {
        $scan = function($state) use($md, $ruleName, $tokenType, $iteartor) {
            for ($blkIdx = count($state->tokens) - 1; $blkIdx >= 0; $blkIdx--) {
                if ($state->tokens[$blkIdx]->type !== 'inline') {
                    continue;
                }

                $inlineTokens = $state->tokens[$blkIdx]->children;

                for ($i = count($inlineTokens) - 1; $i >= 0; $i--) {
                    if ($inlineTokens[$i]->type !== $tokenType) {
                        continue;
                    }

                    $iteartor($inlineTokens, $i);
                }
            }
        };

        $md->core->ruler->push($ruleName, $scan);
    }

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


Question:
Compare both classes and throw {@link UnsupportedOperationException} if
they differ

public static void compareAccumulatorTypes(Object name,
			@SuppressWarnings("rawtypes") Class<? extends Accumulator> first,
			@SuppressWarnings("rawtypes") Class<? extends Accumulator> second)
			throws UnsupportedOperationException {
		if (first != second) {
			throw new UnsupportedOperationException("The accumulator object '" + name
					+ "' was created with two different types: " + first + " and " + second);
		}
	}

public boolean sameAs(Frame<ValueType> other) {
        if (isTop != other.isTop) {
            return false;
        }

        if (isTop && other.isTop) {
            return true;
        }

        if (isBottom != other.isBottom) {
            return false;
        }

        if (isBottom && other.isBottom) {
            return true;
        }

        if (getNumSlots() != other.getNumSlots()) {
            return false;
        }

        for (int i = 0; i < getNumSlots(); ++i) {
            if (!getValue(i).equals(other.getValue(i))) {
                return false;
            }
        }

        return true;
    }

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


Question:
Return the path segments

        :param list value: the new path segments to use

def path_segments(self, value=None):

        if value is not None:
            encoded_values = map(unicode_quote_path_segment, value)
            new_path = '/' + '/'.join(encoded_values)
            return URL._mutate(self, path=new_path)
        parts = self._tuple.path.split('/')
        segments = parts[1:]
        if self._tuple.path.endswith('/'):
            segments.pop()
        segments = map(unicode_unquote, segments)
        return tuple(segments)

public function getViewParameters(BlockInterface $block)
    {
        $parameters = [
            'block_service' => $this,
            'block' => $block,
        ];

        if ($this->environment->getObject() instanceof Content) {
            // Get current page slug to mark it as active when listing
            $parameters['content'] = $this->environment->getObject();
            $parameters['breadcrumbs'] = $parameters['content']->getBreadCrumbs();
        } else {
            $parameters['content'] = $this->contentManager->initialize();
            $parameters['content']->setSlug('example');
            $parameters['breadcrumbs'] = [
                'directory' => 'Example Directory',
                'example' => 'Example Page',
            ];
        }

        // Add homepage link as first breadcrumb if it does not exist in breadcrumbs
        if (!array_key_exists('index', $parameters['breadcrumbs'])) {
            $homePage = $this->contentManager->findOneBySlug('index');

            $parameters['breadcrumbs'] = array_merge(['index' => $homePage->getShortTitle()], $parameters['breadcrumbs']);
        }

        return $parameters;
    }

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


Question: returns a function that extracts the value for a column.

def get_extract_value_function(column_identifier):

    def extract_value(run_result):
        pos = None
        for i, column in enumerate(run_result.columns):
            if column.title == column_identifier:
                pos = i
                break
        if pos is None:
            sys.exit('CPU time missing for task {0}.'.format(run_result.task_id[0]))
        return Util.to_decimal(run_result.values[pos])
    return extract_value

func NeedValue(name string) bool {
	switch name {
	case ast.AggFuncSum, ast.AggFuncAvg, ast.AggFuncFirstRow, ast.AggFuncMax, ast.AggFuncMin,
		ast.AggFuncGroupConcat, ast.AggFuncBitOr, ast.AggFuncBitAnd, ast.AggFuncBitXor:
		return true
	default:
		return false
	}
}

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


Question:
@param ApplyArg $arg

@throws Exception\JavaException
@throws Exception\RuntimeException

public function apply(ApplyArg $arg): void
    {
        $name = $arg->p;
        $object = $arg->v;
        $ob = ($object == null) ? $name : [&$object, $name];
        $isAsync = $this->isAsync;
        $methodCache = $this->methodCache;
        $currentArgumentsFormat = $this->currentArgumentsFormat;
        try {
            $res = $arg->getResult(true);
            if ((($object == null) && !function_exists($name)) || (!($object == null) && !method_exists($object, $name))) {
                throw new Exception\JavaException('java.lang.NoSuchMethodError', (string) $name);
            }
            $res = call_user_func($ob, $res);
            if (is_object($res) && (!($res instanceof JavaType))) {
                $msg = "Client failed to applyArg(), Object returned from '$name()' is not a Java object";
                $this->logger->warning("[soluble-japha] $msg (".__METHOD__.')');
                trigger_error($msg, E_USER_WARNING);

                $this->protocol->invokeBegin(0, 'makeClosure');
                $this->protocol->writeULong($this->globalRef->add($res));
                $this->protocol->invokeEnd();
                $res = $this->getResult();
            }
            $this->protocol->resultBegin();
            $this->writeArg($res);
            $this->protocol->resultEnd();
        } catch (Exception\JavaException $e) {
            $trace = $e->getTraceAsString();
            $this->protocol->resultBegin();
            $this->protocol->writeException($e->__java, $trace);
            $this->protocol->resultEnd();
        } catch (\Throwable $ex) {
            $msg = 'Unchecked exception detected in callback ('.$ex->__toString().')';
            $this->logger->error("[soluble-japha] $msg (".__METHOD__.')');
            trigger_error($msg, E_USER_WARNING);
            throw new Exception\RuntimeException($msg);
        }
        $this->isAsync = $isAsync;
        $this->methodCache = $methodCache;
        $this->currentArgumentsFormat = $currentArgumentsFormat;
    }

public String getValidationDescription() {
		final JvmOperation feature = getOperation();
		String message = null;
		if (!getDeclaredTypeParameters().isEmpty()) {
			message = MessageFormat.format(Messages.CastOperatorLinkingCandidate_0,
					getFeatureTypeParametersAsString(true),
					feature.getSimpleName(),
					getFeatureParameterTypesAsString(),
					feature.getDeclaringType().getSimpleName());
		} else {
			message = MessageFormat.format(Messages.CastOperatorLinkingCandidate_1,
					feature.getSimpleName(),
					getFeatureParameterTypesAsString(),
					feature.getDeclaringType().getSimpleName());
		}
		return message;
	}

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


Question: Interactive seed setting with 3d seed editor

def interactivity(self, min_val=None, max_val=None, qt_app=None):

        from .seed_editor_qt import QTSeedEditor
        from PyQt4.QtGui import QApplication

        if min_val is None:
            min_val = np.min(self.img)

        if max_val is None:
            max_val = np.max(self.img)

        window_c = (max_val + min_val) / 2  # .astype(np.int16)
        window_w = max_val - min_val  # .astype(np.int16)

        if qt_app is None:
            qt_app = QApplication(sys.argv)

        pyed = QTSeedEditor(
            self.img,
            modeFun=self.interactivity_loop,
            voxelSize=self.voxelsize,
            seeds=self.seeds,
            volume_unit=self.volume_unit,
        )

        pyed.changeC(window_c)
        pyed.changeW(window_w)

        qt_app.exec_()

@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case AfplibPackage.PEC__TRIPLETS:
				return triplets != null && !triplets.isEmpty();
		}
		return super.eIsSet(featureID);
	}

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


Question: Convert degrees to radians

def radians(x):

    if isinstance(x, UncertainFunction):
        mcpts = np.radians(x._mcpts)
        return UncertainFunction(mcpts)
    else:
        return np.radians(x)

def cidr_to_netmask(cidr_range)
      cidr = IP::CIDR.new(cidr_range)
      return cidr.ip.ip_address, cidr.long_netmask.ip_address
    end

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


Question:
@param array $servers

@return array

public function connect(array $servers)
    {
        $class = $this->redisClient;
        $options = isset($servers['options']) ? (array) $servers['options'] : [];

        foreach ($servers as $key => $server) {
            $this->connections[$key] = new $class($server, $options);
        }

        return $this->connections;
    }

protected function describeProcedures($names, $refresh = false)
    {
        $names = static::validateAsArray(
            $names,
            ',',
            true,
            'The request contains no valid procedure names or properties.'
        );

        $out = [];
        foreach ($names as $name) {
            $out[] = $this->describeProcedure($name, $refresh);
        }

        return $out;
    }

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


Question: Load table class by name, class not yet initialized

def get(self, table_name):
        """"""
        assert table_name in self.tabs, \
            "Table not avaiable. Avaiable tables: {}".format(
                ", ".join(self.tabs.keys())
            )
        return self.tabs[table_name]

public function prepare()
    {
        if ( $this->fromString == null || $this->fromString == '' )
        {
            $this->from( $this->getDummyTableName() );
        }
        return parent::prepare();
    }

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


Question:
/* -------- Helper Functions --------
Performs a n-point moving average on array.

function moving_average(array, n) {
  var nums = [];

  for (i in array) {
    /* If this item in the array is a number */
    if (_.isNumber(array[i])) {
      nums.push(array[i]);
      if (nums.length > n) {
	nums.splice(0,1); /* Remove the first element of the array */
      }
      /* Take the average of the n items in this array */
      var sum = _.reduce(nums, function(memo, num){ return memo + num; }, 0);
      array[i] = sum/nums.length;
    }
  }

  return array;
}

func NeedValue(name string) bool {
	switch name {
	case ast.AggFuncSum, ast.AggFuncAvg, ast.AggFuncFirstRow, ast.AggFuncMax, ast.AggFuncMin,
		ast.AggFuncGroupConcat, ast.AggFuncBitOr, ast.AggFuncBitAnd, ast.AggFuncBitXor:
		return true
	default:
		return false
	}
}

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


Question:
.. versionadded:: 2019.2.0

    Create a device role

    role
        String of device role, e.g., ``router``

    CLI Example:

    .. code-block:: bash

        salt myminion netbox.create_device_role router

def create_device_role(role, color):
    '''

    '''
    nb_role = get_('dcim', 'device-roles', name=role)
    if nb_role:
        return False
    else:
        payload = {'name': role, 'slug': slugify(role), 'color': color}
        role = _add('dcim', 'device-roles', payload)
        if role:
            return{'dcim': {'device-roles': payload}}
        else:
            return False

func (s *LogConfig) SetCloudWatchLogsRoleArn(v string) *LogConfig {
	s.CloudWatchLogsRoleArn = &v
	return s
}

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


Question:
Get the schema parser by its classname. This method will cache the
constructed schema parsers.

@param schemaParserClassName
The class name of the schema parser
@return The constructed schema parser.

@SuppressWarnings("unchecked")
  private KeyEntitySchemaParser<?, ?> getSchemaParser(
      String schemaParserClassName) {
    if (schemaParsers.contains(schemaParserClassName)) {
      return schemaParsers.get(schemaParserClassName);
    } else {
      try {
        Class<KeyEntitySchemaParser<?, ?>> schemaParserClass = (Class<KeyEntitySchemaParser<?, ?>>) Class
            .forName(schemaParserClassName);
        KeyEntitySchemaParser<?, ?> schemaParser = schemaParserClass
            .getConstructor().newInstance();
        schemaParsers.putIfAbsent(schemaParserClassName, schemaParser);
        return schemaParser;
      } catch (Exception e) {
        throw new DatasetException(
            "Could not instantiate schema parser class: "
                + schemaParserClassName, e);
      }
    }
  }

def spawn_missing_classes(self, context=None):

        if context is None:
            if self.context is not None:
                context = self.context
            else:
                # if context is missing, use the calling namespace
                frame = inspect.currentframe().f_back
                context = frame.f_locals
                del frame
        tables = [
            row[0] for row in self.connection.query('SHOW TABLES in `%s`' % self.database)
            if lookup_class_name('`{db}`.`{tab}`'.format(db=self.database, tab=row[0]), context, 0) is None]
        master_classes = (Lookup, Manual, Imported, Computed)
        part_tables = []
        for table_name in tables:
            class_name = to_camel_case(table_name)
            if class_name not in context:
                try:
                    cls = next(cls for cls in master_classes if re.fullmatch(cls.tier_regexp, table_name))
                except StopIteration:
                    if re.fullmatch(Part.tier_regexp, table_name):
                        part_tables.append(table_name)
                else:
                    # declare and decorate master relation classes
                    context[class_name] = self(type(class_name, (cls,), dict()))

        # attach parts to masters
        for table_name in part_tables:
            groups = re.fullmatch(Part.tier_regexp, table_name).groupdict()
            class_name = to_camel_case(groups['part'])
            try:
                master_class = context[to_camel_case(groups['master'])]
            except KeyError:
                raise DataJointError('The table %s does not follow DataJoint naming conventions' % table_name)
            part_class = type(class_name, (Part,), dict(definition=...))
            part_class._master = master_class
            self.process_relation_class(part_class, context=context, assert_declared=True)
            setattr(master_class, class_name, part_class)

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


Question:
@param string|array $field
@param string       $value

@return static

public function whereContains($field, $value)
    {
        foreach ($this->queries as $query) {
            $query->whereContains($field, $value);
        }

        return $this;
    }

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

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

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

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

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

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

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

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

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

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

    return null;
  }

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


Question:
Execute hook

@param  \Symfony\Component\Console\Input\InputInterface   $input
@param  \Symfony\Component\Console\Output\OutputInterface $output
@return int
@throws \Exception

public function doRun(InputInterface $input, OutputInterface $output) : int
    {
        $output->setDecorated(false);
        $input->setInteractive(false);

        $command = $this->createCommand();
        return $command->run($input, $output);
    }

public SassValue invoke(List<?> arguments) {
    try {
      ArrayList<Object> values = new ArrayList<>(argumentConverters.size());

      for (ArgumentConverter argumentConverter : argumentConverters) {
        Object value = argumentConverter.convert(arguments, importStack, context);
        values.add(value);
      }

      Object result = method.invoke(object, values.toArray());

      return TypeUtils.convertToSassValue(result);
    } catch (Throwable throwable) {
      StringWriter stringWriter = new StringWriter();
      PrintWriter printWriter = new PrintWriter(stringWriter);

      String message = throwable.getMessage();
      if (StringUtils.isNotEmpty(message)) {
        printWriter.append(message).append(System.lineSeparator());
      }
      throwable.printStackTrace(printWriter);

      return new SassError(stringWriter.toString());
    }
  }

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


Question: // isUDP returns true if the transmission channel in use is UDP.

func isUDP(w dns.ResponseWriter) bool {
	return strings.HasPrefix(w.RemoteAddr().Network(), "udp")
}

def content_encoding
      if content_type = headers["content-type"]
        mime_type, charset = content_type.split(SEMICOLON, 2)
        charset = charset[CHARSET_OFFSET] if charset
        charset ||= EMPTY

        if charset.empty? and mime_type.start_with?("text/")
          Encoding::UTF_8
        elsif charset.empty?
          Encoding::BINARY
        else
          ENCODINGS[charset] or raise StompParser::InvalidEncodingError, "invalid encoding #{charset.inspect}"
        end
      else
        Encoding::BINARY
      end
    end

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


Question: Function : diff_y -To compute differntiation along y axis.

public double[][] diff_y(double maty[][]) {
        mat3 = new double[width][height];
        double mat1, mat2;
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                if (i == 0) {
                    mat1 = maty[i][j];
                    mat2 = maty[i + 1][j];
                } else if (i == width - 1) {
                    mat1 = maty[i - 1][j];
                    mat2 = maty[i][j];
                } else {
                    mat1 = maty[i - 1][j];
                    mat2 = maty[i + 1][j];
                }
                mat3[i][j] = (mat2 - mat1) / 2;
            }
        }
        // maty= subMatrix(mat2,mat1,width,height);

        return mat3;
    }

func (dt DateTime) Date() (year int, month time.Month, day int) {
	return dt.t.Date()
}

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


Question:
Calculate the theme palette name
@param {Array} parts
@param {string} theme name
@return {string}

function extractPalette(parts, theme) {
      // If the next section is one of the palettes we assume it's a two word palette
      // Two word palette can be also written in camelCase, forming camelCase to dash-case

      var isTwoWord = parts.length > 1 && colorPalettes.indexOf(parts[1]) !== -1;
      var palette = parts[0].replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();

      if (isTwoWord)  palette = parts[0] + '-' + parts.splice(1, 1);

      if (colorPalettes.indexOf(palette) === -1) {
        // If the palette is not in the palette list it's one of primary/accent/warn/background
        var scheme = $mdTheming.THEMES[theme].colors[palette];
        if (!scheme) {
          throw new Error($mdUtil.supplant(
            'mdColors: couldn\'t find \'{palette}\' in the palettes.',
            {palette: palette}));
        }
        palette = scheme.name;
      }

      return palette;
    }

public function parseResults(LoopResult $loopResult)
    {
        foreach ($loopResult->getResultDataCollection() as $filter) {
            $loopResultRow = new LoopResultRow($filter);

            $loopResultRow->set("ID", $filter->getId())
                ->set("IS_TRANSLATED", $filter->getVirtualColumn('IS_TRANSLATED'))
                ->set("LOCALE", $filter->locale)
                ->set("TITLE", $filter->getVirtualColumn('i18n_TITLE'))
                ->set("CODE", $filter->getCode())
                ->set("DESCRIPTION", $filter->getVirtualColumn('i18n_DESCRIPTION'))
                ->set("ACTIVATE", $filter->getActive())
                ->set("TYPE", $filter->getFiltertype());

            $loopResult->addRow($loopResultRow);
        }

        return $loopResult;
    }

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


Question:
//given a uniqueId, compute a related blob of stuff that can be used to
//shove into the session (currently a prefix and an expiration time)

func computeRawSessionId(uniqueId string, t time.Time) string {
	return fmt.Sprintf("%s:%s,%d", s5CookiePrefix, uniqueId, t.Unix())
}

def ExpirePrefix(self, prefix):
    """"""
    for key in list(self._hash):
      if key.startswith(prefix):
        self.ExpireObject(key)

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


Question: Draw a satellite image tile to screen.

def _draw_satellite_tile(self, tile, x, y):
        """"""
        image, colours = tile.rendered_text
        for (i, line) in enumerate(image):
            self._screen.paint(line, x, y + i, colour_map=colours[i])
        return 1

func CreateTargetFrom(tablet *topodatapb.Tablet) *query.Target {
	return &query.Target{
		Cell:       tablet.Alias.Cell,
		Keyspace:   tablet.Keyspace,
		Shard:      tablet.Shard,
		TabletType: tablet.Type,
	}
}

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


Question: console.log('deepLoad : ', entry, context, destructive, excludeFunctions);

function(toLoad) {
			var value = toLoad.value;
			if (value && value._deep_ocm_)
				value = value();
			switch (typeof value) {
				case 'string':
					if (context)
						value = deep.utils.interpret(value, context);
					var s = deep.get(value, {
						entry: toLoad
					});
					if (s && s.then)
						return deep.when(s)
							.then(function(s) {
								if (s && s._deep_ocm_)
									return s();
							});
					if (s && s._deep_ocm_)
						return s();
					return s;
				case 'function':
					var d = null;
					if (toLoad.ancestor)
						d = value.call(toLoad.ancestor.value, context);
					else
						d = value(context);
					if (d && d.then)
						return deep.when(d)
							.done(function(s) {
								if (s && s._deep_ocm_)
									return s();
							});
					return d;
				default:
					return value;
			}
		}

function (opts, cb) {
      var self = this
      opts = opts || {}
      var root = opts.root || RootKey
      var _cb = function (err, doc) {
        if (err) {
          cb(err, ERR.config.FA_LIST_CONFIG)
        } else {
          if (!doc) {
            if (opts.all) return cb(null, {})
            return cb(null, [])
          }
          if (opts.all) {
            for (var key in doc) {
              var _doc = self._parse(doc[key])
              if (_doc.value) {
                doc[key] = _doc.value
              } else {
                delete doc[key]
              }
            }
          }
          cb(null, doc)
        }
      }
      if (opts.all) {
        mq.hgetall(root, _cb)
      } else {
        mq.hkeys(root, _cb)
      }
    }

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


Question: // Configure add default target in the deny list

func (p *Proxy) Configure(ctx context.Context, port string) {
	p.addToEndpointList(ctx, "localhost")
	p.addToEndpointList(ctx, "127.0.0.1")
}

public function build(): SetRequestInterceptionRequest
	{
		$instance = new SetRequestInterceptionRequest();
		if ($this->patterns === null) {
			throw new BuilderException('Property [patterns] is required.');
		}
		$instance->patterns = $this->patterns;
		return $instance;
	}

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


Question: Closure to fetch a key from one of two places (environment vars or a specified object). Env vars take precedence.

function envOrSource(env, source) {
    function getKey(keyName) {
        return env[keyName] || source[keyName];
    }
    return getKey;
}

def conditions(self, start, last_attempt):

        if time.time() - start > self.timeout:
            yield WaitCondition.Timedout
            return

        if last_attempt is not None and time.time() - last_attempt < self.wait_between_attempts:
            yield WaitCondition.KeepWaiting
            return

        if self.greps is not NotSpecified:
            for name, val in self.greps.items():
                yield 'grep "{0}" "{1}"'.format(val, name)

        if self.file_value is not NotSpecified:
            for name, val in self.file_value.items():
                command = 'diff <(echo {0}) <(cat {1})'.format(val, name)
                if not self.harpoon.debug:
                    command = "{0} > /dev/null".format(command)
                yield command

        if self.port_open is not NotSpecified:
            for port in self.port_open:
                yield 'nc -z 127.0.0.1 {0}'.format(port)

        if self.curl_result is not NotSpecified:
            for url, content in self.curl_result.items():
                yield 'diff <(curl "{0}") <(echo {1})'.format(url, content)

        if self.file_exists is not NotSpecified:
            for path in self.file_exists:
                yield 'cat {0} > /dev/null'.format(path)

        if self.command not in (None, "", NotSpecified):
            for command in self.command:
                yield command

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


Question:
Get a number of characters without advancing the scan pointer.

            >>> s = Scanner("test string")
            >>> s.peek(7)
            'test st'
            >>> s.peek(7)
            'test st'

def peek(self, length):

        return self.string[self.pos:self.pos + length]

def reverse_cipher(message):

    translated = ''

    i = len(message) - 1
    while i >= 0:
        translated = translated + message[i]
        i = i - 1

    return translated

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


Question:
Create the stream output file; the flv itself.

@throws IOException

private void createOutputFile() throws IOException {
        this.fileChannel = Files.newByteChannel(Paths.get(filePath), StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);
    }

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

    logging.info("Processing schedule data.")

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

    logging.info("Schedule data processed.")

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


Question:
Writes the supplied variables to the config file

@param  array  $vars The variables to write
@param  string $file The file to write to

@return boolean

private function writeFile($vars, $file)
    {
        $fp = fopen($file, 'w');

        fwrite($fp, "<?php\n");
        foreach ($vars as $v) {

            if (is_string($v)) {

                fwrite($fp, $v . "\n");

            } else {

                if (is_numeric($v['value'])) {

                    $sValue = $v['value'];

                } else {

                    $sValue = "'" . str_replace("'", "\'", $v['value']) . "'";
                }

                fwrite($fp, "define('" . $v['key'] . "', " . $sValue . ");\n");
            }
        }

        fclose($fp);

        return true;
    }

public static function add($message = 'No message', $logCode = self::LEVEL_INFO)
    {
        // if file pointer doesn't exist, then open log file
        if (!self::$_fileHandler) {
            self::_openLogFile();
        }

        // Get user IP
        if (!empty($_SERVER['REMOTE_ADDR'])) {
            $userIP = $_SERVER['REMOTE_ADDR'];
        } else {
            $userIP = '0.0.0.0';
        }

        // define current time
        $time = date('j/M/Y H:i:s');

        // define script name
        $scriptName = pathinfo($_SERVER['PHP_SELF'], PATHINFO_BASENAME);

        // write message to the log file
        $fwrite = fwrite(self::$_fileHandler, "$userIP [$time][$logCode] ($scriptName) --> $message\n");

        if ($fwrite === false) {
            return false;
        } else {
            return true;
        }
    }

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


Question: Got a message from a channel

def on_pubmsg(self, connection, event):

        sender = self.get_nick(event.source)
        channel = event.target
        message = event.arguments[0]

        self.handle_message(connection, sender, channel, message)

func NewMsgReject(command string, code RejectCode, reason string) *MsgReject {
	return &MsgReject{
		Cmd:    command,
		Code:   code,
		Reason: reason,
	}
}

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


Question:
Compile the column type.

This function is used by compileColumnDefinition().

@param string $type by Column type supported by Database Access Layer
@param int|null $size
@param int|null $scale
@return string

protected function compileFieldType($type, $size, $scale)
    {
        switch (strtolower($type)) {
            case 'smallint':    // 2 Byte
                return 'SMALLINT';

            case 'integer':     // 4 Byte
                return 'INT';

            case 'unsigned':    // 4 Byte
                return 'INT UNSIGNED';

            case 'bigint':      // 8 Byte
                return 'BIGINT';

            case 'numeric':
                return 'NUMERIC(' . ($size ?: 10) . ', ' . ($scale ?: 0) . ')'; // size in digits

            case 'float':
                return 'DOUBLE';

            case 'string':
                return 'VARCHAR(' . ($size ?: 255) . ')'; // size in characters

            case 'text':
            case 'array':  // needs type-hint!
            case 'json':   // needs type-hint!
            case 'object': // needs type-hint!
                return 'TEXT';

            case 'guid':
                return 'UUID'; // PostgreSQL converts to lowercase letters, MSSQL to uppercase!

            case 'binary':
                // size in bytes:
                // 1 Byte  = 2^8-1  = 255 characters
                // 2 Bytes = 2^16-1 = 65535 characters
                // 3 Bytes = 2^24-1 = 16777215 characters
                // 4 Bytes = 2^32-1 = 4294967295 characters
                return 'VARBINARY(' . ($size ?: 2) . ')';

            case 'blob':
                return 'BLOB';

            case 'boolean':
                return 'BOOLEAN';

            case 'date':
                return 'DATE';

            case 'datetime':
                return 'DATETIME';

            case 'timestamp':  // datetime with time zone
                return 'TIMESTAMP';

            case 'time':
                return 'TIME';

            default:
                throw new InvalidArgumentException("Type '{$type}' not supported by Database Access Layer.");
        }
    }

String getLiteralPrefix() {

        switch (type) {

            case Types.SQL_BINARY :
            case Types.SQL_BLOB :
            case Types.SQL_CHAR :
            case Types.SQL_NCHAR :
            case Types.SQL_CLOB :
            case Types.SQL_VARBINARY :
            case Types.SQL_VARCHAR :
            case Types.SQL_NVARCHAR :
                return "'";

            case Types.SQL_DATALINK :
                return "'";    // hypothetically: "{url '";

            case Types.SQL_DATE :
                return "'";    // or JDBC escape: "{d '";

            case Types.OTHER :
                return "'";    // hypothetically: "{o '"; or new "pkg.cls"(...)

            case Types.SQL_TIME_WITH_TIME_ZONE :
            case Types.SQL_TIME :
                return "'";    // or JDBC escape: "{t '";

            case Types.SQL_TIMESTAMP_WITH_TIME_ZONE :
            case Types.SQL_TIMESTAMP :
                return "'";    // or JDBC escape: "{ts '";

            case Types.SQL_XML :
                return "'";    // hypothetically: "{xml '";

            default :
                return null;
        }
    }

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


Question:
Handle an event
@private
@param e {Event} the event to handle
@returns {Boolean} true if the tooltip changed

function(e) {
			var me = this;
			var options = me._options;
			var changed = false;

			me._lastActive = me._lastActive || [];

			// Find Active Elements for tooltips
			if (e.type === 'mouseout') {
				me._active = [];
			} else {
				me._active = me._chartInstance.getElementsAtEventForMode(e, options.mode, options);
			}

			// Remember Last Actives
			changed = !helpers.arrayEquals(me._active, me._lastActive);
			me._lastActive = me._active;

			if (options.enabled || options.custom) {
				me._eventPosition = helpers.getRelativePosition(e, me._chart);

				var model = me._model;
				me.update(true);
				me.pivot();

				// See if our tooltip position changed
				changed |= (model.x !== me._model.x) || (model.y !== me._model.y);
			}

			return changed;
		}

protected void transportTrailersReceived(Metadata trailers) {
    Preconditions.checkNotNull(trailers, "trailers");
    if (transportError == null && !headersReceived) {
      transportError = validateInitialMetadata(trailers);
      if (transportError != null) {
        transportErrorMetadata = trailers;
      }
    }
    if (transportError != null) {
      transportError = transportError.augmentDescription("trailers: " + trailers);
      http2ProcessingFailed(transportError, false, transportErrorMetadata);
    } else {
      Status status = statusFromTrailers(trailers);
      stripTransportDetails(trailers);
      inboundTrailersReceived(trailers, status);
    }
  }

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


Question:
// Value returns the value associated with this context for key, or nil
// if no value is associated with key. Successive calls to Value with
// the same key returns the same result.

func (ctx *Context) Value(key interface{}) (val interface{}) {
	if key == isRecursive {
		return isRecursive
	}
	return ctx._ctx.Value(key)
}

def process_value(self, value):

        # UID -> SuperModel
        if api.is_uid(value):
            return self.to_super_model(value)
        # Content -> SuperModel
        elif api.is_object(value):
            return self.to_super_model(value)
        # String -> Unicode
        elif isinstance(value, basestring):
            return safe_unicode(value).encode("utf-8")
        # DateTime -> DateTime
        elif isinstance(value, DateTime):
            return value
        # Process list values
        elif isinstance(value, (LazyMap, list, tuple)):
            return map(self.process_value, value)
        # Process dict values
        elif isinstance(value, (dict)):
            return {k: self.process_value(v) for k, v in value.iteritems()}
        # Process function
        elif safe_callable(value):
            return self.process_value(value())
        # Always return the unprocessed value last
        return value

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


Question:
Add violation
@param string $key
@param array|string $message

public function add($key, $message)
    {
        if (empty($this->violations[$key])) {
            $this->violations[$key] = [];
        }

        $this->violations[$key] = array_merge(
            $this->violations[$key],
            (array) $message
        );

        return $this;
    }

public static function ingoing($config = [])
    {
        $config['env'] = isset($config['env']) ? $config['env'] : $_SERVER;

        if (!isset($config['env']['REQUEST_URI'])) {
            throw new NetException("Missing `'REQUEST_URI'` environment variable, unable to create the main request.");
        }

        if (!isset($config['env']['SCRIPT_NAME'])) {
            throw new NetException("Missing `'SCRIPT_NAME'` environment variable, unable to create the main request.");
        }

        return new static($config + [
            'body'    => new Part(['filename' => 'php://input', 'mode' => 'r']),
            'query'   => isset($_GET) ? $_GET : [],
            'cookies' => $_COOKIE
        ]);
    }

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


Question:
Get the attributes.

@param null $key

@return \Illuminate\Support\Collection|mixed

public function getAttributes($key = null)
    {
        if (!($key)) {
            return $this->attributes;
        }

        return $this->attributes->get($key);
    }

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

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

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

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

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

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


Question:
return null if there is no CrawlDatum to generate
@return

public CrawlDatum next(){
        int topN = getConf().getTopN();
        int maxExecuteCount = getConf().getOrDefault(Configuration.KEY_MAX_EXECUTE_COUNT, Integer.MAX_VALUE);

        if(topN > 0 && totalGenerate >= topN){
            return null;
        }

        CrawlDatum datum;
        while (true) {
            try {
                datum = nextWithoutFilter();
                if (datum == null) {
                    return datum;
                }
                if(filter == null || (datum = filter.filter(datum))!=null){
                    if (datum.getExecuteCount() > maxExecuteCount) {
                        continue;
                    }
                    totalGenerate += 1;
                    return datum;
                }

            } catch (Exception e) {
                LOG.info("Exception when generating", e);
                return null;
            }

        }
    }

def select_optional_row(statement, build_arg = nil)
    rows = select(statement, build_arg)
    raise UnexpectedQueryResult, "selected #{rows.size} rows; expected 0 or 1" if rows.size > 1
    if rows.empty? then nil else rows[0] end
  end

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


Question:
Resets all fields for this manager.

@return RoleManager for chaining convenience

@Override
    @CheckReturnValue
    public RoleManager reset()
    {
        super.reset();
        this.name = null;
        this.color = Role.DEFAULT_COLOR_RAW;
        return this;
    }

public NotificationChain basicSetName(JvmParameterizedTypeReference newName, NotificationChain msgs)
	{
		JvmParameterizedTypeReference oldName = name;
		name = newName;
		if (eNotificationRequired())
		{
			ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, SarlPackage.SARL_BEHAVIOR_UNIT__NAME, oldName, newName);
			if (msgs == null) msgs = notification; else msgs.add(notification);
		}
		return msgs;
	}

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


Question: // DeleteRelease deletes a provided release

func (r *ReleaseModuleServiceServer) DeleteRelease(ctx context.Context, in *rudderAPI.DeleteReleaseRequest) (*rudderAPI.DeleteReleaseResponse, error) {
	grpclog.Print("delete")

	resp := &rudderAPI.DeleteReleaseResponse{}
	rel := in.Release
	vs, err := tiller.GetVersionSet(clientset.Discovery())
	if err != nil {
		return resp, fmt.Errorf("Could not get apiVersions from Kubernetes: %v", err)
	}

	kept, errs := tiller.DeleteRelease(rel, vs, kubeClient)
	rel.Manifest = kept

	allErrors := ""
	for _, e := range errs {
		allErrors = allErrors + "\n" + e.Error()
	}

	if len(allErrors) > 0 {
		err = fmt.Errorf(allErrors)
	}

	return &rudderAPI.DeleteReleaseResponse{
		Release: rel,
	}, err
}

public function hDel($key, $field) {
        return $this->getHandler($this->judge(__FUNCTION__))->hDel($key, $field);
    }

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


Question: Update os_version attribute.

def update_os_version(self):
        """"""
        self.chain.connection.log("Detecting os version")
        os_version = self.driver.get_os_version(self.version_text)
        if os_version:
            self.chain.connection.log("SW Version: {}".format(os_version))
            self.os_version = os_version

func DefaultUpdaterLabel(runMode libkb.RunMode) string {
	label := AppUpdaterLabel.String()
	if runMode != libkb.ProductionRunMode {
		label = label + "." + string(runMode)
	}
	return label
}

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


Question:
Adds a log record to the span

@param array $fields
@param int|float|\DateTimeInterface $timestamp
@throws SpanAlreadyFinished if the span is already finished

public function log(array $fields = [], $timestamp = null){
        $log['timestamp'] = $timestamp ? $timestamp : $this->microtimeToInt();
        $log['fields'] = $fields;
        $this->logs[] = $log;
    }

@Task(name = "createStream", version = "1.0", resource = "{scope}/{stream}")
    public CompletableFuture<CreateStreamStatus.Status> createStream(String scope, String stream, StreamConfiguration config, long createTimestamp) {
        return execute(
                new Resource(scope, stream),
                new Serializable[]{scope, stream, config, createTimestamp},
                () -> createStreamBody(scope, stream, config, createTimestamp));
    }

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


Question: Marshall the given parameter object.

public void marshall(OverallVolume overallVolume, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(overallVolume.getVolumeStatistics(), VOLUMESTATISTICS_BINDING);
            protocolMarshaller.marshall(overallVolume.getReadRatePercent(), READRATEPERCENT_BINDING);
            protocolMarshaller.marshall(overallVolume.getDomainIspPlacements(), DOMAINISPPLACEMENTS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question: // Uints32 adds the field key with i as a []int32 to the *Event context.

func (e *Event) Uints32(key string, i []uint32) *Event {
	if e == nil {
		return e
	}
	e.buf = enc.AppendUints32(enc.AppendKey(e.buf, key), i)
	return e
}

public static <K, V> CacheEvent<K, V> creation(K newKey, V newValue, Cache<K, V> source) {
    return new CreationEvent<>(newKey, newValue, source);
  }

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


Question:
Set the feature style into the polygon options

@param polygonOptions polygon options
@param featureStyle   feature style
@return true if style was set into the polygon options

public boolean setFeatureStyle(PolygonOptions polygonOptions, FeatureStyle featureStyle) {
        return StyleUtils.setFeatureStyle(polygonOptions, featureStyle, density);
    }

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

      :ok # passes
    end

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


Question: Query PYPI via XMLRPC interface for a pkg's available versions

def package_releases(self, package_name):
        """"""
        if self.debug:
            self.logger.debug("DEBUG: querying PyPI for versions of " \
                    + package_name)
        return self.xmlrpc.package_releases(package_name)

def dump_stats(self, fdump, close=True):

        if self.tracker:
            self.tracker.stop_periodic_snapshots()

        if isinstance(fdump, type('')):
            fdump = open(fdump, 'wb')
        pickle.dump(self.index, fdump, protocol=pickle.HIGHEST_PROTOCOL)
        pickle.dump(self.snapshots, fdump, protocol=pickle.HIGHEST_PROTOCOL)
        if close:
            fdump.close()

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


Question:
Build a {@link DistributedDelayQueue} from the current builder values.

@return distributed delay queue

public DistributedDelayQueue<T>      buildDelayQueue()
    {
        return new DistributedDelayQueue<T>
        (
            client,
            consumer,
            serializer,
            queuePath,
            factory,
            executor,
            Integer.MAX_VALUE,
            lockPath,
            maxItems,
            putInBackground,
            finalFlushMs
        );
    }

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:
@param string $name
@param array  $description

@return $this

public function addModule($name, array $description)
    {
        if (!isset($this->descriptor['modules'])) {
            $this->descriptor['modules'] = [];
        }
        $this->descriptor['modules'][$name] = $description;

        return $this;
    }

public static DescriptorExtensionList<ParameterDefinition,ParameterDescriptor> all() {
        return Jenkins.getInstance().<ParameterDefinition,ParameterDescriptor>getDescriptorList(ParameterDefinition.class);
    }

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


Question:
Override get_margin_width

@return int

function get_margin_width()
    {
        //ignore image width, use same width as on predefined bullet ListBullet
        //for proper alignment of bullet image and text. Allow image to not fitting on left border.
        //This controls the extra indentation of text to make room for the bullet image.
        //Here use actual image size, not predefined bullet size
        //return $this->_frame->get_style()->get_font_size()*ListBullet::BULLET_SIZE +
        //  2 * ListBullet::BULLET_PADDING;

        // Small hack to prevent indenting of list text
        // Image Might not exist, then position like on list_bullet_frame_decorator fallback to none.
        if ($this->_frame->get_style()->list_style_position === "outside" || $this->_width == 0) {
            return 0;
        }
        //This aligns the "inside" image position with the text.
        //The text starts to the right of the image.
        //Between the image and the text there is an added margin of image width.
        //Where this comes from is unknown.
        //The corresponding ListBullet sets a smaller margin. bullet size?
        return $this->_width + 2 * ListBullet::BULLET_PADDING;
    }

public function setBorderSize($pValue = null) {
		$this->_borderTopSize = $pValue;
		$this->_borderLeftSize = $pValue;
		$this->_borderRightSize = $pValue;
		$this->_borderBottomSize = $pValue;
		$this->_borderInsideHSize = $pValue;
		$this->_borderInsideVSize = $pValue;
	}

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


Question:
// You should always use this function to get a new AuthorizeSecurityGroupEgressParams instance,
// as then you are sure you have configured all required params

func (s *SecurityGroupService) NewAuthorizeSecurityGroupEgressParams() *AuthorizeSecurityGroupEgressParams {
	p := &AuthorizeSecurityGroupEgressParams{}
	p.p = make(map[string]interface{})
	return p
}

func Convert_v1_EgressNetworkPolicyList_To_network_EgressNetworkPolicyList(in *v1.EgressNetworkPolicyList, out *network.EgressNetworkPolicyList, s conversion.Scope) error {
	return autoConvert_v1_EgressNetworkPolicyList_To_network_EgressNetworkPolicyList(in, out, s)
}

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


Question:
return the main model

@param bool|false $reload
@return \Illuminate\Database\Eloquent\Model

public function getModel($reload = false)
    {
        if (!isset($this->model) || $reload) {
            $class = static::$modelClass;
            $this->model = $class::findOrFail($this->getId());
        }

        return $this->model;
    }

public function solveFetch(Entity &$entity)
    {
        // We need to find all target entities with the ID defined in the current entity source column
        $column = $this->relation->join->column;

        $value = $entity->{$column};
        $where = array($this->relation->join->targetColumn => $value);

        $query = EntityManager::find($this->relation->targetEntity);
        return $query->where($where)->all();
    }

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