Question:
Reads the file

@return  string

public function read()
	{
		if (!isset($this->contents))
		{
			$this->contents = $this->hasAdapterOrFail()->adapter->read($this->getPath());
		}

		return (string) $this->contents;
	}

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

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


Question:
Element that must match the given time format
@param format time format to match
@param example example time to use for generated bodies

public PactDslJsonArray time(String format, Date example) {
        FastDateFormat instance = FastDateFormat.getInstance(format);
        body.put(instance.format(example));
        matchers.addRule(rootPath + appendArrayIndex(0), matchTime(format));
        return this;
    }

def prepare_metadata(self):
        # type: () -> None

        assert self.source_dir

        with indent_log():
            if self.use_pep517:
                self.prepare_pep517_metadata()
            else:
                self.run_egg_info()

        if not self.req:
            if isinstance(parse_version(self.metadata["Version"]), Version):
                op = "=="
            else:
                op = "==="
            self.req = Requirement(
                "".join([
                    self.metadata["Name"],
                    op,
                    self.metadata["Version"],
                ])
            )
            self._correct_build_location()
        else:
            metadata_name = canonicalize_name(self.metadata["Name"])
            if canonicalize_name(self.req.name) != metadata_name:
                logger.warning(
                    'Generating metadata for package %s '
                    'produced metadata for project name %s. Fix your '
                    '#egg=%s fragments.',
                    self.name, metadata_name, self.name
                )
                self.req = Requirement(metadata_name)

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


Question: run a full execution of their code & addon, uses a `require()` in a child process and check the stdout for expected

function checkExec (mode, callback) {
  if (!exercise.passed)
    return callback(null, true) // shortcut if we've already had a failure

  execWith(copyTempDir, 'testing', function (err, pass) {
    if (err)
      return callback(err)
    if (!pass) {
      exercise.emit('fail', 'JavaScript code loads addon, invokes `length(str)` method and prints the return value')
      return callback(null, false)
    }

    execWith(copyTempDir, 'this is a longer test string, with spaces in it', function (err, pass) {
      if (err)
        return callback(err)

      exercise.emit(pass ? 'pass' : 'fail', 'Add-on receives string, calculates length and returns value')
      callback(null, pass)
    })
  })
}

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

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

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

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

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

      return true
    end

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


Question: Supplemental description of the list, with length and type

def info(self):
        """"""
        itext = self.class_info
        if self.prop.info:
            itext += ' (each item is {})'.format(self.prop.info)
        if self.max_length is None and self.min_length is None:
            return itext
        if self.max_length is None:
            lentext = 'length >= {}'.format(self.min_length)
        elif self.max_length == self.min_length:
            lentext = 'length of {}'.format(self.min_length)
        else:
            lentext = 'length between {mn} and {mx}'.format(
                mn='0' if self.min_length is None else self.min_length,
                mx=self.max_length,
            )
        return '{} with {}'.format(itext, lentext)

public final OrderSpecifier<T> desc() {
        if (desc == null) {
            desc = new OrderSpecifier<T>(Order.DESC, mixin);
        }
        return desc;
    }

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


Question: Logs process output (stderr)

def _on_process_stderr_ready(self):

        try:
            o = self.readAllStandardError()
        except (TypeError, RuntimeError):
            # widget already deleted
            return
        try:
            output = bytes(o).decode(self._encoding)
        except TypeError:
            output = bytes(o.data()).decode(self._encoding)
        for line in output.splitlines():
            self._srv_logger.error(line)

func (rl *RevelLogger) Errorf(msg string, param ...interface{}) {
	rl.Error(fmt.Sprintf(msg, param...))
}

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


Question: // GetSettings returns setting even if it fails to resolve IPs for dynamic networks.

func (s *settingsService) GetSettings() Settings {
	s.settingsMutex.Lock()

	settingsCopy := s.settings

	if s.settings.Networks != nil {
		settingsCopy.Networks = make(map[string]Network)
	}

	for networkName, network := range s.settings.Networks {
		settingsCopy.Networks[networkName] = network
	}
	s.settingsMutex.Unlock()

	for networkName, network := range settingsCopy.Networks {
		if !network.IsDHCP() {
			continue
		}

		resolvedNetwork, err := s.resolveNetwork(network)
		if err != nil {
			break
		}

		settingsCopy.Networks[networkName] = resolvedNetwork
	}
	return settingsCopy
}

def read_registry(self):
        """"""
        lm = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
        want_scan = False
        try:
            try:
                # XP, 2000
                tcp_params = _winreg.OpenKey(lm,
                                             r'SYSTEM\CurrentControlSet'
                                             r'\Services\Tcpip\Parameters')
                want_scan = True
            except EnvironmentError:
                # ME
                tcp_params = _winreg.OpenKey(lm,
                                             r'SYSTEM\CurrentControlSet'
                                             r'\Services\VxD\MSTCP')
            try:
                self._config_win32_fromkey(tcp_params)
            finally:
                tcp_params.Close()
            if want_scan:
                interfaces = _winreg.OpenKey(lm,
                                             r'SYSTEM\CurrentControlSet'
                                             r'\Services\Tcpip\Parameters'
                                             r'\Interfaces')
                try:
                    i = 0
                    while True:
                        try:
                            guid = _winreg.EnumKey(interfaces, i)
                            i += 1
                            key = _winreg.OpenKey(interfaces, guid)
                            if not self._win32_is_nic_enabled(lm, guid, key):
                                continue
                            try:
                                self._config_win32_fromkey(key)
                            finally:
                                key.Close()
                        except EnvironmentError:
                            break
                finally:
                    interfaces.Close()
        finally:
            lm.Close()

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


Question:
Clear the module state. This is mainly for testing purposes.
        Note that this must be called _after_ resetting the module 'feature'.

def reset ():

    global __had_unspecified_value, __had_value, __declared_subfeature
    global __init_loc
    global __all_signatures, __debug_configuration, __show_configuration

    # Stores toolsets without specified initialization values.
    __had_unspecified_value = {}

    # Stores toolsets with specified initialization values.
    __had_value = {}

    # Stores toolsets with declared subfeatures.
    __declared_subfeature = {}

    # Stores all signatures of the toolsets.
    __all_signatures = {}

    # Stores the initialization locations of each toolset
    __init_loc = {}

    __debug_configuration = '--debug-configuration' in bjam.variable('ARGV')
    __show_configuration = '--show-configuration' in bjam.variable('ARGV')

    global __executable_path_variable
    OS = bjam.call("peek", [], "OS")[0]
    if OS == "NT":
        # On Windows the case and capitalization of PATH is not always predictable, so
        # let's find out what variable name was really set.
        for n in os.environ:
            if n.lower() == "path":
                __executable_path_variable = n
                break
    else:
        __executable_path_variable = "PATH"

    m = {"NT": __executable_path_variable,
         "CYGWIN": "PATH",
         "MACOSX": "DYLD_LIBRARY_PATH",
         "AIX": "LIBPATH",
         "HAIKU": "LIBRARY_PATH"}
    global __shared_library_path_variable
    __shared_library_path_variable = m.get(OS, "LD_LIBRARY_PATH")

func (menu *Menu) HandleReply(reply CommandResponse) {

	for k, v := range menu.WaitingResponses {
		if v.ID != reply.ID {
			continue
		}
		Log.Print("MENU(", menu.TargetID, ")::Handling Reply", reply)
		removeAt := func(k int) {
			if len(menu.WaitingResponses) > 1 {
				menu.WaitingResponses = menu.WaitingResponses[:k+copy(menu.WaitingResponses[k:], menu.WaitingResponses[k+1:])]
			} else {
				menu.WaitingResponses = []*Command{}
			}
		}
		defer removeAt(k)

		if menu.TargetID == 0 && v.Action == "create" {
			//Assume we have a reply to action:create
			if reply.Result.TargetID != 0 {
				menu.TargetID = reply.Result.TargetID
				Log.Print("Received TargetID", "\nSetting Ready State")
				menu.Ready = true
			}
			for i, _ := range menu.CommandQueue {
				menu.CommandQueue[i].TargetID = menu.TargetID
				menu.Send(menu.CommandQueue[i])
			}
			// Reinitialize empty command queue, and allow gc.
			menu.CommandQueue = []*Command{}
			return
		}

		if v.Action == "call" && v.Method == "set_application_menu" {
			Log.Print("Received reply to set_application_menu", "Setting Menu Displayed to True")
			menu.setDisplayed(true)
		}

	}
}

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


Question:
Returns the result of {@link core_component::get_plugin_types()} ordered for humans

@see self::reorder_plugin_types()
@return array (string)name => (string)location

public function get_plugin_types() {
        if (func_num_args() > 0) {
            if (!func_get_arg(0)) {
                throw new coding_exception('core_plugin_manager->get_plugin_types() does not support relative paths.');
            }
        }
        if ($this->plugintypes) {
            return $this->plugintypes;
        }

        $this->plugintypes = $this->reorder_plugin_types(core_component::get_plugin_types());
        return $this->plugintypes;
    }

public function addRoute($route)
    {
        if (!$route instanceof Route && !is_array($route)) {
            throw new \LogicException('Route invalid. Expected Route instance or array.');
        } elseif ($route instanceof Route) {
            $name = $route->getName();
            if (isset($this->routes[$name])) {
                throw new \LogicException(sprintf('Trying to register two routes with the same name "%s"', $name));
            }
            $this->routes[$route->getName()] = $route;
        } elseif (is_array($route) && !count($route) == 4) {
            throw new \LogicException('Array Route invalid. Expected array(string|array method, string pattern, callback|string action, string name).');
        } else {
            list($methods, $patternUri, $action, $name) = array_values($route);

            $this->routes[$name] = new Route($methods, $patternUri, $action, $name);
        }

        return $this;
    }

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


Question: // FinishRestore implements the server side of Backups.FinishRestore.

func (a *API) FinishRestore() error {
	info := a.backend.RestoreInfo()
	currentStatus, err := info.Status()
	if err != nil {
		return errors.Trace(err)
	}
	if currentStatus != state.RestoreFinished {
		if err := info.SetStatus(state.RestoreFailed); err != nil {
			return errors.Trace(err)
		}
		return errors.Errorf("Restore did not finish successfully")
	}
	logger.Infof("Successfully restored")
	return info.SetStatus(state.RestoreChecked)
}

