Question:
>>> parse_form_request("123456",{"nonce": 1451122677, "msg": "helllo", "code": 0, "sign": "DB30F4D1112C20DFA736F65458F89C64"})
        <Storage {'nonce': 1451122677, 'msg': 'helllo', 'code': 0, 'sign': 'DB30F4D1112C20DFA736F65458F89C64'}>

def parse_form_request(api_secret, request):

    if not check_sign(api_secret, request):
        raise SignError(u"message sign error")

    return Storage(request)

function writeNaptr(buff, val, label_index) {
  assertUndefined(val.order, 'NAPTR record requires "order"');
  assertUndefined(val.preference, 'NAPTR record requires "preference"');
  assertUndefined(val.flags, 'NAPTR record requires "flags"');
  assertUndefined(val.service, 'NAPTR record requires "service"');
  assertUndefined(val.regexp, 'NAPTR record requires "regexp"');
  assertUndefined(val.replacement, 'NAPTR record requires "replacement"');
  buff.writeUInt16BE(val.order & 0xFFFF);
  buff.writeUInt16BE(val.preference & 0xFFFF);
  buff.writeUInt8(val.flags.length);
  buff.write(val.flags, val.flags.length, 'ascii');
  buff.writeUInt8(val.service.length);
  buff.write(val.service, val.service.length, 'ascii');
  buff.writeUInt8(val.regexp.length);
  buff.write(val.regexp, val.regexp.length, 'ascii');
  namePack(val.replacement, buff, label_index);
  return WRITE_RESOURCE_DONE;
}

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


Question: Compute the appropriate namer for the Java field @ManyToOne (with intermediate table)

public Namer getManyToOneIntermediateNamer(Namer fromEntityNamer, ColumnConfig pointsOnToEntity, Namer toEntityNamer) {

        // new configuration
        Namer result = getManyToOneNamerFromConf(pointsOnToEntity, toEntityNamer);

        // fallback
        if (result == null) {
            // NOTE: we use the many to many fallback as it is totally complient with intermediate m2o fallback expectations.
            result = getManyToManyNamerFallBack(fromEntityNamer, pointsOnToEntity, toEntityNamer);
        }

        return result;
    }

public static Collection<ModelElementType> calculateAllExtendingTypes(Model model, Collection<ModelElementType> baseTypes) {
    Set<ModelElementType> allExtendingTypes = new HashSet<ModelElementType>();
    for (ModelElementType baseType : baseTypes) {
      ModelElementTypeImpl modelElementTypeImpl = (ModelElementTypeImpl) model.getType(baseType.getInstanceType());
      modelElementTypeImpl.resolveExtendingTypes(allExtendingTypes);
    }
    return allExtendingTypes;
  }

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


Question: // Untrack tells juju to stop tracking this payload.

func (c *Context) Untrack(class, id string) error {
	fullID := payload.BuildID(class, id)
	logger.Tracef("Calling untrack on payload context %q", fullID)

	res, err := c.api.Untrack(fullID)
	if err != nil {
		return errors.Trace(err)
	}
	// TODO(ericsnow) We should not ignore a 0-len result.
	if len(res) > 0 && res[0].Error != nil {
		return errors.Trace(res[0].Error)
	}
	delete(c.payloads, id)

	return nil
}

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

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


Question: Execute queries against SQLite3, merge and return as a dict

def ext_pillar(minion_id,
               pillar,
               *args,
               **kwargs):
    '''

    '''
    return SQLite3ExtPillar().fetch(minion_id, pillar, *args, **kwargs)

def migrate(app_name=None, revision=None):
    ""
    cmd = ['python bin/manage.py syncdb --migrate']
    if app_name:
        cmd.append(app_name)
        if revision:
            cmd.append(revision)
    verun(' '.join(cmd))

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


Question:
Get tbody at specified index
@param index 0=first tbody, 1=second tbody.
添え字です。0なら一つ目のtbody、1なら二つ目のtbody
@return

public tbody tbody(int index) {
        while (tbodyList.size() <= index) {
            tbodyList.add(new tbody());
        }
        return tbodyList.get(index);
    }

protected function build($template)
    {
        $this->body['flash'] = array();
        if(isset($_SESSION['flash']['message'])) {
            $this->body['flash']['message'] = $_SESSION['flash']['message'];
            $this->body['flash']['type'] = $_SESSION['flash']['type'];
            unset($_SESSION['flash']);
        }

        $body = $this->parse($template, $this->body);

        $page = array(
            'flash' => $this->body['flash'],
            'meta' => $this->meta,
            'links' => $this->links,
            'styles' => $this->styles,
            'scripts' => $this->scripts,
            'title' => $this->title,
            'class' => $this->id,
            'head' => $this->head,
            'body' => $body,
            'foot' => $this->foot);

        $page = $this->parse($this->layout, $page);

        $this->response
            ->set('headers', 'Content-Type', 'text/html; charset=utf-8')
            ->set('body', $page);

        return $page;
    }

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


Question:
Parses the the rule OrExpr according to the following production rule:
<p>
[8] OrExpr ::= AndExpr ( "or" AndExpr )* .
</p>

@throws TTXPathException

private void parseOrExpr() throws TTXPathException {

        parseAndExpr();

        while (is("or", true)) {

            mPipeBuilder.addExpressionSingle();

            parseAndExpr();
            mPipeBuilder.addOrExpression(getTransaction());

        }
    }

public static String print(Expression expression) {
        return expression.match(new Expression.MatchBlock<String>() {

            @Override
            public String _case(LiteralExpression x) {
                return print(x.literal);
            }

            @Override
            public String _case(VariableExpression x) {
                return x.selector.match(new Optional.MatchBlock<Expression, String>() {
                    @Override
                    public String _case(Some<Expression> x) {
                        return print(x.value) + ".";
                    }

                    @Override
                    public String _case(None<Expression> x) {
                        return "";
                    }
                }) + x.identifier;
            }

            @Override
            public String _case(NestedExpression x) {
                return "( " + print(x.expression) + " )";
            }

            @Override
            public String _case(ClassReference x) {
                return print(x.type) + ".class";
            }

            @Override
            public String _case(TernaryExpression x) {
                return print(x.cond) + " ? " + print(x.trueExpression) + " : " + print (x.falseExpression);
            }

            @Override
            public String _case(BinaryExpression x) {
                return print(x.left) + " " + print(x.op) + " " +  print(x.right);
            }
        });
    }

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


Question:
Generate a new AES key used to encrypt the message.

@param keyType Key Type
@param keyLength Key Length in bit
@return new AES key
@throws NoSuchAlgorithmException

public static byte[] generateKey(String keyType, int keyLength) throws NoSuchAlgorithmException {
        KeyGenerator generator = KeyGenerator.getInstance(keyType);
        generator.init(keyLength);
        return generator.generateKey().getEncoded();
    }

private static int checkFormalTypeParameters(final String signature, int pos) {
        // FormalTypeParameters:
        // < FormalTypeParameter+ >

        pos = checkChar('<', signature, pos);
        pos = checkFormalTypeParameter(signature, pos);
        while (getChar(signature, pos) != '>') {
            pos = checkFormalTypeParameter(signature, pos);
        }
        return pos + 1;
    }

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


Question:
Returns true/false if the command is supported or not.

@method queryCommandSupported
@param {String} command Command that we check support for.
@return {Boolean} true/false if the command is supported or not.

function queryCommandSupported(command) {
        command = command.toLowerCase();

        if (commands.exec[command]) {
          return true;
        }

        // Browser commands
        try {
          return editor.getDoc().queryCommandSupported(command);
        } catch (ex) {
          // Fails sometimes see bug: 1896577
        }

        return false;
      }

