Question:
Returns a microtime.
@param int|null $microtime
@return float

protected function microtime($microtime = null)
    {
        list($usec, $sec) = explode(" ", $microtime ?: microtime());
        return (float)$usec + (float)$sec;
    }

func (listener *Listener) fromWavefrontDatapoint(line string) *datapoint.Datapoint {
	pieces := getMetricPieces(line)
	if len(pieces) < 3 {
		return nil
	}
	metricName, dimensions := extractCollectdDimensions(listener.extractCollectdDimensions, stripQuotes(pieces[0]))

	valueString := pieces[1]

	var value datapoint.Value
	if i, err := strconv.ParseInt(valueString, 10, 64); err == nil {
		value = datapoint.NewIntValue(i)
	} else if f, err := strconv.ParseFloat(valueString, 64); err == nil {
		value = datapoint.NewFloatValue(f)
	} else {
		return nil
	}
	var timestamp time.Time
	epoch, err := strconv.ParseInt(pieces[2], 10, 64)
	if err != nil {
		// probably not the timestamp, probably a dimension
		pieces = pieces[2:]
		timestamp = time.Now()
	} else {
		timestamp = time.Unix(epoch, 0)
		pieces = pieces[3:]
	}
	for _, p := range pieces {
		dimPieces := strings.SplitN(p, "=", 2)
		if len(dimPieces) == 2 {
			key := dimPieces[0]
			value := stripQuotes(dimPieces[1])
			dimensions[key] = value
		}
		// ignore malformed dimensions
	}
	return datapoint.New(metricName, dimensions, value, datapoint.Gauge, timestamp)
}

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


Question:
Check if the user has all permissions.

@param int|string|array $permission

@return bool

public function hasAllPermissions($permission)
    {
        foreach ($this->getArrayFrom($permission) as $permission) {
            if (!$this->checkPermission($permission)) {
                return false;
            }
        }

        return true;
    }

func parseVariablePermissions(v interface{}, errors, warnings *[]error) (*SubjectPermission, error) {
	switch vv := v.(type) {
	case map[string]interface{}:
		// New style with allow and/or deny properties.
		return parseSubjectPermission(vv, errors, warnings)
	default:
		// Old style
		return parseOldPermissionStyle(v, errors, warnings)
	}
}

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


Question: // Close implements tcpip.Endpoint.Close.

func (ep *endpoint) Close() {
	ep.mu.Lock()
	defer ep.mu.Unlock()

	if ep.closed {
		return
	}

	ep.stack.UnregisterRawTransportEndpoint(ep.registeredNIC, ep.netProto, ep.transProto, ep)

	ep.rcvMu.Lock()
	defer ep.rcvMu.Unlock()

	// Clear the receive list.
	ep.rcvClosed = true
	ep.rcvBufSize = 0
	for !ep.rcvList.Empty() {
		ep.rcvList.Remove(ep.rcvList.Front())
	}

	if ep.connected {
		ep.route.Release()
	}

	ep.waiterQueue.Notify(waiter.EventHUp | waiter.EventErr | waiter.EventIn | waiter.EventOut)
}

private void getConnInput() throws IOException
  {
    if (_didGet)
      return;

    try {
      getConnInputImpl();
    } catch (IOException e) {
      _isKeepalive = false;
      throw e;
    } catch (RuntimeException e) {
      _isKeepalive = false;
      throw e;
    }
  }

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


Question:
Get an existing node id by name or id.

    Return -1 if invalid

def existing_node_input():

    input_from_user = raw_input("Existing node name or id: ")
    node_id = INVALID_NODE

    if not input_from_user:
        return node_id

    # int or str?
    try:
        parsed_input = int(input_from_user)
    except ValueError:
        parsed_input = input_from_user

    if isinstance(parsed_input, int):
        result = db.execute(text(fetch_query_string('select_node_from_id.sql')),
                node_id=parsed_input).fetchall()
        if result:
            node_id = int(result[0]['node_id'])
    else:
        result = db.execute(text(fetch_query_string('select_node_from_name.sql')),
                node_name=parsed_input).fetchall()
        if result:
            if len(result) == 1:
                print 'Node id: {node_id}\nNode name: {name}'.format(**result[0])
                print '-------------'
                node_id = result[0]['node_id']
            else:
                print 'Multiple nodes found with the name: {0}'.format(parsed_input)
                for item in result:
                    print '{node_id}: {name} = {value}'.format(**item)
                node_selection = raw_input('Enter a node id from this list or enter "?" to render all or "?<node>" for a specific one.')
                if node_selection:
                    node_selection_match = re.match(r"\?(\d)*", node_selection)
                    if node_selection_match:
                        if node_selection_match.groups()[0]:
                            value = render_node(int(node_selection_match.groups()[0]), noderequest={'_no_template':True}, **result[0])
                            print safe_dump(value, default_flow_style=False)
                        else:
                            for item in result:
                                value = render_node(item['node_id'], noderequest={'_no_template':True}, **item)
                                print 'Node id: {0}'.format(item['node_id'])
                                print safe_dump(value, default_flow_style=False)
                                print '---'
                        node_id = node_input()
                    else:
                        try:
                            node_id = int(node_selection)
                        except ValueError:
                            node_id = INVALID_NODE
                            print 'invalid node id: %s' % node

    return node_id

public static void assertNodeNotExistById(final Session session, final String itemId) throws RepositoryException {
        try {
            session.getNodeByIdentifier(itemId);
            fail("ItemNotFoundException expected");
        } catch (final ItemNotFoundException e) { // NOSONAR
            // this was expected
        }
    }

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


Question:
Computes the eigenvalues only for a square nonsymmetric matrix A.

 @param a [Numo::NArray] square nonsymmetric matrix (>= 2-dimensinal NArray)
 @return [Numo::NArray] eigenvalues

def eigvals(a)
    jobvl, jobvr = 'N','N'
    case blas_char(a)
    when /c|z/
      w, = Lapack.call(:geev, a, jobvl:jobvl, jobvr:jobvr)
    else
      wr, wi, = Lapack.call(:geev, a, jobvl:jobvl, jobvr:jobvr)
      w  = wr + wi * Complex::I
    end
    w
  end

def to_xml_string(str='')
      add_worksheet(name: 'Sheet1') unless worksheets.size > 0
      str << '<?xml version="1.0" encoding="UTF-8"?>'
      str << ('<workbook xmlns="' << XML_NS << '" xmlns:r="' << XML_NS_R << '">')
      str << ('<workbookPr date1904="' << @@date1904.to_s << '"/>')
      views.to_xml_string(str)
      str << '<sheets>'
      if is_reversed
        worksheets.reverse_each { |sheet| sheet.to_sheet_node_xml_string(str) }
      else
        worksheets.each { |sheet| sheet.to_sheet_node_xml_string(str) }
      end
      str << '</sheets>'
      defined_names.to_xml_string(str)
      unless pivot_tables.empty?
        str << '<pivotCaches>'
        pivot_tables.each do |pivot_table|
          str << ('<pivotCache cacheId="' << pivot_table.cache_definition.cache_id.to_s << '" r:id="' << pivot_table.cache_definition.rId << '"/>')
        end
        str << '</pivotCaches>'
      end
      str << '</workbook>'
    end

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


Question:
set1, set2的交集（同时在set1和set2的对象）的只读view，不复制产生新的Set对象.

如果尝试写入该View会抛出UnsupportedOperationException

public static <E> Set<E> intersectionView(final Set<E> set1, final Set<?> set2) {
		return Sets.intersection(set1, set2);
	}

public void updateIndex(ChangesHolder changes, ChangesHolder parentChanges)
   {
      // pass lists to search manager
      if (searchManager != null && changes != null)
      {
         try
         {
            searchManager.apply(changes);
         }
         catch (RepositoryException e)
         {
            log.error("Error indexing changes " + e, e);
         }
         catch (IOException e)
         {
            log.error("Error indexing changes " + e, e);
            try
            {
               handler.logErrorChanges(new HashSet<String>(changes.getRemove()), new HashSet<String>(changes
                  .getAddIds()));
            }
            catch (IOException ioe)
            {
               log.warn("Exception occure when errorLog writed. Error log is not complete. " + ioe, ioe);
            }
         }
      }
      // pass lists to parent search manager
      if (parentSearchManager != null && parentChanges != null)
      {
         try
         {
            parentSearchManager.apply(parentChanges);
         }
         catch (RepositoryException e)
         {
            log.error("Error indexing changes " + e, e);
         }
         catch (IOException e)
         {
            log.error("Error indexing changes " + e, e);
            try
            {
               parentHandler.logErrorChanges(new HashSet<String>(parentChanges.getRemove()), new HashSet<String>(
                  parentChanges.getAddIds()));
            }
            catch (IOException ioe)
            {
               log.warn("Exception occure when errorLog writed. Error log is not complete. " + ioe, ioe);
            }
         }
      }
   }

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


Question:
Convert an entry into the corresponding file path.

@param entry the entry.
@return the corresponding file.
@since 1.0

private File toFile( Entry entry )
    {
        Stack<String> stack = new Stack<String>();
        Entry entryRoot = entry.getFileSystem().getRoot();
        while ( entry != null && !entryRoot.equals( entry ) )
        {
            String name = entry.getName();
            if ( "..".equals( name ) )
            {
                if ( !stack.isEmpty() )
                {
                    stack.pop();
                }
            }
            else if ( !".".equals( name ) )
            {
                stack.push( name );
            }
            entry = entry.getParent();
        }
        File file = this.root;
        while ( !stack.empty() )
        {
            file = new File( file, (String) stack.pop() );
        }
        return file;
    }

public function processFile(string $type)
    {
        $this->alert(strtoupper($type) . ' PROCESS');
        foreach ($this->tables as $key => $table) {
            if ($table->relationTable === true && $type !== 'pivot') {
                continue;
            }

            if ($table->relationTable !== true && $type === 'pivot') {
                continue;
            }

            if (trim($this->option('table')) !== 'all') {
                $tableKey = $this->option('table');
                if ((int) $tableKey !== (int) $key) {
                    continue;
                }
            }

            $table->arqs = [
                $type => $this->getTemplate($type),
            ];

            foreach ($this->marks()[$type] as $mark){
                $table->arqs[$type] = str_replace('{{{' . $mark . '}}}',
                                                        trim($table->marks[$mark]),
                                                        $table->arqs[$type]);
            }

            //$this->info($table->arqs[$type]);
            $this->createFile($type, $table);
        }
    }

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