func (r *DB) Begin() (err error) {
	if r.inTx > 0 {
		_, err = r.Exec(fmt.Sprintf("SAVEPOINT sp_%d", r.inTx))
	}
	if r.inTx == 0 {
		if r.ctx == nil {
			r.Log(func() {
				r.Tx, err = r.DB.Beginx()
			}, "BEGIN;")
		} else {
			r.Log(func() {
				r.Tx, err = r.DB.BeginTxx(r.ctx, r.TxOpts)
			}, "BEGIN; -- with context")
		}
	}
	if err != nil {
		return errors.WithStack(err)
	}

	r.inTx++
	return nil
}

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


Question:
Get path-info

@param string $path
@param string $base
@param string $full
@param string $type
@param bool $recursive
@return object

protected function info( $path, $base, $full, $type, $recursive = true )
    {
        $name = basename( $path );

        if ( isset( $name[0] ) && $name[0] == '.' )
        {
            return null;
        }

        $result = (object) array(
            'name' => $name,
            'path' => $path,
            'uri'  => '/' . $base,
            'type' => $type,
            'size' => filesize( $full ),
            'time' => filemtime( $full ),
        );

        $result->rights = $this->rights( $path );

        if ( ! $result->rights->read )
        {
            return null;
        }

        switch ( $type )
        {
            case 'dir':

                if ( $recursive )
                {
                    $result->entries = array();

                    $iterator = new FilesystemIterator( $full,
                        FilesystemIterator::KEY_AS_FILENAME     |
                        FilesystemIterator::CURRENT_AS_FILEINFO |
                        FilesystemIterator::SKIP_DOTS
                    );

                    $iterator = new SortIterator(
                        $iterator,
                        function ( $a, $b )
                        {
                            $aIsDir = $a->isDir();
                            $bIsDir = $b->isDir();
                            $aFname = $a->getFilename();
                            $bFname = $b->getFilename();

                            switch ( true )
                            {
                                case ! $aIsDir && $bIsDir:
                                    return 1;

                                case $aIsDir && ! $bIsDir:
                                    return -1;

                                default:
                                    return strnatcasecmp( $aFname, $bFname );
                            }
                        }
                    );

                    foreach ( $iterator as $name => $info )
                    {
                        $child = null;

                        if ( $name[0] != '.' )
                        {
                            if ( $info->isDir() )
                            {
                                $child = $this->info(
                                    ( empty( $path ) ? ''
                                        : $path . '/' ) . $name,
                                    $base . '/' . $name,
                                    $full . '/' . $name,
                                    'dir', false
                                );
                            }
                            else if ( $info->isFile() )
                            {
                                $child = $this->info(
                                    ( empty( $path ) ? ''
                                        : $path . '/' ) . $name,
                                    $base . '/' . $name,
                                    $full . '/' . $name,
                                    'file', false
                                );
                            }
                        }

                        if ( null !== $child )
                        {
                            $result->entries[] = $child;
                        }
                    }
                }

                break;

            case 'file':

                $result->mime = $this->mime( $full );

                break;
        }

        return $result;
    }

def name!(node)
      return node unless node.is_a?(Parser::AST::Node)
      type = node.type
      return '' if type == :cbase
      first, second = node.children
      if type == :str
        loc = node.loc
        # Preserve quote formatting, some folks may prefer double quotes.
        return "#{loc.begin.source}#{first}#{loc.end.source}"
      end
      first ? [name!(first), second].join('::') : second
    end

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


Question: Create a new list of metrics where all metrics are using the valid character set.

public static List<Metric> toValidValues(List<Metric> metrics) {
    return metrics.stream().map(ValidCharacters::toValidValue).collect(Collectors.toList());
  }

def read(self):
        """"""
        lines = self.readlines()
        if self.metadata and 'encoding' in self.metadata:
            encoding = self.metadata['encoding']
        else:
            encoding = 'utf-8'
        if sys.version < '3':
            return "\n".join( unicode(line, 'utf-8') if isinstance(line, str) else line for line in lines)
        else:
            return "\n".join( str(line, 'utf-8') if isinstance(line, bytes) else line for line in lines)

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


Question:
returns a value associated with the key or the default value

@param   string  $key  key where value is stored under
@return  mixed

public function value($key)
    {
        if (isset($this->data[$key])) {
            return $this->data[$key];
        }

        return null;
    }

public function getPrimaryKey()
    {
        $pks = [];
        foreach ($this->__primaryKeys as $pk) {
            if (is_object($this->$pk)) {
                $traits = class_uses($this->$pk);
                if (isset($traits['Ornament\Model'])
                    || isset($traits['Ornament\JsonModel'])
                ) {
                    $pks[] = $this->$pk->getPrimaryKey();
                } else {
                    $pks[] = "{$this->$pk}";
                }
            } else {
                $pks[] = $this->$pk;
            }
        }
        return count($pks) == 1 ? $pks[0] : $pks;
    }

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


Question:
Read an exception day for a calendar.

@param mpxjCalendar ProjectCalendar instance
@param day ConceptDraw PROJECT exception day

private void readExceptionDay(ProjectCalendar mpxjCalendar, ExceptedDay day)
   {
      ProjectCalendarException mpxjException = mpxjCalendar.addCalendarException(day.getDate(), day.getDate());
      if (day.isIsDayWorking())
      {
         for (Document.Calendars.Calendar.ExceptedDays.ExceptedDay.TimePeriods.TimePeriod period : day.getTimePeriods().getTimePeriod())
         {
            mpxjException.addRange(new DateRange(period.getFrom(), period.getTo()));
         }
      }
   }

private MultipartBody duplicateMultipartBody(MultipartBody body) {

        // It is possible to access individual parts by the Content-Id values
        // This MultipartBody is expected to contain 3 parts,
        // "book1", "book2" and "image".

        // These individual parts have their Content-Type set to
        // application/xml, application/json and application/octet-stream

        // MultipartBody will use the Content-Type value of the individual
        // part to read its data in a type safe way by delegating to a matching
        // JAX-RS MessageBodyReader provider

        Book jaxbBook = body.getAttachmentObject("book1", Book.class);
        Book jsonBook = body.getAttachmentObject("book2", Book.class);

        // Accessing individual attachment part, its DataHandler will be
        // used to access the underlying input stream, the type-safe access
        // is also possible

        Attachment imageAtt = body.getAttachment("image");

        if ("JAXB".equals(jaxbBook.getName()) && 1L == jaxbBook.getId()
            && "JSON".equals(jsonBook.getName()) && 2L == jsonBook.getId()
            && imageAtt != null) {
            return createMultipartBody(jaxbBook, jsonBook, imageAtt.getDataHandler());
        }
        throw new RuntimeException("Received Book attachment is corrupted");
    }

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


Question: // SetObjectIdentifiers sets the ObjectIdentifiers field's value.

func (s *PathToObjectIdentifiers) SetObjectIdentifiers(v []*string) *PathToObjectIdentifiers {
	s.ObjectIdentifiers = v
	return s
}

public KeyArea setupKey(int iKeyArea)
    {
        KeyArea keyArea = null;
        if (iKeyArea == 0)
        {
            keyArea = this.makeIndex(DBConstants.UNIQUE, ID_KEY);
            keyArea.addKeyField(ID, DBConstants.ASCENDING);
        }
        if (iKeyArea == 1)
        {
            keyArea = this.makeIndex(DBConstants.UNIQUE, KEY_KEY);
            keyArea.addKeyField(KEY, DBConstants.ASCENDING);
        }
        if (keyArea == null)
            keyArea = super.setupKey(iKeyArea);
        return keyArea;
    }

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


Question:
Serialize a Boolean as a true or false element.

@param val
boolean to serialize.
@param handler
destination of serialization events.
@throws SAXException
if exception during serialization.

private static void serializeBoolean(final Boolean val, final ContentHandler handler) throws SAXException {
    String tag = "false";
    if (val.booleanValue()) {
      tag = "true";
    }
    final AttributesImpl attributes = new AttributesImpl();
    handler.startElement(null, tag, tag, attributes);
    handler.endElement(null, tag, tag);
  }

function parseFile(file, done) {

    // create stream
    var saxStream = sax.createStream(options.strict, options);

    saxStream.on('error', function(e) {
      // unhandled errors will throw, since this is a proper node
      // event emitter.
      console.error('error!', e);
      // clear the error
      this._parser.error = null;
      this._parser.resume();

      // TODO: send to error callback
    });

    saxStream.on('opentag', function(node) {
      var name = node.name,
          value;

      if (parsedTags.indexOf(name) !== -1) {
        var parser = parsers[name];

        if (!parser) {
          throw new Error('[modelgen] no parser for tag <' + name + '>');
        }

        value = parser(node, this);
      }

      if (value) {
        stack.push(value);
      }
    });

    saxStream.on('closetag', function(nodeName) {
      if (parsedTags.indexOf(nodeName) !== -1) {
        stack.pop();
      }
    });

    saxStream.on('end', function() {

      var result = { byId: elementsById, byType: elementsByType };

      postProcess(result);
      done(null, result);
    });

    // pipe is supported, and it's readable/writable
    // same chunks coming in also go out.
    fs.createReadStream(file).pipe(saxStream);
  }

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


Question:
Checks for empty identifiers in the pre-release version or build metadata.

@throws ParseException
if the pre-release version or build metadata have empty identifier(s)

private void checkForEmptyIdentifier() {
    Character la = chars.lookahead(1);
    if (CharType.DOT.isMatchedBy(la) || CharType.PLUS.isMatchedBy(la)
        || CharType.EOL.isMatchedBy(la)) {
      throw new ParseException("Identifiers MUST NOT be empty", new UnexpectedCharacterException(la,
          chars.currentOffset(), CharType.DIGIT, CharType.LETTER, CharType.HYPHEN));
    }
  }

public static TemplateMetadata fromTemplate(TemplateNode template) {
    TemplateMetadata.Builder builder =
        builder()
            .setTemplateName(template.getTemplateName())
            .setSourceLocation(template.getSourceLocation())
            .setSoyFileKind(SoyFileKind.SRC)
            .setContentKind(template.getContentKind())
            .setStrictHtml(template.isStrictHtml())
            .setDelPackageName(template.getDelPackageName())
            .setVisibility(template.getVisibility())
            .setParameters(Parameter.directParametersFromTemplate(template))
            .setDataAllCallSituations(DataAllCallSituation.fromTemplate(template));
    switch (template.getKind()) {
      case TEMPLATE_BASIC_NODE:
        builder.setTemplateKind(Kind.BASIC);
        break;
      case TEMPLATE_DELEGATE_NODE:
        builder.setTemplateKind(Kind.DELTEMPLATE);
        TemplateDelegateNode deltemplate = (TemplateDelegateNode) template;
        builder.setDelTemplateName(deltemplate.getDelTemplateName());
        builder.setDelTemplateVariant(deltemplate.getDelTemplateVariant());
        break;
      case TEMPLATE_ELEMENT_NODE:
        builder.setTemplateKind(Kind.ELEMENT);
        break;
      default:
        throw new AssertionError("unexpected template kind: " + template.getKind());
    }
    return builder.build();
  }

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


