query large_stringlengths 4 15k | positive large_stringlengths 5 373k | source stringclasses 7
values |
|---|---|---|
Return a RefContext object given a geoloc entry. | def ref_context_from_geoloc(geoloc):
"""Return a RefContext object given a geoloc entry."""
text = geoloc.get('text')
geoid = geoloc.get('geoID')
rc = RefContext(name=text, db_refs={'GEOID': geoid})
return rc | csn |
Event thatis firex when particular ApiRoute is matched | public function routeMatched(ApiRoute $route, Request $request): void
{
if (($format = $request->getParameter(self::API_DOCU_STARTER_QUERY_KEY_GENERATE)) !== null) {
$this->generator->generateAll($this->router);
exit(0);
}
if (($format = $request->getParameter(self::API_DOCU_STARTER_QUERY_KEY_TARGET)) !=... | csn |
Unmarshall a DOMElement object corresponding to a QTI sectionPart element.
@param \DOMElement $element A DOMElement object.
@return \qtism\data\QtiComponent A SectionPart object.
@throws \qtism\data\storage\xml\marshalling\UnmarshallingException | protected function unmarshall(DOMElement $element)
{
if (($identifier = $this->getDOMElementAttributeAs($element, 'identifier')) !== null) {
$object = new SectionPart($identifier);
if (($required = $this->getDOMElementAttributeAs($element, 'required', 'boolean')) !== null) {
... | csn |
Demand create a destination block.
@return the active block; null if there isn't one
@throws IOException on any failure to create | private synchronized COSDataBlocks.DataBlock createBlockIfNeeded() throws IOException {
if (activeBlock == null) {
blockCount++;
if (blockCount >= COSConstants.MAX_MULTIPART_COUNT) {
LOG.error("Number of partitions in stream exceeds limit for S3: "
+ COSConstants.MAX_MULTIPART_COUNT
... | csn |
Get a checkbox.
@param bool $checked Checked ?
@return string Returns the checkbox. | public static function getCheckbox($checked) {
if (true === $checked) {
return sprintf("<fg=green;options=bold>%s</>", OSHelper::isWindows() ? "OK" : "\xE2\x9C\x94");
}
return sprintf("<fg=yellow;options=bold>%s</>", OSHelper::isWindows() ? "KO" : "!");
} | csn |
check if this url can serve the refUrl.
@param refUrl a URL object
@return boolean true can serve | @Override
public boolean canServe(URL refUrl) {
if (refUrl == null || !this.getPath().equals(refUrl.getPath())) {
return false;
}
if(!protocol.equals(refUrl.getProtocol())) {
return false;
}
if (!Constants.NODE_TYPE_SERVICE.equals(this.getParameter(U... | csn |
// Stack creates an instance of StackController | func Stack() (c *StackController) {
return &StackController{
List: stackList,
New: stackNew,
Create: stackCreate,
Detail: stackDetail,
Edit: stackEdit,
Update: stackUpdate,
Deploy: stackDeploy,
Shutdown: stackShutdown,
Delete: stackDelete,
}
} | csn |
Create a Subquery to check if a image has a specific filename.
@param filename The Value that the property tag should have.
@return A subquery that can be used in an exists statement to see if a topic has a property tag with the specified value. | private Subquery<ImageFile> getImagesWithFileNameSubquery(final String filename, final FilterStringLogic searchLogic) {
final CriteriaBuilder criteriaBuilder = getCriteriaBuilder();
final Subquery<ImageFile> subQuery = getCriteriaQuery().subquery(ImageFile.class);
final Root<LanguageImage> root ... | csn |
Parse points from OSM nodes.
Parameters
----------
response : JSON
Nodes from OSM response.
Returns
-------
Dict of vertex IDs and their lat, lon coordinates. | def parse_osm_node(response):
"""
Parse points from OSM nodes.
Parameters
----------
response : JSON
Nodes from OSM response.
Returns
-------
Dict of vertex IDs and their lat, lon coordinates.
"""
try:
point = Point(response['lon'], response['lat'])
... | csn |
Creates a new anti-affinity policy within a given account.
https://t3n.zendesk.com/entries/45042770-Create-Anti-Affinity-Policy
*TODO* Currently returning 400 error:
clc.APIFailedResponse: Response code 400. . POST https://api.tier3.com/v2/antiAffinityPolicies/BTDI | def Create(name,alias=None,location=None,session=None):
"""Creates a new anti-affinity policy within a given account.
https://t3n.zendesk.com/entries/45042770-Create-Anti-Affinity-Policy
*TODO* Currently returning 400 error:
clc.APIFailedResponse: Response code 400. . POST https://api.tier3.com/v2/antiAffinit... | csn |
Creates a new Dhii invalid argument exception.
@since [*next-version*]
@param string|Stringable|int|float|bool|null $message The message, if any.
@param int|float|string|Stringable|null $code The numeric error code, if any.
@param RootException|null $previous The inner exception, if any.
... | protected function _createInvalidArgumentException(
$message = null,
$code = null,
RootException $previous = null,
$argument = null
) {
return new InvalidArgumentException($message, $code, $previous, $argument);
} | csn |
// Close implements watcher. | func (t *trg) Close() (err error) {
t.Lock()
if err = t.t.Stop(); err != nil {
t.Unlock()
return
}
<-t.s
var e error
for _, w := range t.pthLkp {
if e = t.unwatch(w.p, w.fi); e != nil {
dbgprintf("trg: unwatch %q failed: %q\n", w.p, e)
err = nonil(err, e)
}
}
if e = t.t.Close(); e != nil {
dbgpr... | csn |
Implementation of Lua's os.time function.
@param {object} table The table that will receive the metatable. | function (table) {
var time;
if (!table) {
time = Date['now']? Date['now']() : new Date().getTime();
} else {
var day, month, year, hour, min, sec;
if (!(day = table.getMember('day'))) throw new shine.Error("Field 'day' missing in date table");
if (!(month = table.getMember('month... | csn |
Recursively requires the modules in current dir.
@param {String} dir The base directory to require entities from.
@return {Object} An object with all the modules loaded. | function requireMethods(dir) {
if (!dir) dir = getCallerDirname();
var modules = {};
fs
.readdirSync(dir)
.filter(function(filename) {
return filename !== 'index.js';
})
.forEach(function(filename) {
var filePath = path.join(dir, filename);
var Stats = fs.lstatSync(filePath);
... | csn |
Process the registration of one service.
@param string $className The class name of the service
@throws \Subbly\Api\Exception If class name does not exists
@throws \Subbly\Api\Exception If the class does not implement \Subbly\Api\Service\Service
@throws \Subbly\Api\Exception If service name is already register | public function registerService($className)
{
if (! class_exists($className)) {
throw new Exception(sprintf(Exception::SERVICE_CLASS_NOT_EXISTS, $className));
}
$service = new $className($this);
if (!$service instanceof Service) {
throw new Exception(sprintf... | csn |
Find object in database.
@param {Object} req Request
@param {Object} res Response
@param {Object} options {model, populate, callback} | function (req, res, options) {
if (!options) {
options = {};
}
options.operation = 'FIND';
options.res = res;
exports.find.before(req, res, options);
vulpejs.models.find({
model: req.params.model,
populate: req.params.populate,
history: true,
id: req.params.id || fa... | csn |
// toSlice takes in a "generic" slice and converts and copies
// it's elements into the typed slice pointed at by ptr.
// Note that this is a costly operation. | func toSlice(from []interface{}, ptr interface{}) {
// Value of the pointer to the target
obj := reflect.Indirect(reflect.ValueOf(ptr))
// We can't just convert from interface{} to whatever the target is (diff memory layout),
// so we need to create a New slice of the proper type and copy the values individually
t... | csn |
Returns optional default if field is not required and
default was not provided.
:param bool required: whether the field is required in a given model.
:param default: default provided by creator of field.
:param optional_default: default for the data type if none provided.
:return: default or option... | def init_default(required, default, optional_default):
"""
Returns optional default if field is not required and
default was not provided.
:param bool required: whether the field is required in a given model.
:param default: default provided by creator of field.
:param optional_default: default... | csn |
See how often two members voted together in a given Congress.
Takes two member IDs, a chamber and a Congress number. | def compare(self, first, second, chamber, type='votes', congress=CURRENT_CONGRESS):
"""
See how often two members voted together in a given Congress.
Takes two member IDs, a chamber and a Congress number.
"""
check_chamber(chamber)
path = "members/{first}/{type}/{second}/... | csn |
Turn baseParser results into a dataframe | def get_baseparser_extended_df(sample, bp_lines, ref, alt):
"""Turn baseParser results into a dataframe"""
columns = "chrom\tpos\tref\tcov\tA\tC\tG\tT\t*\t-\t+".split()
if bp_lines is None:
return None
# change baseparser output to get most common maf per indel
bpdf = pd.DataFrame([[sample]... | csn |
Generate top level CMakeLists.txt.
:param working_path: current working directory
:param subdirs: a list of subdirectories of current working directory.
:param files: a list of files in current working directory.
:return: the full path name of generated CMakeLists.txt. | def genTopLevelDirCMakeListsFile(self, working_path, subdirs, files, cfg):
"""
Generate top level CMakeLists.txt.
:param working_path: current working directory
:param subdirs: a list of subdirectories of current working directory.
:param files: a list of files in current workin... | csn |
// Receive waits for the response promised by the future and returns detailed
// information about a wallet transaction. | func (r FutureGetTransactionResult) Receive() (*btcjson.GetTransactionResult, error) {
res, err := receiveFuture(r)
if err != nil {
return nil, err
}
// Unmarshal result as a gettransaction result object
var getTx btcjson.GetTransactionResult
err = json.Unmarshal(res, &getTx)
if err != nil {
return nil, err... | csn |
Gets the pushbutton field.
@throws IOException on error
@throws DocumentException on error
@return the pushbutton field | public PdfFormField getField() throws IOException, DocumentException {
PdfFormField field = PdfFormField.createPushButton(writer);
field.setWidget(box, PdfAnnotation.HIGHLIGHT_INVERT);
if (fieldName != null) {
field.setFieldName(fieldName);
if ((options & READ_ONLY) != 0)... | csn |
// Remove removes a writer from the group. | func (g *WriterGroup) Remove(key string) {
g.mu.Lock()
defer g.mu.Unlock()
w, ok := g.writers[key]
if !ok {
return
}
w.Close()
delete(g.writers, key)
} | csn |
// AddAttribute adds an Attribute to this BinaryAttributeGroup | func (b *BinaryAttributeGroup) AddAttribute(a Attribute) error {
b.attributes = append(b.attributes, a)
return nil
} | csn |
Factory method for error in authentication.
@param aCredentialValidationFailure
The validation failure. May not be <code>null</code> in case of
failure!
@return Never <code>null</code>. | @Nonnull
public static AuthIdentificationResult createFailure (@Nonnull final ICredentialValidationResult aCredentialValidationFailure)
{
ValueEnforcer.notNull (aCredentialValidationFailure, "CredentialValidationFailure");
return new AuthIdentificationResult (null, aCredentialValidationFailure);
} | csn |
Exports the records produced by the specified report.
@param mixed $reportId integer or numeric string ID of the report to use.
@param string $format output data format.
<ul>
<li> 'php' - [default] array of maps of values</li>
<li> 'csv' - string of CSV (comma-separated values)</li>
<li> 'json' - string of JSON encode... | public function exportReports(
$reportId,
$format = 'php',
$rawOrLabel = 'raw',
$rawOrLabelHeaders = 'raw',
$exportCheckboxLabel = false
) {
$data = array(
'token' => $this->apiToken,
'content' => 'report',
'returnFormat... | csn |
Expands this URITemplate to a URI.
@param {Object} params The parameters to use for expansion. This object is a map of keys (variable names) to values (the variable's
value in the <a href="http://tools.ietf.org/html/rfc6570#section-3.2.1">expansion algorithm</a>).
@returns {String} The resulting URI. | function(params) {
var result = [];
for (var i = 0; i < this._templateComponents.length; i++) {
result.push(this._templateComponents[i].expand(params));
}
return result.join("");
} | csn |
Runs tests based on the given \PHPUnit_Framework_TestSuite object.
@param \PHPUnit_Framework_TestSuite $suite | public function run($suite)
{
$printer = $this->createPrinter();
$testResult = new \PHPUnit_Framework_TestResult();
$testRunner = new TestRunner();
$testRunner->setTestResult($testResult);
$testRunner->doRun($suite, $this->createArguments($printer, $testResult), false);
... | csn |
Execute a method
@method execute
@param {string} method name of the method to execute
@param {object} args arguments for this method
@param {options} [options] options for execution
@return {promise<object>} | function(method, args, options) {
var that = this, methodHandler;
options = options || {};
var handler = this.getHandler(method);
if (!handler) return Q.reject(new Error("No handler found for method: "+method));
// Is offline
if (!Offline.isConn... | csn |
Generate all page links and return them as array.
@return array The page links as array | public function getItemsAsArray()
{
$items = [];
foreach ($this->teasers as $page => $teaser) {
if ($page == $this->intPage) {
$items[] = [
'page' => $page,
'href' => null,
'title' => null,
'... | csn |
Verify password against hash using timing attack resistant approach
@return bool
@param $pw string
@param $hash string | function verify($pw,$hash) {
$val=crypt($pw,$hash);
$len=strlen($val);
if ($len!=strlen($hash) || $len<14)
return FALSE;
$out=0;
for ($i=0;$i<$len;$i++)
$out|=(ord($val[$i])^ord($hash[$i]));
return $out===0;
} | csn |
Page for edit a custom field | function edit_field() {
global $mf_domain;
//check param custom_field_id
$data = $this->fields_form();
$field = $this->get_custom_field($_GET['custom_field_id']);
//check if exist field
if(!$field){
$this->mf_flash('error');
}else{
$no_set = array('options','active','display_or... | csn |
Check ``mode`` parameter of `~fs.base.FS.openbin` is valid.
Arguments:
mode (str): Mode parameter.
Raises:
`ValueError` if mode is not valid. | def validate_openbin_mode(mode, _valid_chars=frozenset("rwxab+")):
# type: (Text, Union[Set[Text], FrozenSet[Text]]) -> None
"""Check ``mode`` parameter of `~fs.base.FS.openbin` is valid.
Arguments:
mode (str): Mode parameter.
Raises:
`ValueError` if mode is not valid.
"""
if ... | csn |
A convenient way of creating a map on the fly.
@param <K> the key type
@param <V> the value type
@param entries
Map.Entry objects to be added to the map
@return a LinkedHashMap with the supplied entries | @SafeVarargs
public static <K, V> Map<K, V> map(final Entry<? extends K, ? extends V>... entries) {
final Map<K, V> map = new LinkedHashMap<K, V>(entries.length);
for (final Entry<? extends K, ? extends V> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
re... | csn |
// validateEndpoints determines if all endpoints are valid.
// Each endpoint is either from local application or remote.
// If more than one remote endpoint are supplied, the input argument are considered invalid. | func (c *addRelationCommand) validateEndpoints(all []string) error {
for _, endpoint := range all {
// We can only determine if this is a remote endpoint with 100%.
// If we cannot parse it, it may still be a valid local endpoint...
// so ignoring parsing error,
if url, err := crossmodel.ParseOfferURL(endpoint... | csn |
Generate a v4 UUID
@return string | public function generateUuid() {
if (is_readable(self::UUID_SOURCE)) {
$uuid = trim(file_get_contents(self::UUID_SOURCE));
} elseif (function_exists('mt_rand')) {
/**
* Taken from stackoverflow answer, possibly not the fastest or
* strictly standards com... | csn |
Checks whether this is a legitimate request coming from the Index Queue
page indexer worker task.
@return bool TRUE if it's a legitimate request, FALSE otherwise. | public function isAuthenticated()
{
$authenticated = false;
if (is_null($this->parameters)) {
return $authenticated;
}
$calculatedHash = md5(
$this->parameters['item'] . '|' .
$this->parameters['page'] . '|' .
$GLOBALS['TYPO3_CONF_VAR... | csn |
If file and text, append file and text
@return type
@throws ArchException | protected function getMetaContent()
{
if ($this->mdFile && !file_exists($this->mdFile)) {
throw new ArchException('Wrong markdown file [' . $this->mdFile . ']');
}
if ($this->mdFile && !$this->getContent()) {
return Container::getMarkdown()->file($this->mdFile, $this-... | csn |
Checks whether the container contains the value x.
@param buf underlying buffer
@param position starting position of the container in the ByteBuffer
@param x target value x
@param cardinality container cardinality
@return whether the container contains the value x | public static boolean contains(ByteBuffer buf, int position, final short x, int cardinality) {
return BufferUtil.unsignedBinarySearch(buf, position, 0, cardinality, x) >= 0;
} | csn |
Makes array of <option>. Can handle associative arrays just fine. Checks for duplicate values.
@param array $items
@param callable $optionArgs takes ($value,$caption) and spits out an array of <option>
attributes
@param array $valuesRendered for internal use. Do not change.
@return array
@throws I... | public function makeOptionList($items, callable $optionArgs, array &$valuesRendered = [])
{
$ret = [];
foreach ($items as $value => $caption) {
if (is_int($value)) {
$value = (string)$value;
}
if (is_array($caption)) {
// subgroup
$option = Html::el('optgroup', ['label' => $value]);
// o... | csn |
Returns the nearest available revision to the specified revision counter.
@param revisionCounter
revision counter
@return Revision | public Revision getNearest(final int revisionCounter)
{
if (first != null) {
ChronoStorageBlock previous = null, current = first;
while (current != null
&& current.getRevisionCounter() <= revisionCounter) {
previous = current;
current = current.getCounterNext();
}
return previous.getRev()... | csn |
Get Default Style.
@return object
@throws Exception | public function getDefaultStyle()
{
//build URI to merge Docs
$strURI = Product::$baseProductUri . '/cells/' . $this->getFileName() . '/defaultStyle';
//sign URI
$signedURI = Utils::sign($strURI);
$responseStream = Utils::processCommand($signedURI, 'GET', '');
$json =... | csn |
The current day midnight.
@return Date | static function Today()
{
$now = new Date();
return new Date($now->Day(), $now->Month(), $now->Year(), 0, 0, 0);
} | csn |
Indicates that the client is connected to the Redis server or
cluster and is ready for use.
:rtype: bool | def ready(self):
"""Indicates that the client is connected to the Redis server or
cluster and is ready for use.
:rtype: bool
"""
if self._clustering:
return (all([c.connected for c in self._cluster.values()])
and len(self._cluster))
retur... | csn |
Validate that spectrum and bandpass overlap.
Warnings are stored in ``self.warnings``.
Parameters
----------
force : {'extrap', 'taper', `None`}
If `None`, it is required that the spectrum and bandpass fully
overlap. Partial overlap is allowed if this is set to
... | def validate_overlap(self,force):
"""Validate that spectrum and bandpass overlap.
Warnings are stored in ``self.warnings``.
Parameters
----------
force : {'extrap', 'taper', `None`}
If `None`, it is required that the spectrum and bandpass fully
overlap. P... | csn |
Insert settings data.
@param array $inserts | private function insertSettings(array $inserts)
{
if (empty($inserts)) {
return;
}
$dbData = [];
foreach ($inserts as $key => $value) {
$data = compact('key', 'value');
$dbData[] = empty($this->extraColumns) ? $data : array_merge($this->extra... | csn |
//Convert2JavaProps is a FileHandler
//it convert the yaml content into java props | func Convert2JavaProps(p string, content []byte) (map[string]interface{}, error) {
configMap := make(map[string]interface{})
ss := yaml.MapSlice{}
err := yaml.Unmarshal([]byte(content), &ss)
if err != nil {
return nil, fmt.Errorf("yaml unmarshal [%s] failed, %s", content, err)
}
configMap = retrieveItems("", s... | csn |
Call the API check-version endpoint for API data.
@since 1.0.0
@param array $args API arguments to pass.
@return mixed $response Object for valid response, or error message as string. | public function callCheckVersion( $args ) {
if ( ! empty( $args['key'] ) ) {
$call = new Api\Call( Configs::get( 'api' ) . '/api/plugin/checkVersion', $args );
// If there's an error set that as the response.
if ( ! $response = $call->getError() ) {
// If the response is successful, then retrieve the r... | csn |
// alloc allocates a buffer from the manager, if one is available. | func (b *bufferManager) alloc() *queue.TxBuffer {
if b.freeList != nil {
// There is a descriptor ready for reuse in the free list.
d := b.freeList
b.freeList = d.Next
d.Next = nil
return d
}
if b.curOffset < b.limit {
// There is room available in the never-used range, so create
// a new descriptor f... | csn |
Copy self attributes to the new object.
:param CFGBase copy_to: The target to copy to.
:return: None | def make_copy(self, copy_to):
"""
Copy self attributes to the new object.
:param CFGBase copy_to: The target to copy to.
:return: None
"""
for attr, value in self.__dict__.items():
if attr.startswith('__') and attr.endswith('__'):
continue
... | csn |
Returns minimal message identifier in the result
@return int Minimal message identifier | public function min()
{
if (!isset($this->meta['min'])) {
$this->meta['min'] = (int) @min($this->get());
}
return $this->meta['min'];
} | csn |
Add the supplied file to the file system.
Note: If overriding this function, it is advisable to store the file
in the path returned by get_local_path_from_hash as there may be
subsequent uses of the file in the same request.
@param string $pathname Path to file currently on disk
@param string $contenthash SHA1 hash o... | public function add_file_from_path($pathname, $contenthash = null) {
list($contenthash, $filesize) = $this->validate_hash_and_file_size($contenthash, $pathname);
$hashpath = $this->get_fulldir_from_hash($contenthash);
$hashfile = $this->get_local_path_from_hash($contenthash, false);
$... | csn |
find and compile a list of all unique modules, and their paths | function compile() {
swig.log.info('', 'Compiling module list...');
const modulesPath = path.join(swig.temp, '/**/node_modules/@gilt-tech');
const modPaths = glob.sync(modulesPath);
let dirs;
swig.log.verbose(`[compile] searching: ${modulesPath}`);
swig.log.verbose(`[compile] found module dire... | csn |
Get append max limit type from the input
@param extractType Extract type
@param maxLimit
@return Max limit type | private static AppendMaxLimitType getAppendLimitType(ExtractType extractType, String maxLimit) {
LOG.debug("Getting append limit type");
AppendMaxLimitType limitType;
switch (extractType) {
case APPEND_DAILY:
limitType = AppendMaxLimitType.CURRENTDATE;
break;
case APPEND_HOURLY:
... | csn |
Performs the decryption of the given data.
@param privateKey PGP Private Key to decrypt
@param data encrypted data
@param calculator instance of {@link BcKeyFingerprintCalculator}
@param targetStream stream to receive the decrypted data
@throws PGPException if the decryption process fails
@throws IOException if the str... | protected static void decryptData(final PGPPrivateKey privateKey, final PGPPublicKeyEncryptedData data,
final BcKeyFingerprintCalculator calculator, final OutputStream targetStream)
throws PGPException, IOException {
PublicKeyDataDecryptorFactory decryptorFactory = ... | csn |
// Run runs a git command and returns its output or errors | func Run(args ...string) (string, error) {
// TODO: use exex.CommandContext here and refactor.
var extraArgs = []string{
"-c", "log.showSignature=false",
}
args = append(extraArgs, args...)
/* #nosec */
var cmd = exec.Command("git", args...)
log.WithField("args", args).Debug("running git")
bts, err := cmd.Com... | csn |
Lists all hosts on the LB | def action_list(self):
"Lists all hosts on the LB"
format = "%-35s %-25s %-8s"
print format % ("HOST", "ACTION", "SUBDOMS")
for host, details in sorted(self.client.get_all().items()):
if details[0] in ("proxy", "mirror"):
action = "%s<%s>" % (
... | csn |
256 colors supported | def term_color(code):
"""
256 colors supported
"""
def inner(text, rl=False):
"""
Every raw_input with color sequences should be called with
rl=True to avoid readline messed up the length calculation
"""
c = code
if rl:
return "\001\033[38;5;%s... | csn |
Given a PDOStatement that has just been executed, generate results
and report any errors
@param PDOStatementHandle $statement
@param int $errorLevel
@param string $sql
@param array $parameters
@return PDOQuery | protected function prepareResults(PDOStatementHandle $statement, $errorLevel, $sql, $parameters = array())
{
// Catch error
if ($this->hasError($statement)) {
$this->lastStatementError = $statement->errorInfo();
$statement->closeCursor();
$this->databaseError($t... | csn |
// BatchV1beta1 retrieves the BatchV1beta1Client | func (c *Clientset) BatchV1beta1() batchv1beta1.BatchV1beta1Interface {
return &fakebatchv1beta1.FakeBatchV1beta1{Fake: &c.Fake}
} | csn |
returns a plain text string when given a html string text
handles a, p, h1 to h6 and br, inserts newline chars to
create space in the string
@todo handle images | def html_to_text(html_string):
"""
returns a plain text string when given a html string text
handles a, p, h1 to h6 and br, inserts newline chars to
create space in the string
@todo handle images
"""
# create a valid html document from string
# beware that it inserts <hmtl> <body> and <p... | csn |
// GetEmailAddresses returns all email addresses belongs to given user. | func GetEmailAddresses(uid int64) ([]*EmailAddress, error) {
emails := make([]*EmailAddress, 0, 5)
if err := x.Where("uid=?", uid).Find(&emails); err != nil {
return nil, err
}
u, err := GetUserByID(uid)
if err != nil {
return nil, err
}
isPrimaryFound := false
for _, email := range emails {
if email.Em... | csn |
Create an error object from the response and call the callback function
@param {Object} body The parsed response body (or null if not yet parsed)
@param {Response} response The HTTP response object
@param {Function} callback Function to call with the resulting error object
@returns {void} | function handleError(body, response, callback) {
var error;
if (!body) {
response.pipe(concat(function (body) {
body = parseJSONBody(body);
error = body.message || statusText(response.statusCode);
callback(new Error(error), body, response);
}));
} else {
... | csn |
Determines if a record is garbage and can be deleted.
@param string $table
@param array $record
@return bool | protected function getIsGarbageRecord($table, $record):bool
{
return $this->tcaService->isHidden($table, $record) ||
$this->isInvisibleByStartOrEndtime($table, $record) ||
$this->hasFrontendGroupsRemoved($table, $record) ||
($table === 'pages' && $this->isPage... | csn |
// filterPreparedQueries is used to filter prepared queries based on ACL rules.
// We prune entries the user doesn't have access to, and we redact any tokens
// if the user doesn't have a management token. | func (f *aclFilter) filterPreparedQueries(queries *structs.PreparedQueries) {
// Management tokens can see everything with no filtering.
if f.authorizer.ACLWrite() {
return
}
// Otherwise, we need to see what the token has access to.
ret := make(structs.PreparedQueries, 0, len(*queries))
for _, query := range ... | csn |
Add metedata next to a node | def decorate(svg, node, metadata):
"""Add metedata next to a node"""
if not metadata:
return node
xlink = metadata.get('xlink')
if xlink:
if not isinstance(xlink, dict):
xlink = {'href': xlink, 'target': '_blank'}
node = svg.node(node, 'a', **xlink)
svg.node(
... | csn |
Configure Auth system
@param array $config
@return Auth | public static function configure(array $config)
{
if (!is_null(static::$instance)) {
return static::$instance;
}
static::$config = $config;
static::$session = Session::getInstance();
return static::$instance = new Auth($config[$config['default']]);
} | csn |
Retrieve Core Stats
@access public
@return object JSON | public function retrieveCoreStats ()
{
$data = file_get_contents("http://battlefield.play4free.com/en/profile/stats/" .$this->_profileID. "/" .$this->_soldierID. "?g=[%22CoreStats%22]");
$coreStats = json_decode($data);
return $coreStats;
} | csn |
// MarshalJSON converts a Deployment into a Cloud Controller Deployment. | func (d Deployment) MarshalJSON() ([]byte, error) {
type Droplet struct {
GUID string `json:"guid,omitempty"`
}
var ccDeployment struct {
Droplet *Droplet `json:"droplet,omitempty"`
Relationships Relationships `json:"relationships,omitempty"`
}
if d.DropletGUID != "" {
ccDeployment.Droplet = &... | csn |
Create Serializer instance
@param {?_cSerializer} config | function(config) {
if (config) {
if (config.check_property_names === false) this._check_property_names = false;
}
this._serializeFunction = (config && config.pretty_print_functions)
? this._serializeFunction_PrettyPrint
: this._serializeFunction_Normal
} | csn |
// Convert_build_SecretLocalReference_To_v1_SecretLocalReference is an autogenerated conversion function. | func Convert_build_SecretLocalReference_To_v1_SecretLocalReference(in *build.SecretLocalReference, out *v1.SecretLocalReference, s conversion.Scope) error {
return autoConvert_build_SecretLocalReference_To_v1_SecretLocalReference(in, out, s)
} | csn |
The maximum number of textures available for this graphic card's fragment shader. | def max_texture_limit(self):
"""The maximum number of textures available for this graphic card's fragment shader."""
max_unit_array = (gl.GLint * 1)()
gl.glGetIntegerv(gl.GL_MAX_TEXTURE_IMAGE_UNITS, max_unit_array)
return max_unit_array[0] | csn |
Transform an array into a string using identation
@param array $array Array to transform
@return string | private static function arrayToFileWrite($array, $numParent) {
$tabs = "";
for ($index = 0; $index <= $numParent; $index++) {
$tabs .= chr(9);
}
$strArr = "";
foreach ($array as $key => $value) {
if (is_array($value)) {
$strValue = ... | csn |
Make a very small database call | def sdb(opts, functions=None, whitelist=None, utils=None):
'''
Make a very small database call
'''
if utils is None:
utils = {}
return LazyLoader(
_module_dirs(opts, 'sdb'),
opts,
tag='sdb',
pack={
'__sdb__': functions,
'__opts__': opt... | csn |
// isValidChaincodeVersion checks the validity of chaincode version. Versions
// should never be blank and should only consist of alphanumerics, '_', '-',
// '+', and '.' | func (lscc *LifeCycleSysCC) isValidChaincodeVersion(chaincodeName string, version string) error {
if version == "" {
return EmptyVersionErr(chaincodeName)
}
if !isValidCCNameOrVersion(version, allowedCharsVersion) {
return InvalidVersionErr(version)
}
return nil
} | csn |
hex decode a value. | def dehex_app(parser, cmd, args): # pragma: no cover
"""
hex decode a value.
"""
parser.add_argument('value', help='the value to base64 decode, read from stdin if omitted', nargs='?')
args = parser.parse_args(args)
return dehex(pwnypack.main.string_value_or_stdin(args.value)) | csn |
does the real work of releasing the FileLock | private boolean releaseFileLock() {
// Note: Closing the super class RandomAccessFile has the
// side-effect of closing the file lock's FileChannel,
// so we do not deal with this here.
boolean success = false;
if (this.fileLock == null) {
success = t... | csn |
// Access token endpoint | func (r *rest) AppToken(c *gin.Context) {
resp := r.server.NewResponse()
defer resp.Close()
if ar := r.server.HandleAccessRequest(resp, c.Request); ar != nil {
ar.UserData = uint(0)
switch ar.Type {
case osin.AUTHORIZATION_CODE:
ar.Authorized = true
case osin.REFRESH_TOKEN:
ar.Authorized = true
case ... | csn |
Set print area
@param int $column1 Column 1
@param int $row1 Row 1
@param int $column2 Column 2
@param int $row2 Row 2
@param int $index Identifier for a specific print area range allowing several ranges to be set
When the method is "O"verwri... | public function setPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE)
{
return $this->setPrintArea(
PHPExcel_Cell::stringFromColumnIndex($column1) . $row1 . ':' . PHPExcel_Cell::stringFromColumnIndex($column2) . $row2,
$inde... | csn |
// FormatTime returns a string with the local time formatted
// in an arbitrary format used for status or and localized tz
// or in UTC timezone and format RFC3339 if u is specified. | func FormatTime(t *time.Time, formatISO bool) string {
if formatISO {
// If requested, use ISO time format.
// The format we use is RFC3339 without the "T". From the spec:
// NOTE: ISO 8601 defines date and time separated by "T".
// Applications using this syntax may choose, for the sake of
// readability, t... | csn |
Create a .pyc by disassembling the file and assembling it again, printing
a message that the reassembled file was loaded. | def recompile(filename):
"""Create a .pyc by disassembling the file and assembling it again, printing
a message that the reassembled file was loaded."""
# Most of the code here based on the compile.py module.
import os
import imp
import marshal
import struct
f = open(filename, 'U')
... | csn |
// PercentTermsToMatch will be changed to MinimumShouldMatch. | func (q MoreLikeThisQuery) PercentTermsToMatch(percentTermsToMatch float64) MoreLikeThisQuery {
q.minimumShouldMatch = fmt.Sprintf("%d%%", int(math.Floor(percentTermsToMatch*100)))
return q
} | csn |
// middleware for request length metrics. | func requestMetrics(l *log.Logger) service {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
h.ServeHTTP(w, r)
l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Now().Sub(start).Nanoseconds())
})
}
} | csn |
// Init initializes a broker and configures an AWS session and SQS struct | func (b *sqsBroker) Init(opts ...broker.Option) error {
for _, o := range opts {
o(&b.options)
}
return nil
} | csn |
// FindTools returns al ist of tools matching the specified version number and
// series, and, arch. If arch is blank, a default will be used. | func (st *State) FindTools(v version.Number, series string, arch string) (tools.List, error) {
args := params.FindToolsParams{
Number: v,
Series: series,
MajorVersion: -1,
MinorVersion: -1,
}
if arch != "" {
args.Arch = arch
}
var result params.FindToolsResult
if err := st.facade.FacadeCall(... | csn |
Create and set an Event Identification block for this audit event message
@param outcome The Event Outcome Indicator
@param action The Event Action Code
@param id The Event ID
@param type The Event Type Code
@return The Event Identification block created | protected EventIdentificationType setEventIdentification(
RFC3881EventOutcomeCodes outcome,
RFC3881EventActionCodes action,
CodedValueType id, CodedValueType[] type,
List<CodedValueType> purposesOfUse) {
EventIdentificationType eventBlock = new EventIdentification... | csn |
// AddCookie adds a cookie to the page.
// Returns true if the cookie was successfully added. | func (p *WebPage) AddCookie(cookie *http.Cookie) (bool, error) {
var resp struct {
ReturnValue bool `json:"returnValue"`
}
req := map[string]interface{}{"ref": p.ref.id, "cookie": encodeCookieJSON(cookie)}
if err := p.ref.process.doJSON("POST", "/webpage/AddCookie", req, &resp); err != nil {
return false, err
... | csn |
// GetBounce retrieves a single bounce record, if any exist, for the given recipient address. | func (mg *MailgunImpl) GetBounce(ctx context.Context, address string) (Bounce, error) {
r := newHTTPRequest(generateApiUrl(mg, bouncesEndpoint) + "/" + address)
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
var response Bounce
err := getResponseFromJSON(ctx, r, &response)
return response, e... | csn |
Get all parameters defined as public static fields in the given type.
@param type Type
@return Set of parameters | private static Set<Parameter<?>> getParametersFromPublicFields(Class<?> type) {
Set<Parameter<?>> params = new HashSet<>();
try {
Field[] fields = type.getFields();
for (Field field : fields) {
if (field.getType().isAssignableFrom(Parameter.class)) {
params.add((Parameter<?>)field.... | csn |
All the unique types found in user supplied model | def types(self):
"""All the unique types found in user supplied model"""
res = []
for column in self.column_definitions:
tmp = column.get('type', None)
res.append(ModelCompiler.get_column_type(tmp)) if tmp else False
res = list(set(res))
return res | csn |
// NewInitModeFromType returns an InitMode object corresponding to the
// given type. | func NewInitModeFromType(t InitModeType) InitMode {
switch t {
case InitDefault:
return modeDefault{}
case InitMinimal:
return modeMinimal{}
case InitSingleOp:
return modeSingleOp{modeDefault{}}
case InitConstrained:
return modeConstrained{modeDefault{}}
case InitMemoryLimited:
return modeMemoryLimited{... | csn |
Return a SDIV instruction. | def gen_sdiv(src1, src2, dst):
"""Return a SDIV instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.SDIV, src1, src2, dst) | csn |
MOTD is missing. | async def on_raw_422(self, message):
""" MOTD is missing. """
await self._registration_completed(message)
self.motd = None
await self.on_connect() | csn |
Checks a field signature.
@param signature
a string containing the signature that must be checked. | public static void checkFieldSignature(final String signature) {
int pos = checkFieldTypeSignature(signature, 0);
if (pos != signature.length()) {
throw new IllegalArgumentException(signature + ": error at index "
+ pos);
}
} | csn |
//RegisterMocker puts mocker to the list of controller mockers | func (c *Controller) RegisterMocker(m Mocker) {
c.Lock()
c.mockers = append(c.mockers, m)
c.Unlock()
} | csn |
Given a region code, try to find a region that matches it, using replacements, disambiguation, indexes and other wizardry.
@private
@param {RegionProvider} regionProvider The RegionProvider instance.
@param {String} code Code to search for. Falsy codes return -1.
@returns {Number} Zero-based index in list of regions if... | function findRegionIndex(regionProvider, code, disambigCode) {
if (!defined(code) || code === "") {
// Note a code of 0 is ok
return -1;
}
var processedCode = applyReplacements(
regionProvider,
code,
"dataReplacements"
);
var id = regionProvider._idIndex[processedCode];
if (!defined(id))... | csn |
Return ESCoreEndpoint instance from endpoint string
:param inline: Endpoint string
:return: | def from_inline(cls: Type[ESCoreEndpointType], inline: str) -> ESCoreEndpointType:
"""
Return ESCoreEndpoint instance from endpoint string
:param inline: Endpoint string
:return:
"""
m = ESCoreEndpoint.re_inline.match(inline)
if m is None:
raise Malfo... | csn |
// RemoveSection removes a section from the configuration.
// It returns true if the section was removed, and false if section did not exist. | func (self *Config) RemoveSection(section string) bool {
_, ok := self.data[section]
// Default section cannot be removed.
if !ok || section == _DEFAULT_SECTION {
return false
}
for o, _ := range self.data[section] {
delete(self.data[section], o) // *value
}
delete(self.data, section)
delete(self.lastIdO... | csn |
Adds an event handler to a DOM node ensuring cross-browser compatibility.
@param {Node} node The DOM node to add the event handler to.
@param {string} event The event name.
@param {Function} fn The event handler to add.
@param {boolean} opt_useCapture Optionally adds the even to the capture
phase. Note: this only works... | function addEvent(node, event, fn, opt_useCapture) {
if (typeof node.addEventListener == 'function') {
node.addEventListener(event, fn, opt_useCapture || false);
}
else if (typeof node.attachEvent == 'function') {
node.attachEvent('on' + event, fn);
}
} | csn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.