comment
stringlengths 16
255
| code
stringlengths 52
3.87M
|
---|---|
Validate bucket.
@param left
the left
@param right
the right
@param operator
the operator
@return true, if successful | private boolean validateBucket(String left, String right, String operator)
{
Double leftValue = Double.valueOf(left);
Double rightValue = Double.valueOf(right);
logger.debug("Comparison expression " + operator + "found with left value: " + left + " right value: " + right);
if (Expression.GREATER_THAN.equals(operator))
{
return leftValue > rightValue;
}
else if (Expression.GREATER_THAN_OR_EQUAL.equals(operator))
{
return leftValue >= rightValue;
}
else if (Expression.LOWER_THAN.equals(operator))
{
return leftValue < rightValue;
}
else if (Expression.LOWER_THAN_OR_EQUAL.equals(operator))
{
return leftValue <= rightValue;
}
else if (Expression.EQUAL.equals(operator))
{
return leftValue == rightValue;
}
else
{
logger.error(operator + " in having clause is not supported in Kundera");
throw new UnsupportedOperationException(operator + " in having clause is not supported in Kundera");
}
} |
Verifies whether the user has permission to grant all of the provided roles. If not it throws an UnauthorizedException.
@throws UnauthorizedException User did not have the permission to grant at least one role. | private void verifyPermissionToGrantRoles(Subject subject, Iterable<RoleIdentifier> roleIds) {
Set<RoleIdentifier> unauthorizedIds = Sets.newTreeSet();
boolean anyAuthorized = false;
for (RoleIdentifier roleId : roleIds) {
// Verify the caller has permission to grant this role
if (subject.hasPermission(Permissions.grantRole(roleId))) {
anyAuthorized = true;
} else {
unauthorizedIds.add(roleId);
}
}
if (!unauthorizedIds.isEmpty()) {
// If the caller was not authorized to assign any of the provided roles raise a generic exception, otherwise
// the exception provides insight as to which roles were unauthorized. This provides some helpful feedback
// where appropriate without exposing potentially exploitable information about whether the subject's API key
// is valid.
if (!anyAuthorized) {
throw new UnauthorizedException();
} else {
throw new UnauthorizedException("Not authorized for roles: " + Joiner.on(", ").join(unauthorizedIds));
}
}
} |
Adds image parameters to a list of parameters
@param params
@param images | protected void handleFeedImages(List<Pair<String, CharSequence>> params,
Collection<IFeedImage> images) {
if (images != null && images.size() > 4) {
throw new IllegalArgumentException("At most four images are allowed, got " +
Integer.toString(images.size()));
}
if (null != images && !images.isEmpty()) {
int image_count = 0;
for (IFeedImage image : images) {
++image_count;
String imageUrl = image.getImageUrlString();
assert null != imageUrl && "".equals(imageUrl) : "Image URL must be provided";
params.add(new Pair<String, CharSequence>(String.format("image_%d", image_count),
image.getImageUrlString()));
assert null != image.getLinkUrl() : "Image link URL must be provided";
params.add(new Pair<String, CharSequence>(String.format("image_%d_link", image_count),
image.getLinkUrl().toString()));
}
}
} |
// newUploadRequest creates a new h.Request for uploading | func newUploadRequest(target, username, secret string, headers map[string]string, a *asset) (*h.Request, error) {
req, err := h.NewRequest(h.MethodPut, target, a.ReadCloser)
if err != nil {
return nil, err
}
req.ContentLength = a.Size
req.SetBasicAuth(username, secret)
for k, v := range headers {
req.Header.Add(k, v)
}
return req, err
} |
Create a type list. | def run(self):
""""""
config = self.state.document.settings.env.config
# Group processes by category
processes = get_processes(config.autoprocess_process_dir, config.autoprocess_source_base_url)
processes.sort(key=itemgetter('type'))
processes_by_types = {k: list(g) for k, g in groupby(processes, itemgetter('type'))}
listnode = nodes.bullet_list()
for typ in sorted(processes_by_types.keys()):
par = nodes.paragraph()
par += nodes.literal(typ, typ)
par += nodes.Text(' - ')
processes = sorted(processes_by_types[typ], key=itemgetter('name'))
last_process = processes[-1]
for process in processes:
node = nodes.reference('', process['name'], internal=True)
node['refuri'] = config.autoprocess_definitions_uri + '#process-' + process['slug']
node['reftitle'] = process['name']
par += node
if process != last_process:
par += nodes.Text(', ')
listnode += nodes.list_item('', par)
return [listnode] |
Returns an empty module. | def load_module(self, fullname):
mod = sys.modules.setdefault(fullname, imp.new_module(fullname))
mod.__file__ = self._path
mod.__loader__ = self
mod.__path__ = []
mod.__package__ = fullname
return mod |
Returns the javascript coming with the object
@return string javascript string | public function script($with_ele=1)
{
$this->update();
$r = '';
if ( isset($this->attr['id']) ){
if ( isset($this->cfg['events']) ){
foreach ( $this->cfg['events'] as $event => $fn ){
$r .= '.'.$event.'('.
( strpos($fn, 'function') === 0 ? $fn : 'function(e){'.$fn.'}' ).
')';
}
}
if ( isset($this->cfg['widget'], $this->cfg['widget']['name']) ){
$r .= '.'.$this->cfg['widget']['name'].'(';
if ( isset($this->cfg['widget']['options']) ){
$r .= '{';
foreach ( $this->cfg['widget']['options'] as $n => $o ){
$r .= '"'.$n.'":';
if ( \is_string($o) ){
$o = trim($o);
if ( (strpos($o, 'function(') === 0) ){
$r .= $o;
}
else{
$r .= '"'.bbn\str::escape_dquotes($o).'"';
}
}
else if ( \is_bool($o) ){
$r .= $o ? 'true' : 'false';
}
else{
$r .= json_encode($o);
}
$r .= ',';
}
$r .= '}';
}
$r .= ')';
}
if ( !empty($this->help) ){
// tooltip
}
if ( !empty($r) ){
if ( $with_ele ){
$r = '$("#'.$this->attr['id'].'")'.$r.';'.PHP_EOL;
}
else{
$r = $r.';'.PHP_EOL;
}
}
}
if ( !empty($this->script) ){
$r .= $this->script.PHP_EOL;
}
if ( \is_array($this->content) ){
foreach ( $this->content as $c ){
if ( \is_array($c) ){
$c = new bbn\html\element($c);
}
if (\is_object($c) && method_exists($c, 'script') ){
$r .= $c->script();
}
}
}
return $r;
} |
Given a query result from a SPARQL query, obtain the number value at the
given variable
@param resultRow the result from a SPARQL query
@param variableName the name of the variable to obtain
@return the Integer value, or null otherwise | public static Integer getIntegerValue(QuerySolution resultRow, String variableName) {
if (resultRow != null) {
Resource res = resultRow.getResource(variableName);
if (res != null && res.isLiteral()) {
Literal val = res.asLiteral();
if (val != null) {
return Integer.valueOf(val.getInt());
}
}
}
return null;
} |
锁定
@param int $id
@return boolean | public function isLocked($id=-1)
{
if($id === -1){
return $self->state === 0 ? true : false;
}else{
$rec = Member::find($id)->state;
if(count($rec)){
return Member::find($id)->state === 0 ? true : false;
}else{
die('FooWeChat\Authorize\Auth\isLocked: 无效id');
}
}
} |
Sets the type of this arc to the specified value. | public void setArcType (int type) {
if (type != OPEN && type != CHORD && type != PIE) {
throw new IllegalArgumentException("Invalid Arc type: " + type);
}
this.type = type;
} |
********************************************************************************************************************************************************************** | public function ajouterAdresseFromArray($adresse = array(), $params = array())
{
$mail = new mailObject();
$arrayRetour=array();
if (count($adresse)>0) {
$select ="";
$leftJoin="";
$numero=$adresse['numero'];
$indicatif=$adresse['indicatif'];
if ($numero != '' && $numero !='0') {
$select .=" AND ha.numero='".$numero."' ";
if ($indicatif!='' && $indicatif!='0') {
$select .=" AND ha.idIndicatif='".$indicatif."' ";
} else {
$select .=" AND ha.idIndicatif='0' ";
}
} else {
$select .=" AND ha.numero='0' AND ha.idIndicatif='0' ";
}
if ($adresse['idRue']>0) {
$select .=" AND ha.idRue ='".$adresse['idRue']."' ";
} elseif ($adresse['idSousQuartier']>0) {
$select .=" AND ha.idSousQuartier ='".$adresse['idSousQuartier']."' AND ha.idRue='0' ";
} elseif ($adresse['idQuartier']>0) {
$select .=" AND ha.idQuartier ='".$adresse['idQuartier']."' AND ha.idRue='0' AND ha.idSousQuartier='0' ";
} elseif ($adresse['idVille']>0) {
$select .=" AND ha.idVille ='".$adresse['idVille']."' AND ha.idRue='0' AND ha.idSousQuartier='0' AND ha.idQuartier='0' ";
}
$reqVerifAdresse = "SELECT ha.idAdresse as idAdresse,ha.idHistoriqueAdresse as idHistoriqueAdresse
FROM historiqueAdresse ha, historiqueAdresse ha2
".$leftJoin."
WHERE 1=1
".$select."
AND ha2.idAdresse = ha.idAdresse
GROUP BY ha.idAdresse , ha.idHistoriqueAdresse
HAVING ha.idHistoriqueAdresse = max(ha2.idHistoriqueAdresse)
";
$resVerifAdresse = $this->connexionBdd->requete($reqVerifAdresse);
if (mysql_num_rows($resVerifAdresse)==1) {
//l'adresse existe deja , on recupere son id
$fetchAdresse = mysql_fetch_assoc($resVerifAdresse);
$idAdresse = $fetchAdresse['idAdresse'];
$arrayRetour = array("idAdresse"=>$idAdresse,"newAdresse"=>true);
// on va ecraser les coordonnees googlemap dans tous les cas
$reqIdHistoriqueAdresse = "
SELECT ha1.idHistoriqueAdresse as idHistoriqueAdresse, ha1.coordonneesVerrouillees as coordonneesVerrouillees
FROM historiqueAdresse ha1, historiqueAdresse ha2
WHERE
ha2.idAdresse = ha1.idAdresse
AND ha1.idAdresse = '$idAdresse'
GROUP BY ha1.idAdresse, ha2.idHistoriqueAdresse
HAVING ha1.idHistoriqueAdresse = max(ha2.idHistoriqueAdresse)
";
$resIdHistoriqueAdresse = $this->connexionBdd->requete($reqIdHistoriqueAdresse);
if (mysql_num_rows($resIdHistoriqueAdresse)==1) {
$fetchIdHistoriqueAdresse = mysql_fetch_assoc($resIdHistoriqueAdresse);
if ($fetchIdHistoriqueAdresse['idHistoriqueAdresse']!='' && $fetchIdHistoriqueAdresse['idHistoriqueAdresse']!='0') {
$longitude='0';
$latitude='0';
// attention si les coordonnees on ete verrouillees , elles ne sont pas mis a jour (verrouillees si modifiées avec la popup googlemap sur le detail d'une adresse
if (isset($adresse['longitude']) && $adresse['longitude']!='' && isset($adresse['latitude']) && $adresse['latitude']!='' && $fetchIdHistoriqueAdresse['coordonneesVerrouillees']!='1') {
$longitude=$adresse['longitude'];
$latitude=$adresse['latitude'];
$reqUpdateCoordonnees = "UPDATE historiqueAdresse SET longitude='$longitude',latitude='$latitude' WHERE idHistoriqueAdresse='".$fetchIdHistoriqueAdresse['idHistoriqueAdresse']."'";
$resUpdateCoordonnees = $this->connexionBdd->requete($reqUpdateCoordonnees);
}
}
}
} elseif (mysql_num_rows($resVerifAdresse)>1) {
// il y a des adresses redondantes : envoyer un mail
$this->erreurs->ajouter("Il existe une adresse redondante dans la base de donnée , veuillez contacter l'administrateur");
$fetchAdresse = mysql_fetch_assoc($resVerifAdresse);
$idAdresse =$fetchAdresse['idAdresse']; // on prend la premiere
$arrayRetour = array("idAdresse"=>$idAdresse,"newAdresse"=>false);
} else {
// on enregistre la nouvelle adresse et on renvoi son id
$newIdAdresse = $this->getNewIdAdresse();
// Auto filling of the subsidiaries ID (ex: filling city and country id from neighborhood id)
if ($adresse['idRue']>0) {
$idRue = $adresse['idRue'];
$idSousQuartier = $this->getIdSousQuartier($idRue);
$idQuartier = $this->getIdQuartier($idSousQuartier);
$idVille = $this->getIdVille($idQuartier);
$idPays = $this->getIdPays($idVille);
} elseif ($adresse['idSousQuartier']>0) {
$idRue = 0;
$idSousQuartier = $adresse['idSousQuartier'];
$idQuartier = $this->getIdQuartier($idSousQuartier);
$idVille = $this->getIdVille($idQuartier);
$idPays = $this->getIdPays($idVille);
$numero="";
$indicatif="";
} elseif ($adresse['idQuartier']>0) {
$idRue = 0;
$idSousQuartier = 0;
$idQuartier = $adresse['idQuartier'];
$idVille = $this->getIdVille($idQuartier);
$idPays = $this->getIdPays($idVille);
$numero="";
$indicatif="";
} elseif ($adresse['idVille']>0) {
$idRue = 0;
$idSousQuartier = 0;
$idQuartier = 0;
$idVille = $adresse['idVille'];
$idPays = $this->getIdPays($idVille);
$numero="";
$indicatif="";
}
// recuperation du nom de la rue , le complément et l'indicatif
$reqRue = "SELECT idRue, nom, prefixe FROM rue WHERE idRue = '".$idRue."'";
$resRue = $this->connexionBdd->requete($reqRue);
$fetchRue = mysql_fetch_assoc($resRue);
$idUtilisateur = 0;
$auth = new archiAuthentification();
if ($auth->estConnecte()) {
$idUtilisateur = $auth->getIdUtilisateur();
}
$longitude='0';
$latitude='0';
if (isset($adresse['longitude']) && $adresse['longitude']!='' && isset($adresse['latitude']) && $adresse['latitude']!='') {
$longitude=$adresse['longitude'];
$latitude=$adresse['latitude'];
}
$reqInsertAdresse="INSERT INTO historiqueAdresse (idAdresse,date,idRue,numero, idQuartier,idSousQuartier,idPays, idVille,nom,idIndicatif,idUtilisateur,longitude,latitude)
VALUES ('".$newIdAdresse."',now(),'".$idRue."','".$numero."','".$idQuartier."','".$idSousQuartier."','".$idPays."','".$idVille."',\"".$numero.' '.$fetchRue['prefixe'].' '.$fetchRue['nom']."\",'".$indicatif."','".$idUtilisateur."','".$longitude."','".$latitude."')
";
$resInsertAdresse = $this->connexionBdd->requete($reqInsertAdresse);
$idAdresse = $newIdAdresse;
$libelleAdresse = $this->getIntituleAdresse(array('nomRue'=>$fetchRue['nom'],'idIndicatif'=>$indicatif,'numero'=>$numero,'prefixeRue'=>$fetchRue['prefixe']));
// ****************************************************************************************************************************************************************
// envoi du mail de notification aux administrateurs => ce mail s'envoi maintenant en meme temps que le signalement d'un nouvel evenement sur une nouvelle adresse dans la fonction ajouterNouveauDossier() sauf dans le cas
// d'une modif d'un groupe d'adresse ( option params['envoiMailAdminSiNouvelleAdresse'])
if (isset($params['envoiMailAdminSiNouvelleAdresse']) && $params['envoiMailAdminSiNouvelleAdresse']==true) {
if (isset($this->variablesGet['archiIdEvenementGroupeAdresses'])) {
$message = "Une nouvelle adresse a été ajoutée sur un groupe d'adresses existant: <a href='".$this->creerUrl('', '', array('archiAffichage'=>'adresseDetail',"archiIdAdresse"=>$idAdresse,"archiIdEvenementGroupeAdresse"=>$this->variablesGet['archiIdEvenementGroupeAdresses']))."'>".$libelleAdresse."</a><br>";
} else {
$message = "Une nouvelle adresse a été ajoutée sur un groupe d'adresses existant: <a href='".$this->creerUrl('', 'adresseDetail', array("archiIdAdresse"=>$idAdresse))."'>".$libelleAdresse."</a><br>";
}
// recuperation des infos sur l'utilisateur qui fais la modif
$utilisateur = new archiUtilisateur();
$arrayInfosUtilisateur = $utilisateur->getArrayInfosFromUtilisateur($this->session->getFromSession('utilisateurConnecte'.$this->idSite));
$message .="<br>".$arrayInfosUtilisateur['nom']." - ".$arrayInfosUtilisateur['prenom']." - ".$arrayInfosUtilisateur['mail']."<br>";
$mail->sendMailToAdministrators($mail->getSiteMail(), "Ajout d'une adresse sur archi-strasbourg.org : ".$libelleAdresse, $message, " and alerteMail='1' ", true);
$u = new archiUtilisateur();
$u->ajouteMailEnvoiRegroupesAdministrateurs(array('contenu'=>$message,'idTypeMailRegroupement'=>4,'criteres'=>" and alerteMail='1' "));
}
// ****************************************************************************************************************************************************************
// envoi du mail aux utilisateurs dont la notification est activée (alerteMail)
// ****************************************************************************************************************************************************************
//ATTENTION : on n'envoit plus de mails aux utilisateurs a chaque creation d'adresse, on envoi un mail de resumé de creation d'adresse chaque semaine.
/*$reqUtilisateurs = "SELECT idUtilisateur,mail FROM utilisateur WHERE alerteMail='1' and compteActif='1' and estAdmin='0'";
$resUtilisateurs = $this->connexionBdd->requete($reqUtilisateurs);
while($fetchUtilisateurs = mysql_fetch_assoc($resUtilisateurs))
{
if($fetchUtilisateurs['idUtilisateur']!=$auth->getIdUtilisateur())
{
$message="";
$message.="Un utilisateur a ajouté une adresse sur le site : <br>".$libelleAdresse;
$message.=$this->getMessageDesabonnerAlerteMail();
$sujet = "Une nouvelle adresse a été ajouté sur le site : <a href='".$this->creerUrl('','',array(''=>))."'>".$libelleAdresse."</a>";
$mail->sendMail($mail->getSiteMail(),$fetchUtilisateurs['mail'],$sujet,$message,true);
}
}*/
// ****************************************************************************************************************************************************************
$arrayRetour = array("idAdresse"=>$idAdresse,"newAdresse"=>true);
}
} else {
// erreur dans le tableau d'adresse (ajouterAdressesFromArray)
$this->erreurs->ajouter("Erreur dans la saisie de l'adresse");
$idAdresse = 0;
$arrayRetour = array();
}
return $arrayRetour;
} |
Insert data in a keyspace.
@param table
@param fields | public void insertData(String table, Map<String, Object> fields) {
String query = this.cassandraqueryUtils.insertData(table, fields);
LOGGER.debug(query);
executeQuery(query);
} |
{@inheritDoc}
@see org.modeshape.sequencer.ddl.StandardDdlParser#initializeTokenStream(org.modeshape.sequencer.ddl.DdlTokenStream) | @Override
protected void initializeTokenStream( DdlTokenStream tokens ) {
super.initializeTokenStream(tokens);
tokens.registerKeyWords(CUSTOM_KEYWORDS);
tokens.registerStatementStartPhrase(ALTER_PHRASES);
tokens.registerStatementStartPhrase(CREATE_PHRASES);
tokens.registerStatementStartPhrase(DROP_PHRASES);
tokens.registerStatementStartPhrase(SET_PHRASES);
tokens.registerStatementStartPhrase(MISC_PHRASES);
} |
// Get blocks until it can return an item to be processed. If shutdown = true,
// the caller should end their goroutine. You must call Done with item when you
// have finished processing it. | func (q *Type) Get() (item interface{}, shutdown bool) {
q.cond.L.Lock()
defer q.cond.L.Unlock()
for len(q.queue) == 0 && !q.shuttingDown {
q.cond.Wait()
}
if len(q.queue) == 0 {
// We must be shutting down.
return nil, true
}
item, q.queue = q.queue[0], q.queue[1:]
q.processing.insert(item)
q.dirty.delete(item)
return item, false
} |
See `cirq.protocols.SupportsApproximateEquality`. | def _approx_eq_(self, other: Any, atol: Union[int, float]) -> bool:
""""""
if not isinstance(other, type(self)):
return NotImplemented
return cirq.protocols.approx_eq(
self._moments,
other._moments,
atol=atol
) and self._device == other._device |
/*
Have to change Bytes into a Long, to avoid the inevitable signs in the Hash | private static long hashToLong(int hash) {
long rv;
if(hash<0) {
rv = 0xFFFFFFFFL & hash;
} else {
rv = hash;
}
return rv;
} |
// configure TLS and retry settings before making any connections | func (flag *ClientFlag) configure(sc *soap.Client) (soap.RoundTripper, error) {
if flag.cert != "" {
cert, err := tls.LoadX509KeyPair(flag.cert, flag.key)
if err != nil {
return nil, err
}
sc.SetCertificate(cert)
}
// Set namespace and version
sc.Namespace = "urn:" + flag.vimNamespace
sc.Version = flag.vimVersion
sc.UserAgent = fmt.Sprintf("govc/%s", Version)
if err := flag.SetRootCAs(sc); err != nil {
return nil, err
}
if err := sc.LoadThumbprints(flag.tlsKnownHosts); err != nil {
return nil, err
}
if t, ok := sc.Transport.(*http.Transport); ok {
var err error
value := os.Getenv("GOVC_TLS_HANDSHAKE_TIMEOUT")
if value != "" {
t.TLSHandshakeTimeout, err = time.ParseDuration(value)
if err != nil {
return nil, err
}
}
}
// Retry twice when a temporary I/O error occurs.
// This means a maximum of 3 attempts.
return vim25.Retry(sc, vim25.TemporaryNetworkError(3)), nil
} |
get the interval of two times | def get_time_interval(time1, time2):
''''''
try:
#convert time to timestamp
time1 = time.mktime(time.strptime(time1, '%Y/%m/%d %H:%M:%S'))
time2 = time.mktime(time.strptime(time2, '%Y/%m/%d %H:%M:%S'))
seconds = (datetime.datetime.fromtimestamp(time2) - datetime.datetime.fromtimestamp(time1)).seconds
#convert seconds to day:hour:minute:second
days = seconds / 86400
seconds %= 86400
hours = seconds / 3600
seconds %= 3600
minutes = seconds / 60
seconds %= 60
return '%dd %dh %dm %ds' % (days, hours, minutes, seconds)
except:
return 'N/A' |
Creates a RSA key with the given key size and additional values.
@param int $size The key size in bits
@param array $values values to configure the key | public static function createRSAKey(int $size, array $values = []): JWK
{
if (0 !== $size % 8) {
throw new \InvalidArgumentException('Invalid key size.');
}
if (384 > $size) {
throw new \InvalidArgumentException('Key length is too short. It needs to be at least 384 bits.');
}
$key = \openssl_pkey_new([
'private_key_bits' => $size,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
]);
\openssl_pkey_export($key, $out);
$rsa = RSAKey::createFromPEM($out);
$values = \array_merge(
$values,
$rsa->toArray()
);
return JWK::create($values);
} |
Applies the specified timezone to all dates in the list.
All dates added to this list will also have this timezone
applied.
@param timeZone a timezone to apply to contained dates | public final void setTimeZone(final TimeZone timeZone) {
if (!Value.DATE.equals(type)) {
for (Date date: this) {
((DateTime) date).setTimeZone(timeZone);
}
}
this.timeZone = timeZone;
this.utc = false;
} |
Create a new instance using the specified API key and configured {@link Retrofit}. | public static PagerDuty create(String apiKey, Retrofit retrofit) {
checkStringArgument(apiKey, "apiKey");
checkNotNull(retrofit, "retrofit");
return realPagerDuty(apiKey, retrofit.create(EventService.class));
} |
Returns true if the relation holds. | private static boolean polylineRelateMultiPoint_(Polyline polyline_a,
MultiPoint multipoint_b, double tolerance, int relation,
ProgressTracker progress_tracker) {
switch (relation) {
case Relation.disjoint:
return polylineDisjointMultiPoint_(polyline_a, multipoint_b,
tolerance, progress_tracker);
case Relation.contains:
return polylineContainsMultiPoint_(polyline_a, multipoint_b,
tolerance, progress_tracker);
case Relation.touches:
return polylineTouchesMultiPoint_(polyline_a, multipoint_b,
tolerance, progress_tracker);
case Relation.crosses:
return polylineCrossesMultiPoint_(polyline_a, multipoint_b,
tolerance, progress_tracker);
default:
break; // warning fix
}
return false;
} |
Returns an `Executor.Runner` for the given java command. | def runner(self, classpath, main, jvm_options=None, args=None, cwd=None):
""""""
return self._runner(*self._scrub_args(classpath, main, jvm_options, args, cwd=cwd)) |
Transliterate Unicode string to a initials.
@param str Unicode String to initials.
@return String initials. | public static String initials(final String str) {
if (str == null) {
return "";
}
StringBuilder sb = new StringBuilder();
Pattern p = Pattern.compile("^\\w|\\s+\\w");
Matcher m = p.matcher(decode(str));
while (m.find()) {
sb.append(m.group().replaceAll(" ", ""));
}
return sb.toString();
} |
Invokes the /app-xxxx/run API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Apps#API-method:-/app-xxxx%5B/yyyy%5D/run | def app_run(app_name_or_id, alias=None, input_params={}, always_retry=True, **kwargs):
input_params_cp = Nonce.update_nonce(input_params)
fully_qualified_version = app_name_or_id + (('/' + alias) if alias else '')
return DXHTTPRequest('/%s/run' % fully_qualified_version, input_params_cp, always_retry=always_retry, **kwargs) |
A CSS Selector .class > div + h1 li a:hover Selectors are made out of one or more Elements, see above. | function () {
var sel, e, elements = [], c, match, extend, extendList = [];
while ((extend = $(this.extend)) || (e = $(this.element))) {
if (extend) {
extendList.push.apply(extendList, extend);
} else {
if (extendList.length) {
error("Extend can only be used at the end of selector");
}
c = input.charAt(i);
elements.push(e)
e = null;
}
if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') { break }
}
if (elements.length > 0) { return new(tree.Selector)(elements, extendList); }
if (extendList.length) { error("Extend must be used to extend a selector, it cannot be used on its own"); }
} |
example: {% captureas myvar 1 %}content...{% endcaptureas %} - {{ myvar }}
result: content... - content...
example: {% captureas myvar %}content...{% endcaptureas %} - {{ myvar }}
result: - content... | def captureas(parser, arg):
args = arg.contents.split()
if not 2 <= len(args) <= 3:
raise template.TemplateSyntaxError('"captureas" node requires a variable name and/or assign only')
nodelist = parser.parse(('endcaptureas',))
parser.delete_first_token()
return CaptureasNode(nodelist, args) |
// Find returns the user with the given name. nil is returned if no user exists
// with the given name. | func (u Users) Find(name string) *User {
for _, user := range u {
if user.Name == name {
return user
}
}
return nil
} |
{@inheritDoc}
@see \Ajax\semantic\html\base\HtmlSemDoubleElement::run() | public function run(JsUtils $js){
parent::run($js);
return $js->semantic()->sticky("#".$this->identifier,$this->_params);
} |
Print ping exit statistics | def exit_statistics(hostname, start_time, count_sent, count_received, min_time, avg_time, max_time, deviation):
end_time = datetime.datetime.now()
duration = end_time - start_time
duration_sec = float(duration.seconds * 1000)
duration_ms = float(duration.microseconds / 1000)
duration = duration_sec + duration_ms
package_loss = 100 - ((float(count_received) / float(count_sent)) * 100)
print(f'\b\b--- {hostname} ping statistics ---')
try:
print(f'{count_sent} packages transmitted, {count_received} received, {package_loss}% package loss, time {duration}ms')
except ZeroDivisionError:
print(f'{count_sent} packets transmitted, {count_received} received, 100% packet loss, time {duration}ms')
print(
'rtt min/avg/max/dev = %.2f/%.2f/%.2f/%.2f ms' % (
min_time.seconds*1000 + float(min_time.microseconds)/1000,
float(avg_time) / 1000,
max_time.seconds*1000 + float(max_time.microseconds)/1000,
float(deviation)
)
) |
// path is only passed for debugging purposes | func (c *httpClient) parseResponse(ctx context.Context, path string, rdr io.Reader, res interface{}) error {
if c.debug {
var buf bytes.Buffer
io.Copy(&buf, rdr)
c.logger.Debugf(ctx, "-----> %s (response)", path)
var m map[string]interface{}
if err := json.Unmarshal(buf.Bytes(), &m); err != nil {
c.logger.Debugf(ctx, "failed to unmarshal payload: %s", err)
c.logger.Debugf(ctx, buf.String())
} else {
formatted, _ := json.MarshalIndent(m, "", " ")
c.logger.Debugf(ctx, "%s", formatted)
}
c.logger.Debugf(ctx, "<----- %s (response)", path)
rdr = &buf
}
return json.NewDecoder(rdr).Decode(res)
} |
// Produce the KEY token. | func yaml_parser_fetch_key(parser *yaml_parser_t) bool {
// In the block context, additional checks are required.
if parser.flow_level == 0 {
// Check if we are allowed to start a new key (not nessesary simple).
if !parser.simple_key_allowed {
return yaml_parser_set_scanner_error(parser, "", parser.mark,
"mapping keys are not allowed in this context")
}
// Add the BLOCK-MAPPING-START token if needed.
if !yaml_parser_roll_indent(parser, parser.mark.column, -1, yaml_BLOCK_MAPPING_START_TOKEN, parser.mark) {
return false
}
}
// Reset any potential simple keys on the current flow level.
if !yaml_parser_remove_simple_key(parser) {
return false
}
// Simple keys are allowed after '?' in the block context.
parser.simple_key_allowed = parser.flow_level == 0
// Consume the token.
start_mark := parser.mark
skip(parser)
end_mark := parser.mark
// Create the KEY token and append it to the queue.
token := yaml_token_t{
typ: yaml_KEY_TOKEN,
start_mark: start_mark,
end_mark: end_mark,
}
yaml_insert_token(parser, -1, &token)
return true
} |
************************************************************************* | public function getResources()
{
$services = [];
foreach (ServiceManager::getServiceNames(true) as $serviceName) {
if (Session::allowsServiceAccess($serviceName)) {
$services[] = [static::getResourceIdentifier() => $serviceName];
}
}
return $services;
} |
Produce a random sample of the given DBIDs.
@param source Original DBIDs, no duplicates allowed
@param except Excluded object
@param k k Parameter
@param random Random generator
@return new DBIDs | public static ModifiableDBIDs randomSampleExcept(DBIDs source, DBIDRef except, int k, Random random) {
if(k < 0 || k > source.size()) {
throw new IllegalArgumentException("Illegal value for size of random sample: " + k + " > " + source.size() + " or < 0");
}
// Fast, and we're single-threaded here anyway.
random = (random != null) ? random : new FastNonThreadsafeRandom();
// TODO: better balancing for different sizes
// Two methods: constructive vs. destructive
if(k < source.size() >> 2) {
ArrayDBIDs aids = DBIDUtil.ensureArray(source);
DBIDArrayIter iter = aids.iter();
int size = aids.size();
HashSetModifiableDBIDs sample = DBIDUtil.newHashSet(k);
while(sample.size() < k) {
if(!equal(iter.seek(random.nextInt(size)), except)) {
sample.add(iter);
}
}
return sample;
}
else {
ArrayModifiableDBIDs sample = DBIDUtil.newArray(source);
randomShuffle(sample, random, k);
// Avoid excluded object:
for(DBIDArrayIter iter = sample.iter(); iter.valid() && iter.getOffset() < k; iter.advance()) {
if(equal(iter, except)) {
sample.swap(iter.getOffset(), k);
break; // Assuming that except occurrs only once!
}
}
// Delete trailing elements
for(int i = sample.size() - 1; i >= k; i--) {
sample.remove(i);
}
return sample;
}
} |
Create the PHP syntax for the given schema.
@param array $schema
@param array $meta
@return string
@throws GeneratorException | public function create($schema, $meta)
{
$up = $this->createSchemaForUpMethod($schema, $meta);
$down = $this->createSchemaForDownMethod($schema, $meta);
return compact('up', 'down');
} |
Add a sample to this measurements. | def add_sample(self, ts, **kwargs):
""""""
if not self.series.offsets:
self.ts = ts
offset = 0
else:
dt = ts - self.ts
offset = (dt.days * 24 * 60 * 60 * 1000 + dt.seconds * 1000 +
dt.microseconds // 1000)
self.series.add_sample(offset, **kwargs) |
Links a rich menu to multiple users.
@param string[] $userIds Found in the source object of webhook event objects. Max: 150 user IDs.
@param string $richMenuId ID of an uploaded rich menu
@return Response | public function bulkLinkRichMenu($userIds, $richMenuId)
{
$url = $this->endpointBase . '/v2/bot/richmenu/bulk/link';
return $this->httpClient->post($url, [
'richMenuId' => $richMenuId,
'userIds' => $userIds
]);
} |
Given a + operation node with a list of fraction nodes as args that all have the same denominator, add them together. e.g. 2/3 + 5/3 -> (2+5)/3 Returns the new node. | function combineNumeratorsAboveCommonDenominator(node) {
let newNode = clone(node);
const commonDenominator = newNode.args[0].args[1];
const numeratorArgs = [];
newNode.args.forEach(fraction => {
numeratorArgs.push(fraction.args[0]);
});
const newNumerator = Node.Creator.parenthesis(
Node.Creator.operator('+', numeratorArgs));
newNode = Node.Creator.operator('/', [newNumerator, commonDenominator]);
return Node.Status.nodeChanged(
ChangeTypes.COMBINE_NUMERATORS, node, newNode);
} |
32位MD5加密算法
@param s
@return | public static String convert32(String s)
{
try {
byte[] bytes = s.getBytes();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(bytes);
bytes = md.digest();
int j = bytes.length;
char[] chars = new char[j * 2];
int k = 0;
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
chars[k++] = hexChars[b >>> 4 & 0xf];
chars[k++] = hexChars[b & 0xf];
}
return new String(chars);
}
catch (Exception e){
return null;
}
} |
Disable automatic decoding on a netCDF4.Variable.
We handle these types of decoding ourselves. | def _disable_auto_decode_variable(var):
var.set_auto_maskandscale(False)
# only added in netCDF4-python v1.2.8
with suppress(AttributeError):
var.set_auto_chartostring(False) |
Returns a copy of the buffer if offset and length are used, otherwise a reference.
@return byte array with a copy of the buffer. | public byte[] getBuffer() {
if(buf == null)
return null;
if(offset == 0 && length == buf.length)
return buf;
else {
byte[] retval=new byte[length];
System.arraycopy(buf, offset, retval, 0, length);
return retval;
}
} |
Provides a synopsis for the given Input Argument.
@param input\Argument $definition The Input Argument to provide a synopsis for.
@param array $options Additional options to be considered by the Descriptor.
@return mixed | public function getInputArgumentSynopsis(input\Argument $definition, array $options = null)
{
$output = '\<'.$definition->getName().'>';
$value = $definition->getValue();
if (!$value->is(input\Value::REQUIRED)) {
$output = '['.$output.']';
} elseif ($value instanceof input\values\Multiple) {
$output = $output.' ('.$output.')';
}
if ($value instanceof input\values\Multiple) {
$output .= '...';
}
return $output;
} |
Returned expression results in Date arithmetic.
Returns the elapsed time between two UNIX timestamps as an integer whose unit is part. | public static Expression dateDiffMillis(String expression1, String expression2, DatePart part) {
return dateDiffMillis(x(expression1), x(expression2), part);
} |
converts a argument scope to a regular struct
@param arg argument scope to convert
@return resulting struct | public static Struct toStruct(Argument arg) {
Struct trg = new StructImpl();
StructImpl.copy(arg, trg, false);
return trg;
} |
/*
Implementation notes:
The requirement that "K extends CopyableValue<K>" can be removed when
Flink has a self-join which performs the skew distribution handled by
GenerateGroupSpans / GenerateGroups / GenerateGroupPairs. | @Override
public DataSet<Result<K>> runInternal(Graph<K, VV, EV> input)
throws Exception {
// s, t, d(t)
DataSet<Edge<K, Tuple2<EV, LongValue>>> neighborDegree = input
.run(new EdgeTargetDegree<K, VV, EV>()
.setParallelism(parallelism));
// group span, s, t, d(t)
DataSet<Tuple4<IntValue, K, K, IntValue>> groupSpans = neighborDegree
.groupBy(0)
.sortGroup(1, Order.ASCENDING)
.reduceGroup(new GenerateGroupSpans<>(groupSize))
.setParallelism(parallelism)
.name("Generate group spans");
// group, s, t, d(t)
DataSet<Tuple4<IntValue, K, K, IntValue>> groups = groupSpans
.rebalance()
.setParallelism(parallelism)
.name("Rebalance")
.flatMap(new GenerateGroups<>())
.setParallelism(parallelism)
.name("Generate groups");
// t, u, d(t)+d(u)
DataSet<Tuple3<K, K, IntValue>> twoPaths = groups
.groupBy(0, 1)
.sortGroup(2, Order.ASCENDING)
.reduceGroup(new GenerateGroupPairs<>(groupSize))
.name("Generate group pairs");
// t, u, intersection, union
DataSet<Result<K>> scores = twoPaths
.groupBy(0, 1)
.reduceGroup(new ComputeScores<>(unboundedScores,
minimumScoreNumerator, minimumScoreDenominator,
maximumScoreNumerator, maximumScoreDenominator))
.name("Compute scores");
if (mirrorResults) {
scores = scores
.flatMap(new MirrorResult<>())
.name("Mirror results");
}
return scores;
} |
Save a thumbnail to the thumbnail_storage.
Also triggers the ``thumbnail_created`` signal and caches the
thumbnail values and dimensions for future lookups. | def save_thumbnail(self, thumbnail):
filename = thumbnail.name
try:
self.thumbnail_storage.delete(filename)
except Exception:
pass
self.thumbnail_storage.save(filename, thumbnail)
thumb_cache = self.get_thumbnail_cache(
thumbnail.name, create=True, update=True)
# Cache thumbnail dimensions.
if settings.THUMBNAIL_CACHE_DIMENSIONS:
dimensions_cache, created = (
models.ThumbnailDimensions.objects.get_or_create(
thumbnail=thumb_cache,
defaults={'width': thumbnail.width,
'height': thumbnail.height}))
if not created:
dimensions_cache.width = thumbnail.width
dimensions_cache.height = thumbnail.height
dimensions_cache.save()
signals.thumbnail_created.send(sender=thumbnail) |
Get a hash key for the session this stanza belongs to.
@param sid The session id
@param initiator The initiator
@return A hash key | public static int getSessionHash(final String sid, final Jid initiator) {
final int PRIME = 31;
int result = 1;
result = PRIME * result + (initiator == null ? 0 : initiator.hashCode());
result = PRIME * result + (sid == null ? 0 : sid.hashCode());
return result;
} |
Method: onVertexModified
Registered as a listener for the vertexmodified event on the editable
layer.
Parameters:
event - {Object} The vertex modified event. | function(event) {
this.feature = event.feature;
var loc = this.layer.map.getLonLatFromViewPortPx(event.pixel);
this.considerSnapping(
event.vertex, new OpenLayers.Geometry.Point(loc.lon, loc.lat)
);
} |
Checks if there is an extension and adds it if does not
@param string $file File name
@param string $extension Extension (dot included)
@return string | public static function addExtension(string $file, string $extension)
{
if (substr($file, strlen($extension) * -1) !== $extension) {
$file .= $extension;
}
return $file;
} |
// EvalString implements Expression interface. | func (sf *ScalarFunction) EvalString(ctx sessionctx.Context, row chunk.Row) (string, bool, error) {
return sf.Function.evalString(row)
} |
@function maxRecordNumber
get max record (n)umber with optional where
@param {object} args
@param {object} args.session
@param {object} args.where
@returns {Promise<integer>} | function maxRecordNumber (args) {
// get sql
var select = sql.maxRecordNumber(this, args)
// do query
return this.mysql().query(select.sql, select.params)
// get n value from response
.then(res => {
return res[0][0].n
})
} |
Loads properties from the passed URL
@param url The url to load from
@return the loaded properties | protected static Properties loadConfig(URL url) {
InputStream is = null;
try {
URLConnection connection = url.openConnection();
if(connection instanceof HttpURLConnection) {
((HttpURLConnection)connection).setConnectTimeout(2000);
}
is = connection.getInputStream();
return loadConfig(url.toString(), is);
} catch (Exception ex) {
throw new IllegalArgumentException("Failed to load configuration from [" + url + "]");
}finally {
if(is!=null) try { is.close(); } catch (Exception ex) { /* No Op */ }
}
} |
Handles pycosio exceptions and raise standard OS exceptions. | def handle_os_exceptions():
try:
yield
# Convert pycosio exception to equivalent OSError
except ObjectException:
exc_type, exc_value, _ = exc_info()
raise _OS_EXCEPTIONS.get(exc_type, OSError)(exc_value)
# Re-raise generic exceptions
except (OSError, same_file_error, UnsupportedOperation):
raise
# Raise generic OSError for other exceptions
except Exception:
exc_type, exc_value, _ = exc_info()
raise OSError('%s%s' % (
exc_type, (', %s' % exc_value) if exc_value else '')) |
Returns the value of field without HTML tags
@return string | function getFrozenHtml()
{
$value = array();
if (is_array($this->_values)) {
foreach ($this->_values as $key => $val) {
foreach ($this->_optGroups as $optGroup) {
if (empty($optGroup['options'])) {
continue;
}
for ($i = 0, $optCount = count($optGroup['options']); $i < $optCount; $i++) {
if ((string)$val == (string)$optGroup['options'][$i]['attr']['value']) {
$value[$key] = $optGroup['options'][$i]['text'];
break;
}
}
}
}
}
$html = empty($value)? ' ': join('<br />', $value);
if ($this->_persistantFreeze) {
$name = $this->getPrivateName();
// Only use id attribute if doing single hidden input
if (1 == count($value)) {
$id = $this->getAttribute('id');
$idAttr = isset($id)? array('id' => $id): array();
} else {
$idAttr = array();
}
foreach ($value as $key => $item) {
$html .= '<input' . $this->_getAttrString(array(
'type' => 'hidden',
'name' => $name,
'value' => $this->_values[$key]
) + $idAttr) . ' />';
}
}
return $html;
} |
// UnmarshalJSON does a no-op unmarshal to PathenumPathEnum.
// It just validates that the input is sane. | func (e PathenumPathEnum) UnmarshalJSON(b []byte) error {
return unmarshalJSONEnum(b, pbpathenum.PathEnum_value)
} |
Rescores all priorities by multiplying them with the same factor.
@param factor the factor to multiply with | public void rescore(double factor) {
for (int i = 0; i < this.prior.size(); i++)
this.prior.set(i, this.prior.get(i) * factor);
} |
Return the last directory.
Returns absolute path to new working directory. | def cdpop():
if len(_cdhist) >= 1:
old = _cdhist.pop() # Pop from history.
os.chdir(old)
return old
else:
return pwd() |
Trim the trailing spaces.
@param line | private String trim(String line) {
char[] chars = line.toCharArray();
int len = chars.length;
while (len > 0) {
if (!Character.isWhitespace(chars[len - 1])) {
break;
}
len--;
}
return line.substring(0, len);
} |
Returns the AWS region for this environment
@return string
@throws DriverException | protected function getRegion()
{
if (empty($this->sS3Region)) {
$this->sS3Region = $this->getRegionAndBucket()->region;
if (empty($this->sS3Region)) {
throw new DriverException('S3 Region has not been defined.');
}
}
return $this->sS3Region;
} |
/*
(non-Javadoc)
@see com.impetus.kundera.query.QueryImpl#getReader() | @Override
protected RDBMSEntityReader getReader()
{
if (reader == null)
{
reader = new RDBMSEntityReader(getJPAQuery(), kunderaQuery, kunderaMetadata);
}
return reader;
} |
Adds @item to the end of the list
-> #int length of list after operation | def append(self, item):
return self._client.rpush(self.key_prefix, self._dumps(item)) |
Creates a NumberMap for Integers.
@param <K>
@return NumberMap<K, Integer> | public static <K> NumberMap<K, Integer> newIntegerMap() {
return new NumberMap<K, Integer>() {
@Override
public void add(K key, Integer addend) {
put(key, containsKey(key) ? (get(key) + addend) : addend);
}
@Override
public void sub(K key, Integer subtrahend) {
put(key, (containsKey(key) ? get(key) : 0) - subtrahend);
}
};
} |
Make identity from JSON object.
@param json JSON received from Twitter
@return Identity found | private static Identity parse(final JsonObject json) {
final Map<String, String> props = new HashMap<>(json.size());
props.put(PsTwitter.NAME, json.getString(PsTwitter.NAME));
props.put("picture", json.getString("profile_image_url"));
return new Identity.Simple(
String.format("urn:twitter:%d", json.getInt("id")),
props
);
} |
Unset hive key
@param $key string | function clear($key) {
// Normalize array literal
$cache=Cache::instance();
$parts=$this->cut($key);
if ($key=='CACHE')
// Clear cache contents
$cache->reset();
elseif (preg_match('/^(GET|POST|COOKIE)\b(.+)/',$key,$expr)) {
$this->clear('REQUEST'.$expr[2]);
if ($expr[1]=='COOKIE') {
$parts=$this->cut($key);
$jar=$this->hive['JAR'];
unset($jar['lifetime']);
$jar['expire']=0;
call_user_func_array('setcookie',
array_merge([$parts[1],NULL],$jar));
unset($_COOKIE[$parts[1]]);
}
}
elseif ($parts[0]=='SESSION') {
if (!headers_sent() && session_status()!=PHP_SESSION_ACTIVE)
session_start();
if (empty($parts[1])) {
// End session
session_unset();
session_destroy();
$this->clear('COOKIE.'.session_name());
}
$this->sync('SESSION');
}
if (!isset($parts[1]) && array_key_exists($parts[0],$this->init))
// Reset global to default value
$this->hive[$parts[0]]=$this->init[$parts[0]];
else {
eval('unset('.$this->compile('@this->hive.'.$key).');');
if ($parts[0]=='SESSION') {
session_commit();
session_start();
}
if ($cache->exists($hash=$this->hash($key).'.var'))
// Remove from cache
$cache->clear($hash);
}
} |
Check if this assertion is true
@param AuthorizationService $authorizationService
@param mixed $context
@return bool | public function assert(AuthorizationService $authorizationService, $context = null)
{
/** @var EnvironmentInterface $context */
/** @var UserInterface $identity */
$identity = $authorizationService->getIdentity();
if ($identity->getRole() === UserInterface::ROLE_USER) {
return false;
}
if ($authorizationService->isGranted('manageAllEnv', $context) || ($context != null && $context->hasUser($identity))) {
return true;
}
if ($context == null) {
return false;
}
if (!$context->hasParent()) {
return false;
}
$parent = $context->getParent();
return $parent->hasUser($identity) || $authorizationService->isGranted('manageEnv', $parent);
} |
TODO: suggest the old value & the current version | def complete_set(self, cmd_param_text, full_cmd, *rest):
complete_value = partial(complete_values, ["updated-value"])
complete_version = partial(complete_values, [str(i) for i in range(1, 11)])
completers = [self._complete_path, complete_value, complete_version]
return complete(completers, cmd_param_text, full_cmd, *rest) |
/*
Apply effects on an image
Parameters
resource $resource : image resource
resource $mask : mask resource
integer $xinit : initial x coord in source image
integer $yinit : initial y coord in source image
Return
resource | public function apply($resource){
// Extract arguments
@list(,$mask,$xinit,$yinit)=func_get_args();
if(is_subclass_of($mask,'Imagix\AbstractImage')){
$mask=$mask->getResource();
}
elseif(!is_resource($mask)){
throw new Exception("The 'mask' parameter must be a valid GD resource or a Lumy_File_Image child object");
}
// Prepare
$w_mask=imagesx($mask);
$h_mask=imagesy($mask);
if($w_mask===false || $h_mask===false){
throw new Exception("An error was encountered while getting mask image resolution");
}
$width=imagesx($resource);
$height=imagesy($resource);
if($width===false || $height===false){
throw new Exception("An error was encountered while getting source image resolution");
}
$xinit=(int)$xinit;
$yinit=(int)$yinit;
if($xinit<0) $xinit=0;
if($xinit>$width-$w_mask) $xinit=$width-$w_mask;
if($yinit<0) $yinit=0;
if($yinit>$height-$h_mask) $yinit=$height-$h_mask;
// Create new image
$image=$this->_createTrueColor($width,$height);
if(!imagecopy($image,$resource,0,0,0,0,$width,$height)){
throw new Exception("Cannot copy image");
}
// Modify colors
$x=$xinit;
do{
$y=$yinit;
do{
// Get pixel color from source image
$rgba_src=$this->_getColorAt($image,$x,$y);
// Get pixel color from mask image
$rgba_mask=$this->_getColorAt($mask,$x-$xinit,$y-$yinit);
// Generate alpha
if($rgba_mask[0]==$rgba_mask[1] && $rgba_mask[1]==$rgba_mask[2]){
$alpha=floor($rgba_mask[0]/2)+$rgba_src[3];
if($alpha>127) $alpha=127;
}
else{
throw new Exception("Mask image must be in grayscale");
}
// Define new pixel
$color=imagecolorallocatealpha($image,$rgba_src[0],$rgba_src[1],$rgba_src[2],$alpha);
if($color===false){
throw new Exception("Cannot allocate color");
}
if(!imagesetpixel($image,$x,$y,$color)){
throw new Exception("Cannot set pixel");
}
}
while(++$y<$h_mask+$yinit);
}
while(++$x<$w_mask+$xinit);
return $image;
} |
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated | @Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case AfplibPackage.GCMRK__RG:
return rg != null && !rg.isEmpty();
}
return super.eIsSet(featureID);
} |
Gets an initialized CmsObject to be used for the actual search for a given search bean.<p>
@param searchObj the search object
@return the initialized CmsObject
@throws CmsException if something goes wrong | protected CmsObject getSearchCms(CmsGallerySearchBean searchObj) throws CmsException {
CmsObject searchCms = getCmsObject();
if (searchObj.isIncludeExpired()) {
searchCms = OpenCms.initCmsObject(getCmsObject());
searchCms.getRequestContext().setRequestTime(CmsResource.DATE_RELEASED_EXPIRED_IGNORE);
}
return searchCms;
} |
Adds light to specified RayHandler | public void add(RayHandler rayHandler) {
this.rayHandler = rayHandler;
if (active) {
rayHandler.lightList.add(this);
} else {
rayHandler.disabledLights.add(this);
}
} |
{@inheritDoc}
@SuppressWarnings(PHPMD.CamelCaseVariableName) | public function getRoles()
{
$user = $this;
$comparator = function ($level) use ($user) {
return $user->hasAccessLevel($level);
};
// Fallback for PHP < 5.6 which do not support ARRAY_FILTER_USE_KEY.
if (version_compare(PHP_VERSION, '5.6', '<')) {
$filtered = array_flip(array_filter(array_keys(self::$roleMap), $comparator));
return array_values(array_intersect_key(self::$roleMap, $filtered));
}
return array_values(array_filter(self::$roleMap, $comparator, ARRAY_FILTER_USE_KEY));
} |
// Append adds the values to key k, not overwriting what was already stored at that key. | func (md MD) Append(k string, vals ...string) {
if len(vals) == 0 {
return
}
k = strings.ToLower(k)
md[k] = append(md[k], vals...)
} |
// SetName sets the Name field's value. | func (s *ScheduleRunInput) SetName(v string) *ScheduleRunInput {
s.Name = &v
return s
} |
Emit dispatchEvent
@param string $event Le nom de l'évènement
@return bool | public static function emit($event)
{
if (isset(static::$events['__bow.once.event'][$event])) {
$listener = static::$events['__bow.once.event'][$event];
$data = array_slice(func_get_args(), 1);
return $listener->call($data);
}
if (!static::bound($event)) {
return false;
}
if (isset(static::$events[$event])) {
$events = static::$events[$event];
} else {
$events = static::$events['__bow.transmission.event'][$event];
}
$listeners = new Collection($events);
$data = array_slice(func_get_args(), 1);
$listeners->each(function (Listener $listener) use ($data) {
if ($listener->getActionType() === 'string') {
$callable = $listener->getAction();
} else {
$callable = [$listener, 'call'];
}
return Actionner::getInstance()->execute($callable, [$data]);
});
return true;
} |
// Min returns minimun value of the given sample. | func Min(values []int64) int64 {
if len(values) == 0 {
return 0
}
if isSorted(values) {
return values[0]
}
min := values[0]
for i := 1; i < len(values); i++ {
v := values[i]
if min > v {
min = v
}
}
return min
} |
/*
recommend using getMetadataInJson() instead of toString() | public String getMetadataInJson()
throws SQLException {
try {
return getMetadataInJsonFunc();
} catch (TException e) {
boolean flag = connection.reconnect();
this.client = connection.client;
if (flag) {
try {
return getMetadataInJsonFunc();
} catch (TException e2) {
throw new SQLException("Failed to fetch all metadata in json "
+ "after reconnecting. Please check the server status.");
}
} else {
throw new SQLException("Failed to reconnect to the server "
+ "when fetching all metadata in json. Please check the server status.");
}
}
} |
Add a security scheme which can be referenced.
:param str component_id: component_id to use as reference
:param dict kwargs: security scheme fields | def security_scheme(self, component_id, component):
if component_id in self._security_schemes:
raise DuplicateComponentNameError(
'Another security scheme with name "{}" is already registered.'.format(
component_id
)
)
self._security_schemes[component_id] = component
return self |
Retrieve option .
@param string $key
@param mixed|null|string $group
@param null $default
@return mixed | public function get($key, $group = self::DEFAULT_GROUP, $default = null) {
return isset($this->settings[$group][$key]) ? $this->settings[$group][$key] : $default;
} |
resolveRequestData.
@param $request
@return array | protected function resolveRequestData($request): array
{
$params = $request->all();
if ($request instanceof Request) {
$routeParams = $request->route()->parameters();
$params = array_merge($params, $routeParams);
}
return $params;
} |
Real-time update of search results | def append_result(self, results, num_matches):
""""""
filename, lineno, colno, match_end, line = results
if filename not in self.files:
file_item = FileMatchItem(self, filename, self.sorting,
self.text_color)
file_item.setExpanded(True)
self.files[filename] = file_item
self.num_files += 1
search_text = self.search_text
title = "'%s' - " % search_text
nb_files = self.num_files
if nb_files == 0:
text = _('String not found')
else:
text_matches = _('matches in')
text_files = _('file')
if nb_files > 1:
text_files += 's'
text = "%d %s %d %s" % (num_matches, text_matches,
nb_files, text_files)
self.set_title(title + text)
file_item = self.files[filename]
line = self.truncate_result(line, colno, match_end)
item = LineMatchItem(file_item, lineno, colno, line, self.text_color)
self.data[id(item)] = (filename, lineno, colno) |
// dumpTlsCertificates prints some fields of the certificates received from the server.
// Fields will be inspected by the user, so they must be conscise and useful | func dumpTLSCertificates(t *tls.ConnectionState) {
for _, cert := range t.PeerCertificates {
console.Debugln("TLS Certificate found: ")
if len(cert.Issuer.Country) > 0 {
console.Debugln(" >> Country: " + cert.Issuer.Country[0])
}
if len(cert.Issuer.Organization) > 0 {
console.Debugln(" >> Organization: " + cert.Issuer.Organization[0])
}
console.Debugln(" >> Expires: " + cert.NotAfter.String())
}
} |
Gets a dispatcher for the given session and messages.
@param session
the session locking the messages
@return the dispatcher
@throws ResourceException
if a dispatcher could not be created | SibRaDispatcher createDispatcher(final AbstractConsumerSession session,
final Reliability unrecoveredReliability,
final int maxFailedDeliveries,
final int sequentialFailureThreshold)
throws ResourceException {
final String methodName = "createDispatcher";
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.entry(this, TRACE, methodName,
new Object[] { session, unrecoveredReliability, maxFailedDeliveries, sequentialFailureThreshold });
}
if (_closed) {
throw new IllegalStateException(NLS
.getString("LISTENER_CLOSED_CWSIV0953"));
}
final SibRaDispatcher dispatcher;
if (_endpointActivation.isEndpointMethodTransactional()) {
if (_endpointConfiguration.getShareDataSourceWithCMP()) {
dispatcher = new SibRaSynchronizedDispatcher(this,
session, _endpointActivation, unrecoveredReliability, maxFailedDeliveries,
sequentialFailureThreshold);
} else {
dispatcher = new SibRaTransactionalDispatcher(this,
session, _endpointActivation, _busName, unrecoveredReliability, maxFailedDeliveries,
sequentialFailureThreshold);
}
} else {
if (SibRaMessageDeletionMode.BATCH.equals(_endpointConfiguration
.getMessageDeletionMode())) {
dispatcher = new SibRaBatchMessageDeletionDispatcher(
this, session, _endpointActivation, unrecoveredReliability, maxFailedDeliveries,
sequentialFailureThreshold);
} else if (SibRaMessageDeletionMode.SINGLE
.equals(_endpointConfiguration.getMessageDeletionMode())) {
dispatcher = new SibRaSingleMessageDeletionDispatcher(
this, session, _endpointActivation, unrecoveredReliability, maxFailedDeliveries,
sequentialFailureThreshold);
} else {
dispatcher = new SibRaNonTransactionalDispatcher(this,
session, _endpointActivation, unrecoveredReliability, maxFailedDeliveries,
sequentialFailureThreshold);
}
}
_dispatcherCount.incrementAndGet();
if (TraceComponent.isAnyTracingEnabled() && TRACE.isDebugEnabled()) {
SibTr.debug(this, TRACE, "Creating a dispatcher, there are now " + _dispatcherCount.get() + " open dispatchers");
}
if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
SibTr.exit(this, TRACE, methodName, dispatcher);
}
return dispatcher;
} |
// NewHeightHintCache returns a new height hint cache backed by a database. | func NewHeightHintCache(db *channeldb.DB) (*HeightHintCache, error) {
cache := &HeightHintCache{db}
if err := cache.initBuckets(); err != nil {
return nil, err
}
return cache, nil
} |
Modified from the quote method in:
https://github.com/codehaus/jettison/blob/master/src/main/java/org/codehaus/jettison/json/JSONObject.java
@param string The string to escape.
@return An escaped JSON string. | public static String escapeJson(@Nullable String string) {
if (StringUtils.isEmpty(string)) {
return "";
}
int len = string.length();
StringBuilder sb = new StringBuilder(len + 2);
for (int i = 0; i < len; i += 1) {
char c = string.charAt(i);
switch (c) {
case '\\':
case '"':
sb.append('\\');
sb.append(c);
break;
case '\b':
sb.append("\\b");
break;
case '\t':
sb.append("\\t");
break;
case '\n':
sb.append("\\n");
break;
case '\f':
sb.append("\\f");
break;
case '\r':
sb.append("\\r");
break;
default:
if (c < ' ') {
String t = "000" + Integer.toHexString(c);
sb.append("\\u").append(t.substring(t.length() - 4));
} else {
sb.append(c);
}
}
}
return sb.toString();
} |
This mehtod will check the name map for entries where the
WeakReference object has been reclaimed. When they are found it will
reclaim the entry in the map. | private void reclaimSpace()
{
if (_nameMap == null)
return;
if (_nameMap.size() > 0 && _nameMap.size() % _reclaimPoint == 0) {
synchronized (_nameMap) {
Set s = _nameMap.entrySet();
Iterator it = s.iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
TrackingObject to = (TrackingObject) e.getValue();
// If the object has been reclaimed, then we remove the named object from the map.
WeakReference wr = to.getWeakINameable();
INameable o = (INameable) wr.get();
if (o == null) {
it.remove();
}
}
_reclaimPoint = _nameMap.size() + _reclaimIncrement;
}
}
} |
Get a {@link Histogram} with the given name prefix and suffixes.
@param prefix the given name prefix
@param suffixes the given name suffixes
@return a {@link Histogram} with the given name prefix and suffixes | public Histogram getHistogram(String prefix, String... suffixes) {
return this.metricContext.histogram(MetricRegistry.name(prefix, suffixes));
} |
Returns whether the two expressions refer to the same object (e.g. a['b'].c and a.b.c)
@param {Object} a
@param {Object} b
@returns {boolean} | function isEquivalentMemberExp(a, b) {
return _.isEqualWith(a, b, (left, right, key) => {
if (_.includes(['loc', 'range', 'computed', 'start', 'end', 'parent'], key)) {
return true
}
if (isComputed(left) || isComputed(right)) {
return false
}
if (key === 'property') {
const leftValue = left.name || left.value
const rightValue = right.name || right.value
return leftValue === rightValue
}
})
} |
// Area returns the surface area of the Cap on the unit sphere. | func (c Cap) Area() float64 {
return 2.0 * math.Pi * math.Max(0, c.Height())
} |
Use a new context. May be called from outside to update
internal state for a new annotation-processing round. | public void setContext(Context context) {
context.put(JavacTypes.class, this);
syms = Symtab.instance(context);
types = Types.instance(context);
} |
Create the URI object from `$server`.
@param HTTPServerFactory $httpFactory
@param array $server
@return UriInterface | private function createUri(HTTPServerFactory $httpFactory, array $server) : UriInterface {
$uri = $httpFactory->createUri();
$uri = $this->withScheme($uri, $server);
$uri = $this->withHost($uri, $server);
$uri = $this->withServerPort($uri, $server);
$uri = $this->withPath($uri, $server);
$uri = $this->withQueryString($uri, $server);
return $uri;
} |
Starts the dump of an object.
@throws \ReflectionException
@return string
The generated markup. | public function callMe()
{
$output = $this->pool->render->renderSingeChildHr() . $this->dispatchStartEvent();
$ref = $this->parameters[static::PARAM_REF] = new ReflectionClass($this->parameters[static::PARAM_DATA]);
// Dumping public properties.
$output .= $this->dumpStuff('Brainworxx\\Krexx\\Analyse\\Callback\\Analyse\\Objects\\PublicProperties');
// Dumping getter methods.
// We will not dump the getters for internal classes, though.
if ($this->pool->config->getSetting(Fallback::SETTING_ANALYSE_GETTER) === true &&
$ref->isUserDefined() === true
) {
$output .= $this->dumpStuff('Brainworxx\\Krexx\\Analyse\\Callback\\Analyse\\Objects\\Getter');
}
// When analysing an error object, get the backtrace and then analyse it.
$output .= $this->dumpStuff('Brainworxx\\Krexx\\Analyse\\Callback\\Analyse\\Objects\\ErrorObject');
// Dumping protected properties.
if ($this->pool->config->getSetting(Fallback::SETTING_ANALYSE_PROTECTED) === true ||
$this->pool->scope->isInScope() === true
) {
$output .= $this->dumpStuff('Brainworxx\\Krexx\\Analyse\\Callback\\Analyse\\Objects\\ProtectedProperties');
}
// Dumping private properties.
if ($this->pool->config->getSetting(Fallback::SETTING_ANALYSE_PRIVATE) === true ||
$this->pool->scope->isInScope() === true
) {
$output .= $this->dumpStuff('Brainworxx\\Krexx\\Analyse\\Callback\\Analyse\\Objects\\PrivateProperties');
}
// Dumping class constants.
$output .= $this->dumpStuff('Brainworxx\\Krexx\\Analyse\\Callback\\Analyse\\Objects\\Constants');
// Dumping all methods.
$output .= $this->dumpStuff('Brainworxx\\Krexx\\Analyse\\Callback\\Analyse\\Objects\\Methods');
// Dumping traversable data.
if ($this->pool->config->getSetting(Fallback::SETTING_ANALYSE_TRAVERSABLE) === true &&
$this->parameters[static::PARAM_DATA] instanceof \Traversable
) {
$output .= $this->dumpStuff('Brainworxx\\Krexx\\Analyse\\Callback\\Analyse\\Objects\\Traversable');
}
// Dumping all configured debug functions.
// Adding a HR for a better readability.
return $output .
$this->dumpStuff('Brainworxx\\Krexx\\Analyse\\Callback\\Analyse\\Objects\\DebugMethods') .
$this->pool->render->renderSingeChildHr();
} |
Return a new JSON response from the application.
@param string|array $data
@param int $status
@param array $headers
@return \Symfony\Component\HttpFoundation\Response
@static | public function response($data = [], $status = Response::HTTP_OK, $headers = [])
{
return new JsonResponse($data, $status, $headers, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
} |
Sets up the object attributes.
Args:
disk_name (string): Name of the disk to process
project (string): The project containing the disk to process
turbinia_zone (string): The zone containing the disk to process | def setup(self, disk_name, project, turbinia_zone):
# TODO: Consider the case when multiple disks are provided by the previous
# module or by the CLI.
if project is None or turbinia_zone is None:
self.state.add_error(
'project or turbinia_zone are not all specified, bailing out',
critical=True)
return
self.disk_name = disk_name
self.project = project
self.turbinia_zone = turbinia_zone
try:
turbinia_config.LoadConfig()
self.turbinia_region = turbinia_config.TURBINIA_REGION
self.instance = turbinia_config.PUBSUB_TOPIC
if turbinia_config.PROJECT != self.project:
self.state.add_error(
'Specified project {0:s} does not match Turbinia configured '
'project {1:s}. Use gcp_turbinia_import recipe to copy the disk '
'into the same project.'.format(
self.project, turbinia_config.PROJECT), critical=True)
return
self._output_path = tempfile.mkdtemp()
self.client = turbinia_client.TurbiniaClient()
except TurbiniaException as e:
self.state.add_error(e, critical=True)
return |
Get the search directories
@param string $env
@return array
@access protected | protected function getSearchDirs(/*# string */ $env)/*# : array */
{
if (!isset($this->sub_dirs[$env])) {
$this->sub_dirs[$env] = $this->buildSearchDirs($env);
}
return $this->sub_dirs[$env];
} |
// GitFsck calls 'git fsck' to check repository health. | func GitFsck() {
if taskStatusTable.IsRunning(_GIT_FSCK) {
return
}
taskStatusTable.Start(_GIT_FSCK)
defer taskStatusTable.Stop(_GIT_FSCK)
log.Trace("Doing: GitFsck")
if err := x.Where("id>0").Iterate(new(Repository),
func(idx int, bean interface{}) error {
repo := bean.(*Repository)
repoPath := repo.RepoPath()
if err := git.Fsck(repoPath, setting.Cron.RepoHealthCheck.Timeout, setting.Cron.RepoHealthCheck.Args...); err != nil {
desc := fmt.Sprintf("Fail to health check repository '%s': %v", repoPath, err)
log.Warn(desc)
if err = CreateRepositoryNotice(desc); err != nil {
log.Error(3, "CreateRepositoryNotice: %v", err)
}
}
return nil
}); err != nil {
log.Error(2, "GitFsck: %v", err)
}
} |
// ParseHTTP parses the SSE-C headers and returns the SSE-C client key
// on success. SSE-C copy headers are ignored. | func (ssec) ParseHTTP(h http.Header) (key [32]byte, err error) {
if h.Get(SSECAlgorithm) != SSEAlgorithmAES256 {
return key, ErrInvalidCustomerAlgorithm
}
if h.Get(SSECKey) == "" {
return key, ErrMissingCustomerKey
}
if h.Get(SSECKeyMD5) == "" {
return key, ErrMissingCustomerKeyMD5
}
clientKey, err := base64.StdEncoding.DecodeString(h.Get(SSECKey))
if err != nil || len(clientKey) != 32 { // The client key must be 256 bits long
return key, ErrInvalidCustomerKey
}
keyMD5, err := base64.StdEncoding.DecodeString(h.Get(SSECKeyMD5))
if md5Sum := md5.Sum(clientKey); err != nil || !bytes.Equal(md5Sum[:], keyMD5) {
return key, ErrCustomerKeyMD5Mismatch
}
copy(key[:], clientKey)
return key, nil
} |
Escapes a given string as an URI
@param string $uri
@return string | static public function escapeUri(string $uri): string {
self::initSerializer();
return self::$serializer->serialiseValue(new Resource($uri));
} |
// GetPrivate returns the Private field if it's non-nil, zero value otherwise. | func (p *PushEventRepository) GetPrivate() bool {
if p == nil || p.Private == nil {
return false
}
return *p.Private
} |
Warn if nans exist in a numpy array. | def warn_if_nans_exist(X):
""""""
null_count = count_rows_with_nans(X)
total = len(X)
percent = 100 * null_count / total
if null_count > 0:
warning_message = \
'Warning! Found {} rows of {} ({:0.2f}%) with nan values. Only ' \
'complete rows will be plotted.'.format(null_count, total, percent)
warnings.warn(warning_message, DataWarning) |
响应请求
@param \One\Protocol\Contracts\Request $request
@return \One\Context\Contracts\Payload | protected function run(Request $request)
{
$payload = new Payload;
if ($request->get('acme') === 1) {
$payload = $payload->withMessage('Acme Interceptor is work');
}
return $payload;
} |