Question:
Get the {@link List} of {@link ServiceStatus} instances for all
subsystems.
@return the {@link List} of {@link ServiceStatus} instances.

public List<ServiceStatus> getAllStatuses() {
        List<ServiceStatus> list = getCriticalStatuses();
        list.addAll(getNonCriticalStatuses());
        return list;
    }

async def manage(self):

        self._vms = await self.iaas.list_vms(self.name)

        vms_stat = Counter([vm.get_state() for vm in self._vms])
        missing = self.count - len(self._vms) if len(self._vms) < self.count else 0
        logging.info(
            'VMs Status: %s expected, %s in iaas, %s running, %s nearby shutdown, %s pending, %s after time shutdown, '
            '%s terminated, %s error, %s unknown, %s missing',
            self.count, len(self._vms), vms_stat[VmState.RUNNING.value], vms_stat[VmState.NEARBY_SHUTDOWN.value],
            vms_stat[VmState.PENDING.value], vms_stat[VmState.AFTER_TIME_SHUTDOWN.value],
            vms_stat[VmState.TERMINATED.value], vms_stat[VmState.ERROR.value], vms_stat[VmState.UNKNOWN.value], missing, extra=self._extra
        )
        for vm in self._vms:
            if vm.is_dead():
                logging.info("Terminate %s", vm, extra=self._extra)
                await vm.terminate()
                self.terminated += 1
        to_create = self.count - (len(self._vms) - self.terminated - vms_stat[VmState.NEARBY_SHUTDOWN.value])
        to_create = to_create if to_create > 0 else 0
        logging.debug("Create %s Vm", to_create, extra=self._extra)
        await self._create_vms(to_create)
        await self._healthcheck(self._vms)
        logging.info(
            'VMs Status update: %s terminated, %s terminated by healthcheck, %s created, %s failed healthcheck',
            self.terminated, self.healthcheck_terminated, to_create, len(self.runtime.failed_checks),
            extra=self._extra
        )

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


Question:
Add the bonds for a given atom.
@param atom the atom for which bonds are to be formed
@param atomsInGroup the list of atoms in the group
@param allAtoms the list of atoms in the whole structure

private void addBonds(Atom atom, List<Atom> atomsInGroup, List<Atom> allAtoms) {
		if(atom.getBonds()==null){
			return;
		}
		for(Bond bond : atom.getBonds()) {
			// Now set the bonding information.
			Atom other = bond.getOther(atom);
			// If both atoms are in the group
			if (atomsInGroup.indexOf(other)!=-1){
				Integer firstBondIndex = atomsInGroup.indexOf(atom);
				Integer secondBondIndex = atomsInGroup.indexOf(other);
				// Don't add the same bond twice
				if(firstBondIndex>secondBondIndex){
					int bondOrder = bond.getBondOrder();
					mmtfDecoderInterface.setGroupBond(firstBondIndex, secondBondIndex, bondOrder);
				}
			}
			// Otherwise it's an inter group bond - so add it here
			else {
				Integer firstBondIndex = allAtoms.indexOf(atom);
				Integer secondBondIndex = allAtoms.indexOf(other);
				if(firstBondIndex>secondBondIndex){
					// Don't add the same bond twice
					int bondOrder = bond.getBondOrder();
					mmtfDecoderInterface.setInterGroupBond(firstBondIndex, secondBondIndex, bondOrder);
				}
			}
		}
	}

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:
Collect the nearest type variables and effective parameters from the type,
        its bases, and their origins as necessary.

def derive_configuration(cls):

        base_params = cls.base.__parameters__
        if hasattr(cls.type, '__args__'):
            # typing as of commit abefbe4
            tvars = {p: p for p in base_params}
            types = {}
            for t in iter_generic_bases(cls.type):
                if t is cls.base:
                    type_vars = tuple(tvars[p] for p in base_params)
                    parameters = (types.get(tvar, tvar) for tvar in type_vars)
                    break
                if t.__args__:
                    for arg, tvar in zip(t.__args__, t.__origin__.__parameters__):
                        if isinstance(arg, typing.TypeVar):
                            tvars[tvar] = tvars.get(arg, arg)
                        else:
                            types[tvar] = arg
        else:
            # typing 3.5.0
            tvars = [None] * len(base_params)
            for t in iter_generic_bases(cls.type):
                for i, p in enumerate(t.__parameters__):
                    if tvars[i] is None and isinstance(p, typing.TypeVar):
                        tvars[i] = p
                if all(tvars):
                    type_vars = tvars
                    parameters = cls.type.__parameters__
                    break
        cls.type_vars = type_vars
        cls.parameters = tuple(normalize_type(p, 1) for p in parameters)

def _get_corresponding_parsers(self, func):
        """"""
        if func in self._used_functions:
            yield self
        if self._subparsers_action is not None:
            for parser in self._subparsers_action.choices.values():
                for sp in parser._get_corresponding_parsers(func):
                    yield sp

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


Question:
Return a thumbnail for the embeded video

@return string - the thumbnail href

public function image() {
		if (empty($this->_stub['image-src'])) {
			return '';
		}
		$thumb = $this->_stub['image-src'];

		$count = count($this->_match);
		for ($i = 1; $i <= $count; $i++) {
			$thumb = str_ireplace('$' . $i, $this->_match[$i - 1], $thumb);
		}

		return $thumb;
	}

protected function _singleMeta($name, $content)
    {
        if( stripos($name, 'http:') === 0 )
        {
            $name = ' http-equiv="'.str_ireplace('http:', NULL, $name).'"';
        }
        elseif( stripos($name, 'property:') === 0 )
        {
            $name = ' property="'.str_ireplace('property:', NULL, $name).'"';
        }
        else
        {
            $name = ' name="'.str_ireplace('name:', NULL, $name).'"';
        }

        if( ! empty($content) )
        {
            $content = ' content="'.$content.'"';
        }
        else
        {
            $content = '';
        }

        return '<meta' . $name . $content . ' />' . EOL;
    }

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


Question: Create and use a tab-completer object

def _tab_complete_init(items, post_prompt, insensitive, fuzzy, stream):
    ''''''
    # using some sort of nested-scope construct is
    # required because readline doesn't pass the necessary args to
    # its callback functions
    def _get_matches(text, state):
        '''
        Get a valid match, given:
            text - the portion of text currently trying to complete
            state - the index 0..inf which is an index into the list
            of valid matches.
        Put another way, given the text, this function is supposed
        to return matches_for(text)[state], where 'matches_for' returns
        the matches for the text from the options.
        '''
        # a copy of all the valid options
        options = [o for o in items]
        # the full user-entered text
        full_text = _readline.get_line_buffer()
        # insensitivity
        if insensitive:
            options = [o.lower() for o in options]
            text = text.lower()
            full_text = full_text.lower()
        # matches
        matches = []
        try:
            # get matches
            if fuzzy:
                # space-delimited - match words
                _readline.set_completer_delims(' ')
                matches = _get_fuzzy_tc_matches(text, full_text, options)
            else:
                # not delimited - match the whole text
                _readline.set_completer_delims('')
                matches = _get_standard_tc_matches(text, full_text, options)
            # re-sensitization not necessary - this completes what's on
            # the command prompt.  If the search is insensitive, then
            # a lower-case entry will match as well as an original-case
            # entry.
        except Exception:
            # try/catch is for debugging only.  The readline
            # lib swallows exceptions and just doesn't print anything
            import traceback as _traceback
            print(_traceback.format_exc())
            raise
        return matches[state]

    def _completion_display(substitution, matches, length):
        '''
        Display the matches for the substitution, which is the
        text being completed.
        '''
        try:
            response = substitution
            stream.write("\n[!] \"{response}\" matches multiple options:\n".format(
                response=response
            ))
            if fuzzy:
                if insensitive:
                    ordered_matches = [o for o in items if substitution in o.lower()]
                else:
                    ordered_matches = [o for o in items if substitution in o]
            else:
                if insensitive:
                    ordered_matches = [o for o in items if o.lower().startswith(substitution)]
                else:
                    ordered_matches = [o for o in items if o.startswith(substitution)]
            for match in ordered_matches:
                stream.write("[!]   {}\n".format(match))
            stream.write("[!] Please specify your choice further.\n")
            # the full user-entered text
            full_text = _readline.get_line_buffer()
            stream.write(post_prompt + full_text)
            stream.flush()
        except Exception:
            # try/catch is for debugging only.  The readline
            # lib swallows exceptions and just doesn't print anything
            #import traceback as _traceback
            #print(_traceback.format_exc())
            raise

    # activate tab completion
    # got libedit bit from:
    # https://stackoverflow.com/a/7116997
    # -----------------------------------
    if "libedit" in _readline.__doc__:
        # tabcompletion init for libedit
        _readline.parse_and_bind("bind ^I rl_complete")
    else:
        # tabcompletion init for actual readline
        _readline.parse_and_bind("tab: complete")
    # -----------------------------------
    # set the function that will actually provide the valid completions
    _readline.set_completer(_get_matches)
    # set the function that will display the valid completions
    _readline.set_completion_display_matches_hook(_completion_display)

def get_arg_name(self, param):

        if self.current_command in self.cmdtab:
            for arg in self.cmdtab[self.current_command].arguments:

                for name in self.cmdtab[self.current_command].arguments[arg].options_list:
                    if name == param:
                        return arg
        return None

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


Question:
Fetch a flattened array of a nested array element.

@param array  $array
@param string $key

@return array

public static function fetch( $array, $key )
    {
        $result = [ ];

        foreach ( explode( '.', $key ) as $segment )
        {
            foreach ( $array as $value )
            {
                $value = ( array ) $value;

                $result[ ] = $value[ $segment ];
            }

            $array = array_values( $result );
        }

        return array_values( $result );
    }

function flatten(srcArr, isDeep) {
      var tmpArr = [];
      forEach(srcArr, function (val) {
        if (isArr(val)) {
          tmpArr.push.apply(tmpArr, isDeep ? flatten(val, true) : val);
        } else {
          tmpArr.push(val);
        }
      });
      return tmpArr;
    }

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