Question:
批量发送短信

@param $phones
@param $signatures
@param $templateCode
@param array $extDatas
@return array

public function sendBatchSms($phones, $signatures, $templateCode, $extDatas=[]) {
        if(!count($phones) || !count($signatures) || !$templateCode){
            return $this->error('参数有误');
        }
        $request = new SendBatchSmsRequest();
        $request->setPhoneNumberJson(json_encode($phones, JSON_UNESCAPED_UNICODE));
        $request->setSignNameJson(json_encode($signatures, JSON_UNESCAPED_UNICODE));
        $request->setTemplateCode($templateCode);
        $request->setTemplateParamJson(json_encode($extDatas, JSON_UNESCAPED_UNICODE));
        return $this->parseResponse($request, '发送');
    }

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: Performs an action from the menu or toolbar.

public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        int returnValue = -1;
        if (cmd.equals("Cut") || cmd.equals("Copy") || cmd.equals("Paste")) {
            JInternalFrame f = getSelectedFrame();
            if (f != null && f instanceof ActionListener) {
                ((ActionListener)f).actionPerformed(e);
            }
        } else if (cmd.equals("Step Over")) {
            returnValue = Dim.STEP_OVER;
        } else if (cmd.equals("Step Into")) {
            returnValue = Dim.STEP_INTO;
        } else if (cmd.equals("Step Out")) {
            returnValue = Dim.STEP_OUT;
        } else if (cmd.equals("Go")) {
            returnValue = Dim.GO;
        } else if (cmd.equals("Break")) {
            dim.setBreak();
        } else if (cmd.equals("Exit")) {
            exit();
        } else if (cmd.equals("Open")) {
            String fileName = chooseFile("Select a file to compile");
            if (fileName != null) {
                String text = readFile(fileName);
                if (text != null) {
                    RunProxy proxy = new RunProxy(this, RunProxy.OPEN_FILE);
                    proxy.fileName = fileName;
                    proxy.text = text;
                    new Thread(proxy).start();
                }
            }
        } else if (cmd.equals("Load")) {
            String fileName = chooseFile("Select a file to execute");
            if (fileName != null) {
                String text = readFile(fileName);
                if (text != null) {
                    RunProxy proxy = new RunProxy(this, RunProxy.LOAD_FILE);
                    proxy.fileName = fileName;
                    proxy.text = text;
                    new Thread(proxy).start();
                }
            }
        } else if (cmd.equals("More Windows...")) {
            MoreWindows dlg = new MoreWindows(this, fileWindows,
                                              "Window", "Files");
            dlg.showDialog(this);
        } else if (cmd.equals("Console")) {
            if (console.isIcon()) {
                desk.getDesktopManager().deiconifyFrame(console);
            }
            console.show();
            desk.getDesktopManager().activateFrame(console);
            console.consoleTextArea.requestFocus();
        } else if (cmd.equals("Cut")) {
        } else if (cmd.equals("Copy")) {
        } else if (cmd.equals("Paste")) {
        } else if (cmd.equals("Go to function...")) {
            FindFunction dlg = new FindFunction(this, "Go to function",
                                                "Function");
            dlg.showDialog(this);
        } else if (cmd.equals("Go to line...")) {
            final String s = (String) JOptionPane.showInputDialog(
                    this,
                    "Line number",
                    "Go to line...",
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    null,
                    null);
            if (s == null || s.trim().length() == 0) {
                return;
            }
            try {
                final int line = Integer.parseInt(s);
                showFileWindow(null, line);
            }
            catch (final NumberFormatException nfe) {
                // ignore
            }
        } else if (cmd.equals("Tile")) {
            JInternalFrame[] frames = desk.getAllFrames();
            int count = frames.length;
            int rows, cols;
            rows = cols = (int)Math.sqrt(count);
            if (rows*cols < count) {
                cols++;
                if (rows * cols < count) {
                    rows++;
                }
            }
            Dimension size = desk.getSize();
            int w = size.width/cols;
            int h = size.height/rows;
            int x = 0;
            int y = 0;
            for (int i = 0; i < rows; i++) {
                for (int j = 0; j < cols; j++) {
                    int index = (i*cols) + j;
                    if (index >= frames.length) {
                        break;
                    }
                    JInternalFrame f = frames[index];
                    try {
                        f.setIcon(false);
                        f.setMaximum(false);
                    } catch (Exception exc) {
                    }
                    desk.getDesktopManager().setBoundsForFrame(f, x, y,
                                                               w, h);
                    x += w;
                }
                y += h;
                x = 0;
            }
        } else if (cmd.equals("Cascade")) {
            JInternalFrame[] frames = desk.getAllFrames();
            int count = frames.length;
            int x, y, w, h;
            x = y = 0;
            h = desk.getHeight();
            int d = h / count;
            if (d > 30) d = 30;
            for (int i = count -1; i >= 0; i--, x += d, y += d) {
                JInternalFrame f = frames[i];
                try {
                    f.setIcon(false);
                    f.setMaximum(false);
                } catch (Exception exc) {
                }
                Dimension dimen = f.getPreferredSize();
                w = dimen.width;
                h = dimen.height;
                desk.getDesktopManager().setBoundsForFrame(f, x, y, w, h);
            }
        } else {
            Object obj = getFileWindow(cmd);
            if (obj != null) {
                FileWindow w = (FileWindow)obj;
                try {
                    if (w.isIcon()) {
                        w.setIcon(false);
                    }
                    w.setVisible(true);
                    w.moveToFront();
                    w.setSelected(true);
                } catch (Exception exc) {
                }
            }
        }
        if (returnValue != -1) {
            updateEnabled(false);
            dim.setReturnValue(returnValue);
        }
    }

public static void pruneMenus(BaseComponent parent) {
        while (parent != null && parent instanceof BaseMenuComponent) {
            if (parent.getChildren().isEmpty()) {
                BaseComponent newParent = parent.getParent();
                parent.destroy();
                parent = newParent;
            } else {
                break;
            }
        }
    }

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


Question: To append a new child.

def append(self, node):
        """"""
        if node.parent == self.key and not self.elapsed_time:
            self.children.append(node)
        else:
            # Recursive call
            for child in self.children:
                if not child.elapsed_time:
                    child.append(node)

def add_plate(self, plate_definition):

        values = self.get_plate_values(plate_definition)

        # TODO: We should also be checking that the plate is defined over all of the values of the parent plate
        self.plates[plate_definition.plate_id] = Plate(
            plate_id=plate_definition.plate_id,
            meta_data_id=plate_definition.meta_data_id,
            values=values,
            parent_plate=self.plates[plate_definition.parent_plate] if plate_definition.parent_plate else None)

        logging.debug("Added plate: {}".format(self.plates[plate_definition.plate_id]))

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


Question: // setRaw interprets a name=value string and sets the supplied value.

func (v *Value) setRaw(name, str string) error {
	var err error
	switch resolveAlias(name) {
	case Arch:
		err = v.setArch(str)
	case Container:
		err = v.setContainer(str)
	case Cores:
		err = v.setCpuCores(str)
	case CpuPower:
		err = v.setCpuPower(str)
	case Mem:
		err = v.setMem(str)
	case RootDisk:
		err = v.setRootDisk(str)
	case RootDiskSource:
		err = v.setRootDiskSource(str)
	case Tags:
		err = v.setTags(str)
	case InstanceType:
		err = v.setInstanceType(str)
	case Spaces:
		err = v.setSpaces(str)
	case VirtType:
		err = v.setVirtType(str)
	case Zones:
		err = v.setZones(str)
	default:
		return errors.Errorf("unknown constraint %q", name)
	}
	if err != nil {
		return errors.Annotatef(err, "bad %q constraint", name)
	}
	return nil
}

def main(list_ids, model, contact_server, raw_data_id, show_raw,
         mysql_cfg='mysql_online'):
    """"""
    if list_ids:
        preprocessing_desc, _, _ = _get_system(model)
        raw_datapath = os.path.join(utils.get_project_root(),
                                    preprocessing_desc['data-source'])
        _list_ids(raw_datapath)
    else:
        if contact_server:
            data = _fetch_data_from_server(raw_data_id, mysql_cfg)
            print("hwrt version: %s" % hwrt.__version__)
            if data is not None:
                display_data(data['data'], data['id'], model, show_raw)
        else:
            logging.info("RAW_DATA_ID %i does not exist or "
                         "database connection did not work.", raw_data_id)
            # The data was not on the server / the connection to the server did
            # not work. So try it again with the model data
            preprocessing_desc, _, _ = _get_system(model)
            raw_datapath = os.path.join(utils.get_project_root(),
                                        preprocessing_desc['data-source'])
            handwriting = _get_data_from_rawfile(raw_datapath, raw_data_id)
            if handwriting is None:
                logging.info("Recording with ID %i was not found in %s",
                             raw_data_id,
                             raw_datapath)
            else:
                print("hwrt version: %s" % hwrt.__version__)
                display_data(handwriting.raw_data_json,
                             handwriting.formula_id,
                             model,
                             show_raw)

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


Question: Fix (trivial case of) non-membership check.

def fix_e713(self, result):
        """"""
        (line_index, offset, target) = get_index_offset_contents(result,
                                                                 self.source)

        # to convert once 'not in' -> 'in'
        before_target = target[:offset]
        target = target[offset:]
        match_notin = COMPARE_NEGATIVE_REGEX_THROUGH.search(target)
        notin_pos_start, notin_pos_end = 0, 0
        if match_notin:
            notin_pos_start = match_notin.start(1)
            notin_pos_end = match_notin.end()
            target = '{}{} {}'.format(
                target[:notin_pos_start], 'in', target[notin_pos_end:])

        # fix 'not in'
        match = COMPARE_NEGATIVE_REGEX.search(target)
        if match:
            if match.group(3) == 'in':
                pos_start = match.start(1)
                new_target = '{5}{0}{1} {2} {3} {4}'.format(
                    target[:pos_start], match.group(2), match.group(1),
                    match.group(3), target[match.end():], before_target)
                if match_notin:
                    # revert 'in' -> 'not in'
                    pos_start = notin_pos_start + offset
                    pos_end = notin_pos_end + offset - 4     # len('not ')
                    new_target = '{}{} {}'.format(
                        new_target[:pos_start], 'not in', new_target[pos_end:])
                self.source[line_index] = new_target