synchronized String[] dev_poll_status(final String dev_name) throws DevFailed {
        Util.out4.println("In dev_poll_status command");

        // Find the device
        final DeviceImpl dev = Util.instance().get_device_by_name(dev_name);

        final Vector poll_list = dev.get_poll_obj_list();
        final int nb_poll_obj = poll_list.size();

        // Return an empty sequence if nothing is polled for this device
        if (nb_poll_obj == 0) {
            return new String[0];
        }

        // Compute how many cmds and/or attributes are polled
        int nb_cmd = 0;
        for (int i = 0; i < nb_poll_obj; i++) {
            final PollObj poll_obj = (PollObj) poll_list.elementAt(i);
            if (poll_obj.get_type() == Tango_POLL_CMD) {
                nb_cmd++;
            }
        }

        // Allocate memory for returned strings
        final String[] ret = new String[nb_poll_obj];

        // Populate returned strings
        int cmd_ind = 0;
        int attr_ind = nb_cmd;
        String returned_info;

        for (int i = 0; i < nb_poll_obj; i++) {
            final PollObj poll_obj = (PollObj) poll_list.elementAt(i);
            // First, the name
            final int type = poll_obj.get_type();
            if (type == Tango_POLL_CMD) {
                returned_info = "Polled command name = ";
            } else {
                returned_info = "Polled attribute name = ";
            }
            returned_info += poll_obj.get_name();

            // Add update period
            returned_info += "\nPolling period (mS) = ";
            final int tmp = poll_obj.get_upd();
            returned_info = returned_info + tmp;

            // Add ring buffer depth
            returned_info += "\nPolling ring buffer depth = ";
            final int depth = dev.get_poll_ring_depth();
            if (depth == 0) {
                returned_info += Tango_DefaultPollRingDepth;
            } else {
                returned_info += depth;
            }

            // Add a message if the data ring is empty
            if (poll_obj.is_ring_empty() == true) {
                returned_info += "\nNo data recorded yet";
            } else {
                // Add needed time to execute last command
                returned_info += "\nTime needed for the last ";
                if (type == Tango_POLL_CMD) {
                    returned_info += "command execution (mS) = ";
                } else {
                    returned_info += "attribute reading (mS) = ";
                }
                returned_info += poll_obj.get_needed_time_i();

                // Add not updated since... info
                returned_info += "\nData not updated since ";
                final double since = poll_obj.get_last_insert_date_i();

                final long ctm = System.currentTimeMillis();
                final int tv_sec = (int) (ctm / 1000);
                final int tv_usec = (int) (ctm - 1000 * tv_sec) * 1000;

                final double now_d = tv_sec + (double) tv_usec / 1000000;
                final double diff_t = now_d - since;
                if (diff_t < 1.0) {
                    final int nb_msec = (int) (diff_t * 1000);
                    returned_info = returned_info + nb_msec + " mS";
                } else if (diff_t < 60.0) {
                    final int nb_sec = (int) diff_t;
                    final int nb_msec = (int) ((diff_t - nb_sec) * 1000);
                    returned_info = returned_info + nb_sec + " S and ";
                    returned_info = returned_info + nb_msec + " mS";
                } else {
                    final int nb_min = (int) (diff_t / 60);
                    final int nb_sec = (int) (diff_t - 60 * nb_min);
                    final int nb_msec = (int) ((diff_t - (int) diff_t) * 1000);

                    returned_info = returned_info + nb_min + " MN";

                    if (nb_sec != 0) {
                        returned_info = returned_info + " ," + nb_sec + " S";
                    }

                    if (nb_msec != 0) {
                        returned_info = returned_info + " and " + nb_msec + " mS";
                    }
                }

                // Add delta_t between last record(s)
                try {
                    returned_info += "\nDelta between last records (in mS) = ";
                    final double[] delta = poll_obj.get_delta_t_i(4);
                    for (int j = 0; j < delta.length; j++) {
                        final int nb_msec = (int) (delta[j] * 1000);
                        returned_info = returned_info + nb_msec;
                        if (j != delta.length - 1) {
                            returned_info = returned_info + ", ";
                        }
                    }
                } catch (final DevFailed e) {
                }

                // Add last polling exception fields (if any)
                if (poll_obj.is_last_an_error_i() == true) {
                    if (type == Tango_POLL_CMD) {
                        returned_info += "\nLast command execution FAILED :";
                    } else {
                        returned_info += "\nLast attribute read FAILED :";
                    }
                    final DevFailed ex = poll_obj.get_last_except_i();
                    returned_info += "\n\tReason = " + ex.errors[0].reason;
                    returned_info += "\n\tDesc = " + ex.errors[0].desc;
                    returned_info += "\n\tOrigin = " + ex.errors[0].origin;
                }
            }

            // Init. string in sequence
            if (type == Tango_POLL_CMD) {
                ret[cmd_ind] = returned_info;
                cmd_ind++;
            } else {
                ret[attr_ind] = returned_info;
                attr_ind++;
            }
        }
        return ret;
    }

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


Question:
请求获取交易授权码

@param string $url
@param array $params_keys
@param bool $ssl

public static function request($api, $param_keys, $signType = false)
    {
        $params = array_filter(Datasheet::get($param_keys));

        if ($signType !== false) {
            $params['Hash'] = self::signature($signType);
        }

        $client = new Client();
        $option = ['form_params' => $params];

        if (Datasheet::get('SandBoxMode') === "true") {
            $url = self::SANDBOX_DOMAIN . $api;
        } else {
            $url = self::PRODUCT_DOMAIN . $api;
        }

        $response = $client->request('POST', $url, $option);

        if ($response->getStatusCode() != '200') {
            throw new \Exception('网络发生错误，请稍后再试。cURL返回码：' . $response->getReasonPhrase());
        }
        $json = $response->getBody()->getContents();

        return self::response(json_decode($json, true));
    }

protected function prepareCurl()
    {
        $this->curl = curl_init();
        $this->complete = Complete::factory(function() {
            if ($this->curl) {
                curl_close($this->curl);
            }
            $this->curl     = null;
            $this->complete = null;
        });

        foreach(self::$curlOptions as $option => $value) {
            curl_setopt($this->curl, $option, $value);
        }
        if ($this->method === HttpMethods::POST) {
            curl_setopt($this->curl, CURLOPT_POST, true);
        }
        if (!empty($this->auth)) {
            curl_setopt($this->curl, CURLOPT_USERPWD, sprintf(
                "%s:%s",
                $this->auth["user"],
                $this->auth["pass"]
            ));
        }
    }

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


Question: // AllocTree allocates the lefts and rights. Typical construction of the *Dependency doesn't allocate the trees as they're not necessary for a number of tasks.

func AllocTree() depConsOpt {
	fn := func(d *Dependency) {
		d.lefts = make([][]int, d.wordCount)
		d.rights = make([][]int, d.wordCount)
		for i := 0; i < d.wordCount; i++ {
			d.lefts[i] = make([]int, 0)
			d.rights[i] = make([]int, 0)
		}
	}
	return fn
}

def x_build_targets_target( self, node ):
        '''

        '''
        target_node = node
        name = self.get_child_data(target_node,tag='name',strip=True)
        path = self.get_child_data(target_node,tag='path',strip=True)
        jam_target = self.get_child_data(target_node,tag='jam-target',strip=True)
        #~ Map for jam targets to virtual targets.
        self.target[jam_target] = {
            'name' : name,
            'path' : path
            }
        #~ Create the ancestry.
        dep_node = self.get_child(self.get_child(target_node,tag='dependencies'),tag='dependency')
        while dep_node:
            child = self.get_data(dep_node,strip=True)
            child_jam_target = '<p%s>%s' % (path,child.split('//',1)[1])
            self.parent[child_jam_target] = jam_target
            dep_node = self.get_sibling(dep_node.nextSibling,tag='dependency')
        return None

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


Question:
Copy the given mapping but offset as indicated by the split source code.
@param {object} existingMapping An existing source-map mapping from a source-map consumer

function copyAndOffsetMapping(existingMapping) {
    var column     = getColumnAfter(existingMapping.generatedLine - 1, existingMapping.generatedColumn);
    var newMapping = {
      generated: {
        line  : existingMapping.generatedLine,
        column: column
      }
    };
    if (existingMapping.source) {
      newMapping.source   = existingMapping.source;
      newMapping.original = {
        line  : existingMapping.originalLine,
        column: existingMapping.originalColumn
      };
      if (existingMapping.name) {
        newMapping.name = existingMapping.name;
      }
    }
    generator.addMapping(newMapping);
  }

func updateNodeField(src interface{}, targetName string, target interface{}) interface{} {
	var isPtr bool
	srcVal := reflect.ValueOf(src)
	// verify condition
	if srcVal.Kind() == reflect.Ptr {
		isPtr = true
		srcVal = srcVal.Elem()
	}
	targetVal := reflect.ValueOf(target)
	if srcVal.Kind() != reflect.Struct {
		return src
	}
	srcFieldValue := srcVal.FieldByName(targetName)
	if !srcFieldValue.IsValid() || srcFieldValue.Kind() != targetVal.Kind() {
		return src
	}

	if srcFieldValue.CanSet() {
		if srcFieldValue.Kind() == reflect.Slice {
			items := reflect.MakeSlice(srcFieldValue.Type(), targetVal.Len(), targetVal.Len())
			for index := 0; index < items.Len(); index++ {
				tmp := targetVal.Index(index).Interface()
				items.Index(index).Set(reflect.ValueOf(tmp))
			}
			srcFieldValue.Set(items)
		} else {
			srcFieldValue.Set(targetVal)
		}
	}
	if isPtr {
		return srcVal.Addr().Interface()
	}
	return srcVal.Interface()
}

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


Question:
Undo the last change in the stack.

@return {Boolean} returns true if a change was un-done.

@see orion.editor.UndoStack#redo
@see orion.editor.UndoStack#canUndo

function() {
			this._commitUndo();
			var change, result = false;
			this._ignoreUndo = true;
			do {
				if (this.index <= 0) {
					break;
				}
				change = this.stack[--this.index];
			} while (!(result = change.undo(this.view, true)));
			this._ignoreUndo = false;
			return result;
		}

public function formAction(Request $request, $groupId)
    {
        $group = $this->get('open_orchestra_user.repository.group')->find($groupId);
        $this->denyAccessUnlessGranted(ContributionActionInterface::EDIT, $group);

        $form = $this->createForm('oo_group', $group, array(
            'action' => $this->generateUrl('open_orchestra_group_form', array(
                'groupId' => $groupId,
            )),
            'enable_delete_button' => $this->get('open_orchestra_backoffice.business_rules_manager')->isGranted(ContributionActionInterface::DELETE, $group),
            'delete_button' => $this->isGranted(ContributionActionInterface::DELETE, $group)
        ));

        $form->handleRequest($request);
        $message = $this->get('translator')->trans('open_orchestra_group.form.group.edit.success');
        if ($this->handleForm($form, $message)) {
            $this->dispatchEvent(GroupEvents::GROUP_UPDATE, new GroupEvent($group));
        }

        return $this->renderAdminForm($form);
    }

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


Question:
This function sends out a mail
about the intrusion including the intrusion details

@param array $results
@return boolean

private function idsmail($result) {

        vendor('phpids/IDS/Log/Email.php');
        vendor('phpids/IDS/Log/Composite.php');

        $compositeLog = new IDS_Log_Composite();
        $compositeLog->addLogger(
            IDS_Log_Email::getInstance(
                $this->init->config['IDS_Logging']['recipient'],
                $this->config['IDS_Logging']['subject'],
                NULL, //optional headers
                $this->init->config['IDS_Logging']['safemode'],
                $this->init->config['IDS_Logging']['allowed_rate'],
                $this->init->config['IDS_Basic']['tmp_path']
            )
        );

        if (!$result->isEmpty()) {
            $compositeLog->execute($result);
        }

        return true;
    }

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

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

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

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

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


Question:
Get the namespace path.
@return string

public function getPath() {
    $path = '';
    /** @var TokenNode $child */
    $child = $this->head;
    while ($child) {
      $type = $child->getType();
      if ($type === T_NAMESPACE || $type === T_NS_SEPARATOR || $type === T_STRING) {
        $path .= $child->getText();
      }
      $child = $child->next;
    }
    return $path;
  }