Question: per oidc-connect-core-1.0 sec 5.3.2, sub claim of userinfo response must match sub claim in id token.

protected boolean isUserInfoValid(String userInfoStr, String subClaim) {
        String userInfoSubClaim = getUserInfoSubClaim(userInfoStr);
        if (userInfoSubClaim == null || subClaim == null || userInfoSubClaim.compareTo(subClaim) != 0) {
            Tr.error(tc, "USERINFO_INVALID", new Object[] { userInfoStr, subClaim });
            return false;
        }
        return true;
    }

func (s *Storage) LoadAuthorize(code string) (*osin.AuthorizeData, error) {

	// Load Authorize from DB
	var authorize service.Authorize
	if err := dbconn.DB.Where("code = ?", code).Find(&authorize).Error; err != nil {
		return nil, err
	}

	// Copy Authorize in OSIN AuthorizeData
	var data osin.AuthorizeData
	copier.Copy(&data, &authorize)

	c, err := s.GetClient(authorize.Client)
	if err != nil {
		return nil, err
	}

	if data.ExpireAt().Before(time.Now()) {
		return nil, errors.Errorf("Token expired at %s.", data.ExpireAt().String())
	}

	data.Client = c
	return &data, nil
}

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


Question: Recursively gets attributes inside `module` as specified by `path`.

def _recursive_getattr(module, path):
  """"""
  if "." not in path:
    return getattr(module, path)
  else:
    first, rest = path.split(".", 1)
    return _recursive_getattr(getattr(module, first), rest)

def _parse_tree(self, node):

        if 'filename' in node.attrib:
            self.filename = node.attrib['filename']
        if 'type' in node.attrib:
            self.kind = node.attrib['type']
        if 'target' in node.attrib:
            self.target = node.attrib['target']
        self.value = node.text

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


Question:
Import the uploaded file. Existing languages and translations will be updated, new ones will be created.
Source messages won't be updated, only created if they not exist.

@return array

@throws BadRequestHttpException
@throws Exception

public function import()
    {
        $result = [
            'languages' => ['new' => 0, 'updated' => 0],
            'languageSources' => ['new' => 0, 'updated' => 0],
            'languageTranslations' => ['new' => 0, 'updated' => 0],
        ];

        $data = $this->parseImportFile();

        /** @var Language[] $languages */
        $languages = Language::find()->indexBy('language_id')->all();

        foreach ($data['languages'] as $importedLanguage) {
            if (isset($languages[$importedLanguage['language_id']])) {
                $language = $languages[$importedLanguage['language_id']];
            } else {
                $language = new Language();
            }

            //cast integers
            $importedLanguage['status'] = (int) $importedLanguage['status'];

            $language->attributes = $importedLanguage;
            if (count($language->getDirtyAttributes())) {
                $saveType = $language->isNewRecord ? 'new' : 'updated';
                if ($language->save()) {
                    ++$result['languages'][$saveType];
                } else {
                    $this->throwInvalidModelException($language);
                }
            }
        }

        /** @var LanguageSource[] $languageSources */
        $languageSources = LanguageSource::find()->indexBy('id')->all();

        /** @var LanguageTranslate[] $languageTranslations */
        $languageTranslations = LanguageTranslate::find()->all();

        /*
         *  Create 2 dimensional array for current and imported translation, first index by LanguageSource->id
         *  and than indexed by LanguageTranslate->language.
         *  E.g.: [
         *      id => [
         *          language => LanguageTranslate (for $languageTranslations) / Array (for $importedLanguageTranslations)
         *          ...
         *      ]
         *      ...
         * ]
         */
        $languageTranslations = ArrayHelper::map($languageTranslations, 'language', function ($languageTranslation) {
            return $languageTranslation;
        }, 'id');
        $importedLanguageTranslations = ArrayHelper::map($data['languageTranslations'], 'language', function ($languageTranslation) {
            return $languageTranslation;
        }, 'id');

        foreach ($data['languageSources'] as $importedLanguageSource) {
            $languageSource = null;

            //check if id exist and if category and messages are matching
            if (isset($languageSources[$importedLanguageSource['id']]) &&
                ($languageSources[$importedLanguageSource['id']]->category == $importedLanguageSource['category']) &&
                ($languageSources[$importedLanguageSource['id']]->message == $importedLanguageSource['message'])
            ) {
                $languageSource = $languageSources[$importedLanguageSource['id']];
            }

            if (is_null($languageSource)) {
                //no match by id, search by message
                foreach ($languageSources as $languageSourceSearch) {
                    if (($languageSourceSearch->category == $importedLanguageSource['category']) &&
                        ($languageSourceSearch->message == $importedLanguageSource['message'])
                    ) {
                        $languageSource = $languageSourceSearch;
                        break;
                    }
                }
            }

            if (is_null($languageSource)) {
                //still no match, create new
                $languageSource = new LanguageSource([
                    'category' => $importedLanguageSource['category'],
                    'message' => $importedLanguageSource['message'],
                ]);

                if ($languageSource->save()) {
                    ++$result['languageSources']['new'];
                } else {
                    $this->throwInvalidModelException($languageSource);
                }
            }

            //do we have translations for the current source?
            if (isset($importedLanguageTranslations[$importedLanguageSource['id']])) {
                //loop through the translations for the current source
                foreach ($importedLanguageTranslations[$importedLanguageSource['id']] as $importedLanguageTranslation) {
                    $languageTranslate = null;

                    //is there already a translation for this souce
                    if (isset($languageTranslations[$languageSource->id]) &&
                        isset($languageTranslations[$languageSource->id][$importedLanguageTranslation['language']])
                    ) {
                        $languageTranslate = $languageTranslations[$languageSource->id][$importedLanguageTranslation['language']];
                    }

                    //no translation found, create a new one
                    if (is_null($languageTranslate)) {
                        $languageTranslate = new LanguageTranslate();
                    }

                    $languageTranslate->attributes = $importedLanguageTranslation;

                    //overwrite the id because the $languageSource->id might be different from the $importedLanguageTranslation['id']
                    $languageTranslate->id = $languageSource->id;

                    if (count($languageTranslate->getDirtyAttributes())) {
                        $saveType = $languageTranslate->isNewRecord ? 'new' : 'updated';
                        if ($languageTranslate->save()) {
                            ++$result['languageTranslations'][$saveType];
                        } else {
                            $this->throwInvalidModelException($languageTranslate);
                        }
                    }
                }
            }
        }

        return $result;
    }

public function add(Message $message)
    {
        $this->queue->insert($message, is_null($message->getPosition()) ? null : -$message->getPosition());

        $this->copyQueue(clone $this->queue);

        return $this;
    }

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


Question:
Returns HTML representation of the node including children nodes

@param $columnNames
@return string

public function getHTML($columnNames = null)
    {
        if ($this->isTerminal) {
            $value = "$this->classValue";
        } else {
            $value = $this->value;
            if ($columnNames !== null) {
                $col = $columnNames[$this->columnIndex];
            } else {
                $col = "col_$this->columnIndex";
            }
            if (!preg_match("/^[<>=]{1,2}/", $value)) {
                $value = "=$value";
            }
            $value = "$col $value
Gini: ". number_format($this->giniIndex, 2);
        }
        $str = "

				$value
";
        if ($this->leftLeaf || $this->rightLeaf) {
            $str .='
';
            if ($this->leftLeaf) {
                $str .="| Yes
" . $this->leftLeaf->getHTML($columnNames) . "	";
            } else {
                $str .='	';
            }
            $str .=' 	';
            if ($this->rightLeaf) {
                $str .="No |
" . $this->rightLeaf->getHTML($columnNames) . "	";
            } else {
                $str .='	';
            }
            $str .= '
';
        }
        $str .= '
';
        return $str;
    }

private function renderComponentTable( $network, $elr )
	{
		$table = $this->getTaxonomyDescriptionForIdWithDefaults( reset( $network['tables'] ) );

		$componentTable =
			"
" .
			"
Component: Network plus Table
" .
			"
" .
			"
Network
" .
			"
" .
			"
{$network['text']}
" .
			"
$elr
" .
			"
" .
			"
Table
" .
			"
$table
" .
			"
" .
			"
";

		return $componentTable;
	}

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


Question:
Init data group.

@param paramType the param type
@param lists     the lists

public void initDataGroup(ParamType paramType, List<ValidationData> lists) {
        this.paramType = paramType;

        lists.forEach(vd -> {
            this.addRule(vd);
        });

    }

function namedParameterList()
    {
        $def = array( $this->Name => array( 'context' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => false ),
                                            'comment' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => '' ),
                                            'arguments' => array( 'type' => 'hash',
                                                                  'required' => false,
                                                                  'default' => false ) ),
                      $this->ExtensionName => array( 'extension' => array( 'type' => 'string',
                                                                           'required' => true,
                                                                           'default' => false ),
                                                     'context' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => false ),
                                                     'comment' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => '' ),
                                                     'arguments' => array( 'type' => 'hash',
                                                                           'required' => false,
                                                                           'default' => false ) ) );
        $def[ $this->DynamicName ] = $def[ $this->Name ];
        return $def;
    }

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


Question:
Return the aggregate that handles the requested command.
@param {String} name    command name
@param {Number} version command version
@returns {Aggregate}

function (name, version) {
    if (!name || !_.isString(name)) {
      throw new Error('Please pass in a command name!');
    }

    for (var a in this.aggregates) {
      var aggr = this.aggregates[a];
      var cmd = aggr.getCommand(name, version);
      if (cmd) {
        return aggr;
      }
    }

    for (var a in this.aggregates) {
      var aggr = this.aggregates[a];
      var cmdHndl = aggr.getCommandHandler(name, version);
      if (cmdHndl && cmdHndl !== aggr.defaultCommandHandler) {
        return aggr;
      }
    }

    debug('no matching aggregate found for command ' + name);

    return null;
  }