public function getExampleByType($type)
    {
        return isset($this->bodyList[$type]['example']) ? $this->bodyList[$type]['example'] : null;
    }

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


Question:
Open up a GUI browse dialog window and let to user pick a target directory.
    :return str: Target directory path

def browse_dialog_dir():

    _go_to_package()
    logger_directory.info("enter browse_dialog")
    _path_bytes = subprocess.check_output(['python', 'gui_dir_browse.py'], shell=False)
    _path = _fix_path_bytes(_path_bytes, file=False)
    if len(_path) >= 1:
        _path = _path[0]
    else:
        _path = ""
    logger_directory.info("chosen path: {}".format(_path))
    logger_directory.info("exit browse_dialog")
    return _path

def name_of(remote)
      dir_defined?(remote)
      dir = remote[:dir].dup
      dir.gsub! '/', '_'
      name = dir.downcase.to_sym
    end

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


Question:
设置Date类型参数的开始、结束时间.

@param fieldName
@param startTime
@param endTime

public void setTimeRange(String fieldName, Date startTime, Date endTime) {
		this.where += " and " + fieldName + ">=? and " + fieldName + "<=?";
		this.getParam().setDate(startTime);
		this.getParam().setDate(endTime);
	}

static ElementAttributes createElementAttributes(String tag) {
        // Parsing strings
        // <!--$includetemplate$aggregated2$templatewithparams.jsp$-->
        // or
        // <!--$includeblock$aggregated2$$(block)$myblock$-->
        // in order to retrieve driver, page and name attributes
        Pattern pattern = Pattern.compile("(?<=\\$)(?:[^\\$]|\\$\\()*(?=\\$)");
        Matcher matcher = pattern.matcher(tag);
        List<String> listparameters = new ArrayList<>();
        while (matcher.find()) {
            listparameters.add(matcher.group());
        }

        String[] parameters = listparameters.toArray(new String[listparameters.size()]);

        Driver driver;
        String page = "";
        String name = null;

        if (parameters.length > 1) {
            driver = DriverFactory.getInstance(parameters[1]);
        } else {
            driver = DriverFactory.getInstance();
        }

        if (parameters.length > 2) {
            page = parameters[2];
        }

        if (parameters.length > 3) {
            name = parameters[3];
        }
        return new ElementAttributes(driver, page, name);

    }

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


Question:
Implements a state into an entity

@param $state array
@throws InvalidStateException if the state is not valid
@throws \Exception

public function exchangeArray(array $state) {
		if ($this instanceof IValueObject && $this->isExchanged())
			throw new Exception("Cannot change ValueObjects. Create new object instead");
		if ($this instanceof IValidatorAware && !is_null($this->getValidator()) &&
			!$this->getValidator()->isValid($state)) {
			$stateRep = array();
			foreach ($state as $key => $val)
				$stateRep[] = $key.' => '.
					(is_object($val)?'[Object]':(is_resource($val)?'[Resource]':var_export($val,true)));
			throw new InvalidStateException("ExchangeArray called with an invalid state: ".
				             var_export($this->getValidator()->getMessages(),true)."\n\n(".implode(',',$stateRep).')');
		}
		$toSet = $this->getStateVarsWithAll();
		foreach ($this->getStateVO() as $voIndex)
			if (isset($state[$voIndex])) {
				$vo = $state[$voIndex];
				if ($vo instanceof IExchangeState)
					$state = array_merge($state,$vo->getArrayCopy());
			}

		foreach ($toSet as $var) {
			if (isset($state[$var])) {
				$value = $state[$var];
				if ($this instanceof IValueObject && $value instanceof IFreezable) $value->freeze();
				// @TODO Add fields of ValueObjects to motherObject
				$this->{self::_privatizeField($var)} = $value;
			}
			else
				$this->{self::_privatizeField($var)} = null;
		}
		if ($this instanceof IValueObject)
			$this->markExchanged();
	}

public function assertSatisfied()
    {
        foreach ($this->expectations as $expectation) {
            if (!$expectation->isSatisfied()) {
                $comment = $expectation->commentOn($expectation->getMethod(), []);

                if (!$comment) {
                    $comment = "Unsatisfied expectation for method " . $expectation->getMethod();
                }

                throw new UnsatisfiedExpectationException($comment);
            }
        }
    }

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


Question:
Determine if the daemon should process on this iteration.

@param  string  $connection
@param  string  $queue
@return bool

protected function daemonShouldRun($connection, $queue)
    {
        if ($this->manager->isDownForMaintenance()) {
            return false;
        }

        $result = $this->events->until('nova.queue.looping', array($connection, $queue));

        return ($result !== false);
    }

def parse_command_line
      begin
        opts = GetoptLong.new(
          [ '--logfile', '-l',      GetoptLong::REQUIRED_ARGUMENT ],
          [ '--verbose', '-v',      GetoptLong::NO_ARGUMENT ],
          [ '--quiet',   '-q',      GetoptLong::NO_ARGUMENT ],
          [ '--concurrency', '-c',  GetoptLong::REQUIRED_ARGUMENT ],
          [ '--delay', '-d',        GetoptLong::REQUIRED_ARGUMENT ],
          [ '--retry', '-y',        GetoptLong::REQUIRED_ARGUMENT ],
          [ '--port', '-p',         GetoptLong::REQUIRED_ARGUMENT ],
          [ '--bind-address', '-b', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--help', '-h',         GetoptLong::NO_ARGUMENT ],
          [ '--exit', '-x', 				GetoptLong::NO_ARGUMENT ]
        )

        opts.each do |opt, arg|
          case opt
            when '--logfile', '-l'
              @logfile = arg
              Log.logger = Logger.new(@logfile)
            when '--concurrency', '-c'
              @concurrency = arg.to_i
            when '--delay', '-d'
              @delay = arg.to_i
            when '--retry', '-y'
              @retry_count = arg.to_i
            when '--verbose', '-v'
              @verbose = true
            when '--quiet',   '-q'
              @quiet = true
            when '--port', '-p'
              @port = arg
            when '--bind-address', '-b'
              @bind_address = arg.to_s
            when '--help', '-h'
              help
            when '--exit', '-x'
              uri = "http://localhost:#{@port}/admin"
              response = RestClient.post uri, { 'shutdown' => true }.to_yaml
              exit 0
          end
        end
      rescue GetoptLong::InvalidOption => ex
        puts "Syntax: chimpd [--logfile=<name>] [--concurrency=<c>] [--delay=<d>] [--retry=<r>] [--port=<p>] [--bind-address=<addr> ] [--verbose]"
        exit 1
      end

      #
      # Set up logging/verbosity
      #
      Chimp.set_verbose(@verbose, @quiet)

      if not @verbose
      	ENV['REST_CONNECTION_LOG'] = "/dev/null"
      	ENV['RESTCLIENT_LOG'] = "/dev/null"
        Log.threshold= Logger::INFO
      else
        Log.threshold= Logger::DEBUG
      end

      if @quiet
        Log.threshold = Logger::WARN
      end
    end

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


Question: // controllerUser a model userAccessDoc.

func (st *State) controllerUser(user names.UserTag) (userAccessDoc, error) {
	controllerUser := userAccessDoc{}
	controllerUsers, closer := st.db().GetCollection(controllerUsersC)
	defer closer()

	username := strings.ToLower(user.Id())
	err := controllerUsers.FindId(username).One(&controllerUser)
	if err == mgo.ErrNotFound {
		return userAccessDoc{}, errors.NotFoundf("controller user %q", user.Id())
	}
	// DateCreated is inserted as UTC, but read out as local time. So we
	// convert it back to UTC here.
	controllerUser.DateCreated = controllerUser.DateCreated.UTC()
	return controllerUser, nil
}

public ArrayList<String> contact_contactId_document_POST(String contactId, String documentId) throws IOException {
		String qPath = "/store/contact/{contactId}/document";
		StringBuilder sb = path(qPath, contactId);
		HashMap<String, Object>o = new HashMap<String, Object>();
		addBody(o, "documentId", documentId);
		String resp = exec(qPath, "POST", sb.toString(), o);
		return convertTo(resp, t2);
	}

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


Question: Print all devices as JSON

def print_all_devices():
    """"""
    print("Printing information about all devices paired to the Gateway")
    if len(devices) == 0:
        exit(bold("No devices paired"))

    container = []
    for dev in devices:
        container.append(dev.raw)
    print(jsonify(container))

public static Object write(Context cx, Scriptable thisObj,
                               Object[] args, Function funObj)
    {
        return doPrint(args, funObj, false);
    }

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


Question:
Reads a single character from the device.

        :returns: character read from the device
        :raises: :py:class:`~alarmdecoder.util.CommError`

def read(self):

        ret = None

        try:
            ret = self._device.read_data(1)

        except (usb.core.USBError, FtdiError) as err:
            raise CommError('Error reading from device: {0}'.format(str(err)), err)

        return ret

def parse_data_to_internal(self, data=None):

        if data is None:
            f = open(self.location_dat, "rb")
            data = {
                "PMCA SPECTRUM": {},
                "DATA": [],
                "DP5 CONFIGURATION": {},
                "DPP STATUS": {}
            }
            delimiter = {
                "PMCA SPECTRUM": " - ",
                "DP5 CONFIGURATION": "=",
                "DPP STATUS": ":"
            }
            comments = {
                "PMCA SPECTRUM": None,
                "DP5 CONFIGURATION": ";",
                "DPP STATUS": None
            }
            for e in f:
                if "<<" in e:
                    if "<<END>>" in e:
                        current = None
                    elif "<<PMCA SPECTRUM>>" in e:
                        current = "PMCA SPECTRUM"
                    elif "<<DATA>>" in e:
                        current = "DATA"
                    elif "<<DP5 CONFIGURATION>>" in e:
                        current = "DP5 CONFIGURATION"
                    elif "<<DPP STATUS>>" in e:
                        current = "DPP STATUS"
                    elif "<<ROI>>" in e:
                        current = "ROI"
                else:
                    if current == "DATA":
                        data["DATA"].append(float(e))
                    elif current == "ROI":
                        continue
                    elif current is not None:
                        e = e.split("\r\n")[0]
                        if comments[current] is not None:
                            e = e.split(comments[current], 1)[0]
                        e_list = e.split(delimiter[current], 1)
                        data[current][e_list[0]] = e_list[1]
            f.close()
        self.save_to_internal(data)

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


Question:
Read the package metadata from the Package.xml file at $pathAndFileName

@param string $pathAndFileName
@return array|NULL

protected static function readPackageMetaData($pathAndFileName)
    {
        if (file_exists($pathAndFileName)) {
            $xml = simplexml_load_file($pathAndFileName);
            $meta = array();
            if ($xml === false) {
                $meta['description'] = '[Package.xml could not be read.]';
            } else {
                $meta['version'] = (string)$xml->version;
                $meta['title'] = (string)$xml->title;
                $meta['description'] = (string)$xml->description;
            }

            return $meta;
        } else {
            return null;
        }
    }

public function getClassMetadataFactory()
    {
        if (!isset($this->attributes['classMetadataFactory'])) {
            $classMetaDataFactoryName = $this->getClassMetadataFactoryName();
            $this->attributes['classMetadataFactory'] = new $classMetaDataFactoryName;
        }
        return $this->attributes['classMetadataFactory'];
    }

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


Question: Method for setting general data for all views

private function setData()
    {
        $data = $this->config->get('auth.external_concrete5', '');
        $authUrl = $this->urlResolver->resolve(['/ccm/system/authentication/oauth2/external_concrete5/attempt_auth']);
        $attachUrl = $this->urlResolver->resolve(['/ccm/system/authentication/oauth2/external_concrete5/attempt_attach']);
        $baseUrl = $this->urlResolver->resolve(['/']);
        $path = $baseUrl->getPath();
        $path->remove('index.php');
        $name = trim((string) array_get($data, 'name', t('External concrete5')));

        $this->set('data', $data);
        $this->set('authUrl', $authUrl);
        $this->set('attachUrl', $attachUrl);
        $this->set('baseUrl', $baseUrl);
        $this->set('assetBase', $baseUrl->setPath($path));
        $this->set('name', $name);
        $this->set('user', $this->app->make(User::class));
    }

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

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

    }

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