public function storagePath()
    {
        if ($this->storagePath)
            return $this->storagePath;
        return $this->storagePath ?: $this->rootPath() . DIRECTORY_SEPARATOR . 'storage';
    }

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


Question:
Install a repository.

@param string $name
@param string $type
@param string $url

@return void

public function installRepository(string $name, string $type, string $url)
    {
        if (array_key_exists('repositories', $this->definition)
            && array_key_exists($name, $this->definition['repositories'])
        ) {
            return;
        }

        $application = new Application();
        $command     = new ConfigCommand();

        $definition = clone $application->getDefinition();
        $definition->addArguments($command->getDefinition()->getArguments());
        $definition->addOptions($command->getDefinition()->getOptions());

        $input = new ArrayInput(
            [
                'command' => 'config',
                'setting-key' => 'repositories.' . $name,
                'setting-value' => [
                    $type,
                    $url
                ],
                '--working-dir' => $this->workingDir
            ],
            $definition
        );

        $application->setAutoExit(false);
        $application->run($input, $this->output);
    }

public function parseRoute($routeSpec)
    {
        $path           = isset($routeSpec['path']) ? $routeSpec['path'] : null;
        $methods        = isset($routeSpec['methods']) ? $routeSpec['methods'] : array();
        $controller     = isset($routeSpec['controller']) ? $routeSpec['controller'] : null;
        $calls          = isset($routeSpec['calls']) ? $routeSpec['calls'] : null;
        $requirements   = isset($routeSpec['requirements']) ? $routeSpec['requirements'] : array();
        $regex          = isset($routeSpec['path']) ? $routeSpec['path'] : null;

        $route = new Route($path, $methods, $controller, $calls, $requirements, $regex);

        return $route;
    }

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


Question:
Returns the contents of the 'elm-package.json' for the given directory.

 @param directory [Dir] The directory

 @return [Hash] The contents

def json(directory)
      path = File.join(directory, 'elm-package.json')
      JSON.parse(File.read(path))
    rescue JSON::ParserError
      warn "Invalid JSON in file: #{path.bold}"
    rescue Errno::ENOENT
      warn "Could not find file: #{path.bold}"
    end

func ReadSymlinkedDirectory(path string) (string, error) {
	var realPath string
	var err error
	if realPath, err = filepath.Abs(path); err != nil {
		return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err)
	}
	if realPath, err = filepath.EvalSymlinks(realPath); err != nil {
		return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err)
	}
	realPathInfo, err := os.Stat(realPath)
	if err != nil {
		return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err)
	}
	if !realPathInfo.Mode().IsDir() {
		return "", fmt.Errorf("canonical path points to a file '%s'", realPath)
	}
	return realPath, nil
}

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


Question:
If Keep-Alive is disabled, attaches "Connection: close" header to the response
and closes the connection after the response being sent.

private void sendAndCleanupConnection(ChannelHandlerContext ctx, FullHttpResponse response) {
        final FullHttpRequest request = this.request;
        final boolean keepAlive = HttpUtil.isKeepAlive(request);
        HttpUtil.setContentLength(response, response.content().readableBytes());
        if (!keepAlive) {
            // We're going to close the connection as soon as the response is sent,
            // so we should also make it clear for the client.
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        } else if (request.protocolVersion().equals(HTTP_1_0)) {
            response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }

        ChannelFuture flushPromise = ctx.writeAndFlush(response);

        if (!keepAlive) {
            // Close the connection as soon as the response is sent.
            flushPromise.addListener(ChannelFutureListener.CLOSE);
        }
    }

protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (!$this->apiHelper->restore($this->getHelper('question'), $input, $output)) {
            return;
        }

        $output->writeln(\sprintf('Checking for URL: <info>%s</info>', $this->getUrl()).PHP_EOL);

        /** @var QuestionHelper $asker */
        $asker = $this->getHelper('question');
        $user = $this->apiHelper->currentUser();

        $enabled = $this->getCallbackStatus($user);
        $question = new ConfirmationQuestion(
            sprintf(
                '%s [y/N]: ',
                $enabled
                    ? 'The callback is currently <info>ACTIVE</info>, would you like to disable?'
                    : 'The callback is currently <info>INACTIVE</info>, would you like to enable?'
            ),
            false
        );

        if (!$asker->ask($input, $output, $question)) {
            return;
        }

        try {
            if ($enabled) {
                $this->disableCallback($user);
            } else {
                $this->enableCallback($user);
            }

            $output->writeln('<info>New status successfully applied.</info>');
        } catch (BunqException $exception) {
            $output->writeln('<error>An error occured while applying new status: '.$exception->getMessage().'</error>');
        }
    }

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


Question:
Remove variants whos dependencies conflict with the given package
        request.

        Returns:
            (VariantSlice, [Reduction]) tuple, where slice may be None if all
            variants were reduced.

def reduce_by(self, package_request):

        if self.pr:
            reqstr = _short_req_str(package_request)
            self.pr.passive("reducing %s wrt %s...", self, reqstr)

        if self.solver.optimised:
            if package_request in self.been_reduced_by:
                return (self, [])

        if (package_request.range is None) or \
                (package_request.name not in self.fam_requires):
            return (self, [])

        with self.solver.timed(self.solver.reduction_time):
            return self._reduce_by(package_request)

def versions_available(self):

        if self.version:
            spec = "%s==%s" % (self.project_name, self.version)
        else:
            spec = self.project_name

        if self.all_versions and self.version in self.all_versions:
            print_pkg_versions(self.project_name, [self.version])
        elif not self.version and self.all_versions:
            print_pkg_versions(self.project_name, self.all_versions)
        else:
            if self.version:
                self.logger.error("No pacakge found for version %s" \
                        % self.version)
            else:
                self.logger.error("No pacakge found for %s" % self.project_name)
            return 1
        return 0

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


Question:
Check for abuse parameters in query
@param string $q - query

public function sqlQueryCheck($q)
    {
        if (\stripos($q, 'union') !== false) {
            dump('UNION usage is limited.');
        }

        if (\stripos($q, ' like \'%\'') !== false) {
            dump('LIKE \'%\' usage is limited.');
        }

        if (\strpos($q, '/*') !== false || \strpos($q, '--') !== false) {
            dump('Comments like \* or -- usage is limited. Query: ' . $q);
        }
    }

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

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

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


Question: // RunUtil runs the mapping refresher until the given stop channel is closed.

func (m *RegeneratingDiscoveryRESTMapper) RunUntil(stop <-chan struct{}) {
	go wait.Until(func() {
		if err := m.RegenerateMappings(); err != nil {
			klog.Errorf("error regenerating REST mappings from discovery: %v", err)
		}
	}, m.refreshInterval, stop)
}

def _main_loop(self):
        '''

        '''
        while self.active:
            self.expire()
            if self.roll and self.is_expired():
                self.start_time = self.start_time + self.window
                self._set_key()
            self.purge_old()
            time.sleep(self.cycle_time)
        self._clean_up()

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


Question: Builds a pixel heart model and scale it to the specified input width.

function Heart(desired_width) {

    var points = PixelWalker(STARTING_POINT, path);
    var pathModel = new makerjs.models.ConnectTheDots(true, points);
    if (typeof desired_width != 'undefined') {
        var scale = desired_width / HEART_WIDTH;
        makerjs.model.scale(pathModel, scale);
    }
    return pathModel;
}

def fit_text(text, length):
    """"""
    text_length = wcswidth(text)

    if text_length > length:
        return trunc(text, length)

    if text_length < length:
        return pad(text, length)

    return text

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


Question:
Maps a taxonomy field.

@param string $field_name
Field name.
@param string $vid
Taxonomy vid.

@return array
Returns media entities.

public function mapTaxonomyTermField($field_name, $vid) {
    $entities = $this->populateTaxonomyTermField($field_name, $vid);
    if (!empty($entities)) {
      return $entities;
    }
    return [];
  }

def attach(self, media: typing.Union[InputMedia, typing.Dict]):

        if isinstance(media, dict):
            if 'type' not in media:
                raise ValueError(f"Invalid media!")

            media_type = media['type']
            if media_type == 'photo':
                media = InputMediaPhoto(**media)
            elif media_type == 'video':
                media = InputMediaVideo(**media)
            # elif media_type == 'document':
            #     media = InputMediaDocument(**media)
            # elif media_type == 'audio':
            #     media = InputMediaAudio(**media)
            # elif media_type == 'animation':
            #     media = InputMediaAnimation(**media)
            else:
                raise TypeError(f"Invalid media type '{media_type}'!")

        elif not isinstance(media, InputMedia):
            raise TypeError(f"Media must be an instance of InputMedia or dict, not {type(media).__name__}")

        elif media.type in ['document', 'audio', 'animation']:
            raise ValueError(f"This type of media is not supported by media groups!")

        self.media.append(media)

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


Question: // gtk_tree_view_column_get_cell_renderers //deprecated since 2.18

func (v *TreeViewColumn) AddAttribute(cell ICellRenderer, attribute string, column int) {
	ptr := C.CString(attribute)
	defer cfree(ptr)
	C.gtk_tree_view_column_add_attribute(v.GTreeViewColumn, cell.ToCellRenderer(), gstring(ptr), gint(column))
}

def completerTree( self ):

        if not self._completerTree:
            self._completerTree = QTreeWidget(self)
            self._completerTree.setWindowFlags(Qt.Popup)
            self._completerTree.setAlternatingRowColors( True )
            self._completerTree.installEventFilter(self)
            self._completerTree.itemClicked.connect( self.acceptCompletion )
            self._completerTree.setRootIsDecorated(False)
            self._completerTree.header().hide()

        return self._completerTree

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


Question: Return widget context dictionary.

def get_context(self, name, value, attrs):
        """"""
        context = super().get_context(
            name, value, attrs)
        context['widget']['attrs']['dp_config'] = json_dumps(self.config)
        return context

func (c *xContext) Set(key string, val interface{}) {
	c.store.Set(key, val)
}

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