public function run(InputInterface $input, OutputInterface $output, array $args)
    {
        $arguments = [];
        $options   = [];

        foreach ($args as $arg) {
            $matches = [];
            if (0 < preg_match('/^\-{1,2}(?<key>[^\=]+)(\=(?<value>.*))?$/', $arg, $matches)) {
                $options[$matches['key']] = isset($matches['value']) ? $matches['value'] : true;
            } else {
                $arguments[] = $arg;
            }
        }

        if (!count($arguments)) {
            array_unshift($arguments, 'help');
        }

        $config = new Config(
            [
                'uses' => [
                    'core'     => null,
                    'git'      => null,
                    'php'      => null,
                    'composer' => null,
                    'phpunit'  => null,
                    'phpcs'    => null,
                    'travis'   => null,
                    'npm'      => null,
                    'gulp'     => null,
                    'itiqiti'  => null,
                ],
            ]
        );

        $el = new ExpressionLanguage();

        $expressionService = new ExpressionService($el);
        $s                 = new Service\ConfigService($expressionService);

        $s->load($config);

        $commandNames = array_shift($arguments);

        return $this->executeCommandFromName($input, $output, $commandNames, $arguments, $options, $config, $s);
    }

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


Question:
Return the event position, if it exists.

        An event exist if:
        * end is < 0
        * event_type is matching
        Return -1 if the item is not found.

def __event_exist(self, event_type):

        for i in range(self.len()):
            if self.events_list[i][1] < 0 and self.events_list[i][3] == event_type:
                return i
        return -1

public static function view_entries($filters = array()) {

        $warnings = array();
        $params = self::validate_parameters(self::view_entries_parameters(), array('filters' => $filters));

        list($context, $filters, $courseid, $userid) = self::validate_access_and_filters($params['filters']);

        $eventparams = array(
            'other' => array('entryid' => $filters['entryid'], 'tagid' => $filters['tagid'], 'userid' => $userid,
                'modid' => $filters['cmid'], 'groupid' => $filters['groupid'], 'search' => $filters['search']
            )
        );
        if (!empty($userid)) {
            $eventparams['relateduserid'] = $userid;
        }
        $eventparams['other']['courseid'] = ($courseid === SITEID) ? 0 : $courseid;
        $event = \core\event\blog_entries_viewed::create($eventparams);
        $event->trigger();

        return array(
            'warnings' => $warnings,
            'status' => true,
        );
    }

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


Question: // Validate inspects the fields of the type to determine if they are valid.

func (s *GetRouteResponseInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "GetRouteResponseInput"}
	if s.ApiId == nil {
		invalidParams.Add(request.NewErrParamRequired("ApiId"))
	}
	if s.ApiId != nil && len(*s.ApiId) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("ApiId", 1))
	}
	if s.RouteId == nil {
		invalidParams.Add(request.NewErrParamRequired("RouteId"))
	}
	if s.RouteId != nil && len(*s.RouteId) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("RouteId", 1))
	}
	if s.RouteResponseId == nil {
		invalidParams.Add(request.NewErrParamRequired("RouteResponseId"))
	}
	if s.RouteResponseId != nil && len(*s.RouteResponseId) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("RouteResponseId", 1))
	}

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

func (s *messageStoreImpl) CheckValid(message interface{}) bool {
	s.lock.RLock()
	defer s.lock.RUnlock()

	for _, m := range s.messages {
		if s.pol(message, m.data) == common.MessageInvalidated {
			return false
		}
	}
	return true
}

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


Question: // LoadReader creates a Tree from any io.Reader.

func LoadReader(reader io.Reader) (tree *Tree, err error) {
	inputBytes, err := ioutil.ReadAll(reader)
	if err != nil {
		return
	}
	tree, err = LoadBytes(inputBytes)
	return
}

protected void addTagsInfo(Doc doc, Content htmltree) {
        if (configuration.nocomment) {
            return;
        }
        Content dl = new HtmlTree(HtmlTag.DL);
        if (doc instanceof MethodDoc) {
            addMethodInfo((MethodDoc) doc, dl);
        }
        Content output = new ContentBuilder();
        TagletWriter.genTagOuput(configuration.tagletManager, doc,
            configuration.tagletManager.getCustomTaglets(doc),
                getTagletWriterInstance(false), output);
        dl.addContent(output);
        htmltree.addContent(dl);
    }

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


Question:
Transform operator in different formats to canonical array form

@param mixed $mixed
@return array
@throws \Sokil\Mongo\Exception

public static function convertToArray($mixed)
    {
        // get operator from callable
        if (is_callable($mixed)) {
            $callable = $mixed;
            $mixed = new self();
            call_user_func($callable, $mixed);
        }

        // get operator array
        if ($mixed instanceof ArrayableInterface && $mixed instanceof self) {
            $mixed = $mixed->toArray();
        } elseif (!is_array($mixed)) {
            throw new Exception('Mixed must be instance of Operator');
        }

        return $mixed;
    }

def handle_moban_file(moban_file, options):

    moban_file_configurations = load_data(None, moban_file)
    if moban_file_configurations is None:
        raise exceptions.MobanfileGrammarException(
            constants.ERROR_INVALID_MOBAN_FILE % moban_file
        )
    if (
        constants.LABEL_TARGETS not in moban_file_configurations
        and constants.LABEL_COPY not in moban_file_configurations
    ):
        raise exceptions.MobanfileGrammarException(
            constants.ERROR_NO_TARGETS % moban_file
        )
    check_none(moban_file_configurations, moban_file)
    version = moban_file_configurations.get(
        constants.MOBAN_VERSION, constants.DEFAULT_MOBAN_VERSION
    )
    if version == constants.DEFAULT_MOBAN_VERSION:
        mobanfile.handle_moban_file_v1(moban_file_configurations, options)
    else:
        raise exceptions.MobanfileGrammarException(
            constants.MESSAGE_FILE_VERSION_NOT_SUPPORTED % version
        )
    HASH_STORE.save_hashes()

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


Question: // Remove removes the message with given ID from the store.

func (s *messageStore) Remove(id uint64) {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	delete(s.messages, id)
}

public final boolean isRemoved(final String key) {
        final Property prop = find(key);
        if (prop == null) {
            return true;
        }
        return prop.isDeleted();
    }

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


Question:
@static

@param $_view

@return bool|mixed|string|void

private static function locate_template( $_view ) {

		if ( is_array( $_view ) ) {
			$_views = array();

			if ( isset( $_view[0] ) && false === strpos( $_view[0], '.php' ) ) {
				$_view_count = count( $_view );

				for ( $_view_x = $_view_count; 0 < $_view_x; $_view_x -- ) {
					$_view_v = array_slice( $_view, 0, $_view_x );

					$_views[] = implode( '-', $_view_v ) . '.php';
				}
			} else {
				$_views = $_view;
			}

			$_view = false;

			foreach ( $_views as $_view_check ) {
				$_view = self::locate_template( $_view_check );

				if ( ! empty( $_view ) ) {
					break;
				}
			}

			return $_view;
		}//end if

		// Keep it safe
		$_view = trim( str_replace( array( '../', '\\' ), array( '', '/' ), (string) $_view ) );

		if ( empty( $_view ) ) {
			return false;
		}

		$_real_view = realpath( $_view );

		if ( empty( $_real_view ) ) {
			$_real_view = $_view;
		}

		$located = false;

		// Is the view's file somewhere within the plugin directory tree?
		// Note: we explicitly whitelist PODS_DIR for the case of symlinks (see issue #2945)
		if ( false !== strpos( $_real_view, realpath( WP_PLUGIN_DIR ) ) || false !== strpos( $_real_view, realpath( WPMU_PLUGIN_DIR ) ) || false !== strpos( $_real_view, PODS_DIR ) ) {
			if ( file_exists( $_view ) ) {
				$located = $_view;
			} else {
				$located = apply_filters( 'pods_view_locate_template', $located, $_view );
			}
		} else {
			// The view's file is outside the plugin directory
			$_real_view = trim( $_real_view, '/' );

			if ( empty( $_real_view ) ) {
				return false;
			}

			// Allow views in the theme or child theme
			if ( file_exists( realpath( get_stylesheet_directory() . '/' . $_real_view ) ) ) {
				$located = realpath( get_stylesheet_directory() . '/' . $_real_view );
			} elseif ( file_exists( realpath( get_template_directory() . '/' . $_real_view ) ) ) {
				$located = realpath( get_template_directory() . '/' . $_real_view );
			}
		}//end if

		return $located;

	}

public function prepareError($message, $errors=[], $code=404) {
        $this->prepareResult(false, $message, $code, null , $errors);
    }

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


Question: // CreateTargetFrom is a helper function

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

func New(c rest.Interface) *Clientset {
	var cs Clientset
	cs.template = templateinternalversion.New(c)

	cs.DiscoveryClient = discovery.NewDiscoveryClient(c)
	return &cs
}

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


Question: // Whitelist an Add-on Service

func (s *Service) WhitelistedAddOnServiceCreateByOrganization(ctx context.Context, organizationIdentity string, o WhitelistedAddOnServiceCreateByOrganizationOpts) (WhitelistedAddOnServiceCreateByOrganizationResult, error) {
	var whitelistedAddOnService WhitelistedAddOnServiceCreateByOrganizationResult
	return whitelistedAddOnService, s.Post(ctx, &whitelistedAddOnService, fmt.Sprintf("/organizations/%v/whitelisted-addon-services", organizationIdentity), o)
}

function registerExtension(ext) {
  var old = oldHandlers[ext] || oldHandlers[".js"] || require.extensions[".js"];

  var loader = normalLoader;
  if (process.env.running_under_istanbul) loader = istanbulLoader;

  require.extensions[ext] = function (m, filename) {
    if (shouldIgnore(filename)) {
      old(m, filename);
    } else {
      loader(m, filename, old);
    }
  };
}

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


Question:
Returns the list of URLs that can be accessed, and the function/method that should be called when the URL is called.

@param string $instanceName The identifier for this object in the container.

@return SplashRoute[]

public function getUrlsList($instanceName)
    {
        $route = new SplashRoute($this->url, $instanceName, 'action', null, null);

        return array($route);
    }

public function process(ContainerBuilder $container)
    {
        $bundles         = $container->getParameter('kernel.bundles');
        $bundleContainer = $container->getDefinition('atoum.configuration.bundle.container');
        $configuration   = $container->getParameterBag()->resolveValue($container->getParameter('atoum.bundles'));

        foreach ($configuration as $bundleName => $data) {
            if (!isset($bundles[$bundleName])) {
                throw new \LogicException(sprintf('Bundle "%s" does not exists.', $bundleName));
            }

            $rc        = new \ReflectionClass($bundles[$bundleName]);
            $directory = dirname($rc->getFileName());

            $directories = array_map(
                function ($v) use ($directory) {
                    return $directory.'/'.$v;
                },
                $data['directories']
            );

            $definition = new Definition(
                $container->getParameter('atoum.configuration.bundle.class'),
                array($bundleName, $directories)
            );

            $bundleContainer->addMethodCall('add', array($definition));
        }
    }

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