Question: // CurrentSession implements the KeybaseService interface for KeybaseServiceBase.

func (k *KeybaseServiceBase) CurrentSession(
	ctx context.Context, sessionID int) (
	idutil.SessionInfo, error) {
	ctx = CtxWithRandomIDReplayable(
		ctx, CtxKeybaseServiceIDKey, CtxKeybaseServiceOpID, k.log)

	s, newSession, err := k.getCurrentSession(ctx, sessionID)
	if err != nil {
		return idutil.SessionInfo{}, err
	}

	if newSession && k.config != nil {
		// Don't hold the lock while calling `serviceLoggedIn`.
		_ = serviceLoggedIn(ctx, k.config, s, TLFJournalBackgroundWorkEnabled)
	}

	return s, nil
}

func New(ctx context.Context, next http.Handler, config config.PassTLSClientCert, name string) (http.Handler, error) {
	middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware")

	return &passTLSClientCert{
		next: next,
		name: name,
		pem:  config.PEM,
		info: newTLSClientInfo(config.Info),
	}, nil
}

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


Question:
get current repository directory path

@return string

public function getRepository()
    {
        if (null === $this->repository) {
            $this->repository = $this->getBaseRepository();
            if ($this->hasContext()) {
                $this->repository .= DIRECTORY_SEPARATOR.$this->context;
            }
        }

        return $this->repository;
    }

protected function printPendingVersion(Version $version, $style)
    {
        /** @var Version $version */
        $id = $version->getId();
        $reflectionClass = new \ReflectionClass($version->getMigration());
        $absolutePath = $reflectionClass->getFileName();
        $fileName = $absolutePath ? $this->getRelativePath(getcwd(), $absolutePath) : '';
        $this->output->writeln("\t<$style>[$id] $fileName</$style>");
    }

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


Question:
计算七牛API中的数据格式:

    entry规格参考 https://developer.qiniu.com/kodo/api/1276/data-format

    Args:
        bucket: 待操作的空间名
        key:    待操作的文件名

    Returns:
        符合七牛API规格的数据格式

def entry(bucket, key):

    if key is None:
        return urlsafe_base64_encode('{0}'.format(bucket))
    else:
        return urlsafe_base64_encode('{0}:{1}'.format(bucket, key))

func VerifySwaggerDocsExist(kubeTypes []KubeTypes, w io.Writer) (int, error) {
	missingDocs := 0
	buffer := newBuffer()

	for _, kubeType := range kubeTypes {
		structName := kubeType[0].Name
		if kubeType[0].Doc == "" {
			format := "Missing documentation for the struct itself: %s\n"
			s := fmt.Sprintf(format, structName)
			buffer.addLine(s, 0)
			missingDocs++
		}
		kubeType = kubeType[1:] // Skip struct definition

		for _, pair := range kubeType { // Iterate only the fields
			if pair.Doc == "" {
				format := "In struct: %s, field documentation is missing: %s\n"
				s := fmt.Sprintf(format, structName, pair.Name)
				buffer.addLine(s, 0)
				missingDocs++
			}
		}
	}

	if err := buffer.flushLines(w); err != nil {
		return -1, err
	}
	return missingDocs, nil
}

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


Question: Generate a table of sorted (value, frequency) pairs.

def counts(data):

    if data is None:
        raise TypeError('None is not iterable')
    table = collections.Counter(data).most_common()
    if not table:
        return table
        # Extract the values with the highest frequency.
    maxfreq = table[0][1]
    for i in range(1, len(table)):
        if table[i][1] != maxfreq:
            table = table[:i]
            break
    return table

public function getTfIdf(DocumentAbstract $document, $token, $mode = 1)
    {
        return $this->getTermFrequency($document, $token, $mode) * $this->getIdf($token);
    }

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


Question:
Truncates a file to a given length

@param   int  $size length to truncate file to
@return  bool

public function truncate(int $size): bool
    {
        if ($size > $this->size()) {
            // Pad with null-chars if we're "truncating up"
            $this->content .= str_repeat("\0", $size - $this->size());
        } else {
            $this->content = substr($this->content, 0, $size);
        }

        return true;
    }

public function execute(Node $node, Application $application, Deployment $deployment, array $options = [])
    {
        $this->checkOptionsForValidity($options);

        $this->shell->execute('rm -f ' . $options['targetFile'] . '; mkdir -p ' . dirname($options['targetFile']), $node, $deployment);
        $sourcePath = $deployment->getApplicationReleasePath($application);

        $tarOptions = sprintf(' --transform="s,^%s,%s," ', ltrim($sourcePath, '/'), $options['baseDirectory']);
        if (isset($options['exclude']) && is_array($options['exclude'])) {
            foreach ($options['exclude'] as $excludePattern) {
                $tarOptions .= sprintf(' --exclude="%s" ', $excludePattern);
            }
        }

        if (substr($options['targetFile'], -7) === '.tar.gz') {
            $tarOptions .= sprintf(' -czf %s %s', $options['targetFile'], $sourcePath);
            $this->shell->execute(sprintf('tar %s || gnutar %s', $tarOptions, $tarOptions), $node, $deployment);
        } elseif (substr($options['targetFile'], -8) === '.tar.bz2') {
            $tarOptions .= sprintf(' -cjf %s %s', $options['targetFile'], $sourcePath);
            $this->shell->execute(sprintf('tar %s || gnutar %s', $tarOptions, $tarOptions), $node, $deployment);
        } elseif (substr($options['targetFile'], -4) === '.zip') {
            $temporaryDirectory = sys_get_temp_dir() . '/' . uniqid('f3_deploy');
            $this->shell->execute(sprintf('mkdir -p %s', $temporaryDirectory), $node, $deployment);
            $tarOptions .= sprintf(' -cf %s/out.tar %s', $temporaryDirectory, $sourcePath);
            $this->shell->execute(sprintf('tar %s || gnutar %s', $tarOptions, $tarOptions), $node, $deployment);
            $this->shell->execute(sprintf('cd %s; tar -xf out.tar; rm out.tar; zip --quiet -9 -r out %s', $temporaryDirectory, $options['baseDirectory']), $node, $deployment);
            $this->shell->execute(sprintf('mv %s/out.zip %s; rm -Rf %s', $temporaryDirectory, $options['targetFile'], $temporaryDirectory), $node, $deployment);
        } else {
            throw new TaskExecutionException('Unknown target file format', 1314248387);
        }
    }

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


Question: // newGraph summarizes performance data from a profile into a graph.

func newGraph(rpt *Report) (g graph, err error) {
	prof := rpt.prof
	o := rpt.options

	// Generate a tree for graphical output if requested.
	buildTree := o.CallTree && o.OutputFormat == Dot

	locations := make(map[uint64][]nodeInfo)
	for _, l := range prof.Location {
		locations[l.ID] = newLocInfo(l)
	}

	nm := make(nodeMap)
	for _, sample := range prof.Sample {
		if sample.Location == nil {
			continue
		}

		// Construct list of node names for sample.
		var stack []nodeInfo
		for _, loc := range sample.Location {
			id := loc.ID
			stack = append(stack, locations[id]...)
		}

		// Upfront pass to update the parent chains, to prevent the
		// merging of nodes with different parents.
		if buildTree {
			var nn *node
			for i := len(stack); i > 0; i-- {
				n := &stack[i-1]
				n.parent = nn
				nn = nm.findOrInsertNode(*n)
			}
		}

		leaf := nm.findOrInsertNode(stack[0])
		weight := rpt.sampleValue(sample)
		leaf.addTags(sample, weight)

		// Aggregate counter data.
		leaf.flat += weight
		seen := make(map[*node]bool)
		var nn *node
		for _, s := range stack {
			n := nm.findOrInsertNode(s)
			if !seen[n] {
				seen[n] = true
				n.cum += weight

				if nn != nil {
					bumpWeight(n, nn, weight, false)
				}
			}
			nn = n
		}
	}

	// Collect new nodes into a report.
	ns := make(nodes, 0, len(nm))
	for _, n := range nm {
		if rpt.options.DropNegative && n.flat < 0 {
			continue
		}
		ns = append(ns, n)
	}

	return graph{ns}, nil
}