Question: /* Init `treeInit` is triggered when a tree is initalized. We can set up classes or bind event handlers here...

function(ctx){
		var tree = this, // same as ctx.tree,
			opts = ctx.options,
			extOpts = ctx.options.childcounter;
// Optionally check for dependencies with other extensions
		/* this._requireExtension("glyph", false, false); */
// Call the base implementation
		this._super(ctx);
// Add a class to the tree container
		this.$container.addClass("fancytree-ext-childcounter");
	}

def log_initial_states(self):

        # Raise hosts initial status broks
        for elt in self.hosts:
            elt.raise_initial_state()

        # And then services initial status broks
        for elt in self.services:
            elt.raise_initial_state()

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


Question: // SetSourceField sets the SourceField field's value.

func (s *DateOptions) SetSourceField(v string) *DateOptions {
	s.SourceField = &v
	return s
}

def match_source(self, src):

        srcs = []

        names = [src.name]
        for col in self.config['assoc_xmatch_columns']:
            if col in src.assoc and src.assoc[col]:
                names += [src.assoc[col]]

        for name in names:
            name = name.replace(' ', '').lower()
            if name not in self._src_dict:
                continue
            srcs += [s for s in self._src_dict[name] if s not in srcs]

        return srcs

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


Question:
Adds attributes that have been requested vis configuration properties.
Asserts attribute order where necessary.

private void prepareForEncoding() {
		// remove MESSAGE-INTEGRITY and FINGERPRINT attributes so that we can
		// make sure they are added at the end.
		StunAttribute msgIntAttr = removeAttribute(StunAttribute.MESSAGE_INTEGRITY);
		StunAttribute fingerprint = removeAttribute(StunAttribute.FINGERPRINT);

		// add a SOFTWARE attribute if the user said so, and unless they did it
		// themselves.
		String software = System.getProperty("TelScale Media Server");

		if (getAttribute(StunAttribute.SOFTWARE) == null && software != null && software.length() > 0) {
			addAttribute(StunAttributeFactory.createSoftwareAttribute(software.getBytes()));
		}

		// re-add MESSAGE-INTEGRITY if there was one.
		if (msgIntAttr != null) {
			addAttribute(msgIntAttr);
		}

		// add FINGERPRINT if there was one or if user told us to add it
		// everywhere.
		if (fingerprint == null) {
			fingerprint = StunAttributeFactory.createFingerprintAttribute();
		}

		if (fingerprint != null) {
			addAttribute(fingerprint);
		}
	}

def run(self, *args):

        params = self.parser.parse_args(args)

        config_file = os.path.expanduser('~/.sortinghat')

        if params.action == 'get':
            code = self.get(params.parameter, config_file)
        elif params.action == 'set':
            code = self.set(params.parameter, params.value, config_file)
        else:
            raise RuntimeError("Not get or set action given")

        return code

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


Question:
Redirect the user after determining they are locked out.

@param  \Illuminate\Http\Request $request
@return \Illuminate\Http\RedirectResponse

protected function sendLockoutResponse(Request $request)
    {
        $seconds = $this->limiter()->availableIn(
            $this->throttleKey($request)
        );

        return HCLog::info('AUTH-005', trans('auth.throttle', ['seconds' => $seconds]));
    }

private function parse($body)
    {
        $result = array();
        $data = json_decode($body);

        $response = is_array($data->response) ? new \stdClass : $data->response;
        if (null == $response) {
            $response = $data;
        }
        $response->errors = $data->errors;
        $response->test = isset($data->test) ? $data->test : $response->test;

        if ($data->successful == true) {
            if ((isset($response->authorized)
                && $response->authorized == true)
                || (isset($response->id)
                && $response->id !== null)
            ) {
                $response->authorization_id = isset($response->id)
                    ? $response->id
                    : $response->token;
            } else {
                $response->authorization_id = null;
            }

            $response->success = true;
        } else {
            $response->success = false;
            $response->authorization_id = null;
        }

        $response->message = isset($response->message) ? $response->message : $data->errors;

        return (array) $response;

    }

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


Question:
checkImageTitleTags.
Checks if images in content have title tags

@param none
@return boolean

private function checkImageTitleTags() {

        $html = $this->getPageContent();

        // for newly created page
        if ($html == '') {
            return false;
        }

        $dom = $this->createDOMDocumentFromHTML($html);

        $images = $dom->getElementsByTagName('img');

        $imagesWithTitleTags = 0;
        foreach($images as $image){
            if($image->hasAttribute('title') && $image->getAttribute('title') != ''){
                //echo $image->getAttribute('title') . '<br>';
                $imagesWithTitleTags++;
            }
        }

        if($imagesWithTitleTags == $images->length){
            return true;
        }

        return false;
    }

protected function getCaption($file_name)
    {
        if ($this->visitor instanceof Creator) {
            $toc = $this->visitor->getTableOfContents();
            $name = $toc[$file_name]->getName();
            return $name ?: $file_name;
        }

        return $file_name;
    }

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


Question:
Add relationship filter

@param string     $filter   Filter name
@param ElggEntity $target   Target entity
@param int        $priority Priority
@return self

public function addFilter($filter, ElggEntity $target = null, $priority = 500) {
		if (!$filter) {
			return $this;
		}

		while (isset($this->filters[$priority])) {
			$priority++;
		}

		$this->removeFilter($filter);

		if (!isset($target)) {
			$target = elgg_get_logged_in_user_entity();
		}

		$this->filters[$priority] = [
			'filter' => $filter,
			'target' => $target,
		];

		ksort($this->filters);

		return $this;
	}

final protected function process(\SelectQueryInterface $select, Query $query)
    {
        if ($query->hasSortField()) {
            $select->orderBy(
                $query->getSortField(),
                Query::SORT_DESC === $query->getSortOrder() ? 'desc' : 'asc'
            );
        }
        $select->orderBy(
            'u.uid',
            Query::SORT_DESC === $query->getSortOrder() ? 'desc' : 'asc'
        );

        if ($searchstring = $query->getSearchString()) {
            $select->condition(
                'u.name',
                '%'.db_like($searchstring).'%',
                'LIKE'
            );
        }

        $this->applyFilters($select, $query);

        return $select /*->extend(DrupalPager::class)->setQuery($query) */;
    }

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


Question:
Computes the histogram of intensity values for the image.

@param input (input) Image.
@param minValue (input) Minimum possible intensity value
@param histogram (output) Storage for histogram. Number of elements must be equal to max value.

public static void histogram( GrayS32 input , int minValue , int histogram[] ) {
		if( BoofConcurrency.USE_CONCURRENT ) {
			ImplImageStatistics_MT.histogram(input,minValue,histogram);
		} else {
			ImplImageStatistics.histogram(input,minValue,histogram);
		}
	}

protected function saveOptimizedResourceFiles()
  {
    $this->logInfo("Saving minimized files");

    foreach ($this->resourceFilesInfo as $file_info)
    {
      $file_info['full_path_name_with_hash']       = $this->getFullPathNameWithHash($file_info);
      $file_info['path_name_in_sources_with_hash'] = $this->getPathInResources($file_info['full_path_name_with_hash']);

      $bytes = file_put_contents($file_info['full_path_name_with_hash'], $file_info['content_opt']);
      if ($bytes===false) $this->logError("Unable to write to file '%s'", $file_info['full_path_name_with_hash']);

      if (isset($file_info['full_path_name']))
      {
        // If required preserve mtime.
        if ($this->preserveModificationTime)
        {
          $status = touch($file_info['full_path_name_with_hash'], $file_info['mtime']);
          if ($status===false)
          {
            $this->logError("Unable to set mtime of file '%s'", $file_info['full_path_name_with_hash']);
          }
        }
      }
    }
  }

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


Question:
Returns if the current lock state allows editing.

@return true if the resource is editable

public boolean isEditable() {

        return m_permissionInfo.hasWritePermission()
            && CmsStringUtil.isEmptyOrWhitespaceOnly(getNoEditReason())
            && !hasForeignFolderLock()
            && !hasBlockingLockedChildren()
            && (((getLock() == null) || (getLock().getLockOwner() == null)) || getLock().isOwnedByUser());
    }

def _modify(self, **patch):
        """"""

        requests_params, patch_uri, session, read_only = \
            self._prepare_put_or_patch(patch)
        self._check_for_boolean_pair_reduction(patch)
        read_only_mutations = []
        for attr in read_only:
            if attr in patch:
                read_only_mutations.append(attr)
        if read_only_mutations:
            msg = 'Attempted to mutate read-only attribute(s): %s' \
                % read_only_mutations
            raise AttemptedMutationOfReadOnly(msg)

        patch = self._prepare_request_json(patch)
        response = session.patch(patch_uri, json=patch, **requests_params)
        self._local_update(response.json())

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


Question:
Reformat Json input keeping element order

@since 1.0.6.2

need to be rewrite in 2.0

public static String compress(String input, JSONStyle style) {
		try {
			StringBuilder sb = new StringBuilder();
			new JSONParser(DEFAULT_PERMISSIVE_MODE).parse(input, new CompessorMapper(defaultReader, sb, style));
			return sb.toString();
		} catch (Exception e) {
			return input;
		}
	}

def version_history(soup, html_flag=True):
    ""
    convert = lambda xml_string: xml_to_html(html_flag, xml_string)
    version_history = []
    related_object_tags = raw_parser.related_object(raw_parser.article_meta(soup))
    for tag in related_object_tags:
        article_version = OrderedDict()
        date_tag = first(raw_parser.date(tag))
        if date_tag:
            copy_attribute(date_tag.attrs, 'date-type', article_version, 'version')
            (day, month, year) = ymd(date_tag)
            article_version['day'] = day
            article_version['month'] = month
            article_version['year'] = year
            article_version['date'] = date_struct_nn(year, month, day)
        copy_attribute(tag.attrs, 'xlink:href', article_version, 'xlink_href')
        set_if_value(article_version, "comment",
                     convert(node_contents_str(first(raw_parser.comment(tag)))))
        version_history.append(article_version)
    return version_history

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


Question: best invoked on the compaction mananger.

