comment
stringlengths 16
255
| code
stringlengths 52
3.87M
|
---|---|
// Value returns the value of the Coin
|
func (c *SimpleCoin) Value() btcutil.Amount {
return btcutil.Amount(c.txOut().Value)
}
|
Set XML property or method argument value.
@param string $value
@param \DOMElement $node
@param ClassMetadata[] $classesMetadata
|
protected function setAttribute(string $value, \DOMElement $node, array $classesMetadata)
{
if (array_key_exists($value, $classesMetadata)) {
$node->setAttribute('service', $value);
} elseif (class_exists($value)) {
$node->setAttribute('class', $value);
} else {
$node->setAttribute('value', $value);
}
}
|
Get valid string length
@param string $string Some string
@return int
|
protected function _strlen($string)
{
$encoding = function_exists('mb_detect_encoding') ? mb_detect_encoding($string) : false;
return $encoding ? mb_strlen($string, $encoding) : strlen($string);
}
|
Marshall the given parameter object.
|
public void marshall(ImportCatalogToGlueRequest importCatalogToGlueRequest, ProtocolMarshaller protocolMarshaller) {
if (importCatalogToGlueRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(importCatalogToGlueRequest.getCatalogId(), CATALOGID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
|
Send "insert" etc. command, returning response as a dict.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `request_id`: an int.
- `msg`: bytes, the command message.
|
def write_command(self, request_id, msg):
self.send_message(msg, 0)
reply = self.receive_message(request_id)
result = reply.command_response()
# Raises NotMasterError or OperationFailure.
helpers._check_command_response(result)
return result
|
Returns a copy of d with compressed leaves.
|
def compress(self, d=DEFAULT):
""""""
if d is DEFAULT:
d = self
if isinstance(d, list):
l = [v for v in (self.compress(v) for v in d)]
try:
return list(set(l))
except TypeError:
# list contains not hashables
ret = []
for i in l:
if i not in ret:
ret.append(i)
return ret
elif isinstance(d, type(self)):
return type(self)({k: v for k, v in ((k, self.compress(v)) for k, v in d.items())})
elif isinstance(d, dict):
return {k: v for k, v in ((k, self.compress(v)) for k, v in d.items())}
return d
|
Returns all the {@link JavaClassSource} objects from the given {@link Project}
|
public List<JavaResource> getProjectClasses(Project project)
{
final List<JavaResource> classes = new ArrayList<>();
if (project != null)
{
project.getFacet(JavaSourceFacet.class).visitJavaSources(new JavaClassSourceVisitor(classes));
}
return classes;
}
|
// SetGroupMemberList sets the GroupMemberList field's value.
|
func (s *ListGroupMembershipsOutput) SetGroupMemberList(v []*GroupMember) *ListGroupMembershipsOutput {
s.GroupMemberList = v
return s
}
|
// GameControllerAddMapping adds support for controllers that SDL is unaware of or to cause an existing controller to have a different binding.
// (https://wiki.libsdl.org/SDL_GameControllerAddMapping)
|
func GameControllerAddMapping(mappingString string) int {
_mappingString := C.CString(mappingString)
defer C.free(unsafe.Pointer(_mappingString))
return int(C.SDL_GameControllerAddMapping(_mappingString))
}
|
update spectating coordinates in "spectate" mode
|
function(client, packet) {
var x = packet.readFloat32LE();
var y = packet.readFloat32LE();
var zoom = packet.readFloat32LE();
if(client.debug >= 4)
client.log('spectate FOV update: x=' + x + ' y=' + y + ' zoom=' + zoom);
client.emitEvent('spectateFieldUpdate', x, y, zoom);
}
|
Validate label and its shape.
|
def _check_valid_label(self, label):
""""""
if len(label.shape) != 2 or label.shape[1] < 5:
msg = "Label with shape (1+, 5+) required, %s received." % str(label)
raise RuntimeError(msg)
valid_label = np.where(np.logical_and(label[:, 0] >= 0, label[:, 3] > label[:, 1],
label[:, 4] > label[:, 2]))[0]
if valid_label.size < 1:
raise RuntimeError('Invalid label occurs.')
|
<pre>
Use this operation to enable/disable ntpd.
</pre>
|
public static ntp_sync update(nitro_service client, ntp_sync resource) throws Exception
{
resource.validate("modify");
return ((ntp_sync[]) resource.update_resource(client))[0];
}
|
This function sanitize the user given field and return a common Array structure field
list
@param {DataModel} dataModel the dataModel operating on
@param {Array} fieldArr user input of field Array
@return {Array} arrays of field name
|
function getFieldArr (dataModel, fieldArr) {
const retArr = [];
const fieldStore = dataModel.getFieldspace();
const dimensions = fieldStore.getDimension();
Object.entries(dimensions).forEach(([key]) => {
if (fieldArr && fieldArr.length) {
if (fieldArr.indexOf(key) !== -1) {
retArr.push(key);
}
} else {
retArr.push(key);
}
});
return retArr;
}
|
// Get returns value for the given key.
|
func (r *RedisStore) Get(key string) (interface{}, error) {
cmd := redis.NewCmd("get", key)
if err := r.client.Process(cmd); err != nil {
if err == redis.Nil {
return nil, nil
}
return nil, err
}
return cmd.Val(), cmd.Err()
}
|
Return all tags found in the value stream.
Returns:
A `{tagType: ['list', 'of', 'tags']}` dictionary.
|
def Tags(self):
return {
TENSORS: list(self.tensors_by_tag.keys()),
# Use a heuristic: if the metagraph is available, but
# graph is not, then we assume the metagraph contains the graph.
GRAPH: self._graph is not None,
META_GRAPH: self._meta_graph is not None,
RUN_METADATA: list(self._tagged_metadata.keys())
}
|
// Source returns serializable JSON of the TermsOrder.
|
func (order *TermsOrder) Source() (interface{}, error) {
source := make(map[string]string)
if order.Ascending {
source[order.Field] = "asc"
} else {
source[order.Field] = "desc"
}
return source, nil
}
|
// Minify minifies SVG data, it reads from r and writes to w.
|
func (o *Minifier) Minify(m *minify.M, w io.Writer, r io.Reader, _ map[string]string) error {
var tag svg.Hash
defaultStyleType := cssMimeBytes
defaultStyleParams := map[string]string(nil)
defaultInlineStyleParams := map[string]string{"inline": "1"}
p := NewPathData(o)
minifyBuffer := buffer.NewWriter(make([]byte, 0, 64))
attrByteBuffer := make([]byte, 0, 64)
l := xml.NewLexer(r)
defer l.Restore()
tb := NewTokenBuffer(l)
for {
t := *tb.Shift()
switch t.TokenType {
case xml.ErrorToken:
if l.Err() == io.EOF {
return nil
}
return l.Err()
case xml.DOCTYPEToken:
if len(t.Text) > 0 && t.Text[len(t.Text)-1] == ']' {
if _, err := w.Write(t.Data); err != nil {
return err
}
}
case xml.TextToken:
t.Data = parse.ReplaceMultipleWhitespace(parse.TrimWhitespace(t.Data))
if tag == svg.Style && len(t.Data) > 0 {
if err := m.MinifyMimetype(defaultStyleType, w, buffer.NewReader(t.Data), defaultStyleParams); err != nil {
if err != minify.ErrNotExist {
return err
} else if _, err := w.Write(t.Data); err != nil {
return err
}
}
} else if _, err := w.Write(t.Data); err != nil {
return err
}
case xml.CDATAToken:
if tag == svg.Style {
minifyBuffer.Reset()
if err := m.MinifyMimetype(defaultStyleType, minifyBuffer, buffer.NewReader(t.Text), defaultStyleParams); err == nil {
t.Data = append(t.Data[:9], minifyBuffer.Bytes()...)
t.Text = t.Data[9:]
t.Data = append(t.Data, cdataEndBytes...)
} else if err != minify.ErrNotExist {
return err
}
}
var useText bool
if t.Text, useText = xml.EscapeCDATAVal(&attrByteBuffer, t.Text); useText {
t.Text = parse.ReplaceMultipleWhitespace(parse.TrimWhitespace(t.Text))
if _, err := w.Write(t.Text); err != nil {
return err
}
} else if _, err := w.Write(t.Data); err != nil {
return err
}
case xml.StartTagPIToken:
for {
if t := *tb.Shift(); t.TokenType == xml.StartTagClosePIToken || t.TokenType == xml.ErrorToken {
break
}
}
case xml.StartTagToken:
tag = t.Hash
if tag == svg.Metadata {
skipTag(tb)
break
} else if tag == svg.Line {
o.shortenLine(tb, &t, p)
} else if tag == svg.Rect && !o.shortenRect(tb, &t, p) {
skipTag(tb)
break
} else if tag == svg.Polygon || tag == svg.Polyline {
o.shortenPoly(tb, &t, p)
}
if _, err := w.Write(t.Data); err != nil {
return err
}
case xml.AttributeToken:
if len(t.AttrVal) == 0 || t.Text == nil { // data is nil when attribute has been removed
continue
}
attr := t.Hash
val := t.AttrVal
if n, m := parse.Dimension(val); n+m == len(val) && attr != svg.Version { // TODO: inefficient, temporary measure
val, _ = o.shortenDimension(val)
}
if attr == svg.Xml_Space && bytes.Equal(val, []byte("preserve")) ||
tag == svg.Svg && (attr == svg.Version && bytes.Equal(val, []byte("1.1")) ||
attr == svg.X && bytes.Equal(val, []byte("0")) ||
attr == svg.Y && bytes.Equal(val, []byte("0")) ||
attr == svg.Width && bytes.Equal(val, []byte("100%")) ||
attr == svg.Height && bytes.Equal(val, []byte("100%")) ||
attr == svg.PreserveAspectRatio && bytes.Equal(val, []byte("xMidYMid meet")) ||
attr == svg.BaseProfile && bytes.Equal(val, []byte("none")) ||
attr == svg.ContentScriptType && bytes.Equal(val, []byte("application/ecmascript")) ||
attr == svg.ContentStyleType && bytes.Equal(val, []byte("text/css"))) ||
tag == svg.Style && attr == svg.Type && bytes.Equal(val, []byte("text/css")) {
continue
}
if _, err := w.Write(spaceBytes); err != nil {
return err
}
if _, err := w.Write(t.Text); err != nil {
return err
}
if _, err := w.Write(isBytes); err != nil {
return err
}
if tag == svg.Svg && attr == svg.ContentStyleType {
val = minify.Mediatype(val)
defaultStyleType = val
} else if attr == svg.Style {
minifyBuffer.Reset()
if err := m.MinifyMimetype(defaultStyleType, minifyBuffer, buffer.NewReader(val), defaultInlineStyleParams); err == nil {
val = minifyBuffer.Bytes()
} else if err != minify.ErrNotExist {
return err
}
} else if attr == svg.D {
val = p.ShortenPathData(val)
} else if attr == svg.ViewBox {
j := 0
newVal := val[:0]
for i := 0; i < 4; i++ {
if i != 0 {
if j >= len(val) || val[j] != ' ' && val[j] != ',' {
newVal = append(newVal, val[j:]...)
break
}
newVal = append(newVal, ' ')
j++
}
if dim, n := o.shortenDimension(val[j:]); n > 0 {
newVal = append(newVal, dim...)
j += n
} else {
newVal = append(newVal, val[j:]...)
break
}
}
val = newVal
} else if colorAttrMap[attr] && len(val) > 0 && (len(val) < 5 || !parse.EqualFold(val[:4], urlBytes)) {
parse.ToLower(val)
if val[0] == '#' {
if name, ok := minifyCSS.ShortenColorHex[string(val)]; ok {
val = name
} else if len(val) == 7 && val[1] == val[2] && val[3] == val[4] && val[5] == val[6] {
val[2] = val[3]
val[3] = val[5]
val = val[:4]
}
} else if hex, ok := minifyCSS.ShortenColorName[css.ToHash(val)]; ok {
val = hex
// } else if len(val) > 5 && bytes.Equal(val[:4], []byte("rgb(")) && val[len(val)-1] == ')' {
// TODO: handle rgb(x, y, z) and hsl(x, y, z)
}
}
// prefer single or double quotes depending on what occurs more often in value
val = xml.EscapeAttrVal(&attrByteBuffer, val)
if _, err := w.Write(val); err != nil {
return err
}
case xml.StartTagCloseToken:
next := tb.Peek(0)
skipExtra := false
if next.TokenType == xml.TextToken && parse.IsAllWhitespace(next.Data) {
next = tb.Peek(1)
skipExtra = true
}
if next.TokenType == xml.EndTagToken {
// collapse empty tags to single void tag
tb.Shift()
if skipExtra {
tb.Shift()
}
if _, err := w.Write(voidBytes); err != nil {
return err
}
} else {
if _, err := w.Write(t.Data); err != nil {
return err
}
}
case xml.StartTagCloseVoidToken:
tag = 0
if _, err := w.Write(t.Data); err != nil {
return err
}
case xml.EndTagToken:
tag = 0
if len(t.Data) > 3+len(t.Text) {
t.Data[2+len(t.Text)] = '>'
t.Data = t.Data[:3+len(t.Text)]
}
if _, err := w.Write(t.Data); err != nil {
return err
}
}
}
}
|
Declarative Services method for unsetting the connection manager service reference
@param ref reference to the service
|
protected void unsetConnectionManager(ServiceReference<ConnectionManagerService> ref) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(this, tc, "unsetConnectionManager", ref);
}
|
Filter out optional query parameters with no value provided in request data
@private
@param {json} data Generated Data
@returns {json} return all the properties information
|
function filterOutOptionalQueryParams(data) {
data.queryParameters = data.queryParameters.filter(function(queryParam) {
// Let's be conservative and treat params without explicit required field as not-optional
var optional = queryParam.required !== undefined && !queryParam.required;
var dataProvided = data.requestParameters.hasOwnProperty(queryParam.name);
return !optional || dataProvided;
});
return data;
}
|
// Del removes a section or key from Ini returning whether or not it did.
// Set the key to an empty string to remove a section.
|
func (ini *INI) Del(section, key string) bool {
// Remove the section.
if key == "" {
if section == "" {
ini.global = iniSection{}
return true
}
return ini.rmSection(section)
}
// Remove the key for the section.
return ini.getSection(section).rmItem(key, ini.isCaseSensitive)
}
|
http://bookofzeus.com/articles/convert-simplexml-object-into-php-array/
Convert a simpleXMLElement in to an array
@todo this is duplicated from CIMAbstractResponse. Put somewhere shared.
@param \SimpleXMLElement $xml
@return array
|
public function xml2array(\SimpleXMLElement $xml)
{
$arr = array();
foreach ($xml as $element) {
$tag = $element->getName();
$e = get_object_vars($element);
if (!empty($e)) {
$arr[$tag][] = $element instanceof \SimpleXMLElement ? $this->xml2array($element) : $e;
} else {
$arr[$tag] = trim($element);
}
}
return $arr;
}
|
// parseAlterRetentionPolicyStatement parses a string and returns an alter retention policy statement.
// This function assumes the ALTER RETENTION POLICY tokens have already been consumed.
|
func (p *Parser) parseAlterRetentionPolicyStatement() (*AlterRetentionPolicyStatement, error) {
stmt := &AlterRetentionPolicyStatement{}
// Parse the retention policy name.
tok, pos, lit := p.ScanIgnoreWhitespace()
if tok == DEFAULT {
stmt.Name = "default"
} else if tok == IDENT {
stmt.Name = lit
} else {
return nil, newParseError(tokstr(tok, lit), []string{"identifier"}, pos)
}
// Consume the required ON token.
if tok, pos, lit = p.ScanIgnoreWhitespace(); tok != ON {
return nil, newParseError(tokstr(tok, lit), []string{"ON"}, pos)
}
// Parse the database name.
ident, err := p.ParseIdent()
if err != nil {
return nil, err
}
stmt.Database = ident
// Loop through option tokens (DURATION, REPLICATION, SHARD DURATION, DEFAULT, etc.).
found := make(map[Token]struct{})
Loop:
for {
tok, pos, lit := p.ScanIgnoreWhitespace()
if _, ok := found[tok]; ok {
return nil, &ParseError{
Message: fmt.Sprintf("found duplicate %s option", tok),
Pos: pos,
}
}
switch tok {
case DURATION:
d, err := p.ParseDuration()
if err != nil {
return nil, err
}
stmt.Duration = &d
case REPLICATION:
n, err := p.ParseInt(1, math.MaxInt32)
if err != nil {
return nil, err
}
stmt.Replication = &n
case SHARD:
tok, pos, lit := p.ScanIgnoreWhitespace()
if tok == DURATION {
// Check to see if they used the INF keyword
tok, pos, _ := p.ScanIgnoreWhitespace()
if tok == INF {
return nil, &ParseError{
Message: "invalid duration INF for shard duration",
Pos: pos,
}
}
p.Unscan()
d, err := p.ParseDuration()
if err != nil {
return nil, err
}
stmt.ShardGroupDuration = &d
} else {
return nil, newParseError(tokstr(tok, lit), []string{"DURATION"}, pos)
}
case DEFAULT:
stmt.Default = true
default:
if len(found) == 0 {
return nil, newParseError(tokstr(tok, lit), []string{"DURATION", "REPLICATION", "SHARD", "DEFAULT"}, pos)
}
p.Unscan()
break Loop
}
found[tok] = struct{}{}
}
return stmt, nil
}
|
Checks to see if the current user object is registered. If so, it queries that records
default language. Otherwise, it falls back to sitewide settings.
@return string
|
public function getUserLanguageToDisplay()
{
if ($this->getUserDefaultLanguage() != '') {
return $this->getUserDefaultLanguage();
} else {
$app = Application::getFacadeApplication();
$config = $app['config'];
return $config->get('concrete.locale');
}
}
|
Returns an array of field values
@return array
|
protected function getListFieldValue()
{
$id = $this->getParam(0);
if (!isset($id)) {
return $this->field_value->getList(array('limit' => $this->getLimit()));
}
if ($this->getParam('field')) {
return $this->field_value->getList(array('field_id' => $id, 'limit' => $this->getLimit()));
}
if (!is_numeric($id)) {
$this->errorAndExit($this->text('Invalid argument'));
}
$result = $this->field_value->get($id);
if (empty($result)) {
$this->errorAndExit($this->text('Unexpected result'));
}
return array($result);
}
|
Add a new review
|
protected function addReview()
{
if (!$this->isError()) {
$id = $this->review->add($this->getSubmitted());
if (empty($id)) {
$this->errorAndExit($this->text('Unexpected result'));
}
$this->line($id);
}
}
|
Delete -------------
|
public function delete( $model, $config = [] ) {
// Delete files
$this->fileService->deleteMultiple( [ $model->avatar, $model->banner, $model->video ] );
$this->fileService->deleteMultiple( $model->files );
// Delete File Mappings - Shared Files
$this->modelFileService->deleteMultiple( $model->modelFiles );
// Delete mapping
Yii::$app->factory->get( 'modelObjectService' )->deleteByModelId( $model->id );
// Delete model
return parent::delete( $model, $config );
}
|
elem = a graphic element will have an attribute like marker-start attr - marker-start, marker-mid, or marker-end returns the marker element that is linked to the graphic element
|
function getLinked(elem, attr) {
var str = elem.getAttribute(attr);
if(!str) {return null;}
var m = str.match(/\(\#(.*)\)/);
if(!m || m.length !== 2) {
return null;
}
return S.getElem(m[1]);
}
|
Free all the child sFields.
@param bIncludeToolScreens If true, also free the toolScreens.
|
public void freeAllSFields(boolean bIncludeToolScreens)
{
int iToolScreens = 0;
while (this.getSFieldCount() > iToolScreens)
{ // First, get rid of all child screens.
ScreenField sField = this.getSField(iToolScreens);
if ((!bIncludeToolScreens) && (sField instanceof ToolScreen))
iToolScreens++;
else
sField.free();
}
}
|
If the entry is being prepopulated, we may want to filter other views by this entry's
value. This function will create that filter query string.
@since Symphony 2.5.2
@return string
|
public function getFilterString()
{
$filter_querystring = '';
if (isset($_REQUEST['prepopulate']) && is_array($_REQUEST['prepopulate'])) {
foreach ($_REQUEST['prepopulate'] as $field_id => $value) {
$handle = FieldManager::fetchHandleFromID($field_id);
// Properly decode and re-encode value for output
$value = rawurlencode(rawurldecode($value));
$filter_querystring .= sprintf('filter[%s]=%s&', $handle, $value);
}
$filter_querystring = trim($filter_querystring, '&');
}
// This is to prevent the value being interpreted as an additional GET
// parameter. eg. filter[cat]=Minx&June, would come through as:
// $_GET['cat'] = Minx
// $_GET['June'] = ''
$filter_querystring = preg_replace("/&$/", '', $filter_querystring);
return $filter_querystring ? '?' . $filter_querystring : null;
}
|
Prepare the validator.
@param \Asgard\Validation\ValidatorInterface $validator
@param array $locales
@return \Asgard\Validation\ValidatorInterface
|
public function prepareValidator(\Asgard\Validation\ValidatorInterface $validator, array $locales=[]) {
$this->getDefinition()->trigger('validation', [$this, $validator], function($chain, $entity, $validator) use($locales) {
$messages = [];
foreach($this->getDefinition()->properties() as $name=>$property) {
if($locales && $property->get('i18n')) {
foreach($locales as $locale) {
if($property->get('many')) {
if($this->get($name, null, false) instanceof ManyCollection) {
foreach($this->get($name, null, false) as $k=>$v) {
$propValidator = $validator->attribute($name.'.'.$locale.'.'.$k);
$property->prepareValidator($propValidator);
$propValidator->formatParameters(function(&$params) use($name) {
$params['attribute'] = $name;
});
$propValidator->ruleMessages($property->getMessages());
}
}
}
else {
$propValidator = $validator->attribute($name.'.'.$locale);
$property->prepareValidator($propValidator);
$propValidator->formatParameters(function(&$params) use($name) {
$params['attribute'] = $name;
});
$propValidator->ruleMessages($property->getMessages());
}
}
}
else {
if($property->get('many')) {
if($this->get($name, null, false) instanceof ManyCollection) {
foreach($this->get($name, null, false) as $k=>$v) {
$propValidator = $validator->attribute($name.'.'.$k);
$property->prepareValidator($propValidator);
$propValidator->formatParameters(function(&$params) use($name) {
$params['attribute'] = $name;
});
$propValidator->ruleMessages($property->getMessages());
}
}
}
else {
$propValidator = $validator->attribute($name);
$property->prepareValidator($propValidator);
$propValidator->ruleMessages($property->getMessages());
}
}
}
$messages = array_merge($messages, $this->getDefinition()->messages());
$validator->attributesMessages($messages);
$validator->set('entity', $this);
});
return $validator;
}
|
Return a format string for printing an `expr_type`
ket/bra/ketbra/braket
|
def _braket_fmt(self, expr_type):
""""""
if self._settings['unicode_sub_super']:
sub_sup_fmt = SubSupFmt
else:
sub_sup_fmt = SubSupFmtNoUni
mapping = {
'bra': {
True: sub_sup_fmt('⟨{label}|', sup='({space})'),
'subscript': sub_sup_fmt('⟨{label}|', sub='({space})'),
False: sub_sup_fmt('⟨{label}|')},
'ket': {
True: sub_sup_fmt('|{label}⟩', sup='({space})'),
'subscript': sub_sup_fmt('|{label}⟩', sub='({space})'),
False: sub_sup_fmt('|{label}⟩')},
'ketbra': {
True: sub_sup_fmt('|{label_i}⟩⟨{label_j}|', sup='({space})'),
'subscript': sub_sup_fmt(
'|{label_i}⟩⟨{label_j}|', sub='({space})'),
False: sub_sup_fmt('|{label_i}⟩⟨{label_j}|')},
'braket': {
True: sub_sup_fmt('⟨{label_i}|{label_j}⟩', sup='({space})'),
'subscript': sub_sup_fmt(
'⟨{label_i}|{label_j}⟩', sub='({space})'),
False: sub_sup_fmt('⟨{label_i}|{label_j}⟩')},
}
hs_setting = bool(self._settings['show_hs_label'])
if self._settings['show_hs_label'] == 'subscript':
hs_setting = 'subscript'
return mapping[expr_type][hs_setting]
|
Escape special characters in HTML
|
def escape(self, text, quote = True):
if isinstance(text, bytes):
return escape_b(text, quote)
else:
return escape(text, quote)
|
Returns the URL for the given model and admin url name.
|
def admin_url(model, url, object_id=None):
opts = model._meta
url = "admin:%s_%s_%s" % (opts.app_label, opts.object_name.lower(), url)
args = ()
if object_id is not None:
args = (object_id,)
return reverse(url, args=args)
|
getEndTag - returns the end tag representation as HTML string
@return - String of end tag
|
def getEndTag(self):
'''
'''
# If this is a self-closing tag, we have no end tag (opens and closes in the start)
if self.isSelfClosing is True:
return ''
tagName = self.tagName
# Do not add any indentation to the end of preformatted tags.
if self._indent and tagName in PREFORMATTED_TAGS:
return "</%s>" %(tagName, )
# Otherwise, indent the end of this tag
return "%s</%s>" %(self._indent, tagName)
|
//Each runs through the function lists and executing with args
|
func (f *ListenerStack) Each(d Event) {
if f.Size() <= 0 {
return
}
f.lock.RLock()
// var ro sync.Mutex
var stop bool
for _, fx := range f.listeners {
if stop {
break
}
//TODO: is this critical that we send it into a goroutine with a mutex?
fx(d, func() {
// ro.Lock()
stop = true
// ro.Unlock()
})
}
f.lock.RUnlock()
}
|
Gets the type for a property setter.
@param name the name of the property
@return the Class of the property setter
@throws NoSuchMethodException when a setter method cannot be found
|
public Class<?> getSetterType(String name) throws NoSuchMethodException {
Class<?> type = setterTypes.get(name);
if (type == null) {
throw new NoSuchMethodException("There is no WRITABLE property named '" + name +
"' in class '" + className + "'");
}
return type;
}
|
// EjectIso removes the iso file based backing and replaces with the default cdrom backing.
|
func (l VirtualDeviceList) EjectIso(device *types.VirtualCdrom) *types.VirtualCdrom {
l.setDefaultCdromBacking(device)
return device
}
|
Helper function that handles creating the lower and upper bounds for calling {@link
SortedMap#subMap(Object, Object)}.
@see SortedMap#subMap(Object, Object)
|
private static <E> SortedMap<PrefixKey, E> getPrefixSubMap(
TreeMap<PrefixKey, E> map, PrefixKey lowerBound) {
PrefixKey upperBound =
new PrefixKey(lowerBound.getBucket(), lowerBound.getObjectName() + Character.MAX_VALUE);
return map.subMap(lowerBound, upperBound);
}
|
Returns the **real** type for the real or imaginary part of a **real** complex type.
For instance:
COMPLEX128_t -> FLOAT64_t
Args:
cysparse:
|
def cysparse_real_type_from_real_cysparse_complex_type(cysparse_type):
r_type = None
if cysparse_type in ['COMPLEX64_t']:
r_type = 'FLOAT32_t'
elif cysparse_type in ['COMPLEX128_t']:
r_type = 'FLOAT64_t'
elif cysparse_type in ['COMPLEX256_t']:
r_type = 'FLOAT128_t'
else:
raise TypeError("Not a recognized complex type")
return r_type
|
Invokes $fn with $args while managing our internal invocation context
in order to ensure our view of the test DSL's call graph is accurate.
|
public function invokeWithin($fn, $args = array())
{
$this->invocation_context->activate();
$this->invocation_context->push($this);
try {
$result = call_user_func_array($fn, $args);
$this->invocation_context->pop();
$this->invocation_context->deactivate();
return $result;
} catch (\Exception $e) {
$this->invocation_context->pop();
$this->invocation_context->deactivate();
throw $e;
}
}
|
// NewDefaultTrimaWithSrcLen creates a Triangular Moving Average Indicator (Trima) for offline usage with default parameters
|
func NewDefaultTrimaWithSrcLen(sourceLength uint) (indicator *Trima, err error) {
ind, err := NewDefaultTrima()
// only initialise the storage if there is enough source data to require it
if sourceLength-uint(ind.GetLookbackPeriod()) > 1 {
ind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod()))
}
return ind, err
}
|
Obtains all the tags assigned to this area and its child areas (not all descendant areas).
@return a set of tags
|
protected Set<Tag> getAllTags(Area area)
{
Set<Tag> ret = new HashSet<Tag>(area.getTags().keySet());
for (int i = 0; i < area.getChildCount(); i++)
ret.addAll(area.getChildAt(i).getTags().keySet());
return ret;
}
|
Answer a pending approval
:param issue_id_or_key: str
:param approval_id: str
:param decision: str
:return:
|
def answer_approval(self, issue_id_or_key, approval_id, decision):
url = 'rest/servicedeskapi/request/{0}/approval/{1}'.format(issue_id_or_key, approval_id)
data = {'decision': decision}
return self.post(url, headers=self.experimental_headers, data=data)
|
Encode the given object into a series of statements and expressions.
<p>
The implementation simply finds the <code>PersistenceDelegate</code> responsible for the object's class, and delegate the call to it.
</p>
@param o
the object to encode
|
protected void writeObject(Object o)
{
if (o == null)
{
return;
}
getPersistenceDelegate(o.getClass()).writeObject(o, this);
}
|
Store an item in the cache for a given number of minutes.
@param string $key
@param mixed $value
@param int $minutes
@return void
|
public function put($key, $value, $minutes) {
$this->cache[$key] = [
'value' => $value,
'ttl' => $this->getNow() + ($minutes * 60),
];
}
|
Retourne l'ann�e et mois format�s
@param integer $mmaaaa
@param string $format
@param string $separator default ' '
@return string
|
public static function getmoisanneemini($mmaaaa, $format = 'mm/aaaa', $separator = ' ')
{
$str = '';
switch ($format) {
case 'aaaamm':
$str = self::getmoismini(substr($mmaaaa, 4, 2)) . $separator . substr($mmaaaa, 0, 4);
break;
case 'mmaaaa':
$str = self::getmoismini(substr($mmaaaa, 0, 2)) . $separator . substr($mmaaaa, 2);
break;
case 'mm/aaaa':
$date = explode('/', $mmaaaa);
if ($date) {
$str = self::getmoismini($date[0]) . $separator . $date[1];
}
break;
}
return $str;
}
|
Parse and yield array items from the token stream.
|
def array_items(self, number_type, *, number_suffix=''):
""""""
for token in self.collect_tokens_until('CLOSE_BRACKET'):
is_number = token.type == 'NUMBER'
value = token.value.lower()
if not (is_number and value.endswith(number_suffix)):
raise self.error(f'Invalid {number_type} array element '
f'{token.value!r}')
yield int(value.replace(number_suffix, ''))
|
Build the transaction dictionary without sending
|
def buildTransaction(self, transaction=None):
if transaction is None:
built_transaction = {}
else:
built_transaction = dict(**transaction)
if 'data' in built_transaction:
raise ValueError("Cannot set data in build transaction")
if not self.address and 'to' not in built_transaction:
raise ValueError(
"When using `ContractFunction.buildTransaction` from a contract factory "
"you must provide a `to` address with the transaction"
)
if self.address and 'to' in built_transaction:
raise ValueError("Cannot set to in contract call build transaction")
if self.address:
built_transaction.setdefault('to', self.address)
if 'to' not in built_transaction:
raise ValueError(
"Please ensure that this contract instance has an address."
)
return build_transaction_for_function(
self.address,
self.web3,
self.function_identifier,
built_transaction,
self.contract_abi,
self.abi,
*self.args,
**self.kwargs
)
|
// Convert_image_ImageLayerData_To_v1_ImageLayerData is an autogenerated conversion function.
|
func Convert_image_ImageLayerData_To_v1_ImageLayerData(in *image.ImageLayerData, out *v1.ImageLayerData, s conversion.Scope) error {
return autoConvert_image_ImageLayerData_To_v1_ImageLayerData(in, out, s)
}
|
Apply a series of transformations defined as closures in the configuration file.
@param string $string
@return string
|
private function applyTransformers(string $string): string
{
foreach (Transformer::getAll() as $transformer) {
$string = $transformer($string);
}
return $string;
}
|
Return selector special pseudo class info (steps and other).
|
def extract_selector_info(sel):
""""""
# walk the parsed_tree, looking for pseudoClass selectors, check names
# add in steps and/or deferred extras
steps, extras = _extract_sel_info(sel.parsed_tree)
steps = sorted(set(steps))
extras = sorted(set(extras))
if len(steps) == 0:
steps = ['default']
return (steps, extras)
|
// SetGatewayARN sets the GatewayARN field's value.
|
func (s *DescribeVTLDevicesInput) SetGatewayARN(v string) *DescribeVTLDevicesInput {
s.GatewayARN = &v
return s
}
|
Retrieves the project start date. If an explicit start date has not been
set, this method calculates the start date by looking for
the earliest task start date.
@return project start date
|
public Date getStartDate()
{
Date result = (Date) getCachedValue(ProjectField.START_DATE);
if (result == null)
{
result = getParentFile().getStartDate();
}
return (result);
}
|
Merges and returns current query data with defined data and returns as query string
@param string $ns Target namespace (Group)
@param array $data Data to be merged
@param boolean $mark Whether to prepend question mark
@return string
|
public function getWithNsQuery($ns, array $data, $mark = true)
{
if ($this->hasQuery($ns)) {
$query = $this->getQuery($ns);
$url = null;
if ($mark === true) {
$url = '?';
}
$url .= http_build_query(array($ns => array_merge($query, $data)));
$url = str_replace('%25s', '%s', $url);
return $url;
} else {
return null;
}
}
|
Represent date and datetime objects as MATCH strings.
|
def _safe_match_date_and_datetime(graphql_type, expected_python_types, value):
""""""
# Python datetime.datetime is a subclass of datetime.date,
# but in this case, the two are not interchangeable.
# Rather than using isinstance, we will therefore check for exact type equality.
value_type = type(value)
if not any(value_type == x for x in expected_python_types):
raise GraphQLInvalidArgumentError(u'Expected value to be exactly one of '
u'python types {}, but was {}: '
u'{}'.format(expected_python_types, value_type, value))
# The serialize() method of GraphQLDate and GraphQLDateTime produces the correct
# ISO-8601 format that MATCH expects. We then simply represent it as a regular string.
try:
serialized_value = graphql_type.serialize(value)
except ValueError as e:
raise GraphQLInvalidArgumentError(e)
return _safe_match_string(serialized_value)
|
// GasTable returns the gas table corresponding to the current phase (homestead or homestead reprice).
//
// The returned GasTable's fields shouldn't, under any circumstances, be changed.
|
func (c *ChainConfig) GasTable(num *big.Int) GasTable {
if num == nil {
return GasTableHomestead
}
switch {
case c.IsConstantinople(num):
return GasTableConstantinople
case c.IsEIP158(num):
return GasTableEIP158
case c.IsEIP150(num):
return GasTableEIP150
default:
return GasTableHomestead
}
}
|
Register the bindings for the main JWTAuth class.
@return void
|
protected function registerJWTAuth()
{
$this->app->singleton('tymon.jwt.auth', function ($app) {
return (new JWTAuth(
$app['tymon.jwt.manager'],
$app['tymon.jwt.provider.auth'],
$app['tymon.jwt.parser']
))->lockSubject($this->config('lock_subject'));
});
}
|
If the prefix is a JSON string with key-value data, extract it as an
associative array. Otherwise return null.
@param mixed $prefix The raw prefix string.
@return null|array
|
private function extractPrefixKeyValueData($prefix)
{
$result = null;
// If it has key-value data, as evidenced by the raw prefix string
// being a JSON object (not JSON array), use it.
if (substr($prefix, 0, 1) === '{') {
if ($this->isJsonString($prefix)) {
$result = Json::decode($prefix);
}
}
return $result;
}
|
Finds all the snapshots in all the places we know of which could possibly
store snapshots, like command log snapshots, auto snapshots, etc.
@return All snapshots
|
private Map<String, Snapshot> getSnapshots() {
/*
* Use the individual snapshot directories instead of voltroot, because
* they can be set individually
*/
Map<String, SnapshotPathType> paths = new HashMap<String, SnapshotPathType>();
if (VoltDB.instance().getConfig().m_isEnterprise) {
if (m_clSnapshotPath != null) {
paths.put(m_clSnapshotPath, SnapshotPathType.SNAP_CL);
}
}
if (m_snapshotPath != null) {
paths.put(m_snapshotPath, SnapshotPathType.SNAP_AUTO);
}
HashMap<String, Snapshot> snapshots = new HashMap<String, Snapshot>();
FileFilter filter = new SnapshotUtil.SnapshotFilter();
for (String path : paths.keySet()) {
SnapshotUtil.retrieveSnapshotFiles(new File(path), snapshots, filter, false, paths.get(path), LOG);
}
return snapshots;
}
|
------------------------------------------------------------------------
|
private void serializeMasterState(MasterState state, DataOutputStream dos) throws IOException {
// magic number for error detection
dos.writeInt(MASTER_STATE_MAGIC_NUMBER);
// for safety, we serialize first into an array and then write the array and its
// length into the checkpoint
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final DataOutputStream out = new DataOutputStream(baos);
out.writeInt(state.version());
out.writeUTF(state.name());
final byte[] bytes = state.bytes();
out.writeInt(bytes.length);
out.write(bytes, 0, bytes.length);
out.close();
byte[] data = baos.toByteArray();
dos.writeInt(data.length);
dos.write(data, 0, data.length);
}
|
Call a RPC method.
return object: a result
|
def rpc_call(self, request, method=None, params=None, **kwargs):
args = []
kwargs = dict()
if isinstance(params, dict):
kwargs.update(params)
else:
args = list(as_tuple(params))
method_key = "{0}.{1}".format(self.scheme_name, method)
if method_key not in self.methods:
raise AssertionError("Unknown method: {0}".format(method))
method = self.methods[method_key]
if hasattr(method, 'request'):
args.insert(0, request)
return method(*args, **kwargs)
|
Transform reference catalog sky positions (self.all_radec)
to reference tangent plane (self.wcs) to create output X,Y positions.
|
def transformToRef(self):
if 'refxyunits' in self.pars and self.pars['refxyunits'] == 'pixels':
log.info('Creating RA/Dec positions for reference sources...')
self.outxy = np.column_stack([self.all_radec[0][:,np.newaxis],self.all_radec[1][:,np.newaxis]])
skypos = self.wcs.wcs_pix2world(self.all_radec[0],self.all_radec[1],self.origin)
self.all_radec[0] = skypos[0]
self.all_radec[1] = skypos[1]
else:
log.info('Converting RA/Dec positions of reference sources from "%s" to '%self.name+
'X,Y positions in reference WCS...')
self.refWCS = self.wcs
outxy = self.wcs.wcs_world2pix(self.all_radec[0],self.all_radec[1],self.origin)
# convert outxy list to a Nx2 array
self.outxy = np.column_stack([outxy[0][:,np.newaxis],outxy[1][:,np.newaxis]])
|
// Strings reflects over a structure and calls Parse when strings are located
|
func Strings(parser StringParser, obj interface{}) {
parsers := Parsers{
StringParser: parser,
}
parseRecursive(parsers, reflect.ValueOf(obj))
}
|
Recalculate dynamic property values
@param {any} entity Entity instance
@param {any} properties Entity's properties' configuration
@memberof EnTTExt
|
function recalculateAllDynamicProperties(entity, properties) {
// Find all dynamic properties
_lodash2.default.forEach(properties, function (propertyConfiguration, propertyName) {
if (isDynamicProperty(propertyConfiguration)) {
// Recalculate dynamic property value
var dynamicValue = propertyConfiguration.dynamic(entity);
// Set updated dynamic value (wrap into EnTTBypassEverythingValue to bypass read-only restriction)
entity[propertyName] = new _properties.EnTTBypassEverythingValue(dynamicValue);
}
});
}
|
Set twitterImage w/ proxy.
@param Image $twitterImage
@return PageSeo
|
public function setTwitterImage($twitterImage, $locale = null)
{
$this->translate($locale, false)->setTwitterImage($twitterImage);
$this->mergeNewTranslations();
return $this;
}
|
Notify a danger alert.
@param string $message
@param string|null $title
@param array $options
|
protected function notifyDanger($message, $title = null, array $options = [])
{
$this->notifyFlash($message, 'danger', $title, $options);
}
|
Tries to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"jira.py") if it can't be found.
|
def fetch_command(self, subcommand):
# Get commands outside of try block to prevent swallowing exceptions
commands = get_commands()
try:
app_name = commands[subcommand]
except KeyError:
# This might trigger ImproperlyConfigured (masked in get_commands)
settings.INSTALLED_APPS
sys.stderr.write("Unknown command: %r\nType '%s help' for usage.\n" %
(subcommand, self.prog_name))
sys.exit(1)
if isinstance(app_name, BaseCommand):
# If the command is already loaded, use it directly.
klass = app_name
else:
klass = load_command_class(app_name, subcommand)
return klass
|
Executes a command on the server and returns an array of string.
@param string $command Command to execute
@param string $target First parameter
@param string $value Second parameter
@return array The result of the command as an array of string
|
public function getStringArray($command, $target = null, $value = null)
{
$string = $this->getString($command, $target, $value);
$results = preg_split('/(?<!\\\),/', $string);
foreach ($results as &$result) {
$result = str_replace('\,', ',', $result);
}
return $results;
}
|
Setup WordPress conditions.
@param array $conditions
|
public function setConditions(array $conditions = [])
{
$config = $this->container->has('config') ? $this->container->make('config') : null;
if (! is_null($config)) {
$this->conditions = array_merge(
$config->get('app.conditions', []),
$conditions
);
} else {
$this->conditions = $conditions;
}
}
|
Ensure that the field counts match the validation rule counts.
@param array $data
|
private function check_fields(array $data)
{
$ruleset = $this->validation_rules();
$mismatch = array_diff_key($data, $ruleset);
$fields = array_keys($mismatch);
foreach ($fields as $field) {
$this->errors[] = array(
'field' => $field,
'value' => $data[$field],
'rule' => 'mismatch',
'param' => null,
);
}
}
|
Return a list of IR blocks with all Backtrack blocks removed.
|
def remove_backtrack_blocks_from_fold(folded_ir_blocks):
""""""
new_folded_ir_blocks = []
for block in folded_ir_blocks:
if not isinstance(block, Backtrack):
new_folded_ir_blocks.append(block)
return new_folded_ir_blocks
|
Generate header with module table entries for builtin modules.
:param List[(module_name, obj_module, enabled_define)] modules: module defs
:return: None
|
def generate_module_table_header(modules):
# Print header file for all external modules.
mod_defs = []
print("// Automatically generated by makemoduledefs.py.\n")
for module_name, obj_module, enabled_define in modules:
mod_def = "MODULE_DEF_{}".format(module_name.upper())
mod_defs.append(mod_def)
print((
"#if ({enabled_define})\n"
" extern const struct _mp_obj_module_t {obj_module};\n"
" #define {mod_def} {{ MP_ROM_QSTR({module_name}), MP_ROM_PTR(&{obj_module}) }},\n"
"#else\n"
" #define {mod_def}\n"
"#endif\n"
).format(module_name=module_name, obj_module=obj_module,
enabled_define=enabled_define, mod_def=mod_def)
)
print("\n#define MICROPY_REGISTERED_MODULES \\")
for mod_def in mod_defs:
print(" {mod_def} \\".format(mod_def=mod_def))
print("// MICROPY_REGISTERED_MODULES")
|
Builds a property transform from a kernel and some options
@param kernel The transform kernel
@param options Some options regarding the property transform
|
function buildPropertyTransform(kernel, options = {}) {
if (options.splitArrays == null)
options.splitArrays = true;
if (options.neverSkip == null)
options.neverSkip = false;
const ret = kernel;
ret.splitArrays = options.splitArrays;
ret.neverSkip = options.neverSkip;
return ret;
}
|
LOWER LEVEL INDEX OPERATIONS
|
def with_index(new_index) # :yields: new_index
old_index = @index
set_index(new_index, false)
return_value = yield @index
set_index(old_index)
return_value
end
|
Loads project data by namespace:name
@param string $project_name namespace:name
@return \stdClass
@throws \Exception
|
protected function getByName($project_name) {
if (!strstr($project_name, ":")) {
throw (new \Exception("You must search for project with namespace: prefix"));
}
$parts = explode(':', $project_name);
$projects = $this->_client->get('/projects/search/' . urlencode($parts[1]));
$found_project = false;
foreach ($projects as $project) {
if (preg_match("~^" . $parts[0] . "$~", $project->namespace->name)) {
return $project;
}
}
if (!$found_project) {
return false;
}
}
|
Validates subscription data before creating Outbound message
|
def post(self, request, *args, **kwargs):
schedule_disable.delay(kwargs["subscription_id"])
return Response({"accepted": True}, status=201)
|
If this node is newly selected, scroll it into view. Also, move the selection or
context boxes as appropriate.
|
function (prevProps, prevState) {
var wasSelected = prevProps.entry.get("selected"),
isSelected = this.props.entry.get("selected");
if (isSelected && !wasSelected) {
// TODO: This shouldn't really know about project-files-container
// directly. It is probably the case that our Preact tree should actually
// start with project-files-container instead of just the interior of
// project-files-container and then the file tree will be one self-contained
// functional unit.
ViewUtils.scrollElementIntoView($("#project-files-container"), $(Preact.findDOMNode(this)), true);
} else if (!isSelected && wasSelected && this.state.clickTimer !== null) {
this.clearTimer();
}
}
|
// CapFromCenterHeight constructs a cap with the given center and height. A
// negative height yields an empty cap; a height of 2 or more yields a full cap.
// The center should be unit length.
|
func CapFromCenterHeight(center Point, height float64) Cap {
return CapFromCenterChordAngle(center, s1.ChordAngleFromSquaredLength(2*height))
}
|
Get valid user attempts that match the given request and credentials.
|
def get_user_attempts(request: AxesHttpRequest, credentials: dict = None) -> QuerySet:
attempts = filter_user_attempts(request, credentials)
if settings.AXES_COOLOFF_TIME is None:
log.debug('AXES: Getting all access attempts from database because no AXES_COOLOFF_TIME is configured')
return attempts
threshold = get_cool_off_threshold(request.axes_attempt_time)
log.debug('AXES: Getting access attempts that are newer than %s', threshold)
return attempts.filter(attempt_time__gte=threshold)
|
Remove all of the event listeners for the model.
@return void
|
public static function flushEventListeners()
{
if (! isset(static::$dispatcher)) {
return;
}
$instance = new static;
foreach ($instance->getObservableEvents() as $event) {
static::$dispatcher->forget("eloquent.{$event}: ".static::class);
}
foreach (array_values($instance->dispatchesEvents) as $event) {
static::$dispatcher->forget($event);
}
}
|
// SetShippingOption sets the ShippingOption field's value.
|
func (s *UpdateClusterInput) SetShippingOption(v string) *UpdateClusterInput {
s.ShippingOption = &v
return s
}
|
Raise the given event.
@param object $event
@return void
|
protected function raise($event)
{
$qualified = get_class($event);
$name = str_replace('\\', '.', $qualified);
$this->events->fire($name, [$event]);
}
|
Adds the main file definitions from the root package.
@param Config $config
@param PackageInterface $package
@param string $section
@return PackageInterface
|
public static function addMainFiles(Config $config, PackageInterface $package, $section = 'main-files')
{
if ($package instanceof Package) {
$packageExtra = $package->getExtra();
$rootMainFiles = $config->getArray($section);
foreach ($rootMainFiles as $packageName => $files) {
if ($packageName === $package->getName()) {
$packageExtra['bower-asset-main'] = $files;
break;
}
}
$package->setExtra($packageExtra);
}
return $package;
}
|
Return dict of extra fields added to the historical record model
|
def get_extra_fields(self, model, fields):
""""""
def revert_url(self):
"""URL for this change in the default admin site."""
opts = model._meta
app_label, model_name = opts.app_label, opts.model_name
return reverse(
"%s:%s_%s_simple_history" % (admin.site.name, app_label, model_name),
args=[getattr(self, opts.pk.attname), self.history_id],
)
def get_instance(self):
attrs = {
field.attname: getattr(self, field.attname) for field in fields.values()
}
if self._history_excluded_fields:
excluded_attnames = [
model._meta.get_field(field).attname
for field in self._history_excluded_fields
]
values = (
model.objects.filter(pk=getattr(self, model._meta.pk.attname))
.values(*excluded_attnames)
.get()
)
attrs.update(values)
return model(**attrs)
def get_next_record(self):
"""
Get the next history record for the instance. `None` if last.
"""
history = utils.get_history_manager_for_model(self.instance)
return (
history.filter(Q(history_date__gt=self.history_date))
.order_by("history_date")
.first()
)
def get_prev_record(self):
"""
Get the previous history record for the instance. `None` if first.
"""
history = utils.get_history_manager_for_model(self.instance)
return (
history.filter(Q(history_date__lt=self.history_date))
.order_by("history_date")
.last()
)
extra_fields = {
"history_id": self._get_history_id_field(),
"history_date": models.DateTimeField(),
"history_change_reason": self._get_history_change_reason_field(),
"history_type": models.CharField(
max_length=1,
choices=(("+", _("Created")), ("~", _("Changed")), ("-", _("Deleted"))),
),
"history_object": HistoricalObjectDescriptor(
model, self.fields_included(model)
),
"instance": property(get_instance),
"instance_type": model,
"next_record": property(get_next_record),
"prev_record": property(get_prev_record),
"revert_url": revert_url,
"__str__": lambda self: "{} as of {}".format(
self.history_object, self.history_date
),
}
extra_fields.update(self._get_history_related_field(model))
extra_fields.update(self._get_history_user_fields())
return extra_fields
|
Remove the appropriate target listeners to this component
and all its children.
|
protected void removeTargetListeners (Component comp)
{
comp.removeMouseListener(_targetListener);
comp.removeMouseMotionListener(_targetListener);
if (comp instanceof Container) { // again, always true for JComp...
Container cont = (Container) comp;
cont.removeContainerListener(_childListener);
for (int ii=0, nn=cont.getComponentCount(); ii < nn; ii++) {
removeTargetListeners(cont.getComponent(ii));
}
}
}
|
Adjust a single component (red, green, blue or alpha) of a colour.
@param component The value to mutate.
@return The mutated component value.
|
private int mutateColourComponent(int component)
{
int mutatedComponent = (int) Math.round(component + mutationAmount.nextValue());
mutatedComponent = Maths.restrictRange(mutatedComponent, 0, 255);
return mutatedComponent;
}
|
Perform fling action.
Usage:
d().fling() # default vertically, forward
d().fling.horiz.forward()
d().fling.vert.backward()
d().fling.toBeginning(max_swipes=100) # vertically
d().fling.horiz.toEnd()
|
def fling(self):
'''
'''
@param_to_property(
dimention=["vert", "vertically", "vertical", "horiz", "horizental", "horizentally"],
action=["forward", "backward", "toBeginning", "toEnd"]
)
def _fling(dimention="vert", action="forward", max_swipes=1000):
vertical = dimention in ["vert", "vertically", "vertical"]
if action == "forward":
return self.jsonrpc.flingForward(self.selector, vertical)
elif action == "backward":
return self.jsonrpc.flingBackward(self.selector, vertical)
elif action == "toBeginning":
return self.jsonrpc.flingToBeginning(self.selector, vertical, max_swipes)
elif action == "toEnd":
return self.jsonrpc.flingToEnd(self.selector, vertical, max_swipes)
return _fling
|
Marshall the given parameter object.
|
public void marshall(ReservationPurchaseRecommendationSummary reservationPurchaseRecommendationSummary, ProtocolMarshaller protocolMarshaller) {
if (reservationPurchaseRecommendationSummary == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(reservationPurchaseRecommendationSummary.getTotalEstimatedMonthlySavingsAmount(),
TOTALESTIMATEDMONTHLYSAVINGSAMOUNT_BINDING);
protocolMarshaller.marshall(reservationPurchaseRecommendationSummary.getTotalEstimatedMonthlySavingsPercentage(),
TOTALESTIMATEDMONTHLYSAVINGSPERCENTAGE_BINDING);
protocolMarshaller.marshall(reservationPurchaseRecommendationSummary.getCurrencyCode(), CURRENCYCODE_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
|
Given one format, one block id and, optionally, one moduleid, return the corresponding backup_xxx_block_task()
|
public static function get_backup_block_task($format, $blockid, $moduleid = null) {
global $CFG, $DB;
// Check blockid exists
if (!$block = $DB->get_record('block_instances', array('id' => $blockid))) {
throw new backup_task_exception('block_task_block_instance_not_found', $blockid);
}
// Set default block backup task
$classname = 'backup_default_block_task';
$testname = 'backup_' . $block->blockname . '_block_task';
// If the block has custom backup/restore task class (testname), use it
if (class_exists($testname)) {
$classname = $testname;
}
return new $classname($block->blockname, $blockid, $moduleid);
}
|
Pretty version
:param diff_to_increase_ratio: Ratio to convert number of changes into
version increases
:return: string: Pretty version of this repository
|
def get_pretty_version(self, diff_to_increase_ratio):
version = self.get_version(diff_to_increase_ratio)
build = self.get_last_commit_hash()
return str(version) + " (" + build + ")"
|
// GetUint32 gets given key as a uint32
|
func (e *Entity) GetUint32(name string) (uint32, bool) {
if v := e.Get(name); v != nil {
switch x := v.(type) {
case uint32:
return x, true
case uint64:
return uint32(x), true
}
}
return 0, false
}
|
Returns an iterator over this page's {@code results} that:
<ul>
<li>Will not be {@code null}.</li>
<li>Will not support {@link java.util.Iterator#remove()}.</li>
</ul>
@return a non-null iterator.
|
@Override
public java.util.Iterator<com.google.api.ads.admanager.axis.v201805.User> iterator() {
if (results == null) {
return java.util.Collections.<com.google.api.ads.admanager.axis.v201805.User>emptyIterator();
}
return java.util.Arrays.<com.google.api.ads.admanager.axis.v201805.User>asList(results).iterator();
}
|
A wrapper around {@link FileSystem#rename(Path, Path)} which throws {@link IOException} if
{@link FileSystem#rename(Path, Path)} returns False.
|
public static void renamePath(FileSystem fs, Path oldName, Path newName, boolean overwrite) throws IOException {
if (!fs.exists(oldName)) {
throw new FileNotFoundException(String.format("Failed to rename %s to %s: src not found", oldName, newName));
}
if (fs.exists(newName)) {
if (overwrite) {
HadoopUtils.moveToTrash(fs, newName);
} else {
throw new FileAlreadyExistsException(
String.format("Failed to rename %s to %s: dst already exists", oldName, newName));
}
}
if (!fs.rename(oldName, newName)) {
throw new IOException(String.format("Failed to rename %s to %s", oldName, newName));
}
}
|
Read a single message from the connection.
Re-assemble data frames if the message is fragmented.
Return ``None`` when the closing handshake is started.
|
async def read_message(self) -> Optional[Data]:
frame = await self.read_data_frame(max_size=self.max_size)
# A close frame was received.
if frame is None:
return None
if frame.opcode == OP_TEXT:
text = True
elif frame.opcode == OP_BINARY:
text = False
else: # frame.opcode == OP_CONT
raise WebSocketProtocolError("Unexpected opcode")
# Shortcut for the common case - no fragmentation
if frame.fin:
return frame.data.decode("utf-8") if text else frame.data
# 5.4. Fragmentation
chunks: List[Data] = []
max_size = self.max_size
if text:
decoder_factory = codecs.getincrementaldecoder("utf-8")
# https://github.com/python/typeshed/pull/2752
decoder = decoder_factory(errors="strict") # type: ignore
if max_size is None:
def append(frame: Frame) -> None:
nonlocal chunks
chunks.append(decoder.decode(frame.data, frame.fin))
else:
def append(frame: Frame) -> None:
nonlocal chunks, max_size
chunks.append(decoder.decode(frame.data, frame.fin))
max_size -= len(frame.data)
else:
if max_size is None:
def append(frame: Frame) -> None:
nonlocal chunks
chunks.append(frame.data)
else:
def append(frame: Frame) -> None:
nonlocal chunks, max_size
chunks.append(frame.data)
max_size -= len(frame.data)
append(frame)
while not frame.fin:
frame = await self.read_data_frame(max_size=max_size)
if frame is None:
raise WebSocketProtocolError("Incomplete fragmented message")
if frame.opcode != OP_CONT:
raise WebSocketProtocolError("Unexpected opcode")
append(frame)
# mypy cannot figure out that chunks have the proper type.
return ("" if text else b"").join(chunks)
|
Log an error. By default this will also raise an exception.
|
def error(self, *args):
""""""
if _canShortcutLogging(self.logCategory, ERROR):
return
errorObject(self.logObjectName(), self.logCategory,
*self.logFunction(*args))
|
Get type from vmodl name
|
def GetVmodlType(name):
# If the input is already a type, just return
if isinstance(name, type):
return name
# Try to get type from vmodl type names table
typ = vmodlTypes.get(name)
if typ:
return typ
# Else get the type from the _wsdlTypeMap
isArray = name.endswith("[]")
if isArray:
name = name[:-2]
ns, wsdlName = _GetWsdlInfo(name)
try:
typ = GetWsdlType(ns, wsdlName)
except KeyError:
raise KeyError(name)
if typ:
return isArray and typ.Array or typ
else:
raise KeyError(name)
|
Prints a nice side block with an optional header.
@param block_contents $bc HTML for the content
@param string $region the region the block is appearing in.
@return string the HTML to be output.
|
public function block(block_contents $bc, $region) {
$bc = clone($bc); // Avoid messing up the object passed in.
if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
$bc->collapsible = block_contents::NOT_HIDEABLE;
}
$id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
$context = new stdClass();
$context->skipid = $bc->skipid;
$context->blockinstanceid = $bc->blockinstanceid;
$context->dockable = $bc->dockable;
$context->id = $id;
$context->hidden = $bc->collapsible == block_contents::HIDDEN;
$context->skiptitle = strip_tags($bc->title);
$context->showskiplink = !empty($context->skiptitle);
$context->arialabel = $bc->arialabel;
$context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
$context->type = $bc->attributes['data-block'];
$context->title = $bc->title;
$context->content = $bc->content;
$context->annotation = $bc->annotation;
$context->footer = $bc->footer;
$context->hascontrols = !empty($bc->controls);
if ($context->hascontrols) {
$context->controls = $this->block_controls($bc->controls, $id);
}
return $this->render_from_template('core/block', $context);
}
|
// SetGracePeriod sets the health check initial grace period, in seconds
|
func (p *PodHealthCheck) SetGracePeriod(gracePeriodSeconds int) *PodHealthCheck {
p.GracePeriodSeconds = &gracePeriodSeconds
return p
}
|
// UpdateSplunk updates a specific splunk.
|
func (c *Client) UpdateSplunk(i *UpdateSplunkInput) (*Splunk, error) {
if i.Service == "" {
return nil, ErrMissingService
}
if i.Version == 0 {
return nil, ErrMissingVersion
}
if i.Name == "" {
return nil, ErrMissingName
}
path := fmt.Sprintf("/service/%s/version/%d/logging/splunk/%s", i.Service, i.Version, i.Name)
resp, err := c.PutForm(path, i, nil)
if err != nil {
return nil, err
}
var s *Splunk
if err := decodeJSON(&s, resp.Body); err != nil {
return nil, err
}
return s, nil
}
|
Helper around 'locate'
|
def find(pattern, root=os.curdir):
''' '''
hits = ''
for F in locate(pattern, root):
hits = hits + F + '\n'
l = hits.split('\n')
if(not len(l[-1])): l.pop()
if len(l) == 1 and not len(l[0]):
return None
else:
return l
|
Subsets and Splits
Golang Code and Comments
Retrieves all entries containing the term 'golang' in either the comment or code, providing a basic filter for data related to the Go programming language.