Question:
Returns the currency for the given ISO country code.

@param string $countryCode The 2-letter ISO 3166-1 country code.

@return Currency

@throws UnknownCurrencyException If the country code is not known, or the country has no single currency.

public function getCurrencyForCountry(string $countryCode) : Currency
    {
        $currencies = $this->getCurrenciesForCountry($countryCode);

        $count = count($currencies);

        if ($count === 1) {
            return $currencies[0];
        }

        if ($count === 0) {
            throw UnknownCurrencyException::noCurrencyForCountry($countryCode);
        }

        $currencyCodes = [];

        foreach ($currencies as $currency) {
            $currencyCodes[] = $currency->getCurrencyCode();
        }

        throw UnknownCurrencyException::noSingleCurrencyForCountry($countryCode, $currencyCodes);
    }

func New() locales.Translator {
	return &mfe_MU{
		locale:                 "mfe_MU",
		pluralsCardinal:        nil,
		pluralsOrdinal:         nil,
		pluralsRange:           nil,
		group:                  " ",
		timeSeparator:          ":",
		currencies:             []string{"ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", "ANG", "AOA", "AOK", "AON", "AOR", "ARA", "ARL", "ARM", "ARP", "ARS", "ATS", "AUD", "AWG", "AZM", "AZN", "BAD", "BAM", "BAN", "BBD", "BDT", "BEC", "BEF", "BEL", "BGL", "BGM", "BGN", "BGO", "BHD", "BIF", "BMD", "BND", "BOB", "BOL", "BOP", "BOV", "BRB", "BRC", "BRE", "BRL", "BRN", "BRR", "BRZ", "BSD", "BTN", "BUK", "BWP", "BYB", "BYN", "BYR", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLE", "CLF", "CLP", "CNH", "CNX", "CNY", "COP", "COU", "CRC", "CSD", "CSK", "CUC", "CUP", "CVE", "CYP", "CZK", "DDM", "DEM", "DJF", "DKK", "DOP", "DZD", "ECS", "ECV", "EEK", "EGP", "ERN", "ESA", "ESB", "ESP", "ETB", "EUR", "FIM", "FJD", "FKP", "FRF", "GBP", "GEK", "GEL", "GHC", "GHS", "GIP", "GMD", "GNF", "GNS", "GQE", "GRD", "GTQ", "GWE", "GWP", "GYD", "HKD", "HNL", "HRD", "HRK", "HTG", "HUF", "IDR", "IEP", "ILP", "ILR", "ILS", "INR", "IQD", "IRR", "ISJ", "ISK", "ITL", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRH", "KRO", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LTT", "LUC", "LUF", "LUL", "LVL", "LVR", "LYD", "MAD", "MAF", "MCF", "MDC", "MDL", "MGA", "MGF", "MKD", "MKN", "MLF", "MMK", "MNT", "MOP", "MRO", "MTL", "MTP", "MUR", "MVP", "MVR", "MWK", "MXN", "MXP", "MXV", "MYR", "MZE", "MZM", "MZN", "NAD", "NGN", "NIC", "NIO", "NLG", "NOK", "NPR", "NZD", "OMR", "PAB", "PEI", "PEN", "PES", "PGK", "PHP", "PKR", "PLN", "PLZ", "PTE", "PYG", "QAR", "RHD", "ROL", "RON", "RSD", "RUB", "RUR", "RWF", "SAR", "SBD", "SCR", "SDD", "SDG", "SDP", "SEK", "SGD", "SHP", "SIT", "SKK", "SLL", "SOS", "SRD", "SRG", "SSP", "STD", "STN", "SUR", "SVC", "SYP", "SZL", "THB", "TJR", "TJS", "TMM", "TMT", "TND", "TOP", "TPE", "TRL", "TRY", "TTD", "TWD", "TZS", "UAH", "UAK", "UGS", "UGX", "USD", "USN", "USS", "UYI", "UYP", "UYU", "UZS", "VEB", "VEF", "VND", "VNN", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XEU", "XFO", "XFU", "XOF", "XPD", "XPF", "XPT", "XRE", "XSU", "XTS", "XUA", "XXX", "YDD", "YER", "YUD", "YUM", "YUN", "YUR", "ZAL", "ZAR", "ZMK", "ZMW", "ZRN", "ZRZ", "ZWD", "ZWL", "ZWR"},
		currencyPositivePrefix: " ",
		currencyPositiveSuffix: "K",
		currencyNegativePrefix: " ",
		currencyNegativeSuffix: "K",
		monthsAbbreviated:      []string{"", "zan", "fev", "mar", "avr", "me", "zin", "zil", "out", "sep", "okt", "nov", "des"},
		monthsNarrow:           []string{"", "z", "f", "m", "a", "m", "z", "z", "o", "s", "o", "n", "d"},
		monthsWide:             []string{"", "zanvie", "fevriye", "mars", "avril", "me", "zin", "zilye", "out", "septam", "oktob", "novam", "desam"},
		daysAbbreviated:        []string{"dim", "lin", "mar", "mer", "ze", "van", "sam"},
		daysNarrow:             []string{"d", "l", "m", "m", "z", "v", "s"},
		daysWide:               []string{"dimans", "lindi", "mardi", "merkredi", "zedi", "vandredi", "samdi"},
		erasAbbreviated:        []string{"av. Z-K", "ap. Z-K"},
		erasNarrow:             []string{"", ""},
		erasWide:               []string{"avan Zezi-Krist", "apre Zezi-Krist"},
		timezones:              map[string]string{"CLT": "CLT", "CLST": "CLST", "AWDT": "AWDT", "ADT": "ADT", "WESZ": "WESZ", "HNNOMX": "HNNOMX", "UYST": "UYST", "HECU": "HECU", "WEZ": "WEZ", "GFT": "GFT", "JDT": "JDT", "AKST": "AKST", "HKT": "HKT", "CHADT": "CHADT", "NZST": "NZST", "ACDT": "ACDT", "MST": "MST", "HAST": "HAST", "WAST": "WAST", "SGT": "SGT", "HEOG": "HEOG", "EST": "EST", "EAT": "EAT", "WART": "WART", "IST": "IST", "MDT": "MDT", "OESZ": "OESZ", "HNEG": "HNEG", "LHDT": "LHDT", "TMST": "TMST", "HADT": "HADT", "COT": "COT", "HNPMX": "HNPMX", "BOT": "BOT", "HAT": "HAT", "WARST": "WARST", "PDT": "PDT", "WIB": "WIB", "MYT": "MYT", "LHST": "LHST", "CHAST": "CHAST", "HNCU": "HNCU", "ACWST": "ACWST", "HNT": "HNT", "HENOMX": "HENOMX", "HEPMX": "HEPMX", "HNOG": "HNOG", "MESZ": "MESZ", "∅∅∅": "∅∅∅", "HNPM": "HNPM", "HEPM": "HEPM", "UYT": "UYT", "AWST": "AWST", "NZDT": "NZDT", "AKDT": "AKDT", "MEZ": "MEZ", "EDT": "EDT", "SRT": "SRT", "TMT": "TMT", "OEZ": "OEZ", "ART": "ART", "ARST": "ARST", "SAST": "SAST", "ACST": "ACST", "WITA": "WITA", "HEEG": "HEEG", "ACWDT": "ACWDT", "WIT": "WIT", "GMT": "GMT", "PST": "PST", "AEDT": "AEDT", "HKST": "HKST", "GYT": "GYT", "ChST": "ChST", "WAT": "WAT", "JST": "JST", "BT": "BT", "COST": "COST", "CAT": "CAT", "CST": "CST", "CDT": "CDT", "AST": "AST", "AEST": "AEST", "ECT": "ECT", "VET": "VET"},
	}
}

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


Question: Creates the page URLs in the DSA page feed.

private static void createFeedItems(
      AdWordsServicesInterface adWordsServices,
      AdWordsSession session,
      DSAFeedDetails feedDetails,
      String labelName)
      throws RemoteException {
    // Get the FeedItemService.
    FeedItemServiceInterface feedItemService =
        adWordsServices.get(session, FeedItemServiceInterface.class);

    // Create operations to add FeedItems.
    FeedItemOperation[] operations =
        new FeedItemOperation[] {
          createDsaUrlAddOperation(
              feedDetails, "http://www.example.com/discounts/rental-cars", labelName),
          createDsaUrlAddOperation(
              feedDetails, "http://www.example.com/discounts/hotel-deals", labelName),
          createDsaUrlAddOperation(
              feedDetails, "http://www.example.com/discounts/flight-deals", labelName),
        };

    FeedItemReturnValue result = feedItemService.mutate(operations);
    for (FeedItem item : result.getValue()) {
      System.out.printf("Feed item with feed item ID %d was added.%n", item.getFeedItemId());
    }
  }

func (s *ImportJobRequest) SetS3Url(v string) *ImportJobRequest {
	s.S3Url = &v
	return s
}

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


Question:
Renders the audio.

@param MediaInterface $audio
@param array          $params
@return string
@throws \InvalidArgumentException

public function renderAudio(MediaInterface $audio, array $params = [])
    {
        if ($audio->getType() !== MediaTypes::AUDIO) {
            throw new \InvalidArgumentException('Expected media with "audio" type.');
        }

        $params = array_merge([
            'attr' => [
                'id' => 'media-audio-' . $audio->getId(),
            ],
        ], $params);

        return $this->elementTemplate->renderBlock('audio', [
            'src'  => $this->getDownloadUrl($audio),
            'attr' => $params['attr'],
        ]);
    }

public function call($method, $parameters)
    {
        try {
            $ch = curl_init($this->base_url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->encode($method, $parameters));
            curl_setopt($ch, CURLOPT_TIMEOUT, 600);

            $response = curl_exec($ch);

            if ($response === false) {
                $e = new TransportException(curl_error($ch), curl_getinfo($ch, CURLINFO_HTTP_CODE));
                curl_close($ch);

                throw  $e;
            }

            curl_close($ch);

            return $this->decode($response);
        } catch (XmlrpcException $e) {
            throw new TransportException('XML parsing error', 0, $e);
        }
    }

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


Question:
Génère le fichier d'une vue.

@param  string $name
@return boolean