public void dropCf(UUID cfId)
    {
        assert columnFamilyStores.containsKey(cfId);
        ColumnFamilyStore cfs = columnFamilyStores.remove(cfId);
        if (cfs == null)
            return;

        // wait for any outstanding reads/writes that might affect the CFS
        cfs.keyspace.writeOrder.awaitNewBarrier();
        cfs.readOrdering.awaitNewBarrier();

        unloadCf(cfs);
    }

public static Compressor getCompressor(byte code) {
        Compressor compressor = TYPE_COMPRESSOR_MAP.get(code);
        if (compressor == null) {
            throw new SofaRpcRuntimeException("Compressor Not Found :\"" + code + "\"!");
        }
        return compressor;
    }

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


Question:
Handle an error according to the error settings.

        Either raise the error or store it.
        The error will have occured at ``cur_index``

def _handle_error(self, text, ErrorClass, infile, cur_index):

        line = infile[cur_index]
        cur_index += 1
        message = text % cur_index
        error = ErrorClass(message, cur_index, line)
        if self.raise_errors:
            # raise the error - parsing stops here
            raise error
        # store the error
        # reraise when parsing has finished
        self._errors.append(error)

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

        invalid_tree_records = dict()
        invalid_tq_records = dict()

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

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

                tree.update_node(job_record)

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

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

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

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


Question: // getRequestingClientFromRequest validates if a see api call is valid for an organization

func getRequestingClientFromRequest(r *http.Request, w http.ResponseWriter, organizationGlobalID string, allowOnWebsite bool) (string, bool) {
	requestingClient, validClient := context.Get(r, "client_id").(string)
	if !validClient {
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return requestingClient, false
	}
	if requestingClient == "itsyouonline" {
		if allowOnWebsite {
			requestingClient = organizationGlobalID
		} else {
			// This should never happen as the oauth 2  middleware should give a 403
			writeErrorResponse(w, http.StatusBadRequest, "This api call is not available when logged in via the website")
			return requestingClient, false
		}
	} else if requestingClient != organizationGlobalID {
		writeErrorResponse(w, http.StatusForbidden, "unauthorized_organization")
		return requestingClient, false
	}
	return requestingClient, true
}

@Help(help = "Creates a new service")
  public String create(String serviceName, List<String> roles) throws SDKException {
    HashMap<String, Object> requestBody = new HashMap<>();
    requestBody.put("name", serviceName);
    requestBody.put("roles", roles);

    return new String(
        (byte[])
            requestPost(
                "create",
                requestBody,
                MediaType.APPLICATION_OCTET_STREAM_VALUE,
                MediaType.APPLICATION_JSON_VALUE));
  }

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


Question: This internal helper method creates the actual contents of the widget by combining the decorators and the main widget.<p>

protected void initContent() {

        if (m_decoratedPanel != null) {
            m_decoratedPanel.removeFromParent();
        }
        m_decoratedPanel = new CmsSimpleDecoratedPanel(m_decorationWidth, m_mainWidget, m_decorationWidgets);
        m_panel.insert(m_decoratedPanel, 0);
        setSmallView(m_smallView);
    }

public function setData($modelData)
    {
        if ($this->config->getInheritData()) {
            throw new RuntimeException('You cannot change the data of a block inheriting its parent data.');
        }

        if ($this->lockSetData) {
            throw new RuntimeException('A cycle was detected. Listeners to the PRE_SET_DATA event must not call setData(). You should call setData() on the BlockEvent object instead.');
        }

        if (null !== $this->getForm() && null === $this->getForm()->getData()) {
            $this->getForm()->setData($modelData);
        }

        $this->lockSetData = true;
        $dispatcher = $this->config->getEventDispatcher();

        // Hook to change content of the data
        if ($dispatcher->hasListeners(BlockEvents::PRE_SET_DATA)) {
            $event = new BlockEvent($this, $modelData);
            $dispatcher->dispatch(BlockEvents::PRE_SET_DATA, $event);
            $modelData = $event->getData();
        }

        if (BlockUtil::isEmpty($modelData)) {
            $emptyData = $this->config->getEmptyData();

            if ($emptyData instanceof \Closure) {
                /* @var \Closure $emptyData */
                $emptyData = $emptyData($this, $modelData, $this->getOptions());
            }

            $modelData = $emptyData;
        }

        // Treat data as strings unless a value transformer exists
        if (!$this->config->getViewTransformers() && !$this->config->getModelTransformers() && is_scalar($modelData) && !\is_bool($modelData)) {
            $modelData = (string) $modelData;
        }

        // Synchronize representations - must not change the content!
        $normData = $this->modelToNorm($modelData);
        $viewData = $this->normToView($normData);

        // Validate if view data matches data class (unless empty)
        if (!BlockUtil::isEmpty($viewData)) {
            $dataClass = $this->getDataClass();

            $actualType = \is_object($viewData) ? 'an instance of class '.\get_class($viewData) : ' a(n) '.\gettype($viewData);

            if (null === $dataClass && \is_object($viewData) && !$viewData instanceof \ArrayAccess) {
                $expectedType = 'scalar, array or an instance of \ArrayAccess';

                throw new LogicException(
                        'The block\'s view data is expected to be of type '.$expectedType.', '.
                        'but is '.$actualType.'. You '.
                        'can avoid this error by setting the "data_class" option to '.
                        '"'.\get_class($viewData).'" or by adding a view transformer '.
                        'that transforms '.$actualType.' to '.$expectedType.'.'
                );
            }

            if (null !== $dataClass && !$viewData instanceof $dataClass) {
                throw new LogicException(
                        'The block\'s view data is expected to be an instance of class '.
                        $dataClass.', but is '.$actualType.'. You can avoid this error '.
                        'by setting the "data_class" option to null or by adding a view '.
                        'transformer that transforms '.$actualType.' to an instance of '.
                        $dataClass.'.'
                );
            }
        } else {
            $viewData = (string) $this->config->getEmptyMessage();
        }

        $this->modelData = $modelData;
        $this->normData = $normData;
        $this->viewData = $viewData;
        $this->defaultDataSet = true;
        $this->lockSetData = false;

        if (\count($this->children) > 0) {
            $childrenIterator = new InheritDataAwareIterator($this->children);
            $childrenIterator = new \RecursiveIteratorIterator($childrenIterator);
            $this->config->getDataMapper()->mapDataToViews($viewData, $childrenIterator);
        }

        if ($dispatcher->hasListeners(BlockEvents::POST_SET_DATA)) {
            $event = new BlockEvent($this, $modelData);
            $dispatcher->dispatch(BlockEvents::POST_SET_DATA, $event);
        }

        return $this;
    }

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


Question:
Helper method that handles building the assertion failure exceptions.
They are returned from this method so that the stack trace still shows
the assertions method.

static protected function createException($value, $message, $code, $propertyPath, array $constraints = array())
        {
            $constraintString = 'Constraints: ';

            if (count($constraints)) {
                foreach ($constraints as $key => $v) {
                    $constraintString .= "$key => $v, ";
                }

                $constraintString = substr($$constraintString, 0, -2);
            }

            return new Exception("$message => $code => $value => $propertyPath => $constraintString");
        }

def addExpectedFailure(self, test, err):

        super().addExpectedFailure(test, err)
        self.test_info(test)
        self._call_test_results('addExpectedFailure', test, err)

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


Question:
Write a Shuffling object in the current binary stream.

@param \qtism\data\state\Shuffling $shufflingState
@throws QtiBinaryStreamAccessException

public function writeShufflingState(Shuffling $shufflingState)
    {
        try {
            $this->writeIdentifier($shufflingState->getResponseIdentifier());
            $shufflingGroups = $shufflingState->getShufflingGroups();
            $this->writeTinyInt(count($shufflingGroups));

            foreach ($shufflingGroups as $shufflingGroup) {
                $this->writeShufflingGroup($shufflingGroup);
            }
        } catch (BinaryStreamAccessException $e) {
            $msg = "An error occured while writing a shufflingState.";
            throw new QtiBinaryStreamAccessException($msg, $this, QtiBinaryStreamAccessException::SHUFFLING_STATE, $e);
        }
    }

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

        invalid_tree_records = dict()
        invalid_tq_records = dict()

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

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

                tree.update_node(job_record)

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

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

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

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


Question:
// Cap places a hard limit on the number of items, returning all transactions
// exceeding that limit.

func (l *txList) Cap(threshold int) types.Transactions {
	return l.txs.Cap(threshold)
}

private function encapsList($node, $terminator, $encaps_whitespace_allowed = FALSE) {
    if (!$encaps_whitespace_allowed) {
      if ($this->tryMatch(T_ENCAPSED_AND_WHITESPACE, $node)) {
        $node->addChild($this->encapsVar());
      }
    }
    while ($this->currentType !== NULL && $this->currentType !== $terminator) {
      $this->tryMatch(T_ENCAPSED_AND_WHITESPACE, $node) ||
        $node->addChild($this->encapsVar());
    }
  }

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


Question: Uncompress a tar file.

def untar_file(tarname, target_dir='.'):
    ''''''

    o = tarfile.open(tarname, 'r:gz')
    members = o.getmembers()
    for member in members:
        o.extract(member, target_dir)
    o.close()

def CopyFileInZip(from_zip, from_name, to_zip, to_name=None, signer=None):
  """"""
  data = from_zip.read(from_name)
  if to_name is None:
    to_name = from_name
  if signer:
    logging.debug("Signing %s", from_name)
    data = signer.SignBuffer(data)
  to_zip.writestr(to_name, data)

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


Question:
End request
@return void

public function endRequest($req, $appStatus, $protoStatus)
    {
        if ($protoStatus === -1) {
            $this->close();
        } else {
            if ($req->attrs->chunked) {
                $this->write("0\r\n\r\n");
            }

            if (isset($req->keepalive) && $req->keepalive && $this->pool->config->keepalive->value) {
                $this->keepaliveTimer = setTimeout(function ($timer) {
                    $this->finish();
                }, $this->pool->config->keepalive->value);
            } else {
                $this->finish();
            }
        }
        $this->freeRequest($req);
    }

