comment
stringlengths 16
255
| code
stringlengths 52
3.87M
|
---|---|
Assemble parts
@return void | protected function assemble()
{
$this->push($this->replace ? 'REPLACE' : 'INSERT');
$this->pushIgnoreDelayed();
$this->push('INTO');
$this->pushTable();
$this->push('SET');
$this->pushValues();
$this->pushOnDuplicateKeyUpdate();
} |
Creates a new AuthItem model.
If creation is successful, the browser will be redirected to the 'view' page.
@return mixed | public function actionCreate()
{
$model = new AuthItem(null);
$model->type = Item::TYPE_ROLE;
if ($model->load(Yii::$app->getRequest()->post()) && $model->save()) {
AccessHelper::refeshAuthCache();
return $this->redirect(['view', 'id' => $model->name]);
} else {
return $this->render('create', ['model' => $model,]);
}
} |
Moves bytes from the buffer to the beginning of the destination buffer. Also sets the index and
endIndex variables.
@param dest The destination buffer. | private void moveBufferTo(byte[] dest) {
int size = endIndex - index;
System.arraycopy(buffer, index, dest, 0, size);
index = 0;
endIndex = size;
} |
// GetEndorsersForChaincode returns a set of endorsing peers | func (s *SelectionService) GetEndorsersForChaincode(chaincodes []*fab.ChaincodeCall, opts ...copts.Opt) ([]fab.Peer, error) {
params := options.NewParams(opts)
channelPeers, err := s.discoveryService.GetPeers()
if err != nil {
logger.Errorf("Error retrieving peers from discovery service: %s", err)
return nil, nil
}
// Apply peer filter if provided
if params.PeerFilter != nil {
var peers []fab.Peer
for _, peer := range channelPeers {
if params.PeerFilter(peer) {
peers = append(peers, peer)
}
}
channelPeers = peers
}
if params.PeerSorter != nil {
peers := make([]fab.Peer, len(channelPeers))
copy(peers, channelPeers)
channelPeers = params.PeerSorter(peers)
}
if logging.IsEnabledFor(loggerModule, logging.DEBUG) {
str := ""
for i, peer := range channelPeers {
str += peer.URL()
if i+1 < len(channelPeers) {
str += ","
}
}
logger.Debugf("Available peers: [%s]", str)
}
return channelPeers, nil
} |
Return the union of all flags in this dict
Returns
-------
union : `DataQualityFlag`
a new `DataQualityFlag` who's active and known segments
are the union of those of the values of this dict | def union(self):
usegs = reduce(operator.or_, self.values())
usegs.name = ' | '.join(self.keys())
return usegs |
Insert a CSS rule, given by selector(s) and declarations, into a sheet. If the scoped attribute was specified, and scoping is not supported, then emulate scoping, by adding a data-* attribute to the parent element, and rewriting the selectors. | function insert(sheet, [selectors, styles]) {
if (sheet.scopedStyleId) {
selectors = scopifySelectors(selectors, sheet.scopedStyleId);
}
var idx = sheet.insertRule(`${selectors} { }`, sheet.rules.length);
var rule = sheet.rules[idx];
if (typeof styles === 'string') { rule.style = styles; }
else {
// @TODO Fix this to be upward-friendly, and valueize style object.
assign(rule.style, styles);
//mirrorProperties(rule.style, styles);
}
return rule;
} |
Hand off the work to the phing task of ours, after setting it up
@throws BuildException on validation failure or if the target didn't
execute.
@return void | public function main()
{
$sec = 0;
$target = $this->getOwningTarget();
$targetName = $target->getName();
$subTargetName = $this->subTarget;
$allTargets = $this->project->getTargets();
$usedTargets = array_filter(
$allTargets,
function ($key) {
return strrpos($key, ".".$targetName) > 0;
},
ARRAY_FILTER_USE_KEY
);
// If the target was redefined outside of the starterkit.
if (!empty($usedTargets)) {
$sec = 10;
$newTarget = $targetName;
$buildFile = "build.project.xml";
$target = $allTargets[$subTargetName];
} else {
// If a deprecated target is called without redefinition.
$sec = 5;
$newTarget = $subTargetName;
$buildFile = $this->project->getProperty("phing.file");
}
// Inform user of the deprecated target.
$this->log(
"Target '".$targetName."' has been replaced by '".$subTargetName."'.",
Project::MSG_WARN
);
$this->log(
"A ".$sec." second penalty is assigned usage of this target.",
Project::MSG_WARN
);
$this->log(
"Please use '".$subTargetName."' instead to avoid the penalty.",
Project::MSG_WARN
);
$this->log(
"Running PhingCallTask for target '".$subTargetName."'",
Project::MSG_DEBUG
);
sleep($sec);
if ($this->_callee === null) {
$this->init();
}
if ($this->subTarget === null) {
throw new BuildException(
"Attribute target is required.",
$this->getLocation()
);
}
$this->_callee->setPhingfile($buildFile);
$this->_callee->setTarget($newTarget);
$this->_callee->setOwningTarget($target);
$this->_callee->setInheritAll($this->_inheritAll);
$this->_callee->setInheritRefs($this->_inheritRefs);
$this->_callee->main();
} |
Property value setter.
@param value New value for the property | @Override
public String setValue(String value) {
String result = this.value;
this.value = value;
calculateCompareKey();
return result;
} |
Adds a new variable binding. | public TupleRef addVarBinding( VarBinding varBinding)
{
assert varBinding != null;
assert varBinding.getVar() != null;
String varName = varBinding.getVar();
if( varBindings_.containsKey( varName))
{
throw new IllegalStateException( "Value for " + varName + " already defined");
}
varBindings_.put( varName, varBinding);
return this;
} |
Get the previous requests associated request data.
@return RequestInfo|null | public function getLastRequest() {
$path = $this->tmpDir . DIRECTORY_SEPARATOR . self::LAST_REQUEST_FILE;
if( file_exists($path) ) {
$content = file_get_contents($path);
$data = @unserialize($content);
if( $data instanceof RequestInfo ) {
return $data;
}
}
return null;
} |
// GetHeaderByNumber returns a block header from the current canonical chain. If number is <0,
// the latest known header is returned. | func (ec *EthereumClient) GetHeaderByNumber(ctx *Context, number int64) (header *Header, _ error) {
if number < 0 {
rawHeader, err := ec.client.HeaderByNumber(ctx.context, nil)
return &Header{rawHeader}, err
}
rawHeader, err := ec.client.HeaderByNumber(ctx.context, big.NewInt(number))
return &Header{rawHeader}, err
} |
Rename this multireddit.
This function is a handy shortcut to
:meth:`rename_multireddit` of the reddit_session. | def rename(self, new_name, *args, **kwargs):
new = self.reddit_session.rename_multireddit(self.name, new_name,
*args, **kwargs)
self.__dict__ = new.__dict__ # pylint: disable=W0201
return self |
Create a new FileLikeMock instance.
The new mock will inherit the parent's side_effect and read_data
attributes. | def _get_child_mock(self, **kws):
kws.update({
'_new_parent': self,
'side_effect': self._mock_side_effect,
'read_data': self.__read_data,
})
return FileLikeMock(**kws) |
Analyze the string, and decide if quotes should be added or not.
@param string String
@return string String with quotes added if needed.
@deprecated | static function quoteIfNeeded( $value )
{
$quote = '';
if ( strpos( $value, ' ' ) !== false )
{
$quote = '"';
if ( strpos( trim( $value ), '(' ) === 0 )
{
$quote = '';
}
}
return $quote . $value . $quote;
} |
// SetSchedule sets the Schedule field's value. | func (s *TreatmentResource) SetSchedule(v *Schedule) *TreatmentResource {
s.Schedule = v
return s
} |
// needsQuoting returns true if any non-printable characters are found. | func needsQuoting(text string) bool {
for _, r := range text {
if !strconv.IsPrint(r) {
return true
}
}
return false
} |
// Get retrieves the value at the provided key. | func (b *Bucket) Get(key []byte) ([]byte, error) {
i := b.btree.Get(&item{key: key})
if i == nil {
return nil, kv.ErrKeyNotFound
}
j, ok := i.(*item)
if !ok {
return nil, fmt.Errorf("error item is type %T not *item", i)
}
return j.value, nil
} |
Parse the incoming command string
@param cmd
@param pos ignore anything before this pos in cmd
@throws IOException | private void tail(String[] cmd, int pos) throws IOException {
CommandFormat c = new CommandFormat("tail", 1, 1, "f");
String src = null;
Path path = null;
try {
List<String> parameters = c.parse(cmd, pos);
src = parameters.get(0);
} catch(IllegalArgumentException iae) {
System.err.println("Usage: java FreightStreamer " + TAIL_USAGE);
throw iae;
}
boolean foption = c.getOpt("f") ? true: false;
path = new Path(src);
FileSystem srcFs = path.getFileSystem(getConf());
if (srcFs.isDirectory(path)) {
throw new IOException("Source must be a file.");
}
long fileSize = srcFs.getFileStatus(path).getLen();
long offset = (fileSize > 1024) ? fileSize - 1024: 0;
while (true) {
FSDataInputStream in = srcFs.open(path);
in.seek(offset);
IOUtils.copyBytes(in, System.out, 1024, false);
offset = in.getPos();
in.close();
if (!foption) {
break;
}
fileSize = srcFs.getFileStatus(path).getLen();
offset = (fileSize > offset) ? offset: fileSize;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
break;
}
}
} |
// Extract services webhooks from github.com | func (p *WebHookPlugin) Extract(buildCfg *buildv1.BuildConfig, trigger *buildv1.WebHookTrigger, req *http.Request) (revision *buildv1.SourceRevision, envvars []corev1.EnvVar, dockerStrategyOptions *buildv1.DockerStrategyOptions, proceed bool, err error) {
klog.V(4).Infof("Verifying build request for BuildConfig %s/%s", buildCfg.Namespace, buildCfg.Name)
if err = verifyRequest(req); err != nil {
return revision, envvars, dockerStrategyOptions, proceed, err
}
method := getEvent(req.Header)
if method != "ping" && method != "push" {
return revision, envvars, dockerStrategyOptions, proceed, errors.NewBadRequest(fmt.Sprintf("Unknown X-GitHub-Event or X-Gogs-Event %s", method))
}
if method == "ping" {
return revision, envvars, dockerStrategyOptions, proceed, err
}
body, err := ioutil.ReadAll(req.Body)
if err != nil {
return revision, envvars, dockerStrategyOptions, proceed, errors.NewBadRequest(err.Error())
}
var event pushEvent
if err = json.Unmarshal(body, &event); err != nil {
return revision, envvars, dockerStrategyOptions, proceed, errors.NewBadRequest(err.Error())
}
if !webhook.GitRefMatches(event.Ref, webhook.DefaultConfigRef, &buildCfg.Spec.Source) {
klog.V(2).Infof("Skipping build for BuildConfig %s/%s. Branch reference from '%s' does not match configuration", buildCfg.Namespace, buildCfg.Name, event)
return revision, envvars, dockerStrategyOptions, proceed, err
}
revision = &buildv1.SourceRevision{
Git: &buildv1.GitSourceRevision{
Commit: event.HeadCommit.ID,
Author: event.HeadCommit.Author,
Committer: event.HeadCommit.Committer,
Message: event.HeadCommit.Message,
},
}
return revision, envvars, dockerStrategyOptions, true, err
} |
Displays an input prompt
@param string $question
@param string|null $default
@param string $marker
@return mixed | public function prompt($question, $default = null, $marker = ': ')
{
if (isset($default) && strpos($question, '[') === false) {
$question .= ' [default: ' . $default . ']';
}
$this->out($question . $marker);
$input = $this->in();
if ($input === '') {
return $default;
}
return $input;
} |
IE rgba hack
background rgba 转换为 IE ARGB | function ieRgbaHack(decl, i) {
//十六进制不足两位自动补 0
function pad(str) {
return str.length == 1 ? '0' + str : '' + str
}
if (
(decl.prop == 'background' || decl.prop == 'background-color') &&
decl.value.match(reRGBA)
) {
// rgba 转换为 AARRGGBB
var colorR = pad(parseInt(RegExp.$1).toString(16))
var colorG = pad(parseInt(RegExp.$2).toString(16))
var colorB = pad(parseInt(RegExp.$3).toString(16))
var colorA = pad(parseInt(RegExp.$4 * 255).toString(16))
var ARGB = "'" + '#' + colorA + colorR + colorG + colorB + "'"
// 插入IE半透明滤镜
var reBefore = decl.raws.before.replace(reBLANK_LINE, '$1')
insertDecl(decl, i, {
raws: {
before: reBefore
},
prop: 'filter',
value:
'progid:DXImageTransform.Microsoft.gradient(startColorstr=' +
ARGB +
', endColorstr=' +
ARGB +
')'
})
// IE9 rgba 和滤镜都支持,插入 :root hack 去掉滤镜
var newSelector = ':root ' + decl.parent.selector
var nextrule = postcss.rule({
selector: newSelector
})
decl.parent.parent.insertAfter(decl.parent, nextrule)
nextrule.append({
prop: 'filter',
value: 'none\\9'
})
}
} |
Get errors received from Textmagic API
@return array | public function getErrors() {
$result = array();
if (count($this->errors) > 0) {
if (isset($this->errors['common'])) {
$result['common'] = $this->errors['common'];
}
if (isset($this->errors['fields'])) {
foreach ($this->errors['fields'] as $key => $value) {
$result[$key] = $value;
}
}
}
return $result;
} |
// DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists. | func DirExistsf(t TestingT, path string, msg string, args ...interface{}) bool {
if h, ok := t.(tHelper); ok {
h.Helper()
}
return DirExists(t, path, append([]interface{}{msg}, args...)...)
} |
Reset the tailSequenceNumber.
Caller must be synchronized on tailSequenceNumberLock.
@throws ObjectManagerException | private void resetTailSequenceNumber()
throws ObjectManagerException
{
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.entry(this, cclass
, "resetTailSequenceNumber"
);
for (int i = 0; i < subListTokens.length; i++) {
subLists[i] = ((ConcurrentSubList) subListTokens[i].getManagedObject());
// In case another thread is currently removing the tail, take a safe copy.
Token tailToken = subLists[i].tail;
// Establish the highest existing tailSequenceNumber.
if (tailToken != null) {
ConcurrentSubList.Link tail = (ConcurrentSubList.Link) tailToken.getManagedObject();
tailSequenceNumber = Math.max(tailSequenceNumber,
tail.sequenceNumber);
} // if (tailToken != null).
} // for subList.
tailSequenceNumberSet = true;
if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
trace.exit(this, cclass
, "resetHeadSequenceNumber"
);
} |
// Simple wrapper to add multiple resources | func AutoAddResources(fileName string, keys []string, c *cli.Context) error {
OutStoreFormat = getStoreFormatFromFileName(fileName)
config := util.Config{
IgnoreList: c.GlobalStringSlice("exclude-attr"),
Timeout: int(c.Duration("timeout") / time.Millisecond),
}
var gossConfig GossConfig
if _, err := os.Stat(fileName); err == nil {
gossConfig = ReadJSON(fileName)
} else {
gossConfig = *NewGossConfig()
}
sys := system.New(c)
for _, key := range keys {
if err := AutoAddResource(fileName, gossConfig, key, c, config, sys); err != nil {
return err
}
}
WriteJSON(fileName, gossConfig)
return nil
} |
// WithHandle404 configures static module with a base URL path for
// serving static assets | func WithHandle404(fn http.HandlerFunc) option {
return func(m *Module) {
m.handle404 = fn
}
} |
// handleDeleteDocument is the HTTP handler for the DELETE /api/v2/documents/:ns/:id route. | func (h *DocumentHandler) handleDeleteDocument(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
req, err := decodeDeleteDocumentRequest(ctx, r)
if err != nil {
EncodeError(ctx, err, w)
return
}
s, err := h.DocumentService.FindDocumentStore(ctx, req.Namespace)
if err != nil {
EncodeError(ctx, err, w)
return
}
a, err := pcontext.GetAuthorizer(ctx)
if err != nil {
EncodeError(ctx, err, w)
return
}
if err := s.DeleteDocuments(ctx, influxdb.AuthorizedWhereID(a, req.ID)); err != nil {
EncodeError(ctx, err, w)
return
}
w.WriteHeader(http.StatusNoContent)
} |
{@inheritDoc}
Very basic way of framing a sip message. It makes a lot of assumption but
in the framing phase we are, well, just framing. | @Override
public SipPacket frame(final TransportPacket parent, final Buffer buffer) throws IOException {
if (parent == null) {
throw new IllegalArgumentException("The parent frame cannot be null");
}
final SipMessage sip = SipParser.frame(buffer);
if (sip.isRequest()) {
return new SipRequestPacketImpl(parent, sip.toRequest());
}
return new SipResponsePacketImpl(parent, sip.toResponse());
} |
Processes this test, when one of its tokens is encountered.
@param PHP_CodeSniffer_File $phpcsfile The file being scanned.
@param int $stackptr The position of the current token
in the stack passed in $tokens.
@return void | public function process(PHP_CodeSniffer_File $phpcsfile, $stackptr) {
$tokens = $phpcsfile->getTokens();
// Look for final whitespace endings but not in whitespace tokens
// (not sure which cases are covered by this, because it seems to
// conflict/dupe {@link SuperfluousWhitespaceSniff} but, it's kept
// working for any registered token but T_WHITESPACE, that is handled
// by other regexps
if ($tokens[$stackptr]['type'] != 'T_WHITESPACE') {
preg_match('~\s[\r\n]~', $tokens[$stackptr]['content'], $matches);
if (!empty($matches)) {
$error = 'Whitespace found at end of line within string';
$phpcsfile->addError($error, $stackptr, 'EndLine');
}
// Other tests within T_WHITESPACE tokens
} else {
// Look for tabs only in whitespace tokens
if (strpos($tokens[$stackptr]['content'], "\t") !== false) {
$error = 'Tab found within whitespace';
$phpcsfile->addError($error, $stackptr, 'TabWhitespace');
}
}
} |
// OpenFileMaybeCompressed opens a file that might be compressed with gzip
// or bzip2.
// TODO: could sniff file content instead of checking file extension | func OpenFileMaybeCompressed(path string) (io.ReadCloser, error) {
ext := strings.ToLower(filepath.Ext(path))
f, err := os.Open(path)
if err != nil {
return nil, err
}
if ext == ".gz" {
r, err := gzip.NewReader(f)
if err != nil {
f.Close()
return nil, err
}
rc := &readerWrappedFile{
f: f,
r: r,
}
return rc, nil
}
if ext == ".bz2" {
r := bzip2.NewReader(f)
rc := &readerWrappedFile{
f: f,
r: r,
}
return rc, nil
}
return f, nil
} |
Check if this object configuration is correct ::
* Check our own specific properties
* Call our parent class is_correct checker
:return: True if the configuration is correct, otherwise False
:rtype: bool | def is_correct(self):
state = True
# Internal checks before executing inherited function...
loop = self.no_loop_in_parents("host_name", "dependent_host_name")
if loop:
msg = "Loop detected while checking host dependencies"
self.add_error(msg)
state = False
for item in self:
for elem in loop:
if elem == item.host_name:
msg = "Host %s is parent host_name in dependency defined in %s" % (
item.host_name_string, item.imported_from
)
self.add_error(msg)
elif elem == item.dependent_host_name:
msg = "Host %s is child host_name in dependency defined in %s" % (
item.dependent_host_name_string, item.imported_from
)
self.add_error(msg)
return super(Hostdependencies, self).is_correct() and state |
r"""
Runs the example. | def run_example():
"""
weather = mc_e.get_weather_data('weather.csv')
my_turbine, e126, dummy_turbine = mc_e.initialize_wind_turbines()
example_farm, example_farm_2 = initialize_wind_farms(my_turbine, e126)
example_cluster = initialize_wind_turbine_cluster(example_farm,
example_farm_2)
calculate_power_output(weather, example_farm, example_cluster)
plot_or_print(example_farm, example_cluster) |
Normalizes the given value.
@param mixed $value
@return mixed | protected function normalize($value)
{
if ($value instanceof Exception) {
$value = [
'class' => get_class($value),
'message' => $value->getMessage(),
'code' => $value->getCode(),
'file' => $value->getFile(),
'line' => $value->getLine(),
];
}
return $value;
} |
Encode a block of 505 16-bit samples as 4-bit ADPCM samples.
@param {!Array<number>} block A sample block of 505 samples.
@return {!Array<number>} | function encodeBlock(block) {
/** @type {!Array<number>} */
let adpcmSamples = blockHead_(block[0]);
for (let i=3; i<block.length; i+=2) {
/** @type {number} */
let sample2 = encodeSample_(block[i]);
/** @type {number} */
let sample = encodeSample_(block[i + 1]);
adpcmSamples.push((sample << 4) | sample2);
}
while (adpcmSamples.length < 256) {
adpcmSamples.push(0);
}
return adpcmSamples;
} |
Each call to `angular.module()` is analysed here | function(parser, expr){
this.addAngularVariable(parser);
switch(expr.arguments.length){
case 1: return this._parseModuleCallSingleArgument(parser, expr);
case 2: return this._parseModuleCallTwoArgument(parser, expr);
case 3: return this._parseModuleCallThreeArgument(parser, expr);
default:
console.warn("Don't recognise angular.module() with " +
expr.arguments.length + " args");
}
} |
Attempt to find a ResponseHandler that knows how to process this response.
If no handler can be found, raise an Exception. | def _process_response(self, response, object_mapping=None):
try:
pretty_response = response.json()
except ValueError:
pretty_response = response
for handler in self._response_handlers:
if handler.applies_to(self, response):
log.debug("{} matched: {}".format(handler.__name__, pretty_response))
r = handler(self, object_mapping).build(response)
self._clean_dirty_objects()
return r
raise ZenpyException("Could not handle response: {}".format(pretty_response)) |
Detects a mobile device running the Ubuntu Mobile OS. | function DetectUbuntu()
{
if (($this->DetectUbuntuPhone() == $this->true)
|| ($this->DetectUbuntuTablet() == $this->true))
return $this->true;
else
return $this->false;
} |
Marshall the given parameter object. | public void marshall(ResourceConfiguration resourceConfiguration, ProtocolMarshaller protocolMarshaller) {
if (resourceConfiguration == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(resourceConfiguration.getComputeType(), COMPUTETYPE_BINDING);
protocolMarshaller.marshall(resourceConfiguration.getVolumeSizeInGB(), VOLUMESIZEINGB_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} |
Get the azure block blob service for the container in question
Try account_key, sas_token, and no auth in that order | def _get_container_service(container):
'''
'''
if 'account_key' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], account_key=container['account_key'])
elif 'sas_token' in container:
account = azure.storage.CloudStorageAccount(container['account_name'], sas_token=container['sas_token'])
else:
account = azure.storage.CloudStorageAccount(container['account_name'])
blob_service = account.create_block_blob_service()
return blob_service |
Create a SlicePredicate that selects a single column.
@param colName Column name as a byte[].
@return SlicePredicate that select the given column name only. | static SlicePredicate slicePredicateColName(byte[] colName) {
SlicePredicate slicePred = new SlicePredicate();
slicePred.addToColumn_names(ByteBuffer.wrap(colName));
return slicePred;
} |
Returns the URL of the warning results for the specified parser.
@param group
the parser group
@return a unique URL | public static String getResultUrl(final String group) {
if (group == null) { // prior 4.0
return RESULT_URL;
}
else {
return PLUGIN_ID + ParserRegistry.getUrl(group) + RESULT_URL_SUFFIX;
}
} |
Check file extension | def check_filename(filename)
extension = filename.split('.').last
return true if valid_extensions.include?(extension)
false
end |
Формирует <select> из данных, с учетом их организации в виде дерева
@param $data
@param int $selected
@param array $htmlOptions
@param array $options
@return string | public static function selectTree(Collection $data, $selected = 0, $options = [], $htmlOptions = [])
{
$options = array_merge($options instanceof Std ? $options->toArray() : $options, ['tree']);
if (empty($options['treeLevelColumn']))
$options['treeLevelColumn'] = '__lvl';
return self::select($data, $selected, $options, $htmlOptions);
} |
Return the full name (including module) of the given class. | def full_name(cla55: Optional[type]) -> str:
# Special case to handle None:
if cla55 is None:
return "?"
if issubclass(cla55, Initializer) and cla55 not in [Initializer, PretrainedModelInitializer]:
init_fn = cla55()._init_function
return f"{init_fn.__module__}.{init_fn.__name__}"
origin = getattr(cla55, '__origin__', None)
args = getattr(cla55, '__args__', ())
# Special handling for compound types
if origin in (Dict, dict):
key_type, value_type = args
return f"""Dict[{full_name(key_type)}, {full_name(value_type)}]"""
elif origin in (Tuple, tuple, List, list, Sequence, collections.abc.Sequence):
return f"""{_remove_prefix(str(origin))}[{", ".join(full_name(arg) for arg in args)}]"""
elif origin == Union:
# Special special case to handle optional types:
if len(args) == 2 and args[-1] == type(None):
return f"""Optional[{full_name(args[0])}]"""
else:
return f"""Union[{", ".join(full_name(arg) for arg in args)}]"""
else:
return _remove_prefix(f"{cla55.__module__}.{cla55.__name__}") |
// Start the link with the specified toxics | func (link *ToxicLink) Start(name string, source io.Reader, dest io.WriteCloser) {
go func() {
bytes, err := io.Copy(link.input, source)
if err != nil {
logrus.WithFields(logrus.Fields{
"name": link.proxy.Name,
"bytes": bytes,
"err": err,
}).Warn("Source terminated")
}
link.input.Close()
}()
for i, toxic := range link.toxics.chain[link.direction] {
if stateful, ok := toxic.Toxic.(toxics.StatefulToxic); ok {
link.stubs[i].State = stateful.NewState()
}
go link.stubs[i].Run(toxic)
}
go func() {
bytes, err := io.Copy(dest, link.output)
if err != nil {
logrus.WithFields(logrus.Fields{
"name": link.proxy.Name,
"bytes": bytes,
"err": err,
}).Warn("Destination terminated")
}
dest.Close()
link.toxics.RemoveLink(name)
link.proxy.RemoveConnection(name)
}()
} |
Returns an array of configurations
@return array | protected function getListConfig()
{
$name = $this->getParam(0);
if (isset($name)) {
$result = $this->config->get($name);
if (!isset($result)) {
$this->errorAndExit($this->text('Invalid argument'));
}
$list = array($name => $result);
} else {
$list = $this->config->get();
$this->limitArray($list);
}
$saved = $this->config->select();
$reindexed = array();
foreach ($list as $key => $value) {
$reindexed[] = array(
'key' => $key,
'value' => $value,
'in_database' => isset($saved[$key])
);
}
return $reindexed;
} |
${cmd_name}: make a maildir at the specified path.
${cmd_usage}
If the path is relative then create under MAILDIR
else create at the absolute location. | def do_make(self, subcmd, opts, path):
# Do we need to make this ".path" if it's relative?
d = path if path[0] == "/" else joinpath(self.maildir, "." + path)
os.makedirs(joinpath(d, "cur"))
os.makedirs(joinpath(d, "new"))
os.makedirs(joinpath(d, "tmp"))
os.makedirs(joinpath(d, "store")) |
Write the last response to a file.
@param f File
@return long bytes written
@throws HelloSignException Thrown if an exception occurs during the copy
of the response stream to the given file. | public long getResponseAsFile(File f) throws HelloSignException {
long bytesWritten = 0;
try {
bytesWritten = Files.copy(lastResponseStream, f.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
throw new HelloSignException(e);
}
return bytesWritten;
} |
Remove usage rights.
Removes copyright and license information associated with one or more files | def remove_usage_rights_courses(self, file_ids, course_id, folder_ids=None):
path = {}
data = {}
params = {}
# REQUIRED - PATH - course_id
"""ID"""
path["course_id"] = course_id
# REQUIRED - file_ids
"""List of ids of files to remove associated usage rights from."""
params["file_ids"] = file_ids
# OPTIONAL - folder_ids
"""List of ids of folders. Usage rights will be removed from all files in these folders."""
if folder_ids is not None:
params["folder_ids"] = folder_ids
self.logger.debug("DELETE /api/v1/courses/{course_id}/usage_rights with query params: {params} and form data: {data}".format(params=params, data=data, **path))
return self.generic_request("DELETE", "/api/v1/courses/{course_id}/usage_rights".format(**path), data=data, params=params, no_data=True) |
Commits a message to application's log. | private function log($message, $level)
{
// Only log if the logger is enabled.
if (!$this->isEnabled) {
return;
}
if ($level <= $this->level) {
$requestId = null;
try {
$requestID = Application::getCurrent()->getRequestId();
} catch (CoreException $exception) {
$requestID = '---';
}
$logMessage = sprintf(
'%s: %s [%s] %s' . PHP_EOL,
$this->id,
$requestId ?: '———',
@self::$levelNames[$level],
$message
);
// Commit the log message.
if (empty($this->errorLogFile)) {
// If no log file is specified, use the default PHP location.
error_log($logMessage);
} else {
// Silence the eventual error if the message cannot be written
// to the log, so that it doesn't interrupt the program.
@file_put_contents(
$this->errorLogFile,
$logMessage,
FILE_APPEND
);
}
}
} |
// ListDRACs handles a request to list DRACs. | func (*Service) ListDRACs(c context.Context, req *crimson.ListDRACsRequest) (*crimson.ListDRACsResponse, error) {
dracs, err := listDRACs(c, database.Get(c), req)
if err != nil {
return nil, err
}
return &crimson.ListDRACsResponse{
Dracs: dracs,
}, nil
} |
Creates a ChoiceCti with Qt PenStyles.
If includeEmtpy is True, the first option will be None. | def createPenStyleCti(nodeName, defaultData=0, includeNone=False):
displayValues=PEN_STYLE_DISPLAY_VALUES
configValues=PEN_STYLE_CONFIG_VALUES
if includeNone:
displayValues = [''] + list(displayValues)
configValues = [None] + list(configValues)
return ChoiceCti(nodeName, defaultData,
displayValues=displayValues, configValues=configValues) |
Validate tags when saving a discussion. | public function DiscussionModel_BeforeSaveDiscussion_Handler($Sender, $Args) {
$FormPostValues = GetValue('FormPostValues', $Args, array());
$TagsString = trim(strtolower(GetValue('Tags', $FormPostValues, '')));
$NumTagsMax = C('Plugin.Tagging.Max', 5);
// Tags can only contain unicode and the following ASCII: a-z 0-9 + # _ .
if (StringIsNullOrEmpty($TagsString) && C('Plugins.Tagging.Required')) {
$Sender->Validation->AddValidationResult('Tags', 'You must specify at least one tag.');
} else {
$Tags = TagModel::SplitTags($TagsString);
if (!TagModel::ValidateTags($Tags)) {
$Sender->Validation->AddValidationResult('Tags', '@'.T('ValidateTag', 'Tags cannot contain commas.'));
} elseif (count($Tags) > $NumTagsMax) {
$Sender->Validation->AddValidationResult('Tags', '@'.sprintf(T('You can only specify up to %s tags.'), $NumTagsMax));
} else {
}
}
} |
// SetIdleTimeout sets the idleTimeout on the pool. | func (cp *Pool) SetIdleTimeout(idleTimeout time.Duration) {
cp.mu.Lock()
defer cp.mu.Unlock()
if cp.connections != nil {
cp.connections.SetIdleTimeout(idleTimeout)
}
cp.dbaPool.SetIdleTimeout(idleTimeout)
cp.idleTimeout = idleTimeout
} |
Can be used to create entries in the users textfile
@param args username and password | public static void main(String[] args) {
if (args.length < 2) {
System.err.println("Two arguments needed as username and password");
System.exit(-1);
}
User user = new User();
user.name = args[0];
user.password.setPassword(args[1].toCharArray());
for (int i = 2; i<args.length; i++) {
user.roles.add(new UserRole(args[i].trim()));
}
System.out.println(user.format());
} |
Transformar de un array a una lista de objetos. | public function transform() {
$this->resListCallBack = $this->listCallBack->map(function ($call) {
return new HttpCallBack(
$call['method'],
$call['path'],
$call['fn']
);
});
} |
Return the syllable and tone of an IPA syllable. | def _parse_ipa_syllable(unparsed_syllable):
""""""
ipa_tone = re.search('[%(marks)s]+' % {'marks': _IPA_MARKS},
unparsed_syllable)
if not ipa_tone:
syllable, tone = unparsed_syllable, '5'
else:
for tone_number, tone_mark in _IPA_TONES.items():
if ipa_tone.group() == tone_mark:
tone = tone_number
break
syllable = unparsed_syllable[0:ipa_tone.start()]
return syllable, tone |
Replaces a first occurence of a String with another string | private String stringReplace(final String source, final String find, final String replace) {
if (source == null || find == null || replace == null)
return source;
final int index = source.indexOf(find);
if (index == -1)
return source; // no occurence, don't do anything;
if (index == 0)
return replace + source.substring(find.length());
return source.substring(0, index) + replace + source.substring(index + find.length());
} |
Store a newly created resource in storage.
@param $menu
@param FormRequest $request
@return Redirect | public function store($menu = null, FormRequest $request)
{
$data = $request->all();
$data['parent_id'] = null;
$data['page_id'] = $data['page_id'] ?: null;
$data['position'] = $data['position'] ?: 0;
$model = $this->repository->create($data);
return $this->redirect($request, $model);
} |
Update filesystem of all children | public function updateChildFilesystem()
{
// Don't synchronise on live (rely on publishing instead)
if (class_exists(Versioned::class) && Versioned::get_stage() === Versioned::LIVE) {
return;
}
$this->flushCache();
// Writing this record should trigger a write (and potential updateFilesystem) on each child
foreach ($this->AllChildren() as $child) {
$child->write();
}
} |
@param array $nodeTree
@param array $params
@return FacadeInterface | public function transform($nodeTree, array $params = array())
{
$facade = $this->newFacade();
$facade->node = $this->getContext()->transform('node_tree_leaf', $nodeTree['node']);
if (array_key_exists('child', $nodeTree)) {
foreach ($nodeTree['child'] as $child) {
$facade->addChild($this->getContext()->transform('node_tree', $child));
}
}
return $facade;
} |
Adds toil options to a parser object, either optparse or argparse. | def addOptions(parser, config=Config()):
# Wrapper function that allows toil to be used with both the optparse and
# argparse option parsing modules
addLoggingOptions(parser) # This adds the logging stuff.
if isinstance(parser, ArgumentParser):
def addGroup(headingString, bodyString):
return parser.add_argument_group(headingString, bodyString).add_argument
parser.register("type", "bool", lambda v: v.lower() == "true") # Custom type for arg=True/False.
_addOptions(addGroup, config)
else:
raise RuntimeError("Unanticipated class passed to addOptions(), %s. Expecting "
"argparse.ArgumentParser" % parser.__class__) |
Return only the current staff members | def active(self):
qset = super(StaffMemberManager, self).get_queryset()
return qset.filter(is_active=True) |
// setHosts writes the full list of DNS host records .
// https://www.namecheap.com/support/api/methods/domains-dns/set-hosts.aspx | func (d *DNSProvider) setHosts(sld, tld string, hosts []Record) error {
req, err := d.newRequestPost("namecheap.domains.dns.setHosts",
addParam("SLD", sld),
addParam("TLD", tld),
func(values url.Values) {
for i, h := range hosts {
ind := fmt.Sprintf("%d", i+1)
values.Add("HostName"+ind, h.Name)
values.Add("RecordType"+ind, h.Type)
values.Add("Address"+ind, h.Address)
values.Add("MXPref"+ind, h.MXPref)
values.Add("TTL"+ind, h.TTL)
}
},
)
if err != nil {
return err
}
var shr setHostsResponse
err = d.do(req, &shr)
if err != nil {
return err
}
if len(shr.Errors) > 0 {
return fmt.Errorf("%s [%d]", shr.Errors[0].Description, shr.Errors[0].Number)
}
if shr.Result.IsSuccess != "true" {
return fmt.Errorf("setHosts failed")
}
return nil
} |
Get fields for a given model | def get_related_fields(model_class, field_name, path=""):
if field_name:
field, model, direct, m2m = _get_field_by_name(model_class, field_name)
if direct:
# Direct field
try:
new_model = _get_remote_field(field).parent_model()
except AttributeError:
new_model = _get_remote_field(field).model
else:
# Indirect related field
if hasattr(field, 'related_model'): # Django>=1.8
new_model = field.related_model
else:
new_model = field.model()
path += field_name
path += '__'
else:
new_model = model_class
new_fields = get_relation_fields_from_model(new_model)
model_ct = ContentType.objects.get_for_model(new_model)
return (new_fields, model_ct, path) |
// SetMaxResults sets the MaxResults field's value. | func (s *ListTaskDefinitionFamiliesInput) SetMaxResults(v int64) *ListTaskDefinitionFamiliesInput {
s.MaxResults = &v
return s
} |
// handleWarnings looks for the "X-Cf-Warnings" header in the cloud controller
// response and URI decodes them. The value can contain multiple warnings that
// are comma separated. | func (*CloudControllerConnection) handleWarnings(response *http.Response) ([]string, error) {
rawWarnings := response.Header.Get("X-Cf-Warnings")
if len(rawWarnings) == 0 {
return nil, nil
}
var warnings []string
for _, rawWarning := range strings.Split(rawWarnings, ",") {
warning, err := url.QueryUnescape(rawWarning)
if err != nil {
return nil, err
}
warnings = append(warnings, strings.Trim(warning, " "))
}
return warnings, nil
} |
_getTitle
Getter for the title.
Data is used from the vars-column.
The template is used from the configurations.
@return string | protected function _getTitle()
{
$templates = Configure::read('Notifier.templates');
if (array_key_exists($this->_properties['template'], $templates)) {
$template = $templates[$this->_properties['template']];
$vars = json_decode($this->_properties['vars'], true);
return Text::insert($template['title'], $vars);
}
return '';
} |
<p>
retrieveBranch.
</p>
@throws org.apache.maven.plugin.MojoExecutionException
if any.
@return a {@link java.lang.String} object. | public String retrieveBranch() throws MojoExecutionException {
try {
return getRepository().getBranch();
} catch (IOException e) {
throw new MojoExecutionException(e.getClass().getSimpleName(), e);
}
} |
Matches a boolean. | public static DecomposableMatchBuilder0<Boolean> caseBoolean(boolean b) {
List<Matcher<Object>> matchers = new ArrayList<>();
matchers.add(eq(b));
return new DecomposableMatchBuilder0<>(
matchers, new PrimitiveFieldExtractor<>(Boolean.class));
} |
Handles the keyDown event for the dialogs
@param {$.Event} e
@param {boolean} autoDismiss
@return {boolean} | function (e, autoDismiss) {
var $primaryBtn = this.find(".primary"),
buttonId = null,
which = String.fromCharCode(e.which),
$focusedElement = this.find(".dialog-button:focus, a:focus");
function stopEvent() {
e.preventDefault();
e.stopPropagation();
}
// There might be a textfield in the dialog's UI; don't want to mistake normal typing for dialog dismissal
var inTextArea = (e.target.tagName === "TEXTAREA"),
inTypingField = inTextArea || ($(e.target).filter(":text, :password").length > 0);
if (e.which === KeyEvent.DOM_VK_TAB) {
// We don't want to stopEvent() in this case since we might want the default behavior.
// _handleTab takes care of stopping/preventing default as necessary.
_handleTab(e, this);
} else if (e.which === KeyEvent.DOM_VK_ESCAPE) {
buttonId = DIALOG_BTN_CANCEL;
} else if (e.which === KeyEvent.DOM_VK_RETURN && (!inTextArea || e.ctrlKey)) {
// Enter key in single-line text input always dismisses; in text area, only Ctrl+Enter dismisses
// Click primary
stopEvent();
if (e.target.tagName === "BUTTON") {
this.find(e.target).click();
} else if (e.target.tagName !== "INPUT") {
// If the target element is not BUTTON or INPUT, click the primary button
// We're making an exception for INPUT element because of this issue: GH-11416
$primaryBtn.click();
}
} else if (e.which === KeyEvent.DOM_VK_SPACE) {
if ($focusedElement.length) {
// Space bar on focused button or link
stopEvent();
$focusedElement.click();
}
} else if (brackets.platform === "mac") {
// CMD+Backspace Don't Save
if (e.metaKey && (e.which === KeyEvent.DOM_VK_BACK_SPACE)) {
if (_hasButton(this, DIALOG_BTN_DONTSAVE)) {
buttonId = DIALOG_BTN_DONTSAVE;
}
// FIXME (issue #418) CMD+. Cancel swallowed by native shell
} else if (e.metaKey && (e.which === KeyEvent.DOM_VK_PERIOD)) {
buttonId = DIALOG_BTN_CANCEL;
}
} else { // if (brackets.platform === "win") {
// 'N' Don't Save
if (which === "N" && !inTypingField) {
if (_hasButton(this, DIALOG_BTN_DONTSAVE)) {
buttonId = DIALOG_BTN_DONTSAVE;
}
}
}
if (buttonId) {
stopEvent();
_processButton(this, buttonId, autoDismiss);
}
// Stop any other global hooks from processing the event (but
// allow it to continue bubbling if we haven't otherwise stopped it).
return true;
} |
List available database you can install
REST: GET /hosting/web/{serviceName}/databaseCreationCapabilities
@param serviceName [required] The internal name of your hosting | public ArrayList<OvhCreationDatabaseCapabilities> serviceName_databaseCreationCapabilities_GET(String serviceName) throws IOException {
String qPath = "/hosting/web/{serviceName}/databaseCreationCapabilities";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t7);
} |
// DeleteLabel deletes a label. | func (s *Service) DeleteLabel(ctx context.Context, id influxdb.ID) error {
err := s.kv.Update(ctx, func(tx Tx) error {
return s.deleteLabel(ctx, tx, id)
})
if err != nil {
return &influxdb.Error{
Err: err,
}
}
return nil
} |
Returns a HashMap where the key is one of GLY, ALA, VAL, LEU, ILE, SER,
THR, CYS, MET, ASP, ASN, GLU, GLN, ARG, LYS, HIS, PHE, TYR, TRP AND PRO. | public static Map<String, IAminoAcid> getHashMapByThreeLetterCode() {
AminoAcid[] monomers = createAAs();
Map<String, IAminoAcid> map = new HashMap<String, IAminoAcid>();
for (int i = 0; i < monomers.length; i++) {
map.put((String) monomers[i].getProperty(RESIDUE_NAME), monomers[i]);
}
return map;
} |
Notify when an order has been created
@param array $order
@return boolean | public function notifyCreated(array $order)
{
$this->mail->set('order_created_admin', array($order));
if (is_numeric($order['user_id']) && !empty($order['user_email'])) {
return $this->mail->set('order_created_customer', array($order));
}
return false;
} |
// Returns the most recent Image out of a slice of images. | func mostRecentImage(images []images.Image) images.Image {
sortedImages := images
sort.Sort(imageSort(sortedImages))
return sortedImages[len(sortedImages)-1]
} |
// checkExprOrType checks that x is an expression or a type
// (and not a raw type such as [...]T).
// | func (p *parser) checkExprOrType(x ast.Expr) ast.Expr {
switch t := unparen(x).(type) {
case *ast.ParenExpr:
panic("unreachable")
case *ast.UnaryExpr:
if t.Op == token.RANGE {
// the range operator is only allowed at the top of a for statement
p.errorExpected(x.Pos(), "expression")
x = &ast.BadExpr{x.Pos(), x.End()}
}
case *ast.ArrayType:
if len, isEllipsis := t.Len.(*ast.Ellipsis); isEllipsis {
p.error(len.Pos(), "expected array length, found '...'")
x = &ast.BadExpr{x.Pos(), x.End()}
}
}
// all other nodes are expressions or types
return x
} |
Writes all the files inside a static folder to S3. | def _write_files(s3, app, static_url_loc, static_folder, files, bucket,
ex_keys=None, hashes=None):
should_gzip = app.config.get('FLASKS3_GZIP')
add_mime = app.config.get('FLASKS3_FORCE_MIMETYPE')
gzip_include_only = app.config.get('FLASKS3_GZIP_ONLY_EXTS')
new_hashes = []
static_folder_rel = _path_to_relative_url(static_folder)
for file_path in files:
per_file_should_gzip = should_gzip
asset_loc = _path_to_relative_url(file_path)
full_key_name = _static_folder_path(static_url_loc, static_folder_rel,
asset_loc)
key_name = full_key_name.lstrip("/")
logger.debug("Uploading {} to {} as {}".format(file_path, bucket, key_name))
exclude = False
if app.config.get('FLASKS3_ONLY_MODIFIED', False):
file_hash = hash_file(file_path)
new_hashes.append((full_key_name, file_hash))
if hashes and hashes.get(full_key_name, None) == file_hash:
exclude = True
if ex_keys and full_key_name in ex_keys or exclude:
logger.debug("%s excluded from upload" % key_name)
else:
h = {}
# Set more custom headers if the filepath matches certain
# configured regular expressions.
filepath_headers = app.config.get('FLASKS3_FILEPATH_HEADERS')
if filepath_headers:
for filepath_regex, headers in six.iteritems(filepath_headers):
if re.search(filepath_regex, file_path):
for header, value in six.iteritems(headers):
h[header] = value
# check for extension, only if there are extensions provided
if per_file_should_gzip and gzip_include_only:
if os.path.splitext(file_path)[1] not in gzip_include_only:
per_file_should_gzip = False
if per_file_should_gzip:
h["content-encoding"] = "gzip"
if (add_mime or per_file_should_gzip) and "content-type" not in h:
# When we use GZIP we have to explicitly set the content type
# or if the mime flag is True
(mimetype, encoding) = mimetypes.guess_type(file_path,
False)
if mimetype:
h["content-type"] = mimetype
else:
logger.warn("Unable to detect mimetype for %s" %
file_path)
file_mode = 'rb' if six.PY3 else 'r'
with open(file_path, file_mode) as fp:
merged_dicts = merge_two_dicts(get_setting('FLASKS3_HEADERS', app), h)
metadata, params = split_metadata_params(merged_dicts)
if per_file_should_gzip:
compressed = six.BytesIO()
z = gzip.GzipFile(os.path.basename(file_path), 'wb', 9,
compressed)
z.write(fp.read())
z.close()
data = compressed.getvalue()
else:
data = fp.read()
s3.put_object(Bucket=bucket,
Key=key_name,
Body=data,
ACL="public-read",
Metadata=metadata,
**params)
return new_hashes |
Extracts interesting paths from a given path.
Args:
components: Source string represented as a list of components.
Returns:
A list of extracted paths (as strings). | def Extract(self, components):
for index, component in enumerate(components):
if component.lower().endswith(self.EXECUTABLE_EXTENSIONS):
extracted_path = " ".join(components[0:index + 1])
return [extracted_path]
return [] |
Invokes given closure or function withing global IoC scope.
@param ContainerInterface $container
@param callable $scope
@return mixed
@throws \Throwable | public static function runScope(ContainerInterface $container, callable $scope)
{
list ($previous, self::$container) = [self::$container, $container];
try {
return $scope();
} catch (\Throwable $e) {
throw $e;
} finally {
self::$container = $previous;
}
} |
Call a LaTeXML service.
@param latex LaTeX formula
@return MathML String | public LaTeXMLServiceResponse parseAsService(String latex) {
try {
latex = UriComponentsBuilder.newInstance().queryParam("tex", latex).build().encode(StandardCharsets.UTF_8.toString()).getQuery();
} catch (UnsupportedEncodingException ignore) {
LOG.warn("encoding not supported", ignore);
}
String serviceArguments = config.buildServiceRequest();
String payload = serviceArguments + "&" + latex;
RestTemplate restTemplate = new RestTemplate();
try {
LaTeXMLServiceResponse rep = restTemplate.postForObject(config.getUrl(), payload, LaTeXMLServiceResponse.class);
LOG.debug(String.format("LaTeXMLServiceResponse:\n"
+ "statusCode: %s\nstatus: %s\nlog: %s\nresult: %s",
rep.getStatusCode(), rep.getStatus(), rep.getLog(), rep.getResult()));
return rep;
} catch (HttpClientErrorException e) {
LOG.error(e.getResponseBodyAsString());
throw e;
}
} |
Set[PixelFormat]: The available texture formats. | def texture_formats(self):
""""""
info = self._get_renderer_info()
return {PixelFormat(info.texture_formats[i]) for i in range(info.num_texture_formats)} |
// SetError artificially pins the error code returned by impl to err. If err is
// nil, impl will behave normally.
//
// impl must be a memory config isntance created with New, else SetError will
// panic. | func SetError(impl config.Interface, err error) {
impl.(*memoryImpl).err = err
} |
// GetAll returns a slice of *Route for the entire RouteFileStore | func (fs RouteFileStore) GetAll() ([]*Route, error) {
files, err := ioutil.ReadDir(string(fs))
if err != nil {
return nil, err
}
var routes []*Route
for _, file := range files {
fileparts := strings.Split(file.Name(), ".")
if len(fileparts) > 1 && fileparts[1] == "json" {
route, err := fs.Get(fileparts[0])
if err == nil {
routes = append(routes, route)
}
}
}
return routes, nil
} |
Build the entire GUI for this widget. | private void buildGui() {
setTitle(I18nProvider.getGlobal().commandError());
setHeaderIcon(WidgetLayout.iconError);
setIsModal(true);
setShowModalMask(true);
setModalMaskOpacity(WidgetLayout.modalMaskOpacity);
setWidth(WidgetLayout.exceptionWindowWidth);
setHeight(WidgetLayout.exceptionWindowHeightNormal);
setKeepInParentRect(WidgetLayout.exceptionWindowKeepInScreen);
setCanDragResize(true);
centerInPage();
setAutoSize(true);
addCloseClickHandler(this);
addItem(createErrorLayout(error));
} |
Free resources and make this instance unusable | function() {
for (var i = 0, count = this._bind_changed_listeners.length; i < count; i++) {
this._binds[i].removeListener(this._bind_changed_listeners[i]);
}
this._bind_changed_listeners = null;
this.suspendRefreshable();
} |
// GenerateSignerConfig creates a new signer config.
// It generates a fresh user secret and issues a credential
// with four attributes (described above) using the CA's key pair. | func GenerateSignerConfig(roleMask int, ouString string, enrollmentId string, revocationHandle int, key *idemix.IssuerKey, revKey *ecdsa.PrivateKey) ([]byte, error) {
attrs := make([]*FP256BN.BIG, 4)
if ouString == "" {
return nil, errors.Errorf("the OU attribute value is empty")
}
if enrollmentId == "" {
return nil, errors.Errorf("the enrollment id value is empty")
}
attrs[msp.AttributeIndexOU] = idemix.HashModOrder([]byte(ouString))
attrs[msp.AttributeIndexRole] = FP256BN.NewBIGint(roleMask)
attrs[msp.AttributeIndexEnrollmentId] = idemix.HashModOrder([]byte(enrollmentId))
attrs[msp.AttributeIndexRevocationHandle] = FP256BN.NewBIGint(revocationHandle)
rng, err := idemix.GetRand()
if err != nil {
return nil, errors.WithMessage(err, "Error getting PRNG")
}
sk := idemix.RandModOrder(rng)
ni := idemix.BigToBytes(idemix.RandModOrder(rng))
msg := idemix.NewCredRequest(sk, ni, key.Ipk, rng)
cred, err := idemix.NewCredential(key, msg, attrs, rng)
if err != nil {
return nil, errors.WithMessage(err, "failed to generate a credential")
}
credBytes, err := proto.Marshal(cred)
if err != nil {
return nil, errors.WithMessage(err, "failed to marshal credential")
}
// NOTE currently, idemixca creates CRI's with "ALG_NO_REVOCATION"
cri, err := idemix.CreateCRI(revKey, []*FP256BN.BIG{FP256BN.NewBIGint(revocationHandle)}, 0, idemix.ALG_NO_REVOCATION, rng)
if err != nil {
return nil, err
}
criBytes, err := proto.Marshal(cri)
if err != nil {
return nil, errors.WithMessage(err, "failed to marshal CRI")
}
signer := &m.IdemixMSPSignerConfig{
Cred: credBytes,
Sk: idemix.BigToBytes(sk),
OrganizationalUnitIdentifier: ouString,
Role: int32(roleMask),
EnrollmentId: enrollmentId,
CredentialRevocationInformation: criBytes,
}
return proto.Marshal(signer)
} |
Convert our schema to be more avro like. | def make_valid_avro(items, # type: Avro
alltypes, # type: Dict[Text, Dict[Text, Any]]
found, # type: Set[Text]
union=False # type: bool
):
# type: (...) -> Union[Avro, Dict, Text]
""""""
# Possibly could be integrated into our fork of avro/schema.py?
if isinstance(items, MutableMapping):
items = copy.copy(items)
if items.get("name") and items.get("inVocab", True):
items["name"] = avro_name(items["name"])
if "type" in items and items["type"] in (
"https://w3id.org/cwl/salad#record",
"https://w3id.org/cwl/salad#enum", "record", "enum"):
if (hasattr(items, "get") and items.get("abstract")) or ("abstract"
in items):
return items
if items["name"] in found:
return cast(Text, items["name"])
found.add(items["name"])
for field in ("type", "items", "values", "fields"):
if field in items:
items[field] = make_valid_avro(
items[field], alltypes, found, union=True)
if "symbols" in items:
items["symbols"] = [avro_name(sym) for sym in items["symbols"]]
return items
if isinstance(items, MutableSequence):
ret = []
for i in items:
ret.append(make_valid_avro(i, alltypes, found, union=union)) # type: ignore
return ret
if union and isinstance(items, string_types):
if items in alltypes and avro_name(items) not in found:
return cast(Dict, make_valid_avro(alltypes[items], alltypes, found,
union=union))
items = avro_name(items)
return items |
Modular reduction preperation
@see protectedSlidingWindow()
@access private
@param Array $x
@param Array $n
@param Integer $mode
@return Array | public function protectedPrepareReduce($x, $n, $mode)
{
if ($mode == MATH_BIGINTEGER_MONTGOMERY) {
return $this->protectedPrepMontgomery($x, $n);
}
return $this->protectedReduce($x, $n, $mode);
} |
POST /cornerstone/discussions/ | def create
@discussion = Discussion.new(params[:discussion])
# assign user if signed in
if current_cornerstone_user
@discussion.user = current_cornerstone_user
@discussion.posts.first.user = current_cornerstone_user
end
respond_with(@discussion.category, @discussion) do |format|
if @discussion.save
flash[:notice] = 'Discussion was successfully created.'
format.html {redirect_to category_discussion_path(@discussion.category, @discussion)}
else
@categories = Category.discussions
format.html {render :new}
end
end
end |
Maps the query result to instances of IconData.
@param array $iconData
@return array|IconData[] | protected function mapIconDataResult(array $iconData): array
{
$result = [];
foreach ($iconData as $data) {
$result[] = IconData::createFromArray($data);
}
return $result;
} |
Loads the settings from the inputed filename.
:param filename | <str>
:return <bool> | success | def load(self, filename):
if not os.path.exists(filename):
return False
data = None
with open(filename, 'r') as f:
data = f.read()
try:
root = yaml.load(data)
except StandardError:
root = None
if root is None:
root = {}
self._root = root
self._stack = [self._root]
return len(self._root) != 0 |
// midnight returns the date of the midnight of the provided time. | func (e Engine) midnight(t time.Time) time.Time {
y, m, d := t.Date()
return time.Date(y, m, d, 0, 0, 0, 0, t.Location())
} |
// GetLocalPeer returns an internal peer connected to the specified realm. | func (r *defaultRouter) GetLocalPeer(realmURI URI, details map[string]interface{}) (Peer, error) {
realm, ok := r.realms[realmURI]
if !ok {
return nil, NoSuchRealmError(realmURI)
}
// TODO: session open/close callbacks?
return realm.getPeer(details)
} |
// UnmarshalBinary decodes the object from binary form. | func (p *RXParamSetupReqPayload) UnmarshalBinary(data []byte) error {
if len(data) != 4 {
return errors.New("lorawan: 4 bytes of data are expected")
}
if err := p.DLSettings.UnmarshalBinary(data[0:1]); err != nil {
return err
}
// append one block of empty bits at the end of the slice since the
// binary to uint32 expects 32 bits.
b := make([]byte, len(data))
copy(b, data)
b = append(b, byte(0))
p.Frequency = binary.LittleEndian.Uint32(b[1:5]) * 100
return nil
} |
Override the :meth:`.Concurrency.periodic_task` to implement
the :class:`.Arbiter` :ref:`periodic task <actor-periodic-task>`. | async def periodic_task(self, actor, **kw):
while True:
interval = 0
#
if actor.started():
# managed actors job
self.manage_actors(actor)
for m in list(self.monitors.values()):
_remove_monitor(m)
interval = MONITOR_TASK_PERIOD
#
actor.event('periodic_task').fire()
if actor.cfg.reload and autoreload.check_changes():
# reload changes
actor.stop(exit_code=autoreload.EXIT_CODE)
if not actor.stopped():
try:
await asyncio.sleep(interval)
except asyncio.CancelledError:
break |
Convert from an emitter to a XML element description
@param document
The document the element will be part of
@param emitter
The emitter to convert
@return The XML element based on the configured emitter | private static Element emitterToElement(Document document,
ConfigurableEmitter emitter) {
Element root = document.createElement("emitter");
root.setAttribute("name", emitter.name);
root.setAttribute("imageName", emitter.imageName == null ? ""
: emitter.imageName);
root
.setAttribute("useOriented", emitter.useOriented ? "true"
: "false");
root
.setAttribute("useAdditive", emitter.useAdditive ? "true"
: "false");
if (emitter.usePoints == Particle.INHERIT_POINTS) {
root.setAttribute("renderType", "inherit");
}
if (emitter.usePoints == Particle.USE_POINTS) {
root.setAttribute("renderType", "points");
}
if (emitter.usePoints == Particle.USE_QUADS) {
root.setAttribute("renderType", "quads");
}
root.appendChild(createRangeElement(document, "spawnInterval",
emitter.spawnInterval));
root.appendChild(createRangeElement(document, "spawnCount",
emitter.spawnCount));
root.appendChild(createRangeElement(document, "initialLife",
emitter.initialLife));
root.appendChild(createRangeElement(document, "initialSize",
emitter.initialSize));
root.appendChild(createRangeElement(document, "xOffset",
emitter.xOffset));
root.appendChild(createRangeElement(document, "yOffset",
emitter.yOffset));
root.appendChild(createRangeElement(document, "initialDistance",
emitter.initialDistance));
root.appendChild(createRangeElement(document, "speed", emitter.speed));
root
.appendChild(createRangeElement(document, "length",
emitter.length));
root.appendChild(createRangeElement(document, "emitCount",
emitter.emitCount));
root
.appendChild(createValueElement(document, "spread",
emitter.spread));
root.appendChild(createValueElement(document, "angularOffset",
emitter.angularOffset));
root.appendChild(createValueElement(document, "growthFactor",
emitter.growthFactor));
root.appendChild(createValueElement(document, "gravityFactor",
emitter.gravityFactor));
root.appendChild(createValueElement(document, "windFactor",
emitter.windFactor));
root.appendChild(createValueElement(document, "startAlpha",
emitter.startAlpha));
root.appendChild(createValueElement(document, "endAlpha",
emitter.endAlpha));
root.appendChild(createValueElement(document, "alpha", emitter.alpha));
root.appendChild(createValueElement(document, "size", emitter.size));
root.appendChild(createValueElement(document, "velocity",
emitter.velocity));
root
.appendChild(createValueElement(document, "scaleY",
emitter.scaleY));
Element color = document.createElement("color");
ArrayList list = emitter.colors;
for (int i = 0; i < list.size(); i++) {
ColorRecord record = (ColorRecord) list.get(i);
Element step = document.createElement("step");
step.setAttribute("offset", "" + record.pos);
step.setAttribute("r", "" + record.col.r);
step.setAttribute("g", "" + record.col.g);
step.setAttribute("b", "" + record.col.b);
color.appendChild(step);
}
root.appendChild(color);
return root;
} |
/*
RTMPPlayURL generates RTMP play URL | public String RTMPPlayURL(String domain, String hub, String streamKey) {
return String.format("rtmp://%s/%s/%s", domain, hub, streamKey);
} |
// Errorf formats the message and returns the *ErrorResponse with the
// formatted message according to package fmt | func Errorf(status int, format string, v ...interface{}) (int, *ErrorResponse) {
return Error(status, fmt.Sprintf(format, v...))
} |
Return the context containing the specified property.
@param string $property
@return boolean|Context | public function with($property)
{
if (property_exists($this, $property)) {
return $this;
}
if ($this->_parent) {
return $this->_parent->with($property);
}
return false;
} |