public function generateView($name)
    {
        if (!$content = $this->getViewContent($name)) {
            return '';
        }

        $sectionSegments = $this->sectionSegments;

        if ($this->viewsDir) {
            array_unshift($sectionSegments, $this->viewsDir);
        }

        $path = base_path('resources/views/'.implode('/', $sectionSegments).'/'.$name.'.php');

        if (is_file($path)) {
            return '';
        }

        $this->createMissingDirs($path);

        return file_put_contents($path, $content) !== false ? $path : '';
    }

private function createView($view, $viewFile, $type, $moduleDir)
    {
        $template = file_get_contents(
            __DIR__.DIRECTORY_SEPARATOR."templates".DIRECTORY_SEPARATOR."view_".$type.".tpl"
        );

        $template = str_replace('$VIEW', $view, $template);

        file_put_contents($viewFile, $template);
    }

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


Question:
Creates a data category from form data.

@since Moodle 3.5
@param string $jsonformdata
@return array

public static function set_contextlevel_form($jsonformdata) {
        global $PAGE;

        $warnings = [];

        $params = external_api::validate_parameters(self::set_contextlevel_form_parameters(), [
            'jsonformdata' => $jsonformdata
        ]);

        // Validate context and access to manage the registry.
        self::validate_context(\context_system::instance());
        api::check_can_manage_data_registry();

        $serialiseddata = json_decode($params['jsonformdata']);
        $data = array();
        parse_str($serialiseddata, $data);

        $contextlevel = $data['contextlevel'];

        $customdata = \tool_dataprivacy\form\contextlevel::get_contextlevel_customdata($contextlevel);
        $mform = new \tool_dataprivacy\form\contextlevel(null, $customdata, 'post', '', null, true, $data);
        if ($validateddata = $mform->get_data()) {
            $contextlevel = api::set_contextlevel($validateddata);
        } else if ($errors = $mform->is_validated()) {
            $warnings[] = json_encode($errors);
        }

        if ($contextlevel) {
            $result = true;
        } else {
            $result = false;
        }
        return [
            'result' => $result,
            'warnings' => $warnings
        ];
    }

public function favorite($accountId, $mediaId, $isFavorite = true, $mediaType = 'movie')
    {
        return $this->postJson('account/' . $accountId . '/favorite', [
            'media_id'   => $mediaId,
            'media_type' => $mediaType,
            'favorite'   => $isFavorite
        ]);
    }

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


Question:
Register metabox hooks.

@return void

public function hooks()
    {
        // Register metabox
        // on admin init.
        $this->hook->action(
            'admin_init',
            [$this->metabox, 'register']
        )->dispatch();

        // Save all metabox meta
        // data on post save.
        $this->hook->action('save_post', function ($id) {
            $this->metabox->getModel()->setContext('post');

            $this->metabox->save($id);
        })->dispatch();

        // Save metabox meta data
        // on the comment save.
        $this->hook->action('edit_comment', function ($id) {
            $this->metabox->getModel()->setContext('comment');

            $this->metabox->save($id);
        })->dispatch();
    }

public function dispatchCommentUpdateEvent(Post $post, Comment $comment, $changeSet)
    {
        $event = new LogCommentUpdateEvent($post, $comment, $changeSet, $this->translator);

        return $this->dispatch($event);
    }

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


Question:
Returns the TokenStream instance for the class.

@return TokenStream

private function getTokenStream(): TokenStream
    {
        if (null === $this->tokens) {
            $this->tokens = new TokenStream(file_get_contents($this->filename));
        }

        return $this->tokens;
    }

public function register(Renderer $renderer) {
        $this->registerTokenRenderer(HeaderAtxRule::NAME, 'renderContent', $renderer);
        $this->registerTokenRenderer(HeaderSetextRule::NAME, 'renderContent', $renderer);
    }

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


Question: // NewMovingMedian returns a MovingMedian with the given window size.

func NewMovingMedian(size int) MovingMedian {
	m := MovingMedian{
		queue:   make([]item, size),
		maxHeap: maxItemHeap{},
		minHeap: minItemHeap{},
	}

	heap.Init(&m.maxHeap)
	heap.Init(&m.minHeap)
	return m
}

public final void acceptBoth(Consumer<? super L> left, Consumer<? super R> right, L defaultLeft, R defaultRight) {
		left.accept(isLeft() ? getLeft() : defaultLeft);
		right.accept(isRight() ? getRight() : defaultRight);
	}

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


Question:
HTML formats a file entry name  for display in the sidebar.
@param {!File} entry File entry to display
@return {string} HTML formatted string

function getFileEntryDisplay(entry) {
        var name = entry.name,
            ext = LanguageManager.getCompoundFileExtension(name),
            i = name.lastIndexOf("." + ext);

        if (i > 0) {
            // Escape all HTML-sensitive characters in filename.
            name = _.escape(name.substring(0, i)) + "" + _.escape(name.substring(i)) + "";
        } else {
            name = _.escape(name);
        }

        return name;
    }

public function get_type_info($type){
		$path_base_dir = __DIR__.'/../templates/';
		if( !is_dir( $path_base_dir.'form_elms/'.urlencode($type).'/' ) ){
			$type = 'text';
		}
		$rtn = array();
		$rtn['type'] = $type;
		$rtn['templates'] = array();
		$rtn['templates']['input'] = 'form_elms/'.urlencode($type).'/input.html';
		$rtn['templates']['preview'] = 'form_elms/'.urlencode($type).'/preview.html';
		$rtn['validate'] = include($path_base_dir.'form_elms/'.urlencode($type).'/validate.php');
		return $rtn;
	}

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


Question:
Called during initialization to populate the list of queues.

@param event the event received

private void handleQueueParamsEvent(QueueParamsEvent event)
    {
        AsteriskQueueImpl queue;

        final String name = event.getQueue();
        final Integer max = event.getMax();
        final String strategy = event.getStrategy();
        final Integer serviceLevel = event.getServiceLevel();
        final Integer weight = event.getWeight();
        final Integer calls = event.getCalls();
        final Integer holdTime = event.getHoldTime();
        final Integer talkTime = event.getTalkTime();
        final Integer completed = event.getCompleted();
        final Integer abandoned = event.getAbandoned();
        final Double serviceLevelPerf = event.getServiceLevelPerf();

        queue = getInternalQueueByName(name);

        if (queue == null)
        {
            queue = new AsteriskQueueImpl(server, name, max, strategy, serviceLevel, weight, calls, holdTime, talkTime,
                    completed, abandoned, serviceLevelPerf);
            logger.info("Adding new queue " + queue);
            addQueue(queue);
        }
        else
        {
            // We should never reach that code as this method is only called for
            // initialization
            // So the queue should never be in the queues list
            synchronized (queue)
            {
                synchronized (queuesLRU)
                {

                    if (queue.setMax(max) | queue.setServiceLevel(serviceLevel) | queue.setWeight(weight)
                            | queue.setCalls(calls) | queue.setHoldTime(holdTime) | queue.setTalkTime(talkTime)
                            | queue.setCompleted(completed) | queue.setAbandoned(abandoned)
                            | queue.setServiceLevelPerf(serviceLevelPerf))
                    {

                        queuesLRU.remove(queue.getName());
                        queuesLRU.put(queue.getName(), queue);
                    }
                }
            }
        }
    }

protected function insertTableData(& $data, $useQueue = true)
    {
        $job = new DBInsert($this->service->getName(), $this->resource, $data);
        if ($useQueue !== true) {
            $job->onConnection('sync');
        }

        dispatch($job);
        $data = [];
    }

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


Question: Helper function for getting admin metadata.

def _admin_metadata_from_uri(uri, config_path):
    """"""
    uri = dtoolcore.utils.sanitise_uri(uri)
    storage_broker = _get_storage_broker(uri, config_path)
    admin_metadata = storage_broker.get_admin_metadata()
    return admin_metadata

func (s *AuditTaskMetadata) SetTaskId(v string) *AuditTaskMetadata {
	s.TaskId = &v
	return s
}

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


Question:
@param DateTimeTypeBase $type

@return DateFieldBuilder

private function dateTypeBuilder(DateTimeTypeBase $type) : DateFieldBuilder
    {
        $this->type($type);

        return new DateFieldBuilder($type, $this);
    }

public final void setEntryViewFactory(
			Callback<Entry<?>, DayEntryView> factory) {
		requireNonNull(factory);
		entryViewFactoryProperty().set(factory);
	}

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


Question:
Raise the specified alarm when the segmentation fault handler is executed.

        Sends a backtrace.

        :param AlarmType|list[AlarmType] alarm: Alarm.

def alarm_on_segfault(self, alarm):

        self.register_alarm(alarm)

        for alarm in listify(alarm):
            self._set('alarm-segfault', alarm.alias, multi=True)

        return self._section

def _sendMsg(self, type, msg):

        if self.ALERT_STATUS and type in self.ALERT_TYPES:
            self._configMailer()
            self._MAILER.send(self.MAILER_FROM, self.ALERT_EMAIL, self.ALERT_SUBJECT, msg)

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


Question: start a session an independent process

def new(self, filename=None):
        """"""
        path = (self.exec_path,)
        if self.exec_path.filetype() in ('py', 'pyw', 'pyz', self.FTYPE):
            # get the absolute path to the python-executable
            p = find_executable("python")
            path = (p, 'python') + path
        else:
            # if run in frozen env (.exe):
            # first arg if execpath of the next session:
            path += (self.exec_path,)
        if filename:
            path += ('-o', filename)
        os.spawnl(os.P_NOWAIT, *path)

public static BatchSession newBatchSession(KnowledgePackage knowledgePackage,int threadSize,int batchSize){
		return new BatchSessionImpl(knowledgePackage,threadSize,batchSize);
	}

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


Question: Return an empty data collection.

def _get_daily_data_collections(self, data_type, unit, values):
        """"""
        data_header = Header(data_type=data_type, unit=unit,
                             analysis_period=self.analysis_period,
                             metadata={'source': self._location.source,
                                       'country': self._location.country,
                                       'city': self._location.city})
        return HourlyContinuousCollection(data_header, values)

public void setReturnType(String type) {
		if (!Strings.isEmpty(type)
				&& !Objects.equals("void", type)
				&& !Objects.equals(Void.class.getName(), type)) {
			this.sarlAction.setReturnType(newTypeRef(container, type));
		} else {
			this.sarlAction.setReturnType(null);
		}
	}

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


Question: See JDBC 4.0 JavaDoc API for details.

