content
stringlengths
10
4.9M
A closed simple head model:experimental and numerical analysis k t the Technische Universiteit Eindnoven a research program is set up with the title "Determination of the dynamical behavior of brain tissue during impact loading". A numerical head model is developed in MADYMO, to determine the local response during an impact load . This numerical model is partly validated using a simple physical head model. This physical model consists of a cup filled with a silicon gel, that represents khe human brain, covered with a.perspex plate. This cup is rotated over 2 rad in 38 ms. The gel is visco-elastic and described by a four-mode Maxwell model. The dynamical response of the gel can be visualized using markers and a high speed camera. Experiments with the covered cup are done. This results in relative rotation of the markers with respect to the cup. This maximum relative rotation is 0.27 rad. Simulations of the experiments are done using a finite element model in MADYMO. The relative rotation is a factor 13-18 lower than in the experiments. Furthermore the relative rotation is oscilating at a high frequency. To investigate this phenomenon several parameters, that contribute in the conversion from the physical to the mathematical model or in the conversion from the mathematical to the numerical model are varied. None of those changes resulted in a simulation thzt has the saEe t r e d s found in the experiment. It seems that it is not possible to simulate this experiment using the elements that are available in MADYMO.
def make_row_group(f, data, schema, compression=None, stats=True): rows = len(data) if rows == 0: return if isinstance(data.columns, pd.MultiIndex): if any(not isinstance(c, (bytes, str)) for c in itertools.chain(*data.columns.values)): raise ValueError('Column names must be multi-index, str or bytes:', {c: type(c) for c in data.columns if not isinstance(c, (bytes, str))}) else: if any(not isinstance(c, (bytes, str)) for c in data): raise ValueError('Column names must be multi-index, str or bytes:', {c: type(c) for c in data.columns if not isinstance(c, (bytes, str))}) cols = [] for column in schema: if column.type is not None: if isinstance(compression, dict): comp = compression.get(column.name, None) if comp is None: comp = compression.get('_default', None) else: comp = compression st = stats if isinstance(stats, bool) else column.name in stats if isinstance(data.columns, pd.MultiIndex): try: name = ast.literal_eval(column.name) except ValueError: name = column.name coldata = data[name] else: coldata = data[column.name] chunk = write_column(f, coldata, column, compression=comp, stats=st) cols.append(chunk) rg = ThriftObject.from_fields( "RowGroup", num_rows=rows, columns=cols, total_byte_size=sum([c.meta_data.total_uncompressed_size for c in cols])) return rg
package logkit import ( "context" "testing" "time" ) /* logkit.Debug(ctx, "blfdjaklfdjlkdfsjkafjkldfjafds klfdsj aklfd ", args...) logkit.Debugf(ctx, "blfdjaklfdjlkdfsjkafjkldfjafds klfdsj aklfd ", args...) logkit.Info(ctx, "blfdjaklfdjlkdfsjkafjkldfjafds klfdsj aklfd ", args...) logkit.Infof(ctx, "blfdjaklfdjlkdfsjkafjkldfjafds klfdsj aklfd ", args...) logkit.Warn(ctx, "blfdjaklfdjlkdfsjkafjkldfjafds klfdsj aklfd ", args...) logkit.Warnf(ctx, "blfdjaklfdjlkdfsjkafjkldfjafds klfdsj aklfd ", args...) logkit.Error(ctx, "blfdjaklfdjlkdfsjkafjkldfjafds klfdsj aklfd ", args...) logkit.Errorf(ctx, "blfdjaklfdjlkdfsjkafjkldfjafds klfdsj aklfd ", args...) ctx := logkit.context ctx.Info ctx.Infof ctx, done = logkit.Operation("bdasdas", args..) defer done() */ func TestMain(t *testing.T) { ctx := context.Background() Info(ctx, "starting") simulateWebRequest(ctx) Info(ctx, "line") simulateWebRequest(ctx) Info(ctx, "done") time.Sleep(time.Millisecond * 300) } // ------------------------------- // ------------------------------- func simulateWebRequest(ctx context.Context) { //DefaultOutput = NewOutputFilter(DefaultOutput, false, false, false, false, true, true) //log, done := Operation(ctx, "web.request") //defer done() //fmt.Println("---") log, done := OperationWithOutput(ctx, "web.request", NewBufferedOutput(DefaultOutput, func(events []Event) []Event { return events })) defer done() /*defer func() { for _, item := range buffer.buffered { switch item.itemType { case 1: //regularOutput.B } } fmt.Println(buffer.buffered) done() fmt.Println("here") }()*/ /*log, done := OperationWithOutput(ctx, "web.request", func(messages []*Message) []*Message { }) defer done()*/ /*defer func() { for _, item := range buffer.buffered { switch item.itemType { case 1: //regularOutput.B } } fmt.Println(buffer.buffered) done() fmt.Println("here") }()*/ //log.CaptureEverything() log.Info("hello") Info(log, "log syntax #1") //ctx.Info("log syntax #2") time.Sleep(time.Millisecond * 10) Info(log, "Finished") lookupUser(log) searchInventory(log) query(log) standardContextThing(log) } func standardContextThing(ctx context.Context) { log, done := context.WithCancel(ctx) defer done() Info(log, "standard ctx") op, d2 := Operation(log, "stdchild") defer d2() Info(op, "logkit ctx") } func lookupUser(ctx context.Context) { log, done := Operation(ctx, "lookup.user") defer done() log.Debug("Dewbugging.. Doing something else", String("url", "http://laaame.com")) log.Info("Doing so and so") log.Warn("I'm warning yoooo") log.Error("Erroring out") } func searchInventory(ctx context.Context) { log, done := Operation(ctx, "search.inventory") defer done() log.Info("It's something i'm working on.") log.Debug("Doing something else") } func query(ctx context.Context) { _, done := Operation(ctx, "cql.select", String("cql", "select * from something = blah")) defer done() time.Sleep(time.Millisecond * 10) }
#include <iostream> using namespace std; long long int sn=0,sh=0,f=0,p=0,c=0,b=0,m,i,t,n,a,z; // string h;vector <pair<int,int>> d; int main(){ long long int x[2000000]; cin>>n;b=n-1;z=n; for(int i=0;i<n;i++) cin>>x[i]; while(c<b){ a=x[c]; x[c]=x[b]; x[b]=a; //cout<< b-=2; c+=2; } for(int r=0;r<n;r++) cout<<x[r]<<" "; return 0; }
/** * Assert actual data type segment is correct with expected date type. * * @param assertContext assert context * @param actual actual data type statement * @param expected expected data type */ public static void assertIs(final SQLCaseAssertContext assertContext, final DataTypeSegment actual, final ExpectedDataType expected) { assertThat(assertContext.getText(String.format("%s name assertion error: ", "dataType")), actual.getDataTypeName(), is(expected.getValue())); assertThat(assertContext.getText(String.format("%s start index assertion error: ", "dataType")), actual.getStartIndex(), is(expected.getStartIndex())); assertThat(assertContext.getText(String.format("%s end index assertion error: ", "dataType")), actual.getStopIndex(), is(expected.getStopIndex())); }
/* Shut down PBX by freeing it from memory. */ void pbx_shutdown(PBX *pbx) { for (int i = 0; i < PBX_MAX_EXTENSIONS + 4; i++) { if ((pbx -> client_TUs[i]) != NULL) { shutdown((pbx -> client_TUs[i]) -> extension_num, SHUT_RDWR); } } P(&(pbx -> mutex)); while(pbx -> TU_count > 0) { ; } V(&(pbx -> mutex)); free(pbx); }
/** * Wrapper extension to {@link DynamicCollection} which prevents duplicates. * * @see DynamicCollection * @see Set * @author Costin Leau * */ public class DynamicSet<E> extends DynamicCollection<E> implements Set<E> { public DynamicSet() { super(); } public DynamicSet(Collection<? extends E> c) { super(c); } public DynamicSet(int size) { super(size); } public boolean add(E o) { synchronized (storage) { if (storage.contains(o)) return false; storage.add(o); } return true; } public boolean addAll(Collection<? extends E> c) { if (c == null) throw new NullPointerException(); boolean result = false; synchronized (storage) { for (Iterator<? extends E> iter = c.iterator(); iter.hasNext();) { result |= add(iter.next()); } } return result; } }
/* * makeAlias - * creates an Alias node * * NOTE: the given name is copied, but the colnames list (if any) isn't. */ Alias * makeAlias(const char *aliasname, List *colnames) { Alias *a = makeNode(Alias); a->aliasname = pstrdup(aliasname); a->colnames = colnames; return a; }
# Author: <NAME> (<EMAIL>) import sys import re TOC_LIST_PREFIX = "-" # TOC_LIST_PREFIX = "*" HEADER_LINE_RE = re.compile("^(#+)\s*(.*?)\s*(#+$|$)", re.IGNORECASE) HEADER1_UNDERLINE_RE = re.compile("^-+$") HEADER2_UNDERLINE_RE = re.compile("^=+$") # Dictionary of anchor name to number of instances found so far anchors = {} def print_usage(): print("\nUsage: md-to-toc <markdown_file>") def to_github_anchor(title): ''' Converts markdown header title (without #s) to GitHub-formatted anchor. Note that this function attempts to recreate GitHub's anchor-naming logic. ''' # Convert to lower case and replace spaces with dashes anchor_name = title.strip().lower().replace(' ', '-') # Strip all invalid characters anchor_name = re.sub(r"[\[\]\"!#$%&'()*+,./:;<=>?@\^{|}~]", "", anchor_name) # If we've encountered this anchor name before, append next instance count count = anchors.get(anchor_name) if count is None: anchors[anchor_name] = 0 else: count = count + 1 anchors[anchor_name] = count anchor_name = anchor_name + '-' + str(count) anchor_name = anchor_name.replace('`', '') return '#' + anchor_name def toggles_block_quote(line): '''Returns true if line toggles block quotes on or off''' '''(i.e. finds odd number of ```)''' n = line.count("```") return n > 0 and line.count("```") % 2 != 0 def main(argv=None): if argv is None: argv = sys.argv if len(argv) < 2: print_usage() return 0 filespec = argv[1] in_block_quote = False results = [] # list of (header level, title, anchor) tuples last_line = "" file = open(filespec) for line in file.readlines(): if toggles_block_quote(line): in_block_quote = not in_block_quote if in_block_quote: continue found_header = False header_level = 0 m = HEADER_LINE_RE.match(line) if m is not None: header_level = len(m.group(1)) title = m.group(2) found_header = True if not found_header: m = HEADER1_UNDERLINE_RE.match(line) if m is not None: header_level = 1 title = last_line.rstrip() found_header = True if not found_header: m = HEADER2_UNDERLINE_RE.match(line) if m is not None: header_level = 2 title = last_line.rstrip() found_header = True if found_header: results.append((header_level, title, to_github_anchor(title))) last_line = line # Compute min header level so we can offset output to be flush with # left edge min_header_level = min(results, key=lambda e: e[0])[0] for r in results: header_level = r[0] spaces = " " * (header_level - min_header_level) print("{}{} [{}]({})".format(spaces, TOC_LIST_PREFIX, r[1], r[2])) if __name__ == "__main__": sys.exit(main())
<reponame>gseteamproject/smartfactory package productionBehaviours; import basicClasses.CrossAgentData; import basicClasses.Order; import common.AgentDataStore; import interactors.AskBehaviour; import interactors.ResponderBehaviour; public class ProductionAskBehaviour extends AskBehaviour { private static final long serialVersionUID = -4443443755165652310L; public ProductionAskBehaviour(ResponderBehaviour interactionBehaviour, AgentDataStore dataStore) { super(interactionBehaviour, dataStore); } @Override public void action() { if (!this.isStarted()) { Order orderToProduce = Order.fromJson(interactionBehaviour.getRequest().getContent()); if (orderToProduce.searchInList(CrossAgentData.orderQueue) > -1) { CrossAgentData.orderQueue .get(orderToProduce.searchInList(CrossAgentData.orderQueue)).agent = interactionBehaviour .getAgent().getLocalName(); myAgent.addBehaviour(new AskForMaterialsBehaviour(interactionBehaviour, dataStore)); } this.setStarted(true); } } }
package net.oschina.j2cache.hibernate5; import net.oschina.j2cache.CacheChannel; import net.oschina.j2cache.hibernate5.strategy.NonstopAccessStrategyFactory; import net.oschina.j2cache.hibernate5.regions.*; import net.oschina.j2cache.hibernate5.strategy.J2CacheAccessStrategyFactory; import net.oschina.j2cache.hibernate5.strategy.J2CacheAccessStrategyFactoryImpl; import net.oschina.j2cache.hibernate5.util.Timestamper; import org.hibernate.boot.spi.SessionFactoryOptions; import org.hibernate.cache.CacheException; import org.hibernate.cache.spi.*; import org.hibernate.cache.spi.access.AccessType; import java.util.Properties; public abstract class AbstractJ2CacheRegionFactory implements RegionFactory { protected SessionFactoryOptions settings; protected CacheChannel channel; protected final J2CacheAccessStrategyFactory accessStrategyFactory = new NonstopAccessStrategyFactory(new J2CacheAccessStrategyFactoryImpl()); @Override public boolean isMinimalPutsEnabledByDefault() { return true; } @Override public long nextTimestamp() { return Timestamper.next(); } @Override public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException { return new J2CacheEntityRegion(accessStrategyFactory, getCache( regionName ), settings, metadata, properties ); } @Override public NaturalIdRegion buildNaturalIdRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException { return new J2CacheNaturalIdRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties ); } @Override public CollectionRegion buildCollectionRegion( String regionName, Properties properties, CacheDataDescription metadata) throws CacheException { return new J2CacheCollectionRegion( accessStrategyFactory, getCache( regionName ), settings, metadata, properties ); } @Override public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException { return new J2CacheQueryResultsRegion( accessStrategyFactory, getCache( regionName ), properties ); } @Override public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException { return new J2CacheTimestampsRegion( accessStrategyFactory, getCache( regionName ), properties ); } @Override public AccessType getDefaultAccessType() { return AccessType.READ_WRITE; } public void setChannel(CacheChannel channel) { this.channel = channel; } private CacheRegion getCache(String name) throws CacheException { return new J2CacheCacheRegion(channel,name); } }
import java.io.*; import java.util.*; import java.math.*; public class CF153PermutationSequence { public static void main(String[] args) throws IOException { new CF153PermutationSequence().run(); } StreamTokenizer in; int nextInt() throws IOException { in.nextToken(); return (int)in.nval; } class Permutation { public int[] a; public Permutation multiply(Permutation b) { Permutation c = new Permutation(); c.a = new int[a.length]; for (int i = 0; i < a.length; ++i) { c.a[i] = b.a[a[i]]; } return c; } public Permutation power(int n) { Permutation c = new Permutation(); c.a = a.clone(); Permutation result = new Permutation(); result.a = new int[a.length]; for (int i = 0; i < a.length; ++i) { result.a[i] = i; } for (int i = 0; i < n; ++i) { result = result.multiply(c); } return result; } public void read(int length) throws IOException { a = new int[length]; for (int i = 0; i < length; ++i) { a[i] = nextInt(); --a[i]; } } public boolean equals(Permutation b) { for (int i = 0; i < a.length; ++i) { if (a[i] != b.a[i]) { return false; } } return true; } } void run() throws IOException { in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); int n = nextInt(), k = nextInt(); Permutation s = new Permutation(), t = new Permutation(); s.read(n); t.read(n); Permutation s1 = new Permutation(); s1.a = new int[n]; for (int i = 0; i < n; ++i) { s1.a[s.a[i]] = i; } if (s1.multiply(s).equals(t)) { System.out.println("NO"); return; } int step = 120; int good[] = new int[250]; for (int j = 0; j < 250; ++j) { int index = j - step; good[j] = 1; Permutation res; if (index < 0) { res = s1.power(-index); } else { res = s.power(index); } if (res.equals(t)) { good[j] = 0; } } int a[] = new int[1]; a[0] = 0; for (int i = 1; i < k; ++i) { int used[] = new int[250]; for (int j = 0; j < 250; ++j) { used[j] = 0; } for (int j = 0; j < a.length; ++j) { used[a[j] + 1 + step] = 1; used[a[j] - 1 + step] = 1; } int cnt = 0; for (int j = 0; j < 250; ++j) { if (used[j] == 1 && good[j] == 1) { ++cnt; } } if (cnt == 0) { System.out.println("NO"); return; } int b[] = new int[cnt]; cnt = 0; for (int j = 0; j < 250; ++j) { if (used[j] == 1 && good[j] == 1) { b[cnt] = j - step; ++cnt; } } a = b.clone(); /*for (int j = 0; j < a.length; ++j) { System.out.print(a[j] + " "); } System.out.println();*/ } for (int j = 0; j < a.length; ++j) { if (good[a[j] + 1 + step] == 0 || good[a[j] - 1 + step] == 0) { System.out.println("YES"); return; } } System.out.println("NO"); } }
Paleoenvironmental evolution of the coastal plain of Southern Brazil: palynological data from a Holocene core in Santa Catarina State. This paper presents a paleoenvironmental reconstruction from palynological analyses of a sedimentary core of Holocene age, drilled at municipality of Garopaba (Santa Catarina), Southern Brazil. A total of 46 samples was collected for palynological analyses in the 450 cm-long core PCSC-3, as also three samples for radiocarbon dating and granulometric analyses. The palynological content includes 84 taxa related to pollen grains of angiosperms (38) and gimnosperm (3), spores of pteridophyta (16) and bryophyta (2), spores of fungi (8), algae (3), acritarchs (3), dinoflagellate cysts (2) and microforaminiferal linings (1). Three specimens of acritarchs are described and illustrated in detail. Three palynological phases were defined based on changes in assemblages: Phase I, Phase II and Phase III. The Phase I is characterized as a lagoonal paleoenvironment with marine influence from the beginning of the sedimentation (5390 cal yr BP), based on occurrences of acritarchs, dinoflagellate cysts and microforaminiferal linings. The Phase II (3032 yr BP until 858 cal yr BP) also is characterized by a lagoonal paleoenvironment, however, presented decrease in percentage of marine elements and increase in freshwater algae record, suggesting less marine influence in the lagoonal body. In Phase III (last 856 years), underwater sedimentation prevailed, under swamp-like conditions.
package repository; import models.PersonalPhoto; import javax.inject.Inject; import static java.util.concurrent.CompletableFuture.supplyAsync; import java.sql.Timestamp; import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletionStage; /** * Class that performs operations on the database regarding photos. */ public class PhotoRepository { private final DatabaseExecutionContext executionContext; @Inject public PhotoRepository(DatabaseExecutionContext databaseExecutionContext) { this.executionContext = databaseExecutionContext; } /** * Updates a photo. * * @param personalPhoto the photo to update. * @return the updated photo. */ public CompletionStage<PersonalPhoto> updatePhoto(PersonalPhoto personalPhoto) { return supplyAsync( () -> { personalPhoto.update(); return personalPhoto; }, executionContext); } /** * Insert a photo into the database * * @param photo the personal photo to be inserted in the database * @return the photo object */ public CompletionStage<PersonalPhoto> insert(PersonalPhoto photo) { return supplyAsync( () -> { photo.save(); return photo; }, executionContext); } /** * Gets the photo with the given photo Id * * @param photoId the id of the photo to be retrieved * @return the photo */ public CompletionStage<Optional<PersonalPhoto>> getPhotoById(int photoId) { return supplyAsync( () -> PersonalPhoto.find.query().where().eq("photo_id", photoId).findOneOrEmpty(), executionContext); } /** * Gets the photo with the given photo Id including soft deleted photos. * * @param photoId the id of the photo to be retrieved * @return the photo */ public CompletionStage<Optional<PersonalPhoto>> getPhotoByIdWithSoftDelete(int photoId) { return supplyAsync( () -> PersonalPhoto.find .query() .setIncludeSoftDeletes() .where() .eq("photo_id", photoId) .findOneOrEmpty(), executionContext); } /** * Gets a list of a users personal photos from the database * * @param userId the id of the user * @return a list of personal photos. */ public CompletionStage<List<PersonalPhoto>> getPhotosById(int userId) { return supplyAsync( () -> PersonalPhoto.find .query() .where() .eq("user_user_id", userId) .and() .eq("is_cover", false) .findList(), executionContext); } /** * Delete a photo with the given hashed filename by finding the photo's id and deleting it with * the id found * * @param photo the photo to be deleted * @return the id of the photo that was deleted */ public CompletionStage<Integer> deletePhoto(PersonalPhoto photo) { return supplyAsync( () -> { photo.setDeletedExpiry(Timestamp.from(Instant.now().plus(Duration.ofHours(1)))); photo.save(); photo.delete(); // Soft delete return photo.getPhotoId(); }, executionContext); } /** * Retrieves a deleted cover photo. * * @param userId thi id of the user that owns the cover photo. * @param photoId the id of the deleted cover photo. * @return the optional cover photo. */ public CompletionStage<Optional<PersonalPhoto>> retrieveDeletedCoverPhoto( int userId, int photoId) { return supplyAsync( () -> PersonalPhoto.find .query() .setIncludeSoftDeletes() .where() .eq("user_user_id", userId) .and() .eq("photo_id", photoId) .and() .eq("deleted", true) .and() .eq("is_cover", true) .findOneOrEmpty()); } /** * Undoes a personal photo deletion. * * @param personalPhoto the photo to undo deletion of. * @return the photo after deletion is undone. */ public CompletionStage<PersonalPhoto> undoPhotoDelete(PersonalPhoto personalPhoto) { return supplyAsync( () -> { personalPhoto.setDeleted(false); personalPhoto.setDeletedExpiry(null); personalPhoto.save(); return personalPhoto; }); } }
It sounds simplistic, but the greatest thing to realize is that your thoughts create your reality. Once you have really internalized this truth, you can go so much further with the law of attraction than you ever could have imagined. In this post, I want to go a lot deeper than usual. I’ve had a technique I’ve been working on for a while now, which I’ve wanted to post about for a few weeks, but other posts took precedence. Now, though, I want to introduce this technique. But first, I want to describe how it is your thoughts create your reality, and help you to truly and fully internalize this truth for yourself. A New Paradigm Most people fall under a very basic, but persistent delusion: the idea that matter is prime, and consciousness is secondary. I find this is so even for people who strongly believe in a soul and afterlife. We still have this idea that we are a soul that is trapped inside a body, and that at death, we put off the body and enter the spirit realm. In this world, it seems matter is the center, the defining structure, and consciousness must fit within its confines. When you take this paradigm, and try to start using magic / the law of attraction in your life, you are left a bit stuck. You have a great deal of doubt, because, well, in a matter-first world, the law of attraction simply makes no sense. You think, “How can my mind possibly influence the world around me?” In a matter-first world, we pray to God to fix our problems, because at least God can influence the world from the outside. But we, ourselves, are powerless. Or, as atheists, we simply surrender to the fruitlessness and nihilistic pointlessness of the whole thing. However, a new paradigm is called for, and it’s not given enough attention. This paradigm is consciousness-first. It is the idea that consciousness, not matter, is prime. Consciousness is the center, the defining structure, and matter must fit within its confines. What if instead of being a soul within a body, you are actually a soul containing the idea of bodiness? And, that body idea must respond to the commands of the consciousness which contains it. What would this change? Well, only everything. Instead of you being a conscious entity that is subject to the whims of a material universe, you are a conscious entity to whom a material universe is subject, because it is contained within you. Actually, that material universe is really just the idea of a material universe, just as the body idea is just the idea of a body, because it is really all consciousness. Now, you have infinite power. Your thoughts create your reality, because your thoughts are the components which make up your reality. Your reality is made up of thought, and nothing more. This all sounds nice, but how do you know it’s true? Well, let me ask, how do you know it’s not true? Just because the matter-first model of reality seems to be true, doesn’t mean it actually is. When you are in a dream, for example, it seems that the dream world is true, but it really is not. It is just a world constructed in your mind. Unfortunately there’s no way to prove that consciousness-first is the more accurate model of reality, though it seems that quantum physics is getting ever closer to realizing this truth. However, if you try adopting this paradigm, I think you’ll see that it makes more sense than the alternative. Seeing Through the Illusion of Internal and External To realize how your thoughts create your reality, it is necessary to see through yet another common illusion: that of thoughts being internal, and reality being external. One of the biggest reasons that people dismiss the power of magic and the law of attraction is that thoughts are seen as less “real” than external reality. Out there is the real world, and in here is just a collection of thoughts. It’s a false dichotomy. If we follow the consciousness-first model of reality, then inner and outer must have no inherent meaning, other than two different ideas, or two different ways of seeing the world. I think that for many people, reality is so slow to change because they see it as permanent or static. It’s not dynamic and ever-changing like our thoughts are. But, if you started to see reality as just as dynamic as thought, then it would quickly be able to change to whatever you wanted it to. Remember, if consciousness is prime, then whatever you think of reality must be truth in your universe. So, why would you want to see it as real and permanent? When you think, you are essentially experiencing a series of images, sounds, and sensations within your own consciousness. You could call these your inner senses, because they correspond exactly to your outer senses of seeing, hearing, feeling, tasting, and smelling. All of those can be experienced in the imagination, with the “inner” senses. So what’s the difference between thoughts experienced via the inner senses, and so-called “reality” experienced via the outer senses? Only that you give them separate meanings. But imagine if you stopped differentiating so much. Imagine if you knew that these “outer” senses were only feeding you the same types of information as your inner senses. They were still images, sounds, sensations, etc, as created by your thoughts. They just appear to be more real, because that is the meaning you have given to them. Once I started seeing in my own life that outer reality was just as malleable as inner, then I started being able to change outer reality far more quickly than ever before. In fact, I would even dare to say that eventually, one could see inner reality as more real than outer, because it is the inner that is the cause of the outer, not the other way around. If your thoughts create your reality, then surely your thoughts are more real than the “reality” that they create? After all, if you don’t like the reality you have created, you can just change the thoughts that created it. Reality as a Series of Projections Observe the thoughts you are having right now. See that they are just a series of images, sounds, and sensations playing upon the screen of your consciousness. And now, experience what is in your “outer” reality. See what you see, hear what you hear, feel what you feel. And imagine that these, too, are just images, sounds, and sensations playing upon the screen of your own consciousness. The only thing that makes the latter more permanent is your own belief in its permanency. Now recognize that each of these thoughts (which we could call “projections”), both the inner and the apparently outer, are manifestations. Of what are they manifestations? They are manifestations of your own focus and attention—of where you place your emotional investment. If you choose to think about lack, most of your projections will be about lack. If you choose to think about abundance, then most of your projections will be about abundance. Notice the word “choose” in both of those statements. It is always your choice, even if you don’t always exercise that choice. Indeed, this is how your thoughts create your reality. So your thoughts, both internal and external, are just a series of projections upon the screen of consciousness. And, you have the power to change these projections, any time you like, by changing what is being projected. What is being projected is, as I mentioned, your own focus and attention. But, because you see the projections as reality, you waste your time trying to change the projections, instead of changing what is projecting them. The projections are all your thoughts, plus external experience, and even your own words and actions, since words and actions are just a manifestation of your own inner state and what you hold within yourself. Yes, I’m saying that even most of your thoughts are themselves projections, because many of them are just manifestations of current momentum. For example, if you start worrying about money, or obsessing about a relationship, you’re going to start having thoughts that reflect that focus. Those thoughts are not deliberate, but are just manifestations of the momentum of the current energy you have going. Therefore, they, too, are projections. In The Art of Reality Creation, I discuss how a manifestation becomes more and more realized in outer reality, through a series of seven stages, one of which is your thoughts. In any case, you can easily change the projections, by changing what is being projected. It is not as hard as it might initially sound. The Key to Changing What Is Being Projected In NLP, it was always emphasized to me that we can change anything within our own mind. Our mind is our domain, and NLP gave the code to programming it. What NLP didn’t mention, but I will mention now, is that by programming your own mind, you also program outer reality. When I started trying these techniques out during my NLP training, I noticed that outer reality immediately responded to whatever changes I made within. It wasn’t only perceptual changes, which you might be able to dismiss, but real, quantitative changes to how my reality operated. This is in fact how I started realizing that the law of attraction is true after all. I had major doubts about it before, but seeing it first-hand like this really helped to dispel at least some of those doubts, and prove to myself that my thoughts did indeed create my reality. The fascinating thing is that the technique isn’t all that complicated. The way you change your own internal subconscious structures is by changing the representations of those structures. Wait, what? Thoughts hold a special place in the act of creation. You cannot change your subconscious structures by changing so-called “external” projections (i.e., outer reality), but you can change those structures by changing the thoughts that reflect those structures. The place most people go wrong is that they try to change the content of their thoughts. If they are thinking about lack, they try to force themselves to think about abundance. But, it’s not going to work, because the mind’s still focused on lack, because it thinks that is important. To explain this, let me explain the two properties of thought: content and structure. The content of a thought is what the thought is about. For instance, you might be thinking of, say, a pleasant conversation you had yesterday, or you might be thinking of that person who cut you off in traffic. The content of these thoughts are completely different. The way to tell the content of the thought is by asking, “What is it I’m thinking about?” But you also have the structure of a thought. This is harder to define, because we simply never think about it, unless you’re an NLP practitioner. 🙂 Where the content answered the question “what?”, the structure answers the question, “how?” There’s too much to this to discuss in one post, and it is covered much more thoroughly in The Art of Reality Creation, but I’ll discuss the basics. Let’s just take the visual sense. Are you thinking about this thing in big, bold images, or are the images small and blurry? Are the images moving as in a movie, or are they still? Are they in color or are they black and white? You might think, “Who cares? What’s any of this matter?” But all of these structures are encoded data, letting your subconscious mind know exactly how to think about this particular thought. By changing the structure of the thought, you can change the importance that your subconscious mind gives to it. For instance, take a positive memory that has significantly strong emotion. Now, double the size of that image in your mind, and bring it up close. And, make sure it’s in color. Did the emotion intensify? Now, bring up a negative memory that has significantly strong emotion. And now, shrink that image down to a small little thumbnail icon. And, push it far away into the distance. Dim the colors, too, or make it black and white. Did the emotion decrease in intensity? So this is how your thoughts create your reality. By changing the structure of your thoughts, you change the encoded data your subconscious mind holds on those thoughts, and therefore you change their projection out in apparent reality. Remember, creation is based on your emotion. If you can increase or decrease your emotional investment in particular thoughts, then you can change how much those thoughts manifest in your reality. That seems pretty powerful, doesn’t it? Technique: Choosing the Images that Will Be Projected That brings us at last to the technique I’ve been wanting to discuss. You could call it, “changing your projections”. First, lets summarize. Reality is just a series of projections upon the screen of your consciousness. By changing the structure of those projections, you can make them more or less important to your subconscious mind. The ones you make more important will create more like projections in your reality, and the ones you make less important will begin to fade away. How do you know if a projection is seen as important to your subconscious mind? Simply, by the amount of emotional investment you give to it. You can rate that on a scale of 0 to 10 if you like. The higher the scale, the more investment, and the more it’ll continue to manifest. The lower that scale, the less investment, and the less it will manifest. To make this work, let’s take an example. You want to manifest more money. But every time you try, you think about how little of it you have, and how hard it is to get more of it. So what projections do we have? We have a projection that says, “I have too little money.” That projection probably has high importance, because it has high emotional investment (your dread and disappointment when you think about it). We also have a projection that says, “It is hard to earn more money.” Again, it seems to have high importance, because it has high investment. Hint: You can also tell if something has high importance by how often and to what degree it manifests in your reality. Now, the content of these projections has already been discussed. By the traditional methods of the LOA, we’d simply try to change the content from “I don’t have enough money and it’s hard to get more of it,” to “I have enough money and it’s easy to get more of it.” But, because your subconscious mind places high importance on these projections, it’s not so easy. You’ve probably experienced trying to do this exact same thing, and your mind just jumps back to the same thoughts, no matter what you do. So let’s change their structure. Observe how you represent those thoughts in your mind. Are they images? Sounds? Sensations? Make the images smaller and dimmer. Make the sounds softer and farther away. Make the sensations fuzzier and less distinct. Then repeat it. The subconscious mind needs repetition. Do the above process, then go back to the thoughts and see how much emotional investment they have. Then repeat it over again until it is significantly less. It doesn’t have to be zero, just small enough that you can change the content of the thoughts without resistance from your subconscious mind. Great! Now, what would you rather create? Probably a thought like, “Money comes to me easily.” So what would that thought look, sound, and feel like? You don’t have to choose all three. You’ll notice a tendency to gravitate towards one or two of these modalities. Represent that thought in your mind to the best of your ability. It’ll probably be small and indistinct at first. This is because your subconscious mind isn’t used to representing this thought. So, make it bigger, like we did before. Make it full color. Bring it up close. Make the sounds louder and closer to you. Make the sensations well-defined and expansive. Watch as that emotion associated with this thought increases. Now, drop it. After a moment, return to the thought, and do it all over again. And again. And again. Okay, granted, this is pretty involved inner work. But, it can and will produce massive changes in your reality. Obviously you don’t want to do all of this every time you have a negative thought, and I’m not asking you to. But, you can very quickly make that negative thought have less investment, and then replace it with a positive thought that you give more investment, using the above technique. You can just do it once and move on with your day, and it should do the trick. But, however you apply it, I’m showing you the secret of exactly how your thoughts create your reality, and how to use this to change what is being created. Essentially, it is as follows: Observe what is already being projected. If you don’t like it, then change the structure of that projection to give it less importance. Replace that projection with one that you’d rather experience, and increase its importance by changing its structure. It becomes second nature after a while. That’s why it’s often so easy for me to release resistance, because I simply don’t allow those images to become big enough to cause significant emotional investment. If I do for a time, then I know how to reverse it, and now so do you. But wait, what do you do with actual negative experiences in outer reality? Those negative experiences, too, are represented in your own mind, which is calling it “negative”. In other words, it is only negative because of the thoughts you hold in your own mind. Change the structure of those thoughts, thereby giving less emotional investment to this “negative” experience, and it will start to change. Ultimately, the point is that you have full control. If you have negative thoughts or experiences, see them as the projections they are. Change the structure of those projections, and watch as reality shifts to match your new subconscious structures. Similarly, if you have a positive thought or experience, change its structures to increase your emotional investment and really communicate to your subconscious mind that you want more like this. Then, watch as your reality shifts to match your new focus. It’s easy and at least relatively effortless. You hold the key to changing any thought, and thereby changing your “external” reality. How About You? Now it’s your turn. What projections are being projected in your current reality? How can you apply this technique to replace the unwanted ones with ones you’d rather experience? Let me know your thoughts in the comments. [activecampaign form=1] What Lies Beyond the Law of Attraction? What if the LOA isn't enough? Enter your info to get my free e-course, What Lies Beyond the Law of Attraction? Success! Now check your email to confirm your subscription. Share this: Facebook Twitter LinkedIn Email Like this: Like Loading...
<reponame>pjc0247/rookie.lang<filename>compiler/text_processor.h /* text_processer.h Rookie's Lexer and S-exper. */ #pragma once #include <string> #include <regex> #include <vector> #include <list> #include "token.h" struct lexer_token { std::wstring raw; token_type type; int priority; lexer_token(const std::wstring &raw, token_type type, int priority = 0); }; class lexer { public: lexer(compile_context &ctx); std::vector<token> lex(const std::wstring &_src); private: bool is_ignorable(wchar_t c); bool is_number(wchar_t c); bool is_ident_acceptible(wchar_t c); token parse(const std::wstring &raw); private: compile_context &ctx; string_pool *spool; uint32_t line, cols; }; enum class semantic_position { sp_root, sp_class, sp_methodbody }; enum class sexp_state { ss_none, ss_param_list, }; class sexper { public: sexper(compile_context &ctx); std::vector<stoken> sexp(const std::vector<token> &_tokens); private: std::vector<token> preprocess(const std::vector<token> &_tokens); void sexp_root(const token &token); void sexp_class(token &token); void sexp_methodbody(const token &token); stoken parse(const token &token); void parse_keyword(const token &token, stoken &stoken); void flush_single_line(); void flush_expression(); void flush_until_priority(int priority); token flush_until_type(token_type type); stoken pop_and_parse() { if (stack.empty()) return stoken::empty(); auto token = stack.back(); stack.pop_back(); auto p = parse(token); return p; } token prev_token() const { if (cursor == 0) return token::padding(); return tokens[cursor - 1]; } token next_token() const { if (cursor == tokens.size() - 1) return token::padding(); return tokens[cursor + 1]; } semantic_position s_pos() const { if (depth == 0) return semantic_position::sp_root; if (depth == 1) return semantic_position::sp_class; return semantic_position::sp_methodbody; } private: compile_context &ctx; uint32_t cursor; uint32_t depth; bool next_is_at; bool has_inherit_list; sexp_state state; std::vector<token> tokens; std::vector<stoken> result; std::vector<token> stack; };
# from typing import Optional # from snr.core import * # from snr.prelude import * # from . import video_receiver, video_source # from .camera_config import CameraConfig # class VideoSourceFactory(LoopFactory): # def __init__(self, config: CameraConfig): # super().__init__(video_source) # self.config = config # def get(self, parent: AbstractNode) -> AbstractLoop: # return video_source.VideoSource(self, # parent, # f"{self.config.name} source", # "localhost", # self.config.server_port, # self.config.camera_num) # def __repr__(self): # return "Video(Cam: {}) Source Factory:{}".format( # self.config.camera_num, # self.config.server_port # ) # class VideoReceiverFactory(LoopFactory): # def __init__(self, config: CameraConfig) -> None: # super().__init__(video_receiver) # self.config = config # def get(self, parent: NodeProtocol) -> AbstractLoop: # return video_receiver.VideoReceiver(self, # parent, # f"{self.config.name} receiver", # self.config.server_port) # def __repr__(self): # return f"Video Receiver Factory: {self.config.name}" # class CameraPair: # def __init__(self, config: CameraConfig): # self.config = config # self.source = VideoSourceFactory(self.config) # self.receiver = VideoReceiverFactory(self.config)
package worker import ( "context" "fmt" "math/big" "strings" "sync" "time" "github.com/SparkNFT/key_server/abi" "github.com/SparkNFT/key_server/chain" "github.com/SparkNFT/key_server/config" "github.com/SparkNFT/key_server/model" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus" "golang.org/x/xerrors" "xorm.io/xorm" ) var ( scanLock map[string]*sync.Mutex ) func CheckBlockScannerConfig(chainName string) { if config.C.Chain[chainName].ContractAddress == "" || config.C.Chain[chainName].RPCUrl == "" { panic(fmt.Sprintf( "Chain config invalid. ContractAddress: %s, RPC URL: %s", config.C.Chain[chainName].ContractAddress, config.C.Chain[chainName].RPCUrl, )) } if config.C.Chain[chainName].BlockHeight == 0 { panic("BlockHeight not set.") } } func BlockScannerWorker(chainName string) { blockHeight := checkBlockHeight(chainName) l := log.WithFields(log.Fields{"chain": chainName, "worker": "BlockScannerWorker"}) contract, client, err := chain.Init(chainName) if err != nil { panic(xerrors.Errorf("error when initializing worker: %w", err)) } if scanLock == nil { scanLock = make(map[string]*sync.Mutex, 0) } lock := new(sync.Mutex) scanLock[chainName] = lock for { lock.Lock() if err := fetch_block(chainName, contract, client, blockHeight); err != nil { l.WithFields(logrus.Fields{"chain": chainName, "height": blockHeight}).Warnf("Block fetch failed: %s", err.Error()) lock.Unlock() time.Sleep(config.C.Chain[chainName].FailSleepSeconds * time.Second) continue } blockHeight += 1 lock.Unlock() time.Sleep(config.C.Chain[chainName].SleepSeconds * time.Second) } } // checkBlockHeight returns next block height should be fetched func checkBlockHeight(chainName string) (block_height uint64) { l := logrus.WithFields(log.Fields{"chain": chainName, "worker": "check_block_height"}) config_block_height := config.C.Chain[chainName].BlockHeight found_block, err := model.BlockLogFindFirst(chainName) if err != nil { l.Warnf("error when fetching latest block height: %s", err.Error()) l.Warnf("Using config-file specified height") } found_block_height := uint64(0) if found_block != nil { found_block_height = found_block.BlockHeight found_block_height += 1 } if config_block_height > found_block_height { block_height = config_block_height } else { block_height = found_block_height } if block_height == uint64(0) { panic(xerrors.Errorf("Block height: both config file and DB fetching failed.")) } return block_height } // fetch_block fetches specific height of a block and saves all // related events in DB. func fetch_block(chainName string, contract *abi.SparkLink, client *ethclient.Client, block_height uint64) (err error) { l := log.WithFields(log.Fields{"chain": chainName, "worker": "fetch_block", "height": block_height}) newest_block, err := client.BlockNumber(context.Background()) if err != nil { return xerrors.Errorf("error when fetching newest block number: %w", err) } wait_block_count := uint64(config.C.Chain[chainName].BlockConfirmCount) if newest_block < (block_height + wait_block_count) { return xerrors.Errorf("Slow down. Newest: %d, current: %d, should wait: %d", newest_block, block_height, wait_block_count) } session := model.Engine.NewSession() defer session.Close() err = model.BlockLogStart(session, chainName, block_height) if err != nil { session.Rollback() if strings.Contains(err.Error(), "duplicate key value") { l.WithField("height", block_height).Debug("Using existed BlockLog record") } else { return xerrors.Errorf("error when starting a blocklog: %w", err) } } logs, err := chain.GetAllLogsOf(client, chainName, big.NewInt(int64(block_height))) if err != nil { session.Rollback() return xerrors.Errorf("error when fetching block: %w", err) } l.WithFields(log.Fields{"count": len(logs)}).Info("Log fetched.") events, err := create_events(contract, session, chainName, logs) if err != nil { session.Rollback() return xerrors.Errorf("%w", err) } err = session.Commit() if err != nil { return xerrors.Errorf("error when commiting changes: %w", err) } // create NFT from events err = create_nfts(contract, session, chainName, events) if err != nil { return xerrors.Errorf("error when creating NFT: %w", err) } err = update_nfts(contract, session, chainName, events) if err != nil { return xerrors.Errorf("error when updating NFT: %w", err) } err = session.Commit() if err != nil { return xerrors.Errorf("error when commiting changes: %w", err) } // If all set, err = model.BlockLogFinish(session, chainName, block_height) if err != nil { return xerrors.Errorf("error when finishing a block: %w", err) } err = session.Commit() if err != nil { return xerrors.Errorf("error when commiting changes: %w", err) } // Clean old BlockLog err = model.BlockLogClean(chainName) if err != nil { return xerrors.Errorf("error when cleaning BlockLog: %w", err) } return nil } // create_events filter and save all logs as events in DB. func create_events(contract *abi.SparkLink, session *xorm.Session, chainName string, logs []types.Log) (result []*model.Event, err error) { publish_events, err := chain.FilterEventPublish(contract, logs) if err != nil { return nil, xerrors.Errorf("%w", err) } publish, err := model.CreateFromBlockEventPublish(session, chainName, publish_events) if err != nil { return nil, xerrors.Errorf("%w", err) } transfer_events, err := chain.FilterEventTransfer(contract, logs) if err != nil { return nil, xerrors.Errorf("%w", err) } transfer, err := model.CreateFromBlockEventTransfer(session, chainName, transfer_events) if err != nil { return nil, xerrors.Errorf("%w", err) } result = make([]*model.Event, 0, len(logs)) result = append(result, publish...) result = append(result, transfer...) return result, nil } // create_nfts create NFT model records func create_nfts(contract *abi.SparkLink, session *xorm.Session, chainName string, events []*model.Event) (err error) { if len(events) == 0 { return nil } l := log.WithFields(log.Fields{"chain": chainName, "worker": "create_nfts"}) nfts := make([]*model.NFT, 0) existed_parent_nft_ids := make([]uint64, 0) for _, event := range events { if !event.IsMint() { continue } parent, err := chain.GetParentOf(contract, event.NFTId) // parent == 0 : Root NFT if err != nil { return xerrors.Errorf("error when getting parent of %d: %w", event.NFTId, err) } max_shill_count, err := contract.GetShillTimesByNFTId(nil, event.NFTId) if err != nil { return xerrors.Errorf("error when getting remain shill count of %d: %w", event.NFTId, err) } token_addr, err := contract.GetTokenAddrByNFTId(nil, event.NFTId) if err != nil { return xerrors.Errorf("error when getting TokenAddr of %d: %w", event.NFTId, err) } nft := &model.NFT{ Chain: chainName, NFTID: event.NFTId, Parent: parent, ShillCount: 0, MaxShillCount: max_shill_count, Owner: event.To, TokenAddr: token_addr.Hex(), } if parent != uint64(0) { existed_parent_nft_ids = append(existed_parent_nft_ids, parent) } nfts = append(nfts, nft) } if len(nfts) != 0 { affected, err := model.Engine.Insert(&nfts) if err != nil { return xerrors.Errorf("error when inserting NFT record: %w", err) } if int(affected) != len(nfts) { return xerrors.Errorf("error when Inserting NFT Record: records inserted mismatch total length: %d - %d", affected, len(nfts)) } } else { l.Debugf("No NFT created.") } if len(existed_parent_nft_ids) > 0 { err := increase_shill_count(session, chainName, existed_parent_nft_ids) if err != nil { return xerrors.Errorf("%w", err) } } return nil } // increase_shill_count increases 1 shill count for every given nft ids func increase_shill_count(session *xorm.Session, chainName string, nft_ids []uint64) error { l := log.WithFields(log.Fields{"worker": "increase_shill_count"}) for _, nft_id := range nft_ids { nft, err := model.FindNFT(chainName, nft_id) if err != nil { return xerrors.Errorf("error when finding NFT ID %d: %w", nft_id, err) } nft.ShillCount += 1 l.WithFields(log.Fields{"NFTID": nft.NFTID, "ShillCount": nft.ShillCount}).Infof("Updating NFT shill count") _, err = session.Cols("shill_count").ID(nft.Id).Update(nft) if err != nil { return xerrors.Errorf("error when updating NFT %d: %w", nft.NFTID, err) } } return nil } // update_nfts update existed NFT records func update_nfts(contract *abi.SparkLink, session *xorm.Session, chainName string, events []*model.Event) (err error) { if len(events) == 0 { return nil } l := log.WithFields(log.Fields{"worker": "update_nfts"}) for _, event := range events { if event.IsMint() { continue } nft, err := model.FindNFT(chainName, event.NFTId) if err != nil { return xerrors.Errorf("error when update NFT %d: %w", event.NFTId, err) } // Update NFT fields l.WithFields(log.Fields{"NFTID": nft.NFTID, "Owner": event.To}).Infof("Updating NFT owner") nft.Owner = event.To _, err = session.Cols("owner").ID(nft.Id).Update(nft) if err != nil { return xerrors.Errorf("error when updating NFT %d: %w", nft.NFTID, err) } } return nil }
from sklearn.metrics import precision_recall_fscore_support import numpy as np import tensorflow as tf def sequence_binary_tagging_metric_fn(per_example_loss, label_ids, logits, input_mask, is_real_example): predictions = tf.where(tf.logical_and(logits >= 0, input_mask == 1), tf.ones(tf.shape(logits)), tf.zeros(tf.shape(logits))) accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions, weights=is_real_example) loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example) return { "eval_accuracy": accuracy, "eval_loss": loss, } def sequence_tagging_metric_fn(per_example_loss, label_ids, logits, input_mask, is_real_example): """In default, use num_label-1 as mask id.""" num_label=logits.shape[-1].value predictions = tf.argmax(logits, axis=-1, output_type=tf.int32) shape = tf.shape(predictions) predictions = tf.where(input_mask == 1, predictions, tf.fill(shape, num_label - 1)) weights=tf.where(label_ids==num_label-1 ,tf.zeros(shape),tf.ones(shape)) accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions, weights=weights) loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example) return { "eval_accuracy": accuracy, "eval_loss": loss, } def single_label_classification_metric_fn(per_example_loss, label_ids, logits, input_mask, is_real_example): predictions = tf.argmax(logits, axis=-1) accuracy = tf.metrics.accuracy( labels=label_ids, predictions=predictions, weights=is_real_example) loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example) return { "eval_accuracy": accuracy, "eval_loss": loss, } def multi_label_tagging_metric_fn(per_example_loss, label_ids, logits, input_mask, is_real_example): return sequence_binary_tagging_metric_fn(per_example_loss, label_ids, logits, input_mask, is_real_example) def report_metrics(trues, preds, labels_list=None): trues=np.array(trues) preds=np.array(preds) assert trues.shape==preds.shape if trues.ndim==1: precision, recall, fscore, _=precision_recall_fscore_support(trues,preds,average='micro') else: metric_results=[precision_recall_fscore_support(true, pred, labels=labels_list, average='micro') for pred, true in zip(preds, trues)] precision, recall, fscore, _ = list(zip(*metric_results)) precision, recall, fscore=np.apply_along_axis(np.mean,1,[precision, recall, fscore]) accuracy=get_accuracy(trues,preds) report = 'accuracy: {}\n'.format(accuracy) + \ 'precision: {}\n'.format(precision) + \ 'recall: {}\n'.format(recall) + \ 'fscore: {}\n'.format(fscore) return report def threshold_selection(y_true, probs, threshold_num=21,f1_weight=0.5): assert threshold_num>1 metrics=numpy_metrics_at_thresholds(y_true, probs,threshold_num=threshold_num) accuracy, precisions, recalls, f1scores,thresholds=metrics score=f1_weight*f1scores+accuracy*(1-f1_weight) index = np.argmax(score) best=thresholds[index] best_metrics=np.asarray(metrics)[:,index] best_metrics=np.reshape(best_metrics,[-1]) tf.logging.info("best threshold is {}".format(best)) return best,best_metrics def numpy_metrics_at_thresholds(y_true, probs, threshold_num=21, threshold=0.5): epsilon = 1e-9 probs = np.array(probs) y_true = np.array(y_true) assert y_true.shape==probs.shape if probs.ndim==1: probs=np.expand_dims(probs,0) y_true=np.expand_dims(y_true,0) y_true = y_true == 1 total_true = np.sum(y_true, axis=-1) if threshold_num: assert threshold_num > 1 thresholds = [0 - epsilon] + [i / (threshold_num - 1) for i in range(1, threshold_num - 1)] + [1 + epsilon] elif threshold is not None: thresholds = [threshold] else: raise ValueError('Either threshold_num or threshold must be provided.') true = np.array([probs >= threshold for threshold in thresholds]) accuracy = get_accuracy(y_true,true) tps = np.sum(y_true & true, -1) precisions = tps / (np.sum(true, -1) + epsilon) recalls = tps / total_true f1scores = 2 * precisions * recalls / (precisions + recalls + epsilon) precisions = np.mean(precisions, -1) recalls = np.mean(recalls, -1) f1scores = np.mean(f1scores, -1) return accuracy, precisions, recalls, f1scores,thresholds def metrics_at_thresholds(y_true, probs, threshold_num=20,threshold=0.5): epsilon = 1e-9 total_true = tf.reduce_sum(y_true, axis=-1) y_true = tf.equal(y_true, 1) if threshold_num: assert threshold_num > 1 thresholds = [0 - epsilon] + [i / (threshold_num - 1) for i in range(1, threshold_num - 1)] + [1 + epsilon] elif threshold is not None: thresholds = [threshold] else: raise ValueError('Either threshold_num or threshold must be provided.') true = tf.stack([probs >= threshold for threshold in thresholds]) accuracy = tf.reduce_all(tf.equal(true, y_true), axis=-1) accuracy = tf.reduce_mean(tf.cast(accuracy, tf.float32), axis=-1) tps = tf.cast(tf.logical_and(y_true, true), tf.float32) tps = tf.reduce_sum(tps, axis=-1) precisions = tps / tf.add(tf.reduce_sum(tf.cast(true, tf.float32), -1), epsilon) recalls = tps / tf.cast(total_true, tf.float32) f1scores = 2 * precisions * recalls / (precisions + recalls + epsilon) precisions=tf.reduce_mean(precisions,-1) recalls=tf.reduce_mean(recalls,-1) f1scores=tf.reduce_mean(f1scores,-1) return accuracy, precisions, recalls, f1scores, thresholds def get_accuracy(y_true,y_pred): accuracy = np.sum(np.all(y_pred == y_true, axis=-1), -1) / len(y_true) return accuracy
// checkNames takes the root step and runs through all child steps in order // to check if the mentioned service name exists. It returns an appropriate // ParseError on the first missing/invalid service name. func (m Manager) checkNames(st step) error { if st.srvc != "" { if _, ok := m.srvcs[st.srvc]; !ok { return newParseError("unknown service: \"" + st.srvc + "\"") } } var err error curr := st.seq.head for curr != nil { if err = m.checkNames(*curr); err != nil { return err } curr = curr.next } return nil }
"""Test the Litter-Robot sensor entity.""" from unittest.mock import MagicMock from homeassistant.components.sensor import DOMAIN as PLATFORM_DOMAIN, SensorDeviceClass from homeassistant.const import PERCENTAGE, STATE_UNKNOWN from homeassistant.core import HomeAssistant from .conftest import setup_integration WASTE_DRAWER_ENTITY_ID = "sensor.test_waste_drawer" SLEEP_START_TIME_ENTITY_ID = "sensor.test_sleep_mode_start_time" async def test_waste_drawer_sensor( hass: HomeAssistant, mock_account: MagicMock ) -> None: """Tests the waste drawer sensor entity was set up.""" await setup_integration(hass, mock_account, PLATFORM_DOMAIN) sensor = hass.states.get(WASTE_DRAWER_ENTITY_ID) assert sensor assert sensor.state == "50.0" assert sensor.attributes["unit_of_measurement"] == PERCENTAGE async def test_sleep_time_sensor_with_sleep_disabled( hass: HomeAssistant, mock_account_with_sleep_disabled_robot: MagicMock ) -> None: """Tests the sleep mode start time sensor where sleep mode is disabled.""" await setup_integration( hass, mock_account_with_sleep_disabled_robot, PLATFORM_DOMAIN ) sensor = hass.states.get(SLEEP_START_TIME_ENTITY_ID) assert sensor assert sensor.state == STATE_UNKNOWN assert sensor.attributes["device_class"] == SensorDeviceClass.TIMESTAMP async def test_gauge_icon() -> None: """Test icon generator for gauge sensor.""" from homeassistant.components.litterrobot.sensor import icon_for_gauge_level GAUGE_EMPTY = "mdi:gauge-empty" GAUGE_LOW = "mdi:gauge-low" GAUGE = "mdi:gauge" GAUGE_FULL = "mdi:gauge-full" assert icon_for_gauge_level(None) == GAUGE_EMPTY assert icon_for_gauge_level(0) == GAUGE_EMPTY assert icon_for_gauge_level(5) == GAUGE_LOW assert icon_for_gauge_level(40) == GAUGE assert icon_for_gauge_level(80) == GAUGE_FULL assert icon_for_gauge_level(100) == GAUGE_FULL assert icon_for_gauge_level(None, 10) == GAUGE_EMPTY assert icon_for_gauge_level(0, 10) == GAUGE_EMPTY assert icon_for_gauge_level(5, 10) == GAUGE_EMPTY assert icon_for_gauge_level(40, 10) == GAUGE_LOW assert icon_for_gauge_level(80, 10) == GAUGE assert icon_for_gauge_level(100, 10) == GAUGE_FULL
/// /// Displays the scope hierarchy. /// /// Is used for testing purposes. /// pub fn show(&self, level: usize) { println!("{}==== Scope <{}> ====", " ".repeat(level), self.name); for (name, item) in self.items.borrow().iter() { println!("{}{}: {}", " ".repeat(level), name, item.borrow()); if Keyword::is_alias(name.as_str()) { continue; } if let Item::Module(ref module) = *item.borrow() { match module.scope() { Ok(scope) => scope.borrow().show(level + 1), Err(error) => log::warn!("SCOPE IS UNAVAILABLE: {:?}", error), } } } if let Some(parent) = self.parent.as_ref() { if parent.borrow().is_built_in { return; } parent.borrow().show(level + 1); } }
/** * Created by hzqiujiadi on 15/11/18. * hzqiujiadi [email protected] */ public class ChromeLikeLayout extends ViewGroup implements IOnExpandViewListener { private static final String TAG = "ChromeLikeView"; private static final float sMagicNumber = 0.55228475f; private static final int sDefaultCircleColor = 0xFFFFCC11; private static final int sDefaultBackgroundColor = 0xFF333333; private static final float sThreshold = 0.5f; private static final float sAnimCancelThreshold = 0.75f; private Threshold mAnimCancelThreshold; private Paint mPaint; private Path mPath; private float mDegrees; private float mTranslate; private int mCurrentFlag; private int mRadius = dp2px(40); private int mGap = dp2px(15); private IOnRippleListener mRippleListener; private GummyAnimatorHelper mGummyAnimatorHelper = new GummyAnimatorHelper(); private RippleAnimatorHelper mRippleAnimatorHelper = new RippleAnimatorHelper(); private TouchHelper mTouchHelper; public ChromeLikeLayout(Context context) { this(context,null); } public ChromeLikeLayout(Context context, AttributeSet attrs) { this(context, attrs,0); } public ChromeLikeLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private int getItemWidth(){ return mRadius*2 + mGap; } private float getMovingThreshold() { return getItemWidth() * sThreshold; } private int getCircleStartX(){ int contentWidth = getItemWidth(); int totalWidth = getMeasuredWidth(); int totalContextWidth = contentWidth * (getChildCount() - 1); return (totalWidth - totalContextWidth) >> 1; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int startXOffset = getCircleStartX(); int startYOffset = (b - t); for (int i = 0 ; i < getChildCount() ; i++ ){ View view = getChildAt(i); final int left = startXOffset + i * getItemWidth() - view.getMeasuredWidth()/2; final int right = left + view.getMeasuredWidth(); final int top = (startYOffset - view.getMeasuredHeight())>>1; final int bottom = top + view.getMeasuredHeight(); view.layout(left,top,right,bottom); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); measureChildren(getMeasuredWidth(),getMeasuredHeight()); } private void init() { final ViewConfiguration configuration = ViewConfiguration.get(getContext()); mTouchHelper = new TouchHelper(configuration.getScaledTouchSlop()); mAnimCancelThreshold = new Threshold(getMovingThreshold() * sAnimCancelThreshold); setBackgroundColor(sDefaultBackgroundColor); mPaint = new Paint(); mPaint.setColor(sDefaultCircleColor); mPaint.setStyle(Paint.Style.FILL); mPaint.setAntiAlias(true); mPath = new Path(); reset(); setWillNotDraw(false); } public void setIcons(List<Integer> drawables){ this.removeAllViews(); for ( int res : drawables ){ View v = new View(getContext()); v.setBackgroundResource(res); addView(v, LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); } } public void setRippleDuration(int duration){ mRippleAnimatorHelper.setDuration(duration); } public void setGummyDuration(int duration){ mGummyAnimatorHelper.setDuration(duration); } public void setRadius(int radius) { this.mRadius = radius; } public void onActionDown(){ reset(); } public void onActionMove(boolean isExpanded, TouchManager touchManager){ // feed MotionEvent after first expanded int motionX = touchManager.getMotionX(); if ( !mTouchHelper.isExpanded() && isExpanded ){ mTouchHelper.feed(motionX); return; } // reset the mTouchHelper if view is collapsed if ( !isExpanded ) { mTouchHelper.reset(); return; } // now, the view must be expanded. // feed the MotionEvent // to update mTouchHelper status. mTouchHelper.feed(motionX); // if not in moving status if ( !mTouchHelper.isMoving() ){ updateAlpha(1); updatePath( 0, 0, mRadius, false ); updateIconScale(1); return; } if ( mGummyAnimatorHelper.isAnimationStarted() ){ float currentX = mTouchHelper.getCurrentX(); if (mAnimCancelThreshold.absOverflow(currentX)) { mGummyAnimatorHelper.end(); mTouchHelper.resetToReady(currentX); } return; } // we can't move to left if the first circle is selected // neither to right if the last circle is selected if ( mCurrentFlag == prevOfCurrentFlag() ) mTouchHelper.testLeftEdge(); if ( mCurrentFlag == nextOfCurrentFlag() ) mTouchHelper.testRightEdge(); // now, the values can be trusted float currentX = mTouchHelper.getCurrentX(); float prevX = mTouchHelper.getPrevX(); updateAlpha(1); updatePath( currentX, prevX, mRadius, false ); updateIconScale(1); // if diff > threshold, update translate if ( Math.abs( currentX - prevX ) > getMovingThreshold() ){ if ( currentX > prevX ) updateCurrentFlag(nextOfCurrentFlag()); else updateCurrentFlag(prevOfCurrentFlag()); mAnimCancelThreshold.reset(); mGummyAnimatorHelper.launchAnim( currentX , prevX , mTranslate , flag2TargetTranslate() ); } } public void onActionUpOrCancel(boolean isExpanded){ if ( getChildCount() == 0 ) return; if ( !mTouchHelper.isExpanded() ) return; mTouchHelper.reset(); if ( isExpanded ){ boolean isRippleAnimEnabled = getChildCount() > 0; if ( isRippleAnimEnabled ){ if ( mRippleAnimatorHelper.isAnimationStarted() ) return; if ( mGummyAnimatorHelper.isAnimationStarted() ){ mGummyAnimatorHelper.end(); } mRippleAnimatorHelper.launchAnim(mRadius,getMeasuredWidth()); } else { if ( mRippleListener != null ) mRippleListener.onRippleAnimFinished(-1); } } } private void reset(){ onExpandView(0,false); updateAlpha(1); updateCurrentFlag((getChildCount() - 1) >> 1); mTranslate = flag2TargetTranslate(); } private void updateAlpha( float alpha ){ mPaint.setAlpha(Math.round(255 * alpha)); } private void updatePath(float currentX, float prevX, int radius, boolean animate){ updatePath(currentX,0,prevX,0,radius,animate); } private void updatePath(float currentX, float currentY, float prevX, float prevY, int radius, boolean animate ){ float distance = distance(prevX, prevY, currentX, currentY); float tempDegree = points2Degrees(prevX, prevY, currentX, currentY); if ( animate ){ if ( Math.abs( mDegrees - tempDegree ) > 5 ) distance = -distance; } else { //if ( distance < mTouchSlop ) distance = 0; mDegrees = tempDegree; } float longRadius = radius + distance; float shortRadius = radius - distance * 0.1f; mPath.reset(); mPath.lineTo(0, -radius); mPath.cubicTo(radius * sMagicNumber, -radius , longRadius, -radius * sMagicNumber , longRadius, 0); mPath.lineTo(0, 0); mPath.lineTo(0, radius); mPath.cubicTo(radius * sMagicNumber, radius , longRadius, radius * sMagicNumber , longRadius, 0); mPath.lineTo(0, 0); mPath.lineTo(0, -radius); mPath.cubicTo(-radius * sMagicNumber, -radius , -shortRadius, -radius * sMagicNumber , -shortRadius, 0); mPath.lineTo(0, 0); mPath.lineTo(0, radius); mPath.cubicTo(-radius * sMagicNumber, radius , -shortRadius, radius * sMagicNumber , -shortRadius, 0); mPath.lineTo(0, 0); //postInvalidate(); invalidate(); } private void updateIconScale( float fraction ){ float iconFraction = iconOffsetFraction(fraction); for (int i = 0 ; i < getChildCount(); i++ ){ View v = getChildAt(i); ViewCompat.setScaleX(v,iconFraction); ViewCompat.setScaleY(v,iconFraction); } } private void updateCurrentFlag(int flag){ mCurrentFlag = flag; boolean isPressed; for (int i = 0; i < getChildCount(); i++ ){ View view = getChildAt(i); isPressed = i == mCurrentFlag; view.setPressed(isPressed); } } private int nextOfCurrentFlag(){ int tmp = mCurrentFlag; tmp++; return Math.min(tmp,getChildCount()-1); } private int prevOfCurrentFlag(){ int tmp = mCurrentFlag; tmp--; return Math.max(tmp,0); } @Override protected void onDraw(Canvas canvas) { if ( getChildCount() == 0 ) return; int centerY = getMeasuredHeight() >> 1; canvas.save(); canvas.translate(mTranslate, centerY); canvas.rotate(mDegrees); canvas.drawPath(mPath, mPaint); canvas.restore(); } private static float distance(float x1,float y1, float x2, float y2){ return (float) Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); } private int flag2TargetTranslate(){ int startXOffset = getCircleStartX(); return startXOffset + getItemWidth() * mCurrentFlag; } private static float points2Degrees(float x1, float y1, float x2, float y2){ double angle = Math.atan2(y2-y1,x2-x1); return (float) Math.toDegrees(angle); } @Override public void onExpandView(float fraction, boolean isFromCancel) { float circleFraction = circleOffsetFraction(fraction); if (isFromCancel) updateAlpha(circleFraction); updatePath(0,0,Math.round(mRadius*circleFraction),true); updateIconScale(fraction); } private static final float sFactorScaleCircle = 0.75f; private static final float sFactorScaleIcon = 0.3f; private float circleOffsetFraction( float fraction ){ return offsetFraction(fraction, sFactorScaleCircle); } private float iconOffsetFraction( float fraction ){ return offsetFraction(fraction, sFactorScaleIcon); } private float offsetFraction(float fraction, float factor){ float result = (fraction - factor) / (1 - factor); result = result > 0 ? result : 0; return result; } public void setRippleListener(IOnRippleListener mRippleListener) { this.mRippleListener = mRippleListener; } public void setCircleColor(int circleColor) { mPaint.setColor(circleColor); } public void setGap(int gap) { this.mGap = gap; } public interface IOnRippleListener { void onRippleAnimFinished(int index); } public static class TouchHelper { private final int mTouchSlop; private int mStatus; private final int STATUS_NONE = 0; private final int STATUS_EXPANDED = 1; private final int STATUS_READY = 2; private final int STATUS_MOVING = 3; private float mReadyPrevX; private float mMovingPrevX; private float mMovingCurrentX; public TouchHelper(int mTouchSlop) { this.mTouchSlop = mTouchSlop; } public boolean isMoving(){ return mStatus == STATUS_MOVING; } public boolean isExpanded(){ return mStatus > STATUS_NONE; } public void feed(float motionX){ int status = mStatus; //float tmpX = MotionEventCompat.getX(event,pointerIndex); switch ( status ){ case STATUS_NONE: case STATUS_EXPANDED: mReadyPrevX = motionX; mStatus = STATUS_READY; break; case STATUS_READY: if ( Math.abs(motionX - mReadyPrevX) > mTouchSlop ){ mMovingPrevX = motionX; mMovingCurrentX = motionX; mStatus = STATUS_MOVING; } break; case STATUS_MOVING: mMovingCurrentX = motionX; break; } } public float getPrevX(){ return mMovingPrevX; } public float getCurrentX(){ return mMovingCurrentX; } public void resetToReady(float animFromX){ mStatus = STATUS_READY; mReadyPrevX = animFromX; } public void reset(){ mStatus = STATUS_NONE; mReadyPrevX = 0; mMovingPrevX = 0; } public void testLeftEdge() { if ( mMovingCurrentX < mMovingPrevX ) mMovingPrevX = mMovingCurrentX; } public void testRightEdge() { if ( mMovingCurrentX > mMovingPrevX ) mMovingPrevX = mMovingCurrentX; } } public static class Threshold { private boolean mInit; private float mPrev; private float mThreshold; public Threshold(float threshold) { this.mThreshold = threshold; } private boolean checkAbsOverflow(float now){ if (Math.abs(now - mPrev) > mThreshold) return true; else return false; } public boolean absOverflow(float value){ if (!mInit){ mPrev = value; mInit = true; return false; } return checkAbsOverflow(value); } public void reset(){ mInit = false; mPrev = 0; } } /*** * * Ripple animation * * */ private class RippleAnimatorHelper extends AnimationListenerAdapter { private float mAnimFromRadius; private float mAnimToRadius; private boolean mAnimationStarted; private boolean mEventDispatched; private int mDuration = 300; public void onAnimationUpdate(float interpolation) { int currentRadius = FloatEvaluator.evaluate(interpolation,mAnimFromRadius,mAnimToRadius).intValue(); updatePath(0, 0, currentRadius, true); updateAlpha(1-interpolation); } public void launchAnim(float fromRadius, float toRadius) { mAnimFromRadius = fromRadius; mAnimToRadius = toRadius; Animation animation = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { onAnimationUpdate(interpolatedTime); } }; animation.setDuration(mDuration); animation.setInterpolator(new FastOutSlowInInterpolator()); animation.setAnimationListener(this); View target = ChromeLikeLayout.this.getChildAt(mCurrentFlag); if ( target == null ) return; target.clearAnimation(); target.startAnimation(animation); mAnimationStarted = true; mEventDispatched = false; } public boolean isAnimationStarted() { return mAnimationStarted; } @Override public void onAnimationEnd(Animation animation) { mAnimationStarted = false; if ( !mEventDispatched && mRippleListener != null ){ mRippleListener.onRippleAnimFinished(mCurrentFlag); mEventDispatched = true; } } public void setDuration(int duration) { this.mDuration = duration; } } /*** * * Gummy animation * * */ private class GummyAnimatorHelper extends AnimationListenerAdapter { private float mAnimFromX; private float mAnimToX; private float mAnimFromTranslate; private float mAnimToTranslate; private boolean mAnimationStarted; private int mDuration = 300; public void onAnimationUpdate(float interpolation) { Float currentX = FloatEvaluator.evaluate(interpolation,mAnimFromX,mAnimToX); mTranslate = FloatEvaluator.evaluate(interpolation, mAnimFromTranslate, mAnimToTranslate); updatePath(currentX, mAnimToX, mRadius, true); } public void launchAnim(float fromX, float toX, float fromTranslate, float toTranslate) { mAnimFromX = fromX; mAnimToX = toX; mAnimFromTranslate = fromTranslate; mAnimToTranslate = toTranslate; Animation animation = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { onAnimationUpdate(interpolatedTime); } }; animation.setDuration(mDuration); animation.setInterpolator(new BounceInterpolator()); animation.setAnimationListener(this); ChromeLikeLayout.this.clearAnimation(); ChromeLikeLayout.this.startAnimation(animation); mAnimationStarted = true; } public boolean isAnimationStarted() { return mAnimationStarted; } @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (mAnimationStarted){ mTouchHelper.resetToReady(mAnimFromX); mAnimationStarted = false; } } public void setDuration(int duration) { this.mDuration = duration; } public void end() { // false immediately mAnimationStarted = false; // clear animation ChromeLikeLayout.this.clearAnimation(); // anim to end immediately onAnimationUpdate(1); } } private static class FloatEvaluator { public static Float evaluate(float fraction, Number startValue, Number endValue) { float startFloat = startValue.floatValue(); return startFloat + fraction * (endValue.floatValue() - startFloat); } } }
// Copyright 2016-2019, Pulumi Corporation. All rights reserved. import * as aws from "@pulumi/aws"; import * as pulumi from "@pulumi/pulumi"; // Create the role for the Lambda to assume const lambdaRole = new aws.iam.Role("lambdaRole", { assumeRolePolicy: { Version: "2012-10-17", Statement: [ { Action: "sts:AssumeRole", Principal: { Service: "lambda.amazonaws.com", }, Effect: "Allow", Sid: "", }, ], }, }); // Attach the fullaccess policy to the Lambda role created above const rolepolicyattachment = new aws.iam.RolePolicyAttachment("lambdaRoleAttachment", { role: lambdaRole, policyArn: aws.iam.ManagedPolicy.AWSLambdaBasicExecutionRole, }); // Create the Lambda to execute const lambda = new aws.lambda.Function("lambdaFunction", { code: new pulumi.asset.AssetArchive({ ".": new pulumi.asset.FileArchive("./app"), }), runtime: "nodejs12.x", role: lambdaRole.arn, handler: "index.handler", }); // Give API Gateway permissions to invoke the Lambda const lambdapermission = new aws.lambda.Permission("lambdaPermission", { action: "lambda:InvokeFunction", principal: "apigateway.amazonaws.com", function: lambda, }); // Set up the API Gateway const apigw = new aws.apigatewayv2.Api("httpApiGateway", { protocolType: "HTTP", routeKey: "GET /", target: lambda.invokeArn, }); export const endpoint = apigw.apiEndpoint;
/** * Adds NBT tag to YAML section. * @param yaml YAML section to add tag to. * @param name Name of the tag. * @param tag Tag to add. * @throws ReflectiveOperationException Thrown when something went wrong while accessing reflection classes in Minecraft code (usually when class was not properly updated to new Minecraft version). */ public static void addTag(ConfigurationSection yaml, String name, NBTBase tag) throws ReflectiveOperationException{ switch (tag.getTypeId()) { case 1: yaml.set(name + ".byte", ((NBTTagByte) tag).f()); break; case 2: yaml.set(name + ".short", ((NBTTagShort) tag).e()); break; case 3: yaml.set(name + ".int", ((NBTTagInt) tag).d()); break; case 4: yaml.set(name + ".long", ((NBTTagLong) tag).c()); break; case 5: yaml.set(name + ".float", ((NBTTagFloat) tag).h()); break; case 6: yaml.set(name + ".double", ((NBTTagDouble) tag).g()); break; case 7: Array yaml.set(name + ".byteArray", ArrayConvert.convert(((NBTTagByteArray) tag).c())); break; case 11: yaml.set(name + ".intArray", ArrayConvert.convert(((NBTTagIntArray) tag).c())); break; case 8: yaml.set(name, ((NBTTagString) tag).a_()); break; case 9: NBTTagList listTag = (NBTTagList) tag; Field listField = NBTTagList.class.getDeclaredField("list"); listField.setAccessible(true); List<NBTBase> tags = (List) listField.get(listTag); List list = new ArrayList(); if (tags.get(0).getTypeId() == 8) { for (int i = 0; i < tags.size(); i++) { list.add(((NBTTagString)tags.get(i)).a_()); } } else { for (int i = 0; i < tags.size(); i++) { ConfigurationSection listSection = new YamlConfiguration() .createSection("foo"); addTagWithoutName(listSection, tags.get(i)); list.add(listSection); } } yaml.set(name, list.toArray()); break; case 10: ConfigurationSection newSection = yaml.createSection(name).createSection("compound"); NBTTagCompound compoundTag = (NBTTagCompound) tag; Set<String> tagKeys = compoundTag.c(); for (String key : tagKeys) { addTag(newSection, key, compoundTag.get(key)); } } }
import cn from 'classnames' import * as React from 'react' import { CapUIFontWeight, CapUILineHeight } from '../../styles' import { BoxProps } from '../box' import { DropdownListItem as DropdownListItemStyled } from './Dropdown.styles' export type DropdownListItemProps = BoxProps & { active?: boolean } const DropdownListItem: React.FC<DropdownListItemProps> = ({ children, className, active, ...props }) => { return ( <DropdownListItemStyled width="100%" px={3} py={2} fontFamily="body" m={0} bg="white" fontWeight={active ? CapUIFontWeight.Semibold : CapUIFontWeight.Normal} className={cn('cap-dropdown__item', className)} fontSize={3} lineHeight={CapUILineHeight.Base} color="gray.900" as="li" {...props} > {children} </DropdownListItemStyled> ) } DropdownListItem.displayName = 'Dropdown.Item' export default DropdownListItem
<filename>src/melee_combat_system.rs<gh_stars>10-100 use super::{components::*, gamelog::GameLog, particle_system::ParticleBuilder, skill_bonus}; use legion::prelude::*; use rltk::{console, RandomNumberGenerator}; pub fn build() -> Box<(dyn Schedulable + 'static)> { SystemBuilder::new("melee_combat") .with_query(<( Read<WantsToMelee>, Read<Attributes>, Read<Skills>, Read<Pools>, )>::query()) .read_component::<Name>() .read_component::<Position>() .read_component::<HungerClock>() .with_query(<(Read<MeleeWeapon>, Read<Equipped>)>::query()) .with_query(<(Read<Wearable>, Read<Equipped>)>::query()) .read_component::<NaturalAttackDefense>() .write_resource::<GameLog>() .write_resource::<ParticleBuilder>() .write_resource::<RandomNumberGenerator>() .read_resource::<Entity>() .build( |command_buffer, world, (log, particle_builder, rng, player_entity), (query, query_melee, query_defense)| { for (entity, (wants_melee, attacker_attributes, attacker_skills, attacker_pools)) in query.iter_entities(world) { command_buffer.remove_component::<WantsToMelee>(entity); let target = wants_melee.target; let target_attributes = world.get_component::<Attributes>(target); let target_skills = world.get_component::<Skills>(target); let target_pools = world.get_component::<Pools>(target); let attacker_name = match world.get_component::<Name>(entity) { Some(name) => name.name.clone(), None => "-Unnamed-".to_string(), }; let target_name = match world.get_component::<Name>(target) { Some(name) => name.name.clone(), None => "-Unnamed-".to_string(), }; match (target_attributes, target_skills, target_pools) { (Some(target_attributes), Some(target_skills), Some(target_pools)) => { // Are the attacker and defender alive? Only attack if they are if attacker_pools.hit_points.current > 0 && target_pools.hit_points.current > 0 { let mut weapon_info = MeleeWeapon { attribute: WeaponAttribute::Might, hit_bonus: 0, damage_n_dice: 1, damage_die_type: 4, damage_bonus: 0, }; if let Some(nat) = world.get_component::<NaturalAttackDefense>(entity) { if !nat.attacks.is_empty() { let attack_index = if nat.attacks.len() == 1 { 0 } else { rng.roll_dice(1, nat.attacks.len() as i32) as usize - 1 }; let attack = &nat.attacks[attack_index]; weapon_info.hit_bonus = attack.hit_bonus; weapon_info.damage_n_dice = attack.damage_n_dice; weapon_info.damage_die_type = attack.damage_die_type; weapon_info.damage_bonus = attack.damage_bonus; } } for (melee, wielded) in query_melee.iter(world) { if wielded.owner == entity && wielded.slot == EquipmentSlot::Melee { weapon_info = *melee; } } let natural_roll = rng.roll_dice(1, 20); let attribute_hit_bonus = match weapon_info.attribute { WeaponAttribute::Might => attacker_attributes.might.bonus, WeaponAttribute::Quickness => { attacker_attributes.quickness.bonus } }; let skill_hit_bonus = skill_bonus(Skill::Melee, &*attacker_skills); let weapon_hit_bonus = weapon_info.hit_bonus; let mut status_hit_bonus = 0; if let Some(hc) = world.get_component::<HungerClock>(entity) { if hc.state == HungerState::WellFed { status_hit_bonus += 1; } } let modified_hit_roll = natural_roll + attribute_hit_bonus + skill_hit_bonus + weapon_hit_bonus + status_hit_bonus; let mut armor_item_bonus_f = 0.0; for (armor, wielded) in query_defense.iter(world) { if wielded.owner == wants_melee.target { armor_item_bonus_f += armor.armor_class; } } let base_armor_class = match world.get_component::<NaturalAttackDefense>(target) { None => 10, Some(nat) => nat.armor_class.unwrap_or(10), }; let armor_quickness_bonus = target_attributes.quickness.bonus; let armor_skill_bonus = skill_bonus(Skill::Defense, &*target_skills); let armor_item_bonus = armor_item_bonus_f as i32; let armor_class = base_armor_class + armor_quickness_bonus + armor_skill_bonus + armor_item_bonus; if natural_roll == 1 { // Natural 1 miss log.entries.push(format!( "{} considers attacking {}, but misjudges the timing.", attacker_name, target_name )); if let Some(pos) = world.get_component::<Position>(target) { particle_builder.request( pos.x, pos.y, rltk::RGB::named(rltk::BLUE), rltk::RGB::named(rltk::BLACK), rltk::to_cp437('‼'), 200.0, ); } } else if natural_roll == 20 || modified_hit_roll > armor_class { // Target hit! let base_damage = rng.roll_dice( weapon_info.damage_n_dice, weapon_info.damage_die_type, ); let attr_damage_bonus = attacker_attributes.might.bonus; let skill_damage_bonus = skill_bonus(Skill::Melee, &*attacker_skills); let weapon_damage_bonus = weapon_info.damage_bonus; let damage = i32::max( 0, base_damage + attr_damage_bonus + skill_damage_bonus + weapon_damage_bonus, ); SufferDamage::new_damage( &command_buffer, target, damage, entity == **player_entity, ); log.entries.push(format!( "{} hits {}, for {} hp.", &attacker_name, &target_name, damage )); if let Some(pos) = world.get_component::<Position>(target) { particle_builder.request( pos.x, pos.y, rltk::RGB::named(rltk::ORANGE), rltk::RGB::named(rltk::BLACK), rltk::to_cp437('‼'), 200.0, ); } } else { // Miss log.entries.push(format!( "{} attacks {}, but can't connect.", attacker_name, target_name )); if let Some(pos) = world.get_component::<Position>(target) { particle_builder.request( pos.x, pos.y, rltk::RGB::named(rltk::CYAN), rltk::RGB::named(rltk::BLACK), rltk::to_cp437('‼'), 200.0, ); } } } else { console::log(&format!( "{}[{}] => {}[{}] - already dead - cannot do melee", attacker_name, entity, target_name, target )); } } _ => { console::log(&format!( "{} [{}] does not posses required components to fight", target_name, target )); } } } }, ) }
<gh_stars>0 /** * \file protocol.h * * \brief Header file of the protocol component. This file provides a platform-agnostic API to * receive APDUs and send the response. * * This module is initialized by calling \ref protocol_init. Once initialized, the rest of the API * can be safely used. */ #ifndef PROTOCOL_H #define PROTOCOL_H #include <core/core.h> /** * \brief Struct that represents a c_apdu and r_apdu as defined in the ISO_7816-3/4. */ typedef struct { u8 cla; ///< Class byte. u8 ins; ///< Instruction byte. u8 p1; ///< P1 byte. u8 p2; ///< P2 byte. u8 p3; ///< P3 byte. u8 data[256]; ///< Data buffer. u16 nc; ///< Number of bytes received. u16 ne; ///< Expected data. u16 nr; ///< Number of bytes to be sent. u8 sw1; ///< First byte of the status word. u8 sw2; ///< Second byte of the status word. } apdu_t; // Initialize the protocol and send the ATR. void protocol_init(void); // Receive a command APDU. apdu_t* protocol_receive(void); // Send the data and/or the SW. void protocol_send(const apdu_t* r_apdu); // Helper function to set the status word given a u16. void protocol_set_sw(u16 sw, apdu_t* apdu); // Return a mutable pointer to the apdu_t struct. apdu_t* protocol_get_apdu_as_mut_ptr(void); #endif
/** * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.sayee.sxsy.modules.epidemic.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sayee.sxsy.modules.epidemic.dao.EgressInfoDao; import com.sayee.sxsy.modules.epidemic.entity.EgressInfo; import com.sayee.sxsy.modules.epidemic.entity.Statis; import com.sayee.sxsy.modules.sys.utils.UserUtils; import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion; import org.apache.commons.collections.CollectionUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.sayee.sxsy.common.config.Global; import com.sayee.sxsy.common.persistence.Page; import com.sayee.sxsy.common.web.BaseController; import com.sayee.sxsy.common.utils.StringUtils; import com.sayee.sxsy.modules.epidemic.entity.EpidemicDaily; import com.sayee.sxsy.modules.epidemic.service.EpidemicDailyService; import java.util.ArrayList; import java.util.List; /** * 疫情日报Controller * @author zhangfan * @version 2020-02-11 */ @Controller @RequestMapping(value = "${adminPath}/epidemic/epidemicDaily") public class EpidemicDailyController extends BaseController { @Autowired private EpidemicDailyService epidemicDailyService; @ModelAttribute public EpidemicDaily get(@RequestParam(required=false) String id) { EpidemicDaily entity = null; if (StringUtils.isNotBlank(id)){ entity = epidemicDailyService.get(id); } if (entity == null){ entity = new EpidemicDaily(); } return entity; } @RequiresPermissions("epidemic:epidemicDaily:view") @RequestMapping(value = {"list", ""}) public String list(EpidemicDaily epidemicDaily, HttpServletRequest request, HttpServletResponse response, Model model) { Page<EpidemicDaily> page = epidemicDailyService.findPage(new Page<EpidemicDaily>(request, response), epidemicDaily); model.addAttribute("page", page); return "modules/epidemic/epidemicDailyList"; } @RequiresPermissions("epidemic:epidemicDaily:view") @RequestMapping(value = "form") public String form(EpidemicDaily epidemicDaily, Model model,HttpServletRequest request) { if (CollectionUtils.isEmpty(epidemicDaily.getEgressInfoList())){ List<EgressInfo> list=new ArrayList<>(); EgressInfo egressInfo=new EgressInfo(); egressInfo.setEgressName(UserUtils.getUser().getName());//名称 egressInfo= epidemicDailyService.getAcquiesce(egressInfo); if (egressInfo==null){ egressInfo=new EgressInfo(); egressInfo.setEgressSex("1"); egressInfo.setRelation("1"); } egressInfo.setIsEgress("0"); list.add(egressInfo); epidemicDaily.setEgressInfoList(list); } model.addAttribute("epidemicDaily", epidemicDaily); String type = request.getParameter("type"); if("view".equals(type)){ return "modules/epidemic/epidemicDailyView"; }else{ return "modules/epidemic/epidemicDailyForm"; } } @RequiresPermissions("epidemic:epidemicDaily:edit") @RequestMapping(value = "save") public String save(EpidemicDaily epidemicDaily, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) { if (!beanValidator(model, epidemicDaily)){ return form(epidemicDaily, model,request); } epidemicDailyService.save(epidemicDaily); addMessage(redirectAttributes, "保存疫情日报成功"); return "redirect:"+Global.getAdminPath()+"/epidemic/epidemicDaily/?repage"; } @RequiresPermissions("epidemic:epidemicDaily:edit") @RequestMapping(value = "delete") public String delete(EpidemicDaily epidemicDaily, RedirectAttributes redirectAttributes) { epidemicDailyService.delete(epidemicDaily); addMessage(redirectAttributes, "删除疫情日报成功"); return "redirect:"+Global.getAdminPath()+"/epidemic/epidemicDaily/?repage"; } @RequestMapping(value = "statistics") public String statistics(EpidemicDaily epidemicDaily, HttpServletRequest request, HttpServletResponse response, Model model) { Page<Statis> page = epidemicDailyService.findStatistics(new Page<Statis>(request, response), epidemicDaily); model.addAttribute("page", page); return "modules/epidemic/statistics"; } }
<filename>NGSpice/ngspice-30/src/spicelib/devices/bsim3v32/bsim3v32def.h /********** Copyright 2001 Regents of the University of California. All rights reserved. Author: 1995 <NAME> and <NAME>. Author: 1997-1999 <NAME>. Author: 2001 <NAME> Modified by <NAME> 2002 and Dietmar Warning 2003 File: bsim3v32def.h **********/ #ifndef BSIM3v32 #define BSIM3v32 #include "ngspice/ifsim.h" #include "ngspice/gendefs.h" #include "ngspice/cktdefs.h" #include "ngspice/complex.h" #include "ngspice/noisedef.h" typedef struct sBSIM3v32instance { struct GENinstance gen; #define BSIM3v32modPtr(inst) ((struct sBSIM3v32model *)((inst)->gen.GENmodPtr)) #define BSIM3v32nextInstance(inst) ((struct sBSIM3v32instance *)((inst)->gen.GENnextInstance)) #define BSIM3v32name gen.GENname #define BSIM3v32states gen.GENstate const int BSIM3v32dNode; const int BSIM3v32gNode; const int BSIM3v32sNode; const int BSIM3v32bNode; int BSIM3v32dNodePrime; int BSIM3v32sNodePrime; int BSIM3v32qNode; /* MCJ */ /* MCJ */ double BSIM3v32ueff; double BSIM3v32thetavth; double BSIM3v32von; double BSIM3v32vdsat; double BSIM3v32cgdo; double BSIM3v32cgso; double BSIM3v32vjsm; double BSIM3v32IsEvjsm; double BSIM3v32vjdm; double BSIM3v32IsEvjdm; double BSIM3v32l; double BSIM3v32w; double BSIM3v32m; double BSIM3v32drainArea; double BSIM3v32sourceArea; double BSIM3v32drainSquares; double BSIM3v32sourceSquares; double BSIM3v32drainPerimeter; double BSIM3v32sourcePerimeter; double BSIM3v32sourceConductance; double BSIM3v32drainConductance; double BSIM3v32delvto; double BSIM3v32mulu0; double BSIM3v32vth0; double BSIM3v32vfb; double BSIM3v32vfbzb; double BSIM3v32u0temp; double BSIM3v32tconst; double BSIM3v32icVBS; double BSIM3v32icVDS; double BSIM3v32icVGS; int BSIM3v32off; int BSIM3v32mode; int BSIM3v32nqsMod; int BSIM3v32geo; /* OP point */ double BSIM3v32qinv; double BSIM3v32cd; double BSIM3v32cbs; double BSIM3v32cbd; double BSIM3v32csub; double BSIM3v32gm; double BSIM3v32gds; double BSIM3v32gmbs; double BSIM3v32gbd; double BSIM3v32gbs; double BSIM3v32gbbs; double BSIM3v32gbgs; double BSIM3v32gbds; double BSIM3v32cggb; double BSIM3v32cgdb; double BSIM3v32cgsb; double BSIM3v32cbgb; double BSIM3v32cbdb; double BSIM3v32cbsb; double BSIM3v32cdgb; double BSIM3v32cddb; double BSIM3v32cdsb; double BSIM3v32capbd; double BSIM3v32capbs; double BSIM3v32cqgb; double BSIM3v32cqdb; double BSIM3v32cqsb; double BSIM3v32cqbb; double BSIM3v32qgate; double BSIM3v32qbulk; double BSIM3v32qdrn; double BSIM3v32gtau; double BSIM3v32gtg; double BSIM3v32gtd; double BSIM3v32gts; double BSIM3v32gtb; double BSIM3v32rds; /* Noise bugfix */ double BSIM3v32Vgsteff; double BSIM3v32Vdseff; double BSIM3v32Abulk; double BSIM3v32AbovVgst2Vtm; struct bsim3v32SizeDependParam *pParam; unsigned BSIM3v32lGiven :1; unsigned BSIM3v32wGiven :1; unsigned BSIM3v32mGiven :1; unsigned BSIM3v32drainAreaGiven :1; unsigned BSIM3v32sourceAreaGiven :1; unsigned BSIM3v32drainSquaresGiven :1; unsigned BSIM3v32sourceSquaresGiven :1; unsigned BSIM3v32drainPerimeterGiven :1; unsigned BSIM3v32sourcePerimeterGiven :1; unsigned BSIM3v32delvtoGiven :1; unsigned BSIM3v32mulu0Given :1; unsigned BSIM3v32dNodePrimeSet :1; unsigned BSIM3v32sNodePrimeSet :1; unsigned BSIM3v32icVBSGiven :1; unsigned BSIM3v32icVDSGiven :1; unsigned BSIM3v32icVGSGiven :1; unsigned BSIM3v32nqsModGiven :1; unsigned BSIM3v32geoGiven :1; double *BSIM3v32DdPtr; double *BSIM3v32GgPtr; double *BSIM3v32SsPtr; double *BSIM3v32BbPtr; double *BSIM3v32DPdpPtr; double *BSIM3v32SPspPtr; double *BSIM3v32DdpPtr; double *BSIM3v32GbPtr; double *BSIM3v32GdpPtr; double *BSIM3v32GspPtr; double *BSIM3v32SspPtr; double *BSIM3v32BdpPtr; double *BSIM3v32BspPtr; double *BSIM3v32DPspPtr; double *BSIM3v32DPdPtr; double *BSIM3v32BgPtr; double *BSIM3v32DPgPtr; double *BSIM3v32SPgPtr; double *BSIM3v32SPsPtr; double *BSIM3v32DPbPtr; double *BSIM3v32SPbPtr; double *BSIM3v32SPdpPtr; double *BSIM3v32QqPtr; double *BSIM3v32QdpPtr; double *BSIM3v32QgPtr; double *BSIM3v32QspPtr; double *BSIM3v32QbPtr; double *BSIM3v32DPqPtr; double *BSIM3v32GqPtr; double *BSIM3v32SPqPtr; double *BSIM3v32BqPtr; #ifdef USE_OMP /* per instance storage of results, to update matrix at a later stge */ double BSIM3v32rhsG; double BSIM3v32rhsB; double BSIM3v32rhsD; double BSIM3v32rhsS; double BSIM3v32rhsQ; double BSIM3v32DdPt; double BSIM3v32GgPt; double BSIM3v32SsPt; double BSIM3v32BbPt; double BSIM3v32DPdpPt; double BSIM3v32SPspPt; double BSIM3v32DdpPt; double BSIM3v32GbPt; double BSIM3v32GdpPt; double BSIM3v32GspPt; double BSIM3v32SspPt; double BSIM3v32BdpPt; double BSIM3v32BspPt; double BSIM3v32DPspPt; double BSIM3v32DPdPt; double BSIM3v32BgPt; double BSIM3v32DPgPt; double BSIM3v32SPgPt; double BSIM3v32SPsPt; double BSIM3v32DPbPt; double BSIM3v32SPbPt; double BSIM3v32SPdpPt; double BSIM3v32QqPt; double BSIM3v32QdpPt; double BSIM3v32QgPt; double BSIM3v32QspPt; double BSIM3v32QbPt; double BSIM3v32DPqPt; double BSIM3v32GqPt; double BSIM3v32SPqPt; double BSIM3v32BqPt; #endif #define BSIM3v32vbd BSIM3v32states+ 0 #define BSIM3v32vbs BSIM3v32states+ 1 #define BSIM3v32vgs BSIM3v32states+ 2 #define BSIM3v32vds BSIM3v32states+ 3 #define BSIM3v32qb BSIM3v32states+ 4 #define BSIM3v32cqb BSIM3v32states+ 5 #define BSIM3v32qg BSIM3v32states+ 6 #define BSIM3v32cqg BSIM3v32states+ 7 #define BSIM3v32qd BSIM3v32states+ 8 #define BSIM3v32cqd BSIM3v32states+ 9 #define BSIM3v32qbs BSIM3v32states+ 10 #define BSIM3v32qbd BSIM3v32states+ 11 #define BSIM3v32qcheq BSIM3v32states+ 12 #define BSIM3v32cqcheq BSIM3v32states+ 13 #define BSIM3v32qcdump BSIM3v32states+ 14 #define BSIM3v32cqcdump BSIM3v32states+ 15 #define BSIM3v32qdef BSIM3v32states+ 16 #define BSIM3v32numStates 17 /* indices to the array of BSIM3v32 NOISE SOURCES */ #define BSIM3v32RDNOIZ 0 #define BSIM3v32RSNOIZ 1 #define BSIM3v32IDNOIZ 2 #define BSIM3v32FLNOIZ 3 #define BSIM3v32TOTNOIZ 4 #define BSIM3v32NSRCS 5 /* the number of BSIM3v32 MOSFET noise sources */ #ifndef NONOISE double BSIM3v32nVar[NSTATVARS][BSIM3v32NSRCS]; #else /* NONOISE */ double **BSIM3v32nVar; #endif /* NONOISE */ } BSIM3v32instance ; struct bsim3v32SizeDependParam { double Width; double Length; double BSIM3v32cdsc; double BSIM3v32cdscb; double BSIM3v32cdscd; double BSIM3v32cit; double BSIM3v32nfactor; double BSIM3v32xj; double BSIM3v32vsat; double BSIM3v32at; double BSIM3v32a0; double BSIM3v32ags; double BSIM3v32a1; double BSIM3v32a2; double BSIM3v32keta; double BSIM3v32nsub; double BSIM3v32npeak; double BSIM3v32ngate; double BSIM3v32gamma1; double BSIM3v32gamma2; double BSIM3v32vbx; double BSIM3v32vbi; double BSIM3v32vbm; double BSIM3v32vbsc; double BSIM3v32xt; double BSIM3v32phi; double BSIM3v32litl; double BSIM3v32k1; double BSIM3v32kt1; double BSIM3v32kt1l; double BSIM3v32kt2; double BSIM3v32k2; double BSIM3v32k3; double BSIM3v32k3b; double BSIM3v32w0; double BSIM3v32nlx; double BSIM3v32dvt0; double BSIM3v32dvt1; double BSIM3v32dvt2; double BSIM3v32dvt0w; double BSIM3v32dvt1w; double BSIM3v32dvt2w; double BSIM3v32drout; double BSIM3v32dsub; double BSIM3v32vth0; double BSIM3v32ua; double BSIM3v32ua1; double BSIM3v32ub; double BSIM3v32ub1; double BSIM3v32uc; double BSIM3v32uc1; double BSIM3v32u0; double BSIM3v32ute; double BSIM3v32voff; double BSIM3v32vfb; double BSIM3v32delta; double BSIM3v32rdsw; double BSIM3v32rds0; double BSIM3v32prwg; double BSIM3v32prwb; double BSIM3v32prt; double BSIM3v32eta0; double BSIM3v32etab; double BSIM3v32pclm; double BSIM3v32pdibl1; double BSIM3v32pdibl2; double BSIM3v32pdiblb; double BSIM3v32pscbe1; double BSIM3v32pscbe2; double BSIM3v32pvag; double BSIM3v32wr; double BSIM3v32dwg; double BSIM3v32dwb; double BSIM3v32b0; double BSIM3v32b1; double BSIM3v32alpha0; double BSIM3v32alpha1; double BSIM3v32beta0; /* CV model */ double BSIM3v32elm; double BSIM3v32cgsl; double BSIM3v32cgdl; double BSIM3v32ckappa; double BSIM3v32cf; double BSIM3v32clc; double BSIM3v32cle; double BSIM3v32vfbcv; double BSIM3v32noff; double BSIM3v32voffcv; double BSIM3v32acde; double BSIM3v32moin; /* Pre-calculated constants */ double BSIM3v32dw; double BSIM3v32dl; double BSIM3v32leff; double BSIM3v32weff; double BSIM3v32dwc; double BSIM3v32dlc; double BSIM3v32leffCV; double BSIM3v32weffCV; double BSIM3v32abulkCVfactor; double BSIM3v32cgso; double BSIM3v32cgdo; double BSIM3v32cgbo; double BSIM3v32tconst; double BSIM3v32u0temp; double BSIM3v32vsattemp; double BSIM3v32sqrtPhi; double BSIM3v32phis3; double BSIM3v32Xdep0; double BSIM3v32sqrtXdep0; double BSIM3v32theta0vb0; double BSIM3v32thetaRout; double BSIM3v32cof1; double BSIM3v32cof2; double BSIM3v32cof3; double BSIM3v32cof4; double BSIM3v32cdep0; double BSIM3v32vfbzb; double BSIM3v32ldeb; double BSIM3v32k1ox; double BSIM3v32k2ox; struct bsim3v32SizeDependParam *pNext; }; typedef struct sBSIM3v32model { struct GENmodel gen; #define BSIM3v32modType gen.GENmodType #define BSIM3v32nextModel(inst) ((struct sBSIM3v32model *)((inst)->gen.GENnextModel)) #define BSIM3v32instances(inst) ((BSIM3v32instance *)((inst)->gen.GENinstances)) #define BSIM3v32modName gen.GENmodName int BSIM3v32type; int BSIM3v32mobMod; int BSIM3v32capMod; int BSIM3v32acmMod; int BSIM3v32calcacm; int BSIM3v32noiMod; int BSIM3v32nqsMod; int BSIM3v32binUnit; int BSIM3v32paramChk; char *BSIM3v32version; /* The following field is an integer coding * of BSIM3v32version. */ int BSIM3v32intVersion; #define BSIM3v32V324 324 /* BSIM3v32 V3.2.4 */ #define BSIM3v32V323 323 /* BSIM3v32 V3.2.3 */ #define BSIM3v32V322 322 /* BSIM3v32 V3.2.2 */ #define BSIM3v32V32 32 /* BSIM3v32 V3.2 */ #define BSIM3v32V3OLD 0 /* Old model */ double BSIM3v32tox; double BSIM3v32toxm; double BSIM3v32cdsc; double BSIM3v32cdscb; double BSIM3v32cdscd; double BSIM3v32cit; double BSIM3v32nfactor; double BSIM3v32xj; double BSIM3v32vsat; double BSIM3v32at; double BSIM3v32a0; double BSIM3v32ags; double BSIM3v32a1; double BSIM3v32a2; double BSIM3v32keta; double BSIM3v32nsub; double BSIM3v32npeak; double BSIM3v32ngate; double BSIM3v32gamma1; double BSIM3v32gamma2; double BSIM3v32vbx; double BSIM3v32vbm; double BSIM3v32xt; double BSIM3v32k1; double BSIM3v32kt1; double BSIM3v32kt1l; double BSIM3v32kt2; double BSIM3v32k2; double BSIM3v32k3; double BSIM3v32k3b; double BSIM3v32w0; double BSIM3v32nlx; double BSIM3v32dvt0; double BSIM3v32dvt1; double BSIM3v32dvt2; double BSIM3v32dvt0w; double BSIM3v32dvt1w; double BSIM3v32dvt2w; double BSIM3v32drout; double BSIM3v32dsub; double BSIM3v32vth0; double BSIM3v32ua; double BSIM3v32ua1; double BSIM3v32ub; double BSIM3v32ub1; double BSIM3v32uc; double BSIM3v32uc1; double BSIM3v32u0; double BSIM3v32ute; double BSIM3v32voff; double BSIM3v32delta; double BSIM3v32rdsw; double BSIM3v32prwg; double BSIM3v32prwb; double BSIM3v32prt; double BSIM3v32eta0; double BSIM3v32etab; double BSIM3v32pclm; double BSIM3v32pdibl1; double BSIM3v32pdibl2; double BSIM3v32pdiblb; double BSIM3v32pscbe1; double BSIM3v32pscbe2; double BSIM3v32pvag; double BSIM3v32wr; double BSIM3v32dwg; double BSIM3v32dwb; double BSIM3v32b0; double BSIM3v32b1; double BSIM3v32alpha0; double BSIM3v32alpha1; double BSIM3v32beta0; double BSIM3v32ijth; double BSIM3v32vfb; /* CV model */ double BSIM3v32elm; double BSIM3v32cgsl; double BSIM3v32cgdl; double BSIM3v32ckappa; double BSIM3v32cf; double BSIM3v32vfbcv; double BSIM3v32clc; double BSIM3v32cle; double BSIM3v32dwc; double BSIM3v32dlc; double BSIM3v32noff; double BSIM3v32voffcv; double BSIM3v32acde; double BSIM3v32moin; double BSIM3v32tcj; double BSIM3v32tcjsw; double BSIM3v32tcjswg; double BSIM3v32tpb; double BSIM3v32tpbsw; double BSIM3v32tpbswg; /* ACM model */ double BSIM3v32xl; double BSIM3v32xw; double BSIM3v32hdif; double BSIM3v32ldif; double BSIM3v32ld; double BSIM3v32rd; double BSIM3v32rs; double BSIM3v32rdc; double BSIM3v32rsc; double BSIM3v32wmlt; double BSIM3v32lmlt; /* Length Dependence */ double BSIM3v32lcdsc; double BSIM3v32lcdscb; double BSIM3v32lcdscd; double BSIM3v32lcit; double BSIM3v32lnfactor; double BSIM3v32lxj; double BSIM3v32lvsat; double BSIM3v32lat; double BSIM3v32la0; double BSIM3v32lags; double BSIM3v32la1; double BSIM3v32la2; double BSIM3v32lketa; double BSIM3v32lnsub; double BSIM3v32lnpeak; double BSIM3v32lngate; double BSIM3v32lgamma1; double BSIM3v32lgamma2; double BSIM3v32lvbx; double BSIM3v32lvbm; double BSIM3v32lxt; double BSIM3v32lk1; double BSIM3v32lkt1; double BSIM3v32lkt1l; double BSIM3v32lkt2; double BSIM3v32lk2; double BSIM3v32lk3; double BSIM3v32lk3b; double BSIM3v32lw0; double BSIM3v32lnlx; double BSIM3v32ldvt0; double BSIM3v32ldvt1; double BSIM3v32ldvt2; double BSIM3v32ldvt0w; double BSIM3v32ldvt1w; double BSIM3v32ldvt2w; double BSIM3v32ldrout; double BSIM3v32ldsub; double BSIM3v32lvth0; double BSIM3v32lua; double BSIM3v32lua1; double BSIM3v32lub; double BSIM3v32lub1; double BSIM3v32luc; double BSIM3v32luc1; double BSIM3v32lu0; double BSIM3v32lute; double BSIM3v32lvoff; double BSIM3v32ldelta; double BSIM3v32lrdsw; double BSIM3v32lprwg; double BSIM3v32lprwb; double BSIM3v32lprt; double BSIM3v32leta0; double BSIM3v32letab; double BSIM3v32lpclm; double BSIM3v32lpdibl1; double BSIM3v32lpdibl2; double BSIM3v32lpdiblb; double BSIM3v32lpscbe1; double BSIM3v32lpscbe2; double BSIM3v32lpvag; double BSIM3v32lwr; double BSIM3v32ldwg; double BSIM3v32ldwb; double BSIM3v32lb0; double BSIM3v32lb1; double BSIM3v32lalpha0; double BSIM3v32lalpha1; double BSIM3v32lbeta0; double BSIM3v32lvfb; /* CV model */ double BSIM3v32lelm; double BSIM3v32lcgsl; double BSIM3v32lcgdl; double BSIM3v32lckappa; double BSIM3v32lcf; double BSIM3v32lclc; double BSIM3v32lcle; double BSIM3v32lvfbcv; double BSIM3v32lnoff; double BSIM3v32lvoffcv; double BSIM3v32lacde; double BSIM3v32lmoin; /* Width Dependence */ double BSIM3v32wcdsc; double BSIM3v32wcdscb; double BSIM3v32wcdscd; double BSIM3v32wcit; double BSIM3v32wnfactor; double BSIM3v32wxj; double BSIM3v32wvsat; double BSIM3v32wat; double BSIM3v32wa0; double BSIM3v32wags; double BSIM3v32wa1; double BSIM3v32wa2; double BSIM3v32wketa; double BSIM3v32wnsub; double BSIM3v32wnpeak; double BSIM3v32wngate; double BSIM3v32wgamma1; double BSIM3v32wgamma2; double BSIM3v32wvbx; double BSIM3v32wvbm; double BSIM3v32wxt; double BSIM3v32wk1; double BSIM3v32wkt1; double BSIM3v32wkt1l; double BSIM3v32wkt2; double BSIM3v32wk2; double BSIM3v32wk3; double BSIM3v32wk3b; double BSIM3v32ww0; double BSIM3v32wnlx; double BSIM3v32wdvt0; double BSIM3v32wdvt1; double BSIM3v32wdvt2; double BSIM3v32wdvt0w; double BSIM3v32wdvt1w; double BSIM3v32wdvt2w; double BSIM3v32wdrout; double BSIM3v32wdsub; double BSIM3v32wvth0; double BSIM3v32wua; double BSIM3v32wua1; double BSIM3v32wub; double BSIM3v32wub1; double BSIM3v32wuc; double BSIM3v32wuc1; double BSIM3v32wu0; double BSIM3v32wute; double BSIM3v32wvoff; double BSIM3v32wdelta; double BSIM3v32wrdsw; double BSIM3v32wprwg; double BSIM3v32wprwb; double BSIM3v32wprt; double BSIM3v32weta0; double BSIM3v32wetab; double BSIM3v32wpclm; double BSIM3v32wpdibl1; double BSIM3v32wpdibl2; double BSIM3v32wpdiblb; double BSIM3v32wpscbe1; double BSIM3v32wpscbe2; double BSIM3v32wpvag; double BSIM3v32wwr; double BSIM3v32wdwg; double BSIM3v32wdwb; double BSIM3v32wb0; double BSIM3v32wb1; double BSIM3v32walpha0; double BSIM3v32walpha1; double BSIM3v32wbeta0; double BSIM3v32wvfb; /* CV model */ double BSIM3v32welm; double BSIM3v32wcgsl; double BSIM3v32wcgdl; double BSIM3v32wckappa; double BSIM3v32wcf; double BSIM3v32wclc; double BSIM3v32wcle; double BSIM3v32wvfbcv; double BSIM3v32wnoff; double BSIM3v32wvoffcv; double BSIM3v32wacde; double BSIM3v32wmoin; /* Cross-term Dependence */ double BSIM3v32pcdsc; double BSIM3v32pcdscb; double BSIM3v32pcdscd; double BSIM3v32pcit; double BSIM3v32pnfactor; double BSIM3v32pxj; double BSIM3v32pvsat; double BSIM3v32pat; double BSIM3v32pa0; double BSIM3v32pags; double BSIM3v32pa1; double BSIM3v32pa2; double BSIM3v32pketa; double BSIM3v32pnsub; double BSIM3v32pnpeak; double BSIM3v32pngate; double BSIM3v32pgamma1; double BSIM3v32pgamma2; double BSIM3v32pvbx; double BSIM3v32pvbm; double BSIM3v32pxt; double BSIM3v32pk1; double BSIM3v32pkt1; double BSIM3v32pkt1l; double BSIM3v32pkt2; double BSIM3v32pk2; double BSIM3v32pk3; double BSIM3v32pk3b; double BSIM3v32pw0; double BSIM3v32pnlx; double BSIM3v32pdvt0; double BSIM3v32pdvt1; double BSIM3v32pdvt2; double BSIM3v32pdvt0w; double BSIM3v32pdvt1w; double BSIM3v32pdvt2w; double BSIM3v32pdrout; double BSIM3v32pdsub; double BSIM3v32pvth0; double BSIM3v32pua; double BSIM3v32pua1; double BSIM3v32pub; double BSIM3v32pub1; double BSIM3v32puc; double BSIM3v32puc1; double BSIM3v32pu0; double BSIM3v32pute; double BSIM3v32pvoff; double BSIM3v32pdelta; double BSIM3v32prdsw; double BSIM3v32pprwg; double BSIM3v32pprwb; double BSIM3v32pprt; double BSIM3v32peta0; double BSIM3v32petab; double BSIM3v32ppclm; double BSIM3v32ppdibl1; double BSIM3v32ppdibl2; double BSIM3v32ppdiblb; double BSIM3v32ppscbe1; double BSIM3v32ppscbe2; double BSIM3v32ppvag; double BSIM3v32pwr; double BSIM3v32pdwg; double BSIM3v32pdwb; double BSIM3v32pb0; double BSIM3v32pb1; double BSIM3v32palpha0; double BSIM3v32palpha1; double BSIM3v32pbeta0; double BSIM3v32pvfb; /* CV model */ double BSIM3v32pelm; double BSIM3v32pcgsl; double BSIM3v32pcgdl; double BSIM3v32pckappa; double BSIM3v32pcf; double BSIM3v32pclc; double BSIM3v32pcle; double BSIM3v32pvfbcv; double BSIM3v32pnoff; double BSIM3v32pvoffcv; double BSIM3v32pacde; double BSIM3v32pmoin; double BSIM3v32tnom; double BSIM3v32cgso; double BSIM3v32cgdo; double BSIM3v32cgbo; double BSIM3v32xpart; double BSIM3v32cFringOut; double BSIM3v32cFringMax; double BSIM3v32sheetResistance; double BSIM3v32jctSatCurDensity; double BSIM3v32jctSidewallSatCurDensity; double BSIM3v32bulkJctPotential; double BSIM3v32bulkJctBotGradingCoeff; double BSIM3v32bulkJctSideGradingCoeff; double BSIM3v32bulkJctGateSideGradingCoeff; double BSIM3v32sidewallJctPotential; double BSIM3v32GatesidewallJctPotential; double BSIM3v32unitAreaJctCap; double BSIM3v32unitLengthSidewallJctCap; double BSIM3v32unitLengthGateSidewallJctCap; double BSIM3v32jctEmissionCoeff; double BSIM3v32jctTempExponent; double BSIM3v32Lint; double BSIM3v32Ll; double BSIM3v32Llc; double BSIM3v32Lln; double BSIM3v32Lw; double BSIM3v32Lwc; double BSIM3v32Lwn; double BSIM3v32Lwl; double BSIM3v32Lwlc; double BSIM3v32Lmin; double BSIM3v32Lmax; double BSIM3v32Wint; double BSIM3v32Wl; double BSIM3v32Wlc; double BSIM3v32Wln; double BSIM3v32Ww; double BSIM3v32Wwc; double BSIM3v32Wwn; double BSIM3v32Wwl; double BSIM3v32Wwlc; double BSIM3v32Wmin; double BSIM3v32Wmax; /* Pre-calculated constants */ /* MCJ: move to size-dependent param. */ double BSIM3v32vtm; double BSIM3v32cox; double BSIM3v32cof1; double BSIM3v32cof2; double BSIM3v32cof3; double BSIM3v32cof4; double BSIM3v32vcrit; double BSIM3v32factor1; double BSIM3v32PhiB; double BSIM3v32PhiBSW; double BSIM3v32PhiBSWG; double BSIM3v32jctTempSatCurDensity; double BSIM3v32jctSidewallTempSatCurDensity; double BSIM3v32unitAreaTempJctCap; double BSIM3v32unitLengthSidewallTempJctCap; double BSIM3v32unitLengthGateSidewallTempJctCap; double BSIM3v32oxideTrapDensityA; double BSIM3v32oxideTrapDensityB; double BSIM3v32oxideTrapDensityC; double BSIM3v32em; double BSIM3v32ef; double BSIM3v32af; double BSIM3v32kf; double BSIM3v32vgsMax; double BSIM3v32vgdMax; double BSIM3v32vgbMax; double BSIM3v32vdsMax; double BSIM3v32vbsMax; double BSIM3v32vbdMax; double BSIM3v32vgsrMax; double BSIM3v32vgdrMax; double BSIM3v32vgbrMax; double BSIM3v32vbsrMax; double BSIM3v32vbdrMax; struct bsim3v32SizeDependParam *pSizeDependParamKnot; #ifdef USE_OMP int BSIM3v32InstCount; struct sBSIM3v32instance **BSIM3v32InstanceArray; #endif /* Flags */ unsigned BSIM3v32mobModGiven :1; unsigned BSIM3v32binUnitGiven :1; unsigned BSIM3v32capModGiven :1; unsigned BSIM3v32acmModGiven :1; unsigned BSIM3v32calcacmGiven :1; unsigned BSIM3v32paramChkGiven :1; unsigned BSIM3v32noiModGiven :1; unsigned BSIM3v32nqsModGiven :1; unsigned BSIM3v32typeGiven :1; unsigned BSIM3v32toxGiven :1; unsigned BSIM3v32versionGiven :1; unsigned BSIM3v32toxmGiven :1; unsigned BSIM3v32cdscGiven :1; unsigned BSIM3v32cdscbGiven :1; unsigned BSIM3v32cdscdGiven :1; unsigned BSIM3v32citGiven :1; unsigned BSIM3v32nfactorGiven :1; unsigned BSIM3v32xjGiven :1; unsigned BSIM3v32vsatGiven :1; unsigned BSIM3v32atGiven :1; unsigned BSIM3v32a0Given :1; unsigned BSIM3v32agsGiven :1; unsigned BSIM3v32a1Given :1; unsigned BSIM3v32a2Given :1; unsigned BSIM3v32ketaGiven :1; unsigned BSIM3v32nsubGiven :1; unsigned BSIM3v32npeakGiven :1; unsigned BSIM3v32ngateGiven :1; unsigned BSIM3v32gamma1Given :1; unsigned BSIM3v32gamma2Given :1; unsigned BSIM3v32vbxGiven :1; unsigned BSIM3v32vbmGiven :1; unsigned BSIM3v32xtGiven :1; unsigned BSIM3v32k1Given :1; unsigned BSIM3v32kt1Given :1; unsigned BSIM3v32kt1lGiven :1; unsigned BSIM3v32kt2Given :1; unsigned BSIM3v32k2Given :1; unsigned BSIM3v32k3Given :1; unsigned BSIM3v32k3bGiven :1; unsigned BSIM3v32w0Given :1; unsigned BSIM3v32nlxGiven :1; unsigned BSIM3v32dvt0Given :1; unsigned BSIM3v32dvt1Given :1; unsigned BSIM3v32dvt2Given :1; unsigned BSIM3v32dvt0wGiven :1; unsigned BSIM3v32dvt1wGiven :1; unsigned BSIM3v32dvt2wGiven :1; unsigned BSIM3v32droutGiven :1; unsigned BSIM3v32dsubGiven :1; unsigned BSIM3v32vth0Given :1; unsigned BSIM3v32uaGiven :1; unsigned BSIM3v32ua1Given :1; unsigned BSIM3v32ubGiven :1; unsigned BSIM3v32ub1Given :1; unsigned BSIM3v32ucGiven :1; unsigned BSIM3v32uc1Given :1; unsigned BSIM3v32u0Given :1; unsigned BSIM3v32uteGiven :1; unsigned BSIM3v32voffGiven :1; unsigned BSIM3v32rdswGiven :1; unsigned BSIM3v32prwgGiven :1; unsigned BSIM3v32prwbGiven :1; unsigned BSIM3v32prtGiven :1; unsigned BSIM3v32eta0Given :1; unsigned BSIM3v32etabGiven :1; unsigned BSIM3v32pclmGiven :1; unsigned BSIM3v32pdibl1Given :1; unsigned BSIM3v32pdibl2Given :1; unsigned BSIM3v32pdiblbGiven :1; unsigned BSIM3v32pscbe1Given :1; unsigned BSIM3v32pscbe2Given :1; unsigned BSIM3v32pvagGiven :1; unsigned BSIM3v32deltaGiven :1; unsigned BSIM3v32wrGiven :1; unsigned BSIM3v32dwgGiven :1; unsigned BSIM3v32dwbGiven :1; unsigned BSIM3v32b0Given :1; unsigned BSIM3v32b1Given :1; unsigned BSIM3v32alpha0Given :1; unsigned BSIM3v32alpha1Given :1; unsigned BSIM3v32beta0Given :1; unsigned BSIM3v32ijthGiven :1; unsigned BSIM3v32vfbGiven :1; /* CV model */ unsigned BSIM3v32elmGiven :1; unsigned BSIM3v32cgslGiven :1; unsigned BSIM3v32cgdlGiven :1; unsigned BSIM3v32ckappaGiven :1; unsigned BSIM3v32cfGiven :1; unsigned BSIM3v32vfbcvGiven :1; unsigned BSIM3v32clcGiven :1; unsigned BSIM3v32cleGiven :1; unsigned BSIM3v32dwcGiven :1; unsigned BSIM3v32dlcGiven :1; unsigned BSIM3v32noffGiven :1; unsigned BSIM3v32voffcvGiven :1; unsigned BSIM3v32acdeGiven :1; unsigned BSIM3v32moinGiven :1; unsigned BSIM3v32tcjGiven :1; unsigned BSIM3v32tcjswGiven :1; unsigned BSIM3v32tcjswgGiven :1; unsigned BSIM3v32tpbGiven :1; unsigned BSIM3v32tpbswGiven :1; unsigned BSIM3v32tpbswgGiven :1; /* ACM model */ unsigned BSIM3v32xlGiven :1; unsigned BSIM3v32xwGiven :1; unsigned BSIM3v32hdifGiven :1; unsigned BSIM3v32ldifGiven :1; unsigned BSIM3v32ldGiven :1; unsigned BSIM3v32rdGiven :1; unsigned BSIM3v32rsGiven :1; unsigned BSIM3v32rdcGiven :1; unsigned BSIM3v32rscGiven :1; unsigned BSIM3v32wmltGiven :1; unsigned BSIM3v32lmltGiven :1; /* Length dependence */ unsigned BSIM3v32lcdscGiven :1; unsigned BSIM3v32lcdscbGiven :1; unsigned BSIM3v32lcdscdGiven :1; unsigned BSIM3v32lcitGiven :1; unsigned BSIM3v32lnfactorGiven :1; unsigned BSIM3v32lxjGiven :1; unsigned BSIM3v32lvsatGiven :1; unsigned BSIM3v32latGiven :1; unsigned BSIM3v32la0Given :1; unsigned BSIM3v32lagsGiven :1; unsigned BSIM3v32la1Given :1; unsigned BSIM3v32la2Given :1; unsigned BSIM3v32lketaGiven :1; unsigned BSIM3v32lnsubGiven :1; unsigned BSIM3v32lnpeakGiven :1; unsigned BSIM3v32lngateGiven :1; unsigned BSIM3v32lgamma1Given :1; unsigned BSIM3v32lgamma2Given :1; unsigned BSIM3v32lvbxGiven :1; unsigned BSIM3v32lvbmGiven :1; unsigned BSIM3v32lxtGiven :1; unsigned BSIM3v32lk1Given :1; unsigned BSIM3v32lkt1Given :1; unsigned BSIM3v32lkt1lGiven :1; unsigned BSIM3v32lkt2Given :1; unsigned BSIM3v32lk2Given :1; unsigned BSIM3v32lk3Given :1; unsigned BSIM3v32lk3bGiven :1; unsigned BSIM3v32lw0Given :1; unsigned BSIM3v32lnlxGiven :1; unsigned BSIM3v32ldvt0Given :1; unsigned BSIM3v32ldvt1Given :1; unsigned BSIM3v32ldvt2Given :1; unsigned BSIM3v32ldvt0wGiven :1; unsigned BSIM3v32ldvt1wGiven :1; unsigned BSIM3v32ldvt2wGiven :1; unsigned BSIM3v32ldroutGiven :1; unsigned BSIM3v32ldsubGiven :1; unsigned BSIM3v32lvth0Given :1; unsigned BSIM3v32luaGiven :1; unsigned BSIM3v32lua1Given :1; unsigned BSIM3v32lubGiven :1; unsigned BSIM3v32lub1Given :1; unsigned BSIM3v32lucGiven :1; unsigned BSIM3v32luc1Given :1; unsigned BSIM3v32lu0Given :1; unsigned BSIM3v32luteGiven :1; unsigned BSIM3v32lvoffGiven :1; unsigned BSIM3v32lrdswGiven :1; unsigned BSIM3v32lprwgGiven :1; unsigned BSIM3v32lprwbGiven :1; unsigned BSIM3v32lprtGiven :1; unsigned BSIM3v32leta0Given :1; unsigned BSIM3v32letabGiven :1; unsigned BSIM3v32lpclmGiven :1; unsigned BSIM3v32lpdibl1Given :1; unsigned BSIM3v32lpdibl2Given :1; unsigned BSIM3v32lpdiblbGiven :1; unsigned BSIM3v32lpscbe1Given :1; unsigned BSIM3v32lpscbe2Given :1; unsigned BSIM3v32lpvagGiven :1; unsigned BSIM3v32ldeltaGiven :1; unsigned BSIM3v32lwrGiven :1; unsigned BSIM3v32ldwgGiven :1; unsigned BSIM3v32ldwbGiven :1; unsigned BSIM3v32lb0Given :1; unsigned BSIM3v32lb1Given :1; unsigned BSIM3v32lalpha0Given :1; unsigned BSIM3v32lalpha1Given :1; unsigned BSIM3v32lbeta0Given :1; unsigned BSIM3v32lvfbGiven :1; /* CV model */ unsigned BSIM3v32lelmGiven :1; unsigned BSIM3v32lcgslGiven :1; unsigned BSIM3v32lcgdlGiven :1; unsigned BSIM3v32lckappaGiven :1; unsigned BSIM3v32lcfGiven :1; unsigned BSIM3v32lclcGiven :1; unsigned BSIM3v32lcleGiven :1; unsigned BSIM3v32lvfbcvGiven :1; unsigned BSIM3v32lnoffGiven :1; unsigned BSIM3v32lvoffcvGiven :1; unsigned BSIM3v32lacdeGiven :1; unsigned BSIM3v32lmoinGiven :1; /* Width dependence */ unsigned BSIM3v32wcdscGiven :1; unsigned BSIM3v32wcdscbGiven :1; unsigned BSIM3v32wcdscdGiven :1; unsigned BSIM3v32wcitGiven :1; unsigned BSIM3v32wnfactorGiven :1; unsigned BSIM3v32wxjGiven :1; unsigned BSIM3v32wvsatGiven :1; unsigned BSIM3v32watGiven :1; unsigned BSIM3v32wa0Given :1; unsigned BSIM3v32wagsGiven :1; unsigned BSIM3v32wa1Given :1; unsigned BSIM3v32wa2Given :1; unsigned BSIM3v32wketaGiven :1; unsigned BSIM3v32wnsubGiven :1; unsigned BSIM3v32wnpeakGiven :1; unsigned BSIM3v32wngateGiven :1; unsigned BSIM3v32wgamma1Given :1; unsigned BSIM3v32wgamma2Given :1; unsigned BSIM3v32wvbxGiven :1; unsigned BSIM3v32wvbmGiven :1; unsigned BSIM3v32wxtGiven :1; unsigned BSIM3v32wk1Given :1; unsigned BSIM3v32wkt1Given :1; unsigned BSIM3v32wkt1lGiven :1; unsigned BSIM3v32wkt2Given :1; unsigned BSIM3v32wk2Given :1; unsigned BSIM3v32wk3Given :1; unsigned BSIM3v32wk3bGiven :1; unsigned BSIM3v32ww0Given :1; unsigned BSIM3v32wnlxGiven :1; unsigned BSIM3v32wdvt0Given :1; unsigned BSIM3v32wdvt1Given :1; unsigned BSIM3v32wdvt2Given :1; unsigned BSIM3v32wdvt0wGiven :1; unsigned BSIM3v32wdvt1wGiven :1; unsigned BSIM3v32wdvt2wGiven :1; unsigned BSIM3v32wdroutGiven :1; unsigned BSIM3v32wdsubGiven :1; unsigned BSIM3v32wvth0Given :1; unsigned BSIM3v32wuaGiven :1; unsigned BSIM3v32wua1Given :1; unsigned BSIM3v32wubGiven :1; unsigned BSIM3v32wub1Given :1; unsigned BSIM3v32wucGiven :1; unsigned BSIM3v32wuc1Given :1; unsigned BSIM3v32wu0Given :1; unsigned BSIM3v32wuteGiven :1; unsigned BSIM3v32wvoffGiven :1; unsigned BSIM3v32wrdswGiven :1; unsigned BSIM3v32wprwgGiven :1; unsigned BSIM3v32wprwbGiven :1; unsigned BSIM3v32wprtGiven :1; unsigned BSIM3v32weta0Given :1; unsigned BSIM3v32wetabGiven :1; unsigned BSIM3v32wpclmGiven :1; unsigned BSIM3v32wpdibl1Given :1; unsigned BSIM3v32wpdibl2Given :1; unsigned BSIM3v32wpdiblbGiven :1; unsigned BSIM3v32wpscbe1Given :1; unsigned BSIM3v32wpscbe2Given :1; unsigned BSIM3v32wpvagGiven :1; unsigned BSIM3v32wdeltaGiven :1; unsigned BSIM3v32wwrGiven :1; unsigned BSIM3v32wdwgGiven :1; unsigned BSIM3v32wdwbGiven :1; unsigned BSIM3v32wb0Given :1; unsigned BSIM3v32wb1Given :1; unsigned BSIM3v32walpha0Given :1; unsigned BSIM3v32walpha1Given :1; unsigned BSIM3v32wbeta0Given :1; unsigned BSIM3v32wvfbGiven :1; /* CV model */ unsigned BSIM3v32welmGiven :1; unsigned BSIM3v32wcgslGiven :1; unsigned BSIM3v32wcgdlGiven :1; unsigned BSIM3v32wckappaGiven :1; unsigned BSIM3v32wcfGiven :1; unsigned BSIM3v32wclcGiven :1; unsigned BSIM3v32wcleGiven :1; unsigned BSIM3v32wvfbcvGiven :1; unsigned BSIM3v32wnoffGiven :1; unsigned BSIM3v32wvoffcvGiven :1; unsigned BSIM3v32wacdeGiven :1; unsigned BSIM3v32wmoinGiven :1; /* Cross-term dependence */ unsigned BSIM3v32pcdscGiven :1; unsigned BSIM3v32pcdscbGiven :1; unsigned BSIM3v32pcdscdGiven :1; unsigned BSIM3v32pcitGiven :1; unsigned BSIM3v32pnfactorGiven :1; unsigned BSIM3v32pxjGiven :1; unsigned BSIM3v32pvsatGiven :1; unsigned BSIM3v32patGiven :1; unsigned BSIM3v32pa0Given :1; unsigned BSIM3v32pagsGiven :1; unsigned BSIM3v32pa1Given :1; unsigned BSIM3v32pa2Given :1; unsigned BSIM3v32pketaGiven :1; unsigned BSIM3v32pnsubGiven :1; unsigned BSIM3v32pnpeakGiven :1; unsigned BSIM3v32pngateGiven :1; unsigned BSIM3v32pgamma1Given :1; unsigned BSIM3v32pgamma2Given :1; unsigned BSIM3v32pvbxGiven :1; unsigned BSIM3v32pvbmGiven :1; unsigned BSIM3v32pxtGiven :1; unsigned BSIM3v32pk1Given :1; unsigned BSIM3v32pkt1Given :1; unsigned BSIM3v32pkt1lGiven :1; unsigned BSIM3v32pkt2Given :1; unsigned BSIM3v32pk2Given :1; unsigned BSIM3v32pk3Given :1; unsigned BSIM3v32pk3bGiven :1; unsigned BSIM3v32pw0Given :1; unsigned BSIM3v32pnlxGiven :1; unsigned BSIM3v32pdvt0Given :1; unsigned BSIM3v32pdvt1Given :1; unsigned BSIM3v32pdvt2Given :1; unsigned BSIM3v32pdvt0wGiven :1; unsigned BSIM3v32pdvt1wGiven :1; unsigned BSIM3v32pdvt2wGiven :1; unsigned BSIM3v32pdroutGiven :1; unsigned BSIM3v32pdsubGiven :1; unsigned BSIM3v32pvth0Given :1; unsigned BSIM3v32puaGiven :1; unsigned BSIM3v32pua1Given :1; unsigned BSIM3v32pubGiven :1; unsigned BSIM3v32pub1Given :1; unsigned BSIM3v32pucGiven :1; unsigned BSIM3v32puc1Given :1; unsigned BSIM3v32pu0Given :1; unsigned BSIM3v32puteGiven :1; unsigned BSIM3v32pvoffGiven :1; unsigned BSIM3v32prdswGiven :1; unsigned BSIM3v32pprwgGiven :1; unsigned BSIM3v32pprwbGiven :1; unsigned BSIM3v32pprtGiven :1; unsigned BSIM3v32peta0Given :1; unsigned BSIM3v32petabGiven :1; unsigned BSIM3v32ppclmGiven :1; unsigned BSIM3v32ppdibl1Given :1; unsigned BSIM3v32ppdibl2Given :1; unsigned BSIM3v32ppdiblbGiven :1; unsigned BSIM3v32ppscbe1Given :1; unsigned BSIM3v32ppscbe2Given :1; unsigned BSIM3v32ppvagGiven :1; unsigned BSIM3v32pdeltaGiven :1; unsigned BSIM3v32pwrGiven :1; unsigned BSIM3v32pdwgGiven :1; unsigned BSIM3v32pdwbGiven :1; unsigned BSIM3v32pb0Given :1; unsigned BSIM3v32pb1Given :1; unsigned BSIM3v32palpha0Given :1; unsigned BSIM3v32palpha1Given :1; unsigned BSIM3v32pbeta0Given :1; unsigned BSIM3v32pvfbGiven :1; /* CV model */ unsigned BSIM3v32pelmGiven :1; unsigned BSIM3v32pcgslGiven :1; unsigned BSIM3v32pcgdlGiven :1; unsigned BSIM3v32pckappaGiven :1; unsigned BSIM3v32pcfGiven :1; unsigned BSIM3v32pclcGiven :1; unsigned BSIM3v32pcleGiven :1; unsigned BSIM3v32pvfbcvGiven :1; unsigned BSIM3v32pnoffGiven :1; unsigned BSIM3v32pvoffcvGiven :1; unsigned BSIM3v32pacdeGiven :1; unsigned BSIM3v32pmoinGiven :1; unsigned BSIM3v32useFringeGiven :1; unsigned BSIM3v32tnomGiven :1; unsigned BSIM3v32cgsoGiven :1; unsigned BSIM3v32cgdoGiven :1; unsigned BSIM3v32cgboGiven :1; unsigned BSIM3v32xpartGiven :1; unsigned BSIM3v32sheetResistanceGiven :1; unsigned BSIM3v32jctSatCurDensityGiven :1; unsigned BSIM3v32jctSidewallSatCurDensityGiven :1; unsigned BSIM3v32bulkJctPotentialGiven :1; unsigned BSIM3v32bulkJctBotGradingCoeffGiven :1; unsigned BSIM3v32sidewallJctPotentialGiven :1; unsigned BSIM3v32GatesidewallJctPotentialGiven :1; unsigned BSIM3v32bulkJctSideGradingCoeffGiven :1; unsigned BSIM3v32unitAreaJctCapGiven :1; unsigned BSIM3v32unitLengthSidewallJctCapGiven :1; unsigned BSIM3v32bulkJctGateSideGradingCoeffGiven :1; unsigned BSIM3v32unitLengthGateSidewallJctCapGiven :1; unsigned BSIM3v32jctEmissionCoeffGiven :1; unsigned BSIM3v32jctTempExponentGiven :1; unsigned BSIM3v32oxideTrapDensityAGiven :1; unsigned BSIM3v32oxideTrapDensityBGiven :1; unsigned BSIM3v32oxideTrapDensityCGiven :1; unsigned BSIM3v32emGiven :1; unsigned BSIM3v32efGiven :1; unsigned BSIM3v32afGiven :1; unsigned BSIM3v32kfGiven :1; unsigned BSIM3v32LintGiven :1; unsigned BSIM3v32LlGiven :1; unsigned BSIM3v32LlcGiven :1; unsigned BSIM3v32LlnGiven :1; unsigned BSIM3v32LwGiven :1; unsigned BSIM3v32LwcGiven :1; unsigned BSIM3v32LwnGiven :1; unsigned BSIM3v32LwlGiven :1; unsigned BSIM3v32LwlcGiven :1; unsigned BSIM3v32LminGiven :1; unsigned BSIM3v32LmaxGiven :1; unsigned BSIM3v32WintGiven :1; unsigned BSIM3v32WlGiven :1; unsigned BSIM3v32WlcGiven :1; unsigned BSIM3v32WlnGiven :1; unsigned BSIM3v32WwGiven :1; unsigned BSIM3v32WwcGiven :1; unsigned BSIM3v32WwnGiven :1; unsigned BSIM3v32WwlGiven :1; unsigned BSIM3v32WwlcGiven :1; unsigned BSIM3v32WminGiven :1; unsigned BSIM3v32WmaxGiven :1; unsigned BSIM3v32vgsMaxGiven :1; unsigned BSIM3v32vgdMaxGiven :1; unsigned BSIM3v32vgbMaxGiven :1; unsigned BSIM3v32vdsMaxGiven :1; unsigned BSIM3v32vbsMaxGiven :1; unsigned BSIM3v32vbdMaxGiven :1; unsigned BSIM3v32vgsrMaxGiven :1; unsigned BSIM3v32vgdrMaxGiven :1; unsigned BSIM3v32vgbrMaxGiven :1; unsigned BSIM3v32vbsrMaxGiven :1; unsigned BSIM3v32vbdrMaxGiven :1; } BSIM3v32model; #ifndef NMOS #define NMOS 1 #define PMOS -1 #endif /*NMOS*/ /* device parameters */ #define BSIM3v32_W 1 #define BSIM3v32_L 2 #define BSIM3v32_AS 3 #define BSIM3v32_AD 4 #define BSIM3v32_PS 5 #define BSIM3v32_PD 6 #define BSIM3v32_NRS 7 #define BSIM3v32_NRD 8 #define BSIM3v32_OFF 9 #define BSIM3v32_IC_VBS 10 #define BSIM3v32_IC_VDS 11 #define BSIM3v32_IC_VGS 12 #define BSIM3v32_IC 13 #define BSIM3v32_NQSMOD 14 #define BSIM3v32_M 15 #define BSIM3v32_DELVTO 16 #define BSIM3v32_MULU0 17 #define BSIM3v32_GEO 18 /* model parameters */ #define BSIM3v32_MOD_CAPMOD 100 #define BSIM3v32_MOD_ACMMOD 101 #define BSIM3v32_MOD_CALCACM 102 #define BSIM3v32_MOD_MOBMOD 103 #define BSIM3v32_MOD_NOIMOD 104 #define BSIM3v32_MOD_NQSMOD 105 #define BSIM3v32_MOD_TOX 106 #define BSIM3v32_MOD_CDSC 107 #define BSIM3v32_MOD_CDSCB 108 #define BSIM3v32_MOD_CIT 109 #define BSIM3v32_MOD_NFACTOR 110 #define BSIM3v32_MOD_XJ 111 #define BSIM3v32_MOD_VSAT 112 #define BSIM3v32_MOD_AT 113 #define BSIM3v32_MOD_A0 114 #define BSIM3v32_MOD_A1 115 #define BSIM3v32_MOD_A2 116 #define BSIM3v32_MOD_KETA 117 #define BSIM3v32_MOD_NSUB 118 #define BSIM3v32_MOD_NPEAK 119 #define BSIM3v32_MOD_NGATE 120 #define BSIM3v32_MOD_GAMMA1 121 #define BSIM3v32_MOD_GAMMA2 122 #define BSIM3v32_MOD_VBX 123 #define BSIM3v32_MOD_BINUNIT 124 #define BSIM3v32_MOD_VBM 125 #define BSIM3v32_MOD_XT 128 #define BSIM3v32_MOD_K1 129 #define BSIM3v32_MOD_KT1 130 #define BSIM3v32_MOD_KT1L 131 #define BSIM3v32_MOD_K2 132 #define BSIM3v32_MOD_KT2 133 #define BSIM3v32_MOD_K3 134 #define BSIM3v32_MOD_K3B 135 #define BSIM3v32_MOD_W0 136 #define BSIM3v32_MOD_NLX 137 #define BSIM3v32_MOD_DVT0 138 #define BSIM3v32_MOD_DVT1 139 #define BSIM3v32_MOD_DVT2 140 #define BSIM3v32_MOD_DVT0W 141 #define BSIM3v32_MOD_DVT1W 142 #define BSIM3v32_MOD_DVT2W 143 #define BSIM3v32_MOD_DROUT 144 #define BSIM3v32_MOD_DSUB 145 #define BSIM3v32_MOD_VTH0 146 #define BSIM3v32_MOD_UA 147 #define BSIM3v32_MOD_UA1 148 #define BSIM3v32_MOD_UB 149 #define BSIM3v32_MOD_UB1 150 #define BSIM3v32_MOD_UC 151 #define BSIM3v32_MOD_UC1 152 #define BSIM3v32_MOD_U0 153 #define BSIM3v32_MOD_UTE 154 #define BSIM3v32_MOD_VOFF 155 #define BSIM3v32_MOD_DELTA 156 #define BSIM3v32_MOD_RDSW 157 #define BSIM3v32_MOD_PRT 158 #define BSIM3v32_MOD_LDD 159 #define BSIM3v32_MOD_ETA 160 #define BSIM3v32_MOD_ETA0 161 #define BSIM3v32_MOD_ETAB 162 #define BSIM3v32_MOD_PCLM 163 #define BSIM3v32_MOD_PDIBL1 164 #define BSIM3v32_MOD_PDIBL2 165 #define BSIM3v32_MOD_PSCBE1 166 #define BSIM3v32_MOD_PSCBE2 167 #define BSIM3v32_MOD_PVAG 168 #define BSIM3v32_MOD_WR 169 #define BSIM3v32_MOD_DWG 170 #define BSIM3v32_MOD_DWB 171 #define BSIM3v32_MOD_B0 172 #define BSIM3v32_MOD_B1 173 #define BSIM3v32_MOD_ALPHA0 174 #define BSIM3v32_MOD_BETA0 175 #define BSIM3v32_MOD_PDIBLB 178 #define BSIM3v32_MOD_PRWG 179 #define BSIM3v32_MOD_PRWB 180 #define BSIM3v32_MOD_CDSCD 181 #define BSIM3v32_MOD_AGS 182 #define BSIM3v32_MOD_FRINGE 184 #define BSIM3v32_MOD_ELM 185 #define BSIM3v32_MOD_CGSL 186 #define BSIM3v32_MOD_CGDL 187 #define BSIM3v32_MOD_CKAPPA 188 #define BSIM3v32_MOD_CF 189 #define BSIM3v32_MOD_CLC 190 #define BSIM3v32_MOD_CLE 191 #define BSIM3v32_MOD_PARAMCHK 192 #define BSIM3v32_MOD_VERSION 193 #define BSIM3v32_MOD_VFBCV 194 #define BSIM3v32_MOD_ACDE 195 #define BSIM3v32_MOD_MOIN 196 #define BSIM3v32_MOD_NOFF 197 #define BSIM3v32_MOD_IJTH 198 #define BSIM3v32_MOD_ALPHA1 199 #define BSIM3v32_MOD_VFB 200 #define BSIM3v32_MOD_TOXM 201 #define BSIM3v32_MOD_TCJ 202 #define BSIM3v32_MOD_TCJSW 203 #define BSIM3v32_MOD_TCJSWG 204 #define BSIM3v32_MOD_TPB 205 #define BSIM3v32_MOD_TPBSW 206 #define BSIM3v32_MOD_TPBSWG 207 #define BSIM3v32_MOD_VOFFCV 208 /* Length dependence */ #define BSIM3v32_MOD_LCDSC 251 #define BSIM3v32_MOD_LCDSCB 252 #define BSIM3v32_MOD_LCIT 253 #define BSIM3v32_MOD_LNFACTOR 254 #define BSIM3v32_MOD_LXJ 255 #define BSIM3v32_MOD_LVSAT 256 #define BSIM3v32_MOD_LAT 257 #define BSIM3v32_MOD_LA0 258 #define BSIM3v32_MOD_LA1 259 #define BSIM3v32_MOD_LA2 260 #define BSIM3v32_MOD_LKETA 261 #define BSIM3v32_MOD_LNSUB 262 #define BSIM3v32_MOD_LNPEAK 263 #define BSIM3v32_MOD_LNGATE 265 #define BSIM3v32_MOD_LGAMMA1 266 #define BSIM3v32_MOD_LGAMMA2 267 #define BSIM3v32_MOD_LVBX 268 #define BSIM3v32_MOD_LVBM 270 #define BSIM3v32_MOD_LXT 272 #define BSIM3v32_MOD_LK1 275 #define BSIM3v32_MOD_LKT1 276 #define BSIM3v32_MOD_LKT1L 277 #define BSIM3v32_MOD_LK2 278 #define BSIM3v32_MOD_LKT2 279 #define BSIM3v32_MOD_LK3 280 #define BSIM3v32_MOD_LK3B 281 #define BSIM3v32_MOD_LW0 282 #define BSIM3v32_MOD_LNLX 283 #define BSIM3v32_MOD_LDVT0 284 #define BSIM3v32_MOD_LDVT1 285 #define BSIM3v32_MOD_LDVT2 286 #define BSIM3v32_MOD_LDVT0W 287 #define BSIM3v32_MOD_LDVT1W 288 #define BSIM3v32_MOD_LDVT2W 289 #define BSIM3v32_MOD_LDROUT 290 #define BSIM3v32_MOD_LDSUB 291 #define BSIM3v32_MOD_LVTH0 292 #define BSIM3v32_MOD_LUA 293 #define BSIM3v32_MOD_LUA1 294 #define BSIM3v32_MOD_LUB 295 #define BSIM3v32_MOD_LUB1 296 #define BSIM3v32_MOD_LUC 297 #define BSIM3v32_MOD_LUC1 298 #define BSIM3v32_MOD_LU0 299 #define BSIM3v32_MOD_LUTE 300 #define BSIM3v32_MOD_LVOFF 301 #define BSIM3v32_MOD_LDELTA 302 #define BSIM3v32_MOD_LRDSW 303 #define BSIM3v32_MOD_LPRT 304 #define BSIM3v32_MOD_LLDD 305 #define BSIM3v32_MOD_LETA 306 #define BSIM3v32_MOD_LETA0 307 #define BSIM3v32_MOD_LETAB 308 #define BSIM3v32_MOD_LPCLM 309 #define BSIM3v32_MOD_LPDIBL1 310 #define BSIM3v32_MOD_LPDIBL2 311 #define BSIM3v32_MOD_LPSCBE1 312 #define BSIM3v32_MOD_LPSCBE2 313 #define BSIM3v32_MOD_LPVAG 314 #define BSIM3v32_MOD_LWR 315 #define BSIM3v32_MOD_LDWG 316 #define BSIM3v32_MOD_LDWB 317 #define BSIM3v32_MOD_LB0 318 #define BSIM3v32_MOD_LB1 319 #define BSIM3v32_MOD_LALPHA0 320 #define BSIM3v32_MOD_LBETA0 321 #define BSIM3v32_MOD_LPDIBLB 324 #define BSIM3v32_MOD_LPRWG 325 #define BSIM3v32_MOD_LPRWB 326 #define BSIM3v32_MOD_LCDSCD 327 #define BSIM3v32_MOD_LAGS 328 #define BSIM3v32_MOD_LFRINGE 331 #define BSIM3v32_MOD_LELM 332 #define BSIM3v32_MOD_LCGSL 333 #define BSIM3v32_MOD_LCGDL 334 #define BSIM3v32_MOD_LCKAPPA 335 #define BSIM3v32_MOD_LCF 336 #define BSIM3v32_MOD_LCLC 337 #define BSIM3v32_MOD_LCLE 338 #define BSIM3v32_MOD_LVFBCV 339 #define BSIM3v32_MOD_LACDE 340 #define BSIM3v32_MOD_LMOIN 341 #define BSIM3v32_MOD_LNOFF 342 #define BSIM3v32_MOD_LALPHA1 344 #define BSIM3v32_MOD_LVFB 345 #define BSIM3v32_MOD_LVOFFCV 346 /* Width dependence */ #define BSIM3v32_MOD_WCDSC 381 #define BSIM3v32_MOD_WCDSCB 382 #define BSIM3v32_MOD_WCIT 383 #define BSIM3v32_MOD_WNFACTOR 384 #define BSIM3v32_MOD_WXJ 385 #define BSIM3v32_MOD_WVSAT 386 #define BSIM3v32_MOD_WAT 387 #define BSIM3v32_MOD_WA0 388 #define BSIM3v32_MOD_WA1 389 #define BSIM3v32_MOD_WA2 390 #define BSIM3v32_MOD_WKETA 391 #define BSIM3v32_MOD_WNSUB 392 #define BSIM3v32_MOD_WNPEAK 393 #define BSIM3v32_MOD_WNGATE 395 #define BSIM3v32_MOD_WGAMMA1 396 #define BSIM3v32_MOD_WGAMMA2 397 #define BSIM3v32_MOD_WVBX 398 #define BSIM3v32_MOD_WVBM 400 #define BSIM3v32_MOD_WXT 402 #define BSIM3v32_MOD_WK1 405 #define BSIM3v32_MOD_WKT1 406 #define BSIM3v32_MOD_WKT1L 407 #define BSIM3v32_MOD_WK2 408 #define BSIM3v32_MOD_WKT2 409 #define BSIM3v32_MOD_WK3 410 #define BSIM3v32_MOD_WK3B 411 #define BSIM3v32_MOD_WW0 412 #define BSIM3v32_MOD_WNLX 413 #define BSIM3v32_MOD_WDVT0 414 #define BSIM3v32_MOD_WDVT1 415 #define BSIM3v32_MOD_WDVT2 416 #define BSIM3v32_MOD_WDVT0W 417 #define BSIM3v32_MOD_WDVT1W 418 #define BSIM3v32_MOD_WDVT2W 419 #define BSIM3v32_MOD_WDROUT 420 #define BSIM3v32_MOD_WDSUB 421 #define BSIM3v32_MOD_WVTH0 422 #define BSIM3v32_MOD_WUA 423 #define BSIM3v32_MOD_WUA1 424 #define BSIM3v32_MOD_WUB 425 #define BSIM3v32_MOD_WUB1 426 #define BSIM3v32_MOD_WUC 427 #define BSIM3v32_MOD_WUC1 428 #define BSIM3v32_MOD_WU0 429 #define BSIM3v32_MOD_WUTE 430 #define BSIM3v32_MOD_WVOFF 431 #define BSIM3v32_MOD_WDELTA 432 #define BSIM3v32_MOD_WRDSW 433 #define BSIM3v32_MOD_WPRT 434 #define BSIM3v32_MOD_WLDD 435 #define BSIM3v32_MOD_WETA 436 #define BSIM3v32_MOD_WETA0 437 #define BSIM3v32_MOD_WETAB 438 #define BSIM3v32_MOD_WPCLM 439 #define BSIM3v32_MOD_WPDIBL1 440 #define BSIM3v32_MOD_WPDIBL2 441 #define BSIM3v32_MOD_WPSCBE1 442 #define BSIM3v32_MOD_WPSCBE2 443 #define BSIM3v32_MOD_WPVAG 444 #define BSIM3v32_MOD_WWR 445 #define BSIM3v32_MOD_WDWG 446 #define BSIM3v32_MOD_WDWB 447 #define BSIM3v32_MOD_WB0 448 #define BSIM3v32_MOD_WB1 449 #define BSIM3v32_MOD_WALPHA0 450 #define BSIM3v32_MOD_WBETA0 451 #define BSIM3v32_MOD_WPDIBLB 454 #define BSIM3v32_MOD_WPRWG 455 #define BSIM3v32_MOD_WPRWB 456 #define BSIM3v32_MOD_WCDSCD 457 #define BSIM3v32_MOD_WAGS 458 #define BSIM3v32_MOD_WFRINGE 461 #define BSIM3v32_MOD_WELM 462 #define BSIM3v32_MOD_WCGSL 463 #define BSIM3v32_MOD_WCGDL 464 #define BSIM3v32_MOD_WCKAPPA 465 #define BSIM3v32_MOD_WCF 466 #define BSIM3v32_MOD_WCLC 467 #define BSIM3v32_MOD_WCLE 468 #define BSIM3v32_MOD_WVFBCV 469 #define BSIM3v32_MOD_WACDE 470 #define BSIM3v32_MOD_WMOIN 471 #define BSIM3v32_MOD_WNOFF 472 #define BSIM3v32_MOD_WALPHA1 474 #define BSIM3v32_MOD_WVFB 475 #define BSIM3v32_MOD_WVOFFCV 476 /* Cross-term dependence */ #define BSIM3v32_MOD_PCDSC 511 #define BSIM3v32_MOD_PCDSCB 512 #define BSIM3v32_MOD_PCIT 513 #define BSIM3v32_MOD_PNFACTOR 514 #define BSIM3v32_MOD_PXJ 515 #define BSIM3v32_MOD_PVSAT 516 #define BSIM3v32_MOD_PAT 517 #define BSIM3v32_MOD_PA0 518 #define BSIM3v32_MOD_PA1 519 #define BSIM3v32_MOD_PA2 520 #define BSIM3v32_MOD_PKETA 521 #define BSIM3v32_MOD_PNSUB 522 #define BSIM3v32_MOD_PNPEAK 523 #define BSIM3v32_MOD_PNGATE 525 #define BSIM3v32_MOD_PGAMMA1 526 #define BSIM3v32_MOD_PGAMMA2 527 #define BSIM3v32_MOD_PVBX 528 #define BSIM3v32_MOD_PVBM 530 #define BSIM3v32_MOD_PXT 532 #define BSIM3v32_MOD_PK1 535 #define BSIM3v32_MOD_PKT1 536 #define BSIM3v32_MOD_PKT1L 537 #define BSIM3v32_MOD_PK2 538 #define BSIM3v32_MOD_PKT2 539 #define BSIM3v32_MOD_PK3 540 #define BSIM3v32_MOD_PK3B 541 #define BSIM3v32_MOD_PW0 542 #define BSIM3v32_MOD_PNLX 543 #define BSIM3v32_MOD_PDVT0 544 #define BSIM3v32_MOD_PDVT1 545 #define BSIM3v32_MOD_PDVT2 546 #define BSIM3v32_MOD_PDVT0W 547 #define BSIM3v32_MOD_PDVT1W 548 #define BSIM3v32_MOD_PDVT2W 549 #define BSIM3v32_MOD_PDROUT 550 #define BSIM3v32_MOD_PDSUB 551 #define BSIM3v32_MOD_PVTH0 552 #define BSIM3v32_MOD_PUA 553 #define BSIM3v32_MOD_PUA1 554 #define BSIM3v32_MOD_PUB 555 #define BSIM3v32_MOD_PUB1 556 #define BSIM3v32_MOD_PUC 557 #define BSIM3v32_MOD_PUC1 558 #define BSIM3v32_MOD_PU0 559 #define BSIM3v32_MOD_PUTE 560 #define BSIM3v32_MOD_PVOFF 561 #define BSIM3v32_MOD_PDELTA 562 #define BSIM3v32_MOD_PRDSW 563 #define BSIM3v32_MOD_PPRT 564 #define BSIM3v32_MOD_PLDD 565 #define BSIM3v32_MOD_PETA 566 #define BSIM3v32_MOD_PETA0 567 #define BSIM3v32_MOD_PETAB 568 #define BSIM3v32_MOD_PPCLM 569 #define BSIM3v32_MOD_PPDIBL1 570 #define BSIM3v32_MOD_PPDIBL2 571 #define BSIM3v32_MOD_PPSCBE1 572 #define BSIM3v32_MOD_PPSCBE2 573 #define BSIM3v32_MOD_PPVAG 574 #define BSIM3v32_MOD_PWR 575 #define BSIM3v32_MOD_PDWG 576 #define BSIM3v32_MOD_PDWB 577 #define BSIM3v32_MOD_PB0 578 #define BSIM3v32_MOD_PB1 579 #define BSIM3v32_MOD_PALPHA0 580 #define BSIM3v32_MOD_PBETA0 581 #define BSIM3v32_MOD_PPDIBLB 584 #define BSIM3v32_MOD_PPRWG 585 #define BSIM3v32_MOD_PPRWB 586 #define BSIM3v32_MOD_PCDSCD 587 #define BSIM3v32_MOD_PAGS 588 #define BSIM3v32_MOD_PFRINGE 591 #define BSIM3v32_MOD_PELM 592 #define BSIM3v32_MOD_PCGSL 593 #define BSIM3v32_MOD_PCGDL 594 #define BSIM3v32_MOD_PCKAPPA 595 #define BSIM3v32_MOD_PCF 596 #define BSIM3v32_MOD_PCLC 597 #define BSIM3v32_MOD_PCLE 598 #define BSIM3v32_MOD_PVFBCV 599 #define BSIM3v32_MOD_PACDE 600 #define BSIM3v32_MOD_PMOIN 601 #define BSIM3v32_MOD_PNOFF 602 #define BSIM3v32_MOD_PALPHA1 604 #define BSIM3v32_MOD_PVFB 605 #define BSIM3v32_MOD_PVOFFCV 606 #define BSIM3v32_MOD_TNOM 651 #define BSIM3v32_MOD_CGSO 652 #define BSIM3v32_MOD_CGDO 653 #define BSIM3v32_MOD_CGBO 654 #define BSIM3v32_MOD_XPART 655 #define BSIM3v32_MOD_RSH 656 #define BSIM3v32_MOD_JS 657 #define BSIM3v32_MOD_PB 658 #define BSIM3v32_MOD_MJ 659 #define BSIM3v32_MOD_PBSW 660 #define BSIM3v32_MOD_MJSW 661 #define BSIM3v32_MOD_CJ 662 #define BSIM3v32_MOD_CJSW 663 #define BSIM3v32_MOD_NMOS 664 #define BSIM3v32_MOD_PMOS 665 #define BSIM3v32_MOD_NOIA 666 #define BSIM3v32_MOD_NOIB 667 #define BSIM3v32_MOD_NOIC 668 #define BSIM3v32_MOD_LINT 669 #define BSIM3v32_MOD_LL 670 #define BSIM3v32_MOD_LLN 671 #define BSIM3v32_MOD_LW 672 #define BSIM3v32_MOD_LWN 673 #define BSIM3v32_MOD_LWL 674 #define BSIM3v32_MOD_LMIN 675 #define BSIM3v32_MOD_LMAX 676 #define BSIM3v32_MOD_WINT 677 #define BSIM3v32_MOD_WL 678 #define BSIM3v32_MOD_WLN 679 #define BSIM3v32_MOD_WW 680 #define BSIM3v32_MOD_WWN 681 #define BSIM3v32_MOD_WWL 682 #define BSIM3v32_MOD_WMIN 683 #define BSIM3v32_MOD_WMAX 684 #define BSIM3v32_MOD_DWC 685 #define BSIM3v32_MOD_DLC 686 #define BSIM3v32_MOD_EM 687 #define BSIM3v32_MOD_EF 688 #define BSIM3v32_MOD_AF 689 #define BSIM3v32_MOD_KF 690 #define BSIM3v32_MOD_NJ 691 #define BSIM3v32_MOD_XTI 692 #define BSIM3v32_MOD_PBSWG 693 #define BSIM3v32_MOD_MJSWG 694 #define BSIM3v32_MOD_CJSWG 695 #define BSIM3v32_MOD_JSW 696 #define BSIM3v32_MOD_LLC 697 #define BSIM3v32_MOD_LWC 698 #define BSIM3v32_MOD_LWLC 699 #define BSIM3v32_MOD_WLC 700 #define BSIM3v32_MOD_WWC 701 #define BSIM3v32_MOD_WWLC 702 /* ACM parameters */ #define BSIM3v32_MOD_XL 703 #define BSIM3v32_MOD_XW 704 #define BSIM3v32_MOD_HDIF 711 #define BSIM3v32_MOD_LDIF 712 #define BSIM3v32_MOD_LD 713 #define BSIM3v32_MOD_RD 714 #define BSIM3v32_MOD_RS 715 #define BSIM3v32_MOD_RDC 716 #define BSIM3v32_MOD_RSC 717 #define BSIM3v32_MOD_WMLT 718 #define BSIM3v32_MOD_LMLT 719 /* device questions */ #define BSIM3v32_DNODE 751 #define BSIM3v32_GNODE 752 #define BSIM3v32_SNODE 753 #define BSIM3v32_BNODE 754 #define BSIM3v32_DNODEPRIME 755 #define BSIM3v32_SNODEPRIME 756 #define BSIM3v32_VBD 757 #define BSIM3v32_VBS 758 #define BSIM3v32_VGS 759 #define BSIM3v32_VDS 760 #define BSIM3v32_CD 761 #define BSIM3v32_CBS 762 #define BSIM3v32_CBD 763 #define BSIM3v32_GM 764 #define BSIM3v32_GDS 765 #define BSIM3v32_GMBS 766 #define BSIM3v32_GBD 767 #define BSIM3v32_GBS 768 #define BSIM3v32_QB 769 #define BSIM3v32_CQB 770 #define BSIM3v32_QG 771 #define BSIM3v32_CQG 772 #define BSIM3v32_QD 773 #define BSIM3v32_CQD 774 #define BSIM3v32_CGG 775 #define BSIM3v32_CGD 776 #define BSIM3v32_CGS 777 #define BSIM3v32_CBG 778 #define BSIM3v32_CAPBD 779 #define BSIM3v32_CQBD 780 #define BSIM3v32_CAPBS 781 #define BSIM3v32_CQBS 782 #define BSIM3v32_CDG 783 #define BSIM3v32_CDD 784 #define BSIM3v32_CDS 785 #define BSIM3v32_VON 786 #define BSIM3v32_VDSAT 787 #define BSIM3v32_QBS 788 #define BSIM3v32_QBD 789 #define BSIM3v32_SOURCECONDUCT 790 #define BSIM3v32_DRAINCONDUCT 791 #define BSIM3v32_CBDB 792 #define BSIM3v32_CBSB 793 #define BSIM3v32_MOD_VGS_MAX 801 #define BSIM3v32_MOD_VGD_MAX 802 #define BSIM3v32_MOD_VGB_MAX 803 #define BSIM3v32_MOD_VDS_MAX 804 #define BSIM3v32_MOD_VBS_MAX 805 #define BSIM3v32_MOD_VBD_MAX 806 #define BSIM3v32_MOD_VGSR_MAX 807 #define BSIM3v32_MOD_VGDR_MAX 808 #define BSIM3v32_MOD_VGBR_MAX 809 #define BSIM3v32_MOD_VBSR_MAX 810 #define BSIM3v32_MOD_VBDR_MAX 811 #include "bsim3v32ext.h" extern void BSIM3v32evaluate(double,double,double,BSIM3v32instance*,BSIM3v32model*, double*,double*,double*, double*, double*, double*, double*, double*, double*, double*, double*, double*, double*, double*, double*, double*, double*, double*, CKTcircuit*); extern int BSIM3v32debug(BSIM3v32model*, BSIM3v32instance*, CKTcircuit*, int); extern int BSIM3v32checkModel(BSIM3v32model*, BSIM3v32instance*, CKTcircuit*); #endif /*BSIM3v32*/
/** * @author Mariana Azevedo * @since 29/06/2019 * * Question 1.3.36 (page 155) - Choose the appropriate option when attempting to compile * and run the following file: * * class A { * public static void main(String[] args) { * switch(10) { * case < 10: * System.out.println("<"); * default: * System.out.println("="); * case > 10: * System.out.println(">"); * } * } * } * * a) Compile error. (x) * b) Compile and print "=". * c) Compiles and prints "=" and ">". */ class Question36 { public static void main(String[] args) { //switch(10) { //case < 10: System.out.println("<"); //default: System.out.println("="); //case > 10: System.out.println(">"); //} } }
#if not defined(YALR_YASSERT_HPP) #define YALR_YASSERT_HPP #include <cstdio> #include <cstdlib> [[noreturn]] inline void _yassert(const char* expression, const char *mesg, const char* file, int line) noexcept { fprintf(stderr, "Assertion '%s' failed, file '%s' line '%d': %s\n", expression, file, line, mesg); abort(); } [[noreturn]] inline void _yfail( const char *mesg, const char* file, int line) noexcept { fprintf(stderr, "Internal error, file '%s' line '%d': %s\n", file, line, mesg); abort(); } #define yassert(EXPR, MESG) ((EXPR) ? (void)0 : _yassert(#EXPR, MESG, __FILE__, __LINE__)) #define yfail(MESG) (_yfail(MESG, __FILE__, __LINE__)) #endif
/* * Get the outbound dest port for display and logging purposes. */ uint16_t cgn_sess2_port(struct cgn_sess2 *s2) { struct cgn_session *cse; cse = cgn_sess_from_cs2(s2->s2_cs2); if (cgn_session_is_alg_pptp_child(cse)) return cgn_alg_pptp_peer_call_id(cse); return s2->s2_sentry[CGN_DIR_OUT].s2e_key.k_port; }
Cosmo Goss, the executive chef of Chicago’s popular and award-winning Publican restaurants, was fired after ownership said he failed to take disciplinary action when a “personal” and “inappropriate” photo of a female employee was shared among staff without her permission. One Off Hospitality Group, The Publican’s parent, said Goss should have reported this instance of harassment to human resources or fired the employee who shared the photograph. One Off hired a legal firm to investigate the matter before firing Goss and a second employee — Antonio Molina — the general manager of Wicker Park’s Publican Anker. The two were fired for helping foster an atmosphere where women felt uncomfortable working at the restaurant, according to One Off. The initial incident happened in late 2016 at Publican Anker where another employee showed Goss the photograph in question. While One Off maintains Goss and Molina didn’t take the employee’s concerns seriously, Goss said she never approached him with those concerns. The employee eventually reported the incident to One Off’s corporate HR offices. The company hired outside legal counsel to investigate the claim the day the employee spoke with HR, according to a One Off rep. “Throughout the investigation, it was vital for us to understand the full scope of the allegations to ensure the team member’s wellbeing and security,” a prepared statement from the company read. “One Off has an open-door policy, and it’s our responsibility to address instances of inappropriate workplace conduct thoroughly and with zero tolerance.” The Publican is a Beard-winning restaurant and One Off’s Donnie Madia won the Beard Award for Outstanding Restaurateur in 2015. Goss had spent seven years at Madia and chef Paul Kahan’s company. Goss was just named executive chef of The Publican brand last year — he was in charge of the menus at all five restaurants that carry the Publican name. Back in 2012 — when he was 23 — he opened Publican Quality Meats as the restaurant’s head butcher off Fulton Market. While Goss wouldn’t comment directly, he confirmed the incident and firing in a statement that expressed regret. He admitted that he “was in a position to make a difference, and did not to rise to the occasion.” According to Goss, he only viewed the photo for “a few seconds” and that he didn’t “escalate the incident.” Incidents like these “were not the norm,” the statement added. While neither Goss nor One Off provided a detailed description of the photo, Goss did call it an “inappropriate photograph.” “In retrospect, I understand that this seemingly fleeting moment was wholly unprofessional and unacceptable,” Goss’s statement read. “As a leader at One Off Hospitality, I regret not doing enough to address the issue, and I am deeply sorry to the woman portrayed in the photograph and the other individuals whom these consequences have affected.” Molina was Goss’s front-of-the-house counterpart. As the GM, he also had a responsibility to report the incident and failed, One Off contends. Goss is also credited as a co-author on the new Cheers to the Publican cookbook. He was quickly taken off the book’s promotional tour. Goss’s position was created for him, so it could go unfilled. The restaurant is in the process of replacing Molina, a spokeswoman said. There’s additional fallout from the firings as One Off needs to make some decisions. Goss and his good friend Erling Wu-Bower are planning to open a new River North restaurant with One Off’s support. A spokeswoman said the firing won’t affect the opening timeframe for Pacific Standard Time, a collaboration between One Off with Goss’s and Wu-Bower’s new company, Underscore Hospitality. Nationally, it’s one of the most anticipated restaurant openings of the fall. However, One Off is reevaluating its support of the project and Goss’s role at the restaurant. Goss’s own statement mentioned that he looks forward to collaborating with One Off. Wu-Bower was not reached for comment. Eater Chicago Sign up for our newsletter. Enter your email address Subscribe By signing up, you agree to our Privacy Policy and European users agree to the data transfer policy. Goss’s future with Pacific Standard Time is in doubt, according to a spokeswoman who represents One Off and Underscore. Despite that uncertainty, Goss writes that he will be a positive influence on the upcoming restaurant and that he has a “responsibility to be an advocate for immediate change.” Goss wants to establish a stricter, better set of standards for reporting harassment. One Off already mandates managers to participate in anti-harassment training, according to the same spokeswoman. The firings come against the backdrop of women coming forward with their stories of sexual harassment using the #MeToo hashtag — which is bringing awareness and acknowledgement of rape culture. The restaurant industry is hardly immune. One prime example is the 25 women who have alleged sexual harassment while working for the Besh Restaurant Group in New Orleans. On Monday, Besh resigned. UPDATE: Molina said One Off never told him why he was fired, according to DNAinfo.
. Public and private accident insurance companies have in common that the insurance risk is the damage to health caused by trauma. Otherwise, they are fundamentally different. Public accident insurance as part of social law has the function of providing compensation for damage. Functional impairment due to trauma is compensated abstractly according to the general labor market. Private accident insurance as part of civil law is an insurance of fixed sums anchored in the agreement. It is completely unrelated to the consequences of trauma-induced limitation of function.
/** * Hosted version of {@link CollectionAdapterManager} * * @author [email protected] (Abhinav Khandelwal) */ public class FeedServerAdapterManager extends CollectionAdapterManager { public FeedServerAdapterManager(Abdera abdera, ServerConfiguration config) { super(abdera, config); } /** * Gets a {@link CollectionAdapter} for the specified feed based on the * {@link FeedConfiguration} * * @param feedId The feed to get a collection adapter for * @param userId User email of per user feed; null if not per user feed */ public AbstractManagedCollectionAdapter getAdapter(String feedId, String userId) throws Exception { FeedConfiguration feedConfiguration = ((PerNamespaceServerConfiguration) config).loadFeedConfiguration(feedId, userId); return createWrappedAdapter(feedConfiguration, abdera); } /** * Creates a wrapper around {@code targetAdapter}. * * @param wrapperClassName fully qualified class name of wrapper. * @param targetAdapter the adapter to be wrapped. * @param wrapperConfig config data for wrapper. * * @return targetAdapter wrapped with {@code wrapperClassName}. * @throws ClassNotFoundException * @throws SecurityException * @throws NoSuchMethodException * @throws IllegalArgumentException * @throws InstantiationException * @throws IllegalAccessException * @throws InvocationTargetException */ public static AbstractManagedCollectionAdapter createWrapper(String wrapperClassName, AbstractManagedCollectionAdapter targetAdapter, String wrapperConfig) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { return (AbstractManagedCollectionAdapter) createAdapter(wrapperClassName, new Class[] { AbstractManagedCollectionAdapter.class, String.class}, targetAdapter, wrapperConfig); } /** * Creates {@link CollectionAdapter} for feed with given * {@link FeedConfiguration}. This also wraps the adapter with all the needed * wrappers. * * @param config {@link FeedConfiguration} of the feed. * @param abdera {@link Abdera} instance used in the server. * * @return Wrapped {@link CollectionAdapter} for the feed. * * @throws ClassNotFoundException * @throws SecurityException * @throws NoSuchMethodException * @throws IllegalArgumentException * @throws InstantiationException * @throws IllegalAccessException * @throws InvocationTargetException */ public static AbstractManagedCollectionAdapter createWrappedAdapter(FeedConfiguration config, Abdera abdera) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { AbstractManagedCollectionAdapter adapter = createManagedAdapter(config, abdera); if (config.getServerConfiguration() instanceof PerNamespaceServerConfiguration) { String wrapperManagerClass = ((PerNamespaceServerConfiguration) config.getServerConfiguration()) .getWrapperManagerClassName(); return (AbstractManagedCollectionAdapter) createAdapter(wrapperManagerClass, new Class[] {AbstractManagedCollectionAdapter.class}, adapter); } else { return adapter; } } /** * Creates {@link AbstractManagedCollectionAdapter} for the feed with given * {@link FeedConfiguration}. * * @param config {@link FeedConfiguration} of the feed. * @param abdera {@link Abdera} instance used in the server. * * @return {@link CollectionAdapter} for the feed. * * @throws ClassNotFoundException * @throws SecurityException * @throws NoSuchMethodException * @throws IllegalArgumentException * @throws InstantiationException * @throws IllegalAccessException * @throws InvocationTargetException */ public static AbstractManagedCollectionAdapter createManagedAdapter(FeedConfiguration config, Abdera abdera) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { return (AbstractManagedCollectionAdapter) createAdapter(config.getAdapterClassName(), new Class[] {Abdera.class, FeedConfiguration.class}, abdera, config); } /** * Creates {@link CollectionAdapter}. * * @param adapterType fully qualified class name for the adapter. * @param paramClasses the class's for parameters in the constructor of the * adapter (in order). * @param objects the objects that need to be passed to the constructor (in * order). * @return an instance of type {@link CollectionAdapter} * @throws ClassNotFoundException * @throws SecurityException * @throws NoSuchMethodException * @throws IllegalArgumentException * @throws InstantiationException * @throws IllegalAccessException * @throws InvocationTargetException */ @SuppressWarnings("unchecked") public static synchronized CollectionAdapter createAdapter(String adapterType, Class[] paramClasses, Object... objects) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Class<?> adapterClass = cl.loadClass(adapterType); Constructor<?>[] ctors = adapterClass.getConstructors(); for (Constructor<?> element : ctors) { logger.finest("Public constructor found: " + element); } Constructor<?> c = adapterClass.getConstructor(paramClasses); c.setAccessible(true); CollectionAdapter adapterInstance = (CollectionAdapter) c.newInstance(objects); return adapterInstance; } }
Treatment with human immunoglobulin G improves the early disease course in a mouse model of Duchenne muscular dystrophy Duchenne muscular dystrophy (DMD) is a severe hereditary myopathy. Standard treatment by glucocorticosteroids is limited because of numerous side effects. The aim of this study was to test immunomodulation by human immunoglobulin G (IgG) as treatment in the experimental mouse model (mdx) of DMD. 2 g/kg human IgG compared to human albumin was injected intraperitoneally in mdx mice at the age of 3 and 7 weeks. Advanced voluntary wheel running parameters were recorded continuously. At the age of 11 weeks, animals were killed so that blood, diaphragm, and lower limb muscles could be removed for quantitative PCR, histological analysis and ex vivo muscle contraction tests. IgG compared to albumin significantly improved the voluntary running performance and reduced muscle fatigability in an ex vivo muscle contraction test. Upon IgG treatment, serum creatine kinase values were diminished and mRNA expression levels of relevant inflammatory markers were reduced in the diaphragm and limb muscles. Macrophage infiltration and myopathic damage were significantly ameliorated in the quadriceps muscle. Collectively, this study demonstrates that, in the early disease course of mdx mice, human IgG improves the running performance and diminishes myopathic damage and inflammation in the muscle. Therefore, IgG may be a promising approach for treatment of DMD.
/** * This will be called for every importer configuration section for this importer type. * * @param props Properties defined in a configuration section for this importer */ public final void configure(Properties props, FormatterBuilder formatterBuilder) { Map<URI, ImporterConfig> configs = m_factory.createImporterConfigurations(props, formatterBuilder); m_configs = new ImmutableMap.Builder<URI, ImporterConfig>() .putAll(configs) .putAll(Maps.filterKeys(m_configs, not(in(configs.keySet())))) .build(); }
/** An instance of this class represents a parsing context within a node. Data is written to the supplied output stream in utf-8 format. */ public class XMLOutputStreamParsingContext extends XMLWriterParsingContext { /** The writer */ protected OutputStream outputStream; /** Full constructor. Used for individual tags. */ public XMLOutputStreamParsingContext(XMLFuzzyHierarchicalParseState theStream, String namespace, String localname, String qname, Map<String,String> theseAttributes, OutputStream os) throws ManifoldCFException { // Construct an appropriate writer super(theStream,namespace,localname,qname,theseAttributes,new OutputStreamWriter(os, StandardCharsets.UTF_8)); // Save the stream outputStream = os; } /** Flush the data to the underlying output stream */ public void flush() throws ManifoldCFException { try { if (outputStream != null) { // Do the base class first - this flushes the Writer super.flush(); outputStream.flush(); } } catch (java.net.SocketTimeoutException e) { throw new ManifoldCFException("Socket timeout exception: "+e.getMessage(),e); } catch (InterruptedIOException e) { throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (IOException e) { throw new ManifoldCFException("IO exception: "+e.getMessage(),e); } } /** Close the underlying stream. */ public void close() throws ManifoldCFException { // Now, close. try { if (outputStream != null) { outputStream.close(); outputStream = null; } } catch (java.net.SocketTimeoutException e) { throw new ManifoldCFException("Socket timeout exception: "+e.getMessage(),e); } catch (InterruptedIOException e) { throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (IOException e) { throw new ManifoldCFException("IO exception: "+e.getMessage(),e); } } }
/** * Abstract implementation of IExtVisitor that adds an invariant implementation of * storing commands associated with each case in a dictionary indexed by the * case's associated index value. * When a particular case is called, the associated command is retrieved and * executed. The return value is the return value from the command. * If no associated command is found, then a default command is executed. * In general, command-based implementations of IExtVisitor will be concrete subclasses of this class. * <br>Usage:<pre> * public class MyExtVisitor extends AExtVisitor&lt;MyReturn, MyIndex, MyReturn, MyExtVisitorHost&gt; {...} * </pre> * @param <R> The type of the return value * @param <I> The type of the index value * @param <P> The type of the input parameters * @param <H> The type of the host, restricted to being a subclass of IExtVisitorHost&lt;I, ? super H&gt; * @author Stephen Wong (c) 2010 * ---------------------------------------------- * Adds invariant command management and caseAt() behavior. */ public abstract class AExtVisitor<R, I, P, H extends IExtVisitorHost<I, ? super H> > implements IExtVisitor<R,I,P, H> { /** * Version number for serialization */ private static final long serialVersionUID = 4445948668748598430L; /** * The dictionary used to store the commands */ private Map<I, IExtVisitorCmd<R, I, P, H>> cmds = new Hashtable<I, IExtVisitorCmd<R, I, P, H>>(); /** * The default command to use if no command is associated with a case index value. */ private IExtVisitorCmd<R, I, P, H> defaultCmd; /** * Constructor that takes a default command to use. * @param defaultCmd The default command to use. */ public AExtVisitor(IExtVisitorCmd<R, I, P, H> defaultCmd) { this.defaultCmd = defaultCmd; } /** * A convenience constructor that takes a value that the default command will return. * A default command is created will return the given value and do nothing else. * @param noOpResult The value for the default command to return. */ public AExtVisitor(final R noOpResult) { this(new IExtVisitorCmd<R, I, P, H>() { private static final long serialVersionUID = -3773477471593844489L; public <T extends IExtVisitorHost<I, ? super H>> R apply(I index, T host, @SuppressWarnings("unchecked") P... params) { return noOpResult; } }); } /** * Associates the given index value with the given command * @param idx The index value to use associate with the command. * @param cmd The command associated with the index value */ public void setCmd(I idx, IExtVisitorCmd<R, I, P, H> cmd) { cmds.put(idx, cmd); } /** * Retrieve the command associated with given index value. * null is returned if no command is associated with the index value. * @param idx An index value * @return The IExtVisitorCmd associated with the index value or null */ public IExtVisitorCmd<R, I, P, H> getCmd(I idx) { return cmds.get(idx); } /** * Retrieve the current default command * @return The current default command */ public IExtVisitorCmd<R, I, P, H> getDefaultCmd(){ return defaultCmd; } /** * Set the default command to a new value. * @param defaultCmd The new default command */ public void setDefaultCmd(IExtVisitorCmd<R, I, P, H> defaultCmd) { this.defaultCmd = defaultCmd; } /** * Concrete implementation of the parameterized case method that takes * the index value, retrieves an associated IExtVisitor command and * executes the command with the given host and input parameters. * The result from the command execution is returned. If not associated * command is found, then the current default command is executed. * Any given host's execute method will call this method, passing the index value * associated with that host, a reference to the host itself and pass along any * input parameters that were supplied. * @param <T> The type of the host the is expected to call this method. T is restricted to be a subclass of IExtVisitorHost&lt;I, ? super H&gt; * @param idx The index value for the case * @param host The visitor's host. * @param params Vararg input parameters for the case * @return The result from executing the associated or default command */ public <T extends IExtVisitorHost<I, ? super H>> R caseAt(I idx, T host, @SuppressWarnings("unchecked") P... params) { IExtVisitorCmd<R, I, P, H> cmd = cmds.get(idx); if(cmd == null) return defaultCmd.apply(idx, host, params); else return cmd.apply(idx, host, params); } /** * Returns a Set of all the indices currently installed in the visitor * @return a Set of index values */ public Set<I> getAllIndices() { return cmds.keySet(); } }
/* write GPIO OUT value to pin 'gpio' */ int gpio_set_value(unsigned gpio, int value) { debug("gpio_set_value: pin = %d (port %d:bit %d), value = %d\n", gpio, GPIO_FULLPORT(gpio), GPIO_BIT(gpio), value); set_level(gpio, value); return 0; }
<reponame>Deanosim/universal-trakt-scrobbler<filename>src/services/goplay-be/goplay-be.ts import '@/goplay-be/GoplayBeParser'; import { init } from '@service'; void init('goplay-be');
<filename>base/ntos/ke/aligntrk.c /*++ Copyright (c) 1990 Microsoft Corporation Copyright (c) 1993, 1994 Digital Equipment Corporation Module Name: aligntrk.c Abstract: This module implements the code necessary to dispatch exceptions to the proper mode and invoke the exception dispatcher. Author: <NAME> (davec) 3-Apr-1990 Environment: Kernel mode only. Revision History: <NAME> (tvb) 12-May-1992 Adapted for Alpha AXP. <NAME> (forrestf) 30-Dec-1999 Broke out increasingly complex and common alignment fault handling into this file. --*/ #include "ki.h" // // EXINFO_EFFECTIVE_ADDRESS: slot number [0...4] for faulting address. // #if defined(_IA64_) #define EXINFO_EFFECTIVE_ADDRESS 1 #else // !_IA64_ #define EXINFO_EFFECTIVE_ADDRESS 2 #endif // !_IA64_ // // Data misalignment exception (auto alignment fixup) control. // // If KiEnableAlignmentFaultExceptions is 0, then no alignment // exceptions are raised and all misaligned user and kernel mode data // references are emulated. This is consistent with NT/Alpha version // 3.1 behavior. // // If KiEnableAlignmentFaultExceptions is 1, then the // current thread automatic alignment fixup enable determines whether // emulation is attempted in user mode. This is consistent with NT/Mips // behavior. // // If KiEnableAlignmentFaultExceptions is 2, then the behavior depends // on the execution mode at the time of the fault. Kernel-mode code gets // type 1 behaivor above (no fixup), user-mode code gets type 0 above // (fixup). // // This last mode is temporary until we flush out the remaining user-mode // alignment faults, at which point the option will be removed and the // default value will be set to 1. // // N.B. This default value may be reset from the Registry during init. // ULONG KiEnableAlignmentFaultExceptions = 1; #define IsWow64Process() (PsGetCurrentProcess()->Wow64Process != NULL) #if DBG // // Globals to track the number of alignment exception fixups in both user and // kernel. // ULONG KiKernelFixupCount = 0; ULONG KiUserFixupCount = 0; // // Set KiBreakOnAlignmentFault to the desired combination of // the following flags. // #define KE_ALIGNMENT_BREAK_USER 0x01 #define KE_ALIGNMENT_BREAK_KERNEL 0x02 ULONG KiBreakOnAlignmentFault = KE_ALIGNMENT_BREAK_USER; __inline BOOLEAN KI_BREAK_ON_ALIGNMENT_FAULT( IN KPROCESSOR_MODE PreviousMode ) /*++ Routine description: Given that an alignment fault has been encountered, determines whether a debug break should occur based on the execution mode of the fault and flags in KiBreakOnAlignmentFault. Arguments: PreviousMode - The execution mode at the time of the fault. Return Value: TRUE if a debug break should occur, FALSE otherwise. --*/ { if ((KiBreakOnAlignmentFault & KE_ALIGNMENT_BREAK_USER) != 0 && PreviousMode == UserMode) { return TRUE; } if ((KiBreakOnAlignmentFault & KE_ALIGNMENT_BREAK_KERNEL) != 0 && PreviousMode == KernelMode) { return TRUE; } return FALSE; } // // Structures to track alignment fault locations on a global basis. These // are used in the checked kernel only, as an aid in finding and fixing // alignment faults in the system. // #define MAX_IMAGE_NAME_CHARS 15 typedef struct _ALIGNMENT_FAULT_IMAGE *PALIGNMENT_FAULT_IMAGE; typedef struct _ALIGNMENT_FAULT_LOCATION *PALIGNMENT_FAULT_LOCATION; typedef struct _ALIGNMENT_FAULT_IMAGE { // // Head of singly-linked list of fault locations associated with this image // PALIGNMENT_FAULT_LOCATION LocationHead; // // Total number of alignment faults associated with this image. // ULONG Count; // // Number of unique alignment fault locations found in this image // ULONG Instances; // // Name of the image // CHAR Name[ MAX_IMAGE_NAME_CHARS + 1 ]; } ALIGNMENT_FAULT_IMAGE; BOOLEAN KiNewGlobalAlignmentFault( IN PVOID ProgramCounter, IN KPROCESSOR_MODE PreviousMode, OUT PALIGNMENT_FAULT_IMAGE *AlignmentFaultImage ); #endif NTSTATUS KipRecordAlignmentException( IN PVOID ProgramCounter, OUT PALIGNMENT_EXCEPTION_RECORD *ExceptionRecord ); PALIGNMENT_EXCEPTION_RECORD KipFindAlignmentException( IN PVOID ProgramCounter ); PALIGNMENT_EXCEPTION_RECORD KipAllocateAlignmentExceptionRecord( VOID ); BOOLEAN KiHandleAlignmentFault( IN PEXCEPTION_RECORD ExceptionRecord, IN PKEXCEPTION_FRAME ExceptionFrame, IN PKTRAP_FRAME TrapFrame, IN KPROCESSOR_MODE PreviousMode, IN BOOLEAN FirstChance, OUT BOOLEAN *ExceptionForwarded ) /*++ Routine description: This routine deals with alignment exceptions as appropriate. See comments at the beginning of this module. Arguments: ExceptionRecord - Supplies a pointer to an exception record. ExceptionFrame - Supplies a pointer to an exception frame. TrapFrame - Supplies a pointer to a trap frame. PreviousMode - Supplies the previous processor mode. FirstChance - Supplies a boolean variable that specifies whether this is the first (TRUE) or second (FALSE) time that this exception has been processed. ExceptionForwarded - On return, indicates whether the exception had already been forwarded to a user-mode debugger. Return Value: TRUE if the alignment exception was handled, FALSE otherwise. --*/ { BOOLEAN AlignmentFaultHandled; BOOLEAN EmulateAlignmentFault; BOOLEAN ExceptionWasForwarded; BOOLEAN AutoAlignment; NTSTATUS Status; PVOID ProgramCounter; #if DBG BOOLEAN NewAlignmentFault; PVOID EffectiveAddress; PALIGNMENT_FAULT_IMAGE FaultImage; #endif // // Assume the fault was not handled and that the exception had not // been forwarded to a user-mode debugger. // AlignmentFaultHandled = FALSE; ExceptionWasForwarded = FALSE; if (FirstChance != FALSE) { // // This is the first chance for handling an exception... we haven't yet // searched for an exception handler. // EmulateAlignmentFault = FALSE; AutoAlignment = FALSE; ProgramCounter = (PVOID)ExceptionRecord->ExceptionAddress; // // Determine whether autoalignment is enabled for thread. If a DPC or // an interrupt is being executed, then we are in an arbitrary thread // context. Per-process and per-thread settings are ignored in this // case. // if (IsWow64Process() != FALSE) { // // For now, autoalignment is on (both user and kernel) for Wow64 // processes. // AutoAlignment = TRUE; } if (PreviousMode == UserMode && (KeGetCurrentThread()->AutoAlignment != FALSE || KeGetCurrentThread()->ApcState.Process->AutoAlignment != FALSE)) { // // The fault occured in user mode, and the thread and/or process // has autoalignment turned on. // #if defined(_IA64_) // // On IA64 platform, reset psr.ac bit to disable alignment check // TrapFrame->StIPSR &= ~(ULONGLONG)(1ULL << PSR_AC); #endif // defined(_IA64_) AutoAlignment = TRUE; } if (PreviousMode == UserMode && PsGetCurrentProcess()->DebugPort != NULL && AutoAlignment == FALSE) { BOOLEAN DebuggerHandledException; PALIGNMENT_EXCEPTION_RECORD AlignmentExceptionRecord; // // The alignment exception is in user mode, there is a debugger // attached, and autoalignment is not enabled for this thread. // // Determine whether this exception has already been observed // and, if so, whether we should break into the debugger. // Status = KipRecordAlignmentException( ProgramCounter, &AlignmentExceptionRecord ); if (!NT_SUCCESS(Status)) { AlignmentExceptionRecord = NULL; } if (AlignmentExceptionRecord != NULL && AlignmentExceptionRecord->AutoFixup != FALSE) { // // The alignment exception record for this location // indicates that an automatic fixup should be applied // without notifying the debugger. This is because // the user entered 'gh' at the debug prompt the last // time we reported this fault. // EmulateAlignmentFault = TRUE; } else { // // Forward the exception to the debugger. // ExceptionWasForwarded = TRUE; DebuggerHandledException = DbgkForwardException( ExceptionRecord, TRUE, FALSE ); if (DebuggerHandledException != FALSE) { // // The user continued with "gh", so fix up this and all // subsequent alignment exceptions at this address. // EmulateAlignmentFault = TRUE; if (AlignmentExceptionRecord != NULL) { AlignmentExceptionRecord->AutoFixup = TRUE; } } } } else if ((KiEnableAlignmentFaultExceptions == 0) || (AutoAlignment != FALSE) || (PreviousMode == UserMode && KiEnableAlignmentFaultExceptions == 2)) { // // Emulate the alignment if: // // KiEnableAlignmentFaultExceptions is 0, OR // this thread has enabled alignment fixups, OR // the current process is a WOW64 process, OR // KiEnableAlignmentFaultExceptions is 2 and the fault occured // in usermode // EmulateAlignmentFault = TRUE; } else { // // We are not fixing up the alignment fault. // #if defined(_IA64_) // // On IA64 platform, set psr.ac bit to enable h/w alignment check // TrapFrame->StIPSR |= (1ULL << PSR_AC); #endif // defined(_IA64_) } #if DBG // // Count alignment faults by mode. // if (PreviousMode == KernelMode) { KiKernelFixupCount += 1; } else { KiUserFixupCount += 1; } EffectiveAddress = (PVOID)ExceptionRecord->ExceptionInformation[EXINFO_EFFECTIVE_ADDRESS]; NewAlignmentFault = KiNewGlobalAlignmentFault( ProgramCounter, PreviousMode, &FaultImage ); if (NewAlignmentFault != FALSE) { // // Attempt to determine and display the name of the offending // image. // DbgPrint("KE: %s Fixup: %.16s [%.16s], Pc=%.16p, Addr=%.16p ... Total=%ld %s\n", (PreviousMode == KernelMode) ? "Kernel" : "User", &PsGetCurrentProcess()->ImageFileName[0], FaultImage->Name, ProgramCounter, EffectiveAddress, (PreviousMode == KernelMode) ? KiKernelFixupCount : KiUserFixupCount, IsWow64Process() ? "(Wow64)" : ""); if (AutoAlignment == FALSE && KI_BREAK_ON_ALIGNMENT_FAULT( PreviousMode ) != FALSE && ExceptionWasForwarded == FALSE) { if (EmulateAlignmentFault == FALSE) { DbgPrint("KE: Misaligned access WILL NOT be emulated\n"); } // // This alignment fault would not normally have been fixed up, // and KiBreakOnAlignmentFault flags indicate that we should // break into the kernel debugger. // // Also, we know that we have not broken into a user-mode // debugger as a result of this fault. // if (PreviousMode != KernelMode) { RtlMakeStackTraceDataPresent(); } DbgBreakPoint(); } } #endif // // Emulate the reference according to the decisions made above. // if (EmulateAlignmentFault != FALSE) { if (KiEmulateReference(ExceptionRecord, ExceptionFrame, TrapFrame) != FALSE) { KeGetCurrentPrcb()->KeAlignmentFixupCount += 1; AlignmentFaultHandled = TRUE; } } } *ExceptionForwarded = ExceptionWasForwarded; return AlignmentFaultHandled; } NTSTATUS KipRecordAlignmentException( IN PVOID ProgramCounter, OUT PALIGNMENT_EXCEPTION_RECORD *ExceptionRecord ) /*++ Routine Description: This routine searches for an existing ALIGNMENT_EXCEPTION_RECORD on the per-process list of alignment exceptions. If a match is not found, then a new record is created. Arguments: ProgramCounter - Supplies the address of the faulting instruction. ExceptionRecord - Supplies a pointer into which is placed the address of the matching alignment exception record. Return Value: STATUS_SUCCESS if the operation was successful, or an appropriate error code otherwise. --*/ { PALIGNMENT_EXCEPTION_RECORD exceptionRecord; NTSTATUS status; // // Lock the alignment exception database // KeEnterCriticalRegion(); ExAcquireResourceExclusive( &PsLoadedModuleResource, TRUE ); exceptionRecord = KipFindAlignmentException( ProgramCounter ); if (exceptionRecord == NULL) { // // New exception. Allocate a new record. // exceptionRecord = KipAllocateAlignmentExceptionRecord(); if (exceptionRecord == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; goto exitUnlock; } exceptionRecord->ProgramCounter = ProgramCounter; } exceptionRecord->Count += 1; *ExceptionRecord = exceptionRecord; status = STATUS_SUCCESS; exitUnlock: ExReleaseResourceLite( &PsLoadedModuleResource ); KeLeaveCriticalRegion(); return status; } PALIGNMENT_EXCEPTION_RECORD KipAllocateAlignmentExceptionRecord( VOID ) /*++ Routine Description: This is a support routine for KipRecordAlignmentException(). Its purpose is to locate an available alignment exception record in the per-process alignment exception list. If none is found, a new alignment exception table will be allocated and linked into the per-process list. Arguments: None. Return Value: A pointer to the new alignment exception record if successful, or NULL otherwise. --*/ { PKTHREAD thread; PKPROCESS process; PALIGNMENT_EXCEPTION_RECORD exceptionRecord; PALIGNMENT_EXCEPTION_TABLE exceptionTable; ULONG exceptionTableCount; // // Free exception records have a NULL program counter. // exceptionRecord = KipFindAlignmentException( NULL ); if (exceptionRecord == NULL) { thread = KeGetCurrentThread(); process = thread->ApcState.Process; // // Ensure that we haven't exceeded the maximum number of alignment // exception tables for this process. We could keep a count but we // do not care about performance here... this code only executes when // the process is running under a debugger and we're likely about // to break in. // exceptionTableCount = 0; exceptionTable = process->AlignmentExceptionTable; while (exceptionTable != NULL) { exceptionTableCount += 1; exceptionTable = exceptionTable->Next; } if (exceptionTableCount == MAXIMUM_ALIGNMENT_TABLES) { return NULL; } // // Allocate a new exception table and insert it at the // head of the per-process list. // exceptionTable = ExAllocatePoolWithTag( PagedPool, sizeof(ALIGNMENT_EXCEPTION_TABLE), 'tpcX' ); if (exceptionTable == NULL) { return NULL; } RtlZeroMemory( exceptionTable, sizeof(ALIGNMENT_EXCEPTION_TABLE) ); exceptionTable->Next = process->AlignmentExceptionTable; process->AlignmentExceptionTable = exceptionTable; // // Allocate the first record in the array // exceptionRecord = &exceptionTable->RecordArray[0]; } return exceptionRecord; } PALIGNMENT_EXCEPTION_RECORD KipFindAlignmentException( IN PVOID ProgramCounter ) /*++ Routine Description: This routine searches the alignment exception tables associated with the current process for an alignment exception record that matches the supplied program counter. Arguments: ProgramCounter - Supplies the address of the faulting instruction. Return Value: A pointer to the matching alignment exception record, or NULL if none was found. --*/ { PKTHREAD thread; PKPROCESS process; PALIGNMENT_EXCEPTION_RECORD exceptionRecord; PALIGNMENT_EXCEPTION_RECORD lastExceptionRecord; PALIGNMENT_EXCEPTION_TABLE exceptionTable; thread = KeGetCurrentThread(); process = thread->ApcState.Process; // // Walk the singly-linked list of exception tables dangling // off of the process. // exceptionTable = process->AlignmentExceptionTable; while (exceptionTable != NULL) { // // Scan this table looking for a match. // exceptionRecord = exceptionTable->RecordArray; lastExceptionRecord = &exceptionTable->RecordArray[ ALIGNMENT_RECORDS_PER_TABLE ]; while (exceptionRecord < lastExceptionRecord) { if (exceptionRecord->ProgramCounter == ProgramCounter) { // // Found it. // return exceptionRecord; } exceptionRecord++; } if (ProgramCounter == NULL) { // // Caller was looking for a free exception record. If one exists // it will be in the first table, which was just examined. // break; } // // Go look in the next exception table. // exceptionTable = exceptionTable->Next; } return NULL; } #if DBG // // The following routines are used to maintain a global database of alignment // faults that were found in the system. Alignment faults are stored according // to the name of the image and the offset within that image. In this way an // existing alignment fault record will be found if it occurs in the same image // loaded at a different base address in a new process. // typedef struct _ALIGNMENT_FAULT_LOCATION { // // Pointer to fault image associated with this location // PALIGNMENT_FAULT_IMAGE Image; // // Linkage for singly-linked list of fault locations associated with the // same image. // PALIGNMENT_FAULT_LOCATION Next; // // Offset of the PC address within the image. // ULONG_PTR OffsetFromBase; // // Number of alignment faults taken at this location. // ULONG Count; } ALIGNMENT_FAULT_LOCATION; // // The maximum number of individual alignment fault locations that will be // tracked. // #define MAX_FAULT_LOCATIONS 2048 #define MAX_FAULT_IMAGES 128 ALIGNMENT_FAULT_LOCATION KiAlignmentFaultLocations[ MAX_FAULT_LOCATIONS ]; ULONG KiAlignmentFaultLocationCount = 0; ALIGNMENT_FAULT_IMAGE KiAlignmentFaultImages[ MAX_FAULT_IMAGES ]; ULONG KiAlignmentFaultImageCount = 0; KSPIN_LOCK KipGlobalAlignmentDatabaseLock; VOID KiCopyLastPathElement( IN PUNICODE_STRING Source, IN OUT PULONG StringBufferLen, OUT PCHAR StringBuffer, IN KPROCESSOR_MODE PreviousMode ); PALIGNMENT_FAULT_IMAGE KiFindAlignmentFaultImage( IN PCHAR ImageName ); PLDR_DATA_TABLE_ENTRY KiFindLoaderDataTableEntry( IN PLIST_ENTRY ListHead, IN PVOID ProgramCounter, IN KPROCESSOR_MODE PreviousMode ); BOOLEAN KiIncrementLocationAlignmentFault( IN PALIGNMENT_FAULT_IMAGE FaultImage, IN ULONG_PTR OffsetFromBase ); BOOLEAN KiGetLdrDataTableInformation( IN PVOID ProgramCounter, IN KPROCESSOR_MODE PreviousMode, IN OUT PULONG ImageNameBufferLength, OUT PCHAR ImageNameBuffer, OUT PVOID *ImageBase ) /*++ Routine Description: This routine returns the name of the image that contains the supplied address. Arguments: ProgramCounter - Supplies the address for which we would like the name of the containing image. PreviousMode - Indicates whether the module is a user or kernel image. ImageNameBufferLength - Supplies a pointer to a buffer length value. On entry, this value represents the maximum length of StringBuffer. On exit, the value is set to the actual number of characters stored. ImageNameBuffer - Supplies a pointer to the output ANSI string into which the module name will be placed. This string will not be null terminated. ImageBase - Supplies a pointer to a location into which the base address of the located image is placed. Return Value: Returns TRUE if a module was located and its name copied to ImageNameBuffer, or FALSE otherwise. --*/ { PLIST_ENTRY head; PPEB peb; PLDR_DATA_TABLE_ENTRY tableEntry; BOOLEAN status; // // Since we may be poking around in user space, be sure to recover // gracefully from any exceptions thrown. // try { // // Choose the appropriate module list based on whether the fault // occured in user- or kernel-space. // if (PreviousMode == KernelMode) { head = &PsLoadedModuleList; } else { peb = PsGetCurrentProcess()->Peb; head = &peb->Ldr->InLoadOrderModuleList; } tableEntry = KiFindLoaderDataTableEntry( head, ProgramCounter, PreviousMode ); if (tableEntry != NULL) { // // The module of interest was located. Copy its name and // base address to the output paramters. // KiCopyLastPathElement( &tableEntry->BaseDllName, ImageNameBufferLength, ImageNameBuffer, PreviousMode ); *ImageBase = tableEntry->DllBase; status = TRUE; } else { // // A module containing the supplied program counter could not be // found. // status = FALSE; } } except(ExSystemExceptionFilter()) { status = FALSE; } return status; } PLDR_DATA_TABLE_ENTRY KiFindLoaderDataTableEntry( IN PLIST_ENTRY ListHead, IN PVOID ProgramCounter, IN KPROCESSOR_MODE PreviousMode ) /*++ Routine Description: This is a support routine for KiGetLdrDataTableInformation. Its purpose is to search a LDR_DATA_TABLE_ENTRY list, looking for a module that contains the supplied program counter. Arguments: ListHead - Supplies a pointer to the LIST_ENTRY that represents the head of the LDR_DATA_TABLE_ENTRY list to search. ProgramCounter - Supplies the code location of the faulting instruction. Return Value: Returns a pointer to the matching LDR_DATA_TABLE_ENTRY structure, or NULL if no match is found. --*/ { ULONG nodeNumber; PLIST_ENTRY next; PLDR_DATA_TABLE_ENTRY ldrDataTableEntry; ULONG_PTR imageStart; ULONG_PTR imageEnd; // // Walk the user- or kernel-mode module list. It is up to the caller // to capture any exceptions as a result of the lists being corrupt. // nodeNumber = 0; next = ListHead; if (PreviousMode != KernelMode) { ProbeForReadSmallStructure( next, sizeof(LIST_ENTRY), PROBE_ALIGNMENT(LIST_ENTRY) ); } while (TRUE) { nodeNumber += 1; next = next->Flink; if (next == ListHead || nodeNumber > 10000) { // // The end of the module list has been reached, or the // list has been corrupted with a cycle. Indicate that // no matching module could be located. // ldrDataTableEntry = NULL; break; } ldrDataTableEntry = CONTAINING_RECORD( next, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks ); if (PreviousMode != KernelMode) { ProbeForReadSmallStructure( ldrDataTableEntry, sizeof(LDR_DATA_TABLE_ENTRY), PROBE_ALIGNMENT(LDR_DATA_TABLE_ENTRY) ); } imageStart = (ULONG_PTR)ldrDataTableEntry->DllBase; if (imageStart > (ULONG_PTR)ProgramCounter) { // // The start of this module is past the program counter, // keep looking. // continue; } imageEnd = imageStart + ldrDataTableEntry->SizeOfImage; if (imageEnd > (ULONG_PTR)ProgramCounter) { // // Found a match. // break; } } return ldrDataTableEntry; } VOID KiCopyLastPathElement( IN PUNICODE_STRING Source, IN OUT PULONG StringBufferLen, OUT PCHAR StringBuffer, IN KPROCESSOR_MODE PreviousMode ) /*++ Routine Description: This routine locates the last path element of the path name represented by Source and copies it to StringBuffer. Arguments: Source - Supplies a pointer to the source UNICODE_STRING path. StringBufferLen - Supplies a pointer to a buffer length value. On entry, this value represents the maximum length of StringBuffer. On exit, the value is set to the actual number of characters stored. StringBuffer - Supplies a pointer to the output string buffer that is to contain the last path element. This string is not null terminated. PreviousMode - Previous mode of the caller for use in probing Return Value: None. --*/ { PWCHAR src, srcBase; PCHAR dst; USHORT charCount; ULONG srcBaseLength; // // The name of the module containing the specified address is at // ldrDataTableEntry->BaseDllName. It might contain just the name, // or it might contain the whole path. // // Start at the end of the module path and work back until one // of the following is encountered: // // - ModuleName->MaximumLength characters // - the beginning of the module path string // - a path seperator // srcBase = Source->Buffer; srcBaseLength = Source->Length; if (PreviousMode != KernelMode) { ProbeForRead (srcBase, srcBaseLength, sizeof (WCHAR)); } charCount = (USHORT)(srcBaseLength / sizeof(WCHAR)); src = &srcBase[ charCount ]; charCount = 0; while (TRUE) { if (charCount >= *StringBufferLen) { break; } if (src == srcBase) { break; } if (*(src-1) == L'\\') { break; } src--; charCount++; } // // Now copy the characters into the output string. We do our own // ansi-to-unicode conversion because the NLS routines cannot be // called at raised IRQL. // dst = StringBuffer; *StringBufferLen = charCount; while (charCount > 0) { *dst++ = (CHAR)(*src++); charCount--; } } BOOLEAN KiNewGlobalAlignmentFault( IN PVOID ProgramCounter, IN KPROCESSOR_MODE PreviousMode, OUT PALIGNMENT_FAULT_IMAGE *AlignmentFaultImage ) /*++ Routine Description: This routine looks for an existing alignment fault in the global fault database. A new record is created if a match could not be found. The count is incremented, and a pointer to the associated image record is returned. Arguments: ProgramCounter - Supplies the code location of the faulting instruction. PreviousMode - Supplies the execution mode at the time of the fault. AlignmentFaultImage - Supplies a location into which the pointer to the associated ALIGNMENT_FAULT_IMAGE structure is placed. Return Value: TRUE if an existing alignment fault match was not found, FALSE otherwise. --*/ { ULONG_PTR imageOffset; CHAR imageNameBuffer[ MAX_IMAGE_NAME_CHARS + 1 ]; ULONG imageNameBufferLength; PCHAR imageName; PALIGNMENT_FAULT_IMAGE alignmentFaultImage; BOOLEAN newFault; BOOLEAN foundLdrDataInfo; PVOID imageBase; KIRQL oldIrql; imageNameBufferLength = MAX_IMAGE_NAME_CHARS; foundLdrDataInfo = KiGetLdrDataTableInformation( ProgramCounter, PreviousMode, &imageNameBufferLength, imageNameBuffer, &imageBase ); if (foundLdrDataInfo == FALSE) { // // Couldn't find an image for this program counter. // imageBase = NULL; imageName = "Unavailable"; } else { imageNameBuffer[ imageNameBufferLength ] = '\0'; imageName = imageNameBuffer; } // // Acquire the spinlock at synch level so that we can handle exceptions // from ISRs // imageOffset = (ULONG_PTR)ProgramCounter - (ULONG_PTR)imageBase; oldIrql = KeAcquireSpinLockRaiseToSynch( &KipGlobalAlignmentDatabaseLock ); alignmentFaultImage = KiFindAlignmentFaultImage( imageName ); if (alignmentFaultImage == NULL) { // // Image table must be full // newFault = FALSE; } else { newFault = KiIncrementLocationAlignmentFault( alignmentFaultImage, imageOffset ); } KeReleaseSpinLock( &KipGlobalAlignmentDatabaseLock, oldIrql ); *AlignmentFaultImage = alignmentFaultImage; return newFault; } BOOLEAN KiIncrementLocationAlignmentFault( IN PALIGNMENT_FAULT_IMAGE FaultImage, IN ULONG_PTR OffsetFromBase ) /*++ Routine Description: This is a support routine for KiNewGlobalAligmentFault. Its purpose is to find or create an alignment fault record once the appropriate alignment fault image has been found or created. Arguments: FaultImage - Supplies a pointer to the ALIGNMENT_FAULT_IMAGE associated with this alignment fault. OffsetFromBase - Supplies the image offset within the image of the faulting instruction. Return Value: TRUE if an existing alignment fault match was not found, FALSE otherwise. --*/ { PALIGNMENT_FAULT_LOCATION faultLocation; // // Walk the location table, looking for a match. // faultLocation = FaultImage->LocationHead; while (faultLocation != NULL) { if (faultLocation->OffsetFromBase == OffsetFromBase) { faultLocation->Count++; return FALSE; } faultLocation = faultLocation->Next; } // // Could not find a match. Build a new alignment fault record. // if (KiAlignmentFaultLocationCount >= MAX_FAULT_LOCATIONS) { // // Table is full. Indicate that this is not a new alignment fault. // return FALSE; } faultLocation = &KiAlignmentFaultLocations[ KiAlignmentFaultLocationCount ]; faultLocation->Image = FaultImage; faultLocation->Next = FaultImage->LocationHead; faultLocation->OffsetFromBase = OffsetFromBase; faultLocation->Count = 1; FaultImage->LocationHead = faultLocation; FaultImage->Instances += 1; KiAlignmentFaultLocationCount++; return TRUE; } PALIGNMENT_FAULT_IMAGE KiFindAlignmentFaultImage( IN PCHAR ImageName ) /*++ Routine Description: This is a support routine for KiNewGlobalAlignmentFault. Its purpose is to walk the global ALIGNMENT_FAULT_IMAGE list looking for an image name that matches ImageName. If none is found, a new image record is created and inserted into the list. Arguments: ImageName - Supplies a pointer to the ANSI image name. Return Value: Returns a pointer to the matching ALIGNMENT_FAULT_IMAGE structure. --*/ { PALIGNMENT_FAULT_IMAGE faultImage; PALIGNMENT_FAULT_IMAGE lastImage; if (ImageName == NULL || *ImageName == '\0') { // // No image name was supplied. // return NULL; } // // Walk the image table, looking for a match. // faultImage = &KiAlignmentFaultImages[ 0 ]; lastImage = &KiAlignmentFaultImages[ KiAlignmentFaultImageCount ]; while (faultImage < lastImage) { if (strcmp(ImageName, faultImage->Name) == 0) { // // Found it. // faultImage->Count += 1; return faultImage; } faultImage += 1; } // // Create a new fault image if there's room // if (KiAlignmentFaultImageCount >= MAX_FAULT_IMAGES) { // // Table is full up. // return NULL; } KiAlignmentFaultImageCount += 1; // // Zero the image record. The records start out zero-initialized, this // is in case KiAlignmentFaultImageCount was manually reset to zero via // the debugger. // RtlZeroMemory( faultImage, sizeof(ALIGNMENT_FAULT_IMAGE) ); faultImage->Count = 1; strcpy( faultImage->Name, ImageName ); return faultImage; } #endif // DBG
import { Uint64LE } from 'int64-buffer' import { OutPacketBase } from 'packets/out/packet' /** * tells an user to join a host's match * @class OutHostJoinHost */ export class OutHostJoinHost { public static build(hostUserId: number, outPacket: OutPacketBase): void { outPacket.writeUInt32(hostUserId) outPacket.writeUInt64(new Uint64LE(0)) // unk00 } }
<reponame>phillipahereza/mattermost-server<gh_stars>1000+ // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. package plugin import ( "bufio" "errors" "net" "net/http" "net/rpc" "time" ) const ( hijackedConnReadBufSize = 4096 ) var ( ErrNotHijacked = errors.New("response is not hijacked") ErrAlreadyHijacked = errors.New("response was already hijacked") ErrCannotHijack = errors.New("response cannot be hijacked") ) func (w *httpResponseWriterRPCServer) HjConnRWRead(b []byte, reply *[]byte) error { if w.hjr == nil { return ErrNotHijacked } data := make([]byte, len(b)) n, err := w.hjr.bufrw.Read(data) if err != nil { return err } *reply = data[:n] return nil } func (w *httpResponseWriterRPCServer) HjConnRWWrite(b []byte, reply *int) error { if w.hjr == nil { return ErrNotHijacked } n, err := w.hjr.bufrw.Write(b) if err != nil { return err } *reply = n return nil } func (w *httpResponseWriterRPCServer) HjConnRead(size int, reply *[]byte) error { if w.hjr == nil { return ErrNotHijacked } if len(w.hjr.readBuf) < size { w.hjr.readBuf = make([]byte, size) } n, err := w.hjr.conn.Read(w.hjr.readBuf[:size]) if err != nil { return err } *reply = w.hjr.readBuf[:n] return nil } func (w *httpResponseWriterRPCServer) HjConnWrite(b []byte, reply *int) error { if w.hjr == nil { return ErrNotHijacked } n, err := w.hjr.conn.Write(b) if err != nil { return err } *reply = n return nil } func (w *httpResponseWriterRPCServer) HjConnClose(args struct{}, reply *struct{}) error { if w.hjr == nil { return ErrNotHijacked } return w.hjr.conn.Close() } func (w *httpResponseWriterRPCServer) HjConnSetDeadline(t time.Time, reply *struct{}) error { if w.hjr == nil { return ErrNotHijacked } return w.hjr.conn.SetDeadline(t) } func (w *httpResponseWriterRPCServer) HjConnSetReadDeadline(t time.Time, reply *struct{}) error { if w.hjr == nil { return ErrNotHijacked } return w.hjr.conn.SetReadDeadline(t) } func (w *httpResponseWriterRPCServer) HjConnSetWriteDeadline(t time.Time, reply *struct{}) error { if w.hjr == nil { return ErrNotHijacked } return w.hjr.conn.SetWriteDeadline(t) } func (w *httpResponseWriterRPCServer) HijackResponse(args struct{}, reply *struct{}) error { if w.hjr != nil { return ErrAlreadyHijacked } hj, ok := w.w.(http.Hijacker) if !ok { return ErrCannotHijack } conn, bufrw, err := hj.Hijack() if err != nil { return err } w.hjr = &hijackedResponse{ conn: conn, bufrw: bufrw, readBuf: make([]byte, hijackedConnReadBufSize), } return nil } type hijackedConn struct { client *rpc.Client } type hijackedConnRW struct { client *rpc.Client } func (w *hijackedConnRW) Read(b []byte) (int, error) { var data []byte if err := w.client.Call("Plugin.HjConnRWRead", b, &data); err != nil { return 0, err } copy(b, data) return len(data), nil } func (w *hijackedConnRW) Write(b []byte) (int, error) { var n int if err := w.client.Call("Plugin.HjConnRWWrite", b, &n); err != nil { return 0, err } return n, nil } func (w *hijackedConn) Read(b []byte) (int, error) { var data []byte if err := w.client.Call("Plugin.HjConnRead", len(b), &data); err != nil { return 0, err } copy(b, data) return len(data), nil } func (w *hijackedConn) Write(b []byte) (int, error) { var n int if err := w.client.Call("Plugin.HjConnWrite", b, &n); err != nil { return 0, err } return n, nil } func (w *hijackedConn) Close() error { return w.client.Call("Plugin.HjConnClose", struct{}{}, nil) } func (w *hijackedConn) LocalAddr() net.Addr { return nil } func (w *hijackedConn) RemoteAddr() net.Addr { return nil } func (w *hijackedConn) SetDeadline(t time.Time) error { return w.client.Call("Plugin.HjConnSetDeadline", t, nil) } func (w *hijackedConn) SetReadDeadline(t time.Time) error { return w.client.Call("Plugin.HjConnSetReadDeadline", t, nil) } func (w *hijackedConn) SetWriteDeadline(t time.Time) error { return w.client.Call("Plugin.HjConnSetWriteDeadline", t, nil) } func (w *httpResponseWriterRPCClient) Hijack() (net.Conn, *bufio.ReadWriter, error) { c := &hijackedConn{ client: w.client, } rw := &hijackedConnRW{ client: w.client, } if err := w.client.Call("Plugin.HijackResponse", struct{}{}, nil); err != nil { return nil, nil, err } return c, bufio.NewReadWriter(bufio.NewReader(rw), bufio.NewWriter(rw)), nil }
#include<stdio.h> int main( ) { int a,b,d[10],i,c,u,v,h,m; scanf("%d %d",&a,&b); for(i=0;i<10;i++) { d[i]=0; } for(i=a;i<=b;i++) { m=i; while(m>0) { c=m%10; d[c]++; m=m/10; } } v=d[2]+d[3]+d[5]; u=d[6]+d[9]+d[0]; h=(v*5)+(u*6)+(d[1]*2)+(d[4]*4)+(d[7]*3)+(d[8]*7); printf("%d\n",h); return 0; }
/* * Copyright (C) 2021 Google LLC * * 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 com.google.cloud.dataproc.templates.word; import static com.google.cloud.dataproc.templates.util.TemplateConstants.WORD_COUNT_INPUT_FORMAT_PROP; import static com.google.cloud.dataproc.templates.util.TemplateConstants.WORD_COUNT_INPUT_PATH_PROP; import static com.google.cloud.dataproc.templates.util.TemplateConstants.WORD_COUNT_OUTPUT_PATH_PROP; import com.google.cloud.dataproc.templates.BaseTemplate; import java.util.Arrays; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.Tuple2; public class WordCount implements BaseTemplate { private static final Logger LOGGER = LoggerFactory.getLogger(WordCount.class); @Override public void runTemplate() { String inputPath = getProperties().getProperty(WORD_COUNT_INPUT_PATH_PROP); String outputPath = getProperties().getProperty(WORD_COUNT_OUTPUT_PATH_PROP); String format = getProperties().getProperty(WORD_COUNT_INPUT_FORMAT_PROP, "text"); LOGGER.info("Starting word count spark job, inputPath:{},outputPath:{}", inputPath, outputPath); JavaSparkContext sparkContext = new JavaSparkContext(new SparkConf().setAppName("Word Count")); JavaRDD<String> lines = sparkContext.textFile(inputPath); JavaRDD<String> words = lines.flatMap((String line) -> Arrays.asList(line.split(" ")).iterator()); JavaPairRDD<String, Integer> wordCounts = words .mapToPair((String word) -> new Tuple2<>(word, 1)) .reduceByKey((Integer count1, Integer count2) -> count1 + count2); wordCounts.saveAsTextFile(outputPath); wordCounts.saveAsTextFile(outputPath); } }
<filename>src/main/java/org/joelson/mattias/turfgame/statistics/Statistics.java package org.joelson.mattias.turfgame.statistics; import java.io.Serializable; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Objects; import java.util.Set; public class Statistics implements Serializable { private static final long serialVersionUID = 1L; private final Set<Country> countries; private final Set<Region> regions; private final Set<Municipality> municipalities; private final Set<Zone> zones; private final Set<Round> rounds; private final Set<User> users; private final Set<Visits> visits; public Statistics() { countries = new HashSet<>(); regions = new HashSet<>(); municipalities = new HashSet<>(); zones = new HashSet<>(); rounds = new HashSet<>(); users = new HashSet<>(); visits = new HashSet<>(); } public boolean addCountry(Country country) { return countries.add(Objects.requireNonNull(country)); } public Set<Country> getCountries() { return Collections.unmodifiableSet(countries); } public boolean addRegion(Region region) { return regions.add(Objects.requireNonNull(region)); } public Set<Region> getRegions() { return Collections.unmodifiableSet(regions); } public boolean addMunicipality(Municipality municipality) { return municipalities.add(Objects.requireNonNull(municipality)); } public Municipality getMunicipality(String name) { for (Municipality municipality : municipalities) { if (municipality.getName().equals(name)) { return municipality; } } return null; } public boolean addZone(Zone zone) { return zones.add(Objects.requireNonNull(zone)); } public Zone getZone(String name) { for (Zone zone : zones) { if (zone.getName().equals(name)) { return zone; } } return null; } public boolean addRound(Round round) { return rounds.add(Objects.requireNonNull(round)); } public Round getRound(int id) { for (Round round : rounds) { if (round.getId() == id) { return round; } } return null; } public boolean addUser(User user) { return users.add(Objects.requireNonNull(user)); } public User getUser(String name) { for (User user : users) { if (user.getName().equals(name)) { return user; } } return null; } public boolean addVisits(Visits visits) { if (this.visits.stream() .anyMatch(v -> v.getZone().equals(visits.getZone()) && v.getUser().equals(visits.getUser()) && v.getRound().equals(visits.getRound()))) { return false; } return this.visits.add(visits); } @Override public String toString() { return "Statistics{countries:" + countries + ",regions:" + regions + ",municipalities:" + municipalities + ",zones:" + zones + ",rounds:" + rounds + ",users:" + users + ",visits:" + visits + '}'; } public void importRegions(List<org.joelson.mattias.turfgame.apiv4.Region> regions) { for (org.joelson.mattias.turfgame.apiv4.Region region : regions) { String countryName = region.getCountry(); if (countryName == null) { countryName = getCountryCode(region.getName()); } Country country = findOrAddCountry(countryName); findOrAddRegion(country, region.getId(), region.getName()); } } private static String getCountryCode(String name) { /*for (String iso : Locale.getISOCountries()) { Locale l = new Locale("", iso); if (l.getDisplayCountry().equals(name)) { return iso; } }*/ for (Locale locale : Locale.getAvailableLocales()) { if (locale.getDisplayCountry().equals(name)) { return locale.getISO3Country(); } } return "-1"; } private Country findOrAddCountry(String name) { for (Country country : countries) { if (country.getName().equals(name)) { return country; } } Country country = new Country(name); addCountry(country); return country; } private Region findOrAddRegion(Country country, int id, String name) { for (Region region : regions) { boolean issueRegion = false; if (region.getName().equals(name)) { if (region.getId() == id) { throw new IllegalStateException("Region '" + name + "' has id " + id + " - the same as " + region); } if (!country.equals(region.getCountry())) { // is OK if belonging to different countries } else if (!name.equals("Argentina") && !name.equals("Kenya") && !name.equals("Utah") && !name.equals("template")) { // https://issues.turfgame.com/view/8013 throw new IllegalStateException("Region '" + name + "' has both id " + region.getId() + " and " + id + '!'); } } } Region region = new Region(id, name, country); addRegion(region); return region; } }
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ #ifndef __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__ #define __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__ #include "juce_AudioSource.h" //============================================================================== /** An AudioSource that mixes together the output of a set of other AudioSources. Input sources can be added and removed while the mixer is running as long as their prepareToPlay() and releaseResources() methods are called before and after adding them to the mixer. */ class JUCE_API MixerAudioSource : public AudioSource { public: //============================================================================== /** Creates a MixerAudioSource. */ MixerAudioSource(); /** Destructor. */ ~MixerAudioSource(); //============================================================================== /** Adds an input source to the mixer. If the mixer is running you'll need to make sure that the input source is ready to play by calling its prepareToPlay() method before adding it. If the mixer is stopped, then its input sources will be automatically prepared when the mixer's prepareToPlay() method is called. @param newInput the source to add to the mixer @param deleteWhenRemoved if true, then this source will be deleted when no longer needed by the mixer. */ void addInputSource (AudioSource* newInput, bool deleteWhenRemoved); /** Removes an input source. If the source was added by calling addInputSource() with the deleteWhenRemoved flag set, it will be deleted by this method. */ void removeInputSource (AudioSource* input); /** Removes all the input sources. Any sources which were added by calling addInputSource() with the deleteWhenRemoved flag set will be deleted by this method. */ void removeAllInputs(); //============================================================================== /** Implementation of the AudioSource method. This will call prepareToPlay() on all its input sources. */ void prepareToPlay (int samplesPerBlockExpected, double sampleRate); /** Implementation of the AudioSource method. This will call releaseResources() on all its input sources. */ void releaseResources(); /** Implementation of the AudioSource method. */ void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill); private: //============================================================================== Array <AudioSource*> inputs; BigInteger inputsToDelete; CriticalSection lock; AudioSampleBuffer tempBuffer; double currentSampleRate; int bufferSizeExpected; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MixerAudioSource); }; #endif // __JUCE_MIXERAUDIOSOURCE_JUCEHEADER__
JAISALMER: There are 436 villages in Jaisalmer where crimes do not take place. In last three years, not a single crime has been reported in these villages. Adjoining the 477-km long border with Pakistan, these villages have a population of around 3 lakh and are an example of peace and harmony.Jaisalmer is the only district in state having the highest number of villages where the crime rate is zero. To make these villages aspirational, police have sent a recommendation to the state government asking for special packages for the development of these villages.The aim of the initiative is to increase the number of crime-free villages in the times to come.At these villages, police literally have no work to do.According to information, people here even today reside as per tradition and generally are of the same community due to which there is no dispute and people resolve the issues amongst themselves.SP Rajiv Pachar said out of 16 police stations in Jaisalmer, 15 police stations have jurisdiction of 436 villages where the crime rate is zero. Among them are 15 villages under Ramdeora police station, 11 villages in Lathi, 18 in Nokha, 38 in Sankada, 58 in Phalsoon, 33 in Khuhadi, 28 in Nachna, 20 in Ramgarh, 19 in Jhinjhiyali, 88 in Shahgarh, 14 in Pokhran, 29 in Jaisalmer Sadar, 9 in Sangad, 38 in Mohangarh and 18 in Sam. Notably, no crime case has been lodged in Sam area in the last three years.He added that the state government has made a plan to give special package to these villages.Recently at the SP-collector conference, this issue was raised and government has decided to felicitate such villages. The SP said that Jaisalmer leads the country in the number of crime-free villages. Out of 840 villages in Jaisalmer, 436 are crime free.He said that development work will take place in these villages through MLA and MP funds. Besides, all requirements of these villages will be taken up on priority basis.
/// Compute the min and max for each column. Actually compute the min and /// max of each attribute and write out a new metadata file for the data /// partition. void ibis::part::computeMinMax() { for (columnList::iterator it=columns.begin(); it!=columns.end(); ++it) { (*it).second->computeMinMax(); } if (activeDir == 0) return; writeLock lock(this, "computeMinMax"); writeMetaData(nEvents, columns, activeDir); Stat_T tmp; if (backupDir != 0 && *backupDir != 0) { if (UnixStat(backupDir, &tmp) == 0) { if ((tmp.st_mode&S_IFDIR) == S_IFDIR) writeMetaData(nEvents, columns, backupDir); } } }
def import_chem_wizard(cls, name, temp, type): gxapi_cy.WrapGUI._import_chem_wizard(GXContext._get_tls_geo(), name.encode(), temp.encode(), type)
<filename>cmd/remove.go package cmd import ( "os" "path/filepath" "github.com/absfs/afero" "github.com/spf13/cobra" ) var removeCommand = &cobra.Command{ Use: "remove", Aliases: []string{"rm"}, Args: cobra.MinimumNArgs(1), Short: "Remove a file or directory", RunE: makeRunE(runRemoveCommandE), } func init() { rootCommand.AddCommand(removeCommand) } func runRemoveCommandE(fs afero.Fs, command *cobra.Command, args []string) error { targetState, err := config.getTargetState(fs) if err != nil { return err } sourceNames, err := config.getSourceNames(targetState, args) if err != nil { return err } actuator := config.getDefaultActuator(fs) for i, targetFileName := range args { if err := actuator.RemoveAll(filepath.Join(config.TargetDir, targetFileName)); err != nil && !os.IsNotExist(err) { return err } if err := actuator.RemoveAll(filepath.Join(config.SourceDir, sourceNames[i])); err != nil && !os.IsNotExist(err) { return err } } return nil }
<filename>herder/herder.go package herder import ( "encoding/json" "fmt" "html/template" "net/http" "github.com/Webstrates/golem-herder/golem" "github.com/gorilla/mux" "github.com/spf13/viper" ) // TemplateContext is the context which gets used when constructing the emet js init file type TemplateContext struct { ID string BaseURL string } // HomeHandler will serve the js emet init file func HomeHandler(w http.ResponseWriter, r *http.Request) { tmpl, err := template.ParseFiles("emet.tmpl.js") if err != nil { http.Error(w, err.Error(), 500) } context := TemplateContext{BaseURL: viper.GetString("url")} err = tmpl.Execute(w, context) } // ListHandler shows the running golems func ListHandler(w http.ResponseWriter, r *http.Request) { golems, err := golem.List() data, err := json.Marshal(golems) if err != nil { http.Error(w, err.Error(), 500) } w.Write(data) } // SpawnHandler will spawn a new golem for the webstrate given by the mux.Vars func SpawnHandler(w http.ResponseWriter, r *http.Request) { // we need id for webstrate vars := mux.Vars(r) wsid := vars["webstrate"] containerID, err := golem.Spawn(wsid) if err != nil { http.Error(w, err.Error(), 500) return } w.Write([]byte(fmt.Sprintf("%s lumbering along", containerID))) } // ResetHandler will reset/reload the golem on the given webstrate func ResetHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) wsid := vars["webstrate"] containerID, err := golem.Restart(wsid) if err != nil { http.Error(w, err.Error(), 500) return } w.Write([]byte(fmt.Sprintf("Reset done - new container %s", containerID))) } // KillHandler will kill the golem func KillHandler(w http.ResponseWriter, r *http.Request) { // kill, kill, kill vars := mux.Vars(r) wsid := vars["webstrate"] err := golem.Kill(wsid) if err != nil { http.Error(w, err.Error(), 500) return } w.Write([]byte(fmt.Sprintf("Golem for %s is no more", wsid))) }
import React, { useState, useCallback, useContext, useMemo } from 'react'; import { _cs, isDefined, doesObjectHaveNoData, } from '@togglecorp/fujs'; import MapStyleContext, { MapStyle } from '#components/LayerContext'; import LayerSwitcher from '#components/LayerSwitcher'; import TextOutput from '#components/TextOutput'; import Map from '#re-map'; import MapContainer from '#re-map/MapContainer'; import MapBounds from '#re-map/MapBounds'; import MapSource from '#re-map/MapSource'; import MapLayer from '#re-map/MapSource/MapLayer'; import MapTooltip from '#re-map/MapTooltip'; import { Bounds, ShapeType, ConflictElement, ResolutionStatus, ElementGeoJSON, } from '#constants/types'; import { createRequestClient, methods, NewProps, ClientAttributes, } from '#request'; import styles from './styles.scss'; import { tooltipOptions, sourceOptions, areaFillLayerOptions, areaOutlineLayerOptions, linePointOptions, lineLayerOptions, pointLayerOptions, legendItems, } from './mapTheme'; interface Region { tags: { [key: string]: string | undefined; }; } interface ClickedRegion { feature: GeoJSON.Feature<GeoJSON.Polygon, Region>; lngLat: mapboxgl.LngLatLike; } function getShapeType(geoJson: ElementGeoJSON): ShapeType { const { geometry: { type } } = geoJson; if (type === 'Point' || type === 'MultiPoint') { return 'point'; } if (type === 'LineString' || type === 'MultiLineString') { return 'line'; } if (type === 'Polygon' || type === 'MultiPolygon') { return 'area'; } return 'point'; } interface ConflictsResponse { results: ConflictElement[]; } function getFeatures( conflictElements: ConflictElement[], status: ResolutionStatus, overwriteStatus: string, ) { const filteredConflictElements = conflictElements .filter(element => element.status === status); function getGeoJson(element: ConflictElement, finalOverwriteStatus: string) { const geoJson = element.localGeojson && !doesObjectHaveNoData(element.localGeojson) ? element.localGeojson : element.originalGeojson; return { ...geoJson, properties: { ...geoJson.properties, resolution: finalOverwriteStatus, }, }; } const points: ElementGeoJSON[] = filteredConflictElements .filter(element => getShapeType(element.originalGeojson) === 'point') .map(element => getGeoJson(element, overwriteStatus)); const lines: ElementGeoJSON[] = filteredConflictElements .filter(element => getShapeType(element.originalGeojson) === 'line') .map(element => getGeoJson(element, overwriteStatus)); const areas: ElementGeoJSON[] = filteredConflictElements .filter(element => getShapeType(element.originalGeojson) === 'area') .map(element => getGeoJson(element, overwriteStatus)); return [points, lines, areas]; } const getSeggregatedGeojsonsForConflicts = ( resolved: ConflictsResponse, partiallyResolved: ConflictsResponse, unresolved: ConflictsResponse, ) => { const pointFeatures: ElementGeoJSON[] = []; const lineFeatures: ElementGeoJSON[] = []; const areaFeatures: ElementGeoJSON[] = []; if (isDefined(resolved?.results)) { const [points, lines, areas] = getFeatures(resolved.results, 'resolved', 'resolved'); pointFeatures.push(...points); lineFeatures.push(...lines); areaFeatures.push(...areas); } if (isDefined(partiallyResolved?.results)) { const [points, lines, areas] = getFeatures( partiallyResolved.results, 'partially_resolved', 'partially_resolved', ); pointFeatures.push(...points); lineFeatures.push(...lines); areaFeatures.push(...areas); } if (isDefined(unresolved?.results)) { const [points, lines, areas] = getFeatures( unresolved.results, 'unresolved', 'unresolved', ); pointFeatures.push(...points); lineFeatures.push(...lines); areaFeatures.push(...areas); } return ({ pointGeojson: { type: 'FeatureCollection', features: pointFeatures, }, lineGeojson: { type: 'FeatureCollection', features: lineFeatures, }, areaGeojson: { type: 'FeatureCollection', features: areaFeatures, }, }); }; const getSeggregatedGeojsonsForAll = ( allElements: ConflictsResponse, ) => { const pointFeatures: ElementGeoJSON[] = []; const lineFeatures: ElementGeoJSON[] = []; const areaFeatures: ElementGeoJSON[] = []; if (isDefined(allElements?.results)) { const [points, lines, areas] = getFeatures( allElements.results, 'resolved', 'all', ); pointFeatures.push(...points); lineFeatures.push(...lines); areaFeatures.push(...areas); } return ({ pointGeojson: { type: 'FeatureCollection', features: pointFeatures, }, lineGeojson: { type: 'FeatureCollection', features: lineFeatures, }, areaGeojson: { type: 'FeatureCollection', features: areaFeatures, }, }); }; interface OwnProps { className?: string; totalResolvedElements?: number; totalPartiallyResolvedElements?: number; conflictsVisibility: boolean; allElementsVisibility: boolean; bounds?: Bounds; } interface Params { } const requestOptions: { [key: string]: ClientAttributes<OwnProps, Params> } = { unresolvedConflictsGet: { url: '/unresolved-elements/', method: methods.GET, onMount: ({ props }) => !!props.conflictsVisibility, onPropsChanged: { totalResolvedElements: ({ props, prevProps }) => ( props.conflictsVisibility && (props.totalResolvedElements !== prevProps.totalResolvedElements) ), totalPartiallyResolvedElements: ({ props, prevProps }) => ( props.conflictsVisibility && ( props.totalPartiallyResolvedElements !== prevProps.totalPartiallyResolvedElements ) ), }, }, partiallyResolvedConflictsGet: { url: '/partial-resolved-elements/', method: methods.GET, onMount: ({ props }) => !!props.conflictsVisibility, onPropsChanged: { totalResolvedElements: ({ props, prevProps }) => ( props.conflictsVisibility && (props.totalResolvedElements !== prevProps.totalResolvedElements) ), totalPartiallyResolvedElements: ({ props, prevProps }) => ( props.conflictsVisibility && ( props.totalPartiallyResolvedElements !== prevProps.totalPartiallyResolvedElements ) ), }, }, resolvedConflictsGet: { url: '/resolved-elements/', method: methods.GET, onMount: ({ props }) => !!props.conflictsVisibility, onPropsChanged: { totalResolvedElements: ({ props, prevProps }) => ( props.conflictsVisibility && (props.totalResolvedElements !== prevProps.totalResolvedElements) ), totalPartiallyResolvedElements: ({ props, prevProps }) => ( props.conflictsVisibility && ( props.totalPartiallyResolvedElements !== prevProps.totalPartiallyResolvedElements ) ), }, }, nonConflictedElementsGet: { url: '/all-changes/?state=no-conflicts', onMount: ({ props }) => !!props.allElementsVisibility, method: methods.GET, onPropsChanged: { allElementsVisibility: ({ props }) => props.allElementsVisibility, }, }, }; type Props = NewProps<OwnProps, Params>; function DashboardMap(props: Props) { const { bounds, className, requests: { unresolvedConflictsGet: { response: unresolvedConflictsResponse, }, resolvedConflictsGet: { response: resolvedConflictsResponse, }, partiallyResolvedConflictsGet: { response: partiallyResolvedConflictsResponse, }, nonConflictedElementsGet: { response: allElementsResponse, }, }, allElementsVisibility, conflictsVisibility, } = props; const { mapStyles } = useContext(MapStyleContext); const [selectedStyle, setSelectedStyle] = useState('Wikimedia'); const [ clickedRegionProperties, setClickedRegionProperties, ] = useState<ClickedRegion | undefined>(); const mapStyle = useMemo(() => { let style = mapStyles.find((item: MapStyle) => item.name === selectedStyle); if (style === undefined) { [style] = mapStyles; } return style; }, [selectedStyle, mapStyles]); const handleMapRegionClick = useCallback(( feature: mapboxgl.MapboxGeoJSONFeature, lngLat: mapboxgl.LngLat, ) => { const safeFeature = feature as unknown as GeoJSON.Feature<GeoJSON.Polygon, Region>; setClickedRegionProperties({ feature: { ...safeFeature, // FIXME: later properties: { ...safeFeature.properties, tags: JSON.parse(feature.properties.tags), }, }, lngLat, }); return true; }, [setClickedRegionProperties]); const handleTooltipClose = useCallback(() => { setClickedRegionProperties(undefined); }, [setClickedRegionProperties]); const mapOptions = useMemo(() => { if (!bounds) { return {}; } return { bounds, zoomLevel: 3, }; }, [bounds]); const popupTags = clickedRegionProperties?.feature.properties.tags; const { lineGeojson: lineGeojsonForConflicts, pointGeojson: pointGeojsonForConflicts, areaGeojson: areaGeojsonForConflicts, } = useMemo(() => getSeggregatedGeojsonsForConflicts( resolvedConflictsResponse as ConflictsResponse, partiallyResolvedConflictsResponse as ConflictsResponse, unresolvedConflictsResponse as ConflictsResponse, ), [ resolvedConflictsResponse, partiallyResolvedConflictsResponse, unresolvedConflictsResponse, ]); const { lineGeojson: lineGeojsonForAll, pointGeojson: pointGeojsonForAll, areaGeojson: areaGeojsonForAll, } = useMemo(() => getSeggregatedGeojsonsForAll( allElementsResponse as ConflictsResponse, ), [allElementsResponse]); return ( <Map mapStyle={mapStyle.data} mapOptions={mapOptions} scaleControlShown navControlShown > <MapBounds bounds={bounds} padding={50} /> <MapContainer className={_cs(styles.map, className)} /> {clickedRegionProperties && ( <MapTooltip coordinates={clickedRegionProperties.lngLat} tooltipOptions={tooltipOptions} onHide={handleTooltipClose} > <div> {popupTags && Object.keys(popupTags).map( key => ( <TextOutput key={key} label={key} labelClassName={styles.tooltipLabel} value={popupTags[key]} /> ), )} </div> </MapTooltip> )} {conflictsVisibility && areaGeojsonForConflicts && ( <MapSource sourceKey="area" geoJson={areaGeojsonForConflicts} sourceOptions={sourceOptions} > <MapLayer layerKey="fill-area" layerOptions={areaFillLayerOptions} onClick={handleMapRegionClick} /> <MapLayer layerKey="outline-area" layerOptions={areaOutlineLayerOptions} onClick={handleMapRegionClick} /> <MapLayer layerKey="circle-area" layerOptions={linePointOptions} onClick={handleMapRegionClick} /> </MapSource> )} {conflictsVisibility && lineGeojsonForConflicts && ( <MapSource sourceKey="line" geoJson={lineGeojsonForConflicts} sourceOptions={sourceOptions} > <MapLayer layerKey="outline-line" layerOptions={lineLayerOptions} onClick={handleMapRegionClick} /> <MapLayer layerKey="circle-line" layerOptions={linePointOptions} onClick={handleMapRegionClick} /> </MapSource> )} {conflictsVisibility && pointGeojsonForConflicts && ( <MapSource sourceKey="point" geoJson={pointGeojsonForConflicts} sourceOptions={sourceOptions} > <MapLayer layerKey="circle-point" layerOptions={pointLayerOptions} onClick={handleMapRegionClick} /> </MapSource> )} {allElementsVisibility && areaGeojsonForAll && ( <MapSource sourceKey="area-all" geoJson={areaGeojsonForAll} sourceOptions={sourceOptions} > <MapLayer layerKey="fill-area-all" layerOptions={areaFillLayerOptions} onClick={handleMapRegionClick} /> <MapLayer layerKey="outline-area-all" layerOptions={areaOutlineLayerOptions} onClick={handleMapRegionClick} /> <MapLayer layerKey="circle-area-all" layerOptions={linePointOptions} onClick={handleMapRegionClick} /> </MapSource> )} {allElementsVisibility && lineGeojsonForAll && ( <MapSource sourceKey="line-all" geoJson={lineGeojsonForAll} sourceOptions={sourceOptions} > <MapLayer layerKey="outline-line-all" layerOptions={lineLayerOptions} onClick={handleMapRegionClick} /> <MapLayer layerKey="circle-line-all" layerOptions={linePointOptions} onClick={handleMapRegionClick} /> </MapSource> )} {allElementsVisibility && pointGeojsonForAll && ( <MapSource sourceKey="point-all" geoJson={pointGeojsonForAll} sourceOptions={sourceOptions} > <MapLayer layerKey="circle-point-all" layerOptions={pointLayerOptions} onClick={handleMapRegionClick} /> </MapSource> )} {(allElementsVisibility || conflictsVisibility) && ( <div className={styles.legend}> {legendItems.map(legendItem => ( <div key={legendItem.title} className={styles.legendItem} > <span className={styles.legendColor} style={{ backgroundColor: legendItem.color }} /> <span> {legendItem.title} </span> </div> ))} </div> )} <LayerSwitcher className={styles.layerSwitcher} selected={selectedStyle} onSelectedLayerChange={setSelectedStyle} /> </Map> ); } export default createRequestClient(requestOptions)(DashboardMap);
/** * A reactive logout success handler for initiating OIDC logout through the user agent. * * @author Josh Cummings * @since 5.2 * @see <a href="https://openid.net/specs/openid-connect-session-1_0.html#RPLogout">RP-Initiated Logout</a> * @see org.springframework.security.web.server.authentication.logout.ServerLogoutSuccessHandler */ public class OidcClientInitiatedServerLogoutSuccessHandler implements ServerLogoutSuccessHandler { private final ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy(); private final RedirectServerLogoutSuccessHandler serverLogoutSuccessHandler = new RedirectServerLogoutSuccessHandler(); private final ReactiveClientRegistrationRepository clientRegistrationRepository; private String postLogoutRedirectUri; /** * Constructs an {@link OidcClientInitiatedServerLogoutSuccessHandler} with the provided parameters * * @param clientRegistrationRepository The {@link ReactiveClientRegistrationRepository} to use to derive * the end_session_endpoint value */ public OidcClientInitiatedServerLogoutSuccessHandler (ReactiveClientRegistrationRepository clientRegistrationRepository) { Assert.notNull(clientRegistrationRepository, "clientRegistrationRepository cannot be null"); this.clientRegistrationRepository = clientRegistrationRepository; } /** * {@inheritDoc} */ @Override public Mono<Void> onLogoutSuccess(WebFilterExchange exchange, Authentication authentication) { return Mono.just(authentication) .filter(OAuth2AuthenticationToken.class::isInstance) .filter(token -> authentication.getPrincipal() instanceof OidcUser) .map(OAuth2AuthenticationToken.class::cast) .map(OAuth2AuthenticationToken::getAuthorizedClientRegistrationId) .flatMap(this.clientRegistrationRepository::findByRegistrationId) .flatMap(clientRegistration -> { URI endSessionEndpoint = endSessionEndpoint(clientRegistration); if (endSessionEndpoint == null) { return Mono.empty(); } String idToken = idToken(authentication); URI postLogoutRedirectUri = postLogoutRedirectUri(exchange.getExchange().getRequest()); return Mono.just(endpointUri(endSessionEndpoint, idToken, postLogoutRedirectUri)); }) .switchIfEmpty(this.serverLogoutSuccessHandler .onLogoutSuccess(exchange, authentication).then(Mono.empty())) .flatMap(endpointUri -> this.redirectStrategy.sendRedirect(exchange.getExchange(), endpointUri)); } private URI endSessionEndpoint(ClientRegistration clientRegistration) { URI result = null; if (clientRegistration != null) { Object endSessionEndpoint = clientRegistration.getProviderDetails().getConfigurationMetadata() .get("end_session_endpoint"); if (endSessionEndpoint != null) { result = URI.create(endSessionEndpoint.toString()); } } return result; } private URI endpointUri(URI endSessionEndpoint, String idToken, URI postLogoutRedirectUri) { UriComponentsBuilder builder = UriComponentsBuilder.fromUri(endSessionEndpoint); builder.queryParam("id_token_hint", idToken); if (postLogoutRedirectUri != null) { builder.queryParam("post_logout_redirect_uri", postLogoutRedirectUri); } return builder.encode(StandardCharsets.UTF_8).build().toUri(); } private String idToken(Authentication authentication) { return ((OidcUser) authentication.getPrincipal()).getIdToken().getTokenValue(); } private URI postLogoutRedirectUri(ServerHttpRequest request) { if (this.postLogoutRedirectUri == null) { return null; } UriComponents uriComponents = UriComponentsBuilder.fromUri(request.getURI()) .replacePath(request.getPath().contextPath().value()) .replaceQuery(null) .fragment(null) .build(); return UriComponentsBuilder.fromUriString(this.postLogoutRedirectUri) .buildAndExpand(Collections.singletonMap("baseUrl", uriComponents.toUriString())) .toUri(); } /** * Set the post logout redirect uri to use * * @param postLogoutRedirectUri - A valid URL to which the OP should redirect after logging out the user * @deprecated {@link #setPostLogoutRedirectUri(String)} */ @Deprecated public void setPostLogoutRedirectUri(URI postLogoutRedirectUri) { Assert.notNull(postLogoutRedirectUri, "postLogoutRedirectUri cannot be empty"); this.postLogoutRedirectUri = postLogoutRedirectUri.toASCIIString(); } /** * Set the post logout redirect uri template to use. Supports the {@code "{baseUrl}"} * placeholder, for example: * * <pre> * handler.setPostLogoutRedirectUriTemplate("{baseUrl}"); * </pre> * * will make so that {@code post_logout_redirect_uri} will be set to the base url for the client * application. * * @param postLogoutRedirectUri - A template for creating the {@code post_logout_redirect_uri} * query parameter * @since 5.3 */ public void setPostLogoutRedirectUri(String postLogoutRedirectUri) { Assert.notNull(postLogoutRedirectUri, "postLogoutRedirectUri cannot be null"); this.postLogoutRedirectUri = postLogoutRedirectUri; } /** * The URL to redirect to after successfully logging out when not originally an OIDC login * * @param logoutSuccessUrl the url to redirect to. Default is "/login?logout". */ public void setLogoutSuccessUrl(URI logoutSuccessUrl) { Assert.notNull(logoutSuccessUrl, "logoutSuccessUrl cannot be null"); this.serverLogoutSuccessHandler.setLogoutSuccessUrl(logoutSuccessUrl); } }
import { Token } from '../../src/models/token'; import { TokenType } from '../../src/models/tokentypes'; export const createToken = <T extends TokenType>( type: T, lexeme: string, literal?: any, ): Token => { return new Token( type, lexeme, literal, { line: 0, character: 0, }, { line: 0, character: 1, }, 'file:///fake.ks', ); };
<filename>source/dawn/PlatformContextDawn.h // // Copyright (c) 2020 The Aquarium Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #ifndef PLATFORMCONTEXTDAWN_H #define PLATFORMCONTEXTDAWN_H #include "dawn/dawn_wsi.h" #include "../Aquarium.h" #include "ContextDawn.h" class PlatformContextDawn : public ContextDawn { public: explicit PlatformContextDawn(BACKENDTYPE backendType); ~PlatformContextDawn() override; private: DawnSwapChainImplementation *getSwapChainImplementation( wgpu::BackendType backendType) override; wgpu::TextureFormat getPreferredSwapChainTextureFormat( wgpu::BackendType backendType) override; DawnSwapChainImplementation mSwapchainImpl; }; #endif // PLATFORMCONTEXTDAWN_H
/** * Displays an item in the slot. * @param item The item, never {@code null}. */ private void asItem(final Item item) { item.getIcon() .ifPresent(this::installIcon); if (isShowTooltip()) { final ItemWrapper wrapper = new ItemWrapper(item, null); final ItemTooltipRenderer renderer = new ItemTooltipRenderer(); renderer.setItem(wrapper); final Tooltip tooltip = new Tooltip(); tooltip.setGraphic(renderer); this.tooltip.set(tooltip); } SABUIUtils.INSTANCE.updateRarityStyle(this, isShowRarity() ? item.getRarity() : null); }
Beef up your international deal-making skills. crossculture.com You can't expect negotiations with the French to be like negotiations with Americans, and the same holds true for every culture around the world. British linguist Richard D. Lewis charted communication patterns as well as leadership styles and cultural identities in his book, "When Cultures Collide," which is now in a third edition. His organization offers classes in cross-cultural communication for clients like Unilever and BMW. Although cultural generalizations can be overly reductive, Lewis, who speaks 10 languages, insists it can be done fairly. "Determining national characteristics is treading a minefield of inaccurate assessment and surprising exception. There is, however, such a thing as a national norm," he writes. Scroll down to see Lewis' insights on negotiating with people around the world.
/** * Guesses package and class name, and {@code %include} files, based on this grammar definition. * * @param lexFileReader reader for lex spec to process * @param lexFile the lex spec to process, used for relative path name resolution of {@code * %incude}s. * @return collected info about this lex spec. * @throws IOException when an IO exception occurred while processing the reader. Ignores IO * errors for {@code %incude} files. */ static SpecInfo guessSpecInfo(Reader lexFileReader, File lexFile) throws IOException { try (LineNumberReader reader = new LineNumberReader(lexFileReader)) { String className = null; String packageName = null; while (className == null || packageName == null) { String line = reader.readLine(); if (line == null) { break; } if (packageName == null) { packageName = guessPackage(line); } if (className == null) { className = guessClass(line); } } if (className == null) { className = DEFAULT_NAME; } return new SpecInfo(className, packageName, guessIncludes(lexFile)); } }
Samo jedan od navednih redosleda je tačna proporcija brojeva @numb[out[1]]@, @numb[out[2]]@, @numb[out[3]]@ i @numb[out[4]]@. Oboj kružić pored tačnog odgovora. @vspace@ @center@ @lib.check_one_option_radio(answ,ind, true)@
<reponame>sqall01/LSMS from typing import List class PasswdException(Exception): pass class SystemUser: def __init__(self, name: str, password: str, uid: int, gid: int, info: str, home: str, shell: str): self._name = name self._password = password self._uid = uid self._gid = gid self._info = info self._home = home self._shell = shell def __str__(self): return "%s:%s:%d:%d:%s:%s:%s" % (self._name, self._password, self._uid, self._gid, self._info, self._home, self._shell) @staticmethod def from_passwd_line(passwd_line: str): line_split = passwd_line.split(":") return SystemUser(line_split[0], line_split[1], int(line_split[2]), int(line_split[3]), line_split[4], line_split[5], line_split[6]) @property def name(self) -> str: return self._name @property def password(self) -> str: return <PASSWORD>._password @property def uid(self) -> int: return self._uid @property def gid(self) -> int: return self._gid @property def info(self) -> str: return self._info @property def home(self) -> str: return self._home @property def shell(self) -> str: return self._shell def get_system_users() -> List[SystemUser]: """ Gets the system's users from /etc/passwd :return: """ user_list = [] try: with open("/etc/passwd", 'rt') as fp: for line in fp: if line.strip() == "": continue user_list.append(SystemUser.from_passwd_line(line.strip())) except Exception as e: raise PasswdException(str(e)) return user_list
package cn.edu.hit.tumorcnv; /** * * @author <NAME> */ import htsjdk.samtools.SAMReadGroupRecord; import htsjdk.samtools.SamReader; import htsjdk.samtools.util.IntervalList; import htsjdk.samtools.util.SamLocusIterator; import htsjdk.samtools.util.SamLocusIterator.LocusInfo; import java.util.Collection; import java.util.Comparator; import java.util.PriorityQueue; public class MultiSamLocusIterator { private final PriorityQueue<ComparableSamLocusIterator> pq; public MultiSamLocusIterator(Collection<SamReader> readers, IntervalList intervalList) { this.pq = new PriorityQueue<ComparableSamLocusIterator>(readers.size()); for (SamReader reader : readers) { String sampleID = ""; for (int i = 0; i < reader.getFileHeader().getReadGroups().size(); i++) { SAMReadGroupRecord temp = reader.getFileHeader().getReadGroups().get(i); sampleID = temp.getSample(); } addIfNotEmpty(new ComparableSamLocusIterator(new SamLocusIterator(reader, intervalList), sampleID, new Comparator<SamLocusIterator.LocusInfo>() { @Override public int compare(SamLocusIterator.LocusInfo l1, SamLocusIterator.LocusInfo l2) { return l1.toString().compareTo(l2.toString()); } })); } } private void addIfNotEmpty(final ComparableSamLocusIterator iterator) { if (iterator.hasNext()) { pq.offer(iterator); } else { iterator.close(); } } public boolean hasNext() { return !this.pq.isEmpty(); } public LocusInfo next() { ComparableSamLocusIterator iterator = this.pq.poll(); LocusInfo record = iterator.next(); addIfNotEmpty(iterator); return record; } public String getCurrentIteratorSampleID() { ComparableSamLocusIterator iterator = this.pq.peek(); String sampleID = iterator.getSampleID(); return sampleID; } public void close() { for (ComparableSamLocusIterator iterator : pq) { iterator.close(); } } }
/* * zset_testcase.cpp * * Created on: 2013-4-9 * Author: yinqiwen */ #include "db.hpp" #include <string> using namespace ardb; void test_zsets_addrem(Ardb& db) { DBID dbid = 0; db.ZClear(dbid, "myzset"); db.ZAdd(dbid, "myzset", ValueData((int64) 3), "v0"); db.ZAdd(dbid, "myzset", ValueData((int64) 2), "v1"); db.ZAdd(dbid, "myzset", ValueData((int64) 1), "v2"); CHECK_FATAL(db.ZCard(dbid, "myzset") != 3, "zadd myzset failed:%d", db.ZCard(dbid, "myzset")); ValueData score((int64) 0); db.ZScore(dbid, "myzset", "v1", score); CHECK_FATAL(score.NumberValue() != 2, "zscore myzset failed:%f", score.NumberValue()); db.ZAdd(dbid, "myzset", ValueData((int64) 0), "v2"); CHECK_FATAL(db.ZCard(dbid, "myzset") != 3, "zadd myzset failed:%d", db.ZCard(dbid, "myzset")); db.ZRem(dbid, "myzset", "v2"); CHECK_FATAL(db.ZCard(dbid, "myzset") != 2, "zrem myzset failed:%d", db.ZCard(dbid, "myzset")); ValueDataArray values; ZSetQueryOptions options; db.ZRange(dbid, "myzset", 0, -1, values, options); std::string str; CHECK_FATAL(values.size() != 2, "Fail:%zu", values.size()); CHECK_FATAL(values[0].ToString(str) != "v1", "Fail:%s", values[0].ToString(str).c_str()); CHECK_FATAL(values[1].ToString(str) != "v0", "Fail:%s", values[1].ToString(str).c_str()); } void test_zsets_zrange(Ardb& db) { DBID dbid = 0; db.ZClear(dbid, "myzset"); db.ZAdd(dbid, "myzset", ValueData((int64) 1), "one"); db.ZAdd(dbid, "myzset", ValueData((int64) 1), "uno"); db.ZAdd(dbid, "myzset", ValueData((int64) 2), "two"); db.ZAdd(dbid, "myzset", ValueData((int64) 3), "two"); ZSetQueryOptions options; options.withscores = true; ValueDataArray values; db.ZRange(dbid, "myzset", 0, -1, values, options); std::string str; CHECK_FATAL(values.size() != 6, "Fail:%zu", values.size()); CHECK_FATAL(values[0].ToString(str) != "one", "Fail:%s", values[0].ToString(str).c_str()); CHECK_FATAL(values[2].ToString(str) != "uno", "Fail:%s", values[1].ToString(str).c_str()); values.clear(); db.ZRangeByScore(dbid, "myzset", "-inf", "+inf", values, options); CHECK_FATAL(values.size() != 6, "Fail:%zu", values.size()); CHECK_FATAL(values[0].ToString(str) != "one", "Fail:%s", values[0].ToString(str).c_str()); CHECK_FATAL(values[2].ToString(str) != "uno", "Fail:%s", values[1].ToString(str).c_str()); values.clear(); db.ZRangeByScore(dbid, "myzset", "(1", "3", values, options); CHECK_FATAL(values.size() != 2, "Fail:%zu", values.size()); CHECK_FATAL(values[0].ToString(str) != "two", "Fail:%s", values[0].ToString(str).c_str()); db.ZClear(dbid, "myzset"); uint32 maxzsetsize = 1000; for (uint32 i = 0; i < maxzsetsize; i++) { char value[16]; sprintf(value, "value%u", i); db.ZAdd(dbid, "myzset", ValueData((int64) i), value); } options.withscores = false; values.clear(); db.ZRange(dbid, "myzset", 1, 10, values, options); CHECK_FATAL(values.size() != 10, "Fail:%zu", values.size()); } void test_zsets_zcount(Ardb& db) { DBID dbid = 0; db.ZClear(dbid, "myzset"); db.ZAdd(dbid, "myzset", ValueData((int64) 1), "one"); db.ZAdd(dbid, "myzset", ValueData((int64) 2), "two"); db.ZAdd(dbid, "myzset", ValueData((int64) 3), "three"); int count = db.ZCount(dbid, "myzset", "-inf", "+inf"); CHECK_FATAL(count != 3, "Fail:%d", count); count = db.ZCount(dbid, "myzset", "(1", "3"); CHECK_FATAL(count != 2, "Fail:%d", count); } void test_zsets_zrank(Ardb& db) { DBID dbid = 0; db.ZClear(dbid, "myzset"); db.ZAdd(dbid, "myzset", ValueData((int64) 1), "one"); db.ZAdd(dbid, "myzset", ValueData((int64) 2), "two"); db.ZAdd(dbid, "myzset", ValueData((int64) 3), "three"); db.ZCount(dbid, "myzset", "-inf", "+inf"); int rank = db.ZRank(dbid, "myzset", "three"); CHECK_FATAL(rank != 2, "Fail:%d", rank); db.ZClear(dbid, "myzset"); uint32 maxzsetsize = 100000; uint64 start = get_current_epoch_millis(); for (uint32 i = 0; i < maxzsetsize; i++) { char value[16]; sprintf(value, "value%u", i); db.ZAdd(dbid, "myzset", ValueData((int64) i), value); } uint64 end = get_current_epoch_millis(); INFO_LOG("Cost %lldms to write %u zset elements", (end - start), maxzsetsize); start = get_current_epoch_millis(); rank = db.ZRank(dbid, "myzset", "value50001"); CHECK_FATAL(rank != 50001, "Fail:%d", rank); end = get_current_epoch_millis(); INFO_LOG("Cost %lldms to rank.", (end - start)); } void test_zsets_zrem(Ardb& db) { DBID dbid = 0; db.ZClear(dbid, "myzset"); db.ZAdd(dbid, "myzset", ValueData((int64) 1), "one"); db.ZAdd(dbid, "myzset", ValueData((int64) 2), "two"); db.ZAdd(dbid, "myzset", ValueData((int64) 3), "three"); int count = db.ZRemRangeByRank(dbid, "myzset", 0, 1); CHECK_FATAL(count != 2, "Fail:%d", count); db.ZAdd(dbid, "myzset", ValueData((int64) 1), "one"); db.ZAdd(dbid, "myzset", ValueData((int64) 2), "two"); count = db.ZRemRangeByScore(dbid, "myzset", "-inf", "(2"); CHECK_FATAL(count != 1, "Fail:%d", count); } void test_zsets_zrev(Ardb& db) { DBID dbid = 0; db.ZClear(dbid, "myzset"); db.ZAdd(dbid, "myzset", ValueData((int64) 1), "one"); db.ZAdd(dbid, "myzset", ValueData((int64) 2), "two"); db.ZAdd(dbid, "myzset", ValueData((int64) 3), "three"); ZSetQueryOptions options; options.withscores = true; ValueDataArray values; std::string str; db.ZRevRange(dbid, "myzset", 0, -1, values, options); CHECK_FATAL(values.size() != 6, "Fail:%zu", values.size()); CHECK_FATAL(values[0].ToString(str) != "three", "Fail:%s", values[0].ToString(str).c_str()); CHECK_FATAL(values[2].ToString(str) != "two", "Fail:%s", values[2].ToString(str).c_str()); values.clear(); db.ZRevRangeByScore(dbid, "myzset", "+inf", "-inf", values, options); CHECK_FATAL(values.size() != 6, "Fail:%zu", values.size()); CHECK_FATAL(values[0].ToString(str) != "three", "Fail:%s", values[0].ToString(str).c_str()); CHECK_FATAL(values[2].ToString(str) != "two", "Fail:%s", values[2].ToString(str).c_str()); options.withscores = false; values.clear(); db.ZRevRangeByScore(dbid, "myzset", "2", "1", values, options); CHECK_FATAL(values.size() != 2, "Fail:%zu", values.size()); CHECK_FATAL(values[0].ToString(str) != "two", "Fail:%s", values[0].ToString(str).c_str()); CHECK_FATAL(values[1].ToString(str) != "one", "Fail:%s", values[1].ToString(str).c_str()); values.clear(); db.ZRevRangeByScore(dbid, "myzset", "2", "(1", values, options); CHECK_FATAL(values.size() != 1, "Fail:%zu", values.size()); CHECK_FATAL(values[0].ToString(str) != "two", "Fail:%s", values[0].ToString(str).c_str()); } void test_zsets_incr(Ardb& db) { DBID dbid = 0; db.ZClear(dbid, "myzset"); db.ZAdd(dbid, "myzset", ValueData((int64) 1), "one"); db.ZAdd(dbid, "myzset", ValueData((int64) 2), "two"); ValueData score; db.ZIncrby(dbid, "myzset", ValueData((int64) 2), "one", score); ZSetQueryOptions options; options.withscores = true; ValueDataArray values; db.ZRange(dbid, "myzset", 0, -1, values, options); std::string str; CHECK_FATAL(values.size() != 4, "Fail:%zu", values.size()); CHECK_FATAL(values[0].ToString(str) != "two", "Fail:%s", values[0].ToString(str).c_str()); } void test_zsets_inter(Ardb& db) { DBID dbid = 0; db.ZClear(dbid, "myzset1"); db.ZClear(dbid, "myzset2"); db.ZAdd(dbid, "myzset1", ValueData((int64) 1), "one"); db.ZAdd(dbid, "myzset1", ValueData((int64) 2), "two"); db.ZAdd(dbid, "myzset2", ValueData((int64) 1), "one"); db.ZAdd(dbid, "myzset2", ValueData((int64) 2), "two"); db.ZAdd(dbid, "myzset2", ValueData((int64) 3), "three"); SliceArray keys; keys.push_back("myzset1"); keys.push_back("myzset2"); WeightArray ws; ws.push_back(20); ws.push_back(4); db.ZInterStore(dbid, "myzset3", keys, ws); int zcard = db.ZCard(dbid, "myzset3"); CHECK_FATAL(zcard != 2, "Fail:%d", zcard); ZSetQueryOptions options; options.withscores = true; ValueDataArray values; db.ZRange(dbid, "myzset3", 0, -1, values, options); std::string str; CHECK_FATAL(values.size() != 4, "Fail:%zu", values.size()); CHECK_FATAL(values[0].ToString(str) != "one", "Fail:"); } void test_zsets_union(Ardb& db) { DBID dbid = 0; db.ZClear(dbid, "myzset1"); db.ZClear(dbid, "myzset2"); db.ZAdd(dbid, "myzset1", ValueData((int64) 1), "one"); db.ZAdd(dbid, "myzset1", ValueData((int64) 2), "two"); db.ZAdd(dbid, "myzset2", ValueData((int64) 1), "one"); db.ZAdd(dbid, "myzset2", ValueData((int64) 2), "two"); db.ZAdd(dbid, "myzset2", ValueData((int64) 3), "three"); SliceArray keys; keys.push_back("myzset1"); keys.push_back("myzset2"); WeightArray ws; ws.push_back(10); ws.push_back(4); db.ZUnionStore(dbid, "myzset3", keys, ws); CHECK_FATAL(db.ZCard(dbid, "myzset3") != 3, "Fail:"); ZSetQueryOptions options; options.withscores = true; ValueDataArray values; db.ZRange(dbid, "myzset3", 0, -1, values, options); std::string str; CHECK_FATAL(values.size() != 6, "Fail:%zu", values.size()); CHECK_FATAL(values[0].ToString(str) != "three", "Fail:%s", values[0].ToString(str).c_str()); CHECK_FATAL(values[2].ToString(str) != "one", "Fail:%s", values[2].ToString(str).c_str()); CHECK_FATAL(values[4].ToString(str) != "two", "Fail:%s", values[4].ToString(str).c_str()); } void test_zset_expire(Ardb& db) { DBID dbid = 0; db.ZClear(dbid, "myzset"); db.ZAdd(dbid, "myzset", ValueData((int64) 1), "one"); db.Expire(dbid, "myzset", 1); CHECK_FATAL(db.Exists(dbid, "myzset") == false, "Expire myzset failed"); sleep(2); db.CheckExpireKey(dbid, 50, 10000); CHECK_FATAL(db.Exists(dbid, "myzset") == true, "Expire myzset failed"); } void test_geo(Ardb& db) { DBID dbid = 0; db.ZClear(dbid, "mygeo"); double x = 300.3; double y = 300.3; double p_x = 1000.0; double p_y = 1000.0; double raius = 1000; GeoPointArray cmp; for (uint32 i = 0; i < 100000; i++) { char name[100]; sprintf(name, "p%u", i); double xx = x + i * 0.1; double yy = y + i * 0.1; if (((xx - p_x) * (xx - p_x) + (yy - p_y) * (yy - p_y)) < raius * raius) { GeoPoint p; p.x = xx; p.y = yy; cmp.push_back(p); } GeoAddOptions add; add.coord_type = 2; add.x = x + i * 0.1; add.y = y + i * 0.1; add.value = name; db.GeoAdd(dbid, "mygeo", add); } if(db.GetL1Cache() != NULL) { db.GetL1Cache()->SyncLoad(dbid, "mygeo"); } GeoSearchOptions options; StringArray args; std::string err; string_to_string_array("MERCATOR 1000.0 1000.0 RADIUS 1000 ASC WITHCOORDINATES WITHDISTANCES", args); options.Parse(args, err); ValueDataDeque result; db.GeoSearch(dbid, "mygeo", options, result); CHECK_FATAL(cmp.size() != result.size() / 4, "Search failed with %u elements while expected %u", result.size() / 4, cmp.size()); uint64 start = get_current_epoch_millis(); for (uint32 i = 0; i < 10000; i++) { result.clear(); options.x = p_x + i * 0.1; options.y = p_y + i * 0.1; options.radius = 100; db.GeoSearch(dbid, "mygeo", options, result); } uint64 end = get_current_epoch_millis(); for (uint32 i = 0; i < result.size(); i += 4) { INFO_LOG("GeoPoint:%s x:%.2f, y:%.2f, distance:%.2f", result[i].bytes_value.c_str(), result[i + 1].NumberValue(), result[i + 2].NumberValue(), result[i + 3].NumberValue()); } INFO_LOG("Found %d points for search while expected %d points", result.size() / 4, cmp.size()); INFO_LOG("Cost %lldms to geo search 100000 zset elements 10000 times", (end - start)); } void test_zsets(Ardb& db) { test_zsets_addrem(db); test_zsets_zrange(db); test_zsets_zcount(db); test_zsets_zrank(db); test_zsets_zrem(db); test_zsets_zrev(db); test_zsets_incr(db); test_zsets_inter(db); test_zsets_union(db); test_zset_expire(db); test_geo(db); }
/* register the pinctrl interface with the pinctrl subsystem */ static int exynos5440_pinctrl_register(struct platform_device *pdev, struct exynos5440_pinctrl_priv_data *priv) { struct device *dev = &pdev->dev; struct pinctrl_desc *ctrldesc; struct pinctrl_dev *pctl_dev; struct pinctrl_pin_desc *pindesc, *pdesc; struct pinctrl_gpio_range grange; char *pin_names; int pin, ret; ctrldesc = devm_kzalloc(dev, sizeof(*ctrldesc), GFP_KERNEL); if (!ctrldesc) { dev_err(dev, "could not allocate memory for pinctrl desc\n"); return -ENOMEM; } ctrldesc->name = "exynos5440-pinctrl"; ctrldesc->owner = THIS_MODULE; ctrldesc->pctlops = &exynos5440_pctrl_ops; ctrldesc->pmxops = &exynos5440_pinmux_ops; ctrldesc->confops = &exynos5440_pinconf_ops; pindesc = devm_kzalloc(&pdev->dev, sizeof(*pindesc) * EXYNOS5440_MAX_PINS, GFP_KERNEL); if (!pindesc) { dev_err(&pdev->dev, "mem alloc for pin descriptors failed\n"); return -ENOMEM; } ctrldesc->pins = pindesc; ctrldesc->npins = EXYNOS5440_MAX_PINS; for (pin = 0, pdesc = pindesc; pin < ctrldesc->npins; pin++, pdesc++) pdesc->number = pin; pin_names = devm_kzalloc(&pdev->dev, sizeof(char) * PIN_NAME_LENGTH * ctrldesc->npins, GFP_KERNEL); if (!pin_names) { dev_err(&pdev->dev, "mem alloc for pin names failed\n"); return -ENOMEM; } for (pin = 0; pin < ctrldesc->npins; pin++) { snprintf(pin_names, 6, "gpio%02d", pin); pdesc = pindesc + pin; pdesc->name = pin_names; pin_names += PIN_NAME_LENGTH; } ret = exynos5440_pinctrl_parse_dt(pdev, priv); if (ret) return ret; pctl_dev = pinctrl_register(ctrldesc, &pdev->dev, priv); if (!pctl_dev) { dev_err(&pdev->dev, "could not register pinctrl driver\n"); return -EINVAL; } grange.name = "exynos5440-pctrl-gpio-range"; grange.id = 0; grange.base = 0; grange.npins = EXYNOS5440_MAX_PINS; grange.gc = priv->gc; pinctrl_add_gpio_range(pctl_dev, &grange); return 0; }
<reponame>fusion-jena/OAPT<gh_stars>0 package fusion.oapt.model; public class Constant { public static final String OWL_NS = "http://www.w3.org/2002/07/owl#"; public static final String RDF_NS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; public static final String RDFS_NS = "http://www.w3.org/2000/01/rdf-schema#"; public static final String XSD_NS = "http://www.w3.org/2001/XMLSchema#"; public static final String DC_NS = "http://purl.org/dc/elements/1.1/"; public static final String FOAF_NS = "http://xmlns.com/foaf/0.1/"; public static final String ICAL_NS = "http://www.w3.org/2002/12/cal/ical#"; public static final int ONTOLOGY_CLASS = 1; public static final int ONTOLOGY_PROPERTY = 8; public static final int ONTOLOGY_INSTANCE = 16; public static final int EXTERNAL_CLASS = 32; public static final int EXTERNAL_PROPERTY = 64; public static final int EXTERNAL_INSTANCE = 128; public static final int STMT = 256; public static String BUILTIN_NS[] = {XSD_NS, RDF_NS, RDFS_NS, OWL_NS, DC_NS, FOAF_NS, ICAL_NS}; public static boolean isBuiltInNs(String ns) { for (int i = 0, n = BUILTIN_NS.length; i < n; i++) { if (ns.equals(BUILTIN_NS[i])) { return true; } } return false; } }
def field2nullable(self, field, ret): attributes = {} if field.allow_none: if self.openapi_version.major < 3: attributes["x-nullable"] = True elif self.openapi_version.minor < 1: attributes["nullable"] = True else: attributes["type"] = [*make_type_list(ret.get("type")), "null"] return attributes
def _make_link(volume_path, backup_path, vol_id): try: utils.execute('ln', volume_path, backup_path, run_as_root=True, check_exit_code=True) except processutils.ProcessExecutionError as exc: err = (_('backup: %(vol_id)s failed to create device hardlink ' 'from %(vpath)s to %(bpath)s.\n' 'stdout: %(out)s\n stderr: %(err)s') % {'vol_id': vol_id, 'vpath': volume_path, 'bpath': backup_path, 'out': exc.stdout, 'err': exc.stderr}) LOG.error(err) raise exception.InvalidBackup(reason=err)
Integrated inference and evaluation of host–fungi interaction networks Fungal microorganisms frequently lead to life-threatening infections. Within this group of pathogens, the commensal Candida albicans and the filamentous fungus Aspergillus fumigatus are by far the most important causes of invasive mycoses in Europe. A key capability for host invasion and immune response evasion are specific molecular interactions between the fungal pathogen and its human host. Experimentally validated knowledge about these crucial interactions is rare in literature and even specialized host–pathogen databases mainly focus on bacterial and viral interactions whereas information on fungi is still sparse. To establish large-scale host–fungi interaction networks on a systems biology scale, we develop an extended inference approach based on protein orthology and data on gene functions. Using human and yeast intraspecies networks as template, we derive a large network of pathogen–host interactions (PHI). Rigorous filtering and refinement steps based on cellular localization and pathogenicity information of predicted interactors yield a primary scaffold of fungi–human and fungi–mouse interaction networks. Specific enrichment of known pathogenicity-relevant genes indicates the biological relevance of the predicted PHI. A detailed inspection of functionally relevant subnetworks reveals novel host–fungal interaction candidates such as the Candida virulence factor PLB1 and the anti-fungal host protein APP. Our results demonstrate the applicability of interolog-based prediction methods for host–fungi interactions and underline the importance of filtering and refinement steps to attain biologically more relevant interactions. This integrated network framework can serve as a basis for future analyses of high-throughput host–fungi transcriptome and proteome data. Introduction Fungal pathogens infect hundreds of millions of people world-wide every year (Havlickova et al., 2008). Although, the death toll of fungal diseases is comparable to that of malaria or tuberculosis the global burden imposed by fungal pathogens still remains underestimated . In general, infections caused by fungal pathogens can lead to a diverse range of diseases ranging from superficial infections to invasive mycoses. The outcome of fungal infections is often associated with the intactness of the patients' immune system and therefore fungi pose an increasingly severe threat to the growing numbers of immunocompromised patients in modern medicine, with high mortality rates exceeding 50% for invasive fungal diseases . Among fungal pathogens the dimorphic yeast Candida albicans and the filamentous fungus Aspergillus fumigatus are the most important causes of life-threatening invasive mycoses (Horn et al., 2012). C. albicans colonizes the skin and intestinal mucosa of 30-70% of healthy individuals and invasive infection almost exclusively begins endogenously starting from a usually harmless surface colonization, frequently in the gastrointestinal tract . In contrast to the endogenous pathway of C. albicans, infections by A. fumigatus mainly occur exogenously via the inhalation of fungal spores (conidia) causing chronic pulmonary aspergillosis or invasive aspergillosis in patients with a severely weakened immune system . Despite these differences during the infection process, several common strategies of pathogenesis are shared between both fungi. Host-fungi interactions have been described as commensalism, symbiosis, or pathogenicity. Interestingly, the mechanisms of symbiosis and pathogenicity share common features and there is evidence for parallel trends in evolution between host and pathogens (Ochman and Moran, 2001). The transition from commensal to pathogen is often dependent on small differences (Martin and Nehls, 2009) and the hostpathogen relation can change by environmental conditions (Hube, 2004). Strong adhesion of the fungi to the surface forming a protective biofilm is important for invasive growth, as invasion is driven by pressure on the solid substrate (de Groot et al., 2013). In this sense host-fungal interaction can be characterized by the formation of symbiotic or pathogenic interfaces (Bonfante and Genre, 2010). This relates in particular to processes of pathogen-host interaction (PHI) where both fungi mainly need to overcome similar epithelial barriers and develop skills for the evasion of the innate immune system, capabilities which contribute to the aggressiveness of both pathogens (Horn et al., 2012). Therefore, a principal aim of systems biological research of human-pathogenic fungi is to unravel the intricate network of interactions between host and the fungal pathogen and elucidate the complex pathogenesis processes of fungal infections. A major quest in this field is the identification of physical or direct interactions between fungus and host proteins during the infection processes. Albeit the research of host-pathogen interactions is becoming increasingly popular in experimental as well as computational science, only a small number of interactions between fungi and human have been reported in literature so far. This leaves a large gap for novel bioinformatical strategies for the prediction of PHI of pathogenic fungi. With the advent of large scale interaction detection methods the experimental and computational analyses of protein-protein interactions (PPIs) have established an important research field in bioinformatics during the last decade. Still most efforts have been dedicated to the investigation of intraspecies interactions (i.e., interaction between proteins within one species). The primary species in the focus of investigation so far have been Homo sapiens and Saccharomyces cerevisiae. This is reflected in the fact that the largest experimentally derived PPI datasets available in databases primarily cover H. sapiens and S. cerevisiae interactions. Currently, these two species constitute almost 74% percent of all non-redundant physical interactions 1 (H. sapiens: 50.7% and S. cerevisiae: 23.0%) in the BioGRID database (Chatr-Aryamontri et al., 2013). The networks of most other species are considerably smaller and for network analysis these datasets are often extended by the inclusion of interolog based predictions to obtain a larger search space, where interologs are defined as PPIs that are conserved between orthologous proteins in different species (Walhout et al., 2000). Nowadays the interolog approach is commonly used for the classical prediction intraspecies interactions and is particularly valuable for the prediction of novel PPI in species where only a small number of interactions have been experimentally detected. Conceptually, the interactions are transferred from one species to another. This means that if for a given pair of interacting proteins in the source species, homologues for both interaction partners exist in the target species an interaction between those two homologs is inferred. The rational of this interaction transfer is based on the assumption that if a pair of homologous proteins originates from the same ancestral pair of interacting proteins, it can be expected, that the inheritance of the amino acid sequence translates into a related and similar protein structure, and thereby the capability of mutual interaction is also inherited from the ancestral interacting proteins (Walhout et al., 2000). This approach has been extended to the prediction of interspecies interactions and in particular to the prediction of PHIs (Zhou et al., 2013a). Recent studies investigated the interaction between H. sapiens and Plasmodium falciparum (Dyer et al., 2007;Lee et al., 2008;Wuchty, 2011), H. sapiens and Helicobacter pylori (Tyagi et al., 2009), H. sapiens and E. coli (Krishnadev and Srinivasan, 2011), H. sapiens and Salmonella enterica (Krishnadev and Srinivasan, 2011) and H. sapiens and Yersinia pestis (Krishnadev and Srinivasan, 2011) as well as between H. sapiens and Mycobacterium tuberculosis (Zhou et al., 2014). Apart from the more frequently investigated protozoan P. falciparum, most of these studies focus on the interaction with a bacterial pathogens. Fungal infections have only rarely been researched. A recent study examined the interaction between zebra fish and Candida , however, a systemic investigation of direct host-pathogen-PPI between the fungi either C. albicans or A. fumigatus and the human host has to our knowledge not be conducted so far. Here we present an extended interolog-based method for the prediction of fungal-host interactions. We focus on the clinically most relevant fungi, the dimorphic yeast C. albicans and the filamentous fungus A. fumigatus. In addition to the human host, we also investigate interactions between these fungi and Mus musculus, since it is the most frequently used animal model in medical sciences. As basic interolog prediction approaches for cross-species analysis often produce large initial predictions sets, we develop and establish an advanced filtering and selection strategy, to reduce the initial set of raw predictions to a smaller refined set of high quality predictions. To this end, we integrate information on cellular localization of the predicted host and pathogen interaction partners and focus on proteins associated with cellular functions with relevance for the infection process. The enrichment of established infection and pathogenicity related genes during these subsequent refinement steps emphasizes the biological relevance of the predicted PHIs, from which we highlight and describe some promising candidate interaction in more detail. By this, we demonstrate the benefit of the interolog-based approach in combination with advanced filtering and refinement steps for prediction fungalhost interactions. PSICQUIC queries (Aranda et al., 2011) were used to retrieve human and yeast intraspecies interaction information from this databases on 09/09/2014. Non-coding genes, interaction loops of self-interacting proteins as well as interactions of the interaction types "colocalization, " "additive genetic interaction defined by inequality, " "suppressive genetic interaction defined by inequality, " "synthetic genetic interaction defined by inequality, " "genetic interaction, " "genetic inequality, " "genetic interference, " and "self-interaction" were not used for the template networks. Orthology Information Orthology information for C. albicans, S. cerevisiae, H. sapiens, M. musculus, and A. fumigatus was downloaded from InParanoid8 (Sonnhammer and Ostlund, 2014). Additionally, orthology relations between A. fumigatus and S. cerevisiae were retrieved from Aspergillus Genome Database (AspGD; Cerqueira et al., 2014). Orthologies of the species pair A. fumigatus and H. sapiens which was neither available from InParanoid8 nor AspGD, were computed via the InParanoid version 4.1 5 using parameters comparable to the parameters of similar species pairs (H. sapiens -A. kawachii). Blast version 2.2.26 with the scoring matrix Blosum62, a score-cutoff of 40 bits, a sequence overlap of 0.5, a group merging cutoff 0.5 and a minimal score of 0.05 was used as InParanoid settings. The dataset for A. fumigatus protein sequence was downloaded from AspGD, while the protein sequences of H. sapiens originated from the InParanoid8 server. Gene Ontology Gene Ontology (GO) slim annotations, a subset of the GO dataset (Ashburner et al., 2000) were used to categorize genes in host-fungi interactions of the inferred networks regarding three domains: biological process, molecular function and cellular component. GO slim associations were retrieved from the Candida Genome Database (CGD; Arnaud et al., 2005) and the AspGD (Cerqueira et al., 2014) for both fungal pathogen species. GO slim associations for the host species (H. sapiens and M. musculus) were downloaded from EnsEmbl 76 (Flicek et al., 2014). Genes of the inferred fungi-host interaction networks were categorized by GO slim cellular component annotation in likely and unlikely host-fungal interactors under the assumption that interacting host and fungal proteins have to be localized on potential interface (e.g., cell surface or endosome membrane). The GO slim cellular component terms for likely interspecies interactions on the fungal and host side were listed in Table 1. Similar to the refinement step for protein localization, proteins with pathogenicity-associated GO slim biological process terms were selected to enrich for pathogenicity-relevant interaction predictions (see Table 2). Only genes assigned to one of the referenced cellular component and biological process GO terms were used for further analyses. Gene Ontology and Uniprot Tissue Enrichment Interactors of subnetworks were tested for enriched GO annotation level 2 terms of the domains "biological process, " "cellular component, " "molecular function" (Ashburner et al., 2000) versus the GO terms background frequencies of the interactors in the full network. The functional enrichment tests were performed via the DAVID Bioinformatics Resources 6.7 (Huang da et al., 2009a,b) using GO terms of all levels and only reporting groups of the size of least two genes and an EASE Score Threshold (for gene-enrichment analysis modified Fisher Exact P-Value) of less than 0.1. The p-values were adjusted for multiple testing (Hochberg and Benjamini, 1990). Similar to the GO enrichment, the tissue enrichment analyses were performed on Uniprot tissue terms via the DAVID Bioinformatics Resources 6.7. Catalog of Pathogenicity-Relevant Genes To get a set of genes of H. sapiens and M. musculus that are known to be involved in host-pathogen interactions, the PPI information were downloaded from the HPIDB version 5/22/2014 and the PATRIC database version Mar2013. Further, all interspecies interactions that involved viral pathogens or the interaction types which are not related to a direct PPI such as annotated as "colocalization, " "additive genetic interaction defined by inequality, " "suppressive genetic interaction defined by inequality, " "synthetic genetic interaction defined by inequality, " "genetic interaction, " or "genetic inequality" were removed from the dataset. Also, the Victors database of PHIDIAS (Xiang et al., 2007), a database containing virulence factors originating from literature curation and bioinformatics analyses and the PHIbase (Winnenburg et al., 2008), a database containing expertly curated molecular and biological information on pathogenic genes experimentally verified to have an effect on the virulence outcome were searched for genes of the fungal pathogens A. fumigatus and C. albicans that are known as pathogenesis associated. To find already known human-Aspergillus, mouse-Aspergillus, human-Candida, and mouse-Candida interactions the public available interaction databases mentha, HPIDB, APID, PHISTO, PRIMOS, and the databases of IMEx was searched. Analysis of Dual RNA-Seq Data For the comparison of predicted fungal-host interaction networks, gene expression data of a previously published time course of murine bone marrow derived dendritic cells phagocytosing C. albicans SC5314 cells was used (Tierney et al., 2012). The gene expression data constitutes of dual RNA-seq data simultaneously measuring the transcripts of Candida and mouse cells at 30, 60, 90, and 120 min post-infection. The sequenced reads were downloaded from http://www.ebi.ac.uk/arrayexpress/ experiments/E-MTAB-595/. Contamination of poly-T at the read start and poly-A at the read end was removed via cutadapt version 1.6 (Martin, 2011). The curated reads were mapped on a combined reference of the C. albicans SC5314 version A22 (Arnaud et al., 2005) and the M. musculus version GRCm38.75 (Flicek et al., 2014) genome, using the short read mapping tool STAR version 2.4 (Dobin et al., 2013). For each gene of the C. albicans and the M. musculus, the uniquely mapped reads were counted with featureCounts version 1.4.3 (Liao et al., 2014). Fungal and host genes were tested for differential expression in the infection time course with DESeq2 version 1.6.2 (Love et al., 2014). Genes were identified as differentially expressed when they showed a significant (p-value <0.05) change in read counts after multiple testing correction (Hochberg and Benjamini, 1990). Network Visualization The networks were visualized by Cytoscape (Shannon et al., 2003). The top 10% of fungal high degree interactors were removed from the visualized networks to improve the readability. The GO slim interaction network was based on grouping genes in GO slim groups that are annotated by the respective GO slim biological process terms. Improved readability of GO slim networks was achieved by merging GO slim groups fully contained in larger groups. Node size represents the number of genes contained in each GO slim term. Edge width and color depict number of interactions between two GO slim terms. Host-Fungi Interaction Data in Literature and Public Databases is Sparse The primary objective of our work is to establish a comprehensive catalog of host-fungal interactions. A first literature search revealed that overall not much detailed data concerning PHIs for fungi is available so far. However, as PHIs have become an important topic in the last years, several databases for PHIs have been established. Up to date most of the interactions deposited in these databases still relate to viral and bacterial pathogens and almost no information concerning fungi is available at all. For example, the current HPIDB (Kumar and Nanduri, 2010) covers predominantly viral (74%: 29,942) and bacterial (22%: 8,992) pathogens and only 4% (1,628) of the interactions involve fungal species out of which over 92% (1,499) relate to Saccharomyces spp. To obtain a comprehensive overview of all host-fungi interaction data available so far, we first searched the content of the most prominent host-pathogen interaction databases for established host-fungal interactions between human-Candida, human-Aspergillus, mouse-Candida, and mouse-Aspergillus. Nevertheless, the search returned only two distinct interactions between C. albicans and H. sapiens and one more for mouse-Candida: (i) Candida ORC1 (Origin recognition complex subunit 1) and human CDC23 (Cell division cycle protein 23), (ii) Candida Q00308 and human CD2BP2 (CD2 antigen cytoplasmic tail-binding protein 2). For the interaction between mouse and Candida only one interaction between the Candida CDC28 (Cyclin-dependent kinase 1) and murine Cdkn1b (Cyclin-dependent kinase inhibitor 1B) could be found. We could not find any interspecies interaction between human and A. fumigatus or between mouse and A. fumigatus from the above host-pathogen-databases. Therefore, we subsequently scanned APID (Prieto and De Las Rivas, 2006), mentha (Calderone et al., 2013) and all the 14 curated PPI databases of the IMEx consortium (Orchard et al., 2012) for cross-species interactions involving A. fumigatus and C. albicans (see Catalog of Pathogenicity-Relevant Genes section). This extended search revealed only one additional interspecies interaction that was not included in the PHI databases: Candida CDC42 (Cell division control protein 42 homolog) and the murine Scd2 (Acyl-CoA desaturase 2). No interactions for A. fumigatus have been found in above databases for human or mouse. Since information in databases about PPIs between the fungal pathogens C. albicans and A. fumigatus and their hosts is sparse, we propose a framework to infer PHIs and thus create hypotheses for experimental validation. Dual Template Interolog-Based Host-Fungi PPI Network Inference Approach The general approach applied in this study aims on the identification of novel potential PPIs between the selected host species H sapiens and M. musculus and the fungal pathogen species C. albicans and A. fumigatus. To derive these PHIs, we established an interolog-based inference method exploiting known intraspecies interactions in H. sapiens and S. cerevisiae as template networks combined with gene homology information between the template species and the host as well as the fungal species. Our approach comprises three steps which involve (i) the establishment of a comprehensive dual-species PPI template network, (ii) homology based inference of PHIs, and (iii) the application of an extended filtering strategy on the raw predictions to attain a core set of refined interaction predictions (see Figure 1). Comprehensive Dual-Species PPI Template Network To establish a comprehensive intraspecies template network for interspecies PHI interaction prediction we screened the BioGRID database (Chatr-Aryamontri et al., 2013) and 13 PPI databases associated with the Imex consortium for intraspecies PPIs in H. sapiens and S. cerevisiae resulting in 170,774 human interactions with 15,509 interactors and 272,167 yeast interactions with 5,824 interactors. As we primarily focus in this study on direct PPIs, the template networks were curated from PPIs detected by methods which are rather based on functional associations (e.g., "genetic interference"). Furthermore, all selfinteractions were removed from this network. The resulting human and yeast intraspecies PPI networks consisted of 147,760 human interactions with 15,240 interactors and 130,665 yeast interactions with 5,789 interactors. Although the numbers of human interactions were reduced by almost 14%, the number of interactors barely decreased (1.7%). Since a large number of yeast FIGURE 1 | Basic concept of the host-fungi PPI inference and refinement steps. (A) Information of direct PPI from multiple public databases were integrated for the two template networks Homo sapiens and Saccharomyces cerevisiae. (B) These combined with orthology information allowed to identify host-fungi interologs. (C) Primary inferred networks were filtered for interactions which showed protein localizations pointing to possible interfaces between host and fungi. Additionally, the networks were refined for pathogenicity-related processes. (D) Evidence information of several independent sources (e.g., transcriptome data) were exploited to evaluate the refined host-fungi PPI networks. interaction were identified by functional association methods, the number of interaction decreased by almost 52%, while similar to the human network the number of interactors was just reduced by less than 1% (see Supplementary Table S2). Interolog-Based Prediction Yields Large Host Fungal Interaction Networks Host-fungal interactions for each host-fungi pair were predicted based on the two template interaction networks. Thus, in a second step, we integrated the template interaction data with orthology information of the host, pathogen, and template species. Orthology information between the two template PPI networks of H. sapiens and S. cerevisiae and the host species H. sapiens and M. musculus as well as the fungal pathogens C. albicans and A. fumigatus was downloaded from the InParanoid 8 database (Sonnhammer and Ostlund, 2014), the species-specific genome databases Cerqueira et al., 2014;Costanzo et al., 2014) and missing species pairs complemented by orthology identification by the stand-alone program InParanoid 4.1 (Ostlund et al., 2010). For H. sapiens as template species, 16,582 mouse genes were identified as orthologs to 16,417 human genes, while 2,687 Candida genes were orthologs to 3,770 H. sapiens genes (2,808 Aspergillus and 4,277 H. sapiens genes, respectively). Interestingly, we found more than twice the number of Candida proteins being orthologs to yeast than orthologous A. fumigatus proteins, while the number between both fungi and human was comparable to S. cerevisiae -A. fumigatus orthologs (see Supplementary Table S1) We searched for orthologs for both interactors of each template interaction to predict potential direct PPIs between the host species H. sapiens or M. musculus with the fungal pathogen species C. albicans or A. fumigatus. Interologs are PPIs inferred from one species to another by using orthology information (Walhout et al., 2000). In our approach, we simultaneously identified orthologs of one interactor in the host species and one interactor in the fungal species for each template interaction. The resulting cross-species interologs between the hosts and the pathogens should consequently have the potential to perform a PPI, given both interactors share the same location at one point in time. For the human-Aspergillus infection 213,518 interologs with 11,279 human and 3,576 Aspergillus interactors could be superimposed. Similar results were obtained for the three other infection setups human-Candida, mouse-Aspergillus, and mouse-Candida (see Supplementary Table S2). Improving Primary Inferred Host-Fungi PPI Networks Potential false predictions were reduced via refinement of the primary inferred host-fungi PPI networks based on functional data. Therefore, GO slim annotations of the cellular component and biological process (The Gene Ontology, 2014) were exploited in this filtering step. To enrich for likely interactions, only host and pathogen interactors which showed GO slim cellular component annotations pointing at locations associated to the cell surface and intracellular compartments which can be in direct host-fungi contact, were selected for the refined host-fungi PPI networks. The GO slim cellular compartment terms which were selected for filtering interactors based on their localization were summarized for the hosts (see Table 1A) and the fungi (see Table 1B). Only 902 human and 361 mouse genes showed no GO slim cellular component annotation at all. On the fungal side, this was the case for 1114 Candida, but none of Aspergillus genes. Altogether, only very few genes were lost in this filtering step due to missing localization information. The distribution of filtered GO slim cellular component terms clearly shows that the "extracellular region" is less abundant in the murine compared to the human interactor set (783 and 2566), while the other terms are similarly present between mouse and human. Surprisingly, the term "extracellular region" also shows a strong difference in distribution on the fungal side (94 Aspergillus interactors and 33 Candida interactors). This filtering step reduced the interolog networks, e.g., human-Aspergillus with 213,518 interologs to 17,853 interactions with 2,393 human and 363 Aspergillus interactors. For all four interolog networks, the refinement step reduced the number of interactions to less than 9%, while the host interactors were reduced to less than 11% and the fungal interactors to less than 22%, respectively (see Table 1C). In concordance with the localization filtering, a functional refinement utilizing representative biological process terms was applied. To improve the quality of the predicted network and increase the fraction of PPIs potentially associated to pathogenicity-relevant processes, we selected five GO slim biological process terms for filtering the host interactors (see Table 2A) and five GO slim biological process terms on the pathogen side (see Table 2B). All genes of the hosts and fungal pathogens showed an annotation of GO slim biological process. In the localization-refined PPI networks, GO slim biological process annotations were available for each host and fungi interactor. Nonetheless, the number of human interactors assigned to the selected GO slim biological process terms was higher than for mouse. Especially, the GO slim term "Symbiosis, encompassing mutualism through parasitism" yielded the strongest difference with a coverage of 260 human interactors and 0 mouse interactors. For the fungal pathogens, the results were similar with fewer A. fumigatus interactors than C. albicans interactors assigned to selected GO biological process terms. This filtering step reduced the localization-refined networks, e.g., mouse-Candida 8055 interactions with 1,376 mouse and 282 Candida interactors to 1,462 interactions with 461 mouse and 41 Candida interactors. For all four host-fungi networks, the refinement step reduced the number of interactions to less than 20%, while the host interactors were reduced to less than 40% and the fungal interactors to less than 19%, respectively (see Table 2C). The Dual Template Approach Substantially Enhances the Prediction Space for Host Fungal Network Inference To investigate the benefits of our dual-template approach for the interolog-based network inference, we examined for each host and fungal interactors the template network from which they were inferred. For this, we grouped the interactors of the primary inferred PHI networks based on their original template network (see Figure 2). On the host side, the human template exclusively makes up for 67.5% of the human interactors in the PHI networks, while over 10.2% of the human interactors originated only from the yeast template (see Supplementary Figure S1). About 22.3% of the human interactors were inferred from both the human and the yeast template. Similarly, for the mouse interactors, the human template solely makes up for over 66.0% of the murine interactors in the PHI networks, while more than 11.5% of the interactors originated only from the yeast template. About 22.4% of the murine interactors were inferred from both the human and the yeast template. Even though no orthology information was required for the inference of human interactors, we see similar distribution of template origin between human and murine interactors. On the fungal side, a substantially larger fraction of the Aspergillus interactors (24.4%) was inferred from yeast template, while the human template makes up for 42.4% of the Aspergillus interactors originating from the human template. Over 33.1% of the Aspergillus interactors were inferred from both the human and the yeast template. In contrast, only less than 8.5% of the Candida interactors were inferred from the human template, while more than 43.0% originated from yeast interologs. The largest fraction with more than 48.4% of the Candida interactors resulted from both human and yeast template. These numbers represent substantial differences in the distribution between both fungal pathogens, as could be expected by the smaller evolutionary distance from S. cerevisiae to C. albicans than from S. cerevisiae to A. fumigatus. A GO enrichment analysis was performed for each group of interactors originating from human, yeast, or both template interaction networks compared to the whole set of interactors (see Supplementary Tables S3 and S4). The GO enrichment analyses showed that multiple GO categories related to PHI were significantly enriched in the human interactor subsets originating from the human template network (e.g., extracellular region part, cell adhesion, signal transducer activity) and yeast template network (e.g., membrane part, transmembrane transport, ion binding). Surprisingly, the subset of human interactors inferred by both template networks was enriched for GO categories of basic biological processes (e.g., intracellular part, ribonucleoprotein complex, nucleotide binding). Even with the overlap of subsets showing only few interesting enriched GO categories, the integration of both template networks complemented a large amount of significantly enriched pathogenicity-relevant categories (see Supplementary Table S3). Similar to the host side, the GO enrichment analysis of the Aspergillus interactors predicted based on the human template network yielded significantly enriched pathogenicity-associated GO terms (e.g., oxidation reduction, ion binding). For the interactors originating from the yeast template network, a different set of pathogen-relevant GO terms (e.g., membrane, transferase activity) were enriched, while the Aspergillus interactors inferred by both template networks mainly basic biological processes were enriched (e.g., ribonucleoprotein complex, cellular metabolic process, structural constituent of ribosome; see Supplementary Table S4). Localization Filtering and Functional Refinement Improve Predicted Host-Fungi Networks Since data on experimentally validated PHIs for fungal pathogens are rare and there is no golden standard for PHI network inference available, we created a dataset of pathogenicityassociated genes for validation of the refinement step. We extracted functional data encompassing (1) human and murine genes which have been reported to directly interact with pathogenic proteins (Kumar and Nanduri, 2010), (2) virulence and pathogenicity phenotypes induced by knock outs of fungal genes (Xiang et al., 2007;Winnenburg et al., 2008) and (3) infection responsive genes identified by analysis of a data set of an infection time course experiment of murine innate immune cells infected by C. albicans (Tierney et al., 2012). Infection-Regulated Genes are Enriched in Resulting Host-Fungi Networks Under the assumption, that deregulated genes over an infection time course are more likely to be involved in host-fungi interactions, exploiting transcriptomic or proteomic gene expression data can be used for the validation of the refinement step. The recently published simultaneous transcriptome sequencing of C. albicans and murine innate immune cells 0, 30, 60, 90, and 120 min post-infection uncover the temporal dynamics of infection-regulated genes (Tierney et al., 2012). For 21,251 mouse genes and 6,274 Candida genes, we found at least one RNA-seq read matched and performed statistical analyses of all time points compared to 0 min post-infection. This revealed 413 significantly deregulated genes in the mouse transcriptome and 1,068 significantly deregulated genes in the fungal transcriptome. The number of deregulated mouse genes was increasing from time point to time point: 45 genes after 30 min, 169 genes after 60 min, 239 genes after 90 min, and 300 genes after 120 min). Similar to mouse, the number of significant Candida genes was also increasing with 314 genes after 30 min, 316 genes after 60 min, 432 genes after 90 min, and 744 genes after 120 min post-infection (see Figures 3A,B). Interestingly, significantly deregulated genes in mouse were mainly upregulated genes, at a ratio 5:1. In contrast, the significant genes in Candida showed almost the same number of up-and downregulated genes. With the identified deregulated genes in C. albicans and M. musculus, we generated a set of infection-associated genes each for the fungal pathogen and the mammalian host. With these sets as a positive list, deregulated genes were significantly enriched in the final refined network compared to the primary inferred mouse-Candida PPI network (see Figures 3C,D). For the predicted mouse interactors, the localization-based filtering step did not show a significant enrichment in contrast to the functional refinement. Due to the small number of interactors (12 of 41) in the refined network, the functional refinement step did not show a significant enrichment for the predicted Candida interactors. While the deregulated mouse genes were significantly enriched by the interolog-based inference step, the significant Candida genes were significantly depleted. This showed that for a vast number of pathogen-related genes in Candida, there were no interologous interactions found in the template networks. the sets of protein-coding genes, the primary inferred, the localization-filtered, and the functionally refined interactors of mouse. (D) Fraction of significantly deregulated genes in the sets of protein-coding genes, the primary inferred, the localization-filtered, and the biological process refined interactors of C. albicans. A test for enrichment of infection-regulated genes in the interactor sets after the primary inference, localization, and functional refinement step (Fisher exact test, * * * p< 0.001). Pathogenicity-Associated Genes are Enriched in Resulting Host-Fungi Networks Since databases even specialized on PHI contained very few PPI between human and fungal (mainly S. cerevisiae) pathogens , we extracted all human genes interacting with Archaean (0.03%), protozoan (0.3%), fungal (3.6%), or bacterial (96.1%) pathogen genes. Viral interactions were not included in our dataset as these interactions are mainly intracellular. This yielded pathogenicity-associations for 3,419 of the 20,688 protein-coding human genes which translates to a fraction of 16.5%. In contrast to the large number of human interactors, there were only 32 PHI mouse genes in the database. Because of the small number of mouse genes interacting with different pathogens, we focused on human as host. The network inference step with A. fumigatus as fungal pathogen enriched the pathogenicity-associated genes significantly to a fraction of 24.4% (see Figure 4A). Further, the localization filtering for potential host-fungal interfaces also enriched the pathogenicity-relevant genes significantly to a fraction of 32.2%. At last, the refinement step for interactors associated to pathogenicity-relevant processes enriched the fraction to 39.5% (see Figure 4A). For human interactors with C. albicans as pathogen, we observed a similar enrichment of pathogenicity-associated genes from the protein-coding genes (16.5%) over the inferred (24.4%) and the localization-filtered (33.3%) to the pathogenicity-associated process refined (39.3%) interactors (see Figure 4C). Due to the lack of knowledge about C. albicans and A. fumigatus PHIs, we exploited information of the databases PHI-base (Winnenburg et al., 2008) and PHIDIAS (Xiang et al., 2007) about experimentally validated virulence-associated genes. For the fungal pathogen A. fumigatus, we found 39 pathogenicityassociated genes in PHI-base and 29 genes in PHIDIAS (with an overlap of 14 genes), while for C. albicans 128 genes were found FIGURE 4 | Pathogenicity-associated genes in predicted host and fungi interactors. Fraction of pathogenicity-associated genes in the sets of protein-coding genes, the primary inferred, the localization-filtered and the biological process refined interactors of (A) H. sapiens (B) Aspergillus fumigatus (C) H. sapiens (D) C. albicans. A test for enrichment of pathogenicity-associated genes in the interactor sets after the primary inference, localization and functional refinement step (Fisher exact test, * p < 0.05; * * * p < 0.001). in PHI-base and 100 genes in PHIDIAS (with an overlap of 35 genes). For the fungal pathogen A. fumigatus, the fraction of pathogenicity-relevant genes (0.7%) interacting with human genes was not significant for the interolog-based inference step (0.7%), weakly significant for the localization filtering step (1.7%) and strongly significant for the infection-relevant process refinement step (12.1%), (see Figure 4B). Similarly, the fraction of pathogenicity-associated genes (1.6%) did not increase significantly via the interolog-based inference step (1.6%), but strongly significant for the localization filtering step (5.6%) and strongly significant for the infection-relevant process refinement step (26.3%), (see Figure 4D). Cells Involved in Immune Response and Tissues Typically Infected by Fungal Pathogens in the Resulting Host-Fungi PPI Networks The tissue enrichment of refined H. sapiens interactors with either C. albicans or A. fumigatus and the primary H. sapiens interactors yielded several fungal infection relevant tissues (see Supplementary Tables S5 and S6). For both pathogens the cell type "Platelet" was most significantly enriched. This correlates with an investigation that attachment of platelets to fungal surfaces induced morphological changes in Candida spp., such as loosening of discoid shape, generation of pseudopodia, and flattened structure (Robert et al., 2000). Similar findings were described for A. fumigatus showing that hyphal growth is likely to induce platelet activation (Rodland et al., 2010). More in particular, certain cell wall components of A. fumigatus, e.g., melanin and galactosaminogalactan were involved in platelet activation while hydrophobin prevented recognition from the host immune system (Rambach et al., 2015). Besides platelets, the immune system-associated terms "B-cell lymphoma, " "T-cell, " "Bcell, " "Leukemic T-cell, " and "Peripheral blood lymphocyte" were significantly enriched. Furthermore, we observed significantly enriched tissue terms of typical environments of Aspergillus and Candida infections in the human body ("Lung, " "Epithelium, " "Blood, " "Brain, " and "Skin"). Interestingly, the tissues "Urinary bladder" and "Cervix" but also "Bone" were significantly enriched (see Supplementary Table S6). Exploring the Refined Host-Fungi PPI Networks To obtain an overview of the resulting refined networks, we visualized the interactors grouped by the functional GO slim biological process classes. Hence, the nodes represent GO slim terms and edges depict interactions between host and fungal genes belonging to the particular GO slim terms. Since the refined networks were dominated by few fungal interactors showing very high numbers of interactions, the top 10% of high degree fungal interactors (C. albicans: HSP90, UBI4, SSB1, SSA2, CaJ7_0234; A. fumigatus: glyceraldehyde-3-phosphate dehydrogenase GpdA, molecular chaperone and allergen Mod-E/Hsp90/Hsp1, 14-3-3 family protein ArtA) were removed from the network visualizations to improve clearness and readability of the figures (see Figure 5 and Supplementary Figure S2). In the M. musculus (330 interactors) and C. albicans (37 interactors) network, "signal transduction, " "anatomical structure development, " "cell differentiation, " "response to stress, " and "transport" represent the host GO slim terms consisting of the largest numbers of genes. For Candida, the terms comprising of the most interactors were "pathogenesis, " "interspecies interaction between organisms, " "filamentous growth, " "response to stress, " and "carbohydrate metabolic process." As expected, large murine GO slim terms frequently interact with large fungal GO slim terms (e.g., 795 interactions between "signal transduction" and "regulation of biological process" or 767 between "signal transduction" and "interspecies interaction between organisms"; see Figure 5). In the refined PPI network with H. sapiens (317 interactors) and A. fumigatus (30 interactors), "signal transduction, " "transport, " "cellular nitrogen compound metabolic process, " "response to stress, " and "catabolic process" represent the host GO slim terms consisting of the largest numbers of genes. For Aspergillus, the terms comprising of the most interactors were "pathogenesis, " "response to stress, " "carbohydrate metabolic process, " "response to chemical stimulus, " and "cell cycle." Like for the mouse-Candida PPI network, large host GO slim terms frequently interact with large Aspergillus GO slim terms (e.g., 381 interactions between "signal transduction" and "pathogenesis" or 298 between "transport" and "pathogenesis"; see Supplementary Figure S2). Mouse-Candida Subnetworks Contain Infection Related Interaction Candidates To investigate these networks in more detail, we focused on the subnetwork between the pathogenicity-relevant GO slim terms "symbiosis, encompassing mutualism through parasitism" and "interspecies interaction between organisms" (see Figure 6). This subnetwork consists of 37 interactions with 23 murine interactors out of which one was infection regulated, and 12 C. albicans interactors of which three were infection regulated and eight supported by PHIDIAS/PHI-base evidence. For several interaction candidates, we found additional evidence in a literature research. ENO1 and Cd4 One of those is the Candida ENO1 (2-phospho-D-glyceratehydrolyase) interacting with the mouse Cd4 (CD4 antigen). The Cd4 molecule is an important co-receptor of T-lymphocytes that interacts with MHC Class II antigens. It is expressed in several immune cell types and initiates or augments the early phase of T-cell activation (Gibbings and Befus, 2009). The predicted interaction partner on the pathogen side, ENO1, is not only a key component of glycolysis (Sundstrom and Aliaga, 1992), but is also an immunodominant antigen circulating in the bloodstream of patients with disseminated Candida infections (Sundstrom and Aliaga, 1992) and a highly immunogenic protein in Candida-infected mice (Pitarch et al., 2001). Moreover, ENO1 was identified as an antigen that induced protective IgG2a antibody isotype in the sera from vaccinated animals and is thus considered a potential candidate for a vaccine (Fernandez-Arenas et al., 2004). Although ENO1 is primarily a cytoplasmic FIGURE 5 | Mus musculus-C. albicans network of functional GO terms. Nodes represent GO slim terms and edges depict interactions between host and fungal genes belonging to the particular GO slim terms. The node size denotes the number of genes in each GO slim term. The edge width and edge color correspond to the number of interactions between the connected nodes from thin/yellow to thick/red representing low to high interaction degrees. Fungal GO slim terms are visualized by green nodes and murine GO slim terms by blue nodes. The top 10% fungal pathogen interactors with the most interactions were removed from the network visualization to improve readability of the figure. The box shows the subnetworks that are evaluated in more detail. FIGURE 6 | Host-pathogen PPI subnetwork between M. musculus and C. albicans. This subnetwork comprises host interactors annotated as "symbiosis, encompassing mutualism through parasitism" and pathogen interactors annotated as "interspecies interaction between organisms." Blue nodes represent host interactors and green nodes fungal interactors. Nodes with a red border showed evidence for virulence contribution (PHIDIAS, PHI-base, and CGD). A triangular shape depicts infection-regulated genes of the analyzed mouse-Candida RNA-seq data. Interactions highlighted by red edges are described in more detail. protein, it has also been discovered to be an integral cell wall protein (Angiolella et al., 1996). Interestingly, another infectionassociated interaction partner in the refined PHI network is plasminogen, the inactive precursor of plasmin which has been described to facilitate the invasion of the host tissues (Jong et al., 2003). PLB1 and Alb A further interesting candidate is the interaction between the murine Alb (Albumin) and Candida PLB1 (Phospholipase B). It has been described that the extracellular part of PLB1 is required for wild-type virulence of Candida in a mouse model of systemic infection (Ghannoum, 1998), possibly related to its secretion from the hyphal tip during the infection process (Ghannoum, 2000). PLB1 can penetrate wild-type host cells by lysing the plasma membrane (Park et al., 2013). Its interaction partner on the host side, Albumin, was shown to bind to germ-tubes (Page and Odds, 1988) and to inhibit the binding of PLB1 to its substrate (Reisfeld et al., 1994). In the transcriptome data set of murine innate immune cells infected by C. albicans, PLB1 was significantly deregulated. HSP70 and Tlr2 Heat shock proteins have been described to play a role during fungal infection (Lopez-Ribot et al., 1996). Our results predict an interaction between the Candida HSP70 (Heat shock protein 70) and the murine Tlr2 (Toll-like receptor 2). The Candida HSP70 was detected on the surface of both yeast form and hyphal form cells and is a member of a protein family which represents highly conserved immunodominant antigens (La Valle et al., 1995). In vitro studies showed that a Candida HSP70 mutant caused less damage to endothelial cells and oral epithelial cell lines (Sun et al., 2010). On the host side Tlr2 plays an important role in the activation of the innate immunity: It belongs to the family of pattern recognition receptors (PRRs) which are involved in the recognition of pathogen-associated molecular patterns (PAMPs), (Oliveira-Nascimento et al., 2012). Interestingly, the transcripts of both interaction partners were differentially upregulated during the infection process in the mouse-Candida dual RNA-seq experiment. The mouse-Candida subnetwork of the host GO slim term "cell adhesion" and the fungal GO slim term "interspecies interaction between organisms" consisted of 98 interactions with 54 murine interactors (two significantly deregulated) and 16 C. albicans interacting partners (4 significantly deregulated, 11 supported by PHIDIAS/PHI-base evidence; see Supplementary Figure S3). PLB1 and App For the fungal PLB1 (Phospholipase B), we discovered a further potential interaction to the murine App . APP is a cell surface receptor that mediates cell-cell and cell-matrix adhesion (Stahl et al., 2014) and is cleaved by secretases to form a number of peptides. Although, the human APP is primarily known for its role in Alzheimer's Disease (Gorevic et al., 1986), some of the App peptides have antibiotic activity against at least eight common and clinically relevant microorganisms, i.e., Gram-negative, Gram-positive bacteria, and the yeast C. albicans with the latter being the most sensitive (Soscia et al., 2010). CDC19 and Egfr We also found evidence for a very interesting interaction between the fungal CDC19 protein (Pyruvate kinase CDC19) and the murine Egfr protein (epidermal growth factor receptor). The fungal interactor CDC19, usually, an enzyme of the glycolysis, was found to be present on the yeast-form cell surface of C. albicans (Pitarch et al., 2002) and differentially expressed after 3-h co-culture with murine macrophages (Fernandez-Arenas et al., 2007). Furthermore, it is an immunogenic protein that is specifically recognized by antibodies in sera of vaccinated and of systemically Candida-infected mice (Pitarch et al., 2001;Thomas et al., 2006;Martinez-Lopez et al., 2008). A homozygous null mutant showed decreased virulence and filamentous growth . Egfr is a transmembrane glycoprotein and receptor of the epidermal growth factor family. Egfr was shown to induce endocytosis of C. albicans by epithelial cells (Zhu et al., 2012). Furthermore, there is evidence for the secreted agrA (Accessory gene regulator protein A) of Staphylococcus aureus to bind to Egfr and activate a signal pathway in a pathogenicityassociated process (Gomez et al., 2007). Examples for Interesting Human-Aspergillus PPIs in the Resulting Host-Fungi Network Since very little is known about human-Aspergillus interactions in available databases up to date, we selected the infectionrelevant subnetwork of interactions between the host GO slim term "symbiosis, encompassing mutualism through parasitism" and the fungal GO slim term "pathogenesis." To get a transparent FIGURE 7 | Host-pathogen PPI subnetwork between H. sapiens and A. fumigatus. This subnetwork comprises pathogenicity-associated (HPIDB) host interactors annotated as "symbiosis, encompassing mutualism through parasitism" and pathogen interactors annotated as "pathogenesis." Blue nodes represent host interactors and green nodes fungal interactors. Nodes with a red border showed evidence for virulence contribution (PHIDIAS, PHI-base, and AspGD) or other host-pathogen interactions (HPIDB). Interactions highlighted by red edges were described in more detail. size, we visualized only host nodes pathogenicity-associated based on HPIDB and removed the human interactor UBC (ubiquitin C) due to the high number of interactions. This subnetwork consists of 38 interactions with 23 human interactors and 18 A. fumigatus interacting partners (three supported by PHIDIAS/PHI-base evidence; see Figure 7). RBE1 and CAV The interesting interaction between the human CAV1 (caveolin 1) and the Aspergillus AFUA_1G02040 (Uncharacterized protein) in that subnetwork was inferred from the human template CAV1 -GLIPR2 (GLI pathogenesis-related 2) detected by affinity chromatography technology (Eberle et al., 2002). The C. albicans ortholog of AFUA_1G02040, RBE1 (Repressed by EFG1 protein 1), is a Pry family cell wall protein and belongs to a group of plant pathogenesis-related proteins (PR-1; Rohm et al., 2013). A homozygote null mutant of RBE1 in Candida showed a decreased virulence and increased sensitivity to attack by polymorphonuclear leucocytes (Rohm et al., 2013). The human CAV1 is the major structural protein in the caveolae of endothelial cells (Smart et al., 1999). It is also involved in the costimulatory signal essential for T-cell receptor (TCR)-mediated T-cell activation (Ohnuma et al., 2007) and can act as a functional receptor for CD26 in antigen representing cells (Ohnuma et al., 2004) which implies a cell surface localization. HEX1 and FYN In the human-Aspergillus subnetwork, we predicted an interaction between the human FYN (FYN Proto-oncogene) and the Aspergillus AFUA_8G05020 (Uncharacterized protein). FYN is a membrane-associated tyrosine kinase (Morford et al., 2002) and localized in the endosome (Puertollano, 2005). Further, it plays an important role in T-cell activation (Lancki et al., 1995). The Aspergillus AFUA_8G05020 is a putative secreted N-acetylhexosaminidase (Bruns et al., 2010;Sharma et al., 2011) which is highly expressed in biofilm (Bruns et al., 2010). Furthermore, the C. albicans ortholog HEX1 is required for full virulence and these proteins may have a role in carbon or nitrogen scavenging (Niimi et al., 1997). Discussion Even though fungal infections are clinically highly relevant and impose a substantial disease burden worldwide , not much data about interactions between fungal pathogens and the human host on a molecular level are currently available. In our study, a comprehensive search of publically available PHIs (Kumar and Nanduri, 2010) yielded only a small number of reported host-fungi PPIs. Also, thorough searches of all major PPI databases for cross-species interaction revealed only a few fungal candidates. This obvious sparseness of established experimental data on molecular hostfungal interactions generates an important and valuable research challenge for novel PHI prediction approaches. While in silico methods for the prediction of molecular interactions between host and pathogenic organisms have been receiving growing attention in the last years, the main focus still lays on viral and bacterial pathogens (Zhou et al., 2013a), and fungal species have only been sparsely investigated. To our knowledge, a thorough systematic prediction and analysis of A. fumigatus and C. albicans interactions with the human and murine host has not been performed so far. In this study, we developed and examined an interologbased method for the prediction of fungal-host interactions. We focused our investigation on two of the most clinically relevant fungi C. albicans and A. fumigatus. Since murine mouse models have become an invaluable tool in medical research, we also investigated interactions between these fungi and M. musculus in addition to the human host. As the primary objective of our study was to attain a comprehensive catalog of high quality PHI predictions, we used an extended dual species template approach which is based on human and yeast, the two best studied species for PPI network. By this we effectively made use of the majority of all publically available PPI data. Compared to simple approaches relying on the yeast template only, we created a considerably enhanced prediction space, in particular on the host side, which increases the set of interactors for human and mouse by over 200%. A potential limitation of interspecies interolog approaches is the fact that the prediction space is confined to interactions between proteins with orthologs counterparts in the source network on either side. Hence, basing a prediction approach exclusively on the yeast network could lead to a bias toward ancient well conserved proteins and exclude less conserved 'newer' genes and pathways. These could include also hostspecific genes such as those involved in novel adaptive immune responses. The inclusion of the human template network partially alleviates those effects as, at least on the host side, no basal orthology relationship is required. Our results suggest that a large and in particular human based template network is a key prerequisite for the prediction of functionally more relevant interactions. Nevertheless, homology based approaches are known to be prone to produce overpredictions, since, in the first step, pairwise interactions are inferred between all homologs regardless of their cellular function or localization. Indeed, the predicted interaction partners on either side may in fact have little opportunity to physically interact with each other. This applies in particular to proteins which are expressed exclusively in the intracellular compartment and might thus have little opportunity to interact with the predicted host/pathogen counterpart. Although we applied a rigorous filtering cascade to exclude many (99.4%) of these potentially spurious interaction predictions, we noted that many proteins are expressed in various subcellular compartments. In particular, numerous intracellular proteins can shuttle to the membrane compartment or even be secreted. To narrow down this set of 'potentially physically possible' predictions, we focused on interactors involved in pathways which play important roles during cellular infection processes. Enrichment analyses using independent data (Xiang et al., 2007;Winnenburg et al., 2008;Kumar and Nanduri, 2010) revealed a clearly increasing fraction of virulence and pathogenicity-associated genes during the refinement process, suggesting a large set of functionally relevant interactions among the predictions. Moreover, on the host side we found an enrichment of genes which are expressed in tissues that are specifically affected by fungal infections, e.g., activation of platelets by A. fumigatus (Rodland et al., 2010) and C. albicans (Robert et al., 2000). Our extended interolog-based approach assembled a large catalog of PHIs. As this homology based approach is tied to the template interaction network, it is confined to the set of reported physical PPIs and thus also inherits the set false positives from the template network. Therefore, an interesting complementary approach would be the investigation of an approach based on domain-domain interactions (Zhou et al., 2013b). This would eliminate the necessity of homology for the predicted interactors, as it only requires the presence of the interacting domains. Thus, it can be expected to yield a complementary dataset. Similarly, inference methods based on the correlated gene expression in host and pathogen (e.g., measured over an infection time course), are an interesting approach which could be further explored, in combination with and in comparison to the interolog approach (Wang et al., 2013;Weber et al., 2013;Schulze et al., 2015). Certainly, the assembly of large PHI networks establishes an ample hypotheses space as a basis which can be exploited by advanced methods of integrative network analysis (Dittrich et al., 2008;Beisser et al., 2012), for which a large number of approaches have been established in the last years. Here, further development is needed to extend these approaches to the simultaneous analysis of the complex connected host and pathogen networks. Albeit, technically not trivial, it is unquestionably a worthwhile task as it holds the potential to link subcellular response pathways between host and pathogen during the dynamics of the infection process.
/** * Asserts Editor content and selection is as expected * * @param msg * @param expected * @param actualEditor */ protected void assertEditorContent(String msg, ContentWithSelection expected, Editor actualEditor) { EditorAssert.assertXmlEquals(msg, expected.content, ContentSerialisationUtil.getContentString(editor)); assertSelectionEquals(msg, expected, editor); }
// Edge Ctrl Listener port should use ZITI_EDGE_CONTROLLER_PORT if it is set func TestListenerAddressWhenEdgeCtrlPortAndListenerHostPortNotSet(t *testing.T) { myPort := "1234" expectedListenerAddress := "0.0.0.0:" + myPort _ = os.Unsetenv("ZITI_CTRL_EDGE_LISTENER_HOST_PORT") _ = os.Setenv("ZITI_EDGE_CONTROLLER_PORT", myPort) cmd := NewCmdCreateConfigController() _ = captureOutput(func() { _ = cmd.Execute() }) assert.Equal(t, expectedListenerAddress, data.Controller.Edge.ListenerHostPort) }
<reponame>parsa/cheap<gh_stars>10-100 /* libcheap.cpp enables easy use of regions invoke `region_begin(...)` --> all subsequent `malloc`s use the buffer, `free`s are ignored invoke `region_end()` --> back to normal `malloc`/`free` behavior see the C++ API in cheap.h */ #include <heaplayers.h> #include "cheap.h" #if defined(__APPLE__) #include "macinterpose.h" #endif #if defined(__APPLE__) #define LOCAL_PREFIX(x) xx##x #else #define LOCAL_PREFIX(x) x #endif CustomHeapType &getTheCustomHeap() { static CustomHeapType thang; return thang; } class cheap_current { private: cheap_current(); public: cheap_current(const cheap_current&) = delete; cheap_current& operator=(const cheap_current&) = delete; cheap_current(cheap_current &&) = delete; cheap_current & operator=(cheap_current &&) = delete; inline static auto*& current() { #if THREAD_SAFE static __thread cheap::cheap_base * c __attribute__((tls_model ("initial-exec"))); #else static cheap::cheap_base * c; #endif return c; } }; __attribute__((visibility("default"))) cheap::cheap_base*& current() { return cheap_current::current(); } #if 1 #define FLATTEN __attribute__((flatten)) #else #define FLATTEN #endif extern "C" size_t FLATTEN xxmalloc_usable_size(void *ptr) { auto ci = current(); if (likely(ci && ci->in_cheap)) { return ci->getSize(ptr); } return getTheCustomHeap().getSize(ptr); } extern "C" void * FLATTEN xxmalloc(size_t req_sz) __attribute__((alloc_size(1))) __attribute((malloc)); extern "C" void * FLATTEN xxmalloc(size_t req_sz) { size_t sz = req_sz; auto ci = current(); // tprintf::tprintf("xxmalloc(@) OH YEAH @\n", sz, ci); if (likely(ci && ci->in_cheap)) { auto ptr = ci->malloc(sz); // tprintf::tprintf("region malloc @ = @\n", sz, ptr); return ptr; } return getTheCustomHeap().malloc(sz); } extern "C" void FLATTEN xxfree(void *ptr) { auto ci = current(); if (unlikely(!ci || !ci->in_cheap)) { getTheCustomHeap().free(ptr); return; } return ci->free(ptr); } extern "C" void FLATTEN xxfree_sized(void *ptr, size_t) { xxfree(ptr); } extern "C" void * FLATTEN xxmemalign(size_t alignment, size_t sz) { auto ci = current(); if (likely(ci && ci->in_cheap)) { // Round up the region pointer to the required alignment. // auto bufptr = reinterpret_cast<uintptr_t>(ci->region.malloc(sz)); // FIXME THIS IS NOT ENOUGH // ci->region_buffer = // reinterpret_cast<char *>((bufptr + alignment - 1) & ~(alignment - 1)); return xxmalloc(sz); } return getTheCustomHeap().memalign(alignment, sz); } extern "C" void __attribute__((always_inline)) xxmalloc_lock() { getTheCustomHeap().lock(); } extern "C" void __attribute__((always_inline)) xxmalloc_unlock() { getTheCustomHeap().unlock(); } #if !defined(__APPLE__) #include "gnuwrapper.cpp" #endif
/// Parse a single NamedHeader value. pub fn parse_named_field_value<'a, E: ParseError<&'a [u8]>>( input: &'a [u8], ) -> IResult<&'a [u8], (Option<String>, Uri), E> { let (input, name) = opt(parse_name)(input)?; let (input, _) = opt(take_while(is_space))(input)?; let (input, _) = opt(char('<'))(input)?; let (input, value) = parse_uri(input)?; let (input, _) = opt(char('>'))(input)?; Ok((input, (name, value))) }
//---------------------------------------------------------------------------------------- // THIS CODE AND INFORMATION IS PROVIDED "AS-IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------- // Description: Declaration of Utility/Helper functions //---------------------------------------------------------------------------------------- #pragma once //---------------------------------------------------------------------------------------- // MISC UTILITY FUNCTIONS //---------------------------------------------------------------------------------------- UINT GetScanlineStride(UINT width, REFWICPixelFormatGUID pixelFormat); //---------------------------------------------------------------------------------------- // STREAM UTILITY FUNCTIONS //---------------------------------------------------------------------------------------- template< typename T > static HRESULT InputValue(IStream *stream, T &val) { HRESULT result = S_OK; if (NULL == stream) { result = E_INVALIDARG; } ULONG numRead = 0; if (SUCCEEDED(result)) { result = stream->Read(&val, sizeof(T), &numRead); } if (SUCCEEDED(result)) { result = (sizeof(T) == numRead) ? S_OK : E_UNEXPECTED; } return result; } template< typename T > static HRESULT InputValues(IStream *stream, T ptr, UINT count) { HRESULT result = S_OK; if (NULL == stream) { result = E_INVALIDARG; } ULONG numRead = 0; ULONG numToRead = sizeof(*ptr) * count; if (SUCCEEDED(result)) { result = stream->Read(ptr, numToRead, &numRead); } if (SUCCEEDED(result)) { result = (numToRead == numRead) ? S_OK : E_UNEXPECTED; } return result; } template< typename T > static HRESULT OutputValue(IStream *stream, T val) { HRESULT result = S_OK; if (NULL == stream) { result = E_INVALIDARG; } ULONG numWritten = 0; if (SUCCEEDED(result)) { result = stream->Write(&val, sizeof(T), &numWritten); } if (SUCCEEDED(result)) { result = (sizeof(T) == numWritten) ? S_OK : E_UNEXPECTED; } return result; } template< typename T > static HRESULT OutputValues(IStream *stream, T ptr, UINT count) { HRESULT result = S_OK; if (NULL == stream) { result = E_INVALIDARG; } ULONG numWritten = 0; ULONG numToWritten = sizeof(*ptr) * count; if (SUCCEEDED(result)) { result = stream->Write(ptr, numToWritten, &numWritten); } if (SUCCEEDED(result)) { result = (numToWritten == numWritten) ? S_OK : E_UNEXPECTED; } return result; }
''' For the table results aggregate results across context sizes But then generate a plot for each of the dataset size that shows performance for these tasks does not depend much on the context size ''' import numpy as np import joblib from collections import defaultdict import os.path as osp context_sizes = [1,2,3,4] # amounts = [(64,1), (64,20), (16,20), (4,20)] amounts = [(64,1)] sa_irl_results = { 'name': 'Meta-IRL (state-action)', (64,1): [ '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-sub-1-state-action-rew-search-normalized-fixed/hc_rand_vel_np_airl_64_demos_sub_1_state_action_rew_search_normalized_fixed_2019_04_18_17_20_04_0000--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-sub-1-state-action-rew-search-normalized-fixed/hc_rand_vel_np_airl_64_demos_sub_1_state_action_rew_search_normalized_fixed_2019_04_18_17_22_04_0001--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-sub-1-state-action-rew-search-normalized-fixed/hc_rand_vel_np_airl_64_demos_sub_1_state_action_rew_search_normalized_fixed_2019_04_18_17_26_05_0002--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-sub-1-state-action-rew-search-normalized-fixed/hc_rand_vel_np_airl_64_demos_sub_1_state_action_rew_search_normalized_fixed_2019_04_18_17_26_35_0003--s-0', ], (64,20): [ '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-rew-search-with-saving-more-rew-search/hc_rand_vel_np_airl_64_demos_rew_search_with_saving_more_rew_search_2019_04_14_22_27_53_0001--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-rew-search-with-saving-more-rew-search/hc_rand_vel_np_airl_64_demos_rew_search_with_saving_more_rew_search_2019_04_14_22_27_54_0004--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-rew-search-with-saving-more-rew-search/hc_rand_vel_np_airl_64_demos_rew_search_with_saving_more_rew_search_2019_04_14_22_27_54_0007--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-rew-search-with-saving-more-rew-search/hc_rand_vel_np_airl_64_demos_rew_search_with_saving_more_rew_search_2019_04_14_22_27_53_0010--s-0', ], (16,20): [ '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-16-demos-rew-search-with-saving-more-rew-search/hc_rand_vel_np_airl_16_demos_rew_search_with_saving_more_rew_search_2019_04_15_16_03_04_0001--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-16-demos-rew-search-with-saving-more-rew-search/hc_rand_vel_np_airl_16_demos_rew_search_with_saving_more_rew_search_2019_04_15_16_06_43_0004--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-16-demos-rew-search-with-saving-more-rew-search/hc_rand_vel_np_airl_16_demos_rew_search_with_saving_more_rew_search_2019_04_15_16_33_52_0007--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-16-demos-rew-search-with-saving-more-rew-search/hc_rand_vel_np_airl_16_demos_rew_search_with_saving_more_rew_search_2019_04_15_16_57_06_0010--s-0', ], (4,20): [ '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-4-demos-rew-search-with-saving-more-rew-search/hc_rand_vel_np_airl_4_demos_rew_search_with_saving_more_rew_search_2019_04_20_13_22_53_0000--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-4-demos-rew-search-with-saving-more-rew-search/hc_rand_vel_np_airl_4_demos_rew_search_with_saving_more_rew_search_2019_04_20_13_22_53_0001--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-4-demos-rew-search-with-saving-more-rew-search/hc_rand_vel_np_airl_4_demos_rew_search_with_saving_more_rew_search_2019_04_20_13_22_54_0002--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-4-demos-rew-search-with-saving-more-rew-search/hc_rand_vel_np_airl_4_demos_rew_search_with_saving_more_rew_search_2019_04_20_13_22_54_0003--s-0', ] } s_irl_results = { 'name': 'Meta-IRL (state-only)', (64,1): [ '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-sub-1-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_64_demos_sub_1_state_only_rew_search_normalized_correct_2019_04_20_00_00_12_0001--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-sub-1-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_64_demos_sub_1_state_only_rew_search_normalized_correct_2019_04_20_00_00_12_0002--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-sub-1-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_64_demos_sub_1_state_only_rew_search_normalized_correct_2019_04_20_00_00_13_0000--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-sub-1-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_64_demos_sub_1_state_only_rew_search_normalized_correct_2019_04_20_00_01_42_0003--s-0', ], (64,20): [ '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-sub-20-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_64_demos_sub_20_state_only_rew_search_normalized_correct_2019_04_20_00_02_42_0000--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-sub-20-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_64_demos_sub_20_state_only_rew_search_normalized_correct_2019_04_20_00_22_13_0001--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-sub-20-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_64_demos_sub_20_state_only_rew_search_normalized_correct_2019_04_20_00_25_13_0002--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-64-demos-sub-20-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_64_demos_sub_20_state_only_rew_search_normalized_correct_2019_04_20_00_26_13_0003--s-0', ], (16,20): [ '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-16-demos-sub-20-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_16_demos_sub_20_state_only_rew_search_normalized_correct_2019_04_20_00_26_13_0000--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-16-demos-sub-20-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_16_demos_sub_20_state_only_rew_search_normalized_correct_2019_04_20_00_35_13_0001--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-16-demos-sub-20-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_16_demos_sub_20_state_only_rew_search_normalized_correct_2019_04_20_00_46_43_0002--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-16-demos-sub-20-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_16_demos_sub_20_state_only_rew_search_normalized_correct_2019_04_20_00_47_43_0003--s-0', ], (4,20): [ '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-4-demos-sub-20-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_4_demos_sub_20_state_only_rew_search_normalized_correct_2019_04_20_13_21_24_0000--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-4-demos-sub-20-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_4_demos_sub_20_state_only_rew_search_normalized_correct_2019_04_20_13_21_25_0001--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-4-demos-sub-20-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_4_demos_sub_20_state_only_rew_search_normalized_correct_2019_04_20_13_21_25_0002--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-np-airl-4-demos-sub-20-state-only-rew-search-normalized-correct/hc_rand_vel_np_airl_4_demos_sub_20_state_only_rew_search_normalized_correct_2019_04_20_13_21_26_0003--s-0', ] } # MLE version # bc_results = { # 'name': 'Meta-BC', # (64,1): [ # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-64-demos-sub-1-no-norm-with-saving/hc_rand_vel_64_demos_sub_1_no_norm_with_saving_2019_04_19_21_36_41_0000--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-64-demos-sub-1-no-norm-with-saving/hc_rand_vel_64_demos_sub_1_no_norm_with_saving_2019_04_19_21_36_41_0001--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-64-demos-sub-1-no-norm-with-saving/hc_rand_vel_64_demos_sub_1_no_norm_with_saving_2019_04_19_21_36_41_0002--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-64-demos-sub-1-no-norm-with-saving/hc_rand_vel_64_demos_sub_1_no_norm_with_saving_2019_04_19_21_36_41_0003--s-0', # ], # (64,20): [ # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-64-demos-sub-20-no-norm-with-saving/hc_rand_vel_64_demos_sub_20_no_norm_with_saving_2019_04_19_21_41_10_0002--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-64-demos-sub-20-no-norm-with-saving/hc_rand_vel_64_demos_sub_20_no_norm_with_saving_2019_04_19_21_41_11_0000--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-64-demos-sub-20-no-norm-with-saving/hc_rand_vel_64_demos_sub_20_no_norm_with_saving_2019_04_19_21_41_11_0001--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-64-demos-sub-20-no-norm-with-saving/hc_rand_vel_64_demos_sub_20_no_norm_with_saving_2019_04_19_21_41_11_0003--s-0', # ], # (16,20): [ # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-16-demos-sub-20-no-norm-with-saving/hc_rand_vel_16_demos_sub_20_no_norm_with_saving_2019_04_19_21_38_40_0003--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-16-demos-sub-20-no-norm-with-saving/hc_rand_vel_16_demos_sub_20_no_norm_with_saving_2019_04_19_21_38_41_0000--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-16-demos-sub-20-no-norm-with-saving/hc_rand_vel_16_demos_sub_20_no_norm_with_saving_2019_04_19_21_38_41_0001--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-16-demos-sub-20-no-norm-with-saving/hc_rand_vel_16_demos_sub_20_no_norm_with_saving_2019_04_19_21_38_41_0002--s-0', # ], # (4,20): [ # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-4-demos-sub-20-no-norm-with-saving/hc_rand_vel_4_demos_sub_20_no_norm_with_saving_2019_04_19_22_22_41_0001--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-4-demos-sub-20-no-norm-with-saving/hc_rand_vel_4_demos_sub_20_no_norm_with_saving_2019_04_19_22_22_41_0002--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-4-demos-sub-20-no-norm-with-saving/hc_rand_vel_4_demos_sub_20_no_norm_with_saving_2019_04_19_22_22_41_0003--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-4-demos-sub-20-no-norm-with-saving/hc_rand_vel_4_demos_sub_20_no_norm_with_saving_2019_04_19_22_22_43_0000--s-0', # ] # } # MSE version bc_results = { 'name': 'Meta-BC', (64,1): [ '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-64-demos-sub-1-paper-version/hc_rand_vel_mse_64_demos_sub_1_paper_version_2019_05_25_15_00_00_0000--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-64-demos-sub-1-paper-version/hc_rand_vel_mse_64_demos_sub_1_paper_version_2019_05_25_15_00_01_0001--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-64-demos-sub-1-paper-version/hc_rand_vel_mse_64_demos_sub_1_paper_version_2019_05_25_15_00_01_0002--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-64-demos-sub-1-paper-version/hc_rand_vel_mse_64_demos_sub_1_paper_version_2019_05_25_15_00_02_0003--s-0', ], (64,20): [ '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-64-demos-sub-20-paper-version/hc_rand_vel_mse_64_demos_sub_20_paper_version_2019_05_25_14_59_10_0000--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-64-demos-sub-20-paper-version/hc_rand_vel_mse_64_demos_sub_20_paper_version_2019_05_25_14_59_12_0001--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-64-demos-sub-20-paper-version/hc_rand_vel_mse_64_demos_sub_20_paper_version_2019_05_25_14_59_12_0002--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-64-demos-sub-20-paper-version/hc_rand_vel_mse_64_demos_sub_20_paper_version_2019_05_25_14_59_13_0003--s-0', ], (16,20): [ '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-16-demos-sub-20-paper-version/hc_rand_vel_mse_16_demos_sub_20_paper_version_2019_05_25_14_58_30_0000--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-16-demos-sub-20-paper-version/hc_rand_vel_mse_16_demos_sub_20_paper_version_2019_05_25_14_58_31_0001--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-16-demos-sub-20-paper-version/hc_rand_vel_mse_16_demos_sub_20_paper_version_2019_05_25_14_58_31_0002--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-16-demos-sub-20-paper-version/hc_rand_vel_mse_16_demos_sub_20_paper_version_2019_05_25_14_58_33_0003--s-0', ], (4,20): [ '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-4-demos-sub-20-paper-version/hc_rand_vel_mse_4_demos_sub_20_paper_version_2019_05_25_14_57_46_0000--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-4-demos-sub-20-paper-version/hc_rand_vel_mse_4_demos_sub_20_paper_version_2019_05_25_14_57_46_0001--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-4-demos-sub-20-paper-version/hc_rand_vel_mse_4_demos_sub_20_paper_version_2019_05_25_14_57_47_0002--s-0', '/scratch/hdd001/home/kamyar/output/hc-rand-vel-mse-4-demos-sub-20-paper-version/hc_rand_vel_mse_4_demos_sub_20_paper_version_2019_05_25_14_57_47_0003--s-0', ] } # Dagger MSE version dagger_results = { 'name': 'Meta-Dagger', (64,1): [ '/scratch/hdd001/home/kamyar/output/correct-hc-rand-vel-meta-dagger-use-z-sample-det-expert-MSE-64-demos-sub-1-100-updates-per-call/correct_hc_rand_vel_meta_dagger_use_z_sample_det_expert_MSE_64_demos_sub_1_100_updates_per_call_2019_07_28_16_29_06_0000--s-0', '/scratch/hdd001/home/kamyar/output/correct-hc-rand-vel-meta-dagger-use-z-sample-det-expert-MSE-64-demos-sub-1-100-updates-per-call/correct_hc_rand_vel_meta_dagger_use_z_sample_det_expert_MSE_64_demos_sub_1_100_updates_per_call_2019_07_28_16_29_07_0001--s-0', '/scratch/hdd001/home/kamyar/output/correct-hc-rand-vel-meta-dagger-use-z-sample-det-expert-MSE-64-demos-sub-1-100-updates-per-call/correct_hc_rand_vel_meta_dagger_use_z_sample_det_expert_MSE_64_demos_sub_1_100_updates_per_call_2019_07_28_16_29_09_0002--s-0', ] } # MLE version # bc_results = { # 'name': 'Meta-BC', # (64,1): [ # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-64-demos-sub-1-paper-version/hc_rand_vel_MLE_64_demos_sub_1_paper_version_2019_05_25_16_47_11_0000--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-64-demos-sub-1-paper-version/hc_rand_vel_MLE_64_demos_sub_1_paper_version_2019_05_25_16_47_11_0001--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-64-demos-sub-1-paper-version/hc_rand_vel_MLE_64_demos_sub_1_paper_version_2019_05_25_16_47_11_0002--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-64-demos-sub-1-paper-version/hc_rand_vel_MLE_64_demos_sub_1_paper_version_2019_05_25_16_47_12_0003--s-0', # ], # (64,20): [ # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-64-demos-sub-20-paper-version/hc_rand_vel_MLE_64_demos_sub_20_paper_version_2019_05_25_16_47_49_0000--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-64-demos-sub-20-paper-version/hc_rand_vel_MLE_64_demos_sub_20_paper_version_2019_05_25_16_47_50_0001--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-64-demos-sub-20-paper-version/hc_rand_vel_MLE_64_demos_sub_20_paper_version_2019_05_25_16_47_50_0002--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-64-demos-sub-20-paper-version/hc_rand_vel_MLE_64_demos_sub_20_paper_version_2019_05_25_16_47_51_0003--s-0', # ], # (16,20): [ # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-16-demos-sub-20-paper-version/hc_rand_vel_MLE_16_demos_sub_20_paper_version_2019_05_25_16_48_27_0000--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-16-demos-sub-20-paper-version/hc_rand_vel_MLE_16_demos_sub_20_paper_version_2019_05_25_16_48_28_0001--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-16-demos-sub-20-paper-version/hc_rand_vel_MLE_16_demos_sub_20_paper_version_2019_05_25_16_48_28_0002--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-16-demos-sub-20-paper-version/hc_rand_vel_MLE_16_demos_sub_20_paper_version_2019_05_25_16_48_29_0003--s-0', # ], # (4,20): [ # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-4-demos-sub-20-paper-version/hc_rand_vel_MLE_4_demos_sub_20_paper_version_2019_05_25_16_48_59_0000--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-4-demos-sub-20-paper-version/hc_rand_vel_MLE_4_demos_sub_20_paper_version_2019_05_25_16_49_00_0001--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-4-demos-sub-20-paper-version/hc_rand_vel_MLE_4_demos_sub_20_paper_version_2019_05_25_16_49_00_0002--s-0', # '/scratch/hdd001/home/kamyar/output/hc-rand-vel-MLE-4-demos-sub-20-paper-version/hc_rand_vel_MLE_4_demos_sub_20_paper_version_2019_05_25_16_49_01_0003--s-0', # ] # } # for method in [sa_irl_results, s_irl_results, bc_results]: # print('\n{}'.format(method['name'])) # for amount in [(64,1), (64,20), (16,20), (4,20)]: # d = joblib.load() def gather_run_costs_for_context_size(d, c_size): l = [] for task_d in d.values(): l.extend(task_d[c_size]['run_costs']) return l # gather the results def gather_results(method_paths): new_dict = {} for data_amount in amounts: print('\t{}'.format(data_amount)) amount_dict = defaultdict(list) for path in method_paths[data_amount]: print('\t\tGathering: {}'.format(path)) try: d = joblib.load(osp.join(path, 'all_eval_stats.pkl'))['all_eval_stats'][0] except: print('FAILED {}'.format(path)) continue for c in context_sizes: l = gather_run_costs_for_context_size(d, c) amount_dict[c].extend(l) new_dict[data_amount] = amount_dict return new_dict # # IF YOU WANT TO REGATHER RESULTS RUN THIS # save_dict = {} # # for method in [sa_irl_results, s_irl_results, bc_results]: # # for method in [bc_results]: # for method in [dagger_results]: # print(method['name']) # save_dict[method['name']] = gather_results(method) # joblib.dump(save_dict, 'hc_rand_vel_save_dict_with_mse_dagger.pkl', compress=3) # ELSE # save_dict = joblib.load('hc_rand_vel_save_dict.pkl') save_dict = joblib.load('hc_rand_vel_save_dict_with_mse_dagger.pkl') print(save_dict.keys()) # save_dict.update(joblib.load('hc_rand_vel_save_dict_mse_bc.pkl')) # save_dict = joblib.load('hc_rand_vel_save_dict_with_mse_bc.pkl') for name, method_d in save_dict.items(): print('\n') print(name) for amount, amount_d in method_d.items(): print('\t{}'.format(amount)) all_run_costs = [] for context_size, costs in amount_d.items(): all_run_costs.extend(costs) print('\t\tDelta: %.3f +/- %.3f' % (np.mean(all_run_costs)/1000, np.std(all_run_costs)/1000)) # plot some things import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt data_amount_to_plot = (64,1) context_means = defaultdict(list) context_stds = defaultdict(list) for name, method_d in save_dict.items(): # print(name) # print(method_d) for context_size in context_sizes: context_means[name].append( np.mean( method_d[data_amount_to_plot][context_size] ) / 1000.0 ) context_stds[name].append( np.std( method_d[data_amount_to_plot][context_size] ) / 1000.0 ) # print(context_means) # print(context_stds) fig, ax = plt.subplots(1) ax.set_xlabel('Number of Context Trajectories') ax.set_ylabel('Delta from Target Velocity') # ax.set_ylim([0.0, 1.6]) ax.set_ylim([0.0, 0.75]) print(context_means.keys()) # print(len(context_means['bc'])) # ax.errorbar( # np.array(list(range(1,5))), context_means['Meta-BC'], context_stds['Meta-BC'], # elinewidth=2.0, capsize=4.0, barsabove=True, linewidth=2.0, label='Meta-BC' # ) # ax.errorbar( # np.array(list(range(1,5))) + 0.03, context_means['Meta-IRL (state-action)'], context_stds['Meta-IRL (state-action)'], # elinewidth=2.0, capsize=4.0, barsabove=True, linewidth=2.0, label='Meta-IRL (state-action)' # ) # ax.errorbar( # np.array(list(range(1,5))) + 0.06, context_means['Meta-IRL (state-action)'], context_stds['Meta-IRL (state-action)'], # elinewidth=2.0, capsize=4.0, barsabove=True, linewidth=2.0, label='Meta-IRL (state-only)' # ) ax.errorbar( np.array(list(range(1,5))) + 0.06, context_means['Meta-Dagger'], context_stds['Meta-Dagger'], elinewidth=2.0, capsize=4.0, barsabove=True, linewidth=2.0, label='Meta-Dagger' ) # lgd = ax.legend(loc='upper center', bbox_to_anchor=(0.725, 0.1), shadow=False, ncol=3) lgd = ax.legend(loc='upper right', shadow=False, ncol=1) # plt.savefig('hc_context_size_plot.png', bbox_extra_artists=(lgd,), bbox_inches='tight') plt.savefig('hc_rand_vel_dagger_context_size_plot.png', bbox_extra_artists=(lgd,), bbox_inches='tight') plt.close()
package com.worldbiomusic.allgames.games.solobattle; import java.util.ArrayList; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.Sound; import org.bukkit.entity.Arrow; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.entity.Zombie; import org.bukkit.event.Event; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import com.wbm.plugin.util.InventoryTool; import com.wbm.plugin.util.Metrics; import com.wbm.plugin.util.ParticleTool; import com.wbm.plugin.util.SoundTool; import com.worldbiomusic.allgames.AllMiniGamesMain; import com.worldbiomusic.minigameworld.minigameframes.SoloBattleMiniGame; import com.worldbiomusic.minigameworld.minigameframes.helpers.MiniGameCustomOption.Option; public class SuperMob extends SoloBattleMiniGame { private Zombie superMob; private List<Entity> entities; double skillChance; public SuperMob() { super("SuperMob", 2, 10, 60 * 2, 30); // bstats new Metrics(AllMiniGamesMain.getInstance(), 14396); this.entities = new ArrayList<>(); // settings getSetting().setIcon(Material.ZOMBIE_HEAD); getSetting().addCustomDetectableEvent(EntityDeathEvent.class); // options getCustomOption().set(Option.INVENTORY_SAVE, true); getCustomOption().set(Option.PVP, false); getCustomOption().set(Option.COLOR, ChatColor.RED); registerTask(); } private void registerTask() { // random targeting task getTaskManager().registerTask("changeTarget", new Runnable() { @Override public void run() { int r = (int) (Math.random() * getPlayerCount()); superMob.setTarget(getPlayers().get(r)); } }); } @Override protected void initGame() { this.killAllEntities(); this.skillChance = 0.1; } private void killAllEntities() { this.entities.forEach(e -> e.remove()); this.entities.clear(); } @SuppressWarnings("deprecation") @Override protected void onStart() { super.onStart(); // give kits for (Player p : this.getPlayers()) { InventoryTool.addItemToPlayer(p, new ItemStack(Material.IRON_SWORD)); InventoryTool.addItemToPlayer(p, new ItemStack(Material.COOKED_PORKCHOP, 20)); InventoryTool.addItemToPlayer(p, new ItemStack(Material.BOW)); InventoryTool.addItemToPlayer(p, new ItemStack(Material.ARROW, 64)); InventoryTool.addItemToPlayer(p, new ItemStack(Material.GOLDEN_APPLE)); p.getEquipment().setHelmet(new ItemStack(Material.IRON_HELMET)); p.getEquipment().setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); p.getEquipment().setLeggings(new ItemStack(Material.IRON_LEGGINGS)); p.getEquipment().setBoots(new ItemStack(Material.IRON_BOOTS)); p.getEquipment().setItemInOffHand(new ItemStack(Material.SHIELD)); } // spawn super mob this.superMob = (Zombie) this.getLocation().getWorld().spawnEntity(this.getLocation(), EntityType.ZOMBIE); this.superMob.setMaxHealth(100_000_000); this.superMob.setHealth(this.superMob.getMaxHealth()); this.superMob.getEquipment().setItemInMainHand(new ItemStack(Material.STONE_SWORD)); this.superMob.getEquipment().setHelmet(new ItemStack(Material.IRON_HELMET)); this.superMob.getEquipment().setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); this.superMob.getEquipment().setLeggings(new ItemStack(Material.IRON_LEGGINGS)); this.superMob.getEquipment().setBoots(new ItemStack(Material.IRON_BOOTS)); this.superMob.setBaby(true); // glow this.superMob.setGlowing(true); // add to list this.entities.add(this.superMob); // run random targeting task this.getTaskManager().runTaskTimer("changeTarget", 0, 20 * 60); } @Override protected void onFinish() { super.onFinish(); this.killAllEntities(); } @Override protected void onEvent(Event event) { // custom detectable event if (event instanceof EntityDeathEvent) { onMobDeath((EntityDeathEvent) event); } else if (event instanceof EntityDamageEvent) { if (((EntityDamageEvent) event).getEntity() instanceof Player) { onPlayerDamaged((EntityDamageEvent) event); } else if (event instanceof EntityDamageByEntityEvent) { onSuperMobDamaged((EntityDamageByEntityEvent) event); } } } private void onMobDeath(EntityDeathEvent e) { if (this.entities.contains(e.getEntity())) { Entity killer = e.getEntity().getKiller(); if (killer == null) { return; } Player killerPlayer = null; if (!(killer instanceof Player)) { return; } killerPlayer = (Player) killer; this.plusScore(killerPlayer, 5); e.getDrops().clear(); } } private void onPlayerDamaged(EntityDamageEvent e) { Player p = (Player) e.getEntity(); // if death if (p.getHealth() <= e.getDamage()) { // cancel damage e.setDamage(0); sendTitle(p, ChatColor.GREEN + "Respawn", ""); SoundTool.play(p.getLocation(), Sound.BLOCK_NOTE_BLOCK_BELL); this.setLive(p, false); } } private void onSuperMobDamaged(EntityDamageByEntityEvent e) { if (!(e.getEntity() instanceof Zombie)) { return; } Zombie zombie = (Zombie) e.getEntity(); if (!this.superMob.equals(zombie)) { return; } // direct damage if (e.getDamager() instanceof Player) { this.whenSuperMobDamagedByPlayer(e, (Player) e.getDamager()); } // projectile damage else if (e.getDamager() instanceof Arrow) { Arrow proj = (Arrow) e.getDamager(); if (!(proj.getShooter() instanceof Player)) { return; } Player shooter = (Player) proj.getShooter(); if (!this.containsPlayer(shooter)) { return; } this.whenSuperMobDamagedByPlayer(e, shooter); } } private void whenSuperMobDamagedByPlayer(EntityDamageByEntityEvent e, Player p) { int damage = (int) e.getDamage(); if (damage > 0) { // plus score this.plusScore(p, damage); } // use skill if (Math.random() < this.skillChance) { this.useSkill(); this.skillChance += 0.01; } // set target player this.superMob.setTarget(p); } public enum Mode { ATTACK, DEFENSE, FAST; public static Mode random() { switch ((int) (Math.random() * 3)) { case 0: return ATTACK; case 1: return DEFENSE; default: return FAST; } } } private void useSkill() { int r = (int) (Math.random() * 2); switch (r) { case 0: this.spawnFriends(); break; case 1: this.useMode(Mode.random()); break; } // etc SoundTool.play(getPlayers(), Sound.BLOCK_BELL_USE); ParticleTool.spawn(this.superMob.getLocation(), Particle.FLAME, 50, 0.2); } private void spawnFriends() { int amount = this.getPlayerCount(); Location loc = this.superMob.getLocation(); for (int i = 0; i < amount; i++) { this.spawnMob(loc, EntityType.ZOMBIE); this.spawnMob(loc, EntityType.SKELETON); this.spawnMob(loc, EntityType.SPIDER); } sendMessages(ChatColor.RED + "SuperMob invites friends"); } private void spawnMob(Location loc, EntityType type) { // add to entities List this.entities.add(loc.getWorld().spawnEntity(loc, type)); } private void useMode(Mode mode) { switch (mode) { case ATTACK: this.useAttackMode(); break; case DEFENSE: this.useDefenseMode(); break; case FAST: this.useFastMode(); break; } } private void useAttackMode() { this.superMob.addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, 20 * 10, 0)); this.sendMessages(ChatColor.RED + "SuperMob uses attack mode"); } private void useDefenseMode() { this.superMob.addPotionEffect(new PotionEffect(PotionEffectType.DAMAGE_RESISTANCE, 20 * 10, 0)); this.sendMessages(ChatColor.RED + "SuperMob uses defense mode"); } private void useFastMode() { this.superMob.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 20 * 10, 0)); this.sendMessages(ChatColor.RED + "SuperMob uses fast mode"); } @Override protected List<String> tutorial() { List<String> tutorial = new ArrayList<>(); tutorial.add("Hit Super Mob: +(damage)"); tutorial.add("Super mob has some skills: ATTACK, DEFENSE, FAST, FRIENDSHIP"); return tutorial; } } // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //
<gh_stars>1-10 package envs import ( "bufio" "fmt" "log" "os" "strconv" "strings" ) type EnvConfig map[string]string // Get returns an environment variable value as a string func (c EnvConfig) Get(key string, defaultValue ...string) string { value, ok := c[key] if !ok && len(defaultValue) > 0 { return defaultValue[0] } return value } // GetBool returns an environment variable value as a boolean field func (c EnvConfig) GetBool(key string, defaultValue ...bool) bool { value, ok := c[key] if !ok && len(defaultValue) > 0 { return defaultValue[0] } res, err := strconv.ParseBool(value) if err != nil { log.Fatal(fmt.Sprintf("Failed to parse key %s to boolean - ", key), err) } return res } // GetFloat returns an environment variable value as a float func (c EnvConfig) GetFloat(key string, defaultValue ...float32) float32 { value, ok := c[key] if !ok && len(defaultValue) > 0 { return defaultValue[0] } res, err := strconv.ParseFloat(value, 32) if err != nil { log.Fatal(fmt.Sprintf("Failed to parse key %s to float - ", key), err) } return float32(res) } // GetInt returns an environment variable value as an integer func (c EnvConfig) GetInt(key string, defaultValue ...int) int { value, ok := c[key] if !ok && len(defaultValue) > 0 { return defaultValue[0] } res, err := strconv.Atoi(value) if err != nil { log.Fatal(fmt.Sprintf("Failed to parse key %s to integer - ", key), err) } return res } // GetMap returns an environment variable value as a map of strings func (c EnvConfig) GetMap(key string, defaultValue ...map[string]string) map[string]string { value, ok := c[key] if !ok && len(defaultValue) > 0 { return defaultValue[0] } pairs := strings.Split(value, ";") result := make(map[string]string, len(pairs)) for _, pair := range pairs { keyVal := strings.Split(pair, ":") result[keyVal[0]] = keyVal[1] } return result } // GetSlice returns an environment variable value as a slice of strings func (c EnvConfig) GetSlice(key string, defaultValue ...[]string) []string { value, ok := c[key] if !ok && len(defaultValue) > 0 { return defaultValue[0] } return strings.Split(value, ",") } // GetSliceFloat returns an environment variable value as a slice of floats func (c EnvConfig) GetSliceFloat(key string, defaultValue ...[]float32) []float32 { value, ok := c[key] if !ok && len(defaultValue) > 0 { return defaultValue[0] } nums := strings.Split(value, ",") result := make([]float32, len(nums)) for i, num := range nums { flo64, err := strconv.ParseFloat(num, 32) if err != nil { log.Fatal(fmt.Sprintf("Failed to parse key %s to slice of floats - ", key), err) } result[i] = float32(flo64) } return result } // GetSliceInt returns an environment variable value as a slice of integers func (c EnvConfig) GetSliceInt(key string, defaultValue ...[]int) []int { value, ok := c[key] if !ok && len(defaultValue) > 0 { return defaultValue[0] } nums := strings.Split(value, ",") var ( err error result = make([]int, len(nums)) ) for i, num := range nums { result[i], err = strconv.Atoi(num) if err != nil { log.Fatal(fmt.Sprintf("Failed to parse key %s to slice of integers - ", key), err) } } return result } // ReadEnvs obtains firstly from the file .env and then from environment variables to rewrite got from the file func (c EnvConfig) ReadEnvs() { file, err := os.Open(".env") if err != nil { log.Println("Failed to read file, read from all environment variables -", err) for _, env := range os.Environ() { keyValuePair := strings.SplitN(env, "=", 2) c[keyValuePair[0]] = keyValuePair[1] } return } defer func(file *os.File) { if err = file.Close(); err != nil { log.Fatal("Failed to close file -", err) } }(file) scanner := bufio.NewScanner(file) for scanner.Scan() { text := scanner.Text() if !strings.HasPrefix(text, "#") && text != "" { keyValuePair := strings.SplitN(text, "=", 2) c[keyValuePair[0]] = keyValuePair[1] } } if err = scanner.Err(); err != nil { log.Fatal("Failed to scan file -", err) } for key := range c { if value, exist := os.LookupEnv(key); exist { c[key] = value } } }
If humans are going to get to Mars, they're going to need rockets with some serious liftoff power. NASA’s Space Launch System is the most powerful rocket in the world—it has twin five-segment solid rocket boosters, four liquid propellant engines, and a minimum of 70 metric tons of lifting power—but engineers won’t know until June 28th if it’s really going to work. At 8:05 am MDT on Tuesday, SLS will undergo a qualification ground test at Orbital ATK’s facilities in Utah that will see if its systems are up to snuff. And scientists are setting a high bar. The qualification testing has over 80 objectives—basically, everything but launching skyward—to determine whether SLS is ready to send the Orion spacecraft on the first leg of Exploration Mission-1, an unmanned mission planned for 2018. EM-1 will take Orion 40,000 miles beyond the moon, which is further than any spacecraft built for humans has ever gone. But EM-1, and the manned missions planned for the 2020s, can't happen unless SLS can get them off the ground. Granted, everyone's pretty sure that it will be able to. This test is the fifth of five. And it's the second of two qualification tests, which are more about how the boosters will perform than if. Tuesday's burn is mostly a test of the engines to see how much power they provide when the propellant is at a low temperature of about 40 degrees Fahrenheit (so that's Florida cold, not space cold). The last qualification test back in March tested hot motor performance, with propellant at 90 degrees. NASA Which is not to say that designing, building, and proving SLS—which draws on the retired shuttle program's launch systems—has been a cinch. "The rocket looks a lot like the one in the museum, but that's about all that's the same: the outside," says Fred Brasfield, Orbital ATK's SLS Boosters lead. Not only did engineers have to determine whether the space shuttle tech was still up to the task, they also overhauled the avionics system (Brasfield calls the '70s version "basically analog"), updated the nozzle, and pretty much everything going on inside. Take just the insulation: NASA and Orbital ATK had to make it safer by getting rid of voids that might expand under high temperatures. They also had to make it more environmentally friendly (and 10,000 pounds lighter) by eliminating asbestos. But the rubber asbestos replacement had a tendency to evolve gases—and you really don't want any unexpected additions to your rocket fuel. Computing power and environmental impact are only a small part of the story. SLS has to be capable of so much more than its shuttle program predecessors. "It's almost a totally different mession," says Alex Priskos, NASA SLS Boosters Manager. "One is designed to go the store, and one is designed to go halfway across the country." The massively increased velocity and power—both boosters produce 3.6 million pounds of thrust each—means massively increased loads. SLS has to be very precisely controlled if it's going to avoid ripping itself to pieces. That's why NASA has been taking a more tortoise than hare approach with these deep space missions. "This test is part of a deliberate buildup approach," says Mike Sarafin, EM-1 mission manager. "We're going to go past the GPS system constellation, beyond the Tracking and Data Relay Satellite, beyond the Earth's magnetic field. Until we demo, there's going to be a lot of uncertainty." If this test goes well, it should remove another whisper of that uncertainty, and bring Mars that much closer.
/* * Copyright (c) 2021, <NAME> <<EMAIL>> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/Format.h> #include <Kernel/Arch/x86/Processor.h> #include <Kernel/CommandLine.h> #include <Kernel/KSyms.h> #include <Kernel/Panic.h> namespace Kernel { [[noreturn]] static void __reset() { // FIXME: This works for i686/x86_64, but needs to be ported to any other arch when needed. asm( "lidt 0\n" "movl $0, 0\n"); __builtin_unreachable(); } void __panic(const char* file, unsigned int line, const char* function) { critical_dmesgln("at {}:{} in {}", file, line, function); dump_backtrace(); if (kernel_command_line().boot_mode() == BootMode::SelfTest) __reset(); else Processor::halt(); } }
package gae import "testing" func runtest(t *testing.T, name, exp, act string) { if exp != act { t.Errorf("expect '%v' to return\n'%v'; got\n'%v'", name, exp, act) } } func TestErrors2(t *testing.T) { ea1 := DuplicateError{} runtest(t, "DuplicateError.Error - basic", "Duplicate value", ea1.Error()) ea2 := DuplicateError{Name: "email"} runtest(t, "DuplicateError.Error - with name", "Duplicate value for email", ea2.Error()) ea3 := DuplicateError{Name: "email", Msg: "must be unique"} runtest(t, "DuplicateError.Error - with name and msg", "Duplicate value for email - must be unique", ea3.Error()) if !IsDuplicateError(ea3) { t.Errorf("expect IsDuplicateError to return true; got false") } eb1 := InsufficientError{} runtest(t, "InsufficientError.Error - basic", "Insufficient value", eb1.Error()) eb2 := InsufficientError{Name: "email"} runtest(t, "InsufficientError.Error - with name", "Insufficient value for email", eb2.Error()) eb3 := InsufficientError{Name: "email", Msg: "must be more than 1"} runtest(t, "InsufficientError.Error - with name and msg", "Insufficient value for email - must be more than 1", eb3.Error()) if !IsInsufficientError(eb3) { t.Errorf("expect IsInsufficientError to return true; got false") } ec1 := InvalidError{} runtest(t, "InvalidError.Error - basic", "Invalid value ()", ec1.Error()) ec2 := InvalidError{"email"} runtest(t, "InvalidError.Error - with msg", "Invalid value (email)", ec2.Error()) if !IsInvalidError(ec2) { t.Errorf("expect IsInvalidError to return true; got false") } ed1 := MismatchError{} runtest(t, "MismatchError.Error - basic", "Mismatched values", ed1.Error()) ed2 := MismatchError{"IDs are different"} runtest(t, "MismatchError.Error - with msg", "Mismatched values - IDs are different", ed2.Error()) if !IsMismatchError(ed2) { t.Errorf("expect IsMismatchError to return true; got false") } ee1 := MissingError{} runtest(t, "MissingError.Error - basic", "Missing value", ee1.Error()) ee2 := MissingError{"IDs are different"} runtest(t, "MissingError.Error - with msg", "Missing value - IDs are different", ee2.Error()) if !IsMissingError(ee2) { t.Errorf("expect IsMissingError to return true; got false") } ef1 := NilError{} runtest(t, "NilError.Error - basic", "Nil error", ef1.Error()) ef2 := NilError{Msg: "Missing ID"} runtest(t, "NilError.Error - with msg", "Nil error (Missing ID)", ef2.Error()) ef3 := NilError{Err: ee1} runtest(t, "NilError.Error - with error", "Nil error - Missing value", ef3.Error()) ef4 := NilError{Err: ee1, Msg: "Missing ID"} runtest(t, "NilError.Error - with msg and error", "Nil error (Missing ID) - Missing value", ef4.Error()) if !IsNilError(ef4) { t.Errorf("expect IsNilError to return true; got false") } eg1 := NotFoundError{} runtest(t, "NotFoundError.Error - basic", "entity not found", eg1.Error()) eg2 := NotFoundError{Kind: "Group"} runtest(t, "NotFoundError.Error - with kind", "'Group' entity not found", eg2.Error()) eg3 := NotFoundError{Err: ee1} runtest(t, "NotFoundError.Error - with error", "entity not found - Missing value", eg3.Error()) eg4 := NotFoundError{Err: ee1, Kind: "Group"} runtest(t, "NotFoundError.Error - with msg and error", "'Group' entity not found - Missing value", eg4.Error()) if !IsNotFoundError(eg4) { t.Errorf("expect IsNotFoundError to return true; got false") } eh1 := ValidityError{} runtest(t, "ValidityError.Error - basic", "validation error - ", eh1.Error()) eh2 := ValidityError{"invalid value"} runtest(t, "ValidityError.Error - with msg", "validation error - invalid value", eh2.Error()) if !IsValidityError(eh2) { t.Errorf("expect IsValidityError to return true; got false") } ei1 := TypeError{} runtest(t, "TypeError.Error - basic", "type error", ei1.Error()) ei2 := TypeError{Name: "name"} runtest(t, "TypeError.Error - with name", "type error on 'name'", ei2.Error()) ei3 := TypeError{Cause: "conversion failed"} runtest(t, "TypeError.Error - with cause", "type error - conversion failed", ei3.Error()) ei4 := TypeError{Name: "name", Cause: "conversion failed"} runtest(t, "TypeError.Error - with name and cause", "type error on 'name' - conversion failed", ei4.Error()) if !IsTypeError(ei2) { t.Error("expect IsTypeError to return true; got false") } }
/** * Http header check. * @param headers * MAP storing Http header */ private void checkHeaders(Map<String, String> headers) { String contentType = headers.get(HttpHeaders.CONTENT_TYPE); if (!"application/zip".equals(contentType)) { throw PersoniumCoreException.BarInstall.REQUEST_HEADER_FORMAT_ERROR .params(HttpHeaders.CONTENT_TYPE); } }
Reliability of multimodal MRI brain measures in youth at risk for mental illness Abstract Introduction A new generation of large‐scale studies is using neuroimaging to investigate adolescent brain development across health and disease. However, imaging artifacts such as head motion remain a challenge and may be exacerbated in pediatric clinical samples. In this study, we assessed the scan–rescan reliability of multimodal MRI in a sample of youth enriched for risk of mental illness. Methods We obtained repeated MRI scans, an average of 2.7 ± 1.4 weeks apart, from 50 youth (mean age 14.7 years, SD = 4.4). Half of the sample (52%) had a diagnosis of an anxiety disorder; 22% had attention‐deficit/hyperactivity disorder (ADHD). We quantified reliability with the test–retest intraclass correlation coefficient (ICC). Results Gray matter measurements were highly reliable with mean ICCs as follows: cortical volume (ICC = 0.90), cortical surface area (ICC = 0.89), cortical thickness (ICC = 0.82), and local gyrification index (ICC = 0.85). White matter volume reliability was excellent (ICC = 0.98). Diffusion tensor imaging (DTI) components were also highly reliable. Fractional anisotropy was most consistently measured (ICC = 0.88), followed by radial diffusivity (ICC = 0.84), mean diffusivity (ICC = 0.81), and axial diffusivity (ICC = 0.78). We also observed regional variability in reconstruction, with some brain structures less reliably reconstructed than others. Conclusions Overall, we showed that developmental MRI measures are highly reliable, even in youth at risk for mental illness and those already affected by anxiety and neurodevelopmental disorders. Yet, caution is warranted if patterns of results cluster within regions of lower reliability. | INTRODUC TI ON A new generation of large-scale studies (Alexander et al., 2017;Casey et al., 2018) is using neuroimaging techniques to investigate adolescent brain development across health and disease. These tremendous undertakings, often called "biobanks" for the wealth of biological data that they collect, are particularly focused on mental health. A primary goal includes identifying developmental trajectories of psychiatric illness which in turn might help improve early detection and guide intervention (Alexander et al., 2017;Casey et al., 2018). Such research is highly valuable, as epidemiologic studies show that 75% of psychiatric disorders begin early in the lifespan, prior to age 24 (Kessler et al., 2005;Kim-Cohen et al., 2003). However, identifying clinically useful brain markers of illness, or "biomarkers," hinges on the reliability of the MRI data. Reliability is the ability of a measurement to provide consistent results under similar circumstances. Imaging artifacts, such as head motion, remain a challenge to reliability (Reuter et al., 2015), and there are concerns that measurement error may be exacerbated in pediatric clinical samples (Ducharme et al., 2016). Functional MRI studies have begun to address within-subject reliability in youth as motion can have a profound effect on functional connectivity estimates (Van Dijk, Sabuncu, & Buckner, 2012;Vetter et al., 2017). However, a large body of imaging research deals with brain structure, and here too image artifacts are of concern. It has been shown that head motion in healthy volunteers can resemble cortical gray matter atrophy (Reuter et al., 2015). Children and adolescents might be particularly sensitive to scanner noise and may have difficulty remaining still for the duration of the sequences. One study examining pediatric MRI data has shown that low-quality data can affect inferences regarding the developmental trajectories of cortical maturation (Ducharme et al., 2016). These findings necessitate the assessment of the reliability of MRI data in participants who are not merely undergoing normal development but are also showing externalizing and internalizing symptoms or are at increased familial risk for mental illness (Rasic, Hajek, Alda, & Uher, 2014). In this study, we assessed the scan-rescan reliability of multimodal MRI in a sample of youth at risk for mental illness, including those already experiencing psychopathology. We measured common structural imaging metrics reported in the literature and quantified regional reliability based on widely used brain atlases. We also compared the reliability of structural measures to published estimates from samples of healthy adults. | Participants We recruited 53 youth (mean age 14.7 years, SD = 4.4) at familial risk for mental illness from FORBOW study, a longitudinal study enriched for sons and daughters of parents with mental illness . Offspring at familial risk for mental illness and participants from control families were invited to complete the MRI study. Participants were scanned twice, an average of 2.7 ± 1.4 weeks apart. Exclusion criteria were personal history of (i) psychotic illness, (ii) any serious medical or neurologic disorders, or (iii) MRI contraindications. The study protocol was approved by the Research Ethics Board of the Nova Scotia Health Authority. Participants provided written informed consent. For children who did not have capacity to make a fully informed decision, a parent or guardian provided written informed consent and the child provided assent. | Parent assessment We used the Schedule for Affective Disorders and Schizophrenia (SADS-IV; Endicott & Spitzer, 1978) and the Structured Clinical Interview for DSM-5 (SCID-5;First, 2015) to establish diagnoses of mental disorders according to DSM-IV and DSM-5. | Offspring assessment Participating youth were interviewed using the Kiddie Schedule for Affective Disorders and Schizophrenia, Present and Lifetime Version (K-SADS-PL; Kaufman et al., 1997) by assessors blind to parent psychopathology. Diagnoses were confirmed in consensus meetings with a psychiatrist. Full-scale intelligence quotient (FSIQ) was assessed using the Wechsler Abbreviated Scale of Intelligence (Wechsler, 2011). | Socioeconomic status (SES) Socioeconomic status was captured as a composite variable (range 0-5) indexing: (i) maternal and (ii) paternal levels of education (iii) family household annual income, (iv) ownership of primary residence, and (v) ratio of bedrooms to residents in household, as previously described (MacKenzie et al., 2017;Zwicker et al., 2019). Higher numeric value reflects higher SES. | MRI acquisition Images were acquired with a 3T General Electric Discovery MR750 scanner equipped with a 32-channel MR Instruments RF head coil. | MRI processing Scans were processed with the Human Connectome Project (HCP) Minimal Preprocessing Pipeline (Glasser et al., 2013). The HCP pipeline is a well-documented set of scripts developed to analyze high-quality multimodal MRI data. It leverages the most widely used open-source MRI processing software: FreeSurfer 6 (RRID:SCR_001847) (Fischl, 2012) and the FMRIB Software Library (FSL, RRID:SCR_002823) (Jenkinson, Beckmann, Behrens, Woolrich, & Smith, 2012). We have optimized the pipeline for our data by matching it to our acquisition parameters and by replacing the MNI template with a pediatric template for registration. The modified pipeline is available and freely accessible on https:// github.com/GitDr o/Youth Relia bilit y/tree/maste r/HCP_custom_ pipeline. We used the NIHPD pediatric atlas (NIHPD Objective 1 atlases , RRID:SCR_008794) (Fonov et al., 2011) to minimize registration bias in our developmental cohort. In order to measure cortical folding, we ran the local gyrification index (LGI) analysis, the details of which can be found in the validation paper (Desikan et al., 2006). Thus, we measured cortical gray matter volume, cortical surface area, cortical thickness, and LGI/cortical folding in 68 parcellations per individual at each time point. Quality control was done both manually early in the processing stream and later with an automated supervised-learning tool on the FreeSurfer segmented output. Manual quality ratings of T 1weighted and T 2 -weighted images were performed by authors VD and HVG. Automated quality control was done with the Qoala-T tool (Klapwijk, Kamp, Meulen, Peters, & Wierenga, 2019). https://github. com/Qoala -T/QC is an automated machine learning model used to classify the quality of FreeSurfer output. Six scans from three participants were excluded after the combined quality control (largely due to excess motion), bringing the total number of participants in the analysis to 50. For white matter reliability, we examined white matter volume and diffusion tensor imaging (DTI) metrics based on the 20-structure JHU DTI-based white-matter tractography atlas (Mori, Wakana, Zijl, & Nagae-Poetscher, 2005). Data inclusion required absolute and relative motion to be under one and a half times the voxel size. Briefly, the processing was done in three steps: (i) creating binary maps of the 20 tracts in MNI152-space, (ii) registering each binary map into subject diffusion-space by combining and applying the nonlinear warps from MNI152 to NIHPD space, and NIHPD space to subject T 1 -weighted space, and the rigid-body linear transform from subject T 1 -weighted space to subject diffusion-space, (iii) using "fslstats" to report each metric; white matter volume, fractional anisotropy (FA), mean diffusivity (MD), axial diffusivity (AD), and radial diffusivity (RD) for each tract. | Statistical analysis We used RStudio (R Version 3.6.2; RStudio version 1.2.5033; RStudio Team, 2019) to calculate the intraclass correlation coefficient (ICC) for the processed scan-rescan datasets. Reliability is the ability of a measurement to provide consistent results under similar circumstances. Test-retest reliability assesses stability under repeated tests, quantifying the extent to which measurements can be replicated. The ICC indexes both correlation and agreement between measurements (Koo & Li, 2016) and is commonly used to quantify reliability. We wanted to capture the variation in measurements taken by MRI and introduced in postprocessing, on the same participant under the same conditions weeks apart. We used ICC (1,1) for calculating scan-rescan reliability implemented in the https://cran.rproj ect.org/web/packa ges/ICC/index.html (Version 2.3.0; Wolak, Fairbairn, & Paulsen, 2012) which estimates the ICC and confidence intervals using the variance components form a one-way ANOVA. We examined averaged ICC and the regional (parcellated) ICC for all measures and classified reliability according to generally defined criteria (Cicchetti, 1994): poor (<0.40), fair (0.41-0.59), good (>0.59-0.74), and excellent (>0.74). The code, data and analysis, is available https://github.com/GitDr o/Youth Relia bility in a reproducible R notebook. We also repeated the analysis on a subsample of the participants scanned again twice, on average 14 months following their initial pair of scans (see Tables S1-S10). | Demographic and clinical characteristics We present results from 100 scans collected from 50 youth (64% female) imaged several weeks apart (M = 2.70, SD = 1.36). The age range was 9-25 years old (M = 14.7, SD = 4.4). The majority of the participants have a family history of mental illness: 25 (50%) with a family history of major depressive disorder, 13 (26%) with a family history of bipolar disorder, and 2 (4%) with a family history of schizophrenia. Ten participants (20%) were recruited from control families. A large proportion of the scanned youth have been affected by mental illness: 26 participants (52%) had been diagnosed with an anxiety disorder, 13 (26%) had been diagnosed with major depressive disorder, and 11 (22%) have had a diagnosis of attention-deficit/hyperactivity disorder (ADHD). The sample was predominantly white (90%), with a minority | Cortical volume We observed "excellent" scan-rescan ICC for cortical gray mat- the high mean ICC, the reliability for most of the structures (65 out of 68; 96%) was classified as "excellent." However, there was some regional variation (Table S1) , with the ICC dipping into the "fair" classification and the lower bound of the confidence interval crossing the "poor" threshold. The contralateral right temporal pole was the next least reliably measured structure (ICC = 0.55, 95% CI ). The only other structure with a designation below "excellent" was the right frontal pole, for which the ICC was only "fair" (ICC = 0.58, 95% CI ). Cortical volume is a composite measure comprised of cortical surface area and cortical thickness; thus, we proceeded to examine the reliability of its components. | Cortical thickness Across the Desikan atlas, the mean ICC for cortical thickness was | White matter volume We observed remarkable reliability of white matter volume meas- (Table S5). The lowest regional reliability was observed in the cingulum near the hippocampus (ICC = 0.96, 95% CI ), which was nevertheless categorized as "excellent." | Fractional anisotropy (FA) Next, we examined white matter FA, which is often used to index microstructural integrity. Scan-rescan ICCs were "excellent" averaged range; however, a number of the regions had the lower confidence interval overlap with the "good" threshold (Table S6). | Radial diffusivity (RD) Radial diffusivity has been previously used as a proxy measure for myelin damage or demyelination. In our study, we found the measure to be, on average, of "good" to "excellent" reliability (M = 0.84, 95% CI ). The forceps major, also known as the posterior forceps, was the white matter fiber bundle with the highest RD reliability (ICC = 0.94, 95% CI ). The right hippocampal cingulum bundle had the lowest scan-rescan reliability (ICC = 0.69, 95% CI ). Of note, the lower confidence interval around the ICC was "fair" for five white matter tracts (Table S7). | Mean diffusivity (MD) Mean diffusivity summarizes the average diffusion properties of a voxel and can be sensitive to pathology such as edema and necrosis, among others. Overall, mean atlas-averaged ICCs were "good" to "excellent" (M = 0.81, 95% CI ). Based on the lower CI bounds, six white matter tracts overlap with the "fair" reliability classification (Table S8) | Axial diffusivity (AD) Axial diffusivity measures water diffusion along the principal axis of diffusion and may be correlated with axonal injury. AD had the lowest average ICC of the DTI scalars in our study (M = 0.78, 95% CI ). While the overall ICC can be classified as "good" to "excellent," there is some regional variability of note (Table S9) | D ISCUSS I ON In this paper, we report the reliability of nine MRI-derived measures of cortical and white matter morphology and integrity based on 100 scans from 50 youth. Despite the high prevalence of anxiety and ADHD disorders in our young sample, we found good to excellent reliability for all measures. White matter volume was most consistently reconstructed with a scan-rescan ICC of 0.98 averaged across the white matter atlas. Axial diffusivity was the least reliable, with an average ICC of 0.78 across scan sessions. We also observed regional variability in reconstruction, with many structures showing excellent stability across measures, and some showing poor to fair reconstruction. This analysis might be of particular interest for hypothesis driven studies focusing on select regions of interest, and for exploratory and predictive multivariate studies to cross reference the pattern of findings to their reported reliability distributions. The excellent reliability of gray matter measures should be interpreted in the context of prior work. While the reliability of functional MRI data in youth has received some attention (Thomason et al., 2011;Vetter et al., 2017), literature examining the reliability of structural MRI data remains sparse. Therefore, we interpret the consistency of our data by comparing it to similar work in adult samples. Iscan and colleagues (Iscan et al., 2015) reported a comparable analysis to ours. Their study included 40 healthy controls (age 18-65), scanned twice, whose MRI images were processed in FreeSurfer. F I G U R E 2 Scan-rescan reliability of diffusion tensor imaging (DTI) measures Overall, 25 individuals passed their thorough quality control. In the approved scans, reported ICCs for cortical thickness/ surface area/ volume were 0.81, 0.87, and 0.88; remarkably similar to our values of 0.82, 0.89, and 0.90. The closeness of these values carries two messages: (i) It is possible to collect highly reliable MRI data from young people with anxiety and/or ADHD, and (ii) after proper quality control, the reliability can compare to that attained from scans of healthy adults. We extended our gray matter analysis to investigate the reliability of cortical folding (LGI), an important neurodevelopmental marker that is essential to the optimization of axonal wiring and the functional organization of the brain (Klyachko & Stevens, 2003). With an ICC of 0.85, cortical folding was of excellent reliability, ranking between measures of cortical thickness and cortical surface area. Cortical folding reliability was slightly lower than what was reported (ICC = 0.94) in a recent paper (Madan & Kensinger, 2017). The difference can be attributed to several factors, as the prior work focused on healthy adults who were scanned either 10 times or with a sequence specifically optimized for brain morphology research. To our knowledge, the current study is the first to report on the reliability of this morphological measure in a pediatric risk sample. Out of all the cortical gray matter measures, cortical thickness had the lowest ICC overall and had the most structures categorized to be of poor reliability based on their lower bound confidence interval. The average thickness of the cortical mantle is 2.5 mm (Fischl & Dale, 2000) which is close to the 1 mm spatial resolution of most scan sequences. Thereby cortical thickness measurements may be particularly sensitive to motion artifacts even in high-quality data (Alexander-Bloch et al., 2016). The structures with the least reliable cortical thickness reconstructions were the temporal pole, frontal pole, medial orbitofrontal gyrus, and the entorhinal cortex. The temporal and frontal poles also exhibited reduced reconstruction consistency in analysis of gray matter volume and surface area, and are known to be problematic in the literature (Klapwijk et al., 2019). The medial orbitofrontal gyrus and entorhinal cortex are localized to the inferior aspect of the brain, and their location makes them particularly affected by susceptibility gradients from air-filled cavities, the bone-tissue interface, and orbital artifacts. However, the orbitofrontal and entorhinal cortices are both essential to fundamental aspects of memory and cognition and have been implicated in a wide range of disorders (Baiano et al., 2008;Rolls & Grabenhorst, 2008). Our results suggest the need for stringent quality control and adequately powered samples in future studies of the cortical thickness of these areas. In contrast, white matter volume had the highest reconstruction reliability in our study. The near-perfect ICC, both regionally and overall, makes the measure particularly suitable for longitudinal research. However, the assessment of white matter microstructure with diffusion tensor imaging (DTI) was more variable. DTI is widely used to infer white matter microstructure, structural connectivity, and axonal health. Our results ranged from good to excellent (ICC 0.78-0.88) for the four DTI measures, with axial diffusivity (AD) being the least reliable and fractional anisotropy (FA) the most reliable. This mirrors the relative interest attained for these measures in the research community. AD may be a correlate of axonal injury (Budde, Xie, Cross, & Song, 2009); however, the measure is less widely used than FA which has been the most popular correlate of white matter integrity (Soares, Marques, Alves, & Sousa, 2013). Regionally, none of the lower confidence intervals for FA ICCs crossed below the good into the fair or poor classification. Across all DTI measures, the only region with the lower bound confidence interval in the poor classification was the hippocampal cingulum bundle. This white matter tract, along with the cingulum cingulate bundle, had the lowest scan-rescan reliability estimates for AD, MD, and RD. The cingulum bundle is a large white matter tract interconnecting the frontal, parietal, medial temporal, and other areas and has been implicated in a spectrum of neuropsychiatric disorders (Bubb, Metzler-Baddeley, & Aggleton, 2018). Its size and midline positioning might make it particularly susceptible to motion artifacts and spatial misregistration errors, and thus, a similar warning akin to low reliability areas of cortical thickness applies here as well. Lower scan-rescan reliability also applied to the corticospinal tract. Interpreting these findings in the context of prior research might be illuminating. Investigations of the underlying reliability of white matter measures in pediatric samples have mainly been restricted to small samples, specific illness, or a limited number of white matter tracts (Alhamud, Taylor, Laughton, Kouwe, & Meintjes, 2015;Bonekamp et al., 2007;Carlson et al., 2014). However, a recent paper has examined FA reliability in a well-powered sample comprising of both an adult and an adolescent group (Acheson et al., 2017). Similar to our results, the authors found that in adolescents, the lowest reliability was observed in the corticospinal tract. This observation held in adults, signifying low reliability of the corticospinal tract across development. The corticospinal tract is a white matter motor pathway, and thus, the reliability concerns might not be immediately relevant to psychiatric research. Lastly, our structural MRI reliability estimates were higher than those reported in functional MRI literature. An early account provided the first empirical evidence of the longitudinal reliability of resting state fMRI in children (Thomason et al., 2011). The authors obtained positive ICC values for the majority of brain voxels, indicating stability within participants across measurements. The first group to investigate the reliability of resting state fMRI in clinical developing groups observed fair (>0.40) to good (>0.70) ICC in the short term (Somandepalli et al., 2015). The authors noted higher ICC in typically developing children compared to those with ADHD. A more recent report examined reliability in adolescent fMRI within a 2-year period (Vetter et al., 2017). The investigators found both variability and stability, with the reliability results dependent on task domain and region of interest. For example, whole-brain ICC was lower (0.44) in cognitive control paradigms and higher (0.74) in reward paradigms. There was great variability across regions of interest, with ICCs ranging from poor (0.19) to excellent (0.84). Two recent meta-analyses suggest that even these modest fMRI reliability values are potentially optimistic. One meta-analysis examined a decade of test-retest reliability work surrounding functional connectivity. The authors concluded that most functional connections exhibited "poor" ICC of 0.29 (95% CI ; Noble, Scheinost, & Constable, 2019). Another recent meta-analysis examined test-retest reliability of common taskbased fMRI measures (Elliott et al., 2020). Echoing the previously mentioned findings, their work revealed poor to fair overall reliability (ICC = 0.40) across 90 studies. However, it is worth noting that contrasting the reliability of structural and functional MRI is not an apples-to-apples comparison. The excellent structural reliability we report in this manuscript is based on the consistent reconstruction of a priori anatomically defined regions. Functional reliability deals with spatial, temporal, and frequency domains that often try to map onto fluid brain processes. Nevertheless, the discrepancy between the two modalities is worth acknowledging as it can have practical applications, such as sample size requirements for biomarker discovery (Elliott et al., 2020). | Limitations There are several limitations to this study. Sample size is of concern, not in respect to accurately estimating reliability but to problems of scale. Our approach of manual ratings for raw data followed by automated quality assessment for processed data can become resource intensive for large-scale projects, such as the modern biobanks collecting tens of thousands of scans. Our relatively small number of excluded scans would grow substantially in those samples and could potentially vary between groups of interest, for example, those with or without psychopathology. Nevertheless, this is actively being addressed with behavioral interventions before or during scanning, with optimized sequences utilizing prospective motion correction, as well as at the study design phase with oversampling of at-risk youth. We were also restricted to a single scan site, and data were acquired on the same scanner at all time points. In our study, we found that results generalized to the same scanner over a year later (Table S10). However, large collaborative efforts are often made possible by acquisitions on scanners from different manufacturers at sites that may be continents apart (Thompson et al., 2014). This can increase variability that confounds the effects of interest. Nevertheless, these challenges are being overcome with the standardization of scanning parameters and statistical techniques that correct for site differences (Chen et al., 2014). Lastly, beyond site differences, variations in data analysis methods are more likely to have a stronger effect on neuroimaging results, but are also being addressed (Nichols et al., 2017). Another limitation is our choice of parcellation scheme for assessing regional reliability of cortical areas and white matter tracts. The construction of an accurate map of the major subdivisions of the human brain is a century-old endeavor with an accompanying and equally long debate on what constitutes a boundary. There are other parcellations than the one used in this paper that are more biologically grounded, accounting for cortical architecture, topography, and functional connectivity (Glasser et al., 2016). However, given that it is impossible to exhaustively test each parcellation, we decided to focus on those most likely to be commonly used in the field. The Desikan atlas has over 5,000 citations on PubMed, and the JHU atlas has almost 2,000. They come default or preinstalled with commonly used MRI software, including FreeSurfer and FSL, respectively. Thus, these atlases are the starting point for a great number of neuroimaging researchers and a basis of comparison for those on the cutting edge who choose to use newer or custom parcellations. | CON CLUS IONS In conclusion, while researchers should be cognizant of regional variability in reconstruction, pediatric MRI brain data are highly reliable overall. Furthermore, the high reliability was established in youth at risk for mental illness or those already affected by anxiety and neurodevelopmental disorders. This bodes well for work investigating the neurodevelopmental markers of mental illness at an early stage, before medication, drug use, and other confounds take a persistent toll on the brain. Confidence in the data quality of high-risk youth samples is also a prerequisite for improved diagnosis and development of personalized prevention strategies based on brain markers. ACK N OWLED G M ENTS The authors would like to thank the participating families and acknowledge the contributions of the FORBOW research team (see http://www.forbow.org). We would also like to thank Anna Minarik and Anna Nazarova for their help in the lab. CO N FLI C T O F I NTE R E S T None of the authors have any conflicts of interest to declare. AUTH O R CO NTR I B UTI O N S V. Drobinin, M. Schmidt, C. Bowen, and R. Uher designed the study. V. Drobinin, H. Van Gestel, C. Helmick, and R. Uher acquired the data, which V. Drobinin and R. Uher analyzed. V. Drobinin wrote the article, which all authors reviewed. All authors approved the final version to be published and can certify that no other individuals not listed as authors have made substantial contributions to the paper. DATA AVA I L A B I L I T Y S TAT E M E N T The data that support the findings of this study are openly available in Zenodo at https://doi.org/10.5281/zenodo.3627320 (Drobinin, 2020
DALLAS — A same-sex couple was granted a marriage license Monday within hours of filing a federal lawsuit against a county clerk in Texas who cited religious opposition when denying them a license last week. Jim Cato and Joe Stapleton filed the lawsuit against Hood County Clerk Katie Lang, saying they repeatedly were turned away when trying to obtain a license last week in Granbury, the county seat. The men were quickly granted a license and “are delighted” that they can get married in their home county, according to their attorney, Jan Soifer. “It’s a shame that they needed to hire lawyers and file a lawsuit to make that happen,” Soifer said in a statement. But the couple hasn’t withdrawn the lawsuit just yet. Soifer said they are seeking an agreement from Lang that her office will issue licenses to same-sex couples without delay, along with attorneys’ fees. The lawsuit alleges that Lang violated their right to equal protection under the law, among other charges. Lang posted a statement on the Hood County clerk’s website saying others in her office would issue the licenses, but that “the religious doctrines to which I adhere compel me to personally refrain from issuing same-sex marriage licenses.” Lang referred questions Monday to the Texas-based Liberty Institute, which litigates cases nationwide relating to religious liberty. The institute’s senior counsel, Jeremy Dys, said that while the U.S. Supreme Court was split in legalizing same-sex marriage nationwide in its ruling last month, it was unanimous in recognizing legal protections for public officials and others who invoke religious objections. “The Supreme Court did not overrule the First Amendment on that day,” Dys said. In a statement released earlier Monday, Soifer criticized Lang for issuing the license to Cato and Stapleton days after saying her office could not provide it because state forms were not updated with same-sex references. Dys said Lang was concerned that altering a license could result in an accusation of tampering with a government document. Lang received an opinion from the Hood County attorney over the weekend saying she could issue the license, Dys said. “The bottom line is somebody can walk in and get a marriage license if they’re entitled to a marriage license,” he said. “There’s no controversy here.” Article continues below Hood County Attorney Lori Kaspar declined to provide details of her opinion to Lang, but noted that Lang took her advice and the license was issued. Public officials take an oath to follow the law, and if they’re unable to complete that oath “due to personal conviction, then you need to get someone else to do it or to step aside,” Lang said. “I think as long as people get licenses then it doesn’t particularly matter who issues them.” © 2015, Associated Press, All Rights Reserved. This material may not be published, broadcast, rewritten, or redistributed. This Story Filed Under
import { GenerateCommonPipelineFilesProcessor } from "../GenerateCommonPipelineFilesProcessor"; import { GenerateCommonPipelineFilesArguments } from "../GenerateCommonPipelineFilesArguments"; import { GenerateFileFromTemplateArguments, GenerateFileFromTemplateExecutor } from "../../GenerateFileFromTemplate"; import S from "string"; import upath = require("upath"); import { GenerateExecutorFileArguments, GenerateExecutorFileExecutor } from "../../GenerateExecutorFile"; import { InteractionModeEnum } from "../../EnsureFileModel/InteractionModeEnum"; export class GenerateExecutor extends GenerateCommonPipelineFilesProcessor { public static readonly Instance = new GenerateExecutor(); public async SafeExecute(args: GenerateCommonPipelineFilesArguments): Promise<void> { let model = args.modelsProvider.getExecutorModel(); model.subdirectories = [...args.commonSubfolders, ...model.subdirectories]; let executorGeneration = new GenerateExecutorFileArguments( model, args.yeomanGenerator, args.generatorsProvider.getFileFromTemplateGenerator(), args.pipelineNameSpecifiedByUser, InteractionModeEnum.Minimum ); if (!S(args.generatedArguments.options["className"]).isEmpty()) { executorGeneration.argumentsClassName = args.generatedArguments.options["className"]; } else { args.AddWarning("Cannot obtain arguments class name during the 'Pipeline executor' creation."); } if (!S(args.generatedArguments.fileName).isEmpty()) { executorGeneration.argumentsFileName = upath.trimExt(upath.basename(args.generatedArguments.fileName)); } else { args.AddWarning("Cannot obtain arguments file name during the 'Pipeline executor' creation."); } if (!S(args.generatedPipeline.options["className"]).isEmpty()) { executorGeneration.pipelineClassName = args.generatedPipeline.options["className"]; } else { args.AddWarning("Cannot obtain pipeline class name during the 'Pipeline executor' creation."); } if (!S(args.generatedPipeline.fileName).isEmpty()) { executorGeneration.pipelineFileName = upath.trimExt(upath.basename(args.generatedPipeline.fileName)); } else { args.AddWarning("Cannot obtain pipeline file name during the 'Pipeline executor' creation."); } let result = await args.generatorsProvider.getExecutorGenerator().execute(executorGeneration); args.generatedExecutor = result.result; args.AddMessageObjects(executorGeneration.GetAllMessages()); } public SafeCondition(args: GenerateCommonPipelineFilesArguments): boolean { return super.SafeCondition(args) && this.CustomCondition(args); } public CustomCondition(args: GenerateCommonPipelineFilesArguments): boolean { let safeCondition = true; return safeCondition; } }
package com.amyliascarlet.lib.thread; public enum Status { Ready,Running,Started,Stop,Remove }
package com.lagou.edu.rpc.provider.handler; import com.lagou.edu.rpc.common.RpcRequest; import com.lagou.edu.rpc.common.RpcResponse; import com.lagou.edu.rpc.common.annotations.RpcService; import com.lagou.edu.rpc.common.idle.Beat; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.timeout.IdleStateEvent; import org.apache.commons.collections4.MapUtils; import org.springframework.beans.BeansException; import org.springframework.cglib.reflect.FastClass; import org.springframework.cglib.reflect.FastMethod; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; import java.lang.reflect.InvocationTargetException; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * 托管所有暴露接口的实现 */ @Component public class RpcServerHandler extends SimpleChannelInboundHandler<RpcRequest> implements ApplicationContextAware { private static final Map<String, Object> SERVICE_INSTANCE_MAP = new ConcurrentHashMap<>(); @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { Map<String, Object> serviceBeanMap = applicationContext.getBeansWithAnnotation(RpcService.class); if (MapUtils.isNotEmpty(serviceBeanMap)) { Set<Map.Entry<String, Object>> entries = serviceBeanMap.entrySet(); for (Map.Entry<String, Object> item : entries) { Object serviceBean = item.getValue(); if (serviceBean.getClass().getInterfaces().length == 0) { throw new RuntimeException("service must implements interface."); } String interfaceName = serviceBean.getClass().getInterfaces()[0].getName(); SERVICE_INSTANCE_MAP.put(interfaceName, serviceBean); } } } /** * 处理客户端业务请求 * * @param ctx * @param rpcRequest * @throws Exception */ @Override protected void channelRead0(ChannelHandlerContext ctx, RpcRequest rpcRequest) throws Exception { if (Beat.BEAT_ID.equalsIgnoreCase(rpcRequest.getRequestId())) { System.out.println("===idle==="); return; } RpcResponse response = new RpcResponse(); response.setRequestId(rpcRequest.getRequestId()); try { response.setResult(handler(rpcRequest)); } catch (Exception e) { e.printStackTrace(); throw e; } ctx.writeAndFlush(response); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { System.out.println("发生异常:" + cause.getMessage()); ctx.channel().close(); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent) { ctx.channel().close(); } else { super.userEventTriggered(ctx, evt); } } /** * 业务逻辑处理 * * @param request * @return * @throws InvocationTargetException */ private Object handler(RpcRequest request) throws InvocationTargetException { Object serviceBean = SERVICE_INSTANCE_MAP.get(request.getClassName()); Class<?> serviceClass = serviceBean.getClass(); String methodName = request.getMethodName(); Class<?>[] parameterTypes = request.getParameterTypes(); Object[] parameters = request.getParameters(); //使用CGLB Reflect FastClass fastClass = FastClass.create(serviceClass); FastMethod fastMethod = fastClass.getMethod(methodName, parameterTypes); return fastMethod.invoke(serviceBean, parameters); } }
/* * Copyright 2002-2015 <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. * * More information about this project is available at: * * https://drewnoakes.com/code/exif/ * https://github.com/drewnoakes/metadata-extractor */ package com.drew.metadata; import com.drew.lang.annotations.NotNull; import com.drew.lang.annotations.Nullable; import java.util.*; /** * A top-level object that holds the metadata values extracted from an image. * <p> * Metadata objects may contain zero or more {@link Directory} objects. Each directory may contain zero or more tags * with corresponding values. * * @author <NAME> https://drewnoakes.com */ public final class Metadata { /** * The list of {@link Directory} instances in this container, in the order they were added. */ @NotNull private final List<Directory> _directories = new ArrayList<Directory>(); /** * Returns an iterable set of the {@link Directory} instances contained in this metadata collection. * * @return an iterable set of directories */ @NotNull public Iterable<Directory> getDirectories() { return _directories; } @Nullable @SuppressWarnings("unchecked") public <T extends Directory> Collection<T> getDirectoriesOfType(Class<T> type) { List<T> directories = new ArrayList<T>(); for (Directory dir : _directories) { if (type.isAssignableFrom(dir.getClass())) { directories.add((T)dir); } } return directories; } /** * Returns the count of directories in this metadata collection. * * @return the number of unique directory types set for this metadata collection */ public int getDirectoryCount() { return _directories.size(); } /** * Adds a directory to this metadata collection. * * @param directory the {@link Directory} to add into this metadata collection. */ public <T extends Directory> void addDirectory(@NotNull T directory) { _directories.add(directory); } /** * Gets the first {@link Directory} of the specified type contained within this metadata collection. * If no instances of this type are present, <code>null</code> is returned. * * @param type the Directory type * @param <T> the Directory type * @return the first Directory of type T in this metadata collection, or <code>null</code> if none exist */ @Nullable @SuppressWarnings("unchecked") public <T extends Directory> T getFirstDirectoryOfType(@NotNull Class<T> type) { for (Directory dir : _directories) { if (type.isAssignableFrom(dir.getClass())) return (T)dir; } return null; } /** * Indicates whether an instance of the given directory type exists in this Metadata instance. * * @param type the {@link Directory} type * @return <code>true</code> if a {@link Directory} of the specified type exists, otherwise <code>false</code> */ public boolean containsDirectoryOfType(Class<? extends Directory> type) { for (Directory dir : _directories) { if (type.isAssignableFrom(dir.getClass())) return true; } return false; } /** * Indicates whether any errors were reported during the reading of metadata values. * This value will be true if Directory.hasErrors() is true for one of the contained {@link Directory} objects. * * @return whether one of the contained directories has an error */ public boolean hasErrors() { for (Directory directory : getDirectories()) { if (directory.hasErrors()) return true; } return false; } @Override public String toString() { int count = getDirectoryCount(); return String.format("Metadata (%d %s)", count, count == 1 ? "directory" : "directories"); } }
def build_get_schema_request(submitter_did: Optional[str], schema_id: str) -> Request: handle = RequestHandle() did_p = encode_str(submitter_did) schema_id_p = encode_str(schema_id) do_call("indy_vdr_build_get_schema_request", did_p, schema_id_p, byref(handle)) return Request(handle)
package ch.bailu.tlg_awt; import java.awt.Color; import java.io.File; import ch.bailu.tlg.PlatformContext; import ch.bailu.tlg.StateRunning; import ch.bailu.tlg.TlgPoint; import ch.bailu.tlg.TlgRectangle; public class BaseContext extends PlatformContext { private static final int PALETTE_RESERVED=5; private static final int PALETTE_SIZE=(StateRunning.SHAPE_PER_LEVEL*3)+PALETTE_RESERVED; private static final int COLOR_GRID=PALETTE_SIZE-PALETTE_RESERVED-1; private static final int COLOR_BACKGROUND=COLOR_GRID+1; private static final int COLOR_HIGHLIGHT=COLOR_GRID+2; private static final int COLOR_DARK=COLOR_GRID+3; private static final int COLOR_FRAME=COLOR_GRID+4; private static final int COLOR_GRAYED=COLOR_GRID+5; private static Color palette[] = null; public BaseContext() { if (palette == null) { initPalette(); } } private void initPalette() { final float color_step=1f/StateRunning.SHAPE_PER_LEVEL; float h=0f; palette=new Color[PALETTE_SIZE]; for (int i=0; i< (PALETTE_SIZE - PALETTE_RESERVED); i++) { palette[i]= Color.getHSBColor(h, 1f, 1f); h+=color_step; } palette[COLOR_GRID]= new Color(44,67,77); palette[COLOR_FRAME]= new Color(44,109,205); palette[COLOR_BACKGROUND]= Color.BLACK; palette[COLOR_HIGHLIGHT]= Color.LIGHT_GRAY; palette[COLOR_DARK]= Color.DARK_GRAY; palette[COLOR_GRAYED]= Color.GRAY; } public Color getAwtColor(int color) { return palette[color]; } @Override public void drawLine(int color, TlgPoint p1, TlgPoint p2) { } @Override public void drawFilledRectangle(int color, TlgRectangle rect) { } @Override public void drawText(int color, TlgRectangle rect, String text) { } @Override public int colorBackground() { return COLOR_BACKGROUND; } @Override public int colorDark() { return COLOR_DARK; } @Override public int colorHighlight() { return COLOR_HIGHLIGHT; } @Override public int colorGrayed() { return COLOR_GRAYED; } @Override public int colorFrame() { return COLOR_FRAME; } @Override public int colorGrid() { return COLOR_GRID; } @Override public int countOfColor() { return PALETTE_SIZE; } @Override public int getColor(int i) { return i; } @Override public void onNewHighscore() { } }
/** * A builder for {@link PutBlobOptions} objects. */ public class PutBlobOptionsBuilder { private boolean chunkUpload = false; private long maxUploadSize = Long.MAX_VALUE; private RestRequest restRequest = null; /** * @param chunkUpload {@code true} to indicate that this is an upload of a data chunk of a stitched upload. * @return this builder */ public PutBlobOptionsBuilder chunkUpload(boolean chunkUpload) { this.chunkUpload = chunkUpload; return this; } /** * @param maxUploadSize the max size of the uploaded blob in bytes. To be enforced by the router. * @return this builder */ public PutBlobOptionsBuilder maxUploadSize(long maxUploadSize) { this.maxUploadSize = maxUploadSize; return this; } /** * @param restRequest The {@link RestRequest} that triggered this put operation. * @return this builder. */ public PutBlobOptionsBuilder restRequest(RestRequest restRequest) { this.restRequest = restRequest; return this; } /** * @return the {@link PutBlobOptions} built. */ public PutBlobOptions build() { return new PutBlobOptions(chunkUpload, maxUploadSize, restRequest); } }
import AdminList from "./AdminList"; export default AdminList;
As usual, Betsey Johnson's spring 2015 collection was raunchy, girly, loud, and — above all — fun. While all of her shows are beauteous spectacles, this one was especially great: it was a ruffly, lacy, glittery celebration of marriage equality. Backstage, Johnson said that the show is part of "the whole world of straight brides, gay brides, transgender marriages, everybody getting married. Finally, freedom." Accordingly, the show featured gay couples, transgender brides and a great deal of gender-bending. The result was fabulous and irreverent, a laughing rejection of several antiquated traditions at once. Of course, some of Johnson's well-known friends served as models — among the celebrities who walked were Camille Grammer of the Real Housewives of Beverly Hills (in drag queen-esque makeup, of course), William Belli from RuPaul's Drag Race, Sharon Needles and Isis King, a transgender model who got her start on ANTM. Here's the collection in full: Advertisement Advertisement Advertisement Advertisement Advertisement Advertisement Advertisement Advertisement
// Copyright 2018 The gVisor Authors. // // 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 cmd import ( "context" "encoding/json" "fmt" "io" "os" "text/tabwriter" "time" "github.com/google/subcommands" specs "github.com/opencontainers/runtime-spec/specs-go" "gvisor.dev/gvisor/pkg/log" "gvisor.dev/gvisor/runsc/cmd/util" "gvisor.dev/gvisor/runsc/config" "gvisor.dev/gvisor/runsc/container" "gvisor.dev/gvisor/runsc/flag" ) // List implements subcommands.Command for the "list" command. type List struct { quiet bool format string sandbox bool } // Name implements subcommands.command.name. func (*List) Name() string { return "list" } // Synopsis implements subcommands.Command.Synopsis. func (*List) Synopsis() string { return "list containers started by runsc with the given root" } // Usage implements subcommands.Command.Usage. func (*List) Usage() string { return `list [flags]` } // SetFlags implements subcommands.Command.SetFlags. func (l *List) SetFlags(f *flag.FlagSet) { f.BoolVar(&l.quiet, "quiet", false, "only list container ids") f.StringVar(&l.format, "format", "text", "output format: 'text' (default) or 'json'") f.BoolVar(&l.sandbox, "sandbox", false, "limit output to sandboxes only") } // Execute implements subcommands.Command.Execute. func (l *List) Execute(_ context.Context, f *flag.FlagSet, args ...any) subcommands.ExitStatus { if f.NArg() != 0 { f.Usage() return subcommands.ExitUsageError } conf := args[0].(*config.Config) if err := l.execute(conf.RootDir, os.Stdout); err != nil { util.Fatalf("%v", err) } return subcommands.ExitSuccess } func (l *List) execute(rootDir string, out io.Writer) error { var ids []container.FullID var err error if l.sandbox { ids, err = container.ListSandboxes(rootDir) } else { ids, err = container.List(rootDir) } if err != nil { return err } if l.quiet { for _, id := range ids { fmt.Fprintln(out, id.ContainerID) } return nil } // Collect the containers. var containers []*container.Container for _, id := range ids { c, err := container.Load(rootDir, id, container.LoadOpts{Exact: true}) if err != nil { log.Warningf("Skipping container %q: %v", id, err) continue } containers = append(containers, c) } switch l.format { case "text": // Print a nice table. w := tabwriter.NewWriter(out, 12, 1, 3, ' ', 0) fmt.Fprint(w, "ID\tPID\tSTATUS\tBUNDLE\tCREATED\tOWNER\n") for _, c := range containers { fmt.Fprintf(w, "%s\t%d\t%s\t%s\t%s\t%s\n", c.ID, c.SandboxPid(), c.Status, c.BundleDir, c.CreatedAt.Format(time.RFC3339Nano), c.Owner) } _ = w.Flush() case "json": // Print just the states. var states []specs.State for _, c := range containers { states = append(states, c.State()) } if err := json.NewEncoder(out).Encode(states); err != nil { return fmt.Errorf("marshaling container state: %w", err) } default: return fmt.Errorf("unknown list format %q", l.format) } return nil }
//#define DEBUG 1 /* MIT License Copyright (c) 2017 <NAME> <<EMAIL>> <<EMAIL>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "param_storage.h" #include <iostream> using namespace gsparams; int main(){ /* ParamMap *mymap = new ParamMap(); ParamList *mylist = new ParamList(); mymap->emplace("Foo", mylist); */ /* DictList a_prim(1.5); DictList another_prim = a_prim; //std::cerr << "another prim : " << another_prim.my_type << " : " << another_prim.my_value << std::endl; DictList i_plan_to_use_as_a_list; std::cout << "going to push_back" << std::endl; i_plan_to_use_as_a_list.push_back(a_prim); std::cout << "size " << i_plan_to_use_as_a_list.size() << std::endl; i_plan_to_use_as_a_list.push_back(1.4);//Why does this trigger the copy constructor of a_prim? //Maybe because when the underlying vector is copied std::cout << "foobar" << std::endl << std::flush; std::cout << "size " << i_plan_to_use_as_a_list.size() << std::endl; i_plan_to_use_as_a_list.push_back(4.5); std::cout << "size " << i_plan_to_use_as_a_list.size() << std::endl; i_plan_to_use_as_a_list.push_back(3.5); std::cout << "size " << i_plan_to_use_as_a_list.size() << std::endl; std::cout << "size " << i_plan_to_use_as_a_list.size() << std::endl; DictList as_dict; as_dict.set("test",i_plan_to_use_as_a_list); as_dict.set("foobar",4.5656565); std::vector< double > gya; as_dict.traverse(&gya); std::cout << "traversal" << std::endl; for(int i = 0;i<gya.size();i++){ std::cout << gya[i] << std::endl; } DictList as_dict_another = as_dict; as_dict_another.traverse(&gya); std::cout << "traversal" << std::endl; for(int i = 0;i<gya.size();i++){ std::cout << gya[i] << std::endl; } std::cout << "Ensuring that deep copies are made." << std::endl; std::cout << as_dict.list_storage - as_dict_another.list_storage << std::endl; */ DictList top_dict; DictList tfs; DictList a_tf; DictList b_tf; a_tf.push_back(1.23); a_tf.push_back(1.24); a_tf.push_back(1.25); tfs["A"] = a_tf; b_tf.push_back(2.1); b_tf.push_back(2.2); b_tf.push_back(2.3); tfs["B"] = b_tf; top_dict["tfs"] = tfs; std::cout << "Access test " << top_dict["tfs"]["A"][0] << std::endl; top_dict["tfs"]["A"][0] = 1.2345; std::cout << "Access test after alteration " << top_dict["tfs"]["A"][0] << std::endl; top_dict["tfs"]["A"][0] = 1.23; double foobar = 5.0*top_dict["tfs"]["A"][0]; dictlist_primitive_t foobaz = 3.3/top_dict["tfs"]["A"][0]; std::cout << "traversal" << std::endl; std::vector< double > gya; gya.clear(); top_dict.traverse(&gya); for(int i = 0;i<gya.size();i++){ std::cout << gya[i] << std::endl; } DictList::iterator myiter = top_dict.begin(); std::cout << "Iterator in standard for loop" << std::endl; myiter = top_dict.begin(); for(int i = 0;i<gya.size();i++){ std::cout << "from iter: " << (*myiter).v() << std::endl; ++myiter; } std::cout << "Using iterators" << std::endl; myiter = top_dict.begin(); std::cout << "Starting loop" << std::endl; for(DictList::iterator itr2 = top_dict.begin();itr2 != top_dict.end();++itr2){ std::cout << "from iter: " << (*itr2).v() << std::endl; } std::cout << "Iterators assignable? (Should change the 4th one to 5.6789.)" << std::endl; myiter = top_dict.begin(); for(int i = 0;i<gya.size();i++){ if( i == 3){ (*myiter) = 5.6789; } ++myiter; } for(DictList::iterator itr2 = top_dict.begin();itr2 != top_dict.end();++itr2){ std::cout << "from iter: " << (*itr2).v() << std::endl; } std::cout << "Assign from a vector: 6 5 4 3 2 1" << std::endl; myiter = top_dict.begin(); (*(myiter++)) = 6.0; (*(myiter++)) = 5.0; (*(myiter++)) = 4.0; (*(myiter++)) = 3.0; (*(myiter++)) = 2.0; (*(myiter++)) = 1.0; std::cout << "Now contains? " << std::endl; std::cout << "Using iterators" << std::endl; for(DictList::iterator itr2 = top_dict.begin();itr2 != top_dict.end();++itr2){ std::cout << "from iter: " << (*itr2).v() << std::endl; } std::cout << "PATHS " << std::endl; for(myiter = top_dict.begin();myiter!=top_dict.end();++myiter){ std::cout << myiter.get_path() << std::endl; } }
/* * Return the smallest component index in 'p' whose value is non-zero */ int First_Non_Zero(Value *p,unsigned length) { Value *cp; int i; cp = p; for (i=0;i<length;i++) { if (value_notzero_p(*cp)) break; cp++; } return((i==length) ? -1 : i ); }
def invoke(self, job_name, **params): inv = _SingleJobInvocation(self, self.securitytoken, self.job_name_prefix, self.max_tries, job_name, params, self.propagation, self.secret_params_re, self.allow_missing_jobs) self.invocations.append(inv) return inv
package p; interface I1 { void /*target*/m(List l); } interface I2 { void /*ripple*/m(List l); } class I implements I1, I2 { void /*ripple*/m(List l); }
/// Returns the event that this cursors points and advances it to the next one. pub fn pop_next_event(&self, cursor: &mut BindingCursor) -> Option<&(Lit, BindTarget)> { let ret = self.binding_events.get(cursor.0); if ret.is_some() { cursor.0 += 1; } ret }
/** * This models a "Healing Touch" spells, which restores a number of health * points to the target creature. * @author Alex Ghita */ public class HealingTouch extends Spell { private static final int HEALING_INCREASE = 4; private static final int MANA_COST_INCREASE = 3; private int healing; private int healedLife; public HealingTouch() { super("Healing Touch", 1, 50, 5, 5, 10, Spell.ANYTIME_SPELL); healing = 5; } public String getEffectMessage(Creature c) { String message = "You've healed " + healedLife + " health points. " + c.getName() + " now has " + c.getHealth() + " health."; return message; } public String getDescription() { return "Cast on a target creature to heal it for " + healing + " (+ Spell Power) health."; } public String getLevelUpDescription() { return "+" + HEALING_INCREASE + " Healing, +" + MANA_COST_INCREASE + " Mana Cost."; } protected void improveSpell() { healing += HEALING_INCREASE; manaCost += MANA_COST_INCREASE; } protected void affect(Creature c, int casterSpellPower) { healedLife = Math.min(healing + casterSpellPower, c.getMaxHealth() - c.getHealth()); c.setHealth(Math.min(c.getMaxHealth(), c.getHealth() + healedLife)); } }