public function indexAction(Request $request)
    {
        $this->get('white_october_breadcrumbs')
            ->addItem('Home', $this->get('router')->generate('_homepage'))
        ;

        $chart = $this->get('phospr.account_handler')
            ->getChartOfAccounts()
        ;

        return array(
            'favourite_accounts' => $this->get('phospr.account_handler')
                ->getFavouriteAccountsForUser(
                    $this->get('security.context')
                        ->getToken()
                        ->getUser()
                )
        );
    }

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


Question:
Render a template, optionally with parameters.

Implementations MUST support the `namespace::template` naming convention,
and allow omitting the filename extension.

@param string $name
@param array  $params

public function render(string $name, array $params = []): string
    {
        $path = $this->finder->findTemplate($name);
        $params = array_merge($this->attributes, $params);

        return $this->engine->render($path, $params);
    }

protected function generateStandardUrl(array $urlParameters = array(), $absolute = false)
    {
        $urlParameters = $this->addRequestVariablesToUrlParameters($urlParameters);

        $anchor = '';
        if ($this->hasAnchor())
        {
            $anchor = '#'.$this->getAnchor();
        }

        return $this->getRouter()->generate($this->getRouteName(), $urlParameters, $absolute) . $anchor;
    }

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


Question:
Determines if this analyzer is enabled.

@return true if the analyzer is enabled; otherwise
false

private boolean checkEnabled() {
        boolean retVal = false;

        try {
            if (getSettings().getBoolean(Settings.KEYS.ANALYZER_CENTRAL_ENABLED)) {
                if (!getSettings().getBoolean(Settings.KEYS.ANALYZER_NEXUS_ENABLED)
                        || NexusAnalyzer.DEFAULT_URL.equals(getSettings().getString(Settings.KEYS.ANALYZER_NEXUS_URL))) {
                    LOGGER.debug("Enabling the Central analyzer");
                    retVal = true;
                } else {
                    LOGGER.info("Nexus analyzer is enabled, disabling the Central Analyzer");
                }
            } else {
                LOGGER.info("Central analyzer disabled");
            }
        } catch (InvalidSettingException ise) {
            LOGGER.warn("Invalid setting. Disabling the Central analyzer");
        }
        return retVal;
    }

public Selector getSelector(String selector)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      tc.entry(cclass,
               "getSelector",
               "selector: " + selector);
  	// Start by parsing the selector expression (in-line for the moment)
  	selOperands = new ArrayList();
    // We'll Construct a selector tree
    Selector selectorTree = null;

    try
    {
      parseSelector(selector);

      Selector[] selectorArray = new Selector[selOperands.size()];
      selOperands.toArray(selectorArray);

      // Iterate over the nodes that were passed into us
      for(int i = selectorArray.length - 1 ; i>=0; i--)
      {
        Selector parsedSelector = (Selector)selectorArray[i];
        if(selectorTree == null)
          selectorTree = parsedSelector;
        else
          selectorTree = matching.createExtensionOperator(Selector.AND, parsedSelector, selectorTree);
      }
    }
    catch(InvalidXPathSyntaxException iex)
    {
      // No FFDC Code Needed.
      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
        tc.debug(this,cclass, "getSelector", iex);

      // Attempt to parse the entire selector expression. If that fails, then
      // we really can despair of handling this expression.
      selectorTree = parseWholeSelector(selector);
    }
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
        tc.exit(this,cclass, "getSelector", selectorTree);

    return selectorTree;
  }

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


Question: // mergeCollectedData merges the collected data into cache. It should be invoked under lock protected.

func (n *networkCounter) mergeCollectedData(packetsReceivedPerSecondData,
	packetsSentPerSecondData,
	bytesReceivedPerSecondData,
	bytesSentPerSecondData,
	packetsReceivedDiscardedData,
	packetsReceivedErrorsData,
	packetsOutboundDiscardedData,
	packetsOutboundErrorsData map[string]uint64) {
	adapters := sets.NewString()

	// merge the collected data and list of adapters.
	adapters.Insert(n.mergePacketsReceivedPerSecondData(packetsReceivedPerSecondData)...)
	adapters.Insert(n.mergePacketsSentPerSecondData(packetsSentPerSecondData)...)
	adapters.Insert(n.mergeBytesReceivedPerSecondData(bytesReceivedPerSecondData)...)
	adapters.Insert(n.mergeBytesSentPerSecondData(bytesSentPerSecondData)...)
	adapters.Insert(n.mergePacketsReceivedDiscardedData(packetsReceivedDiscardedData)...)
	adapters.Insert(n.mergePacketsReceivedErrorsData(packetsReceivedErrorsData)...)
	adapters.Insert(n.mergePacketsOutboundDiscardedData(packetsOutboundDiscardedData)...)
	adapters.Insert(n.mergePacketsOutboundErrorsData(packetsOutboundErrorsData)...)

	// delete the cache for non-existing adapters.
	for adapter := range n.adapterStats {
		if !adapters.Has(adapter) {
			delete(n.adapterStats, adapter)
		}
	}
}

public <K> Map<K, String> getMulti(Serializer<K> keySerializer, K... keys) {
    MultigetSliceQuery<K, String,String> q = createMultigetSliceQuery(keyspace, keySerializer, serializer, serializer);
    q.setColumnFamily(CF_NAME);
    q.setKeys(keys);
    q.setColumnNames(COLUMN_NAME);

    QueryResult<Rows<K, String,String>> r = q.execute();
    Rows<K, String,String> rows = r.get();
    Map<K, String> ret = new HashMap<K, String>(keys.length);
    for (K k: keys) {
      HColumn<String,String> c = rows.getByKey(k).getColumnSlice().getColumnByName(COLUMN_NAME);
      if (c != null && c.getValue() != null) {
        ret.put(k, c.getValue());
      }
    }
    return ret;
  }

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


Question:
Get the @font-face rule at the specified index.