func newOpClientRequest(reqType opClientRequestType, args interface{}) opClientRequest {
	return opClientRequest{
		op:       reqType,
		args:     args,
		response: make(chan interface{}),
	}
}

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


Question:
// Close cleans up all resources.
// This method must not be called concurrently with other lookup methods.

func (sb *SafeBrowser) Close() error {
	if atomic.LoadUint32(&sb.closed) == 0 {
		atomic.StoreUint32(&sb.closed, 1)
		close(sb.done)
	}
	return nil
}

static boolean isEndToEnd(String fieldName) {
    return !"Connection".equalsIgnoreCase(fieldName)
        && !"Keep-Alive".equalsIgnoreCase(fieldName)
        && !"Proxy-Authenticate".equalsIgnoreCase(fieldName)
        && !"Proxy-Authorization".equalsIgnoreCase(fieldName)
        && !"TE".equalsIgnoreCase(fieldName)
        && !"Trailers".equalsIgnoreCase(fieldName)
        && !"Transfer-Encoding".equalsIgnoreCase(fieldName)
        && !"Upgrade".equalsIgnoreCase(fieldName);
  }

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


Question:
Remove the highlights that are associated with the given points

@param points The points

private void removeHighlights(Collection<? extends Point> points)
    {
        Set<Object> highlightsToRemove = new LinkedHashSet<Object>();
        for (Point point : points)
        {
            Object oldHighlight = highlights.remove(point);
            if (oldHighlight != null)
            {
                highlightsToRemove.add(oldHighlight);
            }
        }
        JTextComponents.removeHighlights(textComponent, highlightsToRemove);
    }

public function disThumbRmove()
    {
        $properties = $this->getProperties();
        $properties['thumbRmove'] = self::BOOLEAN_FALSE;
        $this->setProperties($properties);
        return $this;
    }

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


Question:
phpinfo()の結果を取得する

@return  string

public function getInfo(){
        ob_start();
        phpinfo();

        $dom    = new \DOMDocument();
        $new    = new \DOMDocument();
        @$dom->loadHTML(ob_get_clean());

        $list   = (new \DOMXPath($dom))->query("//div[@class='center']/*");

        for($i = 0; $i < $list->length; $i++){
            $new->appendChild($new->importNode($list->item($i), true));
        }

        return $new->saveHTML();
    }

protected function debug_query($sql, $params = null) {
        echo '
 (', $this->get_dbtype(), '): ',  htmlentities($sql, ENT_QUOTES, 'UTF-8');
        if($params) {
            echo ' (parameters ';
            print_r($params);
            echo ')';
        }
        echo '
';
    }

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


Question:
Get the additional values to inject while exporting.

@param renderer_base $output The renderer.
@return array Keys are the property names, values are their values.

protected function get_other_values(renderer_base $output) {
        $pagecount = ceil($this->recordcount / $this->pagesize);

        $pages = [];
        if ($pagecount > 1) {
            for ($pageno = 1; $pageno <= $pagecount; $pageno++) {
                $pages[] = [
                    'page' => $pageno,
                    'url' => call_user_func_array($this->pageurlcallback, [$pageno, $this->pagesize]),
                    'active' => $pageno === $this->pagenumber,
                    'content' => null,
                ];
            }
        }

        return [
            'itemsperpage' => $this->pagesize,
            'buttons' => [
                'first' => false,
                'previous' => false,
                'next' => false,
                'last' => false,
            ],
            'pages' => $pages,
        ];
    }

public function load($file, $type = null)
    {
        $path = $this->locator->locate($file);

        $xml = $this->parseFile($path);
        $xml->registerXPathNamespace('config', 'http://thelia.net/schema/dic/config');

        $this->removeScope($xml);

        $this->container->addResource(new FileResource($path));

        $this->parseLoops($xml);

        $this->parseFilters($xml);

        $this->parseTemplateDirectives($xml);

        $this->parseParameters($xml);

        $this->parseCommands($xml);

        $this->parseForms($xml);

        $this->parseDefinitions($xml, $path);

        $this->parseHooks($xml, $path, $type);

        $this->propelOnlyRun(
            [$this, "parseExportCategories"],
            $xml
        );

        $this->propelOnlyRun(
            [$this, "parseExports"],
            $xml
        );

        $this->propelOnlyRun(
            [$this, "parseImportCategories"],
            $xml
        );

        $this->propelOnlyRun(
            [$this, "parseImports"],
            $xml
        );
    }

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


Question: Return the cross-origin-resource-sharing headers.