public SQLXML getSQLXML(int columnIndex) throws SQLException {
        try {
            SQLXML xml = rsetImpl.getSQLXML(columnIndex);
            if (xml != null && freeResourcesOnClose)
                xmls.add(xml);
            return xml;
        } catch (SQLException sqlX) {
            FFDCFilter.processException(
                                        sqlX, getClass().getName() + ".getSQLXML", "2115", this);
            throw WSJdbcUtil.mapException(this, sqlX);
        } catch (NullPointerException nullX) {
            // No FFDC code needed; we might be closed.
            throw runtimeXIfNotClosed(nullX);
        } catch (AbstractMethodError methError) {
            // No FFDC code needed; wrong JDBC level.
            throw AdapterUtil.notSupportedX("ResultSet.getSQLXML", methError);
        } catch (RuntimeException runX) {
            FFDCFilter.processException(
                                        runX, getClass().getName() + ".getSQLXML", "2131", this);
            if (tc.isDebugEnabled())
                Tr.debug(this, tc, "getSQLXML", runX);
            throw runX;
        } catch (Error err) {
            FFDCFilter.processException(
                                        err, getClass().getName() + ".getSQLXML", "2138", this);
            if (tc.isDebugEnabled())
                Tr.debug(this, tc, "getSQLXML", err);
            throw err;
        }
    }

public void putDevicePipeProperty(String deviceName, DbPipe dbPipe) throws DevFailed {
        databaseDAO.putDevicePipeProperty(this, deviceName, dbPipe);
    }

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


Question:
Get CnvIbnStringToCv (create and put into map).

@return requested CnvIbnStringToCv
@throws Exception - an exception

protected final CnvIbnStringToCv
    createPutCnvIbnStringToCv() throws Exception {
    CnvIbnStringToCv convrt = new CnvIbnStringToCv();
    convrt.setIsNeedsToSqlEscape(getIsNeedsToSqlEscape());
    convrt.setSrvSqlEscape(getSrvSqlEscape());
    this.convertersMap
      .put(CnvIbnStringToCv.class.getSimpleName(), convrt);
    return convrt;
  }

func addBgp(ctx *cli.Context) {
	if len(ctx.Args()) < 1 {
		errExit(ctx, exitHelp, "Host name required", true)
	}

	hostname := ctx.Args()[0]
	routerip := ctx.String("router-ip")
	asid := ctx.String("as")
	neighboras := ctx.String("neighbor-as")
	neighbor := ctx.String("neighbor")

	//Error checks
	_, _, err := net.ParseCIDR(routerip)
	if err != nil {
		errExit(ctx, exitHelp, "Wrong CIDR format. Enter in x.x.x.x/len format", true)
	}

	ip := net.ParseIP(neighbor)
	if ip == nil {
		errExit(ctx, exitHelp, "Wrong IP format. Enter in x.x.x.x format", true)
	}

	if routerip == "" || asid == "" || neighbor == "" || neighboras == "" {
		errExit(ctx, exitHelp, "Missing attributes", true)
	}

	errCheck(ctx, getClient(ctx).BgpPost(&contivClient.Bgp{
		As:         asid,
		Hostname:   hostname,
		Neighbor:   neighbor,
		NeighborAs: neighboras,
		Routerip:   routerip,
	}))

}

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


Question:
/* isAlphanum -- return true if the character is a letter, digit, underscore,
   dollar sign, or non-ASCII character.
*/

def type_string text, options={}
      shift_key_down = nil

      text.each_char do |char|
        key_to_press = KEY_PRESS_CHARS[char]
        unless key_to_press.nil?
          key_press key_to_press
        else
          key_needs_shift = SHIFTED_CHARS.include? char

          if shift_key_down.nil? || shift_key_down != key_needs_shift
            if key_needs_shift
              key_down :shift
            else
              key_up :shift
            end
          end

          type char
          shift_key_down = key_needs_shift
        end
      end
      wait options
    end

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


Question:
Returns the number of elements stored in {@link #illegalFieldPointers}.

@return the number of elements stored in {@link #illegalFieldPointers}

private final int getIllegalFieldPointerSize () {
        if (illegalFieldPointers == null) return 0;
        int size = 0;
        while (size < illegalFieldPointers.length) {
            if (illegalFieldPointers[size] != null)
                ++size;
            else
                break;
        }
        return size;
    }

def process(event, watch_type = nil)
      @zk.raw_event_handler(event)

      logger.debug { "EventHandler#process dispatching event for #{watch_type.inspect}: #{event.inspect}" }# unless event.type == -1
      event.zk = @zk

      cb_keys =
        if event.node_event?
          [event.path, ALL_NODE_EVENTS_KEY]
        elsif event.session_event?
          [state_key(event.state), ALL_STATE_EVENTS_KEY]
        else
          raise ZKError, "don't know how to process event: #{event.inspect}"
        end

      cb_ary = synchronize do
        clear_watch_restrictions(event, watch_type)

        @callbacks.values_at(*cb_keys)
      end

      cb_ary.flatten! # takes care of not modifying original arrays
      cb_ary.compact!

      # we only filter for node events
      if event.node_event?
        interest_key = event.interest_key
        cb_ary.select! { |sub| sub.interests.include?(interest_key) }
      end

      safe_call(cb_ary, event)
    end

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


Question:
Delete all messages that are sticky and return the other messages
        This storage never save objects

def _store(self, messages, response, *args, **kwargs):

        return [message for message in messages if not message.level in STICKY_MESSAGE_LEVELS]

protected function store(Request $request, Response $response)
    {
        try {
            $this->store->write($request, $response);

            $this->record($request, 'store');

            $response->headers->set('Age', $response->getAge());
        } catch (\Exception $e) {
            $this->record($request, 'store-failed');

            if ($this->options['debug']) {
                throw $e;
            }
        }

        // now that the response is cached, release the lock
        $this->store->unlock($request);
    }

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


Question: Add the menu items to this frame.

public JMenu addMenu(JMenuBar menuBar, String strAction, int iLocation)
    {
        JMenu menu = null;
        Application application = BaseApplet.getSharedInstance().getApplication();
        ResourceBundle oldResources = application.getResourceBundle();
        application.getResources(null, true);

        if (iLocation == JBaseToolbar.BEFORE_HELP)
            menuBar.add(menu = new JMenu(application.getString(strAction)), menuBar.getComponentCount() - 1);
        else
            menuBar.add(menu = new JMenu(application.getString(strAction)));
        menu.setMnemonic(menu.getText().charAt(0));

        if (oldResources != null)
            application.setResourceBundle(oldResources);
        menu.setOpaque(false);

        return menu;
    }

protected JMenu newFileMenu(final ActionListener listener)
	{
		final JMenu fileMenu = new JMenu("File");
		fileMenu.setMnemonic('F');

		return fileMenu;
	}

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


Question: // SetWorkflowType sets the WorkflowType field's value.

func (s *WorkflowExecutionContinuedAsNewEventAttributes) SetWorkflowType(v *WorkflowType) *WorkflowExecutionContinuedAsNewEventAttributes {
	s.WorkflowType = v
	return s
}

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

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

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


Question:
Dispatch cartLine event when is edited.

@param CartInterface     $cart     Cart
@param CartLineInterface $cartLine CartLine

@return $this Self object

public function dispatchCartLineOnEditEvent(
        CartInterface $cart,
        CartLineInterface $cartLine
    ) {
        $this->eventDispatcher->dispatch(
            ElcodiCartEvents::CARTLINE_ONEDIT,
            new CartLineOnEditEvent(
                $cart,
                $cartLine
            )
        );

        return $this;
    }

public function addColor(Color $color)
    {
        if (!$this->colors->contains($color)) {
            $this->colors->add($color);
            $color->setInteractionSelection($this);
        }
    }

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


Question: process a securityData node - FIXME: currently not handling relateDate node

def on_security_data_node(self, node):

        sid = XmlHelper.get_child_value(node, 'security')
        farr = node.getElement('fieldData')
        dmap = defaultdict(list)
        for i in range(farr.numValues()):
            pt = farr.getValue(i)
            [dmap[f].append(XmlHelper.get_child_value(pt, f, allow_missing=1)) for f in ['date'] + self.fields]

        if not dmap:
            frame = pd.DataFrame(columns=self.fields)
        else:
            idx = dmap.pop('date')
            frame = pd.DataFrame(dmap, columns=self.fields, index=idx)
            frame.index.name = 'date'
        self.response.on_security_complete(sid, frame)

public function parseLiteral($valueNode, ?array $variables = null): Carbon
    {
        if (! $valueNode instanceof StringValueNode) {
            throw new Error(
                'Query error: Can only parse strings got: '.$valueNode->kind,
                [$valueNode]
            );
        }

        return $this->tryParsingDateTime($valueNode->value, Error::class);
    }

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


Question:
Notifies all registered listeners, that a validation failed.

@param validator
The validator, which failed, as an instance of the type {@link Validator}. The
validator may not be null

private void notifyOnValidationFailure(@NonNull final Validator<ValueType> validator) {
        for (ValidationListener<ValueType> listener : listeners) {
            listener.onValidationFailure(this, validator);
        }
    }

public boolean isValid(String value) {
        if (value == null) {
            return false;
        }
        for (Pattern pattern : patterns) {
            if (pattern.matcher(value).matches()) {
                return true;
            }
        }
        return false;
    }

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


Question:
Given a set of default values, add them to the scope if
a value does not already exist.

@param scope
@param defaults

function setDefaults(scope, defaults) {
        if (!defaults) { return; }

        // store defaults for use in generateRemodel
        scope.defaults = defaults;

        for (var name in defaults) {
            if (defaults.hasOwnProperty(name) && scope[name] === undefined) {
                scope[name] = defaults[name];
            }
        }
    }

protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot)
    {
        // controller
        $classAnnot = $this->reader->getClassAnnotation($class, $this->routeAnnotationClass);
        if ($classAnnot instanceof FrameworkExtraBundleRoute && $service = $classAnnot->getService()) {
            $route->setDefault('_controller', $service.':'.$method->getName());
        } elseif ('__invoke' === $method->getName()) {
            $route->setDefault('_controller', $class->getName());
        } else {
            $route->setDefault('_controller', $class->getName().'::'.$method->getName());
        }

        // requirements (@Method)
        foreach ($this->reader->getMethodAnnotations($method) as $configuration) {
            if ($configuration instanceof Method) {
                $route->setMethods($configuration->getMethods());
            } elseif ($configuration instanceof FrameworkExtraBundleRoute && $configuration->getService()) {
                throw new \LogicException('The service option can only be specified at class level.');
            }
        }
    }

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