@param nIndex
The index to be resolved. Should be ≥ 0 and <
{@link #getFontFaceRuleCount()}.
@return null if an invalid index was specified.
@since 3.7.4

@Nullable
  public CSSFontFaceRule getFontFaceRuleAtIndex (@Nonnegative final int nIndex)
  {
    return m_aRules.getAtIndexMapped (r -> r instanceof CSSFontFaceRule, nIndex, r -> (CSSFontFaceRule) r);
  }

function unexpectedTokenError(token, message) {
        var value, msg = message || Messages.UnexpectedToken;

        if (token) {
            if (!message) {
                msg = (token.type === Token.EOF) ? Messages.UnexpectedEOS :
                    (token.type === Token.Identifier) ? Messages.UnexpectedIdentifier :
                    (token.type === Token.NumericLiteral) ? Messages.UnexpectedNumber :
                    (token.type === Token.StringLiteral) ? Messages.UnexpectedString :
                    (token.type === Token.Template) ? Messages.UnexpectedTemplate :
                    Messages.UnexpectedToken;

                if (token.type === Token.Keyword) {
                    if (isFutureReservedWord(token.value)) {
                        msg = Messages.UnexpectedReserved;
                    } else if (strict && isStrictModeReservedWord(token.value)) {
                        msg = Messages.StrictReservedWord;
                    }
                }
            }

            value = (token.type === Token.Template) ? token.value.raw : token.value;
        } else {
            value = 'ILLEGAL';
        }

        msg = msg.replace('%0', value);

        return (token && typeof token.lineNumber === 'number') ?
            createError(token.lineNumber, token.start, msg) :
            createError(scanning ? lineNumber : lastLineNumber, scanning ? index : lastIndex, msg);
    }

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


Question:
<p>
An array of objects that contain detailed information about recovery points saved in a backup vault.
</p>

@param recoveryPoints
An array of objects that contain detailed information about recovery points saved in a backup vault.

public void setRecoveryPoints(java.util.Collection<RecoveryPointByBackupVault> recoveryPoints) {
        if (recoveryPoints == null) {
            this.recoveryPoints = null;
            return;
        }

        this.recoveryPoints = new java.util.ArrayList<RecoveryPointByBackupVault>(recoveryPoints);
    }

function(class_data) {

		var prototype = {},
			skeleton = class_data.skeleton,
			serialized_value,
			constructor_actions = [],
			name,
			source,
			constructor,
			object_properties,
			uses_references = false,
			is_monomorphic = class_data.is_monomorphic;

		for (name in skeleton) {

			switch (skeleton[name].type) {
				case this.MEMBER_TYPES.STRING:
					if (is_monomorphic) {
						serialized_value = Firestorm.String.quote(skeleton[name].value);
					} else {
						prototype[name] = skeleton[name].value;
					}
					break;
				case this.MEMBER_TYPES.PRIMITIVE: // null, boolean, number
					if (is_monomorphic) {
						serialized_value = skeleton[name].value + '';
					} else {
						prototype[name] = skeleton[name].value;
					}
					break;
				case this.MEMBER_TYPES.EMPTY_ARRAY:
					serialized_value = "[]";
					break;
				case this.MEMBER_TYPES.INLINE_ARRAY:
					serialized_value = this._serializeInlineArray(skeleton[name].value);
					break;
				case this.MEMBER_TYPES.REGEXP:
				case this.MEMBER_TYPES.FUNCTION:
					prototype[name] = class_data.references[skeleton[name].index];
					break;
				case this.MEMBER_TYPES.SLICE_ARRAY:
					serialized_value = 'r[' + skeleton[name].index + '].slice()';
					uses_references = true;
					break;
				case this.MEMBER_TYPES.OBJECT:
					object_properties = [];
					if (this._serializeSkeleton(skeleton[name].skeleton, class_data, "\t", object_properties)) {
						uses_references = true;
					}
					serialized_value = object_properties.length
						? "{\n\t" + object_properties.join(",\n\t") + "\n}"
						: "{}";
					break;
				default:
					Lava.t("[_buildRealConstructor] unknown property descriptor type: " + skeleton[name].type);
			}

			if (serialized_value) {

				if (Lava.VALID_PROPERTY_NAME_REGEX.test(name)) {

					constructor_actions.push('this.' + name + ' = ' + serialized_value);

				} else {

					constructor_actions.push('this[' + Firestorm.String.quote(name) + '] = ' + serialized_value);

				}

				serialized_value = null;

			}

		}

		for (name in class_data.shared) {

			prototype[name] = class_data.shared[name];

		}

		prototype.Class = class_data;

		source = (uses_references ? ("var r=this.Class.references;\n") : '')
			+ constructor_actions.join(";\n")
			+ ";";

		if (class_data.skeleton.init) {

			source += "\nthis.init.apply(this, arguments);";

		}

		constructor = new Function(source);
		// for Chrome we could assign prototype object directly,
		// but in Firefox this will result in performance degradation
		Firestorm.extend(constructor.prototype, prototype);
		return constructor;

	}

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


Question:
// blockIsTip determines if the block is in the db and if it is the current
// chain tip. Returning a nil indicates that the block is the Chain Tip.

func (db *PublicRecord) blockIsTip(tx *sql.Tx, sha *wire.ShaHash) error {
	r, err := tx.Stmt(db.blockIsTipStmt).Query(sha.String())
	defer r.Close()
	if err != nil {
		return err
	}

	var isTip bool
	r.Next()
	if err = r.Scan(&isTip); err != nil {
		return err
	}

	if !isTip {
		return ErrBlockNotTip
	}
	return nil
}

def borrow_from_next_sibling(next_node)
      if next_node.keys.length - 1 > min_keys
        # The next sibling now has a new lead key that requires the branch key
        # to be updated in the parent node.
        index = next_node.parent.search_node_index(next_node) - 1

        @tree.node_cache.insert(self)
        @tree.node_cache.insert(next_node.get_node)
        @tree.node_cache.insert(next_node.parent.get_node)
        if @is_leaf
          # Move the first key of the next node to the end of the this node
          @keys << next_node.keys.shift
          # Register the new lead key of next_node with its parent
          next_node.parent.keys[index] = next_node.keys.first
          # Move the first value of the next node to the end of this node
          @values << next_node.values.shift
        else
          # For branch nodes we need to get the lead key from the parent of
          # next_node.
          @keys << next_node.parent.keys[index]
          # The old lead key of next_node becomes the branch key in the parent
          # of next_node. And the keys of next_node are shifted.
          next_node.parent.keys[index] = next_node.keys.shift
          # Move the first child of the next node to the end of this node
          @children << (node = next_node.children.shift)
          node.parent = link(self)
        end

        return true
      end

      false
    end

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


Question: // SetFlags is part of the cmd.Command interface.

func (c *trustCommand) SetFlags(f *gnuflag.FlagSet) {
	c.ModelCommandBase.SetFlags(f)
	f.BoolVar(&c.removeTrust, "remove", false, "Remove trusted access from a trusted application")
}

def refresh(cls):

        # clear the old values in _flag_map
        try:
            del cls._flag_map["t"]
        except KeyError:
            pass

        try:
            del cls._flag_map["-"]
        except KeyError:
            pass

        # set the value given the git version
        if Git().version_info[:2] >= (2, 10):
            cls._flag_map["t"] = cls.TAG_UPDATE
        else:
            cls._flag_map["-"] = cls.TAG_UPDATE

        return True

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


Question:
Create the standard expression query.

 @api private

 @example Create the selection.
   selectable.expr_query(age: 50)

 @param [ Hash ] criterion The field/value pairs.

 @return [ Selectable ] The cloned selectable.

 @since 1.0.0

def expr_query(criterion)
      selection(criterion) do |selector, field, value|
        if (field.is_a? Key) && custom_serialization?(field.name, field.operator)
          specified = custom_specify(field.name, field.operator, value)
        else
          specified = field.specify(value.__expand_complex__, negating?)
        end
        selector.merge!(specified)
      end
    end

protected AVariableExp getVarExp(ILexNameToken name, PDefinition vardef)
	{
		AVariableExp var = new AVariableExp();
		var.setName(name.clone());
		var.setOriginal(name.getFullName());
		var.setVardef(vardef.clone());
		return var;
	}

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


Question: Only allow a trusted parameter "white list" through.

def access_group_params(mode = :all)
      list = []
      list += [ :name ] if mode == :before_create || mode == :all
      list += [ { group_ids: [], user_ids: [] } ] if mode == :after_create || mode == :all

      params.require(:access_group).permit(list)
    end

func (sp *StandardProvider) Ready() bool {
	switch {
	case sp.internal.priv == nil:
		return false
	case sp.internal.cert == nil:
		return false
	case sp.internal.keyPEM == nil:
		return false
	case sp.internal.certPEM == nil:
		return false
	default:
		return true
	}
}

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


Question:
Return build metadata by key, project and optionally build id.
@param $key
@param $projectId
@param null $buildId
@param null $branch
@param int $numResults
@return array|null

public function getMeta($key, $projectId, $buildId = null, $branch = null, $numResults = 1)
    {
        $query = 'SELECT bm.build_id, bm.meta_key, bm.meta_value
                    FROM build_meta AS bm
                    LEFT JOIN build b ON b.id = bm.build_id
                    WHERE   bm.meta_key = :key
                      AND   bm.project_id = :projectId';

        // If we're getting comparative meta data, include previous builds
        // otherwise just include the specified build ID:
        if ($numResults > 1) {
            $query .= ' AND bm.build_id <= :buildId ';
        } else {
            $query .= ' AND bm.build_id = :buildId ';
        }

        // Include specific branch information if required:
        if (!is_null($branch)) {
            $query .= ' AND b.branch = :branch ';
        }

        $query .= ' ORDER BY bm.id DESC LIMIT :numResults';

        $stmt = Database::getConnection('read')->prepare($query);
        $stmt->bindValue(':key', $key, \PDO::PARAM_STR);
        $stmt->bindValue(':projectId', (int)$projectId, \PDO::PARAM_INT);
        $stmt->bindValue(':buildId', (int)$buildId, \PDO::PARAM_INT);
        $stmt->bindValue(':numResults', (int)$numResults, \PDO::PARAM_INT);

        if (!is_null($branch)) {
            $stmt->bindValue(':branch', $branch, \PDO::PARAM_STR);
        }

        if ($stmt->execute()) {
            $rtn = $stmt->fetchAll(\PDO::FETCH_ASSOC);

            $rtn = array_reverse($rtn);
            $rtn = array_map(function ($item) {
                $item['meta_value'] = json_decode($item['meta_value'], true);
                return $item;
            }, $rtn);

            if (!count($rtn)) {
                return null;
            } else {
                return $rtn;
            }
        } else {
            return null;
        }
    }

public function get($type)
    {
        $ret = null;
        if ('image' == $type) {
            if (isset($this->metasProp['og:image'])) {
                $ret = $this->metasProp['og:image'];
            } elseif ($this->getParameter('nyroDev_utility.share.image')) {
                $ret = $this->getParameter('nyroDev_utility.share.image');
            }
        } else {
            if (isset($this->metas[$type])) {
                $ret = $this->metas[$type];
            } elseif ($this->getParameter('nyroDev_utility.share.'.$type)) {
                $ret = $this->getParameter('nyroDev_utility.share.'.$type);
            }
        }

        return preg_replace('/\s\s+/', ' ', $this->trans($ret));
    }

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


Question:
Builds flex message structure.

@return array

public function buildMessage()
    {
        if (isset($this->message)) {
            return $this->message;
        }

        $this->message = [
            BuildUtil::removeNullElements([
                'type' => MessageType::FLEX,
                'altText' => $this->altText,
                'contents' => $this->containerBuilder->build(),
                'quickReply' => BuildUtil::build($this->quickReply, 'buildQuickReply'),
            ])
        ];

        return $this->message;
    }

def send(self, msg, timeout=None):

        arb_id = msg.arbitration_id
        if msg.is_extended_id:
            arb_id |= NC_FL_CAN_ARBID_XTD
        raw_msg = TxMessageStruct(arb_id,
                                  bool(msg.is_remote_frame),
                                  msg.dlc,
                                  CanData(*msg.data))
        nican.ncWrite(
            self.handle, ctypes.sizeof(raw_msg), ctypes.byref(raw_msg))

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


Question: // Disconnect disconnects from VPP API and releases all connection-related resources.

func (c *Connection) Disconnect() {
	if c == nil {
		return
	}

	if c.vppClient != nil {
		c.disconnectVPP()
	}
}

public function leave(ResponseInterface $response = null)
    {
        $this->ends = [
            'wt' => microtime(true),
            'mu' => memory_get_usage(),
            'pmu' => memory_get_peak_usage(),
        ];
        if ($response) {
            $this->response = [
                'headers' => $response->getHeaders(),
                'statusCode' => $response->getStatusCode(),
                'body' => (string)$response->getBody(),
            ];
        }
    }

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


Question:
Output a warning message that designates the beginning of a task.

@param string $message The message to output.
@param array $context Context variables to pass to the message.
@return $this

public function beginWarning(string $message, array $context = []) {
        return $this->begin(LogLevel::WARNING, $message, $context);
    }

protected function logInfo()
  {
    $args   = func_get_args();
    $format = array_shift($args);

    foreach ($args as &$arg)
    {
      if (!is_scalar($arg)) $arg = var_export($arg, true);
    }

    if (sizeof($args)==0)
    {
      $this->log($format, \Project::MSG_INFO);
    }
    else
    {
      $this->log(vsprintf($format, $args), \Project::MSG_INFO);
    }
  }

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


Question:
// IfEmpty adds an empty check on the given key to the given condition
// and returns the updated condition.

func (c WriteCondition) add(key []string, updater func(wc *writeCondition)) WriteCondition {
	if c.conditions == nil {
		c.conditions = make(map[string]writeCondition)
	}
	fullKey := createFullKey(key)
	wc := c.conditions[fullKey]
	updater(&wc)
	c.conditions[fullKey] = wc
	return c
}

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

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

        return self._output.getvalue()

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


Question: // SetGT sets the GT field's value.

func (s *DescribeDataSourcesInput) SetGT(v string) *DescribeDataSourcesInput {
	s.GT = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question:
Create a CSS expression only containing a text value

@param sValue
The value to be wrapped in an expression
@return The CSS expression to be used.

@Nonnull
  public static CSSExpression createSimple (@Nonnull @Nonempty final String sValue)
  {
    return new CSSExpression ().addTermSimple (sValue);
  }

function(container_config, x) {

		var i,
			count,
			name;

		if ('event' in x) {

			if (typeof(x.event) != 'object') Lava.t("Malformed x:event attribute");

			container_config.events = {};

			for (name in x.event) {

				container_config.events[name] = Lava.parsers.Common.parseTargets(x.event[name]);

			}

		}

		// Attribute binding. Example: x:bind:src="<any_valid_expression>"
		if ('bind' in x) {

			if (typeof(x.bind) != 'object') Lava.t("Malformed x:bind attribute");

			container_config.property_bindings = this._parseBindingsHash(x.bind);

		}

		if ('style' in x) {

			if (typeof(x.style) != 'object') Lava.t("Malformed x:style attribute");

			container_config.style_bindings = this._parseBindingsHash(x.style);

		}

		if ('classes' in x) {

			var arguments = Lava.ExpressionParser.parse(x.classes, Lava.ExpressionParser.SEPARATORS.SEMICOLON),
				class_bindings = {};

			for (i = 0, count = arguments.length; i < count; i++) {

				class_bindings[i] = arguments[i];

			}

			container_config.class_bindings = class_bindings;

		}

		if ('container_class' in x) {

			container_config['class'] = x.container_class;

		}

	}

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


Question:
@param string $name
@param        $value

@return void

private function set(string $name, $value):void{
		$method = 'magic_set_'.$name;

		if(\method_exists($this, $method)){
			$this->$method($value);
		}

	}

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

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

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

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

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

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

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

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

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

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

    return null;
  }

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


Question:
Method for a single column with actions

@return ColumnInterface

public function setKeyAction(): ColumnInterface
    {
        $this->key = self::ACTION_NAME;
        $this->setValue('');
        $this->setSort(false);
        $this->setScreening(true);

        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: Returns True is a function is a descendant of itself.

def is_recursive(self, child_item):
        """"""
        ancestor = child_item.parent()
        # FIXME: indexes to data should be defined by a dictionary on init
        while ancestor:
            if (child_item.data(0, Qt.DisplayRole
                                ) == ancestor.data(0, Qt.DisplayRole) and
                child_item.data(7, Qt.DisplayRole
                                ) == ancestor.data(7, Qt.DisplayRole)):
                return True
            else:
                ancestor = ancestor.parent()
        return False

def append(self, node):
        """"""
        if node.parent == self.key and not self.elapsed_time:
            self.children.append(node)
        else:
            # Recursive call
            for child in self.children:
                if not child.elapsed_time:
                    child.append(node)

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


Question: // IsShuttingDown answers if we are shutting down or not

func (t *Tab) IsShuttingDown() bool {
	if flag, ok := t.shutdown.Load().(bool); ok {
		return flag
	}
	return false
}

public function canConnect()
    {
        $data = $this->get(self::CURRENT_USER_ENDPOINT);
        if (strpos($data['code'], '2') === 0) {
            return true;
        }
        return false;
    }

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


Question: Run the iteration.

def Run(self):
    """"""
    count = 0
    for count, input_data in enumerate(self.GetInput()):
      if count % 2000 == 0:
        logging.debug("%d processed.", count)
      args = (input_data, self.out_queue, self.token)
      self.thread_pool.AddTask(
          target=self.IterFunction, args=args, name=self.THREAD_POOL_NAME)

    while count >= 0:
      try:
        # We only use the timeout to wait if we got to the end of the Queue but
        # didn't process everything yet.
        out = self.out_queue.get(timeout=self.QUEUE_TIMEOUT, block=True)
        if out:
          yield out
          count -= 1
      except queue.Empty:
        break

    # Join and stop to clean up the threadpool.
    self.thread_pool.Stop(join_timeout=THREADPOOL_JOIN_TIMEOUT)

public Iterator<RangeTombstone> rangeIterator()
    {
        return ranges == null ? Iterators.<RangeTombstone>emptyIterator() : ranges.iterator();
    }

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


Question:
Init the SMTPClienSesion by adding all needed data to the attributes

@param session

@SuppressWarnings("unchecked")
    private void initSession(SMTPClientSession session) {
        Iterator<SMTPDeliveryEnvelope> transactionList = ((Iterator<SMTPDeliveryEnvelope>) session.getAttribute(SMTP_TRANSACTIONS_KEY));
        SMTPDeliveryEnvelope transaction =  transactionList.next();

        session.setAttribute(CURRENT_SMTP_TRANSACTION_KEY,transaction);
        session.setAttribute(RECIPIENTS_KEY, transaction.getRecipients().iterator());
        session.setAttribute(DELIVERY_STATUS_KEY, new ArrayList<DeliveryRecipientStatus>());

        // cleanup old attribute
        session.setAttribute(CURRENT_RCPT_KEY, null);

    }

def capture_setting(self, sbp_msg, **metadata):

        if sbp_msg.msg_type == SBP_MSG_SETTINGS_READ_RESP:
            section, setting, value = sbp_msg.payload.split(b'\0')[:3]
            self.settings.append((section, setting, value))

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


Question: // addItemToGroups adds and item to a group

func (c *Cache) addItemToGroups(itmKey string, groupIDs []string) {
	for _, grpID := range groupIDs {
		if _, has := c.groups[grpID]; !has {
			c.groups[grpID] = make(map[string]struct{})
		}
		c.groups[grpID][itmKey] = struct{}{}
	}
}

public function create()
	{

		$GLOBALS['TL_DCA']['tl_content']['palettes'][$this->element] .= ';{section-'. $this->id . (($this->hidden) ? ':hide' : ''). '}';
		$GLOBALS['TL_LANG']['tl_content']['section-' . $this->id] = $this->label;
	}

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


Question:
Parse XML

This method creates a SimpleXMLElement
based upon the XML input. If the SimpleXML
extension is not available, the raw input
will be returned unchanged.

@param  string                   $input
@return \SimpleXMLElement|string

protected function parseXml($input)
    {
        if (class_exists('SimpleXMLElement')) {
            try {
                $backup = libxml_disable_entity_loader(true);
                $result = new \SimpleXMLElement($input);
                libxml_disable_entity_loader($backup);

                return $result;
            } catch (\Exception $e) {
                // Do nothing
            }
        }

        return $input;
    }

public function getChild($tag, $attrs = [])
    {
        $ret = null;
        if ($this->children) {
            if (is_int($tag)) {
                if (isset($this->children[$tag])) {
                    return $this->children[$tag];
                } else {
                    return;
                }
            }
            foreach ($this->children as $child) {
                if (strcmp($child->tag, $tag) == 0) {
                    $found = true;
                    foreach ($attrs as $key => $value) {
                        if (strcmp($child->getAttribute($key), $value) != 0) {
                            $found = false;
                            break;
                        }
                    }
                    if ($found) {
                        return $child;
                    }
                }
                $ret = $child->getChild($tag, $attrs);
                if ($ret) {
                    return $ret;
                }
            }
        }
    }

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


Question:
Simplify a query, taking away exact values and fields selected.

    Imperfect but better than super explicit, value-dependent queries.

def sql_fingerprint(query, hide_columns=True):

    parsed_query = parse(query)[0]
    sql_recursively_simplify(parsed_query, hide_columns=hide_columns)
    return str(parsed_query)

def get_specification_info(self, obj):

        info = self.get_base_info(obj)

        results_range = obj.getResultsRange()
        info.update({
            "results_range": results_range,
            "sample_type_uid": obj.getSampleTypeUID(),
            "sample_type_title": obj.getSampleTypeTitle(),
            "client_uid": obj.getClientUID(),
        })

        bsc = api.get_tool("bika_setup_catalog")

        def get_service_by_keyword(keyword):
            if keyword is None:
                return []
            return map(api.get_object, bsc({
                "portal_type": "AnalysisService",
                "getKeyword": keyword
            }))

        # append a mapping of service_uid -> specification
        specifications = {}
        for spec in results_range:
            service_uid = spec.get("uid")
            if service_uid is None:
                # service spec is not attached to a specific service, but to a
                # keyword
                for service in get_service_by_keyword(spec.get("keyword")):
                    service_uid = api.get_uid(service)
                    specifications[service_uid] = spec
                continue
            specifications[service_uid] = spec
        info["specifications"] = specifications
        # spec'd service UIDs
        info["service_uids"] = specifications.keys()
        return info

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


Question:
@param \Reliese\Coders\Model\Model $model
@param array $custom

@return string

protected function modelPath(Model $model, $custom = [])
    {
        $modelsDirectory = $this->path(array_merge([$this->config($model->getBlueprint(), 'path')], $custom));

        if (! $this->files->isDirectory($modelsDirectory)) {
            $this->files->makeDirectory($modelsDirectory, 0755, true);
        }

        return $this->path([$modelsDirectory, $model->getClassName().'.php']);
    }

private void distributedProcessFinish(ResponseBuilder rb,
      ComponentFields mtasFields) throws IOException {
    // rewrite

    Object mtasResponseRaw;
    if ((mtasResponseRaw = rb.rsp.getValues().get("mtas")) != null
        && mtasResponseRaw instanceof NamedList) {
      NamedList<Object> mtasResponse = (NamedList<Object>) mtasResponseRaw;
      Object mtasResponseTermvectorRaw;
      if ((mtasResponseTermvectorRaw = mtasResponse.get(NAME)) != null
          && mtasResponseTermvectorRaw instanceof ArrayList) {
        MtasSolrResultUtil.rewrite(
            (ArrayList<Object>) mtasResponseTermvectorRaw, searchComponent);
      }
    }
  }

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


Question:
Returns the list of available collections.
@param array $condition filter condition.
@param array $options options list.
@return array collections information.

public function listCollections($condition = [], $options = [])
    {
        $this->document = $this->db->getQueryBuilder()->listCollections($condition, $options);
        $cursor = $this->execute();

        return $cursor->toArray();
    }

public static function getQueryWhere($request, $query, $parameters)
    {
        $indexColumns   = isset($parameters['indexColumns'])? $parameters['indexColumns'] : null;
        $where          = isset($parameters['where'])? $parameters['where'] : null;
        $whereColumns   = isset($parameters['whereColumns'])? $parameters['whereColumns'] : null;

        if($where != null)
        {
            $columns = $request->input('columns');

            $query->where(function($query) use ($columns, $indexColumns, $where){
                $i=0;
                foreach($indexColumns as $indexColumn)
                {
                    // check if column if is searchable
                    if($columns[$i]['searchable'] === 'true')
                    {
                        if(is_array($indexColumn)) $indexColumn = $indexColumn['data'];

                        $query->orWhere($indexColumn, 'LIKE', '%' . $where . '%');
                    }
                    $i++;
                }
            });
        }

        if(is_array($whereColumns))
        {
            $query->where(function($query) use ($whereColumns) {
                foreach($whereColumns as $whereColumn)
                {
                    // enable option to be null value, with NULL
                    if($whereColumn['value'] == 'NULL')
                        $whereColumn['value'] = null;

                    $query->where($whereColumn['column'], $whereColumn['operator'], $whereColumn['value']);
                }
            });
        }

        return $query;
    }

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


Question:
Reimplement Qt method to be able to save the widget's size from the
        main application

def resizeEvent(self, event):

        QDialog.resizeEvent(self, event)
        self.size_change.emit(self.size())

def register_actions(self, shortcut_manager):

        shortcut_manager.add_callback_for_action("delete", self.remove_action_callback)
        shortcut_manager.add_callback_for_action("add", self.add_action_callback)
        shortcut_manager.add_callback_for_action("copy", self.copy_action_callback)
        shortcut_manager.add_callback_for_action("cut", self.cut_action_callback)
        shortcut_manager.add_callback_for_action("paste", self.paste_action_callback)

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


Question:
Yield lines to execute in a docker context

        All conditions must evaluate for the container to be considered ready

def conditions(self, start, last_attempt):

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

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

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

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

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

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

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

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

def perform_start_stop_operations
      behavior(:detect_os)
      s=@servers.first
      # Save configuration files for comparison after starting
      behavior(:save_configuration_files, s)
      # Stop the servers
      behavior(:stop_ebs_all)
      # Verify all stopped
      # Start the servers
      behavior(:start_ebs_all, true)
#      Do this for all? Or just the one?
#      @servers.each { |server| server.wait_for_operational_with_dns }
      s=@servers.first
      object_behavior(s, :wait_for_operational_with_dns)
      # Verify operational
      behavior(:run_simple_check, s)
    end

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


Question:
深度复制一个对象，该对象及其属性都必须实现java.io.Serializable方法。此方法用于
TypeEngine引擎复制一个Program，并做优化用
@param o
@return

public static Object copy(Object o)
	{
		if (o instanceof java.io.Serializable)
		{
			try
			{
				ByteArrayOutputStream bs = new ByteArrayOutputStream(128);
				ObjectOutputStream dos = new ObjectOutputStream(bs);
				dos.writeObject(o);
				ByteArrayInputStream is = new ByteArrayInputStream(bs.toByteArray());
				ObjectInputStream ios = new ObjectInputStream(is);
				Object copy = ios.readObject();
				return copy;

			}
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			catch (ClassNotFoundException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return null;
	}

public static FilterStreamType unserialize(String str)
    {
        if (str == null) {
            return null;
        }

        String wikiType = str;
        String data = null;
        String version = null;

        // Version

        int versionIndex = str.lastIndexOf('/');

        if (versionIndex == 0) {
            throw new IllegalArgumentException("'/' is invalid as first character: " + str);
        }

        if (versionIndex != -1) {
            version = wikiType.substring(versionIndex + 1);
            wikiType = wikiType.substring(0, versionIndex);
        }

        // Data

        int dataIndex = str.indexOf('+');

        if (dataIndex == 0) {
            throw new IllegalArgumentException("'+' is invalid as first character: " + str);
        }

        if (dataIndex != -1) {
            data = wikiType.substring(dataIndex + 1);
            wikiType = wikiType.substring(0, dataIndex);
        }

        return new FilterStreamType(SystemType.unserialize(wikiType), data, version);
    }

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


Question: // SetName sets the Name field's value.

func (s *GetMaintenanceWindowTaskOutput) SetName(v string) *GetMaintenanceWindowTaskOutput {
	s.Name = &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:
Input: Portals device object.
        Output: The same device object with the device meta
                converted to a python string.

def stringify_device_meta(device_object):

    try:
        if isinstance(device_object['info']['description']['meta'], dict):
            device_object['info']['description']['meta'] =\
                json.dumps(device_object['info']['description']['meta'])
    except ValueError as err:
        print("stringify: {0}".format(err))
    return device_object

def _macronize_word(self, word):

        head_word = word[0]
        tag = word[1]
        if tag is None:
            logger.info('Tagger {} could not tag {}.'.format(self.tagger, head_word))
            return head_word, tag, head_word
        elif tag == 'U--------':
            return (head_word, tag.lower(), head_word)
        else:
            entries = self._retrieve_morpheus_entry(head_word)
            if entries is None:
                return head_word, tag.lower(), head_word
            matched_entry = [entry for entry in entries if entry[0] == tag.lower()]
            if len(matched_entry) == 0:
                logger.info('No matching Morpheus entry found for {}.'.format(head_word))
                return head_word, tag.lower(), entries[0][2]
            elif len(matched_entry) == 1:
                return head_word, tag.lower(), matched_entry[0][2].lower()
            else:
                logger.info('Multiple matching entries found for {}.'.format(head_word))
                return head_word, tag.lower(), matched_entry[1][2].lower()

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


Question:
添加节点分类

@param values
@return

public Graph categories(Category... values) {
        if (values == null || values.length == 0) {
            return this;
        }
        this.categories().addAll(Arrays.asList(values));
        return this;
    }

function yy_r130()
    {
        $this->_retvalue = '[' . $this->compiler->compileTag('private_special_variable', array(), '[\'section\'][\'' .
                                                                                $this->yystack[ $this->yyidx +
                                                                                - 1 ]->minor .
                                                                                '\'][\'index\']') . ']';
    }

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


Question:
// TabletsInUse returns a string of all tablet aliases currently in use.
// The tablets are separated by a space.

func (t *TabletTracker) TabletsInUse() string {
	t.mu.Lock()
	defer t.mu.Unlock()

	var aliases []string
	for alias := range t.usedTablets {
		aliases = append(aliases, alias)
	}
	sort.Strings(aliases)
	return strings.Join(aliases, " ")
}

def get_tables_and_gsis():

    table_names = set()
    configured_tables = get_configured_tables()
    not_used_tables = set(configured_tables)

    # Add regexp table names
    for table_instance in list_tables():
        for key_name in configured_tables:
            try:
                if re.match(key_name, table_instance.table_name):
                    logger.debug("Table {0} match with config key {1}".format(
                        table_instance.table_name, key_name))

                    # Notify users about regexps that match multiple tables
                    if table_instance.table_name in [x[0] for x in table_names]:
                        logger.warning(
                            'Table {0} matches more than one regexp in config, '
                            'skipping this match: "{1}"'.format(
                                table_instance.table_name, key_name))
                    else:
                        table_names.add(
                            (
                                table_instance.table_name,
                                key_name
                            ))
                        not_used_tables.discard(key_name)
                else:
                    logger.debug(
                        "Table {0} did not match with config key {1}".format(
                            table_instance.table_name, key_name))
            except re.error:
                logger.error('Invalid regular expression: "{0}"'.format(
                    key_name))
                sys.exit(1)

    if not_used_tables:
        logger.warning(
            'No tables matching the following configured '
            'tables found: {0}'.format(', '.join(not_used_tables)))

    return sorted(table_names)

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


Question:
检查元素或其祖先节点的属性是否等于预给值
@param elem {element} 起始元素
@param property {string} css属性
@param value {string} css属性值
@returns {boolean}

function checkParentsProperty(elem, property, value) {
    while (elem = elem.offsetParent) {
        if (getCss(elem, property) === value) {
            return true;
        }
    }
    return false;
}

function validateProp(key, value) {
  const type = typeof value;

  switch (key) {
  case 'orderByKey':
  case 'orderByPriority':
  case 'orderByValue':
    if (!value) {
      throw new Error(`"query.${key}" should not be set to false. Set it off by setting an other order.`);
    }
    break;

  case 'orderByChild':
    if (value == null) {
      throw new Error('"query.orderByChild" should not be set to null. Set it off by setting an other order.');
    }
    if (type !== 'string') {
      throw new Error('"query.orderByChild" should be a string or null.');
    }
    break;

  case 'startAt':
  case 'endAt':
  case 'equalTo':
    if (
      value !== null &&
      type !== 'string' &&
      type !== 'number' &&
      type !== 'boolean'
    ) {
      throw new Error(`query.${key} should be a string, a number, a boolean or null.`);
    }
    break;

  case 'limitToFirst':
  case 'limitToLast':
    if (value != null && type !== 'number') {
      throw new Error(`query.${key} should be a number or null.`);
    }
    break;

  default:
    throw new Error(`"${key}" is not a query parameter.`);
  }
}

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


Question:
mark

@param string $name
@param string $context
@param array  $data

@return  void

public static function mark($name, $context = null, $data = [])
    {
        if ($context) {
            $name .= ' / ' . $context;
        }

        $name .= sprintf('(%s)', uniqid());

        try {
            static::getInstance()->mark($name, $data);
        } catch (\Exception $e) {
            return;
        }
    }

public function initializeArguments()
    {
        parent::initializeArguments();
        $this->registerArgument('results', '\Solarium\QueryType\Select\Result\Result', 'Query results', true);
        $this->registerArgument('document', '\Solarium\QueryType\Select\Result\Document', 'Result document to work on',
            true);
        $this->registerArgument('field', 'string', 'name of field in document to highlight', true);
        $this->registerArgument('alternateField', 'string',
            'name of alternate field in document to use for highlighting', false, null);
        $this->registerArgument('index', 'int', 'if the field is an array: index of the single element to highlight',
            false);
        $this->registerArgument('idKey', 'string', 'name of the field in document that is its ID', false, 'id');
        $this->registerArgument('highlightTagOpen', 'string', 'opening tag to insert to begin highlighting', false,
            '');
        $this->registerArgument('highlightTagClose', 'string', 'closing tag to insert to end highlighting', false,
            '');
        $this->registerArgument('raw', 'boolean', 'whether to not HTML escape the output', false, false);
    }

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