def _cors_headers(self, environ):
        """"""
        if isinstance(self.cors_allowed_origins, six.string_types):
            if self.cors_allowed_origins == '*':
                allowed_origins = None
            else:
                allowed_origins = [self.cors_allowed_origins]
        else:
            allowed_origins = self.cors_allowed_origins
        if allowed_origins is not None and \
                environ.get('HTTP_ORIGIN', '') not in allowed_origins:
            return []
        if 'HTTP_ORIGIN' in environ:
            headers = [('Access-Control-Allow-Origin', environ['HTTP_ORIGIN'])]
        else:
            headers = [('Access-Control-Allow-Origin', '*')]
        if environ['REQUEST_METHOD'] == 'OPTIONS':
            headers += [('Access-Control-Allow-Methods', 'OPTIONS, GET, POST')]
        if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in environ:
            headers += [('Access-Control-Allow-Headers',
                         environ['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])]
        if self.cors_credentials:
            headers += [('Access-Control-Allow-Credentials', 'true')]
        return headers

func (self *simplePBundle) SetReturnHeader(k string, v string) {
	self.out[k] = v
}

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


Question:
Parse named parameter using {@link StringNumberParser#parseTime(String)} and return time in
milliseconds (Long value).

@param name
parameter name
@return Long value
@throws RepositoryConfigurationException

public Long getParameterTime(String name) throws RepositoryConfigurationException
   {
      try
      {
         return StringNumberParser.parseTime(getParameterValue(name));
      }
      catch (NumberFormatException e)
      {
         throw new RepositoryConfigurationException(name + ": unparseable time (as Long). " + e, e);
      }
   }

public void marshall(StartQueryRequest startQueryRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(startQueryRequest.getLogGroupName(), LOGGROUPNAME_BINDING);
            protocolMarshaller.marshall(startQueryRequest.getStartTime(), STARTTIME_BINDING);
            protocolMarshaller.marshall(startQueryRequest.getEndTime(), ENDTIME_BINDING);
            protocolMarshaller.marshall(startQueryRequest.getQueryString(), QUERYSTRING_BINDING);
            protocolMarshaller.marshall(startQueryRequest.getLimit(), LIMIT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
/*
(non-Javadoc)
@see net.timewalker.ffmq4.common.message.selector.expression.SelectorNode#evaluate(javax.jms.Message)

@Override
	public Object evaluate(Message message) throws JMSException
    {
        String leftValue = leftOperand.evaluateString(message);
        String[] rightValue = (String[])rightOperand.evaluate(message);
        if (leftValue == null)
        	return null; // [JMS Spec]

        // Look for a match
        for (int n = 0 ; n < rightValue.length ; n++)
        	if (rightValue[n] != null && leftValue.equals(rightValue[n]))
        		return Boolean.TRUE;

        return Boolean.FALSE;
    }

JCExpression cast(JCExpression tree, Type target) {
        int oldpos = make.pos;
        make.at(tree.pos);
        if (!types.isSameType(tree.type, target)) {
            if (!resolve.isAccessible(env, target.tsym))
                resolve.logAccessErrorInternal(env, tree, target);
            tree = make.TypeCast(make.Type(target), tree).setType(target);
        }
        make.pos = oldpos;
        return tree;
    }

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


Question:
Validates the config of vcs repositories.

@param int|string  $index The index
@param array|mixed $repo  The config repo

@throws \UnexpectedValueException

protected function validateVcsRepositories($index, $repo)
    {
        if ('package' === $repo['type']) {
            return;
        }

        if (false === strpos($repo['type'], '-')) {
            throw new \UnexpectedValueException('Repository '.$index.' ('.json_encode($repo).') must have a type defined in this way: "%asset-type%-%type%"');
        }
        if (!isset($repo['url'])) {
            throw new \UnexpectedValueException('Repository '.$index.' ('.json_encode($repo).') must have a url defined');
        }
    }

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

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


Question:
// ServeNext implements the Middleware interface for Logger.
// It wraps the corresponding http.ResponseWriter and saves statistics about the status code returned, the number of bytes written and the time that requests took.

func (l *Logger) ServeNext(next http.Handler) http.Handler {

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		res := wrapResponseWriter(w)
		start := time.Now()

		next.ServeHTTP(res, r)

		l.Printf("%s %s | %s | %dB in %v from %s", magenta(r.Method), hiBlue(r.URL.Path), statusColor(res.Status()), res.BytesWritten(), timeColor(time.Since(start)), r.RemoteAddr)
	})
}

public function addHandler(CommandHandlerInterface $handler)
    {
        $this->__queue->enqueue($handler, $handler->getPriority());
        return $this;
    }

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


Question: Use this API to fetch the statistics of all protocoludp_stats resources that are configured on netscaler.

public static protocoludp_stats get(nitro_service service) throws Exception{
		protocoludp_stats obj = new protocoludp_stats();
		protocoludp_stats[] response = (protocoludp_stats[])obj.stat_resources(service);
		return response[0];
	}

public function get($code, $offset = 0, $limit = self::MAX_GET_USERS): array
    {
        $options = ['json' => [
            'code' => $code,
            'offset' => $offset,
            'size' => $limit
        ]];

        /** @var JsonStream $stream */
        $stream = $this->client
            ->get(UserApi::generateUrl('organization/users.json'), $options)
            ->getBody();

        return $stream->jsonSerialize()['userTitles'];
    }

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


Question:
// why?
// on the future we may change how these encoders/decoders
// and we may need different method for store and other for entry.

func init() {
	gob.Register(Store{})
	gob.Register(Entry{})
	gob.Register(time.Time{})
}

async def _digital_message(self, data):

        port = data[0]
        port_data = (data[PrivateConstants.MSB] << 7) + \
                    data[PrivateConstants.LSB]
        pin = port * 8
        for pin in range(pin, min(pin + 8, len(self.digital_pins))):
            # get pin value
            value = port_data & 0x01

            # set the current value in the pin structure
            self.digital_pins[pin].current_value = value

            # append pin number, pin value, and pin type to return value and return as a list
            message = [pin, value, Constants.INPUT]

            if self.digital_pins[pin].cb:
                if self.digital_pins[pin].cb_type:
                    await self.digital_pins[pin].cb(message)
                else:
                    # self.digital_pins[pin].cb(data)
                    loop = self.loop
                    loop.call_soon(self.digital_pins[pin].cb, message)

                # is there a latch entry for this pin?
                key = 'D' + str(pin)
                if key in self.latch_map:
                    await self._check_latch_data(key, port_data & 0x01)
            port_data >>= 1

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


Question:
Resets the paginator's instance

@return \Krystal\Paginate\Paginator

public function reset()
    {
        $this->itemsPerPage = null;
        $this->currentPage = null;
        $this->totalAmount = null;
        $this->url = null;

        return $this;
    }

def search_cat(self, catid, keyword, p_index=1):
        '''

        '''
        catid = 'sid' + catid
        logger.info('-' * 20)
        logger.info('search cat')
        logger.info('catid: {0}'.format(catid))
        logger.info('keyword: {0}'.format(keyword))

        # catid = ''
        if p_index == '' or p_index == '-1':
            current_page_number = 1
        else:
            current_page_number = int(p_index)
        res_all = self.ysearch.get_all_num(keyword, catid=catid)

        results = self.ysearch.search_pager(
            keyword,
            catid=catid,
            page_index=current_page_number,
            doc_per_page=CMS_CFG['list_num']
        )
        page_num = int(res_all / CMS_CFG['list_num'])

        kwd = {'title': '查找结果',
               'pager': '',
               'count': res_all,
               'current_page': current_page_number,
               'catid': catid,
               'keyword': keyword}

        self.render('misc/search/search_list.html',
                    kwd=kwd,
                    srecs=results,
                    pager=gen_pager_bootstrap_url(
                        '/search/{0}/{1}'.format(catid, keyword),
                        page_num,
                        current_page_number
                    ),
                    userinfo=self.userinfo,
                    cfg=CMS_CFG)

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


Question:
Rollbacks changes in a transaction.
@param string $savepoint

public function rollback($savepoint = null){
		if(!$this->resource->rollBack()){
			$error = $this->resource->errorInfo();
			throw new DriverException("SQLSTATE[$error[0]]: $error[2]", $error[1]);
		}
	}

func (mr *MockDatabaseMockRecorder) RunRawTransaction(arg0 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RunRawTransaction", reflect.TypeOf((*MockDatabase)(nil).RunRawTransaction), arg0)
}

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


Question: True iff two side lengths are equal, boolean.

def isIsosceles(self):
        '''

        '''
        return (self.a == self.b) or (self.a == self.c) or (self.b == self.c)

def get_self_attention_bias(x):

  x_shape = common_layers.shape_list(x)
  self_attention_bias = common_attention.attention_bias_lower_triangle(
      x_shape[1])
  return self_attention_bias

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


Question:
Execute command.

@param InputInterface $input
@param OutputInterface $output

protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->entityManager;
        $force = $input->getOption('force');
        $fixDepth = $input->getOption('fix-depth');

        $repo = $this->accountRepository;
        $verify = $repo->verify();

        $success = false;

        // fix nested tree
        if (true !== $verify) {
            $output->writeln(sprintf('<comment>%s errors were found.</comment>', count($verify)));

            if ($force) {
                $repo->recover();
                $em->flush();
                $success = true;
            }
        } else {
            $output->writeln('<info>Your tree is fine. No errors found.<info>');
        }

        // fix depths if -depth is defined
        if ($fixDepth) {
            // fix nodes without parents
            $numberParentLess = $this->findNodesWithoutParents();
            if ($numberParentLess > 0) {
                $output->writeln(
                    sprintf('<comment>%s nodes without parent were found.</comment>', $numberParentLess)
                );
                if ($force) {
                    $this->fixNodesWithoutParents();
                    $success = true;
                    $em->flush();
                }
            } else {
                $output->writeln('<info>No wrong depth gaps detected<info>');
            }

            // fix depth gaps
            $numberWrongDepth = $this->findInitialWrongDepthGap();
            if ($numberWrongDepth > 0) {
                $output->writeln(sprintf('<comment>%s wrong depths were found.</comment>', $numberWrongDepth));
                if ($force) {
                    // update depths
                    $affected = 1;
                    while ($affected > 0) {
                        $affected = $this->fixWrongDepthGap();
                    }
                    $success = true;
                    $em->flush();
                }
            } else {
                $output->writeln('<info>No nodes without parents detected<info>');
            }
        }

        if (!$force) {
            $output->writeln(sprintf('Call this command with <info>--force</info> option to perform recovery.'));
        }

        if (true === $success) {
            $output->writeln('<info>Recovery complete<info>');
        }
    }

public static void main( String [] args )
    {
        if ( args.length > 0 ) {
            String filename = args[0];

            String [] bshArgs;
            if ( args.length > 1 ) {
                bshArgs = new String [ args.length -1 ];
                System.arraycopy( args, 1, bshArgs, 0, args.length-1 );
            } else
                bshArgs = new String [0];

            try {
                Interpreter interpreter = new Interpreter();
                interpreter.setu( "bsh.args", bshArgs );
                Object result =
                    interpreter.source( filename, interpreter.globalNameSpace );
                if ( result instanceof Class )
                    try {
                        invokeMain( (Class<?>)result, bshArgs );
                    } catch ( Exception e )
                    {
                        Object o = e;
                        if ( e instanceof InvocationTargetException )
                            o = e.getCause();
                        System.err.println(
                            "Class: "+result+" main method threw exception:"+o);
                    }
            } catch ( FileNotFoundException e ) {
                System.err.println("File not found: "+e);
            } catch ( TargetError e ) {
                System.err.println("Script threw exception: "+e);
                if ( e.inNativeCode() )
                    e.printStackTrace( DEBUG.get(), System.err );
            } catch ( EvalError e ) {
                System.err.println("Evaluation Error: "+e);
            } catch ( IOException e ) {
                System.err.println("I/O Error: "+e);
            }
        } else {
            @SuppressWarnings("resource")
            Interpreter interpreter =
            new Interpreter(new CommandLineReader(
                new FileReader(System.in)),
                System.out, System.err, true );
            interpreter.run();
        }
    }

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


Question: // GetOrCreateSecret implements fi.SecretStore::GetOrCreateSecret

func (c *ClientsetSecretStore) GetOrCreateSecret(name string, secret *fi.Secret) (*fi.Secret, bool, error) {
	for i := 0; i < 2; i++ {
		s, err := c.FindSecret(name)
		if err != nil {
			return nil, false, err
		}

		if s != nil {
			return s, false, nil
		}

		_, err = c.createSecret(secret, name, false)
		if err != nil {
			if errors.IsAlreadyExists(err) && i == 0 {
				glog.Infof("Got already-exists error when writing secret; likely due to concurrent creation.  Will retry")
				continue
			} else {
				return nil, false, err
			}
		}

		if err == nil {
			break
		}
	}

	// Make double-sure it round-trips
	s, err := c.loadSecret(name)
	if err != nil {
		glog.Fatalf("unable to load secret immediately after creation %v: %v", name, err)
		return nil, false, err
	}
	return s, true, nil
}

def create(self, sid):

        data = values.of({'Sid': sid, })

        payload = self._version.create(
            'POST',
            self._uri,
            data=data,
        )

        return ShortCodeInstance(self._version, payload, service_sid=self._solution['service_sid'], )

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


Question:
Get a single submission.

        Get a single submission, based on user id.

def get_single_submission_courses(self, user_id, course_id, assignment_id, include=None):

        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # REQUIRED - PATH - assignment_id
        """ID"""
        path["assignment_id"] = assignment_id

        # REQUIRED - PATH - user_id
        """ID"""
        path["user_id"] = user_id

        # OPTIONAL - include
        """Associations to include with the group."""
        if include is not None:
            self._validate_enum(include, ["submission_history", "submission_comments", "rubric_assessment", "visibility", "course", "user"])
            params["include"] = include

        self.logger.debug("GET /api/v1/courses/{course_id}/assignments/{assignment_id}/submissions/{user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/assignments/{assignment_id}/submissions/{user_id}".format(**path), data=data, params=params, no_data=True)

public function getPost( $slug ) {

		// Supported post names (ie. slugs)
		$supported = array_keys( $this->supported );
		if ( ! in_array( $slug, $supported, true ) ) {
			return false;
		}

		$args = [
			'name' => $slug,
			'post_type' => 'custom-style',
			'posts_per_page' => 1,
			'post_status' => 'publish',
			'orderby' => 'modified',
			'no_found_rows' => true,
			'cache_results' => true,
		];

		$q = new \WP_Query();
		$results = $q->query( $args );

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

		return $results[0];
	}

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


Question: Run querty to Daxko to get the token.

protected function getDaxkoToken() {
    $time_start = microtime(true);
    $client = new Client(['base_uri' => $this->daxkoConfig->get('base_uri')]);
    $response = $client->request('POST', 'partners/oauth2/token',
      [
        'form_params' => [
          'client_id' => $this->daxkoConfig->get('user'),
          'client_secret' => $this->daxkoConfig->get('pass'),
          'grant_type' => 'client_credentials',
          'scope' => 'client:' . $this->daxkoConfig->get('client_id'),
        ],
        'headers' => [
          'Authorization' => "Bearer " . $this->daxkoConfig->get('referesh_token')
        ],
      ]);
    $time_end = microtime(true);
    $time = $time_end - $time_start;
    \Drupal::logger('openy_daxko2')->info('Daxko call. Time %times. URL %url', [
      '%time' => number_format($time, 2),
      '%url' => 'partners/oauth2/token',
    ]);

    return json_decode((string) $response->getBody())->access_token;
  }

def qhalfx(self):

        if self.__qhalfx is None:
            self.log("qhalfx")
            self.__qhalfx = self.qhalf * self.jco
            self.log("qhalfx")
        return self.__qhalfx

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


Question: This method returns userId argument of the target method invocation.

private Long getUserIdArg(Object[] arguments) {
        if (arguments.length <= USER_ID_INDEX) {
            log.error("Illegal number of args: " + arguments.length);
        }
        return (Long) arguments[USER_ID_INDEX];
    }

func (ip *Interpreter) login(args []string) {
	uid, err := ip.Backend.LoginUser(args[0], args[1])
	if err == nil {
		ip.Server.Stats.Login++
	} else {
		ip.Server.Stats.FailedLogin++
	}
	ip.intResponder(uid, err)
}

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


Question: // Eq compares that left value is equal to right value.

func Eq(left, right interface{}) Condition {
	return Condition{
		Type:  ConditionEq,
		Left:  NewOperand(left),
		Right: NewOperand(right),
	}
}

func IsValue(node Expr) bool {
	switch v := node.(type) {
	case *SQLVal:
		switch v.Type {
		case StrVal, HexVal, IntVal, ValArg:
			return true
		}
	}
	return false
}

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


Question: finalize for StatisticsConsumer

def finalize(self):
        """"""
        super(StatisticsConsumer, self).finalize()
        # run statistics on timewave slice w at grid point g
        # self.result = [(g, self.statistics(w)) for g, w in zip(self.grid, self.result)]
        # self.result = zip(self.grid, (self.statistics(w) for w in self.result))
        self.result = zip(self.grid, map(self.statistics, self.result))

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

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


Question:
Generator for comparing 'simple' dicts when they are encountered.  This
    does not currently recurse further.  Arguments are as per other
    ``compare_``\ *X* functions.

def compare_dict_iter(propval_a, propval_b, fs_a=None, fs_b=None,
                      options=None):

    if fs_a is None:
        fs_a = FieldSelector(tuple())
        fs_b = FieldSelector(tuple())
    if not options:
        options = DiffOptions()
    propvals = dict(a=propval_a, b=propval_b)
    values = dict()
    rev_keys = dict()
    for x in "a", "b":
        propval_x = propvals[x]
        vals = values[x] = set()
        rev_key = rev_keys[x] = dict()
        seen = collections.Counter()
        for k, v in collection_generator(propval_x):
            v = options.normalize_item(
                v, propval_a if options.duck_type else propval_x
            )
            if not v.__hash__:
                v = repr(v)
            if v is not _nothing or not options.ignore_empty_slots:
                vals.add((v, seen[v]))
                rev_key[(v, seen[v])] = k
                seen[v] += 1

    removed = values['a'] - values['b']
    added = values['b'] - values['a']

    if options.moved or options.unchanged:
        unchanged = values['a'] & values['b']
        for v, seq in unchanged:
            a_key = rev_keys['a'][v, seq]
            b_key = rev_keys['b'][v, seq]
            if options.moved and a_key != b_key:
                yield DiffInfo(
                    diff_type=DiffTypes.MOVED,
                    base=fs_a + [a_key],
                    other=fs_b + [b_key],
                )
            elif options.unchanged:
                yield DiffInfo(
                    diff_type=DiffTypes.NO_CHANGE,
                    base=fs_a + [a_key],
                    other=fs_b + [b_key],
                )

    removed_keys = set(rev_keys['a'][v, seq] for v, seq in removed)
    added_keys = set(rev_keys['b'][v, seq] for v, seq in added)
    modified_keys = set(removed_keys.intersection(added_keys))

    for v, seq in removed:
        a_key = rev_keys['a'][v, seq]
        if a_key in modified_keys:
            continue
        selector = fs_a + [a_key]
        yield DiffInfo(
            diff_type=DiffTypes.REMOVED,
            base=selector,
            other=fs_b,
        )

    for v, seq in added:
        b_key = rev_keys['b'][v, seq]
        if b_key in modified_keys:
            continue
        selector = fs_b + [b_key]
        yield DiffInfo(
            diff_type=DiffTypes.ADDED,
            base=fs_a,
            other=selector,
        )

    for key in modified_keys:
        yield DiffInfo(
            diff_type=DiffTypes.MODIFIED,
            base=fs_a + [key],
            other=fs_b + [key],
        )

def __label_cmp(self, other):

        if other is None:
            return -1

        label_name = strip_accents(self.name).lower()
        other_name = strip_accents(other.name).lower()
        if label_name < other_name:
            return -1
        elif label_name == other_name:
            return 0
        else:
            return 1

        if self.get_color_str() < other.get_color_str():
            return -1
        elif self.get_color_str() == other.get_color_str():
            return 0
        else:
            return 1

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


Question:
Replicates all instance changes to peer eureka nodes except for
replication traffic to this node.

private void replicateInstanceActionsToPeers(Action action, String appName,
                                                 String id, InstanceInfo info, InstanceStatus newStatus,
                                                 PeerEurekaNode node) {
        try {
            InstanceInfo infoFromRegistry = null;
            CurrentRequestVersion.set(Version.V2);
            switch (action) {
                case Cancel:
                    node.cancel(appName, id);
                    break;
                case Heartbeat:
                    InstanceStatus overriddenStatus = overriddenInstanceStatusMap.get(id);
                    infoFromRegistry = getInstanceByAppAndId(appName, id, false);
                    node.heartbeat(appName, id, infoFromRegistry, overriddenStatus, false);
                    break;
                case Register:
                    node.register(info);
                    break;
                case StatusUpdate:
                    infoFromRegistry = getInstanceByAppAndId(appName, id, false);
                    node.statusUpdate(appName, id, newStatus, infoFromRegistry);
                    break;
                case DeleteStatusOverride:
                    infoFromRegistry = getInstanceByAppAndId(appName, id, false);
                    node.deleteStatusOverride(appName, id, infoFromRegistry);
                    break;
            }
        } catch (Throwable t) {
            logger.error("Cannot replicate information to {} for action {}", node.getServiceUrl(), action.name(), t);
        }
    }

def generate_answers
      masterless = @options[:masterless]
      return super if masterless

      dashboard = only_host_with_role(@hosts, 'dashboard')
      database = only_host_with_role(@hosts, 'database')
      master = only_host_with_role(@hosts, 'master')

      the_answers = super
      if dashboard != master
        # in 3.2, dashboard needs the master certname
        the_answers[dashboard.name][:q_puppetmaster_certname] = master.to_s
      end

      # do we want to check for updates?
      pe_check_for_updates = answer_for(@options, :q_pe_check_for_updates, 'n')
      the_answers[dashboard.name][:q_pe_check_for_updates] = pe_check_for_updates
      the_answers[master.name][:q_pe_check_for_updates] = pe_check_for_updates

      if @options[:type] == :upgrade && dashboard != database
        # In a split configuration, there is no way for the upgrader
        # to know how much disk space is available for the database
        # migration. We tell it to continue on, because we're
        # awesome.
        the_answers[dashboard.name][:q_upgrade_with_unknown_disk_space] = 'y'
      end
      @hosts.each do |h|
        h[:answers] = the_answers[h.name]
      end
      return the_answers
    end

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


Question:
Send a transaction proposal to specific peers.

@param transactionProposalRequest The transaction proposal to be sent to the peers.
@param peers
@return responses from peers.
@throws InvalidArgumentException
@throws ProposalException

public Collection<ProposalResponse> sendTransactionProposal(TransactionProposalRequest transactionProposalRequest, Collection<Peer> peers) throws ProposalException, InvalidArgumentException {

        return sendProposal(transactionProposalRequest, peers);
    }

public void marshall(SearchRequest searchRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(searchRequest.getCursor(), CURSOR_BINDING);
            protocolMarshaller.marshall(searchRequest.getExpr(), EXPR_BINDING);
            protocolMarshaller.marshall(searchRequest.getFacet(), FACET_BINDING);
            protocolMarshaller.marshall(searchRequest.getFilterQuery(), FILTERQUERY_BINDING);
            protocolMarshaller.marshall(searchRequest.getHighlight(), HIGHLIGHT_BINDING);
            protocolMarshaller.marshall(searchRequest.getPartial(), PARTIAL_BINDING);
            protocolMarshaller.marshall(searchRequest.getQuery(), QUERY_BINDING);
            protocolMarshaller.marshall(searchRequest.getQueryOptions(), QUERYOPTIONS_BINDING);
            protocolMarshaller.marshall(searchRequest.getQueryParser(), QUERYPARSER_BINDING);
            protocolMarshaller.marshall(searchRequest.getReturn(), RETURN_BINDING);
            protocolMarshaller.marshall(searchRequest.getSize(), SIZE_BINDING);
            protocolMarshaller.marshall(searchRequest.getSort(), SORT_BINDING);
            protocolMarshaller.marshall(searchRequest.getStart(), START_BINDING);
            protocolMarshaller.marshall(searchRequest.getStats(), STATS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question: // SetJobQueueName sets the JobQueueName field's value.

func (s *CreateJobQueueInput) SetJobQueueName(v string) *CreateJobQueueInput {
	s.JobQueueName = &v
	return s
}

public function add() {
		$this->err('Queue Email Task cannot be added via Console.');
		$this->out('Please use createJob() on the QueuedTask Model to create a Proper Email Task.');
		$this->out('The Data Array should look something like this:');
		$this->out(var_export([
			'settings' => [
				'to' => 'email@example.com',
				'subject' => 'Email Subject',
				'from' => 'system@example.com',
				'template' => 'sometemplate',
			],
			'content' => 'hello world',
		], true));
		$this->out('Alternativly, you can pass the whole EmailLib to directly use it.');
	}

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