repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
benjamin010505/pixel-dungeon-master
core/src/main/java/com/postmodern/postmoderndungeon/actors/mobs/YogDzewa.java
/* * Pixel Dungeon * Copyright (C) 2012-2015 <NAME> * * Shattered Pixel Dungeon * Copyright (C) 2014-2021 <NAME> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.postmodern.postmoderndungeon.actors.mobs; import com.postmodern.postmoderndungeon.Challenges; import com.postmodern.postmoderndungeon.Dungeon; import com.postmodern.postmoderndungeon.Statistics; import com.postmodern.postmoderndungeon.actors.Actor; import com.postmodern.postmoderndungeon.actors.Char; import com.postmodern.postmoderndungeon.actors.buffs.Amok; import com.postmodern.postmoderndungeon.actors.buffs.Charm; import com.postmodern.postmoderndungeon.actors.buffs.Dread; import com.postmodern.postmoderndungeon.actors.buffs.Frost; import com.postmodern.postmoderndungeon.actors.buffs.Light; import com.postmodern.postmoderndungeon.actors.buffs.LockedFloor; import com.postmodern.postmoderndungeon.actors.buffs.Paralysis; import com.postmodern.postmoderndungeon.actors.buffs.Sleep; import com.postmodern.postmoderndungeon.actors.buffs.Terror; import com.postmodern.postmoderndungeon.actors.buffs.Vertigo; import com.postmodern.postmoderndungeon.effects.Beam; import com.postmodern.postmoderndungeon.effects.CellEmitter; import com.postmodern.postmoderndungeon.effects.Pushing; import com.postmodern.postmoderndungeon.effects.TargetedCell; import com.postmodern.postmoderndungeon.effects.particles.PurpleParticle; import com.postmodern.postmoderndungeon.effects.particles.ShadowParticle; import com.postmodern.postmoderndungeon.items.artifacts.DriedRose; import com.postmodern.postmoderndungeon.levels.Level; import com.postmodern.postmoderndungeon.mechanics.Ballistica; import com.postmodern.postmoderndungeon.messages.Messages; import com.postmodern.postmoderndungeon.scenes.GameScene; import com.postmodern.postmoderndungeon.sprites.CharSprite; import com.postmodern.postmoderndungeon.sprites.LarvaSprite; import com.postmodern.postmoderndungeon.sprites.YogSprite; import com.postmodern.postmoderndungeon.tiles.DungeonTilemap; import com.postmodern.postmoderndungeon.ui.BossHealthBar; import com.postmodern.postmoderndungeon.utils.GLog; import com.watabou.utils.Bundle; import com.watabou.utils.GameMath; import com.watabou.utils.PathFinder; import com.watabou.utils.Random; import com.watabou.utils.Reflection; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; public class YogDzewa extends Mob { { spriteClass = YogSprite.class; HP = HT = 1000; EXP = 50; //so that allies can attack it. States are never actually used. state = HUNTING; viewDistance = 12; properties.add(Property.BOSS); properties.add(Property.IMMOVABLE); properties.add(Property.DEMONIC); } private int phase = 0; private float abilityCooldown; private static final int MIN_ABILITY_CD = 10; private static final int MAX_ABILITY_CD = 15; private float summonCooldown; private static final int MIN_SUMMON_CD = 10; private static final int MAX_SUMMON_CD = 15; private static Class getPairedFist(Class fist){ if (fist == YogFist.BurningFist.class) return YogFist.SoiledFist.class; if (fist == YogFist.SoiledFist.class) return YogFist.BurningFist.class; if (fist == YogFist.RottingFist.class) return YogFist.RustedFist.class; if (fist == YogFist.RustedFist.class) return YogFist.RottingFist.class; if (fist == YogFist.BrightFist.class) return YogFist.DarkFist.class; if (fist == YogFist.DarkFist.class) return YogFist.BrightFist.class; return null; } private ArrayList<Class> fistSummons = new ArrayList<>(); private ArrayList<Class> challengeSummons = new ArrayList<>(); { Random.pushGenerator(Dungeon.seedCurDepth()); fistSummons.add(Random.Int(2) == 0 ? YogFist.BurningFist.class : YogFist.SoiledFist.class); fistSummons.add(Random.Int(2) == 0 ? YogFist.RottingFist.class : YogFist.RustedFist.class); fistSummons.add(Random.Int(2) == 0 ? YogFist.BrightFist.class : YogFist.DarkFist.class); Random.shuffle(fistSummons); //randomly place challenge summons so that two fists of a pair can never spawn together if (Random.Int(2) == 0){ challengeSummons.add(getPairedFist(fistSummons.get(1))); challengeSummons.add(getPairedFist(fistSummons.get(2))); challengeSummons.add(getPairedFist(fistSummons.get(0))); } else { challengeSummons.add(getPairedFist(fistSummons.get(2))); challengeSummons.add(getPairedFist(fistSummons.get(0))); challengeSummons.add(getPairedFist(fistSummons.get(1))); } Random.popGenerator(); } private ArrayList<Class> regularSummons = new ArrayList<>(); { if (Dungeon.isChallenged(Challenges.STRONGER_BOSSES)){ for (int i = 0; i < 6; i++){ if (i >= 4){ regularSummons.add(YogRipper.class); } if (i >= Statistics.spawnersAlive){ regularSummons.add(Larva.class); } else { regularSummons.add( i % 2 == 0 ? YogEye.class : YogScorpio.class); } } } else { for (int i = 0; i < 6; i++){ if (i >= Statistics.spawnersAlive){ regularSummons.add(Larva.class); } else { regularSummons.add(YogRipper.class); } } } Random.shuffle(regularSummons); } private ArrayList<Integer> targetedCells = new ArrayList<>(); @Override protected boolean act() { //char logic if (fieldOfView == null || fieldOfView.length != Dungeon.level.length()){ fieldOfView = new boolean[Dungeon.level.length()]; } Dungeon.level.updateFieldOfView( this, fieldOfView ); throwItems(); //mob logic enemy = chooseEnemy(); enemySeen = enemy != null && enemy.isAlive() && fieldOfView[enemy.pos] && enemy.invisible <= 0; //end of char/mob logic if (phase == 0){ if (Dungeon.hero.viewDistance >= Dungeon.level.distance(pos, Dungeon.hero.pos)) { Dungeon.observe(); } if (Dungeon.level.heroFOV[pos]) { notice(); } } if (phase == 4 && findFist() == null){ yell(Messages.get(this, "hope")); summonCooldown = -15; //summon a burst of minions! phase = 5; } if (phase == 0){ spend(TICK); return true; } else { boolean terrainAffected = false; HashSet<Char> affected = new HashSet<>(); //delay fire on a rooted hero if (!Dungeon.hero.rooted) { for (int i : targetedCells) { Ballistica b = new Ballistica(pos, i, Ballistica.WONT_STOP); //shoot beams sprite.parent.add(new Beam.DeathRay(sprite.center(), DungeonTilemap.raisedTileCenterToWorld(b.collisionPos))); for (int p : b.path) { Char ch = Actor.findChar(p); if (ch != null && (ch.alignment != alignment || ch instanceof Bee)) { affected.add(ch); } if (Dungeon.level.flamable[p]) { Dungeon.level.destroy(p); GameScene.updateMap(p); terrainAffected = true; } } } if (terrainAffected) { Dungeon.observe(); } for (Char ch : affected) { if (Dungeon.isChallenged(Challenges.STRONGER_BOSSES)){ ch.damage(Random.NormalIntRange(30, 50), new Eye.DeathGaze()); } else { ch.damage(Random.NormalIntRange(20, 30), new Eye.DeathGaze()); } if (Dungeon.level.heroFOV[pos]) { ch.sprite.flash(); CellEmitter.center(pos).burst(PurpleParticle.BURST, Random.IntRange(1, 2)); } if (!ch.isAlive() && ch == Dungeon.hero) { Dungeon.fail(getClass()); GLog.n(Messages.get(Char.class, "kill", name())); } } targetedCells.clear(); } if (abilityCooldown <= 0){ int beams = 1 + (HT - HP)/400; HashSet<Integer> affectedCells = new HashSet<>(); for (int i = 0; i < beams; i++){ int targetPos = Dungeon.hero.pos; if (i != 0){ do { targetPos = Dungeon.hero.pos + PathFinder.NEIGHBOURS8[Random.Int(8)]; } while (Dungeon.level.trueDistance(pos, Dungeon.hero.pos) > Dungeon.level.trueDistance(pos, targetPos)); } targetedCells.add(targetPos); Ballistica b = new Ballistica(pos, targetPos, Ballistica.WONT_STOP); affectedCells.addAll(b.path); } //remove one beam if multiple shots would cause every cell next to the hero to be targeted boolean allAdjTargeted = true; for (int i : PathFinder.NEIGHBOURS9){ if (!affectedCells.contains(Dungeon.hero.pos + i) && Dungeon.level.passable[Dungeon.hero.pos + i]){ allAdjTargeted = false; break; } } if (allAdjTargeted){ targetedCells.remove(targetedCells.size()-1); } for (int i : targetedCells){ Ballistica b = new Ballistica(pos, i, Ballistica.WONT_STOP); for (int p : b.path){ sprite.parent.add(new TargetedCell(p, 0xFF0000)); affectedCells.add(p); } } //don't want to overly punish players with slow move or attack speed spend(GameMath.gate(TICK, Dungeon.hero.cooldown(), 3*TICK)); Dungeon.hero.interrupt(); abilityCooldown += Random.NormalFloat(MIN_ABILITY_CD, MAX_ABILITY_CD); abilityCooldown -= (phase - 1); } else { spend(TICK); } while (summonCooldown <= 0){ Class<?extends Mob> cls = regularSummons.remove(0); Mob summon = Reflection.newInstance(cls); regularSummons.add(cls); int spawnPos = -1; for (int i : PathFinder.NEIGHBOURS8){ if (Actor.findChar(pos+i) == null){ if (spawnPos == -1 || Dungeon.level.trueDistance(Dungeon.hero.pos, spawnPos) > Dungeon.level.trueDistance(Dungeon.hero.pos, pos+i)){ spawnPos = pos + i; } } } if (spawnPos != -1) { summon.pos = spawnPos; GameScene.add( summon ); Actor.addDelayed( new Pushing( summon, pos, summon.pos ), -1 ); summon.beckon(Dungeon.hero.pos); summonCooldown += Random.NormalFloat(MIN_SUMMON_CD, MAX_SUMMON_CD); summonCooldown -= (phase - 1); if (findFist() != null){ summonCooldown += MIN_SUMMON_CD - (phase - 1); } } else { break; } } } if (summonCooldown > 0) summonCooldown--; if (abilityCooldown > 0) abilityCooldown--; //extra fast abilities and summons at the final 100 HP if (phase == 5 && abilityCooldown > 2){ abilityCooldown = 2; } if (phase == 5 && summonCooldown > 3){ summonCooldown = 3; } return true; } @Override public boolean isAlive() { return super.isAlive() || phase != 5; } @Override public boolean isInvulnerable(Class effect) { return phase == 0 || findFist() != null; } @Override public void damage( int dmg, Object src ) { int preHP = HP; super.damage( dmg, src ); if (phase == 0 || findFist() != null) return; if (phase < 4) { HP = Math.max(HP, HT - 300 * phase); } else if (phase == 4) { HP = Math.max(HP, 100); } int dmgTaken = preHP - HP; if (dmgTaken > 0) { abilityCooldown -= dmgTaken / 10f; summonCooldown -= dmgTaken / 10f; } if (phase < 4 && HP <= HT - 300*phase){ phase++; updateVisibility(Dungeon.level); GLog.n(Messages.get(this, "darkness")); sprite.showStatus(CharSprite.POSITIVE, Messages.get(this, "invulnerable")); addFist((YogFist)Reflection.newInstance(fistSummons.remove(0))); if (Dungeon.isChallenged(Challenges.STRONGER_BOSSES)){ addFist((YogFist)Reflection.newInstance(challengeSummons.remove(0))); } CellEmitter.get(Dungeon.level.exit-1).burst(ShadowParticle.UP, 25); CellEmitter.get(Dungeon.level.exit).burst(ShadowParticle.UP, 100); CellEmitter.get(Dungeon.level.exit+1).burst(ShadowParticle.UP, 25); if (abilityCooldown < 5) abilityCooldown = 5; if (summonCooldown < 5) summonCooldown = 5; } LockedFloor lock = Dungeon.hero.buff(LockedFloor.class); if (lock != null) lock.addTime(dmgTaken); } public void addFist(YogFist fist){ fist.pos = Dungeon.level.exit; CellEmitter.get(Dungeon.level.exit-1).burst(ShadowParticle.UP, 25); CellEmitter.get(Dungeon.level.exit).burst(ShadowParticle.UP, 100); CellEmitter.get(Dungeon.level.exit+1).burst(ShadowParticle.UP, 25); if (abilityCooldown < 5) abilityCooldown = 5; if (summonCooldown < 5) summonCooldown = 5; int targetPos = Dungeon.level.exit + Dungeon.level.width(); if (!Dungeon.isChallenged(Challenges.STRONGER_BOSSES) && Actor.findChar(targetPos) == null){ fist.pos = targetPos; } else if (Actor.findChar(targetPos-1) == null){ fist.pos = targetPos-1; } else if (Actor.findChar(targetPos+1) == null){ fist.pos = targetPos+1; } else if (Actor.findChar(targetPos) == null){ fist.pos = targetPos; } GameScene.add(fist, 4); Actor.addDelayed( new Pushing( fist, Dungeon.level.exit, fist.pos ), -1 ); } public void updateVisibility( Level level ){ if (phase > 1 && isAlive()){ level.viewDistance = 4 - (phase-1); } else { level.viewDistance = 4; } level.viewDistance = Math.max(1, level.viewDistance); if (Dungeon.hero != null) { if (Dungeon.hero.buff(Light.class) == null) { Dungeon.hero.viewDistance = level.viewDistance; } Dungeon.observe(); } } private YogFist findFist(){ for ( Char c : Actor.chars() ){ if (c instanceof YogFist){ return (YogFist) c; } } return null; } @Override public void beckon( int cell ) { } @Override public void aggro(Char ch) { for (Mob mob : (Iterable<Mob>)Dungeon.level.mobs.clone()) { if (Dungeon.level.distance(pos, mob.pos) <= 4 && (mob instanceof Larva || mob instanceof RipperDemon)) { mob.aggro(ch); } } } @SuppressWarnings("unchecked") @Override public void die( Object cause ) { for (Mob mob : (Iterable<Mob>)Dungeon.level.mobs.clone()) { if (mob instanceof Larva || mob instanceof RipperDemon) { mob.die( cause ); } } updateVisibility(Dungeon.level); GameScene.bossSlain(); Dungeon.level.unseal(); super.die( cause ); yell( Messages.get(this, "defeated") ); } @Override public void notice() { if (!BossHealthBar.isAssigned()) { BossHealthBar.assignBoss(this); yell(Messages.get(this, "notice")); for (Char ch : Actor.chars()){ if (ch instanceof DriedRose.GhostHero){ ((DriedRose.GhostHero) ch).sayBoss(); } } if (phase == 0) { phase = 1; summonCooldown = Random.NormalFloat(MIN_SUMMON_CD, MAX_SUMMON_CD); abilityCooldown = Random.NormalFloat(MIN_ABILITY_CD, MAX_ABILITY_CD); } } } @Override public String description() { String desc = super.description(); if (Statistics.spawnersAlive > 0){ desc += "\n\n" + Messages.get(this, "desc_spawners"); } return desc; } { immunities.add( Dread.class ); immunities.add( Terror.class ); immunities.add( Amok.class ); immunities.add( Charm.class ); immunities.add( Sleep.class ); immunities.add( Vertigo.class ); immunities.add( Frost.class ); immunities.add( Paralysis.class ); } private static final String PHASE = "phase"; private static final String ABILITY_CD = "ability_cd"; private static final String SUMMON_CD = "summon_cd"; private static final String FIST_SUMMONS = "fist_summons"; private static final String REGULAR_SUMMONS = "regular_summons"; private static final String CHALLENGE_SUMMONS = "challenges_summons"; private static final String TARGETED_CELLS = "targeted_cells"; @Override public void storeInBundle(Bundle bundle) { super.storeInBundle(bundle); bundle.put(PHASE, phase); bundle.put(ABILITY_CD, abilityCooldown); bundle.put(SUMMON_CD, summonCooldown); bundle.put(FIST_SUMMONS, fistSummons.toArray(new Class[0])); bundle.put(CHALLENGE_SUMMONS, challengeSummons.toArray(new Class[0])); bundle.put(REGULAR_SUMMONS, regularSummons.toArray(new Class[0])); int[] bundleArr = new int[targetedCells.size()]; for (int i = 0; i < targetedCells.size(); i++){ bundleArr[i] = targetedCells.get(i); } bundle.put(TARGETED_CELLS, bundleArr); } @Override public void restoreFromBundle(Bundle bundle) { super.restoreFromBundle(bundle); phase = bundle.getInt(PHASE); if (phase != 0) BossHealthBar.assignBoss(this); abilityCooldown = bundle.getFloat(ABILITY_CD); summonCooldown = bundle.getFloat(SUMMON_CD); fistSummons.clear(); Collections.addAll(fistSummons, bundle.getClassArray(FIST_SUMMONS)); //pre-0.9.3 saves if (bundle.contains(CHALLENGE_SUMMONS)) { challengeSummons.clear(); Collections.addAll(challengeSummons, bundle.getClassArray(CHALLENGE_SUMMONS)); } regularSummons.clear(); Collections.addAll(regularSummons, bundle.getClassArray(REGULAR_SUMMONS)); for (int i : bundle.getIntArray(TARGETED_CELLS)){ targetedCells.add(i); } } public static class Larva extends Mob { { spriteClass = LarvaSprite.class; HP = HT = 20; defenseSkill = 12; viewDistance = Light.DISTANCE; EXP = 5; maxLvl = -2; properties.add(Property.DEMONIC); } @Override public int attackSkill( Char target ) { return 30; } @Override public int damageRoll() { return Random.NormalIntRange( 15, 25 ); } @Override public int drRoll() { return Random.NormalIntRange(0, 4); } } //used so death to yog's ripper demons have their own rankings description public static class YogRipper extends RipperDemon {} public static class YogEye extends Eye { { maxLvl = -2; } } public static class YogScorpio extends Scorpio { { maxLvl = -2; } } }
majioa/prometheus2.0
db/migrate/20180815150600_update_counter_cache_for_named_srpms.rb
class UpdateCounterCacheForNamedSrpms < ActiveRecord::Migration[5.1] def change change_column_default(:branches, :srpms_count, 0) change_column_default(:branch_paths, :srpms_count, 0) reversible do |dir| dir.up do BranchPath.all.each { |bp| bp.update(srpms_count: bp.named_srpms.count) } Branch.all.each { |b| b.update(srpms_count: b.named_srpms.count) } end end end end
aswinjose89/ember-vp-md-component
tests/dummy/app/components/ap-map-tooltip.js
<gh_stars>0 import Ember from 'ember'; import layout from '../templates/components/ap-map-tooltip'; export default Ember.Component.extend({ layout, classNames: ['ap-map-tooltip'] });
ClaudioWaldvogel/inspectIT
inspectit.shared.all/src/main/java/rocks/inspectit/shared/all/communication/data/HttpTimerData.java
package rocks.inspectit.shared.all.communication.data; import java.sql.Timestamp; import java.util.Map; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.ManyToOne; import javax.persistence.Transient; import rocks.inspectit.shared.all.cmr.cache.IObjectSizes; /** * Data object holding http based timer data. All timer related information are inherited from the * super class. * * <b> Be careful when adding new attributes. Do not forget to add them to the size calculation. * </b> * * @author <NAME> */ @Entity public class HttpTimerData extends TimerData { /** * Generated serial version id. */ private static final long serialVersionUID = -7868876342858232388L; /** * The default header for tagged requests. */ public static final String INSPECTIT_TAGGING_HEADER = "inspectit_tag"; /** * String used to represent multiple request methods in an aggregation. */ public static final String REQUEST_METHOD_MULTIPLE = "MULTIPLE"; /** * Map is String-String[]. */ @Transient private Map<String, String[]> parameters = null; /** * Map is String-String. */ @Transient private Map<String, String> attributes = null; /** * Map is String-String. */ @Transient private Map<String, String> headers = null; /** * Map is String-String. */ @Transient private Map<String, String> sessionAttributes = null; /** * HTTP response status. */ @Transient private int httpResponseStatus; /** * Http info for optimizing saving to the DB. */ @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.PERSIST) private HttpInfo httpInfo = new HttpInfo(); /** * No-args constructor. */ public HttpTimerData() { } /** * Constructor. * * @param timeStamp * the timestamp of this data * @param platformIdent * the platform identification * @param sensorTypeIdent * the sensor type * @param methodIdent * the method this data comes from */ public HttpTimerData(Timestamp timeStamp, long platformIdent, long sensorTypeIdent, long methodIdent) { super(timeStamp, platformIdent, sensorTypeIdent, methodIdent); } /** * Gets {@link #parameters}. * * @return {@link #parameters} */ public Map<String, String[]> getParameters() { return parameters; } /** * Sets {@link #parameters}. * * @param parameters * New value for {@link #parameters} */ public void setParameters(Map<String, String[]> parameters) { this.parameters = parameters; } /** * Gets {@link #attributes}. * * @return {@link #attributes} */ public Map<String, String> getAttributes() { return attributes; } /** * Sets {@link #attributes}. * * @param attributes * New value for {@link #attributes} */ public void setAttributes(Map<String, String> attributes) { this.attributes = attributes; } /** * Gets {@link #headers}. * * @return {@link #headers} */ public Map<String, String> getHeaders() { return headers; } /** * Sets {@link #headers}. * * @param headers * New value for {@link #headers} */ public void setHeaders(Map<String, String> headers) { this.headers = headers; // set tag value if it exists if (null != headers) { httpInfo.setInspectItTaggingHeaderValue(headers.get(INSPECTIT_TAGGING_HEADER)); } else { httpInfo.setInspectItTaggingHeaderValue(HttpInfo.UNDEFINED); } } /** * Gets {@link #sessionAttributes}. * * @return {@link #sessionAttributes} */ public Map<String, String> getSessionAttributes() { return sessionAttributes; } /** * Sets {@link #sessionAttributes}. * * @param sessionAttributes * New value for {@link #sessionAttributes} */ public void setSessionAttributes(Map<String, String> sessionAttributes) { this.sessionAttributes = sessionAttributes; } /** * Gets {@link #httpInfo}. * * @return {@link #httpInfo} */ public HttpInfo getHttpInfo() { return httpInfo; } /** * Sets {@link #httpInfo}. * * @param httpInfo * New value for {@link #httpInfo} */ public void setHttpInfo(HttpInfo httpInfo) { this.httpInfo = httpInfo; } /** * Gets {@link #httpResponseStatus}. * * @return {@link #httpResponseStatus} */ public int getHttpResponseStatus() { return httpResponseStatus; } /** * Sets {@link #httpResponseStatus}. * * @param httpResponseStatus * New value for {@link #httpResponseStatus} */ public void setHttpResponseStatus(int httpResponseStatus) { this.httpResponseStatus = httpResponseStatus; } /** * {@inheritDoc} */ @Override public long getObjectSize(IObjectSizes objectSizes, boolean doAlign) { long size = super.getObjectSize(objectSizes, doAlign); size += objectSizes.getPrimitiveTypesSize(5, 0, 1, 0, 0, 0); if (null != parameters) { size += objectSizes.getSizeOfHashMap(parameters.size()); for (Map.Entry<String, String[]> entry : parameters.entrySet()) { size += objectSizes.getSizeOf(entry.getKey()); String[] values = entry.getValue(); size += objectSizes.getSizeOfArray(values.length); for (String value : values) { size += objectSizes.getSizeOf(value); } } } if (null != attributes) { size += objectSizes.getSizeOfHashMap(attributes.size()); for (Map.Entry<String, String> entry : attributes.entrySet()) { size += objectSizes.getSizeOf(entry.getKey()); size += objectSizes.getSizeOf(entry.getValue()); } } if (null != headers) { size += objectSizes.getSizeOfHashMap(headers.size()); for (Map.Entry<String, String> entry : headers.entrySet()) { size += objectSizes.getSizeOf(entry.getKey()); size += objectSizes.getSizeOf(entry.getValue()); } } if (null != sessionAttributes) { size += objectSizes.getSizeOfHashMap(sessionAttributes.size()); for (Map.Entry<String, String> entry : sessionAttributes.entrySet()) { size += objectSizes.getSizeOf(entry.getKey()); size += objectSizes.getSizeOf(entry.getValue()); } } size += objectSizes.getSizeOf(httpInfo); if (doAlign) { return objectSizes.alignTo8Bytes(size); } else { return size; } } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = (prime * result) + ((attributes == null) ? 0 : attributes.hashCode()); result = (prime * result) + ((headers == null) ? 0 : headers.hashCode()); result = (prime * result) + ((httpInfo == null) ? 0 : httpInfo.hashCode()); result = (prime * result) + ((parameters == null) ? 0 : parameters.hashCode()); result = (prime * result) + ((sessionAttributes == null) ? 0 : sessionAttributes.hashCode()); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } HttpTimerData other = (HttpTimerData) obj; if (attributes == null) { if (other.attributes != null) { return false; } } else if (!attributes.equals(other.attributes)) { return false; } if (headers == null) { if (other.headers != null) { return false; } } else if (!headers.equals(other.headers)) { return false; } if (httpInfo == null) { if (other.httpInfo != null) { return false; } } else if (!httpInfo.equals(other.httpInfo)) { return false; } if (parameters == null) { if (other.parameters != null) { return false; } } else if (!parameters.equals(other.parameters)) { return false; } if (sessionAttributes == null) { if (other.sessionAttributes != null) { return false; } } else if (!sessionAttributes.equals(other.sessionAttributes)) { return false; } return true; } /** * {@inheritDoc} */ @Override public String toString() { String sup = super.toString(); return sup + "HttpTimerData [uri=" + (null != httpInfo ? httpInfo.getUri() : HttpInfo.UNDEFINED) + ", parameters=" + parameters + ", attributes=" + attributes + ", headers=" + headers + "]"; } }
aixuebo/lin1.5.4
core-storage/src/test/java/org/apache/kylin/storage/translate/ColumnValueRangeTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kylin.storage.translate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.apache.kylin.common.util.Dictionary; import org.apache.kylin.common.util.LocalFileMetadataTestCase; import org.apache.kylin.dict.StringBytesConverter; import org.apache.kylin.dict.TrieDictionaryBuilder; import org.apache.kylin.metadata.filter.TupleFilter.FilterOperatorEnum; import org.apache.kylin.metadata.model.ColumnDesc; import org.apache.kylin.metadata.model.TableDesc; import org.apache.kylin.metadata.model.TblColRef; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class ColumnValueRangeTest extends LocalFileMetadataTestCase { @BeforeClass public static void setUp() throws Exception { staticCreateTestMetadata(); } @AfterClass public static void after() throws Exception { cleanAfterClass(); } @Test public void testPreEvaluateWithDict() { TblColRef col = mockupTblColRef(); Dictionary<String> dict = mockupDictionary(col, "CN", "US"); ColumnValueRange r1 = new ColumnValueRange(col, set("CN", "US", "Other"), FilterOperatorEnum.EQ); r1.preEvaluateWithDict(dict); assertEquals(set("CN", "US"), r1.getEqualValues()); // less than rounding { ColumnValueRange r2 = new ColumnValueRange(col, set("CN"), FilterOperatorEnum.LT); r2.preEvaluateWithDict(dict); assertEquals(null, r2.getBeginValue()); assertEquals("CN", r2.getEndValue()); ColumnValueRange r3 = new ColumnValueRange(col, set("Other"), FilterOperatorEnum.LT); r3.preEvaluateWithDict(dict); assertEquals(null, r3.getBeginValue()); assertEquals("CN", r3.getEndValue()); ColumnValueRange r4 = new ColumnValueRange(col, set("UT"), FilterOperatorEnum.LT); r4.preEvaluateWithDict(dict); assertEquals(null, r4.getBeginValue()); assertEquals("US", r4.getEndValue()); } // greater than rounding { ColumnValueRange r2 = new ColumnValueRange(col, set("CN"), FilterOperatorEnum.GTE); r2.preEvaluateWithDict(dict); assertEquals("CN", r2.getBeginValue()); assertEquals(null, r2.getEndValue()); ColumnValueRange r3 = new ColumnValueRange(col, set("Other"), FilterOperatorEnum.GTE); r3.preEvaluateWithDict(dict); assertEquals("US", r3.getBeginValue()); assertEquals(null, r3.getEndValue()); ColumnValueRange r4 = new ColumnValueRange(col, set("CI"), FilterOperatorEnum.GTE); r4.preEvaluateWithDict(dict); assertEquals("CN", r4.getBeginValue()); assertEquals(null, r4.getEndValue()); } // ever false check { ColumnValueRange r2 = new ColumnValueRange(col, set("UT"), FilterOperatorEnum.GTE); r2.preEvaluateWithDict(dict); assertTrue(r2.satisfyNone()); ColumnValueRange r3 = new ColumnValueRange(col, set("CM"), FilterOperatorEnum.LT); r3.preEvaluateWithDict(dict); assertTrue(r3.satisfyNone()); } } public static Dictionary<String> mockupDictionary(TblColRef col, String... values) { TrieDictionaryBuilder<String> builder = new TrieDictionaryBuilder<String>(new StringBytesConverter()); for (String v : values) { builder.addValue(v); } return builder.build(0); } private static Set<String> set(String... values) { HashSet<String> list = new HashSet<String>(); list.addAll(Arrays.asList(values)); return list; } public static TblColRef mockupTblColRef() { TableDesc t = mockupTableDesc("table_a"); ColumnDesc c = mockupColumnDesc(t, 1, "col_1", "string"); return c.getRef(); } private static TableDesc mockupTableDesc(String tableName) { TableDesc mockup = new TableDesc(); mockup.setName(tableName); return mockup; } private static ColumnDesc mockupColumnDesc(TableDesc table, int oneBasedColumnIndex, String name, String datatype) { ColumnDesc desc = new ColumnDesc(); String id = "" + oneBasedColumnIndex; desc.setId(id); desc.setName(name); desc.setDatatype(datatype); desc.init(table); return desc; } }
khangaikhuu-mstars/mstars-exercises
khangaikhuu/React-Learning/my-demo-npx-app/src/App.js
<filename>khangaikhuu/React-Learning/my-demo-npx-app/src/App.js import { Jumbotron, Container } from "react-bootstrap"; import SearchForm from "./components/SearchForm"; import Result from "./components/Result"; function App() { return ( <div> <Jumbotron> <Container> <h1>This is my React Bootstrap Header</h1> <p> This is my React Bootstrap Paragraph</p> </Container> <SearchForm /> <Result /> </Jumbotron> </div> ); } export default App;
jordsti/stigame
StiGame/bindings/MouseActionMap.cpp
#include "MouseActionMap.h" namespace StiGame { MouseActionMap::MouseActionMap(void) { name = "no name"; button = 0; inputType = IT_MOUSE; positionChecked = false; rect = Rectangle(); } MouseActionMap::MouseActionMap(std::string m_name) { name = m_name; button = 0; inputType = IT_MOUSE; positionChecked = false; rect = Rectangle(); } MouseActionMap::MouseActionMap(std::string m_name, Uint8 m_button) { name = m_name; button = m_button; inputType = IT_MOUSE; positionChecked = false; rect = Rectangle(); } MouseActionMap::~MouseActionMap(void) { } std::string MouseActionMap::toString(void) { return "m" + GetStringValue(button); } int MouseActionMap::getIntValue(void) { return (int)button; } InputType MouseActionMap::getInputType(void) { return inputType; } void MouseActionMap::fromString(std::string str) { std::string action = str; std::string prefix = action.substr(0, 1); if(prefix == "m") { action = action.substr(1, action.size()); } button = GetIntValue(action); } Uint8 MouseActionMap::getButton(void) { return button; } bool MouseActionMap::inputEquals(InputType it, int input) { if(it == inputType) { Uint8 mb = static_cast<Uint8>(input); if(mb == button) { return true; } } return false; } void MouseActionMap::setButton(Uint8 m_button) { button = m_button; } void MouseActionMap::setX(int r_x) { rect.setX(r_x); } void MouseActionMap::setY(int r_y) { rect.setY(r_y); } void MouseActionMap::setWidth(int r_w) { rect.setWidth(r_w); } void MouseActionMap::setHeight(int r_h) { rect.setHeight(r_h); } void MouseActionMap::setRect(int r_x, int r_y, int r_w, int r_h) { rect.setX(r_x); rect.setY(r_y); rect.setWidth(r_w); rect.setHeight(r_h); } void MouseActionMap::setPositionChecked(bool m_positionChecked) { positionChecked = m_positionChecked; } bool MouseActionMap::isPositionChecked(void) { return positionChecked; } bool MouseActionMap::inputMouseEquals(MouseButtonEventArgs *mbEvt) { if(positionChecked) { if(rect.contains(mbEvt->getX(), mbEvt->getY()) && button == mbEvt->getButton() && mbEvt->isDown() ) { return true; } } else { if(mbEvt->isDown() && mbEvt->getButton() == button) { return true; } } return false; } std::string MouseActionMap::GetStringValue(Uint8 m_button) { //SDL_BUTTON_LEFT //SDL_BUTTON_MIDDLE //SDL_BUTTON_RIGHT //SDL_BUTTON_X1 //SDL_BUTTON_X2 std::string str = "unset"; switch(m_button) { case SDL_BUTTON_LEFT: str = "left"; break; case SDL_BUTTON_MIDDLE: str = "middle"; break; case SDL_BUTTON_RIGHT: str = "right"; break; case SDL_BUTTON_X1: str = "x1"; break; case SDL_BUTTON_X2: str = "x2"; break; } return str; } Uint8 MouseActionMap::GetIntValue(std::string m_str) { if(m_str == "left") { return SDL_BUTTON_LEFT; } else if(m_str == "middle") { return SDL_BUTTON_MIDDLE; } else if(m_str == "right") { return SDL_BUTTON_RIGHT; } else if(m_str == "x1") { return SDL_BUTTON_X1; } else { return SDL_BUTTON_X2; } } }
520MianXiangDuiXiang520/JuneGoBlog
src/check/tag.go
package check import ( "JuneGoBlog/src/message" "errors" juneGin "github.com/520MianXiangDuiXiang520/GinTools/gin" "github.com/gin-gonic/gin" "log" ) func TagListCheck(ctx *gin.Context, req juneGin.BaseReqInter) (juneGin.BaseRespInter, error) { return nil, nil } func TagAddCheck(ctx *gin.Context, req juneGin.BaseReqInter) (juneGin.BaseRespInter, error) { reqA := req.(*message.TagAddReq) if reqA.TagName == "" { log.Printf("Check Add Tag Error! name = [%v]\n", reqA.TagName) return juneGin.ParamErrorRespHeader, errors.New("") } return nil, nil }
impastasyndrome/Lambda-Resource-Static-Assets
2-resources/BLOG/Official-Documentation/en.javascript.info-master/en.javascript.info-master/1-js/05-data-types/10-destructuring-assignment/6-max-salary/_js.view/solution.js
function topSalary(salaries) { let maxSalary = 0; let maxName = null; for(const [name, salary] of Object.entries(salaries)) { if (maxSalary < salary) { maxSalary = salary; maxName = name; } } return maxName; }
agramonte/corona
librtt/Core/Rtt_ResourceHandle.cpp
<reponame>agramonte/corona ////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: <EMAIL> // ////////////////////////////////////////////////////////////////////////////// #include "Core/Rtt_Build.h" #include "Core/Rtt_ResourceHandle.h" #include "Core/Rtt_RefCount.h" // ---------------------------------------------------------------------------- namespace Rtt { // ---------------------------------------------------------------------------- BaseResourceHandle::BaseResourceHandle() : fCount( NULL ) { } BaseResourceHandle::BaseResourceHandle( const Self& rhs ) { Retain( rhs.fCount ); } BaseResourceHandle::~BaseResourceHandle() { Release(); } BaseResourceHandle& BaseResourceHandle::operator=( const Self& rhs ) { if ( & rhs != this ) { Release(); Retain( rhs.fCount ); } return * this; } void BaseResourceHandle::Initialize( Rtt_Allocator* pAllocator ) { Rtt_ASSERT( pAllocator ); Retain( Rtt_AllocatorAllocRefCount( pAllocator ) ); } // Bottom (least significant) 8 bits are reserved. Top 24 bits used for ref count. static const int kNumReservedBits = 8; static const RefCount kIncrement = 1 << kNumReservedBits; bool BaseResourceHandle::IsValid() const { Rtt_ASSERT( fCount ); // Valid only if bottom 8 bits must be zero return (fCount && (0 == ((*fCount) & 0xFF))); } void BaseResourceHandle::Invalidate() { // Ensure fCount is valid and > 0 Rtt_ASSERT( IsValid() && (*fCount >> kNumReservedBits) > 0 ); // Turn on bottom 8 bits *fCount = (*fCount) | 0xFF; } void BaseResourceHandle::Retain( RefCount *pCount ) { fCount = pCount; if ( pCount ) { // ++(*pCount); *pCount = *pCount + kIncrement; } } void BaseResourceHandle::Release() { RefCount *pCount = fCount; if ( pCount ) { // --(*pCount); RefCount oldCount = *pCount; RefCount c = (oldCount >> kNumReservedBits) - 1; if ( 0 >= c ) { Rtt_AllocatorFreeRefCount( pCount ); } else { *pCount = oldCount - kIncrement; } } } // ---------------------------------------------------------------------------- } // Rtt // ----------------------------------------------------------------------------
huhong789/shortcut
eglibc-2.15/elf/dl-environ.c
<filename>eglibc-2.15/elf/dl-environ.c /* Environment handling for dynamic loader. Copyright (C) 1995-1998, 2000, 2001, 2002 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <string.h> #include <stdlib.h> #include <unistd.h> #include <ldsodefs.h> /* Walk through the environment of the process and return all entries starting with `LD_'. */ char * internal_function _dl_next_ld_env_entry (char ***position) { char **current = *position; char *result = NULL; while (*current != NULL) { if (__builtin_expect ((*current)[0] == 'L', 0) && (*current)[1] == 'D' && (*current)[2] == '_') { result = &(*current)[3]; /* Save current position for next visit. */ *position = ++current; break; } ++current; } return result; } /* In ld.so __environ is not exported. */ extern char **__environ attribute_hidden; int unsetenv (const char *name) { char **ep; ep = __environ; while (*ep != NULL) { size_t cnt = 0; while ((*ep)[cnt] == name[cnt] && name[cnt] != '\0') ++cnt; if (name[cnt] == '\0' && (*ep)[cnt] == '=') { /* Found it. Remove this pointer by moving later ones to the front. */ char **dp = ep; do dp[0] = dp[1]; while (*dp++); /* Continue the loop in case NAME appears again. */ } else ++ep; } return 0; }
triffon/oop-2019-20
labs/3/lab7/Stack.cpp
// // Created by tony on 16.04.20 г.. // #include "Stack.h" template <class T> Stack<T>::Stack(): size(0), capacity(8){ data = new T[capacity]; } template <class T> Stack<T>::Stack(int _capacity): size(0), capacity(_capacity){ data = new T[capacity]; } template <class T> Stack<T>::~Stack(){ clean(); } template <class T> void Stack<T>::copy(const Stack<T> &other) { size = other.size; capacity = other.capacity; data = new T[capacity]; for(int i = 0; i < size; i++){ data[i] = other.data[i]; } } template <class T> void Stack<T>::clean() { delete[] data; data = nullptr; } template <class T> Stack<T>& Stack<T>::operator=(const Stack<T> &other) { if(this != &other){ clean(); copy(other); } return *this; } template <class T> void Stack<T>::resize() { capacity *= 2; T* newData = new T[capacity]; for(int i = 0; i < size; i++){ newData[i] = data[i]; } clean(); data = newData; } template<typename T> Stack<T>::Stack(const Stack &other) { copy(other); } template <typename T> void Stack<T>::push(T toPush) { if(size == capacity){ resize(); } data[size++] = toPush; } template <class T> bool Stack<T>::empty() const { return size == 0; } template <class T> T Stack<T>::pop() { if (!empty()) { return data[size--]; } } template <typename P> int Stack<P>::getSize() const { return size; } template <typename T> T Stack<T>::top() const { return data[size]; }
DanPopa46/neo-mamba
neo3/contracts/native/fungible.py
from __future__ import annotations import struct from .nativecontract import NativeContract from .decorator import register from neo3 import storage, contracts, vm, settings from neo3.core import types, msgrouter, cryptography, serialization, to_script_hash, Size as s, IInteroperable from typing import Tuple, List, Dict, Sequence, cast class FungibleTokenStorageState(IInteroperable, serialization.ISerializable): """ Helper class for NEP17 balance state """ def __init__(self): super(FungibleTokenStorageState, self).__init__() self.balance: vm.BigInteger = vm.BigInteger.zero() def __len__(self): return len(self.balance.to_array()) def serialize(self, writer: serialization.BinaryWriter) -> None: writer.write_var_bytes(self.balance.to_array()) def deserialize(self, reader: serialization.BinaryReader) -> None: self.balance = vm.BigInteger(reader.read_var_bytes()) def to_stack_item(self, reference_counter: vm.ReferenceCounter) -> vm.StackItem: struct_ = vm.StructStackItem(reference_counter) struct_.append(vm.IntegerStackItem(self.balance)) return struct_ @classmethod def from_stack_item(cls, stack_item: vm.StackItem): si = cast(vm.StructStackItem, stack_item) c = cls() c.balance = si[0].to_biginteger() return c class FungibleToken(NativeContract): _id: int = -99999 _decimals: int = -1 _state = FungibleTokenStorageState _symbol: str = "" def init(self): super(FungibleToken, self).init() self.key_account = storage.StorageKey(self._id, b'\x14') self.key_total_supply = storage.StorageKey(self._id, b'\x0B') self.manifest.supported_standards = ["NEP-17"] self.manifest.abi.events = [ contracts.ContractEventDescriptor( "Transfer", parameters=[ contracts.ContractParameterDefinition("from", contracts.ContractParameterType.HASH160), contracts.ContractParameterDefinition("to", contracts.ContractParameterType.HASH160), contracts.ContractParameterDefinition("amount", contracts.ContractParameterType.INTEGER) ] ) ] self.factor = pow(vm.BigInteger(10), vm.BigInteger(self._decimals)) @register("decimals", contracts.CallFlags.READ_STATES) def decimals(self) -> int: return self._decimals @register("symbol", contracts.CallFlags.READ_STATES) def symbol(self) -> str: """ Token symbol. """ return self._symbol @register("totalSupply", contracts.CallFlags.READ_STATES, cpu_price=1 << 15) def total_supply(self, snapshot: storage.Snapshot) -> vm.BigInteger: """ Get the total deployed tokens. """ storage_item = snapshot.storages.try_get(self.key_total_supply) if storage_item is None: return vm.BigInteger.zero() else: return vm.BigInteger(storage_item.value) @register("balanceOf", contracts.CallFlags.READ_STATES, cpu_price=1 << 15) def balance_of(self, snapshot: storage.Snapshot, account: types.UInt160) -> vm.BigInteger: """ Get the balance of an account. Args: snapshot: snapshot of the storage account: script hash of the account to obtain the balance of Returns: amount of balance. Note: The returned value is still in internal format. Divide the results by the contract's `decimals` """ storage_item = snapshot.storages.try_get(self.key_account + account) if storage_item is None: return vm.BigInteger.zero() else: state = self._state.deserialize_from_bytes(storage_item.value) return state.balance @register("transfer", (contracts.CallFlags.STATES | contracts.CallFlags.ALLOW_CALL | contracts.CallFlags.ALLOW_NOTIFY), cpu_price=1 << 17, storage_price=50) def transfer(self, engine: contracts.ApplicationEngine, account_from: types.UInt160, account_to: types.UInt160, amount: vm.BigInteger, data: vm.StackItem ) -> bool: """ Transfer tokens from one account to another. Raises: ValueError: if the requested amount is negative. Returns: True on success. False otherwise. """ if amount.sign < 0: raise ValueError("Can't transfer a negative amount") # transfer from an account not owned by the smart contract that is requesting the transfer # and there is no signature that approves we are allowed todo so if account_from != engine.calling_scripthash and not engine.checkwitness(account_from): return False storage_key_from = self.key_account + account_from storage_item_from = engine.snapshot.storages.try_get(storage_key_from, read_only=False) if storage_item_from is None: return False state_from = storage_item_from.get(self._state) if amount == vm.BigInteger.zero(): self.on_balance_changing(engine, account_from, state_from, amount) else: if state_from.balance < amount: return False if account_from == account_to: self.on_balance_changing(engine, account_from, state_from, vm.BigInteger.zero()) else: self.on_balance_changing(engine, account_from, state_from, -amount) if state_from.balance == amount: engine.snapshot.storages.delete(storage_key_from) else: state_from.balance -= amount storage_key_to = self.key_account + account_to storage_item_to = engine.snapshot.storages.try_get(storage_key_to, read_only=False) if storage_item_to is None: storage_item_to = storage.StorageItem(self._state().to_array()) engine.snapshot.storages.put(storage_key_to, storage_item_to) state_to = storage_item_to.get(self._state) self.on_balance_changing(engine, account_to, state_to, amount) state_to.balance += amount self._post_transfer(engine, account_from, account_to, amount, data, True) return True def mint(self, engine: contracts.ApplicationEngine, account: types.UInt160, amount: vm.BigInteger, call_on_payment: bool) -> None: """ Mint an amount of tokens into account. Increases the total supply of the token. """ if amount.sign < 0: raise ValueError("Can't mint a negative amount") if amount == vm.BigInteger.zero(): return storage_key = self.key_account + account storage_item = engine.snapshot.storages.try_get(storage_key, read_only=False) if storage_item is None: storage_item = storage.StorageItem(self._state().to_array()) engine.snapshot.storages.put(storage_key, storage_item) state = storage_item.get(self._state) self.on_balance_changing(engine, account, state, amount) state.balance += amount storage_item = engine.snapshot.storages.try_get(self.key_total_supply, read_only=False) if storage_item is None: storage_item = storage.StorageItem(amount.to_array()) engine.snapshot.storages.put(self.key_total_supply, storage_item) else: old_value = vm.BigInteger(storage_item.value) storage_item.value = (amount + old_value).to_array() self._post_transfer(engine, types.UInt160.zero(), account, amount, vm.NullStackItem(), call_on_payment) def burn(self, engine: contracts.ApplicationEngine, account: types.UInt160, amount: vm.BigInteger) -> None: """ Burn an amount of tokens from account. Reduces the total supply of the token. Raises: ValueError: if amount is negative ValueError: if the burn amount is larger than the available balance in the account """ if amount.sign < 0: raise ValueError("Can't burn a negative amount") if amount == vm.BigInteger.zero(): return storage_key = self.key_account + account storage_item = engine.snapshot.storages.get(storage_key, read_only=False) state = storage_item.get(self._state) if state.balance < amount: raise ValueError(f"Insufficient balance. Requesting to burn {amount}, available {state.balance}") self.on_balance_changing(engine, account, state, -amount) if state.balance == amount: engine.snapshot.storages.delete(storage_key) else: state.balance -= amount engine.snapshot.storages.update(storage_key, storage_item) storage_item = engine.snapshot.storages.get(self.key_total_supply, read_only=False) old_value = vm.BigInteger(storage_item.value) new_value = old_value - amount if new_value == vm.BigInteger.zero(): engine.snapshot.storages.delete(self.key_total_supply) else: storage_item.value = new_value.to_array() self._post_transfer(engine, account, types.UInt160.zero(), amount, vm.NullStackItem(), False) def on_balance_changing(self, engine: contracts.ApplicationEngine, account: types.UInt160, state, amount: vm.BigInteger) -> None: pass def on_persist(self, engine: contracts.ApplicationEngine) -> None: pass def _post_transfer(self, engine: contracts.ApplicationEngine, account_from: types.UInt160, account_to: types.UInt160, amount: vm.BigInteger, data: vm.StackItem, call_on_payment: bool) -> None: state = vm.ArrayStackItem(vm.ReferenceCounter()) if account_from == types.UInt160.zero(): state.append(vm.NullStackItem()) else: state.append(vm.ByteStringStackItem(account_from.to_array())) if account_to == types.UInt160.zero(): state.append(vm.NullStackItem()) else: state.append(vm.ByteStringStackItem(account_to.to_array())) state.append(vm.IntegerStackItem(amount)) msgrouter.interop_notify(self.hash, "Transfer", state) # wallet or smart contract if not call_on_payment \ or account_to == types.UInt160.zero() \ or contracts.ManagementContract().get_contract(engine.snapshot, account_to) is None: return if account_from == types.UInt160.zero(): from_: vm.StackItem = vm.NullStackItem() else: from_ = vm.ByteStringStackItem(account_from.to_array()) engine.call_from_native(self.hash, account_to, "onNEP17Payment", [from_, vm.IntegerStackItem(amount), data]) class _NeoTokenStorageState(FungibleTokenStorageState): """ Helper class for storing voting and bonus GAS state """ def __init__(self): super(_NeoTokenStorageState, self).__init__() self.vote_to: cryptography.ECPoint = cryptography.ECPoint.deserialize_from_bytes(b'\x00') self.balance_height: int = 0 def __len__(self): return super(_NeoTokenStorageState, self).__len__() + len(self.vote_to) + s.uint32 def serialize(self, writer: serialization.BinaryWriter) -> None: super(_NeoTokenStorageState, self).serialize(writer) writer.write_serializable(self.vote_to) writer.write_uint32(self.balance_height) def deserialize(self, reader: serialization.BinaryReader) -> None: super(_NeoTokenStorageState, self).deserialize(reader) self.vote_to = reader.read_serializable(cryptography.ECPoint) # type: ignore self.balance_height = reader.read_uint32() class _CandidateState(serialization.ISerializable): """ Helper class for storing consensus candidates and their votes """ def __init__(self): self.registered = True self.votes = vm.BigInteger.zero() def __len__(self): return 1 + len(self.votes.to_array()) def serialize(self, writer: serialization.BinaryWriter) -> None: writer.write_bool(self.registered) writer.write_var_bytes(self.votes.to_array()) def deserialize(self, reader: serialization.BinaryReader) -> None: self.registered = reader.read_bool() self.votes = vm.BigInteger(reader.read_var_bytes()) class _CommitteeState(serialization.ISerializable): def __init__(self, snapshot: storage.Snapshot, validators: Dict[cryptography.ECPoint, vm.BigInteger]): self.snapshot = snapshot self._validators = validators self._storage_key = NeoToken().key_committee def __len__(self): return len(self.to_array()) def __getitem__(self, item: cryptography.ECPoint) -> vm.BigInteger: return self._validators[item] @classmethod def from_snapshot(cls, snapshot: storage.Snapshot): c = cls(snapshot, {}) with serialization.BinaryReader(snapshot.storages.get(c._storage_key, read_only=True).value) as reader: c.deserialize(reader) return c @property def validators(self) -> List[cryptography.ECPoint]: return list(self._validators.keys()) def persist(self, snapshot: storage.Snapshot): self.snapshot = snapshot self.snapshot.storages.update(self._storage_key, storage.StorageItem(self.to_array())) def serialize(self, writer: serialization.BinaryWriter) -> None: writer.write_var_int(len(self._validators)) for key, value in self._validators.items(): writer.write_serializable(key) writer.write_var_bytes(value.to_array()) def deserialize(self, reader: serialization.BinaryReader) -> None: length = reader.read_var_int() if self._validators is None: self._validators = {} else: self._validators.clear() for _ in range(length): public_key = reader.read_serializable(cryptography.ECPoint) # type: ignore self._validators.update({ public_key: vm.BigInteger(reader.read_var_bytes()) }) class _GasRecord(serialization.ISerializable): def __init__(self, index: int, gas_per_block: vm.BigInteger): self.index = index self.gas_per_block = gas_per_block def __len__(self): return s.uint32 + len(self.gas_per_block.to_array()) def serialize(self, writer: serialization.BinaryWriter) -> None: writer.write_uint32(self.index) writer.write_var_bytes(self.gas_per_block.to_array()) def deserialize(self, reader: serialization.BinaryReader) -> None: self.index = reader.read_uint32() self.gas_per_block = vm.BigInteger(reader.read_var_bytes()) @classmethod def _serializable_init(cls): return cls(0, vm.BigInteger.zero()) class GasBonusState(serialization.ISerializable, Sequence): def __init__(self, initial_record: _GasRecord = None): self._storage_key = NeoToken().key_gas_per_block self._records: List[_GasRecord] = [initial_record] if initial_record else [] self._iter = iter(self._records) def __len__(self): return len(self._records) def __iter__(self): self._iter = iter(self._records) return self def __next__(self) -> _GasRecord: return next(self._iter) def __getitem__(self, item): return self._records.__getitem__(item) def __setitem__(self, key, record: _GasRecord) -> None: self._records[key] = record @classmethod def from_snapshot(cls, snapshot: storage.Snapshot, read_only=False): storage_item = snapshot.storages.get(NeoToken().key_gas_per_block, read_only) return storage_item.get(cls) def append(self, record: _GasRecord) -> None: self._records.append(record) def serialize(self, writer: serialization.BinaryWriter) -> None: writer.write_serializable_list(self._records) def deserialize(self, reader: serialization.BinaryReader) -> None: self._records = reader.read_serializable_list(_GasRecord) class NeoToken(FungibleToken): _id: int = -5 _decimals: int = 0 key_committee = storage.StorageKey(_id, b'\x0e') key_candidate = storage.StorageKey(_id, b'\x21') key_voters_count = storage.StorageKey(_id, b'\x01') key_gas_per_block = storage.StorageKey(_id, b'\x29') key_voter_reward_per_committee = storage.StorageKey(_id, b'\x17') key_register_price = storage.StorageKey(_id, b'\x0D') _NEO_HOLDER_REWARD_RATIO = 10 _COMMITTEE_REWARD_RATIO = 10 _VOTER_REWARD_RATIO = 80 _symbol = "NEO" _state = _NeoTokenStorageState _candidates_dirty = True _candidates: List[Tuple[cryptography.ECPoint, vm.BigInteger]] = [] def init(self): super(NeoToken, self).init() # singleton init, similar to __init__ but called only once self.total_amount = self.factor * 100_000_000 self._committee_state = None def _initialize(self, engine: contracts.ApplicationEngine) -> None: # NEO's native contract initialize. Is called upon contract deploy self._committee_state = _CommitteeState(engine.snapshot, dict.fromkeys(settings.standby_validators, vm.BigInteger(0))) engine.snapshot.storages.put(self.key_voters_count, storage.StorageItem(b'\x00')) gas_bonus_state = GasBonusState(_GasRecord(0, GasToken().factor * 5)) engine.snapshot.storages.put(self.key_gas_per_block, storage.StorageItem(gas_bonus_state.to_array())) engine.snapshot.storages.put(self.key_register_price, storage.StorageItem((GasToken().factor * 1000).to_array())) self.mint(engine, contracts.Contract.get_consensus_address(settings.standby_validators), self.total_amount, False) @register("unclaimedGas", contracts.CallFlags.READ_STATES, cpu_price=1 << 17) def unclaimed_gas(self, snapshot: storage.Snapshot, account: types.UInt160, end: int) -> vm.BigInteger: """ Return the available bonus GAS for an account. Requires sending the accounts balance to release the bonus GAS. Args: snapshot: snapshot of storage account: account to calculate bonus for end: ending block height to calculate bonus up to. You should use mostlikly use the current chain height. """ storage_item = snapshot.storages.try_get(self.key_account + account) if storage_item is None: return vm.BigInteger.zero() state = storage_item.get(self._state) return self._calculate_bonus(snapshot, state.vote_to, state.balance, state.balance_height, end) @register("registerCandidate", contracts.CallFlags.STATES) def register_candidate(self, engine: contracts.ApplicationEngine, public_key: cryptography.ECPoint) -> bool: """ Register a candidate for consensus node election. Args: engine: Application engine instance public_key: the candidate's public key Returns: True is succesfully registered. False otherwise. """ script_hash = to_script_hash(contracts.Contract.create_signature_redeemscript(public_key)) if not engine.checkwitness(script_hash): return False engine.add_gas(self.get_register_price(engine.snapshot)) storage_key = self.key_candidate + public_key storage_item = engine.snapshot.storages.try_get(storage_key, read_only=False) if storage_item is None: state = _CandidateState() state.registered = True storage_item = storage.StorageItem(state.to_array()) engine.snapshot.storages.put(storage_key, storage_item) else: state = storage_item.get(_CandidateState) state.registered = True self._candidates_dirty = True return True @register("unregisterCandidate", contracts.CallFlags.STATES, cpu_price=1 << 16) def unregister_candidate(self, engine: contracts.ApplicationEngine, public_key: cryptography.ECPoint) -> bool: """ Remove a candidate from the consensus node candidate list. Args: engine: Application engine instance public_key: the candidate's public key Returns: True is succesfully removed. False otherwise. """ script_hash = to_script_hash(contracts.Contract.create_signature_redeemscript(public_key)) if not engine.checkwitness(script_hash): return False storage_key = self.key_candidate + public_key storage_item = engine.snapshot.storages.try_get(storage_key, read_only=False) if storage_item is None: return True else: state = storage_item.get(_CandidateState) state.registered = False if state.votes == 0: engine.snapshot.storages.delete(storage_key) self._candidates_dirty = True return True @register("vote", contracts.CallFlags.STATES, cpu_price=1 << 16) def vote(self, engine: contracts.ApplicationEngine, account: types.UInt160, vote_to: cryptography.ECPoint) -> bool: """ Vote on a consensus candidate Args: engine: Application engine instance. account: source account to take voting balance from vote_to: candidate public key Returns: True is vote registered succesfully. False otherwise. """ if not engine.checkwitness(account): return False storage_key_account = self.key_account + account storage_item = engine.snapshot.storages.try_get(storage_key_account, read_only=False) if storage_item is None: return False account_state = storage_item.get(self._state) storage_key_candidate = self.key_candidate + vote_to storage_item_candidate = engine.snapshot.storages.try_get(storage_key_candidate, read_only=False) if storage_item_candidate is None: return False candidate_state = storage_item_candidate.get(_CandidateState) if not candidate_state.registered: return False if account_state.vote_to.is_zero(): si_voters_count = engine.snapshot.storages.get(self.key_voters_count, read_only=False) old_value = vm.BigInteger(si_voters_count.value) new_value = old_value + account_state.balance si_voters_count.value = new_value.to_array() self._distribute_gas(engine, account, account_state) if not account_state.vote_to.is_zero(): sk_validator = self.key_candidate + account_state.vote_to si_validator = engine.snapshot.storages.get(sk_validator, read_only=False) validator_state = si_validator.get(_CandidateState) validator_state.votes -= account_state.balance if not validator_state.registered and validator_state.votes == 0: engine.snapshot.storages.delete(sk_validator) account_state.vote_to = vote_to candidate_state.votes += account_state.balance self._candidates_dirty = True return True @register("getCandidates", contracts.CallFlags.READ_STATES, cpu_price=1 << 22) def get_candidates(self, engine: contracts.ApplicationEngine) -> None: array = vm.ArrayStackItem(engine.reference_counter) for k, v in self._get_candidates(engine.snapshot): struct = vm.StructStackItem(engine.reference_counter) struct.append(vm.ByteStringStackItem(k.to_array())) struct.append(vm.IntegerStackItem(v)) array.append(struct) engine.push(array) @register("getNextBlockValidators", contracts.CallFlags.READ_STATES, cpu_price=1 << 16) def get_next_block_validators(self, snapshot: storage.Snapshot) -> List[cryptography.ECPoint]: keys = self.get_committee_from_cache(snapshot)[:settings.network.validators_count] keys.sort() return keys @register("setGasPerBlock", contracts.CallFlags.STATES, cpu_price=1 << 15) def _set_gas_per_block(self, engine: contracts.ApplicationEngine, gas_per_block: vm.BigInteger) -> None: if gas_per_block > 0 or gas_per_block > 10 * self._gas.factor: raise ValueError("new gas per block value exceeds limits") if not self._check_committee(engine): raise ValueError("Check committee failed") index = engine.snapshot.persisting_block.index + 1 gas_bonus_state = GasBonusState.from_snapshot(engine.snapshot, read_only=False) if gas_bonus_state[-1].index == index: gas_bonus_state[-1] = _GasRecord(index, gas_per_block) else: gas_bonus_state.append(_GasRecord(index, gas_per_block)) @register("getGasPerBlock", contracts.CallFlags.READ_STATES, cpu_price=1 << 15) def get_gas_per_block(self, snapshot: storage.Snapshot) -> vm.BigInteger: index = snapshot.best_block_height + 1 gas_bonus_state = GasBonusState.from_snapshot(snapshot, read_only=True) for record in reversed(gas_bonus_state): # type: _GasRecord if record.index <= index: return record.gas_per_block else: raise ValueError @register("setRegisterPrice", contracts.CallFlags.STATES, cpu_price=1 << 15) def set_register_price(self, engine: contracts.ApplicationEngine, register_price: int) -> None: if register_price <= 0: raise ValueError("Register price cannot be negative or zero") if not self._check_committee(engine): raise ValueError("CheckCommittee failed for setRegisterPrice") item = engine.snapshot.storages.get(self.key_register_price, read_only=False) item.value = vm.BigInteger(register_price).to_array() @register("getRegisterPrice", contracts.CallFlags.READ_STATES, cpu_price=1 << 15) def get_register_price(self, snapshot: storage.Snapshot) -> int: return int(vm.BigInteger(snapshot.storages.get(self.key_register_price, read_only=True).value)) def _distribute_gas(self, engine: contracts.ApplicationEngine, account: types.UInt160, state: _NeoTokenStorageState) -> None: if engine.snapshot.persisting_block is None: return gas = self._calculate_bonus(engine.snapshot, state.vote_to, state.balance, state.balance_height, engine.snapshot.persisting_block.index) state.balance_height = engine.snapshot.persisting_block.index GasToken().mint(engine, account, gas, True) @register("getCommittee", contracts.CallFlags.READ_STATES, cpu_price=1 << 16) def get_committee(self, snapshot: storage.Snapshot) -> List[cryptography.ECPoint]: return sorted(self.get_committee_from_cache(snapshot)) def total_supply(self, snapshot: storage.Snapshot) -> vm.BigInteger: """ Get the total deployed tokens. """ return self.total_amount def on_balance_changing(self, engine: contracts.ApplicationEngine, account: types.UInt160, state, amount: vm.BigInteger) -> None: self._distribute_gas(engine, account, state) if amount == vm.BigInteger.zero(): return if state.vote_to.is_zero(): return si_voters_count = engine.snapshot.storages.get(self.key_voters_count, read_only=False) new_value = vm.BigInteger(si_voters_count.value) + amount si_voters_count.value = new_value.to_array() si_candidate = engine.snapshot.storages.get(self.key_candidate + state.vote_to, read_only=False) candidate_state = si_candidate.get(_CandidateState) candidate_state.votes += amount self._candidates_dirty = True self._check_candidate(engine.snapshot, state.vote_to, candidate_state) def on_persist(self, engine: contracts.ApplicationEngine) -> None: super(NeoToken, self).on_persist(engine) # set next committee if self._should_refresh_committee(engine.snapshot.persisting_block.index): validators = self._compute_committee_members(engine.snapshot) if self._committee_state is None: self._committee_state = _CommitteeState.from_snapshot(engine.snapshot) self._committee_state._validators = validators self._committee_state.persist(engine.snapshot) def post_persist(self, engine: contracts.ApplicationEngine): super(NeoToken, self).post_persist(engine) # distribute GAS for committee m = len(settings.standby_committee) n = settings.network.validators_count index = engine.snapshot.persisting_block.index % m gas_per_block = self.get_gas_per_block(engine.snapshot) committee = self.get_committee_from_cache(engine.snapshot) pubkey = committee[index] account = to_script_hash(contracts.Contract.create_signature_redeemscript(pubkey)) GasToken().mint(engine, account, gas_per_block * self._COMMITTEE_REWARD_RATIO / 100, False) if self._should_refresh_committee(engine.snapshot.persisting_block.index): voter_reward_of_each_committee = gas_per_block * self._VOTER_REWARD_RATIO * 100000000 * m / (m + n) / 100 for i, member in enumerate(committee): factor = 2 if i < n else 1 member_votes = self._committee_state[member] if member_votes > 0: voter_sum_reward_per_neo = voter_reward_of_each_committee * factor / member_votes voter_reward_key = (self.key_voter_reward_per_committee + member + self._to_uint32(engine.snapshot.persisting_block.index + 1) ) border = (self.key_voter_reward_per_committee + member).to_array() try: pair = next(engine.snapshot.storages.find_range(voter_reward_key.to_array(), border, "reverse")) result = vm.BigInteger(pair[1].value) except StopIteration: result = vm.BigInteger.zero() voter_sum_reward_per_neo += result engine.snapshot.storages.put(voter_reward_key, storage.StorageItem(voter_sum_reward_per_neo.to_array())) def get_committee_from_cache(self, snapshot: storage.Snapshot) -> List[cryptography.ECPoint]: if self._committee_state is None: self._committee_state = _CommitteeState.from_snapshot(snapshot) return self._committee_state.validators def get_committee_address(self, snapshot: storage.Snapshot) -> types.UInt160: comittees = self.get_committee(snapshot) return to_script_hash( contracts.Contract.create_multisig_redeemscript( len(comittees) - (len(comittees) - 1) // 2, comittees) ) def _calculate_bonus(self, snapshot: storage.Snapshot, vote: cryptography.ECPoint, value: vm.BigInteger, start: int, end: int) -> vm.BigInteger: if value == vm.BigInteger.zero() or start >= end: return vm.BigInteger.zero() if value.sign < 0: raise ValueError("Can't calculate bonus over negative balance") neo_holder_reward = self._calculate_neo_holder_reward(snapshot, value, start, end) if vote.is_zero(): return neo_holder_reward border = (self.key_voter_reward_per_committee + vote).to_array() start_bytes = self._to_uint32(start) key_start = (self.key_voter_reward_per_committee + vote + start_bytes).to_array() try: pair = next(snapshot.storages.find_range(key_start, border, "reverse")) start_reward_per_neo = vm.BigInteger(pair[1].value) # first pair returned, StorageItem except StopIteration: start_reward_per_neo = vm.BigInteger.zero() end_bytes = self._to_uint32(end) key_end = (self.key_voter_reward_per_committee + vote + end_bytes).to_array() try: pair = next(snapshot.storages.find_range(key_end, border, "reverse")) end_reward_per_neo = vm.BigInteger(pair[1].value) # first pair returned, StorageItem except StopIteration: end_reward_per_neo = vm.BigInteger.zero() return neo_holder_reward + value * (end_reward_per_neo - start_reward_per_neo) / 100000000 def _calculate_neo_holder_reward(self, snapshot: storage.Snapshot, value: vm.BigInteger, start: int, end: int) -> vm.BigInteger: gas_bonus_state = GasBonusState.from_snapshot(snapshot, read_only=True) gas_sum = 0 for pair in reversed(gas_bonus_state): # type: _GasRecord cur_idx = pair.index if cur_idx >= end: continue if cur_idx > start: gas_sum += pair.gas_per_block * (end - cur_idx) end = cur_idx else: gas_sum += pair.gas_per_block * (end - start) break return value * gas_sum * self._NEO_HOLDER_REWARD_RATIO / 100 / self.total_amount def _check_candidate(self, snapshot: storage.Snapshot, public_key: cryptography.ECPoint, candidate: _CandidateState) -> None: if not candidate.registered and candidate.votes == 0: for k, v in snapshot.storages.find((self.key_voter_reward_per_committee + public_key).to_array()): snapshot.storages.delete(k) snapshot.storages.delete(self.key_candidate + public_key) def _compute_committee_members(self, snapshot: storage.Snapshot) -> Dict[cryptography.ECPoint, vm.BigInteger]: storage_item = snapshot.storages.get(self.key_voters_count, read_only=True) voters_count = int(vm.BigInteger(storage_item.value)) voter_turnout = voters_count / float(self.total_amount) candidates = self._get_candidates(snapshot) if voter_turnout < 0.2 or len(candidates) < len(settings.standby_committee): results = {} for key in settings.standby_committee: for pair in candidates: if pair[0] == key: results.update({key: pair[1]}) break else: results.update({key: vm.BigInteger.zero()}) return results # first sort by votes descending, then by ECPoint ascending # we negate the value of the votes (c[1]) such that they get sorted in descending order candidates.sort(key=lambda c: (-c[1], c[0])) trimmed_candidates = candidates[:len(settings.standby_committee)] results = {} for candidate in trimmed_candidates: results.update({candidate[0]: candidate[1]}) return results def _get_candidates(self, snapshot: storage.Snapshot) -> \ List[Tuple[cryptography.ECPoint, vm.BigInteger]]: if self._candidates_dirty: self._candidates = [] for k, v in snapshot.storages.find(self.key_candidate.to_array()): candidate = _CandidateState.deserialize_from_bytes(v.value) if candidate.registered: # take of the CANDIDATE prefix point = cryptography.ECPoint.deserialize_from_bytes(k.key[1:]) self._candidates.append((point, candidate.votes)) self._candidates_dirty = False return self._candidates def _should_refresh_committee(self, height: int) -> bool: return height % len(settings.standby_committee) == 0 def _to_uint32(self, value: int) -> bytes: return struct.pack(">I", value) class GasToken(FungibleToken): _id: int = -6 _decimals: int = 8 _state = FungibleTokenStorageState _symbol = "GAS" def _initialize(self, engine: contracts.ApplicationEngine) -> None: account = contracts.Contract.get_consensus_address(settings.standby_validators) self.mint(engine, account, vm.BigInteger(30_000_000) * self.factor, False) def on_persist(self, engine: contracts.ApplicationEngine) -> None: super(GasToken, self).on_persist(engine) total_network_fee = 0 for tx in engine.snapshot.persisting_block.transactions: total_network_fee += tx.network_fee self.burn(engine, tx.sender, vm.BigInteger(tx.system_fee + tx.network_fee)) pub_keys = NeoToken().get_next_block_validators(engine.snapshot) primary = pub_keys[engine.snapshot.persisting_block.primary_index] script_hash = to_script_hash(contracts.Contract.create_signature_redeemscript(primary)) self.mint(engine, script_hash, vm.BigInteger(total_network_fee), False)
Sunrisepeak/Linux2.6-Reading
sound/virtio/virtio_pcm_msg.c
// SPDX-License-Identifier: GPL-2.0+ /* * virtio-snd: Virtio sound device * Copyright (C) 2021 OpenSynergy GmbH */ #include <sound/pcm_params.h> #include "virtio_card.h" /** * struct virtio_pcm_msg - VirtIO I/O message. * @substream: VirtIO PCM substream. * @xfer: Request header payload. * @status: Response header payload. * @length: Data length in bytes. * @sgs: Payload scatter-gather table. */ struct virtio_pcm_msg { struct virtio_pcm_substream *substream; struct virtio_snd_pcm_xfer xfer; struct virtio_snd_pcm_status status; size_t length; struct scatterlist sgs[]; }; /** * enum pcm_msg_sg_index - Index values for the virtio_pcm_msg->sgs field in * an I/O message. * @PCM_MSG_SG_XFER: Element containing a virtio_snd_pcm_xfer structure. * @PCM_MSG_SG_STATUS: Element containing a virtio_snd_pcm_status structure. * @PCM_MSG_SG_DATA: The first element containing a data buffer. */ enum pcm_msg_sg_index { PCM_MSG_SG_XFER = 0, PCM_MSG_SG_STATUS, PCM_MSG_SG_DATA }; /** * virtsnd_pcm_sg_num() - Count the number of sg-elements required to represent * vmalloc'ed buffer. * @data: Pointer to vmalloc'ed buffer. * @length: Buffer size. * * Context: Any context. * Return: Number of physically contiguous parts in the @data. */ static int virtsnd_pcm_sg_num(u8 *data, unsigned int length) { phys_addr_t sg_address; unsigned int sg_length; int num = 0; while (length) { struct page *pg = vmalloc_to_page(data); phys_addr_t pg_address = page_to_phys(pg); size_t pg_length; pg_length = PAGE_SIZE - offset_in_page(data); if (pg_length > length) pg_length = length; if (!num || sg_address + sg_length != pg_address) { sg_address = pg_address; sg_length = pg_length; num++; } else { sg_length += pg_length; } data += pg_length; length -= pg_length; } return num; } /** * virtsnd_pcm_sg_from() - Build sg-list from vmalloc'ed buffer. * @sgs: Preallocated sg-list to populate. * @nsgs: The maximum number of elements in the @sgs. * @data: Pointer to vmalloc'ed buffer. * @length: Buffer size. * * Splits the buffer into physically contiguous parts and makes an sg-list of * such parts. * * Context: Any context. */ static void virtsnd_pcm_sg_from(struct scatterlist *sgs, int nsgs, u8 *data, unsigned int length) { int idx = -1; while (length) { struct page *pg = vmalloc_to_page(data); size_t pg_length; pg_length = PAGE_SIZE - offset_in_page(data); if (pg_length > length) pg_length = length; if (idx == -1 || sg_phys(&sgs[idx]) + sgs[idx].length != page_to_phys(pg)) { if (idx + 1 == nsgs) break; sg_set_page(&sgs[++idx], pg, pg_length, offset_in_page(data)); } else { sgs[idx].length += pg_length; } data += pg_length; length -= pg_length; } sg_mark_end(&sgs[idx]); } /** * virtsnd_pcm_msg_alloc() - Allocate I/O messages. * @vss: VirtIO PCM substream. * @periods: Current number of periods. * @period_bytes: Current period size in bytes. * * The function slices the buffer into @periods parts (each with the size of * @period_bytes), and creates @periods corresponding I/O messages. * * Context: Any context that permits to sleep. * Return: 0 on success, -ENOMEM on failure. */ int virtsnd_pcm_msg_alloc(struct virtio_pcm_substream *vss, unsigned int periods, unsigned int period_bytes) { struct snd_pcm_runtime *runtime = vss->substream->runtime; unsigned int i; vss->msgs = kcalloc(periods, sizeof(*vss->msgs), GFP_KERNEL); if (!vss->msgs) return -ENOMEM; vss->nmsgs = periods; for (i = 0; i < periods; ++i) { u8 *data = runtime->dma_area + period_bytes * i; int sg_num = virtsnd_pcm_sg_num(data, period_bytes); struct virtio_pcm_msg *msg; msg = kzalloc(struct_size(msg, sgs, sg_num + 2), GFP_KERNEL); if (!msg) return -ENOMEM; msg->substream = vss; sg_init_one(&msg->sgs[PCM_MSG_SG_XFER], &msg->xfer, sizeof(msg->xfer)); sg_init_one(&msg->sgs[PCM_MSG_SG_STATUS], &msg->status, sizeof(msg->status)); msg->length = period_bytes; virtsnd_pcm_sg_from(&msg->sgs[PCM_MSG_SG_DATA], sg_num, data, period_bytes); vss->msgs[i] = msg; } return 0; } /** * virtsnd_pcm_msg_free() - Free all allocated I/O messages. * @vss: VirtIO PCM substream. * * Context: Any context. */ void virtsnd_pcm_msg_free(struct virtio_pcm_substream *vss) { unsigned int i; for (i = 0; vss->msgs && i < vss->nmsgs; ++i) kfree(vss->msgs[i]); kfree(vss->msgs); vss->msgs = NULL; vss->nmsgs = 0; } /** * virtsnd_pcm_msg_send() - Send asynchronous I/O messages. * @vss: VirtIO PCM substream. * * All messages are organized in an ordered circular list. Each time the * function is called, all currently non-enqueued messages are added to the * virtqueue. For this, the function keeps track of two values: * * msg_last_enqueued = index of the last enqueued message, * msg_count = # of pending messages in the virtqueue. * * Context: Any context. Expects the tx/rx queue and the VirtIO substream * spinlocks to be held by caller. * Return: 0 on success, -errno on failure. */ int virtsnd_pcm_msg_send(struct virtio_pcm_substream *vss) { struct snd_pcm_runtime *runtime = vss->substream->runtime; struct virtio_snd *snd = vss->snd; struct virtio_device *vdev = snd->vdev; struct virtqueue *vqueue = virtsnd_pcm_queue(vss)->vqueue; int i; int n; bool notify = false; i = (vss->msg_last_enqueued + 1) % runtime->periods; n = runtime->periods - vss->msg_count; for (; n; --n, i = (i + 1) % runtime->periods) { struct virtio_pcm_msg *msg = vss->msgs[i]; struct scatterlist *psgs[] = { &msg->sgs[PCM_MSG_SG_XFER], &msg->sgs[PCM_MSG_SG_DATA], &msg->sgs[PCM_MSG_SG_STATUS] }; int rc; msg->xfer.stream_id = cpu_to_le32(vss->sid); memset(&msg->status, 0, sizeof(msg->status)); if (vss->direction == SNDRV_PCM_STREAM_PLAYBACK) rc = virtqueue_add_sgs(vqueue, psgs, 2, 1, msg, GFP_ATOMIC); else rc = virtqueue_add_sgs(vqueue, psgs, 1, 2, msg, GFP_ATOMIC); if (rc) { dev_err(&vdev->dev, "SID %u: failed to send I/O message\n", vss->sid); return rc; } vss->msg_last_enqueued = i; vss->msg_count++; } if (!(vss->features & (1U << VIRTIO_SND_PCM_F_MSG_POLLING))) notify = virtqueue_kick_prepare(vqueue); if (notify) virtqueue_notify(vqueue); return 0; } /** * virtsnd_pcm_msg_pending_num() - Returns the number of pending I/O messages. * @vss: VirtIO substream. * * Context: Any context. * Return: Number of messages. */ unsigned int virtsnd_pcm_msg_pending_num(struct virtio_pcm_substream *vss) { unsigned int num; unsigned long flags; spin_lock_irqsave(&vss->lock, flags); num = vss->msg_count; spin_unlock_irqrestore(&vss->lock, flags); return num; } /** * virtsnd_pcm_msg_complete() - Complete an I/O message. * @msg: I/O message. * @written_bytes: Number of bytes written to the message. * * Completion of the message means the elapsed period. If transmission is * allowed, then each completed message is immediately placed back at the end * of the queue. * * For the playback substream, @written_bytes is equal to sizeof(msg->status). * * For the capture substream, @written_bytes is equal to sizeof(msg->status) * plus the number of captured bytes. * * Context: Interrupt context. Takes and releases the VirtIO substream spinlock. */ static void virtsnd_pcm_msg_complete(struct virtio_pcm_msg *msg, size_t written_bytes) { struct virtio_pcm_substream *vss = msg->substream; /* * hw_ptr always indicates the buffer position of the first I/O message * in the virtqueue. Therefore, on each completion of an I/O message, * the hw_ptr value is unconditionally advanced. */ spin_lock(&vss->lock); /* * If the capture substream returned an incorrect status, then just * increase the hw_ptr by the message size. */ if (vss->direction == SNDRV_PCM_STREAM_PLAYBACK || written_bytes <= sizeof(msg->status)) vss->hw_ptr += msg->length; else vss->hw_ptr += written_bytes - sizeof(msg->status); if (vss->hw_ptr >= vss->buffer_bytes) vss->hw_ptr -= vss->buffer_bytes; vss->xfer_xrun = false; vss->msg_count--; if (vss->xfer_enabled) { struct snd_pcm_runtime *runtime = vss->substream->runtime; runtime->delay = bytes_to_frames(runtime, le32_to_cpu(msg->status.latency_bytes)); schedule_work(&vss->elapsed_period); virtsnd_pcm_msg_send(vss); } else if (!vss->msg_count) { wake_up_all(&vss->msg_empty); } spin_unlock(&vss->lock); } /** * virtsnd_pcm_notify_cb() - Process all completed I/O messages. * @queue: Underlying tx/rx virtqueue. * * Context: Interrupt context. Takes and releases the tx/rx queue spinlock. */ static inline void virtsnd_pcm_notify_cb(struct virtio_snd_queue *queue) { struct virtio_pcm_msg *msg; u32 written_bytes; unsigned long flags; spin_lock_irqsave(&queue->lock, flags); do { virtqueue_disable_cb(queue->vqueue); while ((msg = virtqueue_get_buf(queue->vqueue, &written_bytes))) virtsnd_pcm_msg_complete(msg, written_bytes); if (unlikely(virtqueue_is_broken(queue->vqueue))) break; } while (!virtqueue_enable_cb(queue->vqueue)); spin_unlock_irqrestore(&queue->lock, flags); } /** * virtsnd_pcm_tx_notify_cb() - Process all completed TX messages. * @vqueue: Underlying tx virtqueue. * * Context: Interrupt context. */ void virtsnd_pcm_tx_notify_cb(struct virtqueue *vqueue) { struct virtio_snd *snd = vqueue->vdev->priv; virtsnd_pcm_notify_cb(virtsnd_tx_queue(snd)); } /** * virtsnd_pcm_rx_notify_cb() - Process all completed RX messages. * @vqueue: Underlying rx virtqueue. * * Context: Interrupt context. */ void virtsnd_pcm_rx_notify_cb(struct virtqueue *vqueue) { struct virtio_snd *snd = vqueue->vdev->priv; virtsnd_pcm_notify_cb(virtsnd_rx_queue(snd)); } /** * virtsnd_pcm_ctl_msg_alloc() - Allocate and initialize the PCM device control * message for the specified substream. * @vss: VirtIO PCM substream. * @command: Control request code (VIRTIO_SND_R_PCM_XXX). * @gfp: Kernel flags for memory allocation. * * Context: Any context. May sleep if @gfp flags permit. * Return: Allocated message on success, NULL on failure. */ struct virtio_snd_msg * virtsnd_pcm_ctl_msg_alloc(struct virtio_pcm_substream *vss, unsigned int command, gfp_t gfp) { size_t request_size = sizeof(struct virtio_snd_pcm_hdr); size_t response_size = sizeof(struct virtio_snd_hdr); struct virtio_snd_msg *msg; switch (command) { case VIRTIO_SND_R_PCM_SET_PARAMS: request_size = sizeof(struct virtio_snd_pcm_set_params); break; } msg = virtsnd_ctl_msg_alloc(request_size, response_size, gfp); if (msg) { struct virtio_snd_pcm_hdr *hdr = virtsnd_ctl_msg_request(msg); hdr->hdr.code = cpu_to_le32(command); hdr->stream_id = cpu_to_le32(vss->sid); } return msg; }
Carolbauer/ULBRA
2022-1/ALGORITMOS/TDE_07:04/10/main.c
<gh_stars>0 #include <stdio.h> #include <stdlib.h> int main(){ int dia1, dia2, mes1, mes2, ano1, ano2, totaldata1, totaldata2; printf ("Digite um dia , um mês e um ano da sua escolha:\n"); scanf ("%d%*c", &dia1); scanf ("%d%*c", &mes1); scanf ("%d%*c", &ano1); printf ("Digite mais um dia, um mês e um ano da sua escolha:\n"); scanf ("%d%*c", &dia2); scanf ("%d%*c", &mes2); scanf ("%d%*c", &ano2); totaldata1 = dia1 + mes1 +ano1; totaldata2 = dia2 + mes2 +ano2; if (totaldata1 > totaldata2) { printf ("A maior data digitada foi %d/%d/%d", dia1, mes1,ano1); } else{ printf("A maior data digitada foi %d/%d/%d", dia2, mes2, ano2); } return 0; }
ScalablyTyped/SlinkyTyped
g/gsap/src/main/scala/typingsSlinky/gsap/mod/Animation.scala
<gh_stars>10-100 package typingsSlinky.gsap.mod import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @JSImport("gsap", "Animation") @js.native /** * Base class for all TweenLite, TweenMax, TimelineLite, and TimelineMax classes, providing core methods/properties/() => voidality, but there is no reason to create an instance of this * class directly. */ class Animation () extends typingsSlinky.gsap.gsap.Animation { def this(duration: Double) = this() def this(duration: js.UndefOr[scala.Nothing], vars: js.Any) = this() def this(duration: Double, vars: js.Any) = this() }
cesarkawakami/chaintool
core/certchain.go
<gh_stars>0 package core import ( "crypto/tls" "crypto/x509" "fmt" "net" "strings" "time" "github.com/aws/aws-sdk-go/service/iam" ) type CertificateChain struct { Leaf *Certificate Intermediates []*Certificate } func FetchCertificateChain(host, port string) (*CertificateChain, error) { tlsClientConfig := &tls.Config{ RootCAs: MustCertPool(), InsecureSkipVerify: true, } conn, err := tls.Dial("tcp", net.JoinHostPort(host, port), tlsClientConfig) if err != nil { return nil, fmt.Errorf("Unable to establish connection to server: %s", err) } connState := conn.ConnectionState() rv := &CertificateChain{} isFirst := true for _, cert := range connState.PeerCertificates { if isFirst { isFirst = false rv.Leaf = &Certificate{ Certificate: cert, } } else { rv.Intermediates = append(rv.Intermediates, &Certificate{ Certificate: cert, }) } } return rv, nil } func ChainFromAWS(awsCertificate *iam.ServerCertificate) (*CertificateChain, error) { rv := &CertificateChain{} if awsCertificate.CertificateBody == nil { return nil, fmt.Errorf("AWS Certificate doesn't have a body.") } leafX509, err := parseCertificate([]byte(*awsCertificate.CertificateBody)) if err != nil { return nil, fmt.Errorf("Unable to parse certificate body: %s", err) } rv.Leaf = &Certificate{ Certificate: leafX509, } if awsCertificate.CertificateChain != nil { intermediatesX509, err := parseCertificates([]byte(*awsCertificate.CertificateChain)) if err != nil { return nil, fmt.Errorf("Unable to parse intermediate certificates: %s", err) } for _, cert := range intermediatesX509 { rv.Intermediates = append(rv.Intermediates, &Certificate{ Certificate: cert, }) } } return rv, nil } func ChainFromCertificateAndIntermediatesData( leaf *Certificate, intermediatesData []byte, ) (*CertificateChain, error) { rv := &CertificateChain{ Leaf: leaf, } intermediatesX509, err := parseCertificates(intermediatesData) intermediatesPool := x509.NewCertPool() if err != nil { return nil, fmt.Errorf("Unable to parse intermediate certificates: %s", err) } for _, cert := range intermediatesX509 { intermediatesPool.AddCert(cert) } verifiedChains, err := leaf.Certificate.Verify(x509.VerifyOptions{ Roots: MustCertPool(), CurrentTime: time.Now(), Intermediates: intermediatesPool, }) switch err := err.(type) { case nil: break case x509.UnknownAuthorityError: return nil, UnknownAuthorityError{} default: return nil, fmt.Errorf("Unable to verify certificate chain: %s", err) } isLeaf := true for _, x509Cert := range verifiedChains[0] { if isLeaf { isLeaf = false continue } cert := &Certificate{ Certificate: x509Cert, } if cert.IsBundled() { break } rv.Intermediates = append(rv.Intermediates, cert) } return rv, nil } func ChainFromCertificateAndInternet(leaf *Certificate) (*CertificateChain, error) { rv := &CertificateChain{ Leaf: leaf, } isLeafCert := true currentCert := leaf var err error for { if currentCert.IsBundled() { break } if !isLeafCert { rv.Intermediates = append(rv.Intermediates, currentCert) } isLeafCert = false if len(currentCert.Certificate.IssuingCertificateURL) == 0 { return nil, fmt.Errorf( "Error fetching intermediates: cert for %s doesn't point to parent", currentCert.ReadableSubject()) } success := false err = fmt.Errorf( "Error fetching intermediates: cert for %s doesn't point to parent", currentCert.ReadableSubject()) for _, url := range currentCert.Certificate.IssuingCertificateURL { currentCert, err = CertificateFromURL(url) if err == nil { success = true break } } if !success { return nil, fmt.Errorf("Unable to fetch next cert in chain: %s", err) } } return rv, nil } func ChainFromFullChainData(chainData []byte) (*CertificateChain, error) { certsX509, err := parseCertificates(chainData) if err != nil { return nil, fmt.Errorf("Unable to parse certificates: %s", err) } if len(certsX509) <= 0 { return nil, fmt.Errorf("Found no certificates in the given file.") } rv := &CertificateChain{} rv.Leaf = &Certificate{ Certificate: certsX509[0], } for _, cert := range certsX509[1:] { rv.Intermediates = append(rv.Intermediates, &Certificate{ Certificate: cert, }) } return rv, nil } func (c *CertificateChain) InfoLines(wrapLength int) *Lines { lines := NewLines() if c.Leaf != nil { lines.Print("Leaf Certificate:") lines.AppendLines(c.Leaf.InfoLines(wrapLength - 2).IndentedBy(" ")) } else { lines.Print("No Leaf Certificate Present") } for index, cert := range c.Intermediates { lines.Print("Intermediate #%d:", index+1) lines.AppendLines(cert.InfoLines(wrapLength - 2).IndentedBy(" ")) } return lines } func (c *CertificateChain) Verify(dnsName string) error { verifyOptions := x509.VerifyOptions{ Roots: MustCertPool(), CurrentTime: time.Now(), Intermediates: x509.NewCertPool(), } if dnsName != "" { verifyOptions.DNSName = dnsName } for _, cert := range c.Intermediates { verifyOptions.Intermediates.AddCert(cert.Certificate) } _, err := c.Leaf.Certificate.Verify(verifyOptions) switch err := err.(type) { case nil: return nil case x509.HostnameError: return HostnameMismatchError{ Certificate: c.Leaf, Hostname: dnsName, } case x509.UnknownAuthorityError: return UnknownAuthorityError{} default: return err } } type HostnameMismatchError struct { Certificate *Certificate Hostname string } func (e HostnameMismatchError) Error() string { nameLines := []string{} for _, certName := range e.Certificate.Certificate.DNSNames { nameLines = append(nameLines, " - "+certName) } return formatVerifyError(` The received certificate, which is valid for: %s Doesn't match the target hostname, which is: %s You're probably using the wrong certificate for this use. `, strings.Join(nameLines, "\n"), e.Hostname, ) } type UnknownAuthorityError struct{} func (e UnknownAuthorityError) Error() string { return formatVerifyError(` Unable to verify the certificate chain up to trusted bundled root CA certificate. This can be due to: - Using self-signed certificates - The server-side not serving the intermediate certificates needed to build a trust chain up to a bundled certificate This should probably be corrected if you want your site to work for the majority of users. In the second case, you might not see errors at first, since modern browsers cache intermediate certificates, but you'll see intermittent connection problems, so this should be solved anyway. `) } func formatVerifyError(format string, a ...interface{}) string { return strings.Trim(fmt.Sprintf(format, a...), " \n") }
rajkubp020/helloword
lammps-master/src/USER-PLUMED/fix_plumed.h
/* -*- c++ -*- ---------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories <NAME>, <EMAIL> Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #ifdef FIX_CLASS FixStyle(plumed,FixPlumed) #else #ifndef LMP_FIX_PLUMED_H #define LMP_FIX_PLUMED_H #include "fix.h" // forward declaration namespace PLMD { class Plumed; } namespace LAMMPS_NS { class FixPlumed : public Fix { public: FixPlumed(class LAMMPS *, int, char **); ~FixPlumed(); int setmask(); void init(); void setup(int); void min_setup(int); void post_force(int); void post_force_respa(int, int, int); void min_post_force(int); double compute_scalar(); void reset_dt(); int modify_param(int narg, char **arg); double memory_usage(); private: PLMD::Plumed *p; // pointer to plumed object int nlocal; // number of atoms local to this process int natoms; // total number of atoms int *gatindex; // array of atom indexes local to this process double *masses; // array of masses for local atoms double *charges; // array of charges for local atoms int nlevels_respa; // this is something to enable respa double bias; // output bias potential class Compute *c_pe; // Compute for the energy class Compute *c_press; // Compute for the pressure int plumedNeedsEnergy; // Flag to trigger calculation of the // energy and virial char *id_pe, *id_press; // ID for potential energy and pressure compute }; }; #endif #endif
lperrod/web
autoconfigure/src/main/java/com/cmpl/web/configuration/manager/ui/ManagerMenuConfiguration.java
<filename>autoconfigure/src/main/java/com/cmpl/web/configuration/manager/ui/ManagerMenuConfiguration.java package com.cmpl.web.configuration.manager.ui; import com.cmpl.web.core.common.user.Privilege; import com.cmpl.web.core.menu.BackMenuItem; import com.cmpl.web.core.menu.BackMenuItemBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ManagerMenuConfiguration { @Bean public BackMenuItem groupBackMenuItem(BackMenuItem administration, com.cmpl.web.core.common.user.Privilege groupsReadPrivilege) { return BackMenuItemBuilder.create().href("/manager/groups").label("back.groups.label") .title("back.groups.title") .iconClass("fa fa-building").parent(administration).order(1) .privilege(groupsReadPrivilege.privilege()).build(); } @Bean public BackMenuItem mediasBackMenuItem(BackMenuItem webmastering, Privilege mediaReadPrivilege) { return BackMenuItemBuilder.create().href("/manager/medias").label("back.medias.label") .title("back.medias.title") .order(4).iconClass("fa fa-file-image-o").parent(webmastering) .privilege(mediaReadPrivilege.privilege()) .build(); } @Bean public BackMenuItem newsBackMenuItem(BackMenuItem webmastering, Privilege newsReadPrivilege) { return BackMenuItemBuilder.create().href("/manager/news").label("back.news.label") .title("back.news.title").order(6) .iconClass("fa fa-newspaper-o").parent(webmastering) .privilege(newsReadPrivilege.privilege()).build(); } @Bean public BackMenuItem pagesBackMenuItem(BackMenuItem webmastering, Privilege pagesReadPrivilege) { return BackMenuItemBuilder.create().href("/manager/pages").label("back.pages.label") .title("back.pages.title") .order(1).iconClass("fa fa-code").parent(webmastering) .privilege(pagesReadPrivilege.privilege()).build(); } @Bean public BackMenuItem roleBackMenuItem(BackMenuItem administration, com.cmpl.web.core.common.user.Privilege rolesReadPrivilege) { return BackMenuItemBuilder.create().href("/manager/roles").label("back.roles.label") .title("back.roles.title") .iconClass("fa fa-tasks").parent(administration).order(1) .privilege(rolesReadPrivilege.privilege()).build(); } @Bean public BackMenuItem styleBackMenuItem(BackMenuItem webmastering, Privilege styleReadPrivilege) { return BackMenuItemBuilder.create().href("/manager/styles").label("back.style.label") .title("back.style.title") .order(5).iconClass("fa fa-css3").parent(webmastering) .privilege(styleReadPrivilege.privilege()).build(); } @Bean public BackMenuItem userBackMenuItem(BackMenuItem administration, Privilege usersReadPrivilege) { return BackMenuItemBuilder.create().href("/manager/users").label("back.users.label") .title("back.users.title") .iconClass("fa fa-user").parent(administration).privilege(usersReadPrivilege.privilege()) .order(0).build(); } @Bean public BackMenuItem indexBackMenuItem(Privilege indexReadPrivilege) { return BackMenuItemBuilder.create().href("/manager/").label("back.index.label") .title("back.index.title") .iconClass("fa fa-home").order(0).privilege(indexReadPrivilege.privilege()).build(); } @Bean public BackMenuItem administration(Privilege administrationReadPrivilege) { return BackMenuItemBuilder.create().href("#").label("back.administration.label") .title("back.administration.title") .iconClass("fa fa-id-badge").order(1).privilege(administrationReadPrivilege.privilege()) .build(); } @Bean public BackMenuItem webmastering(Privilege webmasteringReadPrivilege) { return BackMenuItemBuilder.create().href("#").label("back.webmastering.label") .title("back.webmastering.title") .iconClass("fa fa-sitemap").order(2).privilege(webmasteringReadPrivilege.privilege()) .build(); } @Bean public BackMenuItem websitesBackMenuItem(BackMenuItem webmastering, Privilege websitesReadPrivilege) { return BackMenuItemBuilder.create().href("/manager/websites").label("back.websites.label") .title("back.websites.title").order(6).iconClass("fa fa-sitemap").parent(webmastering) .privilege(websitesReadPrivilege.privilege()).build(); } }
oilegor1029/sri-front
src/mutations/ODF/UpdateODFMutation.js
<gh_stars>1-10 import { commitMutation } from 'react-relay'; // import { ConnectionHandler } from "relay-runtime"; import graphql from 'babel-plugin-relay/macro'; import i18n from '../../i18n'; import environment from '../../createRelayEnvironment'; import { generatePortForInput } from '../MutationsUtils'; const mutation = graphql` mutation UpdateODFMutation($input: CompositeODFMutationInput!) { composite_oDF(input: $input) { updated { errors { field messages } oDF { id name description operational_state { name value } rack_units rack_position rack_back location { id name } max_number_of_ports ports { id name __typename relation_id type: port_type { name } } } } } } `; export default function UpdateODFMutation(ODF, form) { const ports = generatePortForInput(ODF.ports); const variables = { input: { update_input: { id: ODF.id, name: ODF.name, description: ODF.description, operational_state: ODF.operational_state, max_number_of_ports: ODF.max_number_of_ports, rack_units: ODF.rack_units, rack_position: ODF.rack_position, rack_back: ODF.rack_back, relationship_location: ODF.location && ODF.location.length ? ODF.location[0].id : null, }, update_has_port: ports.toSaved, unlink_subinputs: ports.toUnlink, deleted_has_port: ports.toRemove, create_has_port: ports.toCreate, }, }; commitMutation(environment, { mutation, variables, onCompleted: (response, errors) => { if (response.composite_oDF.updated.errors) { form.props.notify(i18n.t('notify/generic-error'), 'error'); return response.update_ODF.updated.errors; } form.props.reset(); if (form.props.isFromModal) { form.props.editedEntity('ODF', response.composite_oDF.updated.oDF.id); } else { form.refetch(); form.props.notify(i18n.t('notify/changes-saved'), 'success'); } }, updater: (store) => {}, onError: (err) => console.error(err), }); }
frc3117/FRC_Java_Tools
src/main/java/frc/robot/Library/FRC_3117/Component/Data/TangentCurveKey.java
package frc.robot.Library.FRC_3117.Component.Data; public class TangentCurveKey { public TangentCurveKey(double x, double y, double inTangent, double outTangent) { X = x; Y = y; InTangent = inTangent; OutTangent = outTangent; } public double X; public double Y; public double InTangent; public double OutTangent; }
heron-brito/powerauth-mobile-sdk
proj-android/PowerAuthLibrary/src/androidTest/java/io/getlime/security/powerauth/integration/support/endpoints/GetApplicationListEndpoint.java
package io.getlime.security.powerauth.integration.support.endpoints; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.gson.reflect.TypeToken; import java.util.List; import io.getlime.security.powerauth.integration.support.model.Application; public class GetApplicationListEndpoint implements IServerApiEndpoint<GetApplicationListEndpoint.Response> { @NonNull @Override public String getRelativePath() { return "/rest/v3/application/list"; } @Nullable @Override public TypeToken<Response> getResponseType() { return TypeToken.get(Response.class); } // Empty request // Response public static class Response { private List<Application> applications; public List<Application> getApplications() { return applications; } public void setApplications(List<Application> applications) { this.applications = applications; } } }
crowdin/crowdin-java-sdk-2
src/main/java/com/crowdin/client/teams/model/Team.java
<reponame>crowdin/crowdin-java-sdk-2 package com.crowdin.client.teams.model; import lombok.Data; import java.util.Date; @Data public class Team { private Long id; private String name; private Integer totalMembers; private Date createdAt; private Date updatedAt; }
fvutils/libvsc
src/IAccept.h
/* * IAccept.h * * Created on: Aug 2, 2020 * Author: ballance */ #pragma once #include "IVisitor.h" namespace vsc { class IAccept { public: virtual ~IAccept() { } virtual void accept(IVisitor *v) = 0; }; }
UltraCart/rest_api_v2_sdk_java
src/main/java/com/ultracart/admin/v2/models/PaymentsConfigurationCOD.java
<gh_stars>0 /* * UltraCart Rest API V2 * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: <EMAIL> * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.ultracart.admin.v2.models; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.ultracart.admin.v2.models.PaymentsConfigurationRestrictions; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.math.BigDecimal; /** * PaymentsConfigurationCOD */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2021-12-29T11:15:51.350-05:00") public class PaymentsConfigurationCOD { @SerializedName("accept_cod") private Boolean acceptCod = null; @SerializedName("approved_customers_only") private Boolean approvedCustomersOnly = null; @SerializedName("restrictions") private PaymentsConfigurationRestrictions restrictions = null; @SerializedName("surcharge_accounting_code") private String surchargeAccountingCode = null; @SerializedName("surcharge_fee") private BigDecimal surchargeFee = null; @SerializedName("surcharge_percentage") private BigDecimal surchargePercentage = null; public PaymentsConfigurationCOD acceptCod(Boolean acceptCod) { this.acceptCod = acceptCod; return this; } /** * Master flag indicating this merchant accepts COD * @return acceptCod **/ @ApiModelProperty(value = "Master flag indicating this merchant accepts COD") public Boolean isAcceptCod() { return acceptCod; } public void setAcceptCod(Boolean acceptCod) { this.acceptCod = acceptCod; } public PaymentsConfigurationCOD approvedCustomersOnly(Boolean approvedCustomersOnly) { this.approvedCustomersOnly = approvedCustomersOnly; return this; } /** * If true, only approved customers may pay with COD * @return approvedCustomersOnly **/ @ApiModelProperty(value = "If true, only approved customers may pay with COD") public Boolean isApprovedCustomersOnly() { return approvedCustomersOnly; } public void setApprovedCustomersOnly(Boolean approvedCustomersOnly) { this.approvedCustomersOnly = approvedCustomersOnly; } public PaymentsConfigurationCOD restrictions(PaymentsConfigurationRestrictions restrictions) { this.restrictions = restrictions; return this; } /** * Get restrictions * @return restrictions **/ @ApiModelProperty(value = "") public PaymentsConfigurationRestrictions getRestrictions() { return restrictions; } public void setRestrictions(PaymentsConfigurationRestrictions restrictions) { this.restrictions = restrictions; } public PaymentsConfigurationCOD surchargeAccountingCode(String surchargeAccountingCode) { this.surchargeAccountingCode = surchargeAccountingCode; return this; } /** * Optional field, if surcharge is set, this is the accounting code the surcharge is tagged with when sent to Quickbooks * @return surchargeAccountingCode **/ @ApiModelProperty(value = "Optional field, if surcharge is set, this is the accounting code the surcharge is tagged with when sent to Quickbooks") public String getSurchargeAccountingCode() { return surchargeAccountingCode; } public void setSurchargeAccountingCode(String surchargeAccountingCode) { this.surchargeAccountingCode = surchargeAccountingCode; } public PaymentsConfigurationCOD surchargeFee(BigDecimal surchargeFee) { this.surchargeFee = surchargeFee; return this; } /** * Additional cost for using COD * @return surchargeFee **/ @ApiModelProperty(value = "Additional cost for using COD") public BigDecimal getSurchargeFee() { return surchargeFee; } public void setSurchargeFee(BigDecimal surchargeFee) { this.surchargeFee = surchargeFee; } public PaymentsConfigurationCOD surchargePercentage(BigDecimal surchargePercentage) { this.surchargePercentage = surchargePercentage; return this; } /** * Additional percentage cost for using COD * @return surchargePercentage **/ @ApiModelProperty(value = "Additional percentage cost for using COD") public BigDecimal getSurchargePercentage() { return surchargePercentage; } public void setSurchargePercentage(BigDecimal surchargePercentage) { this.surchargePercentage = surchargePercentage; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PaymentsConfigurationCOD paymentsConfigurationCOD = (PaymentsConfigurationCOD) o; return Objects.equals(this.acceptCod, paymentsConfigurationCOD.acceptCod) && Objects.equals(this.approvedCustomersOnly, paymentsConfigurationCOD.approvedCustomersOnly) && Objects.equals(this.restrictions, paymentsConfigurationCOD.restrictions) && Objects.equals(this.surchargeAccountingCode, paymentsConfigurationCOD.surchargeAccountingCode) && Objects.equals(this.surchargeFee, paymentsConfigurationCOD.surchargeFee) && Objects.equals(this.surchargePercentage, paymentsConfigurationCOD.surchargePercentage); } @Override public int hashCode() { return Objects.hash(acceptCod, approvedCustomersOnly, restrictions, surchargeAccountingCode, surchargeFee, surchargePercentage); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PaymentsConfigurationCOD {\n"); sb.append(" acceptCod: ").append(toIndentedString(acceptCod)).append("\n"); sb.append(" approvedCustomersOnly: ").append(toIndentedString(approvedCustomersOnly)).append("\n"); sb.append(" restrictions: ").append(toIndentedString(restrictions)).append("\n"); sb.append(" surchargeAccountingCode: ").append(toIndentedString(surchargeAccountingCode)).append("\n"); sb.append(" surchargeFee: ").append(toIndentedString(surchargeFee)).append("\n"); sb.append(" surchargePercentage: ").append(toIndentedString(surchargePercentage)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
Crown-Commercial-Service/crown-marketplace
db/migrate/20210715113725_confirm_drop_facilities_management_regions.rb
class ConfirmDropFacilitiesManagementRegions < ActiveRecord::Migration[6.0] def up drop_table :facilities_management_regions if ActiveRecord::Base.connection.table_exists? 'facilities_management_regions' end def down; end end
tgodzik/intellij-community
python/testData/addImport/relativeImportFromAlreadyImportedModule/foo/bar.py
def oh(): pass def no(): pass
HelloMelanieC/FiveUp
functional_tests/test_logout_page.py
from fuauth.models import User from .utils import SeleniumTestCase class LogoutTest(SeleniumTestCase): def setUp(self): User.objects.create_user( "Melanie", "6192222222", User.ATT, User.HAWAII, email="<EMAIL>", password="<PASSWORD>", ) def test_successful_logout(self): # first login with self.wait_for_page_load(): self.browser.get(self.live_server_url + "/login/") self.browser.find_element_by_name("username").send_keys("<EMAIL>") self.browser.find_element_by_name("password").send_keys("<PASSWORD>") with self.wait_for_page_load(): self.browser.find_element_by_css_selector("*[type=submit]").click() # then logout with self.wait_for_page_load(): self.browser.find_element_by_xpath('//a[@href="/logoutuser/"]').click() text = self.browser.find_element_by_tag_name("body").text assert "Goodbye, you" in text assert " day!" in text with self.wait_for_page_load(): self.browser.get(self.live_server_url + "/login/") text = self.browser.find_element_by_tag_name("body").text assert ( "Copy/paste to share your link with your internet friendsies." not in text ) assert "Log your little gourd in." in text
cburroughs/collins
app/collins/graphs/GraphView.scala
package collins.graphs import models.asset.AssetView import play.api.Application import play.api.mvc.Content trait GraphView { val app: Application def get(asset: AssetView): Option[Content] def validateConfig() { } }
dorkowscy/lyslix
lifx/light_test.go
package lifx_test import ( "bytes" "testing" "github.com/dorkowscy/lyslix/lifx" "github.com/stretchr/testify/assert" ) var setColorMessagePayload = []byte{ '\x00', '\x55', '\x55', '\xFF', '\xFF', '\xFF', '\xFF', '\xAC', '\x0D', '\x00', '\x04', '\x00', '\x00', } // Test that a SetColor message payload is correctly decoded into a SetColorMessage struct. func TestLightMessageDecoding(t *testing.T) { a := assert.New(t) r := bytes.NewReader(setColorMessagePayload) msg, err := lifx.DecodeSetColorMessage(r) a.Nil(err) a.Equal(uint8(0), msg.Reserved) a.Equal(uint16(21845), msg.Color.Hue) a.Equal(uint16(65535), msg.Color.Saturation) a.Equal(uint16(65535), msg.Color.Brightness) a.Equal(uint16(3500), msg.Color.Kelvin) }
twer4774/TIL
Crawling/3_Library/BeautifulSoupSite.py
<gh_stars>1-10 #-*-encoding:UTF-8-*- from bs4 import BeautifulSoup #HTML 파일을 읽어 들이고 BeautifulSop 객체 생성 with open('full_book_list.html') as f: soup = BeautifulSoup(f, 'html.parser') #find_all()메서드로 a요소 우출후 반복문 실행 for a in soup.find_all('a'): #href 속성과 글자 추출 print(a.get('href'), a.text)
SleepyRae/IntelligenceCoding
hoj-springboot/DataBackup/src/main/java/top/hcode/hoj/manager/oj/PassportManager.java
<reponame>SleepyRae/IntelligenceCoding package top.hcode.hoj.manager.oj; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.lang.Validator; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.RandomUtil; import cn.hutool.crypto.SecureUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import top.hcode.hoj.common.exception.StatusAccessDeniedException; import top.hcode.hoj.common.exception.StatusFailException; import top.hcode.hoj.common.exception.StatusForbiddenException; import top.hcode.hoj.manager.email.EmailManager; import top.hcode.hoj.manager.msg.NoticeManager; import top.hcode.hoj.pojo.bo.EmailRuleBo; import top.hcode.hoj.pojo.dto.LoginDto; import top.hcode.hoj.pojo.dto.RegisterDto; import top.hcode.hoj.pojo.dto.ApplyResetPasswordDto; import top.hcode.hoj.pojo.dto.ResetPasswordDto; import top.hcode.hoj.pojo.entity.user.*; import top.hcode.hoj.pojo.vo.ConfigVo; import top.hcode.hoj.pojo.vo.RegisterCodeVo; import top.hcode.hoj.pojo.vo.UserInfoVo; import top.hcode.hoj.pojo.vo.UserRolesVo; import top.hcode.hoj.dao.user.SessionEntityService; import top.hcode.hoj.dao.user.UserInfoEntityService; import top.hcode.hoj.dao.user.UserRecordEntityService; import top.hcode.hoj.dao.user.UserRoleEntityService; import top.hcode.hoj.utils.Constants; import top.hcode.hoj.utils.IpUtils; import top.hcode.hoj.utils.JwtUtils; import top.hcode.hoj.utils.RedisUtils; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.stream.Collectors; /** * @Author: Himit_ZH * @Date: 2022/3/11 16:46 * @Description: */ @Component public class PassportManager { @Resource private RedisUtils redisUtils; @Resource private JwtUtils jwtUtils; @Resource private ConfigVo configVo; @Resource private EmailRuleBo emailRuleBo; @Resource private UserInfoEntityService userInfoEntityService; @Resource private UserRoleEntityService userRoleEntityService; @Resource private UserRecordEntityService userRecordEntityService; @Resource private SessionEntityService sessionEntityService; @Resource private EmailManager emailManager; @Resource private NoticeManager noticeManager; public UserInfoVo login(LoginDto loginDto, HttpServletResponse response, HttpServletRequest request) throws StatusFailException { // 去掉账号密码首尾的空格 loginDto.setPassword(loginDto.getPassword().trim()); loginDto.setUsername(loginDto.getUsername().trim()); if (StringUtils.isEmpty(loginDto.getUsername()) || StringUtils.isEmpty(loginDto.getPassword())) { throw new StatusFailException("用户名或密码不能为空!"); } if (loginDto.getPassword().length() < 6 || loginDto.getPassword().length() > 20) { throw new StatusFailException("密码长度应该为6~20位!"); } if (loginDto.getUsername().length() > 20) { throw new StatusFailException("用户名长度不能超过20位!"); } String userIpAddr = IpUtils.getUserIpAddr(request); String key = Constants.Account.TRY_LOGIN_NUM.getCode() + loginDto.getUsername() + "_" + userIpAddr; Integer tryLoginCount = (Integer) redisUtils.get(key); if (tryLoginCount != null && tryLoginCount >= 20) { throw new StatusFailException("对不起!登录失败次数过多!您的账号有风险,半个小时内暂时无法登录!"); } UserRolesVo userRolesVo = userRoleEntityService.getUserRoles(null, loginDto.getUsername()); if (userRolesVo == null) { throw new StatusFailException("用户名或密码错误!请注意大小写!"); } if (!userRolesVo.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) { if (tryLoginCount == null) { redisUtils.set(key, 1, 60 * 30); // 三十分钟不尝试,该限制会自动清空消失 } else { redisUtils.set(key, tryLoginCount + 1, 60 * 30); } throw new StatusFailException("用户名或密码错误!请注意大小写!"); } if (userRolesVo.getStatus() != 0) { throw new StatusFailException("该账户已被封禁,请联系管理员进行处理!"); } String jwt = jwtUtils.generateToken(userRolesVo.getUid()); response.setHeader("Authorization", jwt); //放到信息头部 response.setHeader("Access-Control-Expose-Headers", "Authorization"); // 会话记录 sessionEntityService.save(new Session() .setUid(userRolesVo.getUid()) .setIp(IpUtils.getUserIpAddr(request)) .setUserAgent(request.getHeader("User-Agent"))); // 登录成功,清除锁定限制 if (tryLoginCount != null) { redisUtils.del(key); } // 异步检查是否异地登录 sessionEntityService.checkRemoteLogin(userRolesVo.getUid()); UserInfoVo userInfoVo = new UserInfoVo(); BeanUtil.copyProperties(userRolesVo, userInfoVo, "roles"); userInfoVo.setRoleList(userRolesVo.getRoles() .stream() .map(Role::getRole) .collect(Collectors.toList())); return userInfoVo; } public RegisterCodeVo getRegisterCode(String email) throws StatusAccessDeniedException, StatusFailException, StatusForbiddenException { if (!configVo.getRegister()) { // 需要判断一下网站是否开启注册 throw new StatusAccessDeniedException("对不起!本站暂未开启注册功能!"); } if (!emailManager.isOk()) { throw new StatusAccessDeniedException("对不起!本站邮箱系统未配置,暂不支持注册!"); } email = email.trim(); boolean isEmail = Validator.isEmail(email); if (!isEmail) { throw new StatusFailException("对不起!您的邮箱格式不正确!"); } boolean isBlackEmail = emailRuleBo.getBlackList().stream().anyMatch(email::endsWith); if (isBlackEmail) { throw new StatusForbiddenException("对不起!您的邮箱无法注册本网站!"); } String lockKey = Constants.Email.REGISTER_EMAIL_LOCK + email; if (redisUtils.hasKey(lockKey)) { throw new StatusFailException("对不起,您的操作频率过快,请在" + redisUtils.getExpire(lockKey) + "秒后再次发送注册邮件!"); } QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("email", email); UserInfo userInfo = userInfoEntityService.getOne(queryWrapper, false); if (userInfo != null) { throw new StatusFailException("对不起!该邮箱已被注册,请更换新的邮箱!"); } String numbers = RandomUtil.randomNumbers(6); // 随机生成6位数字的组合 redisUtils.set(Constants.Email.REGISTER_KEY_PREFIX.getValue() + email, numbers, 5 * 60);//默认验证码有效5分钟 emailManager.sendCode(email, numbers); redisUtils.set(lockKey, 0, 60); RegisterCodeVo registerCodeVo = new RegisterCodeVo(); registerCodeVo.setEmail(email); registerCodeVo.setExpire(5 * 60); return registerCodeVo; } @Transactional(rollbackFor = Exception.class) public void register(RegisterDto registerDto) throws StatusAccessDeniedException, StatusFailException { if (!configVo.getRegister()) { // 需要判断一下网站是否开启注册 throw new StatusAccessDeniedException("对不起!本站暂未开启注册功能!"); } String codeKey = Constants.Email.REGISTER_KEY_PREFIX.getValue() + registerDto.getEmail(); if (!redisUtils.hasKey(codeKey)) { throw new StatusFailException("验证码不存在或已过期"); } if (!redisUtils.get(codeKey).equals(registerDto.getCode())) { //验证码判断 throw new StatusFailException("验证码不正确"); } if (StringUtils.isEmpty(registerDto.getPassword())) { throw new StatusFailException("密码不能为空"); } if (registerDto.getPassword().length() < 6 || registerDto.getPassword().length() > 20) { throw new StatusFailException("密码长度应该为6~20位!"); } if (StringUtils.isEmpty(registerDto.getUsername())) { throw new StatusFailException("用户名不能为空"); } if (registerDto.getUsername().length() > 20) { throw new StatusFailException("用户名长度不能超过20位!"); } String uuid = IdUtil.simpleUUID(); //为新用户设置uuid registerDto.setUuid(uuid); registerDto.setPassword(SecureUtil.md5(registerDto.getPassword().trim())); // 将密码MD5加密写入数据库 registerDto.setUsername(registerDto.getUsername().trim()); registerDto.setEmail(registerDto.getEmail().trim()); //往user_info表插入数据 boolean addUser = userInfoEntityService.addUser(registerDto); //往user_role表插入数据 boolean addUserRole = userRoleEntityService.save(new UserRole().setRoleId(1002L).setUid(uuid)); //往user_record表插入数据 boolean addUserRecord = userRecordEntityService.save(new UserRecord().setUid(uuid)); if (addUser && addUserRole && addUserRecord) { redisUtils.del(registerDto.getEmail()); noticeManager.syncNoticeToNewRegisterUser(uuid); } else { throw new StatusFailException("注册失败,请稍后重新尝试!"); } } public void applyResetPassword(ApplyResetPasswordDto applyResetPasswordDto) throws StatusFailException { String captcha = applyResetPasswordDto.getCaptcha(); String captchaKey = applyResetPasswordDto.getCaptchaKey(); String email = applyResetPasswordDto.getEmail(); if (StringUtils.isEmpty(captcha) || StringUtils.isEmpty(email) || StringUtils.isEmpty(captchaKey)) { throw new StatusFailException("邮箱或验证码不能为空"); } if (!emailManager.isOk()) { throw new StatusFailException("对不起!本站邮箱系统未配置,暂不支持重置密码!"); } String lockKey = Constants.Email.RESET_EMAIL_LOCK + email; if (redisUtils.hasKey(lockKey)) { throw new StatusFailException("对不起,您的操作频率过快,请在" + redisUtils.getExpire(lockKey) + "秒后再次发送重置邮件!"); } // 获取redis中的验证码 String redisCode = (String) redisUtils.get(captchaKey); if (!redisCode.equals(captcha.trim().toLowerCase())) { throw new StatusFailException("验证码不正确"); } QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>(); userInfoQueryWrapper.eq("email", email.trim()); UserInfo userInfo = userInfoEntityService.getOne(userInfoQueryWrapper, false); if (userInfo == null) { throw new StatusFailException("对不起,该邮箱无该用户,请重新检查!"); } String code = IdUtil.simpleUUID().substring(0, 21); // 随机生成20位数字与字母的组合 redisUtils.set(Constants.Email.RESET_PASSWORD_KEY_PREFIX.getValue() + userInfo.getUsername(), code, 10 * 60);//默认链接有效10分钟 // 发送邮件 emailManager.sendResetPassword(userInfo.getUsername(), code, email.trim()); redisUtils.set(lockKey, 0, 90); } public void resetPassword(ResetPasswordDto resetPasswordDto) throws StatusFailException { String username = resetPasswordDto.getUsername(); String password = resetPasswordDto.getPassword(); String code = resetPasswordDto.getCode(); if (StringUtils.isEmpty(password) || StringUtils.isEmpty(username) || StringUtils.isEmpty(code)) { throw new StatusFailException("用户名、新密码或验证码不能为空"); } if (password.length() < 6 || password.length() > 20) { throw new StatusFailException("新密码长度应该为6~20位!"); } String codeKey = Constants.Email.RESET_PASSWORD_KEY_PREFIX.getValue() + username; if (!redisUtils.hasKey(codeKey)) { throw new StatusFailException("重置密码链接不存在或已过期,请重新发送重置邮件"); } if (!redisUtils.get(codeKey).equals(code)) { //验证码判断 throw new StatusFailException("重置密码的验证码不正确,请重新输入"); } UpdateWrapper<UserInfo> userInfoUpdateWrapper = new UpdateWrapper<>(); userInfoUpdateWrapper.eq("username", username).set("password", <PASSWORD>(password)); boolean isOk = userInfoEntityService.update(userInfoUpdateWrapper); if (!isOk) { throw new StatusFailException("重置密码失败"); } redisUtils.del(codeKey); } }
knokko/Fortress-Siege
Client/src/nl/knokko/client/texture/SimpleTexture.java
package nl.knokko.client.texture; class SimpleTexture implements ITexture { private final int textureID; public SimpleTexture(int textureID) { this.textureID = textureID; } @Override public int getTextureID() { return textureID; } @Override public String toString(){ return "SimpleTexture(" + textureID + ")"; } @Override public float getMinU() { return 0f; } @Override public float getMinV() { return 0f; } @Override public float getMaxU() { return 1f; } @Override public float getMaxV() { return 1f; } @Override public int getWidth() { throw new IllegalStateException("A SimpleTexture does not know it's width!"); } @Override public int getHeight() { throw new IllegalStateException("A SimpleTexture does not know it's height!"); } }
galahq/gala
app/models/reply_notification.rb
# frozen_string_literal: true # The record of a reply to a {Reader}’s {Comment}. All the many `belongs_to` # relations are needed for the websocket notification to trigger a Toast with # a ReactRouter link to the reply class ReplyNotification < ApplicationRecord belongs_to :reader belongs_to :notifier, class_name: 'Reader' belongs_to :comment belongs_to :comment_thread belongs_to :case belongs_to :page, optional: true belongs_to :card, optional: true after_create_commit { ReplyNotificationBroadcastJob.perform_later self } after_create_commit { ReplyNotificationMailer.notify(self).deliver_later } def message I18n.t 'notifications.replied_to_your_comment', notifier: notifier.name, case_kicker: self.case.kicker end end
AndreasSM/fluent-jdbc
src/test/java/org/fluentjdbc/hsqldb/HsqldbTests.java
package org.fluentjdbc.hsqldb; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; public final class HsqldbTests { static final Map<String, String> REPLACEMENTS = new HashMap<>(); static { REPLACEMENTS.put("UUID", "uuid"); REPLACEMENTS.put("INTEGER_PK", "integer identity primary key"); REPLACEMENTS.put("DATETIME", "datetime"); REPLACEMENTS.put("BOOLEAN", "boolean"); } public static class DatabaseSaveBuilderTest extends org.fluentjdbc.DatabaseSaveBuilderTest { public DatabaseSaveBuilderTest() throws SQLException { super(getConnection(), REPLACEMENTS); } } public static class RichDomainModelTest extends org.fluentjdbc.RichDomainModelTest { public RichDomainModelTest() throws SQLException { super(getConnection(), REPLACEMENTS); } } public static class FluentJdbcDemonstrationTest extends org.fluentjdbc.FluentJdbcDemonstrationTest { public FluentJdbcDemonstrationTest() throws SQLException { super(getConnection(), REPLACEMENTS); } } public static class DatabaseTableTest extends org.fluentjdbc.DatabaseTableTest { public DatabaseTableTest() throws SQLException { super(getConnection(), REPLACEMENTS); } } public static class BulkInsertTest extends org.fluentjdbc.BulkInsertTest { public BulkInsertTest() throws SQLException { super(getConnection(), REPLACEMENTS); } } static Connection getConnection() throws SQLException { return DriverManager.getConnection("jdbc:hsqldb:mem:test", "sa", null); } }
cockcrow/python-mammoth
mammoth/writers/abc.py
<gh_stars>100-1000 from __future__ import absolute_import import abc class Writer(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def text(self, text): pass @abc.abstractmethod def start(self, name, attributes=None): pass @abc.abstractmethod def end(self, name): pass @abc.abstractmethod def self_closing(self, name, attributes=None): pass @abc.abstractmethod def append(self, html): pass @abc.abstractmethod def as_string(self): pass
MercuriusXeno/Goo
src/main/java/com/xeno/goo/entities/GooBlobShape.java
package com.xeno.goo.entities; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.vector.Vector3d; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class GooBlobShape { public BlobState blobState; public Vector3d pos; public Vector3d shape; public Vector3d motion; public AxisAlignedBB box; public int estAmount; public int ticksAlive; public int ticksOnGround; public int ticksInAir; public UUID uuid; public final List<UUID> parents = new ArrayList<>(); public final List<UUID> children = new ArrayList<>(); public final List<GooBlobBlockProgress> progress = new ArrayList<>(); public GooBlobShape(BlobState state, double x, double y, double z, double dx, double dy, double dz, double mx, double my, double mz, int approximateAmount) { this.blobState = state; this.pos = new Vector3d(x, y, z); this.shape = new Vector3d(dx, dy, dz); this.motion = new Vector3d(mx, my, mz); this.box = new AxisAlignedBB(pos, shape); this.estAmount = approximateAmount; this.uuid = UUID.randomUUID(); } }
joeharrison91/service-manual-publisher
spec/presenters/homepage_presenter_spec.rb
require "rails_helper" RSpec.describe HomepagePresenter, "#content_id" do it "returns a preassigned UUID" do expect( described_class.new.content_id ).to eq("6732c01a-39e2-4cec-8ee9-17eb7fded6a0") end end RSpec.describe HomepagePresenter, "#content_payload" do it "conforms to the schema" do homepage_presenter = described_class.new expect(homepage_presenter.content_payload).to be_valid_against_schema('service_manual_homepage') end it 'includes a title for the service manual' do payload = described_class.new.content_payload expect(payload).to include title: "Service Manual" end it 'includes a description for the service manual' do payload = described_class.new.content_payload expect(payload).to include \ description: 'Helping government teams create and run great digital services that meet the Service Standard.' end it 'includes a base path and exact route for the service manual' do payload = described_class.new.content_payload expect(payload).to include \ base_path: '/service-manual', routes: [ { type: 'exact', path: '/service-manual' } ] end it 'includes the rendering and publishing apps' do payload = described_class.new.content_payload expect(payload).to include \ publishing_app: 'service-manual-publisher', rendering_app: 'service-manual-frontend' end it 'includes the document and schema type' do payload = described_class.new.content_payload expect(payload).to include \ document_type: 'service_manual_homepage', schema_name: 'service_manual_homepage' end end
crro/rio
vendor/github.com/solo-io/solo-kit/pkg/api/v1/resources/core/status.pb.go
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: status.proto package core import ( bytes "bytes" fmt "fmt" math "math" _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" types "github.com/gogo/protobuf/types" _ "github.com/solo-io/protoc-gen-ext/extproto" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package type Status_State int32 const ( // Pending status indicates the resource has not yet been validated Status_Pending Status_State = 0 // Accepted indicates the resource has been validated Status_Accepted Status_State = 1 // Rejected indicates an invalid configuration by the user // Rejected resources may be propagated to the xDS server depending on their severity Status_Rejected Status_State = 2 // Warning indicates a partially invalid configuration by the user // Resources with Warnings may be partially accepted by a controller, depending on the implementation Status_Warning Status_State = 3 ) var Status_State_name = map[int32]string{ 0: "Pending", 1: "Accepted", 2: "Rejected", 3: "Warning", } var Status_State_value = map[string]int32{ "Pending": 0, "Accepted": 1, "Rejected": 2, "Warning": 3, } func (x Status_State) String() string { return proto.EnumName(Status_State_name, int32(x)) } func (Status_State) EnumDescriptor() ([]byte, []int) { return fileDescriptor_dfe4fce6682daf5b, []int{0, 0} } //* // Status indicates whether a resource has been (in)validated by a reporter in the system. // Statuses are meant to be read-only by users type Status struct { // State is the enum indicating the state of the resource State Status_State `protobuf:"varint,1,opt,name=state,proto3,enum=core.solo.io.Status_State" json:"state,omitempty"` // Reason is a description of the error for Rejected resources. If the resource is pending or accepted, this field will be empty Reason string `protobuf:"bytes,2,opt,name=reason,proto3" json:"reason,omitempty"` // Reference to the reporter who wrote this status ReportedBy string `protobuf:"bytes,3,opt,name=reported_by,json=reportedBy,proto3" json:"reported_by,omitempty"` // Reference to statuses (by resource-ref string: "Kind.Namespace.Name") of subresources of the parent resource SubresourceStatuses map[string]*Status `protobuf:"bytes,4,rep,name=subresource_statuses,json=subresourceStatuses,proto3" json:"subresource_statuses,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` // Opaque details about status results Details *types.Struct `protobuf:"bytes,5,opt,name=details,proto3" json:"details,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Status) Reset() { *m = Status{} } func (m *Status) String() string { return proto.CompactTextString(m) } func (*Status) ProtoMessage() {} func (*Status) Descriptor() ([]byte, []int) { return fileDescriptor_dfe4fce6682daf5b, []int{0} } func (m *Status) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Status.Unmarshal(m, b) } func (m *Status) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Status.Marshal(b, m, deterministic) } func (m *Status) XXX_Merge(src proto.Message) { xxx_messageInfo_Status.Merge(m, src) } func (m *Status) XXX_Size() int { return xxx_messageInfo_Status.Size(m) } func (m *Status) XXX_DiscardUnknown() { xxx_messageInfo_Status.DiscardUnknown(m) } var xxx_messageInfo_Status proto.InternalMessageInfo func (m *Status) GetState() Status_State { if m != nil { return m.State } return Status_Pending } func (m *Status) GetReason() string { if m != nil { return m.Reason } return "" } func (m *Status) GetReportedBy() string { if m != nil { return m.ReportedBy } return "" } func (m *Status) GetSubresourceStatuses() map[string]*Status { if m != nil { return m.SubresourceStatuses } return nil } func (m *Status) GetDetails() *types.Struct { if m != nil { return m.Details } return nil } func init() { proto.RegisterEnum("core.solo.io.Status_State", Status_State_name, Status_State_value) proto.RegisterType((*Status)(nil), "core.solo.io.Status") proto.RegisterMapType((map[string]*Status)(nil), "core.solo.io.Status.SubresourceStatusesEntry") } func init() { proto.RegisterFile("status.proto", fileDescriptor_dfe4fce6682daf5b) } var fileDescriptor_dfe4fce6682daf5b = []byte{ // 381 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x90, 0xdf, 0xca, 0xd3, 0x30, 0x18, 0xc6, 0xcd, 0xba, 0x6e, 0x2e, 0x1d, 0x32, 0xe2, 0xd0, 0x52, 0x44, 0xcb, 0x8e, 0x8a, 0xb0, 0xc4, 0x55, 0x04, 0x11, 0x44, 0x1c, 0x78, 0x2e, 0xdd, 0x81, 0x20, 0xc2, 0xec, 0x9f, 0xd7, 0x5a, 0x57, 0x9b, 0x92, 0xa4, 0x63, 0xbd, 0x20, 0xc1, 0x4b, 0xf0, 0x7a, 0xbc, 0x07, 0xcf, 0x25, 0x49, 0x8b, 0xc2, 0xb7, 0xef, 0x28, 0x79, 0xdf, 0xe7, 0x17, 0x9e, 0x3c, 0x0f, 0x5e, 0x4a, 0x95, 0xaa, 0x4e, 0xd2, 0x56, 0x70, 0xc5, 0xc9, 0x32, 0xe7, 0x02, 0xa8, 0xe4, 0x35, 0xa7, 0x15, 0x0f, 0xd6, 0x25, 0x2f, 0xb9, 0x11, 0x98, 0xbe, 0x59, 0x26, 0x20, 0x70, 0x51, 0x76, 0x09, 0x17, 0x35, 0xec, 0x1e, 0x95, 0x9c, 0x97, 0x35, 0x30, 0x33, 0x65, 0xdd, 0x17, 0x26, 0x95, 0xe8, 0xf2, 0x41, 0xdd, 0xfc, 0x70, 0xf0, 0xec, 0x60, 0x6c, 0xc8, 0x33, 0xec, 0x6a, 0x43, 0xf0, 0x51, 0x88, 0xa2, 0x7b, 0x71, 0x40, 0xff, 0x37, 0xa4, 0x16, 0x32, 0x07, 0x24, 0x16, 0x24, 0x0f, 0xf0, 0x4c, 0x40, 0x2a, 0x79, 0xe3, 0x4f, 0x42, 0x14, 0x2d, 0x92, 0x61, 0x22, 0x4f, 0xb0, 0x27, 0xa0, 0xe5, 0x42, 0x41, 0x71, 0xcc, 0x7a, 0xdf, 0x31, 0x22, 0x1e, 0x57, 0xfb, 0x9e, 0x7c, 0xc6, 0x6b, 0xd9, 0x65, 0x02, 0x24, 0xef, 0x44, 0x0e, 0x47, 0x9b, 0x13, 0xa4, 0x3f, 0x0d, 0x9d, 0xc8, 0x8b, 0xb7, 0xd7, 0x9d, 0xff, 0x3d, 0x38, 0x0c, 0xfc, 0xbb, 0x46, 0x89, 0x3e, 0xb9, 0x2f, 0x6f, 0x2a, 0x64, 0x87, 0xe7, 0x05, 0xa8, 0xb4, 0xaa, 0xa5, 0xef, 0x86, 0x28, 0xf2, 0xe2, 0x87, 0xd4, 0xf6, 0x40, 0xc7, 0x1e, 0xe8, 0xc1, 0xf4, 0x90, 0x8c, 0x5c, 0xf0, 0x09, 0xfb, 0xb7, 0x79, 0x90, 0x15, 0x76, 0x4e, 0xd0, 0x9b, 0x66, 0x16, 0x89, 0xbe, 0x92, 0xa7, 0xd8, 0x3d, 0xa7, 0x75, 0x07, 0x26, 0xba, 0x17, 0xaf, 0xaf, 0xfd, 0x39, 0xb1, 0xc8, 0xab, 0xc9, 0x4b, 0xb4, 0x79, 0x8d, 0x5d, 0xd3, 0x1d, 0xf1, 0xf0, 0xfc, 0x3d, 0x34, 0x45, 0xd5, 0x94, 0xab, 0x3b, 0x64, 0x89, 0xef, 0xbe, 0xcd, 0x73, 0x68, 0x15, 0x14, 0x2b, 0xa4, 0xa7, 0x04, 0xbe, 0x41, 0xae, 0xa7, 0x89, 0x06, 0x3f, 0xa4, 0xa2, 0xd1, 0xa0, 0xb3, 0x7f, 0xf3, 0xeb, 0xcf, 0x14, 0xfd, 0xfc, 0xfd, 0x18, 0x7d, 0x7c, 0x51, 0x56, 0xea, 0x6b, 0x97, 0xd1, 0x9c, 0x7f, 0x67, 0xda, 0x6e, 0x5b, 0x71, 0x7b, 0x9e, 0x2a, 0xc5, 0xda, 0x53, 0xc9, 0xd2, 0xb6, 0x62, 0xe7, 0x1d, 0x1b, 0x83, 0x48, 0xa6, 0x7f, 0x96, 0xcd, 0x4c, 0xee, 0xe7, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xa6, 0x34, 0xee, 0xc0, 0x55, 0x02, 0x00, 0x00, } func (this *Status) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*Status) if !ok { that2, ok := that.(Status) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if this.State != that1.State { return false } if this.Reason != that1.Reason { return false } if this.ReportedBy != that1.ReportedBy { return false } if len(this.SubresourceStatuses) != len(that1.SubresourceStatuses) { return false } for i := range this.SubresourceStatuses { if !this.SubresourceStatuses[i].Equal(that1.SubresourceStatuses[i]) { return false } } if !this.Details.Equal(that1.Details) { return false } if !bytes.Equal(this.XXX_unrecognized, that1.XXX_unrecognized) { return false } return true }
riselabs-ufba/RiPLE-HC
dependencies/FeatureIDE-2.6.5/de.ovgu.featureide.fm.ui/src/de/ovgu/featureide/fm/ui/properties/FMPropertyManager.java
<reponame>riselabs-ufba/RiPLE-HC /* FeatureIDE - A Framework for Feature-Oriented Software Development * Copyright (C) 2005-2013 FeatureIDE team, University of Magdeburg, Germany * * This file is part of FeatureIDE. * * FeatureIDE is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FeatureIDE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with FeatureIDE. If not, see <http://www.gnu.org/licenses/>. * * See http://www.fosd.de/featureide/ for further information. */ package de.ovgu.featureide.fm.ui.properties; import java.util.LinkedList; import javax.annotation.CheckReturnValue; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.QualifiedName; import org.eclipse.draw2d.Border; import org.eclipse.draw2d.Graphics; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import de.ovgu.featureide.fm.core.FMCorePlugin; import de.ovgu.featureide.fm.ui.editors.featuremodel.GUIBasics; import de.ovgu.featureide.fm.ui.editors.featuremodel.GUIDefaults; import de.ovgu.featureide.fm.ui.properties.language.English; import de.ovgu.featureide.fm.ui.properties.language.German; import de.ovgu.featureide.fm.ui.properties.language.ILanguage; import de.ovgu.featureide.fm.ui.properties.page.FMPropertyPage; /** * Manages all persistent properties defined at the property page.<br> * These properties are defined for the whole workspace.<br><br> * * Use this methods instead of {@link GUIDefaults}. * * @see FMPropertyPage * @author <NAME> */ @CheckReturnValue public class FMPropertyManager extends FMPropertyManagerDefaults implements GUIDefaults { /* **************************************************** * current values ******************************************************/ private volatile static Boolean CURRENT_HIDE_LEGEND = null; private volatile static Color CURRENT_LEGEND_FORGOUND = null; private volatile static Color CURRENT_LEGEND_BACKGROUND = null; private volatile static Color CURRENT_DECORATOR_FORGROUND_COLOR = null; private volatile static Color CURRENT_FEATURE_FOREGROUND = null; private volatile static Color CURRENT_CONCRETE_BACKGROUND = null; private volatile static Color CURRENT_ABSTRACT_BACKGROUND = null; private volatile static Color CURRENT_CONNECTION_FOREGROUND = null; private volatile static Color CURRENT_DIAGRAM_BACKGROUND = null; private volatile static Color CURRENT_LEGEND_BORDER_COLOR = null; private volatile static Color CURRENT_HIDDEN_FOREGROUND = null; private volatile static Color CURRENT_HIDDEN_BACKGROUND = null; private volatile static Color CURRENT_DEAD_BACKGROUND = null; private volatile static Color CURRENT_FEATURE_DEAD = null; private volatile static Color CURRENT_CONSTRAINT_BACKGROUND = null; private volatile static Color CURRENT_WARNING_BACKGROUND = null; private volatile static Integer CURRENT_CONSTRAINT_SPACE_Y = null; private volatile static Integer CURRENT_FEATURE_SPACE_Y = null; private volatile static Integer CURRENT_FEATURE_SPACE_X = null; private volatile static Integer CURRENT_LAYOUT_MARGIN_Y = null; private volatile static Integer CURRENT_LAYOUT_MARGIN_X = null; public static void setHideLegend(boolean value) { CURRENT_HIDE_LEGEND = value; setBoolean(QN_HIDE_LEGEND, value); } public static boolean isLegendHidden() { if (CURRENT_HIDE_LEGEND == null) { CURRENT_HIDE_LEGEND = getBoolean(QN_HIDE_LEGEND); } return CURRENT_HIDE_LEGEND; } public static void setLegendForgroundColor(Color color) { CURRENT_LEGEND_FORGOUND = color; setColor(QN_LEGEND_FORGOUND, color); } public static Color getLegendForgroundColor() { if (CURRENT_LEGEND_FORGOUND == null) { CURRENT_LEGEND_FORGOUND = getColor(QN_LEGEND_FORGOUND, LEGEND_FOREGROUND); } return CURRENT_LEGEND_FORGOUND; } public static void setLegendBackgroundColor(Color color) { CURRENT_LEGEND_BACKGROUND = color; setColor(QN_LEGEND_BACKGROUND, color); } public static Color getLegendBackgroundColor() { if (CURRENT_LEGEND_BACKGROUND == null) { CURRENT_LEGEND_BACKGROUND = getColor(QN_LEGEND_BACKGROUND, LEGEND_BACKGROUND); } return CURRENT_LEGEND_BACKGROUND; } public static void setLegendBorderColor(Color color) { CURRENT_LEGEND_BORDER_COLOR = color; setColor(QN_LEGEND_BORDER, color); } public static Color getLegendBorderColor() { if (CURRENT_LEGEND_BORDER_COLOR == null) { CURRENT_LEGEND_BORDER_COLOR = getColor(QN_LEGEND_BORDER, LEGEND_BORDER_COLOR); } return CURRENT_LEGEND_BORDER_COLOR; } public static void setFeatureForgroundColor(Color color) { CURRENT_FEATURE_FOREGROUND = color; setColor(QN_FEATURE_FORGROUND, color); } public static Color getFeatureForgroundColor() { if (CURRENT_FEATURE_FOREGROUND == null) { CURRENT_FEATURE_FOREGROUND = getColor(QN_FEATURE_FORGROUND, FEATURE_FOREGROUND); } return CURRENT_FEATURE_FOREGROUND; } public static Color getDiagramBackgroundColor() { if (CURRENT_DIAGRAM_BACKGROUND == null) { CURRENT_DIAGRAM_BACKGROUND = getColor(QN_DIAGRAM_BACKGROUND, DIAGRAM_BACKGROUND); } return CURRENT_DIAGRAM_BACKGROUND; } public static void setDiagramBackgroundColor(Color color) { CURRENT_DIAGRAM_BACKGROUND = color; setColor(QN_DIAGRAM_BACKGROUND, color); } public static void setConcreteFeatureBackgroundColor(Color color) { CURRENT_CONCRETE_BACKGROUND = color; setColor(QN_FEATURE_CONCRETE, color); } public static Color getConcreteFeatureBackgroundColor() { if (CURRENT_CONCRETE_BACKGROUND == null) { CURRENT_CONCRETE_BACKGROUND = getColor(QN_FEATURE_CONCRETE, CONCRETE_BACKGROUND); } return CURRENT_CONCRETE_BACKGROUND; } public static Color getAbstractFeatureBackgroundColor() { if (CURRENT_ABSTRACT_BACKGROUND == null) { CURRENT_ABSTRACT_BACKGROUND = getColor(QN_FEATURE_ABSTRACT, ABSTRACT_BACKGROUND); } return CURRENT_ABSTRACT_BACKGROUND; } public static void setAbstractFeatureBackgroundColor(Color color) { CURRENT_ABSTRACT_BACKGROUND = color; setColor(QN_FEATURE_ABSTRACT, color); } public static Color getHiddenFeatureForgroundColor() { if (CURRENT_HIDDEN_FOREGROUND == null) { CURRENT_HIDDEN_FOREGROUND = getColor(QN_FEATURE_HIDEEN_FORGROUND, HIDDEN_FOREGROUND); } return CURRENT_HIDDEN_FOREGROUND ; } public static void setHiddenFeatureForgroundColor(Color color) { CURRENT_HIDDEN_FOREGROUND = color; setColor(QN_FEATURE_HIDEEN_FORGROUND, color); } public static Color getHiddenFeatureBackgroundColor() { if (CURRENT_HIDDEN_BACKGROUND == null) { CURRENT_HIDDEN_BACKGROUND = getColor(QN_FEATURE_HIDEEN_BACKGROUND, HIDDEN_BACKGROUND); } return CURRENT_HIDDEN_BACKGROUND; } public static void setHiddenFeatureBackgroundColor(Color color) { CURRENT_HIDDEN_BACKGROUND = color; setColor(QN_FEATURE_HIDEEN_BACKGROUND, color); } public static Color getDeadFeatureBackgroundColor() { if (CURRENT_DEAD_BACKGROUND == null) { CURRENT_DEAD_BACKGROUND = getColor(QN_FEATURE_DEAD, DEAD_BACKGROUND); } return CURRENT_DEAD_BACKGROUND; } public static void setDeadFeatureBackgroundColor(Color color) { CURRENT_DEAD_BACKGROUND = color; setColor(QN_FEATURE_DEAD, color); } public static Color getFalseOptionalFeatureBackgroundColor() { if (CURRENT_FEATURE_DEAD == null) { CURRENT_FEATURE_DEAD = getColor(QN_FEATURE_DEAD, DEAD_BACKGROUND); } return CURRENT_FEATURE_DEAD; } public static void setFalseOptionalFeatureBackgroundColor(Color color) { CURRENT_FEATURE_DEAD = color; setColor(QN_FEATURE_DEAD, color); } public static Color getConstraintBackgroundColor() { if (CURRENT_CONSTRAINT_BACKGROUND == null) { CURRENT_CONSTRAINT_BACKGROUND = getColor(QN_CONSTRAINT, CONSTRAINT_BACKGROUND); } return CURRENT_CONSTRAINT_BACKGROUND; } public static void setConstraintBackgroundColor(Color color) { CURRENT_CONSTRAINT_BACKGROUND = color; setColor(QN_CONSTRAINT, color); } public static void setConnectionForgroundColor(Color color) { CURRENT_CONNECTION_FOREGROUND = color; setColor(QN_CONNECTION, color); } public static Color getConnectionForgroundColor() { if (CURRENT_CONNECTION_FOREGROUND == null) { CURRENT_CONNECTION_FOREGROUND = getColor(QN_CONNECTION, CONNECTION_FOREGROUND); } return CURRENT_CONNECTION_FOREGROUND; } public static Color getWarningColor() { if (CURRENT_WARNING_BACKGROUND == null) { CURRENT_WARNING_BACKGROUND = getColor(QN_WARNING, WARNING_BACKGROUND); } return CURRENT_WARNING_BACKGROUND; } public static void setWarningColor(Color color) { CURRENT_WARNING_BACKGROUND = color; setColor(QN_WARNING, color); } public static void setLanguage(String text) { setString(QN_LANGUAGE, text); } public static ILanguage getLanguage() { if (German.NAME.equals(getString(QN_LANGUAGE))) { return new German(); } return new English(); } public static int getLayoutMarginX() { if (CURRENT_LAYOUT_MARGIN_X == null) { CURRENT_LAYOUT_MARGIN_X = getInt(QN_LAYOUT_MARGIN_X, LAYOUT_MARGIN_X); } return CURRENT_LAYOUT_MARGIN_X; } public static void setlayoutMagrginX(int value) { CURRENT_LAYOUT_MARGIN_X = value; setInt(QN_LAYOUT_MARGIN_X, value); } public static int getLayoutMarginY() { if (CURRENT_LAYOUT_MARGIN_Y == null) { CURRENT_LAYOUT_MARGIN_Y = getInt(QN_LAYOUT_MARGIN_Y, LAYOUT_MARGIN_Y); } return CURRENT_LAYOUT_MARGIN_Y; } public static void setlayoutMagrginY(int value) { CURRENT_LAYOUT_MARGIN_Y = value; setInt(QN_LAYOUT_MARGIN_Y, value); } public static int getFeatureSpaceX() { if (CURRENT_FEATURE_SPACE_X == null) { CURRENT_FEATURE_SPACE_X = getInt(QN_FEATURE_X, FEATURE_SPACE_X); } return CURRENT_FEATURE_SPACE_X; } public static void setFeatureSpaceX(int value) { CURRENT_FEATURE_SPACE_X = value; setInt(QN_FEATURE_X, value); } public static int getFeatureSpaceY() { if (CURRENT_FEATURE_SPACE_Y == null) { CURRENT_FEATURE_SPACE_Y = getInt(QN_FEATURE_Y, FEATURE_SPACE_Y); } return CURRENT_FEATURE_SPACE_Y; } public static void setFeatureSpaceY(int value) { CURRENT_FEATURE_SPACE_Y = value; setInt(QN_FEATURE_Y, value); } public static int getConstraintSpace() { if (CURRENT_CONSTRAINT_SPACE_Y == null) { CURRENT_CONSTRAINT_SPACE_Y = getInt(QN_CONSTRAINT_SPACE, CONSTRAINT_SPACE_Y); } return CURRENT_CONSTRAINT_SPACE_Y; } public static void setConstraintSpace(int value) { CURRENT_CONSTRAINT_SPACE_Y = value; setInt(QN_CONSTRAINT_SPACE, value); } public static Color getConstraintBorderColor(boolean selected) { if (selected) { return GUIBasics.createBorderColor(getConstraintBackgroundColor()); } return getConstraintBackgroundColor(); } public static Border getConstraintBorder(boolean selected) { if (selected) { return GUIBasics.createLineBorder(getConstraintBorderColor(true), 3); } return GUIBasics.createLineBorder(getConstraintBorderColor(false), 0); } public static Border getHiddenFeatureBorder(boolean selected) { if (selected) { return GUIBasics.createLineBorder(HIDDEN_BORDER_COLOR, 3, Graphics.LINE_DOT); } return GUIBasics.createLineBorder(HIDDEN_BORDER_COLOR, 1, Graphics.LINE_DASH); } // private static Color getHiddenBorderColor() { // return GUIBasics.createBorderColor(getDeadFeatureBackgroundColor()); // } public static Border getDeadFeatureBorder(boolean selected) { if (selected) { return GUIBasics.createLineBorder(getDeadBorderColor(), 3); } return GUIBasics.createLineBorder(getDeadBorderColor(), 1); } private static Color getDeadBorderColor() { return GUIBasics.createBorderColor(getDeadFeatureBackgroundColor()); } public static Border getLegendBorder() { return GUIBasics.createLineBorder(getLegendBorderColor(), 1); } public static Border getConcreteFeatureBorder(boolean selected) { if (selected) { return GUIBasics.createLineBorder(getConcreteBorderColor(), 3); } return GUIBasics.createLineBorder(getConcreteBorderColor(), 1); } private static Color getConcreteBorderColor() { return GUIBasics.createBorderColor(getConcreteFeatureBackgroundColor()); } public static Border getAbsteactFeatureBorder(boolean selected) { if (selected) { return GUIBasics.createLineBorder(getAbstractBorderColor(), 3); } return GUIBasics.createLineBorder(getAbstractBorderColor(), 1); } private static Color getAbstractBorderColor() { return GUIBasics.createBorderColor(getAbstractFeatureBackgroundColor()); } public static Border getHiddenLegendBorder() { return GUIBasics.createLineBorder(getDiagramBackgroundColor(), 1, SWT.LINE_DOT); } public static Color getDecoratorForgroundColor() { if (CURRENT_DECORATOR_FORGROUND_COLOR == null) { CURRENT_DECORATOR_FORGROUND_COLOR = getConnectionForgroundColor(); } return CURRENT_DECORATOR_FORGROUND_COLOR; } public static Color getDecoratorBackgroundColor() { return getDiagramBackgroundColor(); } /** * Gets the value(int) saved for the QualifiedName.<br> * If there is no value saved, the given default value is returned. * * @param name The QualifiedName * @param defaultValue The default value from {@link GUIDefaults} * @return The value for the QualifiedName */ private static int getInt(QualifiedName name, int defaultValue) { try { String property = workspaceRoot.getPersistentProperty(name); if (property != null && !"".equals(property)) { return Integer.parseInt(property); } } catch (CoreException e) { FMCorePlugin.getDefault().logError(e); } return defaultValue; } /** * Sets the value for the QualifiedName. * @param name The QualifiedName * @param value The value to set */ private static void setInt(QualifiedName name, int value) { try { workspaceRoot.setPersistentProperty(name, Integer.toString(value)); } catch (CoreException e) { FMCorePlugin.getDefault().logError(e); } } /** * Gets the value(boolean) saved for the QualifiedName.<br> * If there is no value saved, it returns: <code>false</code> * * @param name The QualifiedName * @return The value for the QualifiedName */ private static boolean getBoolean(QualifiedName name) { try { return "true".equals(workspaceRoot.getPersistentProperty(name)); } catch (CoreException e) { FMCorePlugin.getDefault().logError(e); } return false; } /** * Sets the value for the QualifiedName. * @param name The QualifiedName * @param value The value to set */ private static void setBoolean(QualifiedName name, boolean value) { try { workspaceRoot.setPersistentProperty(name, value ? TRUE : FALSE); } catch (CoreException e) { FMCorePlugin.getDefault().logError(e); } } /** * Gets the value(Color) saved for the QualifiedName.<br> * If there is no value saved, the given default value is returned. * * @param name The QualifiedName * @param defaultColor The default value from {@link GUIDefaults} * @return The value for the QualifiedName */ private static Color getColor(QualifiedName name, Color deafaultColor) { try { String property = workspaceRoot.getPersistentProperty(name); if (property != null) { String[] color = property.split("[|]"); if (color.length == 3) { return new Color(null, Integer.parseInt(color[0]), Integer.parseInt(color[1]), Integer.parseInt(color[2])); } } } catch (CoreException e) { FMCorePlugin.getDefault().logError(e); } return deafaultColor; } /** * Sets the color for the QualifiedName. * @param name The QualifiedName * @param color The color to set */ private static void setColor(QualifiedName name, Color color) { String c = color.getRed() + "|" + color.getGreen() + "|" + color.getBlue(); try { workspaceRoot.setPersistentProperty(name, c); } catch (CoreException e) { FMCorePlugin.getDefault().logError(e); } } /** * Gets the value(String) saved for the QualifiedName.<br> * If there is no value saved, it returns: "". * * @param name The QualifiedName * @return The value for the QualifiedName */ private static String getString(QualifiedName name) { try { if (workspaceRoot.getPersistentProperty(name) != null) { return workspaceRoot.getPersistentProperty(name); } } catch (CoreException e) { FMCorePlugin.getDefault().logError(e); } return ""; } /** * Sets the value for the QualifiedName. * @param name The QualifiedName * @param value The value to set */ private static void setString(QualifiedName name, String value) { try { workspaceRoot.setPersistentProperty(name, value); } catch (CoreException e) { FMCorePlugin.getDefault().logError(e); } } public static LinkedList<QualifiedName> getQualifiedNames() { LinkedList<QualifiedName> names = new LinkedList<QualifiedName>(); names.add(QN_HIDE_LEGEND); // names.add(QN_LEGEND_FORGOUND); names.add(QN_LEGEND_BACKGROUND); names.add(QN_LEGEND_BORDER); names.add(QN_LANGUAGE); names.add(QN_DIAGRAM_BACKGROUND); // names.add(QN_FEATURE_FORGROUND); names.add(QN_FEATURE_CONCRETE); names.add(QN_FEATURE_ABSTRACT); // names.add(QN_FEATURE_HIDEEN_FORGROUND); names.add(QN_FEATURE_HIDEEN_BACKGROUND); names.add(QN_FEATURE_DEAD); names.add(QN_CONSTRAINT ); names.add(QN_CONNECTION); names.add(QN_WARNING); names.add(QN_LAYOUT_MARGIN_X); names.add(QN_LAYOUT_MARGIN_Y); names.add(QN_FEATURE_X); names.add(QN_FEATURE_Y); names.add(QN_CONSTRAINT_SPACE); return names; } }
yDon96/servletManager
src/main/java/com/daayCyclic/servletManager/controller/UserController.java
<gh_stars>0 package com.daayCyclic.servletManager.controller; import com.daayCyclic.servletManager.dao.CompetencyDao; import com.daayCyclic.servletManager.dao.RoleDao; import com.daayCyclic.servletManager.dao.UserDao; import com.daayCyclic.servletManager.dto.UserDto; import com.daayCyclic.servletManager.exception.NotFoundException; import com.daayCyclic.servletManager.exception.NotValidTypeException; import com.daayCyclic.servletManager.mapper.IDaoToDtoMapper; import com.daayCyclic.servletManager.mapper.IDtoToDaoMapper; import com.daayCyclic.servletManager.service.ICompetencyService; import com.daayCyclic.servletManager.service.IRoleService; import com.daayCyclic.servletManager.service.IUserService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @Slf4j @RestController public class UserController { @Autowired private IUserService userService; @Autowired private IRoleService roleService; @Autowired private ICompetencyService competencyService; @Autowired @Qualifier(value = "UserDaoToDtoMapper") private IDaoToDtoMapper userDaoToDtoMapper; @Autowired @Qualifier(value = "UserDtoToDaoMapper") private IDtoToDaoMapper userDtoToDaoMapper; /** * Insert into the server the {@literal UserDto} passed. * * @param user the {@literal UserDto} to insert. */ @PostMapping(path = "/user") public void postUser(@RequestBody UserDto user) { log.info("[REST] Starting a postUser request."); UserDao userDao = (UserDao) userDtoToDaoMapper.convertToDao(user); log.info("[REST] Start insert of a new user into the database: " + user); userService.generateUser(userDao); log.info("[REST] Insert completed successfully."); } /** * Update into the server the {@literal UserDto} passed. * * @param user the {@literal UserDto} to update. */ @PutMapping(path = "/user") public void putUser(@RequestBody UserDto user) { log.info("[REST] Starting a putUser request."); UserDao userDao = (UserDao) userDtoToDaoMapper.convertToDao(user); log.info("[REST] Start update of a user into the database: " + user); userService.updateUser(userDao); log.info("[REST] Update completed successfully."); } /** * Get from the server the user correspondent to {@literal userId}. * * @param userId the id into the server of the user. * @return a {@literal UserDto} represents the desired user. */ @GetMapping(path = "/user/{userId}") public UserDto getUser(@PathVariable("userId") int userId) { log.info("[REST] Start search for user with id: " + userId); UserDao searchUser = userService.getUser(userId); log.info("[REST] User found: " + searchUser); return (UserDto) userDaoToDtoMapper.convertToDto(searchUser); } /** * Get users from the server according to their roles, if no role is given, get all users. * (if some of the roles in the list does not exist, will be skipped) * * @param roles a {@literal List<String>} of the desired roles. * @return a {@literal List<UserDto>} containing the desired users. */ @GetMapping(path = "/users") @SuppressWarnings("unchecked") public List<UserDto> getUsers(@RequestParam(required = false) List<String> roles) { log.info("[REST] Starting a getUsers with the given roles."); ArrayList<RoleDao> rolesDao = null; if (roles != null) { rolesDao = new ArrayList<>(); for (String role : roles) { try { RoleDao foundRole = roleService.getRole(role); rolesDao.add(foundRole); } catch (NotFoundException e) { log.info("[REST] The role '" + role + "' does not exist inside the server, will be skipped."); } } } log.info("[REST] Start a research with the given roles as filter: " + roles); List<UserDao> foundUsers = userService.getUsers(rolesDao); log.info("[REST] Found a total of " + foundUsers.size() + " users."); return (List<UserDto>) userDaoToDtoMapper.convertDaoListToDtoList(foundUsers); } /** * Assign the role corresponding to the given {@literal String} role * to the user corresponding to the given id. * * @param id a {@literal Integer} ID which identifies a user. * @param role a {@literal String} which identifies an role. */ @PutMapping(path = "/user/{id}/assign-role") public void assignRoleToUser(@PathVariable("id") Integer id, @RequestParam String role) { log.info("[REST] Get role " + role + "to user with id: " + id); if (role != null && id != null) { if(id<0){ log.error("[REST] User with id " + id + "is not valid."); throw new NotValidTypeException("Invalid parameter."); } RoleDao roleDao = roleService.getRole(role); UserDao userDao = userService.getUser(id); userService.assignRoleToUser(userDao, roleDao); log.info("[REST] User role assignment was successful."); } } @PutMapping(path = "/user/{userId}/assign-competencies") public void assignMultipleCompetencyToUser(@PathVariable("userId") Integer userId,@RequestParam List<String> competencies) { log.info("[REST] Starting assign competency: " + competencies + " to user: " + userId); competencies.forEach(competency -> { assignCompetencyToUser(userId,competency); }); log.info("[REST] Competency assigned successfully"); } /** * Assign the competency corresponding to the given {@literal String} competency * to the user corresponding to the given userId. * * @param userId a {@literal Integer} ID which identifies a user. * @param competency a {@literal String} which identifies an competency. */ @PutMapping(path = "/user/{userId}/assign-competency") public void assignCompetencyToUser(@PathVariable("userId") Integer userId, @RequestParam String competency) { log.info("[REST] Starting assign competency: " + competency + " to user: " + userId); UserDao userDao = userService.getUser(userId); CompetencyDao competencyDao = competencyService.getCompetency(competency); userService.assignCompetencyToUser(competencyDao, userDao); log.info("[REST] Competency assigned successfully."); } }
eomanovic3/unit-test
app/containers/App/tests/reducer.test.js
import produce from 'immer'; import appReducer from '../reducer'; import { defaultAction } from '../actions'; /* eslint-disable default-case, no-param-reassign */ describe('appReducer', () => { let state; beforeEach(() => { state = { loading: false, error: false, }; }); it('should return the initial state', () => { const expectedResult = state; expect(appReducer(undefined, {})).toEqual(expectedResult); }); it('should handle the defaultAction action correctly', () => { const expectedResult = produce(state, draft => { draft.loading = true; draft.error = false; }); expect(appReducer(state, defaultAction())).toEqual(expectedResult); }); });
GYosifov88/Python-Basics
test.py
import random import turtle colors = ['red', 'cyan', 'pink', 'yellow', 'green', 'orange'] t = turtle.Turtle() t.speed(10) turtle.bgcolor("black") lenght = 100 angle = 23 size = 5 for i in range (lenght): color = random.choice(colors) t.pencolor(color) t.fillcolor(color) t.penup() t.forward(i+50) t.pendown() t.left(angle) t.begin_fill() t.circle(size) t.end_fill() turtle.exitonclick() turtle.bgcolor("black")
josehu07/SplitFS
kernel/linux-5.4/include/linux/platform_data/serial-imx.h
<gh_stars>10-100 /* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2008 by <NAME> <<EMAIL>> */ #ifndef ASMARM_ARCH_UART_H #define ASMARM_ARCH_UART_H #define IMXUART_HAVE_RTSCTS (1<<0) struct imxuart_platform_data { unsigned int flags; }; #endif
gtalis/openscreen
util/trace_logging/scoped_trace_operations.cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "util/trace_logging/scoped_trace_operations.h" #include "absl/types/optional.h" #include "platform/api/trace_logging_platform.h" #include "platform/base/trace_logging_activation.h" #include "util/osp_logging.h" #if defined(ENABLE_TRACE_LOGGING) namespace openscreen { namespace internal { // static bool ScopedTraceOperation::TraceAsyncEnd(const uint32_t line, const char* file, TraceId id, Error::Code e) { auto end_time = Clock::now(); const CurrentTracingDestination destination; if (destination) { destination->LogAsyncEnd(line, file, end_time, id, e); return true; } return false; } ScopedTraceOperation::ScopedTraceOperation(TraceId trace_id, TraceId parent_id, TraceId root_id) { if (traces_ == nullptr) { // Create the stack if it doesnt' exist. traces_ = new TraceStack(); // Create a new root node. This will re-call this constructor and add the // root node to the stack before proceeding with the original node. root_node_ = new TraceIdSetter(TraceIdHierarchy::Empty()); OSP_DCHECK(!traces_->empty()); } // Setting trace id fields. root_id_ = root_id != kUnsetTraceId ? root_id : traces_->top()->root_id_; parent_id_ = parent_id != kUnsetTraceId ? parent_id : traces_->top()->trace_id_; trace_id_ = trace_id != kUnsetTraceId ? trace_id : trace_id_counter_.fetch_add(1); // Add this item to the stack. traces_->push(this); OSP_DCHECK(traces_->size() < 1024); } ScopedTraceOperation::~ScopedTraceOperation() { OSP_CHECK(traces_ != nullptr && !traces_->empty()); OSP_CHECK_EQ(traces_->top(), this); traces_->pop(); // If there's only one item left, it must be the root node. Deleting the root // node will re-call this destructor and delete the traces_ stack. if (traces_->size() == 1) { OSP_CHECK_EQ(traces_->top(), root_node_); delete root_node_; root_node_ = nullptr; } else if (traces_->empty()) { delete traces_; traces_ = nullptr; } } // static thread_local ScopedTraceOperation::TraceStack* ScopedTraceOperation::traces_ = nullptr; // static thread_local ScopedTraceOperation* ScopedTraceOperation::root_node_ = nullptr; // static std::atomic<std::uint64_t> ScopedTraceOperation::trace_id_counter_{ uint64_t{0x01} << (sizeof(TraceId) * 8 - 1)}; TraceLoggerBase::TraceLoggerBase(TraceCategory::Value category, const char* name, const char* file, uint32_t line, TraceId current, TraceId parent, TraceId root) : ScopedTraceOperation(current, parent, root), start_time_(Clock::now()), result_(Error::Code::kNone), name_(name), file_name_(file), line_number_(line), category_(category) {} TraceLoggerBase::TraceLoggerBase(TraceCategory::Value category, const char* name, const char* file, uint32_t line, TraceIdHierarchy ids) : TraceLoggerBase(category, name, file, line, ids.current, ids.parent, ids.root) {} SynchronousTraceLogger::~SynchronousTraceLogger() { const CurrentTracingDestination destination; if (destination) { auto end_time = Clock::now(); destination->LogTrace(this->name_, this->line_number_, this->file_name_, this->start_time_, end_time, this->to_hierarchy(), this->result_); } } AsynchronousTraceLogger::~AsynchronousTraceLogger() { const CurrentTracingDestination destination; if (destination) { destination->LogAsyncStart(this->name_, this->line_number_, this->file_name_, this->start_time_, this->to_hierarchy()); } } TraceIdSetter::~TraceIdSetter() = default; } // namespace internal } // namespace openscreen #endif // defined(ENABLE_TRACE_LOGGING)
sidtheprince/dokun
include/toggle.h
<reponame>sidtheprince/dokun #ifndef _TOGGLE #define _TOGGLE #include "ui.h" #ifdef __cplusplus // if c++ #include <iostream> #include <lua.hpp> class Toggle : public GUI { // includes check_box, radio, and switch public: Toggle(); static int new_(lua_State *L); virtual ~Toggle(); // functions virtual void draw(); static int draw(lua_State *L); /* can be overriden */ // setters void set_value(bool value); static int set_value_lua(lua_State *L); void set_foreground_color(int red, int green, int blue, int alpha=255); void set_foreground_color(const Vector3& color); void set_foreground_color(const Vector4& color); void set_background_color(int red, int green, int blue, int alpha=255); void set_background_color(const Vector3& color); void set_background_color(const Vector4& color); void set_background_color_on(int red, int green, int blue, int alpha=255); void set_background_color_on(const Vector3& color); void set_background_color_on(const Vector4& color); void set_background_color_off(int red, int green, int blue, int alpha=255); void set_background_color_off(const Vector3& color); void set_background_color_off(const Vector4& color); // outline void set_outline(bool outline); void set_outline_width(double width); void set_outline_color(int red, int green, int blue, int alpha=255); void set_outline_color(const Vector3& color); void set_outline_color(const Vector4& color); void set_outline_antialiased(bool antialiased); // getters bool get_value()const; static int get_value(lua_State *L); std::string get_type()const; static int get_type(lua_State *L); Vector4 get_foreground_color()const; Vector4 get_background_color_on()const; Vector4 get_background_color_off()const; // handle double get_handle_x()const; double get_handle_y()const; int get_handle_width()const; int get_handle_height()const; Vector4 get_handle_color()const; // boolean bool is_checkbox() const; static int is_check(lua_State *L); bool is_radio() const; static int is_radio(lua_State *L); bool is_switch() const; static int is_switch(lua_State *L); void set_switch(); void set_radio(); void set_checkbox(); private: std::string type; bool value; // on-off Vector4 foreground_color; Vector4 background_color; Vector4 background_color_on; Vector4 background_color_off; // handle // outline bool outline; Vector4 outline_color; double outline_width; bool outline_antialiased; // gradient bool gradient; Vector4 gradient_color; }; ///////// /* if(Keyboard::is_pressed(KEY_LEFT)) { toggle->set_value(0); } if(Keyboard::is_pressed(KEY_RIGHT)) { toggle->set_value(1); } */ #endif ///////// /* switch: [=[]] check box: [✔] radio: (O) USAGE: Toggle * toggle = new Toggle(); toggle->set_position(10, 500); */ #endif
Ivarpoiss/wordnet-workbench-client
app/service/AuthService.js
/** * Created by Ivar on 13.12.2015. */ define(['appModule'], function (app) { app.service('AuthService', [ '$http','$state','config','$location','$rootScope','$timeout','$log','$window', '$sessionStorage', '$localStorage', 'wnwbApi', function($http, $state, config, $location, $rootScope, $timeout, $log, $window, $sessionStorage, $localStorage, wnwbApi) { var self = this; var storage = $localStorage; var user = null; var isAuthenticated = false; this.init = function ( callback ) { var token = self.getToken(); $log.debug('[AuthService::init()] Token: ', token); if(token) { self.setupHttpHeader( token ); } self._requestUserInfo( callback ); return; }; this._requestUserInfo = function ( callback ) { if(!self.getToken()){ $log.debug('Has no user token.'); callback(); return; } self.updateUserInfo(self.getToken()); callback(); /*$http.get( config.API_URL + '/user').then(function ( response ) { self.updateUserInfo(response.data); callback(); }, function ( response ) { self.updateUserInfo(response.data); callback(); });*/ }; this.isAuthenticated = function () { return isAuthenticated; }; this.signOut = function () { $log.log('singOut'); user = null; self.removeToken(); isAuthenticated = false; $rootScope.principal = null; $rootScope.$broadcast('notAuthenticated', $state); $http.get(config.API_UNAUTH_URL). then(function(response) { $state.go('auth'); user = null; self.removeToken(); isAuthenticated = false; $rootScope.principal = null; $rootScope.$broadcast('notAuthenticated', $state); }, function(response) { console.error(response); }); return true; }; this.startAuth = function (username, password, callback) { var landingPath = self.getLandingPath() ? self.getLandingPath() : '/'; var returnPath = $location.protocol() + '://' + location.host +'/#'+ landingPath; var returnPathEncoded = encodeURIComponent(returnPath); $http.defaults.headers.common['Authorization'] = 'Basic ' + btoa(username + ':' + password); var auth = new wnwbApi.Authorization(); auth.$auth(function () { $http.defaults.headers.common['Authorization'] = 'Token ' + auth.token; //$sessionStorage.token = {token: auth.token, timeCreated: new Date()}; storage.token = {token: auth.token, timeCreated: new Date()}; isAuthenticated = true; self.updateUserInfo(storage.token); callback({success: true}); $rootScope.$broadcast('authenticationFinished', $state); }, function () { callback({success: false}); }); }; this.logout = function () { storage.token = null; isAuthenticated = false; $state.go('home', {}, {reload: true}); }; this.updateUserInfo = function (token) { $log.debug('Update user info ', token); if (!token || new Date() - new Date(token.timeCreated) >= 28800000) { self.signOut(); } else { isAuthenticated = true; //user = {username: 'test'}; var principal = wnwbApi.Principal.query(function (result) { if (result.length > 0) { $rootScope.principal = result.shift(); } }); //$rootScope.user = user; $rootScope.$broadcast('authenticated', $state); //self.doHeardBeat(); } }; /*this.updateUserInfo = function (userData) { $log.debug('Update user info ', userData); if(userData.statusCode != 200){ self.signOut(); } else { isAuthenticated = true; user = userData.data; $rootScope.user = user; self.doHeardBeat(); } };*/ this.setToken = function (token) { self.setupHttpHeader(token); //return $sessionStorage.token = token; return storage.token = token; }; this.getToken = function(){ //return $sessionStorage.token; return storage.token; }; this.removeToken = function () { //delete $sessionStorage.token; delete storage.token; }; this.getLandingPath = function () { return window.sessionStorage.getItem('landingPath'); }; this.setLandingPath = function (landingPath) { if(landingPath == '/auth' || landingPath == '/err404'){ landingPath = '/home' } return window.sessionStorage.setItem('landingPath', landingPath); }; this.setupHttpHeader = function(token) { $http.defaults.headers.common['Authorization'] = 'Token ' + token.token; }; this.getUser = function(id, callback) { $http.get(config.API_URL + '/user/' + id + '/details').then(function(response) { callback(null, response.data.data); }); }; this.getUsersList = function (pagination, callback) { pagination = pagination || {}; $http.get(config.API_URL + '/user/list', {params: pagination}).then(function (response) { callback(null, response.data.data); }); }; this.updateUser = function(user, callback) { var userData = { role: user.role, discMax: user.discMax, isActive: user.is_active }; $http.put(config.API_URL + '/user/' + user.id + '/details', userData).then(function(response) { callback(response.errors, response.data); }); }; var timeoutPromise = null; this.doHeardBeat = function () { if(!self.isAuthenticated){ return; } if(timeoutPromise){ $timeout.cancel(timeoutPromise); } $http.put(config.API_URL + '/user/heart-beat', {}).then(function(response) { $rootScope.notificationsSummary = response.data.data; if(!config.hearbeat_interval){ return } timeoutPromise = $timeout(function () { if(!self.isAuthenticated){ return; } self.doHeardBeat(); }, config.hearbeat_interval); }, function(response) { $log.error(response); }); }; } ]); });
Cloud11665/satori-git
satori.core/satori/core/entities/SystemRole.py
# vim:ts=4:sts=4:sw=4:expandtab from django.db import models from satori.core.dbev import Events from satori.core.models import Role @ExportModel class SystemRole(Role): """Model. A Role that is used for internal system roles. """ parent_role = models.OneToOneField(Role, parent_link=True, related_name='cast_systemrole') class ExportMeta(object): pass @staticmethod def create(fields): role = SystemRole() role.forbid_fields(fields, ['id', 'sort_field']) role.update_fields(fields, ['name']) role.name = role.name.strip() role.sort_field = role.name role.save() return role def modify(self, fields): self.forbid_fields(fields, ['id', 'sort_field']) self.update_fields(fields, ['name']) self.name = self.name.strip() self.sort_field = self.name self.save() return self class SystemRoleEvents(Events): model = SystemRole on_insert = on_update = on_delete = []
abhaikollara/tensorflow
tensorflow/stream_executor/host/host_stream.cc
<reponame>abhaikollara/tensorflow<filename>tensorflow/stream_executor/host/host_stream.cc /* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // Class method definitions for HostStream, the Stream implementation for // the HostExecutor implementation. #include "tensorflow/stream_executor/host/host_stream.h" #include "absl/synchronization/notification.h" #include "tensorflow/core/platform/denormal.h" #include "tensorflow/core/platform/setround.h" namespace stream_executor { namespace host { HostStream::HostStream() : thread_(port::Env::Default()->StartThread( port::ThreadOptions(), "host_executor", [this]() { WorkLoop(); })) {} HostStream::~HostStream() { { absl::MutexLock lock(&mu_); work_queue_.push(nullptr); } // thread_'s destructor blocks until the thread finishes running. thread_.reset(); } bool HostStream::EnqueueTask(std::function<void()> fn) { CHECK(fn != nullptr); absl::MutexLock lock(&mu_); work_queue_.push(std::move(fn)); return true; } bool HostStream::WorkAvailable() { return !work_queue_.empty(); } void HostStream::WorkLoop() { // Set denormal and rounding behavior to match the default TF ThreadPool // behavior. // TODO(phawkins, jlebar): it's not clear this is the best place to set this. tensorflow::port::ScopedFlushDenormal flush; tensorflow::port::ScopedSetRound round(FE_TONEAREST); while (true) { std::function<void()> fn; { absl::MutexLock lock(&mu_); mu_.Await(absl::Condition(this, &HostStream::WorkAvailable)); fn = std::move(work_queue_.front()); work_queue_.pop(); } if (!fn) { return; } fn(); } } void HostStream::BlockUntilDone() { absl::Notification done; EnqueueTask([&done]() { done.Notify(); }); done.WaitForNotification(); } } // namespace host } // namespace stream_executor
LaudateCorpus1/oci-ansible-collection
plugins/modules/oci_database_cloud_autonomous_vm_cluster_actions.py
<gh_stars>0 #!/usr/bin/python # Copyright (c) 2020, 2022 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for details. # GENERATED FILE - DO NOT EDIT - MANUAL CHANGES WILL BE OVERWRITTEN from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "community", } DOCUMENTATION = """ --- module: oci_database_cloud_autonomous_vm_cluster_actions short_description: Perform actions on a CloudAutonomousVmCluster resource in Oracle Cloud Infrastructure description: - Perform actions on a CloudAutonomousVmCluster resource in Oracle Cloud Infrastructure - For I(action=change_compartment), moves an Autonomous Exadata VM cluster in the Oracle cloud and its dependent resources to another compartment. For Exadata Cloud@Customer systems, see L(ChangeAutonomousVmClusterCompartment,https://docs.cloud.oracle.com/en- us/iaas/api/#/en/database/latest/AutonomousVmCluster/ChangeAutonomousVmClusterCompartment). - For I(action=rotate_cloud_autonomous_vm_cluster_ords_certs), rotates the Oracle REST Data Services (ORDS) certificates for a cloud Autonomous Exadata VM cluster. - For I(action=rotate_cloud_autonomous_vm_cluster_ssl_certs), rotates the SSL certficates for a cloud Autonomous Exadata VM cluster. version_added: "2.9.0" author: Oracle (@oracle) options: compartment_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the compartment. - Required for I(action=change_compartment). type: str cloud_autonomous_vm_cluster_id: description: - The Cloud VM cluster L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm). type: str aliases: ["id"] required: true action: description: - The action to perform on the CloudAutonomousVmCluster. type: str required: true choices: - "change_compartment" - "rotate_cloud_autonomous_vm_cluster_ords_certs" - "rotate_cloud_autonomous_vm_cluster_ssl_certs" extends_documentation_fragment: [ oracle.oci.oracle, oracle.oci.oracle_wait_options ] """ EXAMPLES = """ - name: Perform action change_compartment on cloud_autonomous_vm_cluster oci_database_cloud_autonomous_vm_cluster_actions: # required compartment_id: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx" cloud_autonomous_vm_cluster_id: "ocid1.cloudautonomousvmcluster.oc1..xxxxxxEXAMPLExxxxxx" action: change_compartment - name: Perform action rotate_cloud_autonomous_vm_cluster_ords_certs on cloud_autonomous_vm_cluster oci_database_cloud_autonomous_vm_cluster_actions: # required cloud_autonomous_vm_cluster_id: "ocid1.cloudautonomousvmcluster.oc1..xxxxxxEXAMPLExxxxxx" action: rotate_cloud_autonomous_vm_cluster_ords_certs - name: Perform action rotate_cloud_autonomous_vm_cluster_ssl_certs on cloud_autonomous_vm_cluster oci_database_cloud_autonomous_vm_cluster_actions: # required cloud_autonomous_vm_cluster_id: "ocid1.cloudautonomousvmcluster.oc1..xxxxxxEXAMPLExxxxxx" action: rotate_cloud_autonomous_vm_cluster_ssl_certs """ RETURN = """ cloud_autonomous_vm_cluster: description: - Details of the CloudAutonomousVmCluster resource acted upon by the current operation returned: on success type: complex contains: id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the Cloud Autonomous VM cluster. returned: on success type: str sample: "ocid1.resource.oc1..xxxxxxEXAMPLExxxxxx" compartment_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the compartment. returned: on success type: str sample: "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx" description: description: - User defined description of the cloud Autonomous VM cluster. returned: on success type: str sample: description_example availability_domain: description: - The name of the availability domain that the cloud Autonomous VM cluster is located in. returned: on success type: str sample: Uocm:PHX-AD-1 subnet_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the subnet the cloud Autonomous VM Cluster is associated with. - "**Subnet Restrictions:** - For Exadata and virtual machine 2-node RAC DB systems, do not use a subnet that overlaps with 192.168.128.0/20." - These subnets are used by the Oracle Clusterware private interconnect on the database instance. Specifying an overlapping subnet will cause the private interconnect to malfunction. This restriction applies to both the client subnet and backup subnet. returned: on success type: str sample: "ocid1.subnet.oc1..xxxxxxEXAMPLExxxxxx" nsg_ids: description: - "A list of the L(OCIDs,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the network security groups (NSGs) that this resource belongs to. Setting this to an empty array after the list is created removes the resource from all NSGs. For more information about NSGs, see L(Security Rules,https://docs.cloud.oracle.com/Content/Network/Concepts/securityrules.htm). **NsgIds restrictions:** - Autonomous Databases with private access require at least 1 Network Security Group (NSG). The nsgIds array cannot be empty." returned: on success type: list sample: [] last_update_history_entry_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the last maintenance update history. This value is updated when a maintenance update starts. returned: on success type: str sample: "ocid1.lastupdatehistoryentry.oc1..xxxxxxEXAMPLExxxxxx" lifecycle_state: description: - The current state of the cloud Autonomous VM cluster. returned: on success type: str sample: PROVISIONING display_name: description: - The user-friendly name for the cloud Autonomous VM cluster. The name does not need to be unique. returned: on success type: str sample: display_name_example time_created: description: - The date and time that the cloud Autonomous VM cluster was created. returned: on success type: str sample: "2013-10-20T19:20:30+01:00" time_updated: description: - The last date and time that the cloud Autonomous VM cluster was updated. returned: on success type: str sample: "2013-10-20T19:20:30+01:00" lifecycle_details: description: - Additional information about the current lifecycle state. returned: on success type: str sample: lifecycle_details_example hostname: description: - The hostname for the cloud Autonomous VM cluster. returned: on success type: str sample: hostname_example domain: description: - The domain name for the cloud Autonomous VM cluster. returned: on success type: str sample: domain_example cloud_exadata_infrastructure_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the cloud Exadata infrastructure. returned: on success type: str sample: "ocid1.cloudexadatainfrastructure.oc1..xxxxxxEXAMPLExxxxxx" shape: description: - The model name of the Exadata hardware running the cloud Autonomous VM cluster. returned: on success type: str sample: shape_example node_count: description: - The number of database servers in the cloud VM cluster. returned: on success type: int sample: 56 data_storage_size_in_tbs: description: - The total data storage allocated, in terabytes (TB). returned: on success type: float sample: 1.2 data_storage_size_in_gbs: description: - The total data storage allocated, in gigabytes (GB). returned: on success type: float sample: 1.2 cpu_core_count: description: - The number of CPU cores enabled on the cloud Autonomous VM cluster. returned: on success type: int sample: 56 ocpu_count: description: - The number of CPU cores enabled on the cloud Autonomous VM cluster. Only 1 decimal place is allowed for the fractional part. returned: on success type: float sample: 3.4 memory_size_in_gbs: description: - The memory allocated in GBs. returned: on success type: int sample: 56 license_model: description: - The Oracle license model that applies to the Oracle Autonomous Database. Bring your own license (BYOL) allows you to apply your current on- premises Oracle software licenses to equivalent, highly automated Oracle PaaS and IaaS services in the cloud. License Included allows you to subscribe to new Oracle Database software licenses and the Database service. Note that when provisioning an Autonomous Database on L(dedicated Exadata infrastructure,https://docs.oracle.com/en/cloud/paas/autonomous- database/index.html), this attribute must be null because the attribute is already set at the Autonomous Exadata Infrastructure level. When using L(shared Exadata infrastructure,https://docs.oracle.com/en/cloud/paas/autonomous- database/index.html), if a value is not specified, the system will supply the value of `BRING_YOUR_OWN_LICENSE`. returned: on success type: str sample: LICENSE_INCLUDED last_maintenance_run_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the last maintenance run. returned: on success type: str sample: "ocid1.lastmaintenancerun.oc1..xxxxxxEXAMPLExxxxxx" next_maintenance_run_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the next maintenance run. returned: on success type: str sample: "ocid1.nextmaintenancerun.oc1..xxxxxxEXAMPLExxxxxx" freeform_tags: description: - Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see L(Resource Tags,https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm). - "Example: `{\\"Department\\": \\"Finance\\"}`" returned: on success type: dict sample: {'Department': 'Finance'} defined_tags: description: - Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see L(Resource Tags,https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm). returned: on success type: dict sample: {'Operations': {'CostCenter': 'US'}} sample: { "id": "ocid1.resource.oc1..xxxxxxEXAMPLExxxxxx", "compartment_id": "ocid1.compartment.oc1..xxxxxxEXAMPLExxxxxx", "description": "description_example", "availability_domain": "Uocm:PHX-AD-1", "subnet_id": "ocid1.subnet.oc1..xxxxxxEXAMPLExxxxxx", "nsg_ids": [], "last_update_history_entry_id": "ocid1.lastupdatehistoryentry.oc1..xxxxxxEXAMPLExxxxxx", "lifecycle_state": "PROVISIONING", "display_name": "display_name_example", "time_created": "2013-10-20T19:20:30+01:00", "time_updated": "2013-10-20T19:20:30+01:00", "lifecycle_details": "lifecycle_details_example", "hostname": "hostname_example", "domain": "domain_example", "cloud_exadata_infrastructure_id": "ocid1.cloudexadatainfrastructure.oc1..xxxxxxEXAMPLExxxxxx", "shape": "shape_example", "node_count": 56, "data_storage_size_in_tbs": 1.2, "data_storage_size_in_gbs": 1.2, "cpu_core_count": 56, "ocpu_count": 3.4, "memory_size_in_gbs": 56, "license_model": "LICENSE_INCLUDED", "last_maintenance_run_id": "ocid1.lastmaintenancerun.oc1..xxxxxxEXAMPLExxxxxx", "next_maintenance_run_id": "ocid1.nextmaintenancerun.oc1..xxxxxxEXAMPLExxxxxx", "freeform_tags": {'Department': 'Finance'}, "defined_tags": {'Operations': {'CostCenter': 'US'}} } """ from ansible.module_utils.basic import AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils import ( oci_common_utils, oci_wait_utils, ) from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import ( OCIActionsHelperBase, get_custom_class, ) try: from oci.work_requests import WorkRequestClient from oci.database import DatabaseClient from oci.database.models import ChangeCloudAutonomousVmClusterCompartmentDetails HAS_OCI_PY_SDK = True except ImportError: HAS_OCI_PY_SDK = False class CloudAutonomousVmClusterActionsHelperGen(OCIActionsHelperBase): """ Supported actions: change_compartment rotate_cloud_autonomous_vm_cluster_ords_certs rotate_cloud_autonomous_vm_cluster_ssl_certs """ def __init__(self, *args, **kwargs): super(CloudAutonomousVmClusterActionsHelperGen, self).__init__(*args, **kwargs) self.work_request_client = WorkRequestClient( self.client._config, **self.client._kwargs ) @staticmethod def get_module_resource_id_param(): return "cloud_autonomous_vm_cluster_id" def get_module_resource_id(self): return self.module.params.get("cloud_autonomous_vm_cluster_id") def get_get_fn(self): return self.client.get_cloud_autonomous_vm_cluster def get_resource(self): return oci_common_utils.call_with_backoff( self.client.get_cloud_autonomous_vm_cluster, cloud_autonomous_vm_cluster_id=self.module.params.get( "cloud_autonomous_vm_cluster_id" ), ) def change_compartment(self): action_details = oci_common_utils.convert_input_data_to_model_class( self.module.params, ChangeCloudAutonomousVmClusterCompartmentDetails ) return oci_wait_utils.call_and_wait( call_fn=self.client.change_cloud_autonomous_vm_cluster_compartment, call_fn_args=(), call_fn_kwargs=dict( change_cloud_autonomous_vm_cluster_compartment_details=action_details, cloud_autonomous_vm_cluster_id=self.module.params.get( "cloud_autonomous_vm_cluster_id" ), ), waiter_type=oci_wait_utils.WORK_REQUEST_WAITER_KEY, operation="{0}_{1}".format( self.module.params.get("action").upper(), oci_common_utils.ACTION_OPERATION_KEY, ), waiter_client=self.work_request_client, resource_helper=self, wait_for_states=oci_common_utils.get_work_request_completed_states(), ) def rotate_cloud_autonomous_vm_cluster_ords_certs(self): return oci_wait_utils.call_and_wait( call_fn=self.client.rotate_cloud_autonomous_vm_cluster_ords_certs, call_fn_args=(), call_fn_kwargs=dict( cloud_autonomous_vm_cluster_id=self.module.params.get( "cloud_autonomous_vm_cluster_id" ), ), waiter_type=oci_wait_utils.WORK_REQUEST_WAITER_KEY, operation="{0}_{1}".format( self.module.params.get("action").upper(), oci_common_utils.ACTION_OPERATION_KEY, ), waiter_client=self.work_request_client, resource_helper=self, wait_for_states=oci_common_utils.get_work_request_completed_states(), ) def rotate_cloud_autonomous_vm_cluster_ssl_certs(self): return oci_wait_utils.call_and_wait( call_fn=self.client.rotate_cloud_autonomous_vm_cluster_ssl_certs, call_fn_args=(), call_fn_kwargs=dict( cloud_autonomous_vm_cluster_id=self.module.params.get( "cloud_autonomous_vm_cluster_id" ), ), waiter_type=oci_wait_utils.WORK_REQUEST_WAITER_KEY, operation="{0}_{1}".format( self.module.params.get("action").upper(), oci_common_utils.ACTION_OPERATION_KEY, ), waiter_client=self.work_request_client, resource_helper=self, wait_for_states=oci_common_utils.get_work_request_completed_states(), ) CloudAutonomousVmClusterActionsHelperCustom = get_custom_class( "CloudAutonomousVmClusterActionsHelperCustom" ) class ResourceHelper( CloudAutonomousVmClusterActionsHelperCustom, CloudAutonomousVmClusterActionsHelperGen, ): pass def main(): module_args = oci_common_utils.get_common_arg_spec( supports_create=False, supports_wait=True ) module_args.update( dict( compartment_id=dict(type="str"), cloud_autonomous_vm_cluster_id=dict( aliases=["id"], type="str", required=True ), action=dict( type="str", required=True, choices=[ "change_compartment", "rotate_cloud_autonomous_vm_cluster_ords_certs", "rotate_cloud_autonomous_vm_cluster_ssl_certs", ], ), ) ) module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) if not HAS_OCI_PY_SDK: module.fail_json(msg="oci python sdk required for this module.") resource_helper = ResourceHelper( module=module, resource_type="cloud_autonomous_vm_cluster", service_client_class=DatabaseClient, namespace="database", ) result = resource_helper.perform_action(module.params.get("action")) module.exit_json(**result) if __name__ == "__main__": main()
changziming/VTour
node_modules/grommet-icons/icons/FormAttachment.js
"use strict"; exports.__esModule = true; exports.FormAttachment = void 0; var _react = _interopRequireDefault(require("react")); var _StyledIcon = require("../StyledIcon"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } var FormAttachment = function FormAttachment(props) { return _react["default"].createElement(_StyledIcon.StyledIcon, _extends({ viewBox: "0 0 24 24", a11yTitle: "FormAttachment" }, props), _react["default"].createElement("path", { fill: "none", stroke: "#000", strokeWidth: "2", d: "M6,13.2932321 C7.63138164,11.6618504 10.6214284,8.67180351 12.3609131,6.93231878 C15.1879856,4.10524628 19.4285943,8.34585492 16.6015218,11.1729275 C13.7744493,14 11.6541453,16.1203048 10.2406087,17.5338408 C8.82707218,18.9473767 6.70676816,16.8270724 8.12030436,15.4135364 C9.53384056,14.0000004 14.4812175,9.05262308 14.4812175,9.05262308" })); }; exports.FormAttachment = FormAttachment;
chebizarro/tegola
server/server.go
// Package server implements the http frontend package server import ( "net/http" "strings" "github.com/dimfeld/httptreemux" "github.com/go-spatial/tegola" "github.com/go-spatial/tegola/atlas" "github.com/go-spatial/tegola/internal/log" ) const ( // MaxTileSize is 500k. Currently just throws a warning when tile // is larger than MaxTileSize MaxTileSize = 500000 ) var ( // set at runtime from main Version string // configurable via the tegola config.toml file (set in main.go) HostName string // configurable via the tegola config.toml file (set in main.go) Port string // the "Access-Control-Allow-Origin" CORS header. // configurable via the tegola config.toml file (set in main.go) CORSAllowedOrigin = "*" // reference to the version of atlas to work with Atlas *atlas.Atlas // tile buffer to use. can be overwritten in the config file TileBuffer float64 = tegola.DefaultTileBuffer ) // Start starts the tile server binding to the provided port func Start(port string) *http.Server { Atlas = atlas.DefaultAtlas // notify the user the server is starting log.Infof("starting tegola server on port %v", port) r := httptreemux.New() group := r.NewGroup("/") // capabilities endpoints group.UsingContext().Handler("GET", "/capabilities", CORSHandler(HandleCapabilities{})) group.UsingContext().Handler("OPTIONS", "/capabilities", CORSHandler(HandleCapabilities{})) group.UsingContext().Handler("GET", "/capabilities/:map_name", CORSHandler(HandleMapCapabilities{})) group.UsingContext().Handler("OPTIONS", "/capabilities/:map_name", CORSHandler(HandleMapCapabilities{})) // map tiles group.UsingContext().Handler("GET", "/maps/:map_name/:z/:x/:y", CORSHandler(TileCacheHandler(HandleMapZXY{}))) group.UsingContext().Handler("OPTIONS", "/maps/:map_name/:z/:x/:y", CORSHandler(HandleMapZXY{})) group.UsingContext().Handler("GET", "/maps/:map_name/style.json", CORSHandler(HandleMapStyle{})) // map layer tiles group.UsingContext().Handler("GET", "/maps/:map_name/:layer_name/:z/:x/:y", CORSHandler(TileCacheHandler(HandleMapLayerZXY{}))) group.UsingContext().Handler("OPTIONS", "/maps/:map_name/:layer_name/:z/:x/:y", CORSHandler(HandleMapLayerZXY{})) // static convenience routes group.UsingContext().Handler("GET", "/", http.FileServer(assetFS())) group.UsingContext().Handler("GET", "/*path", http.FileServer(assetFS())) // start our server srv := &http.Server{Addr: port, Handler: r} go func() { log.Error(srv.ListenAndServe()) }() return srv } // determines the hostname:port to return based on the following hierarchy // - HostName / Port vars as configured via the config file // - The request host / port if config HostName or Port is missing func hostName(r *http.Request) string { var requestHostname string var requestPort string substrs := strings.Split(r.Host, ":") switch len(substrs) { case 1: requestHostname = substrs[0] case 2: requestHostname = substrs[0] requestPort = substrs[1] default: log.Warnf("multiple colons (':') in host string: %v", r.Host) } retHost := HostName if HostName == "" { retHost = requestHostname } if Port != "" && Port != "none" { return retHost + Port } if requestPort != "" && Port != "none" { return retHost + ":" + requestPort } return retHost } // various checks to determin if the request is http or https. the scheme is needed for the TileURLs // r.URL.Scheme can be empty if a relative request is issued from the client. (i.e. GET /foo.html) func scheme(r *http.Request) string { if r.Header.Get("X-Forwarded-Proto") != "" { return r.Header.Get("X-Forwarded-Proto") } else if r.TLS != nil { return "https" } return "http" }
zhiqiang-hu/ZJ-SDK-RT-Thread-NORDIC
NORDIC_SDK/components/ble/ble_services/eddystone/es_adv_timing_resolver.h
/** * Copyright (c) 2016 - 2018, Nordic Semiconductor ASA * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form, except as embedded into a Nordic * Semiconductor ASA integrated circuit in a product or a software update for * such product, must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * 3. Neither the name of Nordic Semiconductor ASA nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 4. This software, with or without modification, must only be used with a * Nordic Semiconductor ASA integrated circuit. * * 5. Any software provided in binary form under this license must not be reverse * engineered, decompiled, modified and/or disassembled. * * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef ES_ADV_TIMING_RESOLVER_H__ #define ES_ADV_TIMING_RESOLVER_H__ #include <stdbool.h> #include <stdint.h> #include "es_app_config.h" /** * @file * @addtogroup eddystone_adv_timing * @{ */ /** @brief Timing parameters for a single slot. */ typedef struct { bool is_etlm; //!< Flag that specifies if the slot is an eTLM. uint8_t slot_no; /**< @brief Slot number. @details * For non-eTLM slots: The slot number of the given frame. * * For eTLM slots: The slot number of the corresponding EID frame. */ uint16_t delay_ms; //!< Delay from this frame to the next. } es_adv_timing_resolver_adv_timing_t; /**@brief Results of calculating advertisement delays. */ typedef struct { es_adv_timing_resolver_adv_timing_t timing_results[APP_MAX_ADV_SLOTS - APP_MAX_EID_SLOTS + (APP_MAX_EID_SLOTS * 2)]; //!< List of timing results. uint8_t len_timing_results; //!< Length of results. } es_adv_timing_resolver_result_t; /**@brief Input to the timing resolver. */ typedef struct { uint16_t adv_interval; //!< Global advertisement interval. uint8_t num_slots_configured; //!< Number of configured slots. const uint8_t * p_slots_configured; //!< Pointer to the list of configured slots. uint8_t num_eid_slots_configured; //!< Number of configured EID slots. const uint8_t * p_eid_slots_configured; //!< Pointer to the list of configured EID slots. bool tlm_configured; //!< Flag that specifies if TLM slot is configured. uint8_t tlm_slot; //!< Slot number of the TLM slot (if @p tlm_configured is true). es_adv_timing_resolver_result_t * p_result; //!< Output result. } es_adv_timing_resolver_input_t; /**@brief Function for getting the input for advertisement interval calculation. * * @param[in,out] p_input Input to advertisement interval calculation (see @ref es_adv_timing_resolver_input_t). * @retval NRF_SUCCESS If the operation was successful. Otherwise, an error code is returned. */ ret_code_t es_adv_timing_resolve(es_adv_timing_resolver_input_t * p_input); /** * @} */ #endif // ES_ADV_TIMING_RESOLVER_H__
sxxlearn2rock/AgileJavaStudy
src/cn/sxx/agilejava/courseinfo/SummerCourseSessionTest.java
<filename>src/cn/sxx/agilejava/courseinfo/SummerCourseSessionTest.java package cn.sxx.agilejava.courseinfo; import static org.junit.Assert.*; import java.util.Date; import org.junit.Before; import org.junit.Test; import cn.sxx.agilejava.util.DateUtil; public class SummerCourseSessionTest extends SessionTest { @Override protected Session createSession(Course course, Date startDate) { return SummerCourseSession.create(course, startDate); } @Test public void testEndDate() { Date startDate = DateUtil.createDate(2003, 6, 9); Session session = createSession(createCourse(), startDate); Date eightWeeksOut = DateUtil.createDate(2003, 8, 1); assertEquals(eightWeeksOut, session.getEndDate()); } private Course createCourse() { return new Course("ENLG", "200"); } }
HappyCerberus/moderncpp-aoc-2021
day01/trivial.cc
#include "trivial.h" #include <algorithm> #include <istream> #include <limits> #include <ranges> #include <utility> uint32_t count_increasing(std::istream &input) { return std::ranges::count_if(std::ranges::istream_view<uint32_t>(input), [prev = std::numeric_limits<uint32_t>::max()](uint32_t curr) mutable { return std::exchange(prev, curr) < curr; }); }
islaDevs/Coding-Homeworks
cpp/3BI/Loops/While/while.cpp
<reponame>islaDevs/Coding-Homeworks #include <iostream> #include <string> using namespace std; int main() { int i = 0; int n; string nome; cout<<"Inserire il proprio nome: "; cin>>nome; cout<<"Inserire il numero di volte: "; cin>>n; while (i<n) { cout<<nome <<endl; i++; } return 0; }
totallyGreg/Quicksilver
Quicksilver/Code-App/QSTaskViewer.h
#import <AppKit/AppKit.h> @interface QSTaskViewer : NSWindowController + (instancetype)sharedInstance; - (void)hideWindow:(id)sender; - (void)showWindow:(id)sender; - (void)toggleWindow:(id)sender; @end
agradipyahoo/smart-components
src/Form/FormElement.js
<gh_stars>0 import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { Subject } from 'rxjs/Subject'; import {getRuleValue} from './validators'; class FormElement extends PureComponent { constructor(props) { super(props); let { validations = [], propRules = [] } = this.props; this.change$ = new Subject(); this._changing = false; this.state = { errors: [], }; this.validations = validations.filter(item => item.element === undefined).map(function(rule, index) { return getRuleValue(rule); }); this.siblingValidations = validations.filter(item => item.element !== undefined).map(function(rule, index) { return getRuleValue(rule); }); this.propRules = propRules.map(function(rule, index) { return getRuleValue(rule); }); } subscribeToChange() { let debounceTime = this.props.debounceTime; if (debounceTime !== undefined) { this.changeSubscription = this.change$.debounceTime(debounceTime).subscribe(value => { this.updateValueStore(value); this._changing = false; }); } else { this.changeSubscription = this.change$.subscribe(value => this.updateValueStore(value)); } } subscribeToValidation() { let siblingsToBeValidated = this.siblingValidations; if (siblingsToBeValidated.length === 0) { return; } let self = this; this.validationSubscription = this.props.valueStore.on('change', (changed, fullObject) => { self.validateSiblingsOnChange(changed); self.handlePropRules(changed, fullObject); }); } onChange(event) { this.setValue(this.getValueFromNode(event.target)); } setValue(value, skipValidate) { let name = this.props.name; let toSet = { [name]: value }; if (this.props.options) { let multiSelect = this.multiSelect; let selectedOption = multiSelect ? this.props.options.filter(item => value.indexOf(item.id) > -1) : this.props.options.find(item => item.id === value); this.props.valueDetailStore.set({ [name]: selectedOption }); if (this.props.exposeSelection) { toSet[name + '_selection'] = selectedOption; } if (this.props.exposeName && selectedOption) { toSet[name + '_name'] = multiSelect ? selectedOption.map(v => v.name) : selectedOption.name; } } if (value === null) { if (this.props.exposeSelection) { toSet[name + '_selection'] = undefined; } if (this.props.exposename) { toSet[name + '_name'] = undefined; } } this._changing = true; this.change$.next(toSet); if (skipValidate !== true) { this.validateValue(value); } this.setState({ defaultValue: value }); } updateValueStore(toSet) { this.props.valueStore.set(toSet); } validateSiblingsOnChange(changed) { let toValidateIds = this.siblingValidations.map(item => item.element); let changedKey = Object.keys(changed)[0]; if (toValidateIds.indexOf(changedKey) > -1) { let errors = this.siblingValidations.filter(item => { return item.element === changedKey && item.func.call(this, item, changed[changedKey]) === false; }); this.props.errorStore.set({ [changedKey]: errors }); this.setState({ siblingErrors: errors }); } } handlePropRules(changed, fullObjecdt) { let toValidateIds = this.propRules.map(item => item.element); let changedKey = Object.keys(changed)[0]; if (toValidateIds.indexOf(changedKey) > -1) { let propValue = this.propRules.reduce((memo, rule) => { return !memo && rule.func.call(this, { value: fullObjecdt[rule.element] }, rule) === true; }, false); } } validateSiblings() { let changedKey = this.props.name; let valueStore = this.props.valueStore; let errors = this.siblingValidations.filter(item => { return item.func.call(this, item, valueStore.get(item.element)) === false; }); this.props.errorStore.set({ [changedKey]: errors }); this.setState({ errors: errors }); } validateValue(value) { let name = this.props.name; let errors = this.validations.filter(item => { return item.func.call(this, item, value) === false; }); this.props.errorStore.set({ [name]: errors }); this.setState({ errors: errors }); if (errors.length === 0) { this.validateSiblings(); } } getValueFromNode(node) { return node.value; } componentWillMount() { let self = this; let name = self.props.name; let valueStoreValue = this.props.valueStore.get(this.props.name); if (valueStoreValue === undefined) { self.props.valueStore.set({ [name]: self.props.defaultValue }); } self.props.elementIndex[name] = self; this.unsubscribeErrorStore = this.props.errorStore.on('forceValidate', function() { self.validateValue(self.props.valueStore.get(name)); }); this.subscribeToChange(); this.subscribeToValidation(); } componentWillUnmount() { if (this.unsubscribeErrorStore) { this.unsubscribeErrorStore(); } if (this.validationSubscription) { this.validationSubscription(); } if (this.changeSubscription) { this.changeSubscription.unsubscribe(); } } getDefaultValue() { return this._changing ? this.state.defaultValue : this.props.valueStore.get(this.props.name); } getFormClasses() { let classArray = ['form-group']; classArray.push('element'); classArray.push('element-type-' + this.props.type); classArray.push('element-' + this.props.name); let errors = this.getErrors(); if (errors.length > 0) { classArray.push('has-error'); } if (this.props.disabled) { classArray.push('disabled'); } return classArray.join(' '); } getErrors() { let errors = (this.state && this.state.errors) || []; let siblingErrors = (this.state && this.state.siblingErrors) || []; return errors.concat(siblingErrors); } getSiblingValue(siblingName) { return this.props.valueStore.get(siblingName); } render() { return <div>Base Element</div>; } } FormElement.propTypes = { type: PropTypes.string.isRequired, placeholder: PropTypes.string.isRequired, label: PropTypes.string.isRequired, defaultValue: PropTypes.string, options: PropTypes.array, valueStore: PropTypes.object.isRequired, errorStore: PropTypes.object.isRequired, valueDetailStore: PropTypes.object.isRequired, elementIndex: PropTypes.object.isRequired }; FormElement.defaultProps = { type: 'text', placeholder: 'Enter Text', label: 'Text Input', }; export default FormElement;
Coquinho/dali-core
automated-tests/src/dali-internal/utc-Dali-Internal-PinchGesture.cpp
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <dali-test-suite-utils.h> #include <dali/devel-api/events/pinch-gesture-devel.h> #include <dali/internal/event/events/pinch-gesture/pinch-gesture-impl.h> #include <dali/public-api/dali-core.h> #include <stdlib.h> #include <iostream> using namespace Dali; void utc_dali_internal_pinch_gesture_startup(void) { test_return_value = TET_UNDEF; } void utc_dali_internal_pinch_gesture_cleanup(void) { test_return_value = TET_PASS; } // Positive test case for a method int UtcDaliPinchGestureConstructor(void) { TestApplication application; // Reset all test adapter return codes PinchGesture gesture = DevelPinchGesture::New(GestureState::STARTED); DALI_TEST_EQUALS(GestureState::STARTED, gesture.GetState(), TEST_LOCATION); DALI_TEST_EQUALS(0.0f, gesture.GetScale(), TEST_LOCATION); DALI_TEST_EQUALS(0.0f, gesture.GetSpeed(), TEST_LOCATION); DALI_TEST_EQUALS(GestureType::PINCH, gesture.GetType(), TEST_LOCATION); PinchGesture gesture2 = DevelPinchGesture::New(GestureState::CONTINUING); DALI_TEST_EQUALS(GestureState::CONTINUING, gesture2.GetState(), TEST_LOCATION); DALI_TEST_EQUALS(0.0f, gesture2.GetScale(), TEST_LOCATION); DALI_TEST_EQUALS(0.0f, gesture2.GetSpeed(), TEST_LOCATION); DALI_TEST_EQUALS(GestureType::PINCH, gesture2.GetType(), TEST_LOCATION); PinchGesture gesture3 = DevelPinchGesture::New(GestureState::FINISHED); DALI_TEST_EQUALS(GestureState::FINISHED, gesture3.GetState(), TEST_LOCATION); DALI_TEST_EQUALS(0.0f, gesture3.GetScale(), TEST_LOCATION); DALI_TEST_EQUALS(0.0f, gesture3.GetSpeed(), TEST_LOCATION); DALI_TEST_EQUALS(GestureType::PINCH, gesture3.GetType(), TEST_LOCATION); // Test copy constructor GetImplementation(gesture3).SetScale(3.0f); GetImplementation(gesture3).SetSpeed(5.0f); PinchGesture pinch(gesture3); DALI_TEST_EQUALS(GestureState::FINISHED, pinch.GetState(), TEST_LOCATION); DALI_TEST_EQUALS(3.0f, pinch.GetScale(), TEST_LOCATION); DALI_TEST_EQUALS(5.0f, pinch.GetSpeed(), TEST_LOCATION); DALI_TEST_EQUALS(GestureType::PINCH, pinch.GetType(), TEST_LOCATION); // Test move constructor const auto refCount = gesture.GetObjectPtr()->ReferenceCount(); PinchGesture gesture4(std::move(gesture)); DALI_TEST_CHECK(!gesture); DALI_TEST_EQUALS(GestureType::PINCH, gesture4.GetType(), TEST_LOCATION); DALI_TEST_EQUALS(gesture4.GetBaseObject().ReferenceCount(), refCount, TEST_LOCATION); END_TEST; } int UtcDaliPinchGestureAssignment(void) { // Test Assignment operator PinchGesture gesture = DevelPinchGesture::New(GestureState::STARTED); DALI_TEST_EQUALS(GestureState::STARTED, gesture.GetState(), TEST_LOCATION); DALI_TEST_EQUALS(0.0f, gesture.GetScale(), TEST_LOCATION); DALI_TEST_EQUALS(0.0f, gesture.GetSpeed(), TEST_LOCATION); DALI_TEST_EQUALS(GestureType::PINCH, gesture.GetType(), TEST_LOCATION); PinchGesture gesture2 = DevelPinchGesture::New(GestureState::CONTINUING); DALI_TEST_EQUALS(GestureState::CONTINUING, gesture2.GetState(), TEST_LOCATION); DALI_TEST_EQUALS(0.0f, gesture2.GetScale(), TEST_LOCATION); DALI_TEST_EQUALS(0.0f, gesture2.GetSpeed(), TEST_LOCATION); DALI_TEST_EQUALS(GestureType::PINCH, gesture2.GetType(), TEST_LOCATION); GetImplementation(gesture2).SetScale(3.0f); GetImplementation(gesture2).SetSpeed(5.0f); gesture = gesture2; DALI_TEST_EQUALS(GestureState::CONTINUING, gesture.GetState(), TEST_LOCATION); DALI_TEST_EQUALS(3.0f, gesture.GetScale(), TEST_LOCATION); DALI_TEST_EQUALS(5.0f, gesture.GetSpeed(), TEST_LOCATION); DALI_TEST_EQUALS(GestureType::PINCH, gesture.GetType(), TEST_LOCATION); // Move assignment const auto refCount = gesture.GetObjectPtr()->ReferenceCount(); PinchGesture gesture3; DALI_TEST_EQUALS(gesture3, Gesture(), TEST_LOCATION); gesture3 = std::move(gesture); DALI_TEST_CHECK(!gesture); DALI_TEST_EQUALS(GestureType::PINCH, gesture3.GetType(), TEST_LOCATION); DALI_TEST_EQUALS(gesture3.GetBaseObject().ReferenceCount(), refCount, TEST_LOCATION); END_TEST; } int UtcDaliPinchGestureSetGetScaleP(void) { PinchGesture gesture = DevelPinchGesture::New(GestureState::STARTED); DALI_TEST_EQUALS(gesture.GetScale(), 0.0f, TEST_LOCATION); GetImplementation(gesture).SetScale(123.0f); DALI_TEST_EQUALS(gesture.GetScale(), 123.0f, TEST_LOCATION); END_TEST; } int UtcDaliPinchGestureSetGetSpeedP(void) { PinchGesture gesture = DevelPinchGesture::New(GestureState::STARTED); DALI_TEST_EQUALS(gesture.GetSpeed(), 0.0f, TEST_LOCATION); GetImplementation(gesture).SetSpeed(123.0f); DALI_TEST_EQUALS(gesture.GetSpeed(), 123.0f, TEST_LOCATION); END_TEST; } int UtcDaliPinchGestureSetGetScreenCenterPointP(void) { PinchGesture gesture = DevelPinchGesture::New(GestureState::STARTED); DALI_TEST_EQUALS(gesture.GetScreenCenterPoint(), Vector2::ZERO, TEST_LOCATION); GetImplementation(gesture).SetScreenCenterPoint(Vector2(123.0f, 321.0f)); DALI_TEST_EQUALS(gesture.GetScreenCenterPoint(), Vector2(123.0f, 321.0f), TEST_LOCATION); END_TEST; } int UtcDaliPinchGestureSetGetLocalCenterPointP(void) { PinchGesture gesture = DevelPinchGesture::New(GestureState::STARTED); DALI_TEST_EQUALS(gesture.GetLocalCenterPoint(), Vector2::ZERO, TEST_LOCATION); GetImplementation(gesture).SetLocalCenterPoint(Vector2(123.0f, 321.0f)); DALI_TEST_EQUALS(gesture.GetLocalCenterPoint(), Vector2(123.0f, 321.0f), TEST_LOCATION); END_TEST; }
ScalablyTyped/SlinkyTyped
c/connect-pg-simple/src/main/scala/typingsSlinky/connectPgSimple/mod.scala
package typingsSlinky.connectPgSimple import typingsSlinky.connectPgSimple.connectPgSimpleBooleans.`false` import typingsSlinky.express.mod.RequestHandler import typingsSlinky.expressServeStaticCore.mod.ParamsDictionary import typingsSlinky.expressServeStaticCore.mod.Query import typingsSlinky.expressSession.mod.SessionData import typingsSlinky.expressSession.mod.SessionOptions import typingsSlinky.expressSession.mod.Store import typingsSlinky.pg.mod.Pool import typingsSlinky.pg.mod.PoolConfig import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object mod { @JSImport("connect-pg-simple", JSImport.Namespace) @js.native def apply( session: js.Function1[ /* options */ js.UndefOr[SessionOptions], RequestHandler[ParamsDictionary, _, _, Query] ] ): js.Any = js.native @JSImport("connect-pg-simple", "PGStore") @js.native class PGStore () extends Store { def this(options: PGStoreOptions) = this() def close(): Unit = js.native def pruneSessions(): Unit = js.native def pruneSessions(callback: js.Function1[/* err */ js.Error, Unit]): Unit = js.native @JSName("touch") def touch_MPGStore(sid: String, session: SessionData): Unit = js.native @JSName("touch") def touch_MPGStore(sid: String, session: SessionData, callback: js.Function0[Unit]): Unit = js.native } @js.native trait PGStoreOptions extends StObject { var conObject: js.UndefOr[PoolConfig] = js.native // not typed to avoid dependency to "pg-promise" module (which includes its own types) var conString: js.UndefOr[String] = js.native var errorLog: js.UndefOr[js.Function1[/* repeated */ js.Any, Unit]] = js.native var pgPromise: js.UndefOr[js.Object] = js.native var pool: js.UndefOr[Pool] = js.native var pruneSessionInterval: js.UndefOr[`false` | Double] = js.native var schemaName: js.UndefOr[String] = js.native var tableName: js.UndefOr[String] = js.native var ttl: js.UndefOr[Double] = js.native } object PGStoreOptions { @scala.inline def apply(): PGStoreOptions = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[PGStoreOptions] } @scala.inline implicit class PGStoreOptionsMutableBuilder[Self <: PGStoreOptions] (val x: Self) extends AnyVal { @scala.inline def setConObject(value: PoolConfig): Self = StObject.set(x, "conObject", value.asInstanceOf[js.Any]) @scala.inline def setConObjectUndefined: Self = StObject.set(x, "conObject", js.undefined) @scala.inline def setConString(value: String): Self = StObject.set(x, "conString", value.asInstanceOf[js.Any]) @scala.inline def setConStringUndefined: Self = StObject.set(x, "conString", js.undefined) @scala.inline def setErrorLog(value: /* repeated */ js.Any => Unit): Self = StObject.set(x, "errorLog", js.Any.fromFunction1(value)) @scala.inline def setErrorLogUndefined: Self = StObject.set(x, "errorLog", js.undefined) @scala.inline def setPgPromise(value: js.Object): Self = StObject.set(x, "pgPromise", value.asInstanceOf[js.Any]) @scala.inline def setPgPromiseUndefined: Self = StObject.set(x, "pgPromise", js.undefined) @scala.inline def setPool(value: Pool): Self = StObject.set(x, "pool", value.asInstanceOf[js.Any]) @scala.inline def setPoolUndefined: Self = StObject.set(x, "pool", js.undefined) @scala.inline def setPruneSessionInterval(value: `false` | Double): Self = StObject.set(x, "pruneSessionInterval", value.asInstanceOf[js.Any]) @scala.inline def setPruneSessionIntervalUndefined: Self = StObject.set(x, "pruneSessionInterval", js.undefined) @scala.inline def setSchemaName(value: String): Self = StObject.set(x, "schemaName", value.asInstanceOf[js.Any]) @scala.inline def setSchemaNameUndefined: Self = StObject.set(x, "schemaName", js.undefined) @scala.inline def setTableName(value: String): Self = StObject.set(x, "tableName", value.asInstanceOf[js.Any]) @scala.inline def setTableNameUndefined: Self = StObject.set(x, "tableName", js.undefined) @scala.inline def setTtl(value: Double): Self = StObject.set(x, "ttl", value.asInstanceOf[js.Any]) @scala.inline def setTtlUndefined: Self = StObject.set(x, "ttl", js.undefined) } } }
Auzzy/pyinq
examples/test_skip.py
from pyinq.tags import skip,test,before,testClass @skip @test def test1(): assert False @test @skip def test2(): assert False @skip @before def fix1(): assert False @before @skip def fix2(): assert False @test def fix3(): assert False @testClass class Class1(object): @skip @test def clstest1(): assert False @test @skip def clstest2(): assert False @test def clstest3(): assert False skip(fix3) skip(Class1.clstest3) @skip @testClass class SkipClass1(object): @test def skip1test1(): assert False @test def skip1test2(): assert False @testClass @skip class SkipClass2(object): @test def skip2test1(): assert False @test def skip2test2(): assert False
enginedave/xmen
app/controllers/families.server.controller.js
<reponame>enginedave/xmen 'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Family = mongoose.model('Family'), _ = require('lodash'); /** * Create a Family */ exports.create = function(req, res) { var family = new Family(req.body); family.user = req.user; family.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(family); } }); }; /** * Show the current Family */ exports.read = function(req, res) { res.jsonp(req.family); }; /** * Update a Family */ exports.update = function(req, res) { var family = req.family ; family = _.extend(family , req.body); family.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(family); } }); }; /** * Delete an Family */ exports.delete = function(req, res) { var family = req.family ; family.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(family); } }); }; /** * List of Families */ exports.list = function(req, res) { Family.find().sort('-created').populate('user', 'displayName').exec(function(err, families) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(families); } }); }; /** * Family middleware */ exports.familyByID = function(req, res, next, id) { Family.findById(id).populate('user', 'displayName').exec(function(err, family) { if (err) return next(err); if (! family) return next(new Error('Failed to load Family ' + id)); req.family = family ; next(); }); }; /** * Family authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.family.user.id !== req.user.id) { return res.status(403).send('User is not authorized'); } next(); };
alectoraj/fluid-csv
fluid.csv/src/main/java/com/fluidapi/csv/reader/provider/deserializer/column/primitive/MapPrimitive.java
package com.fluidapi.csv.reader.provider.deserializer.column.primitive; import com.fluidapi.csv.reader.provider.deserializer.column.MapSafe; import com.fluidapi.csv.utility.ClassUtils; import com.fluidapi.csv.utility.MapSupport; public abstract class MapPrimitive<T> extends MapSafe<T> { /** * {@link MapSupport#register(Class, com.fluidapi.csv.function.MapConstructor)} * method to be only used by child classes to register support */ public final static MapSupport<MapPrimitive<?>> support = new MapSupport<>(); static { ClassUtils.load( MapBytePrimitive.class, MapShortPrimitive.class, MapIntPrimitive.class, MapLongPrimitive.class, MapFloatPrimitive.class, MapDoublePrimitive.class, MapCharacterPrimitive.class, MapBooleanPrimitive.class ); } }
psu-libraries/etda_workflow
spec/presenters/presenter_spec_helper.rb
<reponame>psu-libraries/etda_workflow require 'spec_helper' require 'support/rails' require 'support/database_cleaner' # require 'support/committee_factory' # require 'support/keyword_factory' # require 'support/factories' require 'support/fixture' require 'support/i18n' # require 'support/mail' require 'support/ldap_lookup' # require 'support/matchers/have_db_foreign_key' # require 'support/partner' require 'rails_helper'
Ewpratten/DeepSpace-Offseason
docs/html/dir_169123abe98eb20a2abc4d7bb66fbe3e.js
var dir_169123abe98eb20a2abc4d7bb66fbe3e = [ [ "RiologBackupTask.java", "RiologBackupTask_8java.html", [ [ "RiologBackupTask", "classfrc_1_1common_1_1tasks_1_1RiologBackupTask.html", "classfrc_1_1common_1_1tasks_1_1RiologBackupTask" ] ] ] ];
hailongz/kk-logic
logic/swagger.go
package logic import ( "log" "net/url" "strings" "github.com/hailongz/kk-lib/dynamic" "gopkg.in/yaml.v2" ) func init() { SetGlobalIgnoreKey("contentType") } type Swagger struct { scheme string host string basePath string } func NewSwagger(baseURL string) *Swagger { v := Swagger{} u, _ := url.Parse(baseURL) v.scheme = u.Scheme v.host = u.Host v.basePath = u.Path if v.basePath != "/" { if strings.HasSuffix(v.basePath, "/") { v.basePath = v.basePath[0 : len(v.basePath)-1] } } return &v } func (S *Swagger) getType(stype string) string { switch stype { case "int", "long", "integer": return "integer" case "float", "double", "number": return "number" case "bool", "boolean": return "boolean" case "file": return "file" } return "string" } func (S *Swagger) Object(store IStore) interface{} { v := map[string]interface{}{ "swagger": "2.0", "host": S.host, "basePath": S.basePath, "info": map[string]interface{}{ "title": "kk-logic", "version": "1.0", }, "schemes": []interface{}{ S.scheme, }, } paths := map[string]interface{}{} v["paths"] = paths store.Walk(func(path string) { app, err := store.Get(path) if err != nil { log.Println("[ERROR]", path, err) return } name := "/" + path[0:len(path)-4] + "json" input := dynamic.Get(app.Object(), "input") contentType := dynamic.StringValue(dynamic.Get(app.Object(), "contentType"), "application/json") method := dynamic.StringValue(dynamic.Get(input, "method"), "POST") in := "query" if method == "POST" { in = "formData" } parameters := []interface{}{} dynamic.Each(dynamic.Get(input, "fields"), func(key interface{}, field interface{}) bool { parameters = append(parameters, map[string]interface{}{ "name": dynamic.StringValue(dynamic.Get(field, "name"), ""), "description": dynamic.StringValue(dynamic.Get(field, "title"), ""), "in": in, "type": S.getType(dynamic.StringValue(dynamic.Get(field, "type"), "string")), "pattern": dynamic.StringValue(dynamic.Get(field, "pattern"), ""), "required": dynamic.BooleanValue(dynamic.Get(field, "required"), false), }) return true }) produces := []interface{}{"application/json"} if contentType != "application/json" { produces = append(produces, contentType) } consumes := []interface{}{"application/x-www-form-urlencoded"} if method == "POST" { consumes = append(consumes, "multipart/form-data") } object := map[string]interface{}{ "summary": dynamic.StringValue(dynamic.Get(app.Object(), "title"), ""), "produces": produces, "consumes": consumes, "parameters": parameters, "responses": map[string]interface{}{ "200": map[string]interface{}{ "description": "OK", }, }, } if method == "POST" { paths[name] = map[string]interface{}{"post": object} } else { paths[name] = map[string]interface{}{"get": object} } }) return v } func (S *Swagger) Marshal(store IStore) ([]byte, error) { return yaml.Marshal(S.Object(store)) }
alicegraziosi/semaphore
node_modules/angularjs-color-picker/test/e2e/show.protractor.js
<filename>node_modules/angularjs-color-picker/test/e2e/show.protractor.js var Page = require('../page-object.js'); describe('Options: ', () => { describe('Show Swatch: ', () => { beforeAll(() => { Page.openPage(); Page.waitTillPageLoaded(); }); it('Should show when clicking the swatch by default', () => { Page.swatch.click(); expect(Page.color_picker_panel.isDisplayed()).toEqual(true); }); it('Should not show when option is changed', () => { Page.show_swatch_field.$('[label="No"]').click(); Page.swatch.click(); expect(Page.color_picker_panel.isDisplayed()).toEqual(false); }); it('Should show again', () => { Page.show_swatch_field.$('[label="Yes"]').click(); Page.swatch.click(); expect(Page.color_picker_panel.isDisplayed()).toEqual(true); }); }); describe('Show Focus: ', () => { beforeAll(() => { Page.openPage(); Page.waitTillPageLoaded(); }); it('Should show when focusing by default', () => { Page.input_field.click(); expect(Page.color_picker_panel.isDisplayed()).toEqual(true); }); it('Should not show when option is changed', () => { Page.show_focus_field.$('[label="No"]').click(); Page.input_field.click(); expect(Page.color_picker_panel.isDisplayed()).toEqual(false); }); it('Should show again', () => { Page.show_focus_field.$('[label="Yes"]').click(); Page.input_field.click(); expect(Page.color_picker_panel.isDisplayed()).toEqual(true); }); }); });
liangshui999/WanAndroid
app/src/main/java/com/example/asus_cp/wanandroid/contract/DetailContract.java
package com.example.asus_cp.wanandroid.contract; import com.example.asus_cp.wanandroid.base.presenter.BasePresenter; import com.example.asus_cp.wanandroid.base.view.BaseView; public interface DetailContract { interface View extends BaseView{ } interface Presenter extends BasePresenter<DetailContract.View>{ } }
pousse-cafe/pousse-cafe-source
src/main/java/poussecafe/source/generation/AggregatePackage.java
package poussecafe.source.generation; import static java.util.Objects.requireNonNull; public class AggregatePackage { public String packageName() { return packageName; } private String packageName; public String aggregateName() { return aggregateName; } private String aggregateName; public AggregatePackage(String packageName, String aggregateName) { requireNonNull(packageName); this.packageName = packageName; requireNonNull(aggregateName); this.aggregateName = aggregateName; } }
ruifernando7/Fat-Burner
app/src/main/java/edu/stts/fatburner/ui/register/GoalActivity.java
package edu.stts.fatburner.ui.register; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.WindowManager; import android.widget.ImageButton; import android.widget.RadioButton; import edu.stts.fatburner.R; import edu.stts.fatburner.data.model.User; public class GoalActivity extends AppCompatActivity { private ImageButton btnNextGoal; RadioButton rd1, rd2, rd3, rd4, rd5; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().hide(); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_goal); btnNextGoal = findViewById(R.id.btnNextGoal); rd1 = findViewById(R.id.radioButton); rd2 = findViewById(R.id.radioButton2); rd3 = findViewById(R.id.radioButton3); rd4 = findViewById(R.id.radioButton4); rd5 = findViewById(R.id.radioButton5); } public void nextGoal(View v) { Intent intent = null; User userBaru = new User(); if(rd1.isChecked()) userBaru.setGoal(1); else if(rd2.isChecked()) userBaru.setGoal(2); else if(rd3.isChecked()) userBaru.setGoal(3); else if(rd4.isChecked()) userBaru.setGoal(4); else if(rd5.isChecked()) userBaru.setGoal(5); switch(v.getId()){ case R.id.btnNextGoal: intent = new Intent(this,GenderActivity.class); intent.putExtra("userBaru", userBaru); break; } if (intent != null) startActivity(intent); } }
qjclinux/DocxFactory
include/DocxFactory/DocxMerger/DocxMergerAltChunkField.h
#ifndef __DOCXFACTORY_DOCX_MERGER_ALT_CHUNK_FIELD_H__ #define __DOCXFACTORY_DOCX_MERGER_ALT_CHUNK_FIELD_H__ #include "DocxFactory/DocxMerger/DocxMergerField.h" namespace DocxFactory { using namespace std; class ZipFile; class UnzipFile; class DocxMergerPasteFieldGroup; class DocxMergerAltChunkField : public DocxMergerField { public: enum AltChunkType { TYPE_MHTML, TYPE_HTML, TYPE_RTF }; DocxMergerAltChunkField(); virtual ~DocxMergerAltChunkField(); virtual void save( DocxMergerPasteFieldGroup* p_pasteFieldGroup ); virtual void setClipboardValue( const string& p_value ); virtual void setClipboardValue( double p_value ); virtual void deserialize( UnzipFile* p_unzipFile ); AltChunkType getAltChunkType() const; protected: private: DocxMergerAltChunkField( const DocxMergerAltChunkField& p_other ); DocxMergerAltChunkField operator = ( const DocxMergerAltChunkField& p_other ); void insertAltChunk ( const string* p_value, AltChunkType p_type, string& p_fileRId ); void createPasteField ( const string& p_value, AltChunkType p_type ); void getMultiPart ( const string& p_str, string& m_multiPart ); bool getAttr ( const string& p_str, const size_t& p_len, size_t& p_pos, string& p_name, string& p_value ); bool getWord ( const string& p_str, const size_t& p_len, size_t& p_pos, string& p_keyword ); bool skipSpace ( const string& p_str, const size_t& p_len, size_t& p_pos ); AltChunkType m_altChunkType; string m_altChunkString1; string m_altChunkString2; }; }; #endif
tomato-300yen/coding
atcoder/abc/b119.py
n = int(input()) d = [input().split() for _ in range(n)] ans = 0 for x, u in d: x = float(x) if u == "JPY": ans += x else: ans += x * 380000 print(ans)
getkloudi/integration-wrapper-generator
out/bitbucket/src/api/SnippetApi.js
<reponame>getkloudi/integration-wrapper-generator<gh_stars>0 /** * Bitbucket API * Code against the Bitbucket API to automate simple tasks, embed Bitbucket data into your own site, build mobile or desktop apps, or even add custom UI add-ons into Bitbucket itself using the Connect framework. * * The version of the OpenAPI document: 2.0 * Contact: <EMAIL> * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. * */ import ApiClient from "../ApiClient"; import Error from '../model/Error'; /** * Snippet service. * @module api/SnippetApi * @version 1.2.0 */ export default class SnippetApi { /** * Constructs a new SnippetApi. * @alias module:api/SnippetApi * @class * @param {module:ApiClient} [apiClient] Optional API client implementation to use, * default to {@link module:ApiClient#instance} if unspecified. */ constructor(apiClient) { this.apiClient = apiClient || ApiClient.instance; } /** * Callback function to receive the result of the snippetsWorkspaceEncodedIdFilesPathGet operation. * @callback module:api/SnippetApi~snippetsWorkspaceEncodedIdFilesPathGetCallback * @param {String} error Error message, if any. * @param data This operation does not return a value. * @param {String} response The complete HTTP response. */ /** * Convenience resource for getting to a snippet's raw files without the need for first having to retrieve the snippet itself and having to pull out the versioned file links. * @param {String} path * @param {String} encodedId * @param {String} workspace This can either be the workspace ID (slug) or the workspace UUID surrounded by curly-braces, for example: `{workspace UUID}`. * @param {module:api/SnippetApi~snippetsWorkspaceEncodedIdFilesPathGetCallback} callback The callback function, accepting three arguments: error, data, response */ snippetsWorkspaceEncodedIdFilesPathGet(path, encodedId, workspace, callback) { let postBody = null; // verify the required parameter 'path' is set if (path === undefined || path === null) { throw new Error("Missing the required parameter 'path' when calling snippetsWorkspaceEncodedIdFilesPathGet"); } // verify the required parameter 'encodedId' is set if (encodedId === undefined || encodedId === null) { throw new Error("Missing the required parameter 'encodedId' when calling snippetsWorkspaceEncodedIdFilesPathGet"); } // verify the required parameter 'workspace' is set if (workspace === undefined || workspace === null) { throw new Error("Missing the required parameter 'workspace' when calling snippetsWorkspaceEncodedIdFilesPathGet"); } let pathParams = { 'path': path, 'encoded_id': encodedId, 'workspace': workspace }; let queryParams = { }; let headerParams = { }; let formParams = { }; let authNames = ['api_key', 'basic', 'oauth2']; let contentTypes = []; let accepts = ['application/json']; let returnType = null; return this.apiClient.callApi( '/snippets/{workspace}/{encoded_id}/files/{path}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, authNames, contentTypes, accepts, returnType, null, callback ); } }
zgoethel/mycelium
MyceliumCore/src/main/java/net/jibini/mycelium/route/RequestSwitch.java
package net.jibini.mycelium.route; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.jibini.mycelium.api.InternalRequest; import net.jibini.mycelium.api.Request; import net.jibini.mycelium.network.NetworkMember; import net.jibini.mycelium.resource.Checked; import net.jibini.mycelium.resource.MissingResourceException; import net.jibini.mycelium.thread.NamedThread; public class RequestSwitch { private Logger log = LoggerFactory.getLogger(getClass()); private UUID uuid = UUID.randomUUID(); private Map<String, NetworkMember> attached = new ConcurrentHashMap<>(); private String headerElement = "target"; private Checked<NetworkMember> defaultGateway = new Checked<NetworkMember>() .withName("Default Gateway"); private Map<String, JSONObject> targetRoutes = new ConcurrentHashMap<>(); private void routerLoop(NetworkMember member) { try { Request request = new InternalRequest().from(member.link().read()); JSONObject route = request.header().getJSONObject("route"); boolean hasExisting = route.has(uuid.toString()); String existing = hasExisting ? route.getString(uuid.toString()) : ""; route.put(uuid.toString(), member.address()); if (hasExisting) attached.get(existing).link().send(request); else { String target = request.header().getString(headerElement); if (attached.containsKey(target)) attached.get(target).link().send(request); else if (targetRoutes.containsKey(target)) { JSONObject routeAdds = targetRoutes.get(target); for (String key : routeAdds.keySet()) route.put(key, routeAdds.get(key)); target = route.getString(uuid.toString()); route.put(uuid.toString(), member.address()); attached.get(target).link().send(request); } else try { log.debug("No attachment found, resorting to default gateway"); defaultGateway().link().send(request); } catch (MissingResourceException ex) { throw new RoutingException("No attachment found for target '" + target + "'", ex); } } } catch (Throwable t) { if (System.getProperties().getOrDefault("verboseNetworking", false).equals("true")) log.warn("Error in routing request", t); } } public RequestSwitch withDefaultGateway(NetworkMember gateway) { this.defaultGateway.value(gateway); return this; } public RequestSwitch staticRoute(String target, JSONObject route) { this.targetRoutes.put(target, route); return this; } public RequestSwitch routeBy(String headerElement) { this.headerElement = headerElement; return this; } public RequestSwitch attach(NetworkMember member) { attached.put(member.address(), member); new NamedThread() .withName("RouterThread:" + member.address()) .asDaemon() .withRunnable(() -> { log.debug("Opened new switch connection"); while (member.link().isAlive()) { routerLoop(member); Thread.yield(); } log.debug("Switch connection died, removing"); attached.remove(member.address()); }) .start(); return this; } public NetworkMember defaultGateway() { return defaultGateway.value(); } }
vimiomori/vue-rails-tutorial
fishub-api-rails/app/views/catches/index.json.jbuilder
<reponame>vimiomori/vue-rails-tutorial<filename>fishub-api-rails/app/views/catches/index.json.jbuilder json.array! @catches, partial: 'catches/catch', as: :aCatch
fangke-ray/RVS-OGZ
rvs2.0/src/com/osh/rvs/bean/equipment/DeviceJigOrderDetailEntity.java
package com.osh.rvs.bean.equipment; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * 设备工具治具订单明细 * * @author liuxb * */ public class DeviceJigOrderDetailEntity implements Serializable { /** * */ private static final long serialVersionUID = 1651341345956068574L; /** * Key */ private String order_key; /** * 对象类别 */ private Integer object_type; /** * 设备工具品名ID */ private String device_type_id; /** * 型号/规格 */ private String model_name; /** * 系统编码 */ private String system_code; /** * 名称 */ private String name; /** * 受注方 */ private Integer order_from; /** * 数量 */ private Integer quantity; /** * 询价结果 ID */ private String order_invoice_id; /** * 申请者 */ private String applicator_id; /** * 理由/必要性 */ private String nesssary_reason; /** * 申请日期 */ private Date applicate_date; /** * 报价 ID */ private String quotation_id; /** * 重新订购纳期 */ private Date reorder_scheduled_date; /** * 收货时间 */ private Date recept_date; /** * 确认结果 */ private Integer confirm_flg; /** * 确认数量 */ private Integer confirm_quantity; /** * 验收日期 */ private Date inline_recept_date; /** * 验收人 */ private String inline_receptor_id; /** * 预算月 */ private String budget_month; /** * 预算说明 */ private String budget_description; /** * 发票号 */ private String invoice_no; /** * 发票收到日期 */ private Date invoice_date; // 报价单号 private String quotation_no; // 订单号 private String order_no; // 询价 private Integer order_invoice_flg; // 询价发送日期开始 private Date send_date_start; // 询价发送日期结束 private Date send_date_end; // 预计纳期开始 private Date scheduled_date_start; // 预计纳期结束 private Date scheduled_date_end; // 收货时间开始 private Date recept_date_start; // 收货时间结束 private Date recept_date_end; // 验收 private Integer inline_recept_flg; // 委托单号 private String entrust_no; // 询价 private BigDecimal order_price; // 金额 private BigDecimal total_order_price; // 原产单价 private BigDecimal origin_price; // 差异 private BigDecimal differ_price; // 申请者 private String applicator_operator_name; // 委托发送日期 private Date entrust_send_date; // 询价发送日期 private Date send_date; // 确认接收日期 private Date acquire_date; // 发送OSH日期 private Date delivery_osh_date; // 纳期 private Date scheduled_date; // 验收人 private String inline_receptor_operator_name; // 设备名称 private String device_type_name; // 现有备品数 private Integer available_inventory; private String comment; public String getOrder_key() { return order_key; } public void setOrder_key(String order_key) { this.order_key = order_key; } public Integer getObject_type() { return object_type; } public void setObject_type(Integer object_type) { this.object_type = object_type; } public String getDevice_type_id() { return device_type_id; } public void setDevice_type_id(String device_type_id) { this.device_type_id = device_type_id; } public String getModel_name() { return model_name; } public void setModel_name(String model_name) { this.model_name = model_name; } public String getSystem_code() { return system_code; } public void setSystem_code(String system_code) { this.system_code = system_code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getOrder_from() { return order_from; } public void setOrder_from(Integer order_from) { this.order_from = order_from; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public String getOrder_invoice_id() { return order_invoice_id; } public void setOrder_invoice_id(String order_invoice_id) { this.order_invoice_id = order_invoice_id; } public String getApplicator_id() { return applicator_id; } public void setApplicator_id(String applicator_id) { this.applicator_id = applicator_id; } public String getNesssary_reason() { return nesssary_reason; } public void setNesssary_reason(String nesssary_reason) { this.nesssary_reason = nesssary_reason; } public Date getApplicate_date() { return applicate_date; } public void setApplicate_date(Date applicate_date) { this.applicate_date = applicate_date; } public String getQuotation_id() { return quotation_id; } public void setQuotation_id(String quotation_id) { this.quotation_id = quotation_id; } public Date getReorder_scheduled_date() { return reorder_scheduled_date; } public void setReorder_scheduled_date(Date reorder_scheduled_date) { this.reorder_scheduled_date = reorder_scheduled_date; } public Date getRecept_date() { return recept_date; } public void setRecept_date(Date recept_date) { this.recept_date = recept_date; } public Integer getConfirm_flg() { return confirm_flg; } public void setConfirm_flg(Integer confirm_flg) { this.confirm_flg = confirm_flg; } public Date getInline_recept_date() { return inline_recept_date; } public void setInline_recept_date(Date inline_recept_date) { this.inline_recept_date = inline_recept_date; } public String getInline_receptor_id() { return inline_receptor_id; } public void setInline_receptor_id(String inline_receptor_id) { this.inline_receptor_id = inline_receptor_id; } public String getBudget_month() { return budget_month; } public void setBudget_month(String budget_month) { this.budget_month = budget_month; } public String getBudget_description() { return budget_description; } public void setBudget_description(String budget_description) { this.budget_description = budget_description; } public String getInvoice_no() { return invoice_no; } public void setInvoice_no(String invoice_no) { this.invoice_no = invoice_no; } public Date getInvoice_date() { return invoice_date; } public void setInvoice_date(Date invoice_date) { this.invoice_date = invoice_date; } public String getQuotation_no() { return quotation_no; } public void setQuotation_no(String quotation_no) { this.quotation_no = quotation_no; } public String getOrder_no() { return order_no; } public void setOrder_no(String order_no) { this.order_no = order_no; } public Integer getOrder_invoice_flg() { return order_invoice_flg; } public void setOrder_invoice_flg(Integer order_invoice_flg) { this.order_invoice_flg = order_invoice_flg; } public Date getSend_date_start() { return send_date_start; } public void setSend_date_start(Date send_date_start) { this.send_date_start = send_date_start; } public Date getSend_date_end() { return send_date_end; } public void setSend_date_end(Date send_date_end) { this.send_date_end = send_date_end; } public Date getScheduled_date_start() { return scheduled_date_start; } public void setScheduled_date_start(Date scheduled_date_start) { this.scheduled_date_start = scheduled_date_start; } public Date getScheduled_date_end() { return scheduled_date_end; } public void setScheduled_date_end(Date scheduled_date_end) { this.scheduled_date_end = scheduled_date_end; } public Date getRecept_date_start() { return recept_date_start; } public void setRecept_date_start(Date recept_date_start) { this.recept_date_start = recept_date_start; } public Date getRecept_date_end() { return recept_date_end; } public void setRecept_date_end(Date recept_date_end) { this.recept_date_end = recept_date_end; } public Integer getInline_recept_flg() { return inline_recept_flg; } public void setInline_recept_flg(Integer inline_recept_flg) { this.inline_recept_flg = inline_recept_flg; } public String getEntrust_no() { return entrust_no; } public void setEntrust_no(String entrust_no) { this.entrust_no = entrust_no; } public BigDecimal getOrder_price() { return order_price; } public void setOrder_price(BigDecimal order_price) { this.order_price = order_price; } public BigDecimal getTotal_order_price() { return total_order_price; } public void setTotal_order_price(BigDecimal total_order_price) { this.total_order_price = total_order_price; } public BigDecimal getOrigin_price() { return origin_price; } public void setOrigin_price(BigDecimal origin_price) { this.origin_price = origin_price; } public BigDecimal getDiffer_price() { return differ_price; } public void setDiffer_price(BigDecimal differ_price) { this.differ_price = differ_price; } public String getApplicator_operator_name() { return applicator_operator_name; } public void setApplicator_operator_name(String applicator_operator_name) { this.applicator_operator_name = applicator_operator_name; } public Date getEntrust_send_date() { return entrust_send_date; } public void setEntrust_send_date(Date entrust_send_date) { this.entrust_send_date = entrust_send_date; } public Date getSend_date() { return send_date; } public void setSend_date(Date send_date) { this.send_date = send_date; } public Date getAcquire_date() { return acquire_date; } public void setAcquire_date(Date acquire_date) { this.acquire_date = acquire_date; } public Date getDelivery_osh_date() { return delivery_osh_date; } public void setDelivery_osh_date(Date delivery_osh_date) { this.delivery_osh_date = delivery_osh_date; } public Date getScheduled_date() { return scheduled_date; } public void setScheduled_date(Date scheduled_date) { this.scheduled_date = scheduled_date; } public String getInline_receptor_operator_name() { return inline_receptor_operator_name; } public void setInline_receptor_operator_name(String inline_receptor_operator_name) { this.inline_receptor_operator_name = inline_receptor_operator_name; } public String getDevice_type_name() { return device_type_name; } public void setDevice_type_name(String device_type_name) { this.device_type_name = device_type_name; } public Integer getAvailable_inventory() { return available_inventory; } public void setAvailable_inventory(Integer available_inventory) { this.available_inventory = available_inventory; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public Integer getConfirm_quantity() { return confirm_quantity; } public void setConfirm_quantity(Integer confirm_quantity) { this.confirm_quantity = confirm_quantity; } }
mimifitz/IOMED
node_modules/@elastic/eui/test-env/components/form/range/range_highlight.js
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.EuiRangeHighlight = void 0; var _react = _interopRequireDefault(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _classnames = _interopRequireDefault(require("classnames")); /* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var EuiRangeHighlight = function EuiRangeHighlight(_ref) { var className = _ref.className, hasFocus = _ref.hasFocus, showTicks = _ref.showTicks, lowerValue = _ref.lowerValue, upperValue = _ref.upperValue, max = _ref.max, min = _ref.min, compressed = _ref.compressed, background = _ref.background, onClick = _ref.onClick; // Calculate the width the range based on value // const rangeWidth = (value - min) / (max - min); var leftPosition = (lowerValue - min) / (max - min); var rangeWidth = (upperValue - lowerValue) / (max - min); var rangeWidthStyle = { background: background, marginLeft: "".concat(leftPosition * 100, "%"), width: "".concat(rangeWidth * 100, "%") }; var classes = (0, _classnames.default)('euiRangeHighlight', { 'euiRangeHighlight--hasTicks': showTicks, 'euiRangeHighlight--compressed': compressed }, className); var progressClasses = (0, _classnames.default)('euiRangeHighlight__progress', { 'euiRangeHighlight__progress--hasFocus': hasFocus }); return _react.default.createElement("div", { className: classes, onClick: onClick }, _react.default.createElement("div", { className: progressClasses, style: rangeWidthStyle })); }; exports.EuiRangeHighlight = EuiRangeHighlight; EuiRangeHighlight.propTypes = { className: _propTypes.default.string, background: _propTypes.default.string, compressed: _propTypes.default.bool, hasFocus: _propTypes.default.bool, showTicks: _propTypes.default.bool, lowerValue: _propTypes.default.number.isRequired, upperValue: _propTypes.default.number.isRequired, max: _propTypes.default.number.isRequired, min: _propTypes.default.number.isRequired, onClick: _propTypes.default.func }; EuiRangeHighlight.__docgenInfo = { "description": "", "methods": [], "displayName": "EuiRangeHighlight", "props": { "className": { "type": { "name": "string" }, "required": false, "description": "" }, "background": { "type": { "name": "string" }, "required": false, "description": "" }, "compressed": { "type": { "name": "bool" }, "required": false, "description": "" }, "hasFocus": { "type": { "name": "bool" }, "required": false, "description": "" }, "showTicks": { "type": { "name": "bool" }, "required": false, "description": "" }, "lowerValue": { "type": { "name": "number" }, "required": true, "description": "" }, "upperValue": { "type": { "name": "number" }, "required": true, "description": "" }, "max": { "type": { "name": "number" }, "required": true, "description": "" }, "min": { "type": { "name": "number" }, "required": true, "description": "" }, "onClick": { "type": { "name": "func" }, "required": false, "description": "" } } };
MelhorEquipaBackend/spring_boot
src/main/java/com/training/springbootbuyitem/error/GreedyBuyerException.java
<filename>src/main/java/com/training/springbootbuyitem/error/GreedyBuyerException.java<gh_stars>0 package com.training.springbootbuyitem.error; public class GreedyBuyerException extends RuntimeException { public GreedyBuyerException(int cartQuantity, String itemName, int stockQuantity) { super(String.format("You ordered %d '%s' but there are only %s in stock", cartQuantity, itemName, stockQuantity)); } }
satroutr/poppy
poppy/transport/pecan/hooks/error.py
<reponame>satroutr/poppy<gh_stars>1-10 # Copyright (c) 2014 Rackspace, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. import json import logging from oslo_log import log from pecan import hooks import webob LOG = log.getLogger(__name__) class ErrorHook(hooks.PecanHook): '''Intercepts all errors during request fulfillment and logs them.''' def on_error(self, state, exception): '''Fires off when an error happens during a request. :param state: The Pecan state for the current request. :type state: pecan.core.state :param exception: The exception that was raised. :type exception: Exception :returns: webob.Response -- JSON response with the error message. ''' exception_payload = { 'status': 500, } exception_str = u'{0}'.format(exception) message = { 'message': ( 'The server encountered an unexpected condition' ' which prevented it from fulfilling the request.' ) } log_level = logging.ERROR # poppy does not have internal exception/external exceptions # yet, so just catch the HTTPException from pecan.abort # and send out a a json body LOG.log( log_level, u'Exception message: {0}'.format(exception_str), exc_info=True, extra=exception_payload ) if hasattr(exception, 'status'): exception_payload['status'] = exception.status exception_json = exception_str try: exception_json = json.loads(exception_json) except Exception: pass message['message'] = exception_json return webob.Response( json.dumps(message), status=exception_payload['status'], content_type='application/json' )
ds201891/choco-solver
solver/src/main/java/org/chocosolver/solver/constraints/nary/nvalue/amnv/mis/MDRk.java
/* * This file is part of choco-solver, http://choco-solver.org/ * * Copyright (c) 2020, IMT Atlantique. All rights reserved. * * Licensed under the BSD 4-clause license. * * See LICENSE file in the project root for full license information. */ package org.chocosolver.solver.constraints.nary.nvalue.amnv.mis; import org.chocosolver.util.objects.graphs.UndirectedGraph; import org.chocosolver.util.objects.setDataStructures.ISetIterator; import java.util.Random; /** * Min Degree + Random k heuristic * * @author <NAME> * @since 01/01/2014 */ public class MDRk extends MD { //*********************************************************************************** // VARIABLES //*********************************************************************************** protected int k, iter; protected Random rd; //*********************************************************************************** // CONSTRUCTORS //*********************************************************************************** /** * Creates an instance of the Min Degree + Random k heuristic to compute independent sets on graph * * @param graph the grah * @param k number of random iterations */ public MDRk(UndirectedGraph graph, int k) { super(graph); this.k = k; this.rd = new Random(0); } /** * Creates an instance of the Min Degree + Random k heuristic to compute independent sets on graph * * @param graph the graph */ public MDRk(UndirectedGraph graph) { this(graph, Rk.defaultKValue); } //*********************************************************************************** // METHODS //*********************************************************************************** @Override public void prepare() { iter = 0; } @Override public void computeMIS() { iter++; if (iter == 1) { super.computeMIS(); } else { computeMISRk(); } } protected void computeMISRk() { iter++; out.clear(); inMIS.clear(); while (out.cardinality() < n) { int nb = rd.nextInt(n - out.cardinality()); int idx = out.nextClearBit(0); for (int i = idx; i >= 0 && i < n && nb >= 0; i = out.nextClearBit(i + 1)) { idx = i; nb--; } inMIS.set(idx); out.set(idx); ISetIterator nei = graph.getNeighOf(idx).iterator(); while (nei.hasNext()){ out.set(nei.nextInt()); } } } @Override public boolean hasNextMIS() { return iter < k; } }
zvam1/gitlab-on-heroku
spec/services/jira_import/cloud_users_mapper_service_spec.rb
<reponame>zvam1/gitlab-on-heroku # frozen_string_literal: true require 'spec_helper' RSpec.describe JiraImport::CloudUsersMapperService do let(:start_at) { 7 } let(:url) { "/rest/api/2/users?maxResults=50&startAt=#{start_at}" } let(:jira_users) do [ { 'accountId' => 'abcd', 'displayName' => 'user1' }, { 'accountId' => 'efg' }, { 'accountId' => 'hij', 'displayName' => 'user3', 'emailAddress' => '<EMAIL>' } ] end describe '#execute' do it_behaves_like 'mapping jira users' end end
colorshifter/caaers
caAERS/software/core/src/main/java/gov/nih/nci/cabig/caaers/esb/client/impl/AdeersSubmissionResponseMessageProcessor.java
<reponame>colorshifter/caaers /******************************************************************************* * Copyright SemanticBits, Northwestern University and Akaza Research * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/caaers/LICENSE.txt for details. ******************************************************************************/ package gov.nih.nci.cabig.caaers.esb.client.impl; import gov.nih.nci.cabig.caaers.CaaersSystemException; import gov.nih.nci.cabig.caaers.domain.report.Report; import gov.nih.nci.cabig.caaers.esb.client.ResponseMessageProcessor; import java.util.List; import java.util.Locale; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jdom.Element; import org.jdom.Namespace; import org.springframework.transaction.annotation.Transactional; /** * Will handle the responses related to report submission. * * * @author Srini * @author <NAME> * */ /* * BJ : Messages read from resource files. * BJ : TODO copy the testcases checked in at r10219 */ public class AdeersSubmissionResponseMessageProcessor extends ResponseMessageProcessor{ protected final Log log = LogFactory.getLog(getClass()); @Override @Transactional public void processMessage(String message) throws CaaersSystemException { log.debug("AdeersSubmissionResponseMessageProcessor - message recieved"); Element jobInfo = this.getResponseElement(message,"submitAEDataXMLAsAttachmentResponse","AEReportJobInfo"); Namespace emptyNS=null; for (Object obj:jobInfo.getChildren()) { Element e = (Element)obj; if (e.getName().equals("CAEERS_AEREPORT_ID")) { emptyNS = e.getNamespace(); } } log.debug("got JobInfo"); String caaersAeReportId = jobInfo.getChild("CAEERS_AEREPORT_ID",emptyNS).getValue(); log.debug("ID 1 : " + caaersAeReportId); String reportId = jobInfo.getChild("REPORT_ID",emptyNS).getValue(); log.debug("ID 2 : " + reportId); String submitterEmail = jobInfo.getChild("SUBMITTER_EMAIL",emptyNS).getValue(); log.debug("email : " + submitterEmail); Report r = reportDao.getById(Integer.parseInt(reportId)); // buld error messages StringBuffer sb = new StringBuffer(); boolean success = true; boolean communicationError = false; String ticketNumber = ""; String url = ""; try { if (jobInfo.getChild("reportStatus").getValue().equals("SUCCESS")) { ticketNumber = jobInfo.getChild("ticketNumber").getValue(); url = jobInfo.getChild("reportURL").getValue(); String submissionMessage = messageSource.getMessage("successful.reportSubmission.message", new Object[]{String.valueOf(r.getLastVersion().getId()), ticketNumber, url}, Locale.getDefault()); sb.append(submissionMessage); }else{ success = false; List<Element> exceptions = jobInfo.getChildren("jobExceptions"); //find the exception elements if(CollectionUtils.isNotEmpty(exceptions)){ StringBuffer exceptionMsgBuffer = new StringBuffer(); for (Element ex : exceptions) { exceptionMsgBuffer.append(ex.getChild("code").getValue()).append( " - ").append(ex.getChild("description").getValue()).append("\n"); if (ex.getChild("code").getValue().equals("caAERS-adEERS : COMM_ERR")) { communicationError=true; } } String submissionMessage = messageSource.getMessage("failed.reportSubmission.message", new Object[]{String.valueOf(r.getLastVersion().getId()), exceptionMsgBuffer.toString()}, Locale.getDefault()); sb.append(submissionMessage); }//if exceptions } if (jobInfo.getChild("comments") != null) { String commentsMessage = messageSource.getMessage("comments.reportSubmission.message", new Object[]{jobInfo.getChild("comments").getValue()}, Locale.getDefault()); sb.append(commentsMessage); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // Notify submitter try { String messages = sb.toString(); log.debug("Calling notfication service .."); this.getMessageNotificationService().sendNotificationToReporter(submitterEmail, messages, caaersAeReportId, reportId, success, ticketNumber, url,communicationError); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
yhhcg/ibuscloud-ui
demo/src/AppFrame/index.js
import React from 'react'; import {hot} from 'react-hot-loader'; import Layout from 'ibuscloud-ui/Layout'; import Navs from './Navs'; import Router from '../router'; function AppFrame(props) { return <Layout contentComponent={<Router />} footerComponent="公交云 DTCHUXING ©2018 - 2019" siderComponent={<Navs />} />; } AppFrame.propTypes = { }; export default hot(module)(AppFrame);
hakanmhmd/algorithms-and-data-structures
src/main/java/BitManipulation/ToggleBits.java
package BitManipulation; /** * Toggle all the bits to the right of the most significant bit (MSB including) */ public class ToggleBits { public static void main(String[] args) { int n = 50; //110010 -> 1101 System.out.println(toggleBits(n)); } private static int toggleBits(int n) { if(n == 0) return 1; int nextSetBit = 1; int solution = 0; while(n != 0){ int bit = n & 1; // LSB if(bit == 0){ solution |= nextSetBit; } nextSetBit <<= 1; n >>>= 1; // unsigned right shift } return solution; } }
ruffkat/automatiq
spring-base/src/test/java/io/webdevice/settings/BadSettingsBinder.java
package io.webdevice.settings; import org.springframework.core.env.ConfigurableEnvironment; public class BadSettingsBinder implements SettingsBinder { public BadSettingsBinder() { throw new IllegalStateException("not-good"); } @Override public Settings from(ConfigurableEnvironment environment) { return null; } }
baophucct/neon-wallet
app/hocs/helpers/pureStrategy.js
<filename>app/hocs/helpers/pureStrategy.js // @flow import { progressValues, type Progress } from 'spunky' import { map, uniq, find } from 'lodash-es' const { INITIAL, LOADING, LOADED, FAILED } = progressValues function getProgress(actionState: Object) { return actionState.progress || INITIAL } export default function pureStrategy(actionStates: Array<Object>): Progress { const currentProgresses = uniq(map(actionStates, getProgress)) const prioritizedProgress = find( [INITIAL, FAILED, LOADING, LOADED], progress => currentProgresses.includes(progress), ) return prioritizedProgress || INITIAL }
duswo5310/finalproject
finalproject/src/main/java/com/kh/finalproject/repository/CouponDaoImpl.java
package com.kh.finalproject.repository; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.kh.finalproject.entity.CouponDto; import com.kh.finalproject.service.CouponService; @Repository public class CouponDaoImpl implements CouponDao { @Autowired private SqlSession sqlSession; // 전체 쿠폰 등록 @Override public void registA(CouponDto couponDto) { sqlSession.insert("coupon.registA", couponDto); } // 지점 쿠폰 등록 @Override public void registB(CouponDto couponDto) { sqlSession.insert("coupon.registB", couponDto); } // 쿠폰 목록 조회 @Override public List<CouponDto> getList(String order) { return sqlSession.selectList("coupon.getListA", order); } public List<CouponDto> getList(Map<String, Object> param) { return sqlSession.selectList("coupon.getListB", param); } // 쿠폰 그룹번호 추출 @Override public int getGroupSeq() { return sqlSession.selectOne("coupon.getGroupSeq"); } // 쿠폰 삭제 @Override public void delete(int group_no) { sqlSession.delete("coupon.delete", group_no); } // 그룹번호 일치하는 지점번호 조회 @Override public List<CouponDto> getCouponList(String order) { return sqlSession.selectList("coupon.getCouponList", order); } // 시작일이 오늘인 쿠폰 조회 @Override public List<CouponDto> todayStart() { return sqlSession.selectList("coupon.todayStart"); } // 종료일이 오늘인 쿠폰 조회 @Override public List<CouponDto> todayFinish() { return sqlSession.selectList("coupon.todayFinish"); } }
NeutrinoLiu/rocket-chip
chisel3/src/main/scala/chisel3/compatibility.scala
// See LICENSE for license details. /** The Chisel compatibility package allows legacy users to continue using the `Chisel` (capital C) package name * while moving to the more standard package naming convention `chisel3` (lowercase c). */ package object Chisel { // scalastyle:ignore package.object.name import chisel3.internal.firrtl.Width import scala.language.experimental.macros import scala.annotation.StaticAnnotation import scala.annotation.compileTimeOnly import scala.language.implicitConversions implicit val defaultCompileOptions = chisel3.core.ExplicitCompileOptions.NotStrict abstract class Direction case object INPUT extends Direction case object OUTPUT extends Direction case object NODIR extends Direction val Input = chisel3.core.Input val Output = chisel3.core.Output object Flipped { def apply[T<:Data](target: T): T = chisel3.core.Flipped[T](target) } implicit class AddDirectionToData[T<:Data](target: T) { def asInput: T = chisel3.core.Input(target) def asOutput: T = chisel3.core.Output(target) def flip(): T = chisel3.core.Flipped(target) } implicit class AddDirMethodToData[T<:Data](target: T) { import chisel3.core.{DataMirror, ActualDirection, requireIsHardware} def dir: Direction = { requireIsHardware(target) // This has the side effect of calling _autoWrapPorts target match { case e: Element => DataMirror.directionOf(e) match { case ActualDirection.Output => OUTPUT case ActualDirection.Input => INPUT case _ => NODIR } case _ => NODIR } } } implicit class cloneTypeable[T <: Data](target: T) { import chisel3.core.DataMirror def chiselCloneType: T = { DataMirror.internal.chiselTypeClone(target).asInstanceOf[T] } } type ChiselException = chisel3.internal.ChiselException type Data = chisel3.core.Data object Wire extends chisel3.core.WireFactory { import chisel3.core.CompileOptions def apply[T <: Data](dummy: Int = 0, init: T)(implicit compileOptions: CompileOptions): T = chisel3.core.WireInit(init) def apply[T <: Data](t: T, init: T)(implicit compileOptions: CompileOptions): T = chisel3.core.WireInit(t, init) } object Clock { def apply(): Clock = new Clock def apply(dir: Direction): Clock = { val result = apply() dir match { case INPUT => chisel3.core.Input(result) case OUTPUT => chisel3.core.Output(result) case _ => result } } } type Clock = chisel3.core.Clock // Implicit conversion to allow fromBits because it's being deprecated in chisel3 implicit class fromBitsable[T <: Data](data: T) { import chisel3.core.CompileOptions import chisel3.internal.sourceinfo.SourceInfo /** Creates an new instance of this type, unpacking the input Bits into * structured data. * * This performs the inverse operation of toBits. * * @note does NOT assign to the object this is called on, instead creates * and returns a NEW object (useful in a clone-and-assign scenario) * @note does NOT check bit widths, may drop bits during assignment * @note what fromBits assigs to must have known widths */ def fromBits(that: Bits)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): T = { that.asTypeOf(data) } } type Aggregate = chisel3.core.Aggregate object Vec extends chisel3.core.VecFactory { import chisel3.core.CompileOptions import chisel3.internal.sourceinfo._ @deprecated("Vec argument order should be size, t; this will be removed by the official release", "chisel3") def apply[T <: Data](gen: T, n: Int)(implicit compileOptions: CompileOptions): Vec[T] = apply(n, gen) /** Creates a new [[Vec]] of length `n` composed of the result of the given * function repeatedly applied. * * @param n number of elements (and the number of times the function is * called) * @param gen function that generates the [[Data]] that becomes the output * element */ def fill[T <: Data](n: Int)(gen: => T)(implicit compileOptions: CompileOptions): Vec[T] = apply(Seq.fill(n)(gen)) def apply[T <: Data](elts: Seq[T]): Vec[T] = macro VecTransform.apply_elts /** @group SourceInfoTransformMacro */ def do_apply[T <: Data](elts: Seq[T])(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Vec[T] = chisel3.core.VecInit(elts) def apply[T <: Data](elt0: T, elts: T*): Vec[T] = macro VecTransform.apply_elt0 /** @group SourceInfoTransformMacro */ def do_apply[T <: Data](elt0: T, elts: T*) (implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Vec[T] = chisel3.core.VecInit(elt0 +: elts.toSeq) def tabulate[T <: Data](n: Int)(gen: (Int) => T): Vec[T] = macro VecTransform.tabulate /** @group SourceInfoTransformMacro */ def do_tabulate[T <: Data](n: Int)(gen: (Int) => T) (implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): Vec[T] = chisel3.core.VecInit.tabulate(n)(gen) } type Vec[T <: Data] = chisel3.core.Vec[T] type VecLike[T <: Data] = chisel3.core.VecLike[T] type Record = chisel3.core.Record type Bundle = chisel3.core.Bundle val assert = chisel3.core.assert val stop = chisel3.core.stop /** This contains literal constructor factory methods that are deprecated as of Chisel3. */ trait UIntFactory extends chisel3.core.UIntFactory { /** Create a UInt literal with inferred width. */ def apply(n: String): UInt = n.asUInt /** Create a UInt literal with fixed width. */ def apply(n: String, width: Int): UInt = n.asUInt(width.W) /** Create a UInt literal with specified width. */ def apply(value: BigInt, width: Width): UInt = value.asUInt(width) /** Create a UInt literal with fixed width. */ def apply(value: BigInt, width: Int): UInt = value.asUInt(width.W) /** Create a UInt with a specified width - compatibility with Chisel2. */ // NOTE: This resolves UInt(width = 32) def apply(dir: Option[Direction] = None, width: Int): UInt = apply(width.W) /** Create a UInt literal with inferred width.- compatibility with Chisel2. */ def apply(value: BigInt): UInt = value.asUInt /** Create a UInt with a specified direction and width - compatibility with Chisel2. */ def apply(dir: Direction, width: Int): UInt = apply(dir, width.W) /** Create a UInt with a specified direction, but unspecified width - compatibility with Chisel2. */ def apply(dir: Direction): UInt = apply(dir, Width()) def apply(dir: Direction, width: Width): UInt = { val result = apply(width) dir match { case INPUT => chisel3.core.Input(result) case OUTPUT => chisel3.core.Output(result) case NODIR => result } } /** Create a UInt with a specified width */ def width(width: Int): UInt = apply(width.W) /** Create a UInt port with specified width. */ def width(width: Width): UInt = apply(width) } /** This contains literal constructor factory methods that are deprecated as of Chisel3. */ trait SIntFactory extends chisel3.core.SIntFactory { /** Create a SInt type or port with fixed width. */ def width(width: Int): SInt = apply(width.W) /** Create an SInt type with specified width. */ def width(width: Width): SInt = apply(width) /** Create an SInt literal with inferred width. */ def apply(value: BigInt): SInt = value.asSInt /** Create an SInt literal with fixed width. */ def apply(value: BigInt, width: Int): SInt = value.asSInt(width.W) /** Create an SInt literal with specified width. */ def apply(value: BigInt, width: Width): SInt = value.asSInt(width) def Lit(value: BigInt): SInt = value.asSInt // scalastyle:ignore method.name def Lit(value: BigInt, width: Int): SInt = value.asSInt(width.W) // scalastyle:ignore method.name /** Create a SInt with a specified width - compatibility with Chisel2. */ def apply(dir: Option[Direction] = None, width: Int): SInt = apply(width.W) /** Create a SInt with a specified direction and width - compatibility with Chisel2. */ def apply(dir: Direction, width: Int): SInt = apply(dir, width.W) /** Create a SInt with a specified direction, but unspecified width - compatibility with Chisel2. */ def apply(dir: Direction): SInt = apply(dir, Width()) def apply(dir: Direction, width: Width): SInt = { val result = apply(width) dir match { case INPUT => chisel3.core.Input(result) case OUTPUT => chisel3.core.Output(result) case NODIR => result } } } /** This contains literal constructor factory methods that are deprecated as of Chisel3. */ trait BoolFactory extends chisel3.core.BoolFactory { /** Creates Bool literal. */ def apply(x: Boolean): Bool = x.B /** Create a UInt with a specified direction and width - compatibility with Chisel2. */ def apply(dir: Direction): Bool = { val result = apply() dir match { case INPUT => chisel3.core.Input(result) case OUTPUT => chisel3.core.Output(result) case NODIR => result } } } type Element = chisel3.core.Element type Bits = chisel3.core.Bits object Bits extends UIntFactory type Num[T <: Data] = chisel3.core.Num[T] type UInt = chisel3.core.UInt object UInt extends UIntFactory type SInt = chisel3.core.SInt object SInt extends SIntFactory type Bool = chisel3.core.Bool object Bool extends BoolFactory val Mux = chisel3.core.Mux type Reset = chisel3.core.Reset implicit def resetToBool(reset: Reset): Bool = reset.asBool import chisel3.core.Param abstract class BlackBox(params: Map[String, Param] = Map.empty[String, Param]) extends chisel3.core.BlackBox(params) { // This class auto-wraps the BlackBox with IO(...), allowing legacy code (where IO(...) wasn't // required) to build. override def _compatAutoWrapPorts(): Unit = { // scalastyle:ignore method.name if (!_compatIoPortBound()) { _bindIoInPlace(io) } } } val Mem = chisel3.core.Mem type MemBase[T <: Data] = chisel3.core.MemBase[T] type Mem[T <: Data] = chisel3.core.Mem[T] val SeqMem = chisel3.core.SyncReadMem type SeqMem[T <: Data] = chisel3.core.SyncReadMem[T] import chisel3.core.CompileOptions abstract class CompatibilityModule(implicit moduleCompileOptions: CompileOptions) extends chisel3.core.LegacyModule { // This class auto-wraps the Module IO with IO(...), allowing legacy code (where IO(...) wasn't // required) to build. // Also provides the clock / reset constructors, which were used before withClock happened. // Provide a non-deprecated constructor def this(override_clock: Option[Clock]=None, override_reset: Option[Bool]=None) (implicit moduleCompileOptions: CompileOptions) = { this() this.override_clock = override_clock this.override_reset = override_reset } def this(_clock: Clock)(implicit moduleCompileOptions: CompileOptions) = this(Option(_clock), None)(moduleCompileOptions) def this(_reset: Bool)(implicit moduleCompileOptions: CompileOptions) = this(None, Option(_reset))(moduleCompileOptions) def this(_clock: Clock, _reset: Bool)(implicit moduleCompileOptions: CompileOptions) = this(Option(_clock), Option(_reset))(moduleCompileOptions) override def _compatAutoWrapPorts(): Unit = { // scalastyle:ignore method.name if (!_compatIoPortBound() && io != null) { _bindIoInPlace(io) } } } val Module = chisel3.core.Module type Module = CompatibilityModule val printf = chisel3.core.printf val RegNext = chisel3.core.RegNext val RegInit = chisel3.core.RegInit object Reg { import chisel3.core.{Binding, CompileOptions} import chisel3.internal.sourceinfo.SourceInfo // Passthrough for chisel3.core.Reg // Single-element constructor to avoid issues caused by null default args in a type // parameterized scope. def apply[T <: Data](t: T)(implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): T = chisel3.core.Reg(t) /** Creates a register with optional next and initialization values. * * @param t: data type for the register * @param next: new value register is to be updated with every cycle (or * empty to not update unless assigned to using the := operator) * @param init: initialization value on reset (or empty for uninitialized, * where the register value persists across a reset) * * @note this may result in a type error if called from a type parameterized * function, since the Scala compiler isn't smart enough to know that null * is a valid value. In those cases, you can either use the outType only Reg * constructor or pass in `null.asInstanceOf[T]`. */ def apply[T <: Data](t: T = null, next: T = null, init: T = null) (implicit sourceInfo: SourceInfo, compileOptions: CompileOptions): T = { if (t ne null) { val reg = if (init ne null) { RegInit(t, init) } else { chisel3.core.Reg(t) } if (next ne null) { reg := next } reg } else if (next ne null) { if (init ne null) { RegNext(next, init) } else { RegNext(next) } } else if (init ne null) { RegInit(init) } else { throwException("cannot infer type") } } } val when = chisel3.core.when type WhenContext = chisel3.core.WhenContext implicit class fromBigIntToLiteral(x: BigInt) extends chisel3.core.fromBigIntToLiteral(x) implicit class fromtIntToLiteral(x: Int) extends chisel3.core.fromIntToLiteral(x) implicit class fromtLongToLiteral(x: Long) extends chisel3.core.fromLongToLiteral(x) implicit class fromStringToLiteral(x: String) extends chisel3.core.fromStringToLiteral(x) implicit class fromBooleanToLiteral(x: Boolean) extends chisel3.core.fromBooleanToLiteral(x) implicit class fromIntToWidth(x: Int) extends chisel3.core.fromIntToWidth(x) type BackendCompilationUtilities = firrtl.util.BackendCompilationUtilities val Driver = chisel3.Driver val ImplicitConversions = chisel3.util.ImplicitConversions // Deprecated as of Chisel3 object chiselMain { import java.io.File def apply[T <: Module](args: Array[String], gen: () => T): Unit = Predef.assert(false, "No more chiselMain in Chisel3") def run[T <: Module] (args: Array[String], gen: () => T): Unit = { val circuit = Driver.elaborate(gen) Driver.parseArgs(args) val output_file = new File(Driver.targetDir + "/" + circuit.name + ".fir") Driver.dumpFirrtl(circuit, Option(output_file)) } } @deprecated("debug doesn't do anything in Chisel3 as no pruning happens in the frontend", "chisel3") object debug { // scalastyle:ignore object.name def apply (arg: Data): Data = arg } // Deprecated as of Chsiel3 @throws(classOf[Exception]) object throwException { def apply(s: String, t: Throwable = null) = { val xcpt = new Exception(s, t) throw xcpt } } object testers { // scalastyle:ignore object.name type BasicTester = chisel3.testers.BasicTester val TesterDriver = chisel3.testers.TesterDriver } val log2Ceil = chisel3.util.log2Ceil val log2Floor = chisel3.util.log2Floor val isPow2 = chisel3.util.isPow2 /** Compute the log2 rounded up with min value of 1 */ object log2Up { def apply(in: BigInt): Int = { require(in >= 0) 1 max (in-1).bitLength } def apply(in: Int): Int = apply(BigInt(in)) } /** Compute the log2 rounded down with min value of 1 */ object log2Down { def apply(in: BigInt): Int = log2Up(in) - (if (isPow2(in)) 0 else 1) def apply(in: Int): Int = apply(BigInt(in)) } val BitPat = chisel3.util.BitPat type BitPat = chisel3.util.BitPat type ArbiterIO[T <: Data] = chisel3.util.ArbiterIO[T] type LockingArbiterLike[T <: Data] = chisel3.util.LockingArbiterLike[T] type LockingRRArbiter[T <: Data] = chisel3.util.LockingRRArbiter[T] type LockingArbiter[T <: Data] = chisel3.util.LockingArbiter[T] type RRArbiter[T <: Data] = chisel3.util.RRArbiter[T] type Arbiter[T <: Data] = chisel3.util.Arbiter[T] val FillInterleaved = chisel3.util.FillInterleaved val PopCount = chisel3.util.PopCount val Fill = chisel3.util.Fill val Reverse = chisel3.util.Reverse val Cat = chisel3.util.Cat val Log2 = chisel3.util.Log2 val unless = chisel3.util.unless type SwitchContext[T <: Bits] = chisel3.util.SwitchContext[T] val is = chisel3.util.is val switch = chisel3.util.switch type Counter = chisel3.util.Counter val Counter = chisel3.util.Counter type DecoupledIO[+T <: Data] = chisel3.util.DecoupledIO[T] val DecoupledIO = chisel3.util.Decoupled val Decoupled = chisel3.util.Decoupled type QueueIO[T <: Data] = chisel3.util.QueueIO[T] type Queue[T <: Data] = chisel3.util.Queue[T] val Queue = chisel3.util.Queue object Enum extends chisel3.util.Enum { /** Returns n unique values of the specified type. Can be used with unpacking to define enums. * * nodeType must be of UInt type (note that Bits() creates a UInt) with unspecified width. * * @example {{{ * val state_on :: state_off :: Nil = Enum(UInt(), 2) * val current_state = UInt() * switch (current_state) { * is (state_on) { * ... * } * if (state_off) { * ... * } * } * }}} */ def apply[T <: Bits](nodeType: T, n: Int): List[T] = { require(nodeType.isInstanceOf[UInt], "Only UInt supported for enums") require(!nodeType.widthKnown, "Bit width may no longer be specified for enums") apply(n).asInstanceOf[List[T]] } /** An old Enum API that returns a map of symbols to UInts. * * Unlike the new list-based Enum, which can be unpacked into vals that the compiler * understands and can check, map accesses can't be compile-time checked and typos may not be * caught until runtime. * * Despite being deprecated, this is not to be removed from the compatibility layer API. * Deprecation is only to nag users to do something safer. */ @deprecated("Use list-based Enum", "not soon enough") def apply[T <: Bits](nodeType: T, l: Symbol *): Map[Symbol, T] = { require(nodeType.isInstanceOf[UInt], "Only UInt supported for enums") require(!nodeType.widthKnown, "Bit width may no longer be specified for enums") (l zip createValues(l.length)).toMap.asInstanceOf[Map[Symbol, T]] } /** An old Enum API that returns a map of symbols to UInts. * * Unlike the new list-based Enum, which can be unpacked into vals that the compiler * understands and can check, map accesses can't be compile-time checked and typos may not be * caught until runtime. * * Despite being deprecated, this is not to be removed from the compatibility layer API. * Deprecation is only to nag users to do something safer. */ @deprecated("Use list-based Enum", "not soon enough") def apply[T <: Bits](nodeType: T, l: List[Symbol]): Map[Symbol, T] = { require(nodeType.isInstanceOf[UInt], "Only UInt supported for enums") require(!nodeType.widthKnown, "Bit width may no longer be specified for enums") (l zip createValues(l.length)).toMap.asInstanceOf[Map[Symbol, T]] } } val LFSR16 = chisel3.util.LFSR16 val ListLookup = chisel3.util.ListLookup val Lookup = chisel3.util.Lookup val Mux1H = chisel3.util.Mux1H val PriorityMux = chisel3.util.PriorityMux val MuxLookup = chisel3.util.MuxLookup val MuxCase = chisel3.util.MuxCase val OHToUInt = chisel3.util.OHToUInt val PriorityEncoder = chisel3.util.PriorityEncoder val UIntToOH = chisel3.util.UIntToOH val PriorityEncoderOH = chisel3.util.PriorityEncoderOH val RegEnable = chisel3.util.RegEnable val ShiftRegister = chisel3.util.ShiftRegister type ValidIO[+T <: Data] = chisel3.util.Valid[T] val Valid = chisel3.util.Valid val Pipe = chisel3.util.Pipe type Pipe[T <: Data] = chisel3.util.Pipe[T] /** Package for experimental features, which may have their API changed, be removed, etc. * * Because its contents won't necessarily have the same level of stability and support as * non-experimental, you must explicitly import this package to use its contents. */ object experimental { // scalastyle:ignore object.name import scala.annotation.compileTimeOnly class dump extends chisel3.internal.naming.dump // scalastyle:ignore class.name class treedump extends chisel3.internal.naming.treedump // scalastyle:ignore class.name class chiselName extends chisel3.internal.naming.chiselName // scalastyle:ignore class.name } }
marcoarroyo77/yoroi
app/containers/BannerContainer.js
<reponame>marcoarroyo77/yoroi // @flow import type { Node } from 'react'; import React, { Component } from 'react'; import { observer } from 'mobx-react'; import { computed } from 'mobx'; import type { InjectedOrGenerated } from '../types/injectedPropsType'; import TestnetWarningBanner from '../components/topbar/banners/TestnetWarningBanner'; import NotProductionBanner from '../components/topbar/banners/NotProductionBanner'; import ServerErrorBanner from '../components/topbar/banners/ServerErrorBanner'; import environment from '../environment'; import { ServerStatusErrors } from '../types/serverStatusErrorType'; export type GeneratedData = typeof BannerContainer.prototype.generated; @observer export default class BannerContainer extends Component<InjectedOrGenerated<GeneratedData>> { render(): Node { const serverStatus = this.generated.stores.serverConnectionStore.checkAdaServerStatus; return ( <> {serverStatus !== ServerStatusErrors.Healthy && ( <ServerErrorBanner errorType={serverStatus} /> )} <TestnetWarningBanner /> {!environment.isProduction() && <NotProductionBanner />} </> ); } @computed get generated() { if (this.props.generated !== undefined) { return this.props.generated; } if (this.props.stores == null || this.props.actions == null) { throw new Error(`${nameof(BannerContainer)} no way to generated props`); } const { stores, } = this.props; return Object.freeze({ stores: { serverConnectionStore: { checkAdaServerStatus: stores.substores[environment.API] .serverConnectionStore.checkAdaServerStatus, }, }, }); } }
theakman2/node-modules-webant
test/tests/webant-nobootstrap.js
var webantTester = require("../lib/webant.js"); webantTester("nobootstrap",1,{includeBootstrap:false},function(obj,data,done){ data.t.strictEqual(obj,"test"); done(); });
TobiasLeenders/warp10-platform
warp10/src/main/java/io/warp10/continuum/JettyUtil.java
<gh_stars>100-1000 // // Copyright 2018 <NAME>. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package io.warp10.continuum; import org.eclipse.jetty.server.ConnectionFactory; import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.HttpConnectionFactory; import org.eclipse.jetty.server.Server; public class JettyUtil { public static void setSendServerVersion(Server server, boolean send) { // // Remove display of Server header // @see <a href="http://stackoverflow.com/questions/15652902/remove-the-http-server-header-in-jetty-9">http://stackoverflow.com/questions/15652902/remove-the-http-server-header-in-jetty-9</a> // for(Connector y : server.getConnectors()) { for(ConnectionFactory x : y.getConnectionFactories()) { if(x instanceof HttpConnectionFactory) { ((HttpConnectionFactory)x).getHttpConfiguration().setSendServerVersion(send); } } } } }
leonanluppi/ANP-Crawler
api/components/crawler/src/findStationsByCity.js
<filename>api/components/crawler/src/findStationsByCity.js<gh_stars>1-10 'use strict'; let ComponentAction = (() => { let Async = require('async'); let Moment = require('moment'); let Colog = require('colog'); let CheerioAdapter = require('./adapters/cheerioAdapter'); let RequestAdapter = require('./adapters/requestAdapter'); let CrawlerMocks = require('./mapping/crawlerMocks'); let CrawlerMap = require('./mapping/crawlerSiteMapping'); let Mongoose = require('mongoose'); let WeekDataMongo = Mongoose.model('WeekData'); let validateRequestParams = (body) => { if(!body.city.length) { Colog.error(`ERROR: Ops!! Something happens. I can not validate your request completely, please look up body request or params request`); return false; } return true; }; let validateRequestBody = (body) => { if((body && !Object.keys(body).length) && !body.estado.length || !body.dateFrom.length || !body.dateTo.length) { Colog.error(`ERROR: Ops!! Something happens. I can not validate your request completely, please look up body request or params request`); return false; } return true; }; return function middleware(req, res, next) { if (!validateRequestParams(req.params) || !validateRequestBody(req.body)) { return res.status(400) .json({ status : false, message: 'You must need complete data to make this request' }); } let Tasks = []; let Data = req.body; // Try to find current data in MongoDB Tasks.push(function findMongoDataByState(doNext) { WeekDataMongo .findOne({ 'name' : Data.estado, 'date.from' : Data.dateFrom, 'date.to' : Data.dateTo, 'cities.county_id': req.params.city // 'cities.stations' : { // $size: 0 // } }) .exec((err, state) => { if (err) { Colog.error(`ERROR: Ops!! Something. I can not find data in mongo => ${err}`); return doNext(err, false, {}); } if (state && !Object.keys(state).length) { Colog.warning(`WARNING: This city may not exists yet!`); return doNext(null, false, {}); } var cityHasStations = state._doc.cities.filter((el) => { return el.stations.length > 0 }); if (!cityHasStations.length) { Colog.success(`SUCESS: I find data. Lets work...`); return doNext(null, true, state._doc); } if (cityHasStations.length) { Colog.success(`SUCESS: I find data already updated. Rendering...`); return doNext(null, false, state._doc); } }); }); // Get all stations the add to schema Tasks.push(function getStationsFromState(status, stateData, doNext) { if (!status) { console.log('passou 1') return doNext(null, false, stateData); } Async.forEachOf(stateData.cities, (city, key, doNextSubCity) => { Async.forEachOf(CrawlerMocks.fuelTypes, (fuel, keyFuel, doNextSubFuel) => { let formData = { cod_semana : Data.cod_Semana, desc_semana : Data.desc_Semana, cod_combustivel : fuel.id, desc_combustivel: fuel.desc, selMunicipio : req.params.city, tipo : Data.tipo, }; RequestAdapter.build('POST', 'http://www.anp.gov.br/preco/prc/Resumo_Semanal_Posto.asp', formData, (err, response, body) => { if (err || response.statusCode != 200) { Colog.error('ERROR: Ops!! I can not get ANP data. Please try again and I will check what is happen'); return doNext(err, false, false); } let $ = CheerioAdapter.loadCheerio(body); let table = $('.multi_box3 table tr'); Async.forEachOf(table, (el, keyEl, doNextSubTd) => { let td = $(table[keyEl]).find('td'); city.stations.push({ name : CheerioAdapter.getValueByMock($, td, CrawlerMap.tableValues.stations.name), address : CheerioAdapter.getValueByMock($, td, CrawlerMap.tableValues.stations.address), area : CheerioAdapter.getValueByMock($, td, CrawlerMap.tableValues.stations.area), flag : CheerioAdapter.getValueByMock($, td, CrawlerMap.tableValues.stations.flag), prices : [{ type : fuel.name, sellPrice: CheerioAdapter.getValueByMock($, td, CrawlerMap.tableValues.stations.prices.sellPrice), buyPrice : CheerioAdapter.getValueByMock($, td, CrawlerMap.tableValues.stations.prices.buyPrice), saleMode : CheerioAdapter.getValueByMock($, td, CrawlerMap.tableValues.stations.prices.saleMode), provider : CheerioAdapter.getValueByMock($, td, CrawlerMap.tableValues.stations.prices.provider), date : CheerioAdapter.getValueByMock($, td, CrawlerMap.tableValues.stations.prices.date) }] }); }, (err) => { return doNextSubTd(); }); return doNextSubFuel(); }); }, (err) => { return doNextSubCity(); }); }, (err) => { return doNext(null, true, stateData); }); }); // Update in MongoDb if necessary Tasks.push(function updateMongo(status, stateData, doNext) { if (!status) { console.log('passou 2', stateData.name) return doNext(null, false, stateData); } WeekDataMongo .findByIdAndUpdate(stateData._id, { $set: stateData }, (err, created) => { if (err) { Colog.warning(`ERROR: Ops!! I can not update in MongoDB => ${err}`); return doNext(err, false, stateData); } Colog.success(`SUCESS: Yeah!! I updated a data in MongoDB `); return doNext(null, true, stateData); }); }); Async.waterfall(Tasks, function(err, status, result) { console.log(err, status, result) if (!status && Object.keys(result).length) { console.log('passou 3') return res.status(200) .json({ status : true, data : { station: result }, message : 'Date already updated' }); } if (!status) { return res.status(200) .json({ status : false, data : { station: [] }, message: 'Error during tasks' }); } if (!result) { return res.status(200) .json({ status : true, data : { station: [] }, message : 'Empty result' }); } return res.status(200) .json({ status : true, data : { station: result }, message : 'Everything ok. This is the station data' }); }); }; })(); module.exports = ComponentAction
mmoayyed/wicket-spring-boot
wicket-spring-boot-starter/src/main/java/com/giffing/wicket/spring/boot/starter/configuration/extensions/stuff/htmlvalidator/HTMLValidatorConfig.java
package com.giffing.wicket.spring.boot.starter.configuration.extensions.stuff.htmlvalidator; import org.apache.wicket.RuntimeConfigurationType; import org.apache.wicket.protocol.http.WebApplication; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.wicketstuff.htmlvalidator.HtmlValidationResponseFilter; import com.giffing.wicket.spring.boot.context.extensions.ApplicationInitExtension; import com.giffing.wicket.spring.boot.context.extensions.WicketApplicationInitConfiguration; @ApplicationInitExtension @ConditionalOnProperty(prefix = HTMLValidatorProperties.PROPERTY_PREFIX, value = "enabled", matchIfMissing = true) @ConditionalOnClass(value = org.wicketstuff.htmlvalidator.HtmlValidationResponseFilter.class) @EnableConfigurationProperties({ HTMLValidatorProperties.class }) public class HTMLValidatorConfig implements WicketApplicationInitConfiguration { @Override public void init(WebApplication webApplication) { if (RuntimeConfigurationType.DEVELOPMENT == webApplication.getConfigurationType()) { webApplication.getMarkupSettings().setStripWicketTags(true); webApplication.getRequestCycleSettings().addResponseFilter(new HtmlValidationResponseFilter()); } } }
aajjbb/contest-files
HackerEarth/OliverAndTheBattle.cpp
#include <bits/stdc++.h> template<typename T> T gcd(T a, T b) { if(!b) return a; return gcd(b, a % b); } template<typename T> T lcm(T a, T b) { return a * b / gcd(a, b); } template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; } template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; } int in() { int x; scanf("%d", &x); return x; } using namespace std; typedef long long Int; typedef unsigned uint; const int MAXN = 1010; int dx[8] = { 0, 0, -1, 1, -1, 1, -1, 1}; int dy[8] = {-1, 1, 0, 0, -1, 1, 1, -1}; int T, N, M; bool field[MAXN][MAXN]; bool vis[MAXN][MAXN]; int dfs(int x, int y) { int ans = 0; stack<pair<int, int> > stk; stk.push(make_pair(x, y)); for ( ; !stk.empty(); ) { x = stk.top().first; y = stk.top().second; stk.pop(); for (int i = 0; i < 8; i++) { int xx = x + dx[i]; int yy = y + dy[i]; if (xx >= 0 && yy >= 0 && xx < N && yy < M && !vis[xx][yy] && field[xx][yy]) { ans += 1; vis[xx][yy] = true; stk.push(make_pair(xx, yy)); } } } return ans; } int main(void) { cin.tie(0); ios_base::sync_with_stdio(false); cin >> T; int troop = 0; int largest = 0; for (int t = 1; t <= T; t++) { cin >> N >> M; int troop = 0; int largest = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cin >> field[i][j]; vis[i][j] = false; } } for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (field[i][j] == 1 && !vis[i][j]) { troop += 1; largest = max(largest, dfs(i, j)); } } } cout << troop << " " << largest << "\n"; } return 0; }
yabsab/entry-offline
src/main/MainUtils.js
import fstream from 'fstream'; import archiver from 'archiver'; import zlib from 'zlib'; import path from 'path'; import { ProgressTypes } from './Constants'; class MainUtils { constructor(window) { this.window = window; } async saveProject({ sourcePath, destinationPath }) { return new Promise((resolve, reject) => { var archive = archiver('tar'); var gzip = zlib.createGzip(); var fs_writer = fstream.Writer({ path: destinationPath, mode: '0777', type: 'File', }); fs_writer.on('error', (e) => { reject(e); }); fs_writer.on('end', () => { this.window.setProgressBar(ProgressTypes.DISABLE_PROGRESS); resolve(); }); archive.on('error', (e) => { reject(e); }); archive.on('entry', () => { // console.log(a.name); // console.log(a, b, c); }); archive.on('progress', ({ fs }) => { const { totalBytes, processedBytes } = fs; this.window.setProgressBar(processedBytes / totalBytes); }); archive.pipe(gzip).pipe(fs_writer); archive.file(path.join(sourcePath, 'temp', 'project.json'), { name: 'temp/project.json', }); archive.glob( '**', { cwd: path.resolve(sourcePath, 'temp'), ignore: ['project.json'], }, { prefix: 'temp', } ); archive.finalize(); }); } lpad = (str, len) => { var strLen = str.length; if (strLen < len) { for (var i=0; i<len-strLen; i++) { str = "0" + str; } } return String(str); }; getPaddedVersion = (version) => { if(!version) { return ''; } version = String(version); var padded = []; var splitVersion = version.split('.'); splitVersion.forEach((item) => { padded.push(this.lpad(item, 4)); }); return padded.join('.'); } } export default MainUtils;
klaja/pjsip-android
sipservice/src/main/java/org/pjsip/pjsua2/SipHeaderVector.java
<reponame>klaja/pjsip-android /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 4.0.2 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package org.pjsip.pjsua2; public class SipHeaderVector extends java.util.AbstractList<SipHeader> implements java.util.RandomAccess { private transient long swigCPtr; protected transient boolean swigCMemOwn; protected SipHeaderVector(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } protected static long getCPtr(SipHeaderVector obj) { return (obj == null) ? 0 : obj.swigCPtr; } @SuppressWarnings("deprecation") protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; pjsua2JNI.delete_SipHeaderVector(swigCPtr); } swigCPtr = 0; } } public SipHeaderVector(SipHeader[] initialElements) { this(); reserve(initialElements.length); for (SipHeader element : initialElements) { add(element); } } public SipHeaderVector(Iterable<SipHeader> initialElements) { this(); for (SipHeader element : initialElements) { add(element); } } public SipHeader get(int index) { return doGet(index); } public SipHeader set(int index, SipHeader e) { return doSet(index, e); } public boolean add(SipHeader e) { modCount++; doAdd(e); return true; } public void add(int index, SipHeader e) { modCount++; doAdd(index, e); } public SipHeader remove(int index) { modCount++; return doRemove(index); } protected void removeRange(int fromIndex, int toIndex) { modCount++; doRemoveRange(fromIndex, toIndex); } public int size() { return doSize(); } public SipHeaderVector() { this(pjsua2JNI.new_SipHeaderVector__SWIG_0(), true); } public SipHeaderVector(SipHeaderVector other) { this(pjsua2JNI.new_SipHeaderVector__SWIG_1(SipHeaderVector.getCPtr(other), other), true); } public long capacity() { return pjsua2JNI.SipHeaderVector_capacity(swigCPtr, this); } public void reserve(long n) { pjsua2JNI.SipHeaderVector_reserve(swigCPtr, this, n); } public boolean isEmpty() { return pjsua2JNI.SipHeaderVector_isEmpty(swigCPtr, this); } public void clear() { pjsua2JNI.SipHeaderVector_clear(swigCPtr, this); } public SipHeaderVector(int count, SipHeader value) { this(pjsua2JNI.new_SipHeaderVector__SWIG_2(count, SipHeader.getCPtr(value), value), true); } private int doSize() { return pjsua2JNI.SipHeaderVector_doSize(swigCPtr, this); } private void doAdd(SipHeader x) { pjsua2JNI.SipHeaderVector_doAdd__SWIG_0(swigCPtr, this, SipHeader.getCPtr(x), x); } private void doAdd(int index, SipHeader x) { pjsua2JNI.SipHeaderVector_doAdd__SWIG_1(swigCPtr, this, index, SipHeader.getCPtr(x), x); } private SipHeader doRemove(int index) { return new SipHeader(pjsua2JNI.SipHeaderVector_doRemove(swigCPtr, this, index), true); } private SipHeader doGet(int index) { return new SipHeader(pjsua2JNI.SipHeaderVector_doGet(swigCPtr, this, index), false); } private SipHeader doSet(int index, SipHeader val) { return new SipHeader(pjsua2JNI.SipHeaderVector_doSet(swigCPtr, this, index, SipHeader.getCPtr(val), val), true); } private void doRemoveRange(int fromIndex, int toIndex) { pjsua2JNI.SipHeaderVector_doRemoveRange(swigCPtr, this, fromIndex, toIndex); } }
uk-gov-mirror/ministryofjustice.laa-apply-for-legal-aid
spec/requests/providers/has_evidence_of_benefits_spec.rb
require 'rails_helper' RSpec.describe Providers::HasEvidenceOfBenefitsController, type: :request do let(:legal_aid_application) { create :legal_aid_application, :with_dwp_override, :checking_applicant_details, used_delegated_functions: used_delegated_functions } let(:used_delegated_functions) { true } let(:login) { login_as legal_aid_application.provider } before do login subject end describe 'GET /providers/:application_id/has_evidence_of_benefit' do subject { get providers_legal_aid_application_has_evidence_of_benefit_path(legal_aid_application) } it 'returns http success' do expect(response).to have_http_status(:ok) end context 'when the provider is not authenticated' do let(:login) { nil } it_behaves_like 'a provider not authenticated' end end describe 'PATCH /providers/:application_id/has_evidence_of_benefit' do let(:has_evidence_of_benefit) { 'true' } let(:params) do { dwp_override: { has_evidence_of_benefit: has_evidence_of_benefit } } end subject { patch providers_legal_aid_application_has_evidence_of_benefit_path(legal_aid_application), params: params } it 'updates the state' do expect(legal_aid_application.reload.state).to eq 'applicant_details_checked' end context 'application state is already applicant_details_checked' do let(:legal_aid_application) { create :legal_aid_application, :with_dwp_override, :applicant_details_checked } it 'does not update the state' do expect(legal_aid_application).not_to receive(:applicant_details_checked!) end end it 'updates the dwp_override model' do dwp_override = legal_aid_application.reload.dwp_override expect(dwp_override.has_evidence_of_benefit).to be true end it 'redirects to the upload substantive application page' do expect(response).to redirect_to(providers_legal_aid_application_substantive_application_path(legal_aid_application)) end context 'does not use delegated functions' do let(:used_delegated_functions) { false } it 'redirects to the upload capital introductions page' do expect(response).to redirect_to(providers_legal_aid_application_capital_introduction_path(legal_aid_application)) end end it 'updates the state machine type' do expect(legal_aid_application.reload.state_machine).to be_a_kind_of PassportedStateMachine end context 'choose no' do let(:has_evidence_of_benefit) { 'false' } it 'updates the dwp_override model' do dwp_override = legal_aid_application.reload.dwp_override expect(dwp_override.has_evidence_of_benefit).to be false end it 'redirects to the tbc_design page' do expect(response).to redirect_to(providers_legal_aid_application_applicant_employed_index_path(legal_aid_application)) end it 'updates the state machine type' do expect(legal_aid_application.reload.state_machine).to be_a_kind_of NonPassportedStateMachine end end context 'choose nothing' do let(:has_evidence_of_benefit) { nil } it 'show errors' do dwp_override = legal_aid_application.reload.dwp_override passporting_benefit = dwp_override.passporting_benefit.titleize error = I18n.t('activemodel.errors.models.dwp_override.attributes.has_evidence_of_benefit.blank', passporting_benefit: passporting_benefit) expect(response.body).to include(error) end it 'updates the state machine type' do expect(legal_aid_application.reload.state_machine).to be_a_kind_of NonPassportedStateMachine end end context 'Form submitted with Save as draft button' do let(:params) { { draft_button: 'Save as draft' } } it 'redirects to the list of applications' do expect(response).to redirect_to providers_legal_aid_applications_path end end end end
Philipp91/SchulScheduler
ui/src/main/java/schulscheduler/ui/controls/IconMenuItem.java
<reponame>Philipp91/SchulScheduler<filename>ui/src/main/java/schulscheduler/ui/controls/IconMenuItem.java package schulscheduler.ui.controls; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.scene.control.MenuItem; import schulscheduler.ui.AwesomeIcon; public class IconMenuItem extends MenuItem { /** * Das angezeigte Icon. */ private final ObjectProperty<AwesomeIcon> icon = new SimpleObjectProperty<>(); /** * Erstellt ein neues AttachedMenuItem. */ public IconMenuItem() { icon.addListener(observable -> { if (getIcon() == null) { setGraphic(null); } else { if (getGraphic() instanceof Icon) { ((Icon) getGraphic()).setIcon(getIcon()); } else { setGraphic(new Icon(getIcon())); } } }); } /** * @return Das angezeigte Icon. */ public AwesomeIcon getIcon() { return this.icon.get(); } /** * @param icon Das angezeigte Icon. */ public void setIcon(AwesomeIcon icon) { this.icon.set(icon); } /** * @return Das angezeigte Icon. */ public ObjectProperty<AwesomeIcon> iconProperty() { return this.icon; } }
gerbaudg/op
org.opencompare/api-java/src/main/java/org/opencompare/api/java/interpreter/CellContentInterpreter.java
package org.opencompare.api.java.interpreter; import org.opencompare.api.java.PCM; import org.opencompare.api.java.Value; /** * Created by gbecan on 10/02/16. */ public interface CellContentInterpreter { void interpretCells(PCM pcm); Value interpretString(String content); }
zlwandlily/nocalhost-intellij-plugin
src/main/java/dev/nocalhost/plugin/intellij/ui/tree/NocalhostTree.java
<filename>src/main/java/dev/nocalhost/plugin/intellij/ui/tree/NocalhostTree.java package dev.nocalhost.plugin.intellij.ui.tree; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.ui.treeStructure.Tree; import javax.swing.event.TreeExpansionEvent; import javax.swing.event.TreeExpansionListener; import javax.swing.event.TreeWillExpandListener; import javax.swing.tree.ExpandVetoException; import javax.swing.tree.TreeSelectionModel; import dev.nocalhost.plugin.intellij.topic.NocalhostTreeUpdateNotifier; import dev.nocalhost.plugin.intellij.ui.tree.node.ClusterNode; import dev.nocalhost.plugin.intellij.ui.tree.node.NamespaceNode; import dev.nocalhost.plugin.intellij.ui.tree.node.ResourceTypeNode; public class NocalhostTree extends Tree implements Disposable { private final Project project; private final NocalhostTreeModel model; public NocalhostTree(Project project) { this.project = project; this.model = new NocalhostTreeModel(project, this); this.setModel(this.model); init(); } private void init() { this.setRootVisible(false); this.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); this.setCellRenderer(new TreeNodeRenderer()); this.addMouseListener(new TreeMouseListener(this, project)); this.addTreeWillExpandListener(new TreeWillExpandListener() { @Override public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException { Object node = event.getPath().getLastPathComponent(); if (node instanceof ClusterNode) { ClusterNode clusterNode = (ClusterNode) node; model.insertLoadingNode(clusterNode); } if (node instanceof NamespaceNode) { NamespaceNode namespaceNode = (NamespaceNode) node; model.insertLoadingNode(namespaceNode); } if (node instanceof ResourceTypeNode) { ResourceTypeNode resourceTypeNode = (ResourceTypeNode) node; model.insertLoadingNode(resourceTypeNode); } } @Override public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException { } }); this.addTreeExpansionListener(new TreeExpansionListener() { @Override public void treeExpanded(TreeExpansionEvent event) { Object node = event.getPath().getLastPathComponent(); if (node instanceof ClusterNode) { ClusterNode clusterNode = (ClusterNode) node; model.updateNamespaces(clusterNode); } if (node instanceof NamespaceNode) { NamespaceNode namespaceNode = (NamespaceNode) node; model.updateApplications(namespaceNode); } if (node instanceof ResourceTypeNode) { ResourceTypeNode resourceTypeNode = (ResourceTypeNode) node; model.updateResources(resourceTypeNode); } } @Override public void treeCollapsed(TreeExpansionEvent event) { } }); ApplicationManager.getApplication().getMessageBus().connect(this).subscribe( NocalhostTreeUpdateNotifier.NOCALHOST_TREE_UPDATE_NOTIFIER_TOPIC, model::update ); } public void updateDevSpaces() { ApplicationManager.getApplication().getMessageBus().syncPublisher( NocalhostTreeUpdateNotifier.NOCALHOST_TREE_UPDATE_NOTIFIER_TOPIC ).action(); } @Override public void dispose() { } }