content
stringlengths
10
4.9M
/** * Assert Short type detection. * * @throws Exception Any unexpected exception. */ @Test public void testShortTypeDetection() throws Exception { short s = 1; Assert.assertEquals("Test Short detection", Type.SHORT, Type.getTypeForObject(s)); Assert.assertEquals("Test Short detection", Type.SHORT, Type.getTypeForObject(Short.valueOf(s))); }
By Aaron Tilley and Miguel Helft 11:59am: Tim Cook wrapping up. “We believe technology should lift humanity and enrich people’s lives in all the ways people want to experience it — whether that’s on the wrist, in the living room, on the desk, in the palm of their hand, in the car or even automating their home.” 11:50am: Tim Cook is back to talk about Swift, its programming language for coders. Apple is releasing an iPad app called Swift Playgrounds to let kids start programing Apple apps on the iPad. The app is designed to make programming like a little game. Users are guided along with lessons and objectives. A character moves around and collects gems as the user completes objectives. 11:40am: Apple is opening up its messaging app to developers with iMessage Apps. Users can access these in the “App drawer.” Developers could build apps for stickers. The full software development kit gives developers access to the camera or payments — users could, for example, send or receive payment right in iMessage. 11:30am: The new Message app has “rich links” which share the art work from the website. Emojis will be three times bigger and Apple will be providing predictions for what emojis should appear in messages. "Invisible ink" hides messages that users can slide across to reveal. Hand written messages and drawings will now be possible in the new messaging app. 11:26am: Apple is getting more serious about the smart home. Apple is introducing a smart home app called Home app based on the company’s communication protocol called HomeKit. Smart home devices that have been HomeKit approved can now all be accessed through the app. In the lock screen of iPhone, users can access smart home device notifications. 11:20am: Apple is introducing subscriptions, so you can read news with pay walls right in Apple News. 11:19am: A downloaded music section is available be to quickly see which music is locally stored. The “For You” tab, where Apple suggests music, has “Discovery Mix” now at the top. This is where songs are tailored specifically for users. 11:16am: Now Apple Music, which has more than 15 million paid subscribers. People have often complained about the messy interface in Apple Music and Apple is trying to make the app's UI more intuitive. 11:10am: Eddy Cue is back to introduce the new Map design. Maps are now proactive, it will know when you had to work and filter where you might want to go. While driving, Apple Maps will now show traffic conditions while driving along a route. If there’s traffic ahead, it will give alternative routes. Maps will be available to developers for the first time. Users will, for example, be able to make reservations to restaurants in Apple Maps. The new Maps app is coming to CarPlay, Apple’s OS for infotainment systems in cars. 11:05am: Embedded computer learning is coming to the iPhone. In iOS 10, your iPhone will locally be able to do facial recognition to scan photos stored on an iPhone. The iPhone will also now be able to cluster photos based on criteria likes trips, specific groups of people or topics. 11:02am: Siri is coming to Apple’s messaging. It can help users respond where they are, for example. It will learn what you’re talking about and help add a calendar event quickly. 11:00am: Apple has officially announced its opening up its voice-activated digital assistant Siri to developers, an important step in making Siri a valuable service. Users can say, for example, “Tell Emily on WeChat I’m going to be five minutes late,” or send money through payment apps. 10:57am: Here comes the most important platform update: iOS 10. Ten big new features are coming. The first one is user experience. Apple is redesigning the lock screen and will give users quick interaction with apps with an expanded use of 3D touch. Users can now wake up the iPhone screen by simply bringing the phone up. In the lock screen, users can press in and get updates from apps, like the location of an Uber. Users can clear app notifications from the lock screen. The control screen now has special section for music. 10:50am: Siri is finally coming to the Mac. In a demo, Federighi showed how Siri can be summoned in the app dock at the bottom. Users can make queries for searching for documents or bringing up music playlists, for example. 10:46am: Apple Pay is coming to the web. There will be a “Pay with Apple Pay” option in online stores. Users can authenticate with their fingerprint on their iPhone or Apple Watch. 10:45am: Apple is trying to make iCloud better. Optimized storage makes room for new files by keeping old files up in the cloud. It will help clear up data stored on the Mac. 10:41am: Apple is rolling out a “Universal Clipboard” that lets users copy from an iPhone and paste on their Mac. 10:40am: Craig Federighi, Apple senior vice president of software engineering, is up to talk about the Mac operating system. Instead of calling it OS X, Apple is changing the name of the Mac operating system to macOS Sierra. 10:38am: Apple is making it easier to access to cable network apps with a new feature called “Single Sign-In.” Single sign-in lets users sign in with their cable network provider and then access that content across any app. 10:34am: Siri on Apple TV now lets users search for movies by topics. Users can ask, for example, “Find high school comedies from the 80s.” Siri searches over 650,000 movies and TV show 10:33am: Eddy Cue, Apple's senior vice president of Internet Software and Services, is on stage to talk about Apple TV’s tvOS. The last generation Apple TV had only 80 video channels. The new Apple TV with tvOS now has 1,300 video channels and 6,000 native apps that have been created in the past seven months. 10:27am: The Apple Watch activity tracker will become better suited for wheel chair users. The "Time to stand" reminder will be changing to "Time to roll." 10:24am: Apple is introducing an app for sharing your activity. Users can check in with friends and family to see how they’re doing on different metrics, such as steps, work outs or heart rate. 10:18am: A demo of the watchOS 3 shows the now speedy app launch. One touch can start a ten-minute timer or call a car on Lyft. 10:17am: New watch faces are coming: Mini Mouse, activity health tracker and weather. 10:15am: New feature for writing messages called Scribble. Users can quickly draw letters on the watch face and letters will appear on top. 10:13am: Apple is starting out with updates to the Apple Watch OS, watchOS. The third generation OS will solve a major complaint with the device: slow third-party device launching. Apps will now launch instantly with little delay. 10:10am: Cook pointed out that Apple started the App Store eight years with only 500 apps. The company now has two million apps that have downloaded 130 billion times. 10:06am: Apple CEO Tim Cook started conference out with a moment of silence for the victims of the mass shooting in Orlando, Florida yesterday. “The Apple community is made up of people around the world, all different backgrounds and different points of view,” he said. “We celebrate our diversity. We know that it make us stronger and moves everyone forward. Please rise and join in a moment of silence to honor the victims and people who loved them.” 8am PT: Apple CEO Tim Cook is will take the stage Monday at 10am Pacific to kick off the company's annual World Wide Developers Conference. The focus is expected to be on software and services rather than hardware. There will be updates to iOS and OS X, as well as tvOS and watchOS. Also Siri is likely to open up to third party developers, and perhaps iMessage will be extended to Android. We will be updating you on all that and any surprises live from the Bill Graham Civic Auditorium in San Francisco. Tune in at 10am PT. More on the latest Apple news here: Apple Open Siri To Developers To Fight Microsoft, Amazon WWDC 2016: Apple News App Gains Support For Subscriptions Apple Gunning For PayPal As It Introduces Apple Pay For Web WWDC 2016: The Apple Watch Just Got A Whole Lot Better Apple Reaffirms Commitment To Encryption
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.proxy.backend.text.distsql.rdl.impl; import org.apache.shardingsphere.distsql.parser.statement.rdl.drop.impl.DropReplicaQueryRuleStatement; import org.apache.shardingsphere.governance.core.event.model.rule.RuleConfigurationsPersistEvent; import org.apache.shardingsphere.infra.config.RuleConfiguration; import org.apache.shardingsphere.infra.eventbus.ShardingSphereEventBus; import org.apache.shardingsphere.infra.yaml.swapper.YamlRuleConfigurationSwapperEngine; import org.apache.shardingsphere.proxy.backend.communication.jdbc.connection.BackendConnection; import org.apache.shardingsphere.proxy.backend.context.ProxyContext; import org.apache.shardingsphere.proxy.backend.exception.ReplicaQueryRuleNotExistedException; import org.apache.shardingsphere.proxy.backend.response.header.ResponseHeader; import org.apache.shardingsphere.proxy.backend.response.header.update.UpdateResponseHeader; import org.apache.shardingsphere.proxy.backend.text.SchemaRequiredBackendHandler; import org.apache.shardingsphere.replicaquery.api.config.ReplicaQueryRuleConfiguration; import org.apache.shardingsphere.replicaquery.yaml.config.YamlReplicaQueryRuleConfiguration; import java.util.Collection; import java.util.Collections; import java.util.Optional; import java.util.stream.Collectors; /** * Drop replica query rule backend handler. */ public final class DropReplicaQueryRuleBackendHandler extends SchemaRequiredBackendHandler<DropReplicaQueryRuleStatement> { public DropReplicaQueryRuleBackendHandler(final DropReplicaQueryRuleStatement sqlStatement, final BackendConnection backendConnection) { super(sqlStatement, backendConnection); } @Override public ResponseHeader execute(final String schemaName, final DropReplicaQueryRuleStatement sqlStatement) { Collection<String> ruleNames = sqlStatement.getRuleNames(); check(schemaName, ruleNames); Collection<RuleConfiguration> rules = drop(schemaName, ruleNames); post(schemaName, rules); return new UpdateResponseHeader(sqlStatement); } private void check(final String schemaName, final Collection<String> ruleNames) { Optional<ReplicaQueryRuleConfiguration> replicaQueryRuleConfig = ProxyContext.getInstance().getMetaData(schemaName).getRuleMetaData().getConfigurations().stream() .filter(each -> each instanceof ReplicaQueryRuleConfiguration).map(each -> (ReplicaQueryRuleConfiguration) each).findFirst(); if (!replicaQueryRuleConfig.isPresent()) { throw new ReplicaQueryRuleNotExistedException(ruleNames); } Collection<String> replicaQueryNames = replicaQueryRuleConfig.get().getDataSources().stream().map(each -> each.getName()).collect(Collectors.toList()); Collection<String> notExistedRuleNames = ruleNames.stream().filter(each -> !replicaQueryNames.contains(each)).collect(Collectors.toList()); if (!notExistedRuleNames.isEmpty()) { throw new ReplicaQueryRuleNotExistedException(notExistedRuleNames); } } private Collection<RuleConfiguration> drop(final String schemaName, final Collection<String> ruleNames) { Collection<RuleConfiguration> replicaQueryRuleConfig = ProxyContext.getInstance().getMetaData(schemaName).getRuleMetaData().getConfigurations().stream() .filter(each -> each instanceof ReplicaQueryRuleConfiguration).map(each -> (ReplicaQueryRuleConfiguration) each).collect(Collectors.toList()); YamlReplicaQueryRuleConfiguration yamlConfig = (YamlReplicaQueryRuleConfiguration) new YamlRuleConfigurationSwapperEngine().swapToYamlConfigurations(replicaQueryRuleConfig).stream() .findFirst().get(); for (String each : ruleNames) { yamlConfig.getDataSources().remove(each); } return new YamlRuleConfigurationSwapperEngine().swapToRuleConfigurations(Collections.singleton(yamlConfig)); } private void post(final String schemaName, final Collection<RuleConfiguration> rules) { ShardingSphereEventBus.getInstance().post(new RuleConfigurationsPersistEvent(schemaName, rules)); } }
/** * @license * Copyright 2020 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. */ import * as externs from '@firebase/auth-types-exp'; import { FirebaseError } from '@firebase/util'; import { TaggedWithTokenResponse } from '../../model/id_token'; import { UserCredential } from '../../model/user'; import { OAuthCredential } from '../credentials/oauth'; import { OAuthProvider } from './oauth'; export class GithubAuthProvider extends OAuthProvider { static readonly GITHUB_SIGN_IN_METHOD = externs.SignInMethod.GITHUB; static readonly PROVIDER_ID = externs.ProviderId.GITHUB; readonly providerId = GithubAuthProvider.PROVIDER_ID; static credential(accessToken: string): externs.OAuthCredential { return OAuthCredential._fromParams({ providerId: GithubAuthProvider.PROVIDER_ID, signInMethod: GithubAuthProvider.GITHUB_SIGN_IN_METHOD, accessToken }); } static credentialFromResult( userCredential: externs.UserCredential ): externs.OAuthCredential | null { return GithubAuthProvider.credentialFromTaggedObject( userCredential as UserCredential ); } static credentialFromError( error: FirebaseError ): externs.OAuthCredential | null { return GithubAuthProvider.credentialFromTaggedObject( error as TaggedWithTokenResponse ); } private static credentialFromTaggedObject({ _tokenResponse: tokenResponse }: TaggedWithTokenResponse): externs.OAuthCredential | null { if (!tokenResponse || !('oauthAccessToken' in tokenResponse)) { return null; } if (!tokenResponse.oauthAccessToken) { return null; } try { return GithubAuthProvider.credential(tokenResponse.oauthAccessToken); } catch { return null; } } }
class CompoundOperation: """ Creates a `CompoundOperation`, which represents a combination of EditOperations starting the given `operation`. More operations can later be added. Applying the `CompoundOperation` to an `AbstractMethod` will apply all successfully added operations, in order. """ def __init__(self, operation: EditOperation) -> None: """ Creates the compound operation from the given operation. Members: `__beginIndex`: start of the range of deleted tokens `__endIndex`: end of the range of deleted tokens `__newTokens`: list of tokens to add `__type`: the type of the compound operation; can either be InsertOperation, DeleteOperation, or ReplaceOperation """ # determine the range of deleted indices, will be nothing for an insert operation, or will span >= 1 # token for any other type if type(operation) is CompoundOperation: self.__beginIndex, self.__endIndex = operation.getIndexRange() else: self.__beginIndex = operation.getIndex() self.__endIndex = self.__beginIndex if type(operation) is InsertOperation else self.__beginIndex + 1 # determine new tokens which will be added, will be nothing for delete operation if type(operation) is CompoundOperation: self.__newTokens = operation.getTokens() else: self.__newTokens = [] if type(operation) is DeleteOperation else [operation.getToken()] # set the type self.__type = None self.__setType() def FromMachineString(string: str) -> "CompoundOperation": """ Returns a `CompoundOperation` which represents the given machine string such that the following equality holds: `operation == CompoundOperation.FromMachineString(operation.getMachineString())`. The `CompoundOperation` is derived from the given machine string regardless if it is of general form or typed form. """ # first, attempt to parse the input machine string match = re.search(r"^<(?P<type>.+?)> (?P<beginIndex>\d+) (?P<endIndex>\d+)" + r" <sep>(?P<newTokens> (?:[^ ]+ )*)</(?P=type)>$", string) if not match: raise ValueError("CompoundOperation: invalid machine string: '{}'".format(string)) # get compound operation attributes from match results _type = {"op": None, "ins": InsertOperation, "del": DeleteOperation, "rep": ReplaceOperation}[match.group("type")] beginIndex = int(match.group("beginIndex")) endIndex = int(match.group("endIndex")) newTokens = match.group("newTokens").strip().split(" ") if newTokens == [""]: newTokens = [] # make sure endIndex is at least beginIndex if not endIndex >= beginIndex: raise ValueError("CompoundOperation: invalid machine string: '{}'".format(string)) # build the compound operation, start with an "empty" operation with no deletions or insertions operation = CompoundOperation(InsertOperation(beginIndex, "<placeholder>")) operation.addLoose(DeleteOperation(beginIndex)) operation.__beginIndex = beginIndex operation.__endIndex = endIndex operation.__newTokens = newTokens operation.__setType() # make sure that if the machine string was of typed form, that the resulting CompoundOperation has the same type if _type is not None and _type != operation.getType(): raise ValueError("CompoundOperation: invalid machine string: '{}'".format(string)) return operation def getMachineString(self, form: str = "general") -> str: """ Returns a string formatted for use in training a machine learning model, i.e. a `HephaestusModel`. The structure is as follows: `<X> beginIndex endIndex <sep> tokens </X>` The value of `X` depends on the given `form` parameter. The ouputted machine string can be of *general form* or *typed form*: - `"general"`: `X` will always be `"op"`, regardless of the CompoundOperation's type. Thus, the type of the operation is *generalized*. This is the default behavior. - `"typed"`: `X` will be one of `"ins"`, `"del"`, or `"rep"`, depending on the type of the `CompoundOperation`. The range `beginIndex:endIndex` refers to the pythonic range of tokens which the `CompoundOperation` deletes. Thus, if `beginIndex` and `endIndex` are equal, then no tokens are deleted. `tokens` refers to the list of tokens which are added at `beginIndex` once the aformentioned range is deleted. Note: this method is different from the `__str__()` method, which returns a more human-readable string. """ # determine tag value based on form tag = "" if form == "general": tag = "op" elif form == "typed": tag = {InsertOperation: "ins", DeleteOperation: "del", ReplaceOperation: "rep"}[self.__type] else: raise ValueError("CompoundOperation: invalid form: {}".format(repr(form))) return "<{}> {} {} <sep>{}</{}>".format( tag, self.__beginIndex, self.__endIndex, " " if len(self.__newTokens) == 0 else " " + " ".join(self.__newTokens) + " ", tag ) def __eq__(self, other: "CompoundOperation") -> bool: # don't have to check __type attribute, because it is a function of the index range and tokens return ( type(other) is CompoundOperation and self.getIndexRange() == other.getIndexRange() and self.__newTokens == other.__newTokens ) def __str__(self) -> str: s = "COMPOUND_{} ".format({ InsertOperation: "INSERT", DeleteOperation: "DELETE", ReplaceOperation: "REPLACE" }[self.__type]) if self.__type is InsertOperation: s += "{}".format(self.__beginIndex) else: s += "{}:{}".format(self.__beginIndex, self.__endIndex) if self.__type is not DeleteOperation: s += " -> {}".format(self.__newTokens) return s def __repr__(self) -> str: return str(self) def __len__(self) -> int: """ Returns the Levenshtein distance from A to B, where A is some `AbstractMethod` and B is the `AbstractMethod` resulting from applying this compound operation to A. """ return max(self.__endIndex - self.__beginIndex, len(self.__newTokens)) def getIndexRange(self) -> Tuple[int, int]: """ Returns the range of indices whose tokens are deleted as a tuple in the form [start, end). """ return (self.__beginIndex, self.__endIndex) def getTokens(self) -> List[str]: """ Returns the list of tokens to be added. """ return self.__newTokens.copy() def getType(self) -> Type[EditOperation]: """ Returns the type of the `CompoundOperation`, which can be one of three values: - `InsertOperation`: Applying this operation will only result in token insertions - `DeleteOperation`: Applying this operation will only result in token deletions - `ReplaceOperation`: Applying this operation will result in token deletions and insertions """ return self.__type def addLoose(self, operation: EditOperation) -> bool: """ Attempts to add the given `operation` such that it is loosely compatible with the overall `CompoundOperation`. This may change the type of the `CompoundOperation`. If the addition was successful, then returns True; else, returns False. """ # turn the operation to be inserted into a compound operation, then get attibutes op = CompoundOperation(operation) opBeginIndex, opEndIndex = op.getIndexRange() opTokens = op.getTokens() # this is one past the index of the token last affected once this operation is applied endAffectedIndex = self.__beginIndex + len(self.__newTokens) # if the ranges of affected tokens do not touch, then quit if opEndIndex < self.__beginIndex or opBeginIndex > endAffectedIndex: return False # determine how this operation will change considering the added operation if opBeginIndex < self.__beginIndex: if opEndIndex <= endAffectedIndex: self.__newTokens = opTokens + self.__newTokens[opEndIndex - self.__beginIndex :] self.__beginIndex = opBeginIndex else: self.__newTokens = opTokens self.__beginIndex = opBeginIndex self.__endIndex += opEndIndex - endAffectedIndex else: if opEndIndex <= endAffectedIndex: self.__newTokens = (self.__newTokens[: opBeginIndex - self.__beginIndex] + opTokens + self.__newTokens[opEndIndex - self.__beginIndex :]) else: self.__newTokens = self.__newTokens[: opBeginIndex - self.__beginIndex] + opTokens self.__endIndex += opEndIndex - endAffectedIndex # set the type and return true self.__setType() return True def addStrict(self, operation: EditOperation) -> bool: """ Attempts to add the given `operation` such that it is strictly compatible with the overall `CompoundOperation`. If the addition was successful, then returns True; else, returns False. """ # stop if the operation is not of the same type if not (type(operation) is self.__type or type(operation) is CompoundOperation and operation.getType() is self.__type): return False # add the operation return self.addLoose(operation) def applyToTokens(self, tokens: List[str]) -> None: """ Applies the operation to the given list of tokens. Raises an error if it affects token indices which are out of bounds. """ if self.__endIndex > len(tokens): raise IndexError("CompoundOperation: cannot delete index range {}:{} (out of bounds)".format( self.__beginIndex, self.__endIndex)) tokens[self.__beginIndex:self.__endIndex] = self.__newTokens def __setType(self) -> None: """ Sets the type based on the index range and the tokens to be inserted. """ indexRange = self.__endIndex - self.__beginIndex # If nothing is removed and nothing is inserted, then it's a replace operation if indexRange == 0 and len(self.__newTokens) == 0: self.__type = ReplaceOperation # If nothing is removed, then it's an insert operation elif indexRange == 0: self.__type = InsertOperation # if nothing is added, then it's a delete operation elif len(self.__newTokens) == 0: self.__type = DeleteOperation # anything else means that there are removals and additions, so it's a replaceOperation else: self.__type = ReplaceOperation
RICHMOND, Va. — In a packed theater here on Saturday, Dave Chappelle introduced a comedy bit by explaining that there was a time when he didn’t want to return to the public eye. “I didn’t want to do comedy,” he said, explaining that he wasn’t sure he had something to say. That’s certainly changed. After years of dropping by clubs for surprise sets and occasionally playing theaters, Mr. Chappelle is returning to the spotlight in the Oddball Comedy & Curiosity Festival, a tour produced by FunnyorDie.com that will feature Mr. Chappelle, Flight of the Conchords, Hannibal Buress, Demetri Martin and Kristen Schaal, among others. The monthlong tour, which includes a second stage hosted by the comic Brody Stevens, begins in Austin, Tex., on Aug. 23 and will make stops in New Jersey at the Susquehanna Bank Center on Sept. 6 and the PNC Bank Arts Center on Sept. 7. Almost since he left his Comedy Central hit “Chappelle’s Show” in 2005, his return has been rumored, heating up in the past year since he appeared with Chris Rock at the Comedy Cellar in New York. Mr. Chappelle is now touring the South playing to sold-out audiences. At a show in March, his performance was freewheeling with extended exchanges with the crowd. This past weekend his two sets still had that same spontaneity, but the jokes had tightened, and the transitions were quicker. Wearing a tank top and roaming around the stage in a quickening pace, he had the look of a man getting ready.
// Complete the superReducedString function below. static String superReducedString(String s) { int i = 1; while(i < s.length()) { if(s.charAt(i) == s.charAt(i-1)) { s = s.substring(0,i-1) + s.substring(i+1); i = 0; } i++; } if(s.length() == 0){ return "Empty String"; }else{ return s; } }
<filename>FGPopupSchedulerDemo/FGPopupSchedulerDemo/popView/PriorityPopupView.h<gh_stars>100-1000 // // PriorityPopupView.h // FGPopupSchedulerDemo // // Created by FoneG on 2021/6/25. // #import "BasePopupView.h" #import "FGPopupSchedulerConstant.h" NS_ASSUME_NONNULL_BEGIN @interface PriorityPopupView : BasePopupView @property (nonatomic, assign) FGPopupStrategyPriority psp; @end NS_ASSUME_NONNULL_END
/** * A layout for editing a single entity (can either be an existing or a new * entity) * * @author bas.rutten * @param <ID> type of the primary key of the entity * @param <T> type of the entity */ @SuppressWarnings("serial") public class SimpleEditLayout<ID extends Serializable, T extends AbstractEntity<ID>> extends BaseServiceCustomComponent<ID, T> implements Reloadable, CanAssignEntity<ID, T> { private static final long serialVersionUID = -7935358582100755140L; private Consumer<T> customSaveConsumer; private ModelBasedEditForm<ID, T> editForm; private T entity; private Map<String, SerializablePredicate<?>> fieldFilters = new HashMap<>(); /** * Specifies which relations to fetch. When specified this overrides the default * relations defined in the DAO */ private FetchJoinInformation[] joins; private VerticalLayout main; /** * Constructor * * @param entity the entity to edit * @param service the service used to save/refresh the entity * @param entityModel the entity model used to generate the form * @param formOptions the form options * @param joins optional joins to use when fetching the entity from the * database */ public SimpleEditLayout(T entity, BaseService<ID, T> service, EntityModel<T> entityModel, FormOptions formOptions, FetchJoinInformation... joins) { super(service, entityModel, formOptions); setMargin(false); setClassName(DynamoConstants.CSS_SIMPLE_EDIT_LAYOUT); this.entity = entity; this.joins = joins; } /** * Method that is called after the user has completed (or cancelled) an edit * action * * @param cancel whether the edit was cancelled * @param newEntity whether a new entity was being edited * @param entity the entity that has just been edited */ protected void afterEditDone(boolean cancel, boolean newEntity, T entity) { if (entity.getId() != null) { // reset to view mode if (getFormOptions().isOpenInViewMode()) { editForm.setViewMode(true); checkComponentState(getEntity()); } } else { // new entity back(); } } /** * Callback method that fires directly after the entity is set and before any * data binding occurs * * @param entity the entity that was just set */ public void afterEntitySet(T entity) { // overwrite in entity } /** * Callback method that fires after one of the layouts of the underlying edit * form is built for the first time * * @param layout the layout * @param viewMode whether the layout is in view mode */ protected void afterLayoutBuilt(HasComponents layout, boolean viewMode) { // override in subclass } /** * Callback method that first after a tab has been selected in the tab sheet * that is used in a detail form when the attribute group mode has been set to * TABSHEET * * @param tabIndex the zero-based index of the selected tab */ protected void afterTabSelected(int tabIndex) { // overwrite in subclasses } @Override public void assignEntity(T t) { this.entity = t; if (editForm != null) { editForm.resetTabsheetIfNeeded(); } } /** * Callback method that fires after the "back" button is pressed */ protected void back() { // overwrite in subclasses } /** * Constructs the screen - this method is called just once */ @Override public void build() { if (main == null) { main = new DefaultVerticalLayout(); // create new entity if it does not exist yet if (entity == null) { entity = createEntity(); } // there is just one component here, so the screen mode is always // vertical getFormOptions().setScreenMode(ScreenMode.VERTICAL); editForm = new ModelBasedEditForm<ID, T>(entity, getService(), getEntityModel(), getFormOptions(), fieldFilters) { @Override protected void afterEditDone(boolean cancel, boolean newObject, T entity) { setEntity(entity); SimpleEditLayout.this.afterEditDone(cancel, newObject, entity); } @Override protected void afterEntitySet(T entity) { SimpleEditLayout.this.afterEntitySet(entity); } @Override protected void afterLayoutBuilt(HasComponents layout, boolean viewMode) { SimpleEditLayout.this.afterLayoutBuilt(layout, viewMode); } @Override protected void afterModeChanged(boolean viewMode) { SimpleEditLayout.this.afterModeChanged(viewMode, editForm); } @Override protected void afterTabSelected(int tabIndex) { SimpleEditLayout.this.afterTabSelected(tabIndex); } @Override protected void back() { SimpleEditLayout.this.back(); } @Override protected <U, V> Converter<U, V> constructCustomConverter(AttributeModel am) { return SimpleEditLayout.this.constructCustomConverter(am); } @Override protected <V> Validator<V> constructCustomValidator(AttributeModel am) { return SimpleEditLayout.this.constructCustomValidator(am); } @Override protected <V> Validator<V> constructCustomRequiredValidator(AttributeModel am) { return SimpleEditLayout.this.constructCustomRequiredValidator(am); } @Override protected Component constructCustomField(EntityModel<T> entityModel, AttributeModel attributeModel, boolean viewMode) { return SimpleEditLayout.this.constructCustomField(entityModel, attributeModel, viewMode, false); } @Override protected String getParentGroup(String childGroup) { return SimpleEditLayout.this.getParentGroup(childGroup); } @Override protected String[] getParentGroupHeaders() { return SimpleEditLayout.this.getParentGroupHeaders(); } @Override protected boolean isEditAllowed() { return SimpleEditLayout.this.isEditAllowed(); } @Override protected void postProcessButtonBar(FlexLayout buttonBar, boolean viewMode) { SimpleEditLayout.this.postProcessButtonBar(buttonBar, viewMode); } @Override protected void postProcessEditFields() { SimpleEditLayout.this.postProcessEditFields(editForm); } }; editForm.setCustomSaveConsumer(customSaveConsumer); editForm.setDetailJoins(getJoins()); editForm.setFieldEntityModels(getFieldEntityModels()); editForm.build(); main.add(editForm); postProcessLayout(main); add(main); afterEntitySelected(editForm, getEntity()); checkComponentState(getEntity()); } } /** * Callback method that fires when the new entity is being created * * @return */ protected T createEntity() { return getService().createNewEntity(); } public void doSave() { this.editForm.doSave(); } public Consumer<T> getCustomSaveConsumer() { return customSaveConsumer; } public ModelBasedEditForm<ID, T> getEditForm() { return editForm; } public T getEntity() { return entity; } public Map<String, SerializablePredicate<?>> getFieldFilters() { return fieldFilters; } public FetchJoinInformation[] getJoins() { return joins; } /** * Returns the parent group (which must be returned by the getParentGroupHeaders * method) to which a certain child group belongs * * @param childGroup the name of the child group * @return */ protected String getParentGroup(String childGroup) { // overwrite in subclasses if needed return null; } /** * Returns a list of additional group headers that can be used to add an extra * nesting layer to the layout * * @return */ protected String[] getParentGroupHeaders() { // overwrite in subclasses if needed return null; } /** * * @return */ protected boolean isEditAllowed() { return true; } /** * Check if the layout is in edit mode * * @return */ public boolean isViewMode() { return editForm.isViewMode(); } @Override protected void onAttach(AttachEvent attachEvent) { super.onAttach(attachEvent); build(); } /** * Callback method that can be used to add additional buttons to the button bar * (at both the top and the bottom of the screen) * * @param buttonBar the button bar * @param viewMode the view mode */ protected void postProcessButtonBar(FlexLayout buttonBar, boolean viewMode) { // overwrite in subclasses } /** * Callback method that is called after the edit form has been constructed * * @param editForm the edit form */ protected void postProcessEditFields(ModelBasedEditForm<ID, T> editForm) { // do nothing by default - override in subclasses } /** * Method that is called after the entire layout has been constructed. Use this * to e.g. add additional components to the bottom of the layout * * @param main the main layout */ protected void postProcessLayout(VerticalLayout main) { // overwrite in subclass } @Override public void reload() { // reset to view mode if (getFormOptions().isOpenInViewMode()) { editForm.setViewMode(true); } if (entity.getId() != null) { setEntity(getService().fetchById(entity.getId(), getJoins())); editForm.resetTabsheetIfNeeded(); } } /** * Resets the tab component (if any) to its first sheet */ public void resetTab() { editForm.resetTabsheetIfNeeded(); } public void selectTab(int index) { editForm.selectTab(index); } public void setCustomSaveConsumer(Consumer<T> customSaveConsumer) { this.customSaveConsumer = customSaveConsumer; } /** * Sets the entity * * @param entity */ public void setEntity(T entity) { this.entity = entity; if (this.entity == null) { this.entity = createEntity(); } editForm.setEntity(this.entity); afterEntitySelected(editForm, this.entity); checkComponentState(getEntity()); } public void setFieldFilters(Map<String, SerializablePredicate<?>> fieldFilters) { this.fieldFilters = fieldFilters; } public void setJoins(FetchJoinInformation[] joins) { this.joins = joins; } /** * Replaces the contents of a label by its current value. Use in response to an * automatic update if a field * * @param path the path of the property * @param value the name */ public void setLabelValue(String path, String value) { if (editForm != null) { editForm.setLabelValue(path, value); } } }
MANAGERIAL DISCOURSE IN THE COMMUNICATIVE INTERACTION OF THE STATE AND SOCIETY The article considers managerial discourse in the communicative interaction of the state and society. It is determined that in the structure of managerial discourse there are two radically opposed roles in the system of executive management bodies – the subject and object of management or the addressee and recipient of information, since the communication process itself can be traced from these two angles. A number of specific features of management discourse that distinguish it from other types of organizational and managerial activities are clarified, the main ones being impersonality, stability, high level of regulatory regulation, loyalty and state level of responsibility. Managerial discourse, which acts as a link between the state and society, is often identified with the state in the understanding of the general public. Managerial discourse is transformed under the influence of changes in society, but changes in the state and state management bodies are decisive in this process. It is proved that the functions of managerial discourse in the communicative interaction of the state and society are defined by the boundaries of publicity and privacy. The public sphere space can be considered as a management sphere. The boundaries of private space are usually narrowed and localized in a specific location. It is much more correlated with the personality of the individual. Also, management discourse is presented in four component planes: the environment, which means the situation, the type of social event, its purposefulness, ideological and social conditions; the social subject, which is determined by the role relationships, social status, social activity of participants, as well as their personal relationships; the content, including goals and intentions, worldview positions, knowledge of norms and rules of communication, the general fund of knowledge; text from the point of view of such parameters as the topic of speech communication, compositional construction of utterances, attribution to any language genre, and the specifics of the selected language elements for speech interaction).
/** * Provides log4j preferences. */ @ServiceProvider(service=PreferenceProvider.class) public class Log4jPreferenceProviderImpl implements PreferenceProvider { private Map<String, String> mapping; @Override public Integer getOrder() { return 2; } @Override public String getName() { return getMessage("log4j.name"); } @Override public String getShortName() { return getMessage("log4j.name.short"); } @Override public boolean isHorizontalChildLayout() { return true; } @Override public boolean isPreviewLastChildOnly() { return true; } @Override public List<? extends PreferenceProperty> getPreferences() { Log4jPreferencesModel model = SingleModelManagers.LOG4J_PREFERENCES.get(); mapping = new HashMap<String, String>(); List<PreferenceProperty> result = new LinkedList<PreferenceProperty>(); PreferenceProperty log4jEnabled = PPFactory.createEntry(Log4jEntry.class, Log4jPreferenceEnum.LOG4J_ENABLED.getPropertyName(), Boolean.class); result.add(log4jEnabled); for(Log4jPreferencesModel.Child child : model.getPreferences()) { String regex = child.getLogger(); mapping.put("log4j." + regex, child.getDescription()); NCPreferenceProperty pp = PPFactory.createEntry(Log4jEntry.class, "log4j." + regex, Boolean.class); pp.setParent(true); pp.addDependents(log4jEnabled); result.add(pp); List<NCPreferenceProperty> levels = new ArrayList<NCPreferenceProperty>(6); for(String level : new String[] {"fatal", "error", "warn", "info", "debug", "trace", "all"}) { mapping.put("log4j." + regex + ".*." + level.toUpperCase(), getMessage("log4j." + level)); NCPreferenceProperty pplevel = PPFactory.createEntry(Log4jEntry.class, "log4j." + regex + ".*." + level.toUpperCase(), Boolean.class); pplevel.addDependents(log4jEnabled); pplevel.setChild(true); pplevel.addDependents(levels.toArray(new NCPreferenceProperty[levels.size()])); levels.add(pplevel); pplevel.addDependents(pp); pp.addOptionalDependents(pplevel); result.add(pplevel); } } return result; } @Override public String getMessage(String name) { if(mapping.containsKey(name)) { return mapping.get(name); } else { return getMessage(name, null); } } @Override public String getMessage(String name, Object[] args) { return NbBundle.getMessage(Log4jPreferenceProviderImpl.class, name, args); } @Override public String getShortName(Entry entry, PreferenceProperty property) { if(Log4jEntry.class.isInstance(entry)) { return ((Log4jEntry) entry).getLogLevel(); } return entry.getLevel(); } }
namespace $.$$ { const {rem} = $mol_style_unit const {url} = $mol_style_func $mol_style_define( $psb_portal, { Placeholder: { background: { image: [[ url( 'https://habrastorage.org/webt/dp/mm/jz/dpmmjzzibmacgk4547w_sdghy6i.png' ) ]], repeat: 'no-repeat', position: 'center', }, }, Menu: { flex: { grow: 0, shrink: 0, basis: rem(20), }, Title: { flex: { basis: 'auto', } }, Body: { padding: 0, justifyContent: 'space-between', }, }, Logo: { margin: { left: rem(.75), }, }, Menu_items: { padding: $mol_gap.block, }, Menu_link_in: { flex: { grow: 1, }, }, App: { flex: { grow: 10000, shrink: 0, basis: rem(25), }, }, Stats: { flex: { grow: 0, shrink: 1, basis: rem(20), }, padding: 0, }, } ) }
<gh_stars>1-10 import { ApplyOptions } from '@sapphire/decorators'; import { SpecteraCommand } from '#structures/SpecteraCommand'; import type { Message, CommandInteraction } from 'discord.js'; import { type Args, type ApplicationCommandRegistry, RegisterBehavior, UserError } from '@sapphire/framework'; import { reply } from '@sapphire/plugin-editable-commands'; @ApplyOptions<SpecteraCommand.Options>({ aliases: ['unmute'], description: 'Remove timeout of a member' }) export class UntimeoutCommand extends SpecteraCommand { public registerApplicationCommands(registry: ApplicationCommandRegistry) { registry.registerChatInputCommand( { name: this.name, description: this.description, options: [ { name: 'target', description: 'The member to timeout', type: 'USER', required: true } ] }, { guildIds: ['859287138364030977'], behaviorWhenNotIdentical: RegisterBehavior.Overwrite } ); } public async messageRun(message: Message, args: Args) { const member = await args.pick('member').catch(() => { throw new UserError({ message: 'Please provide a member to untimeout', identifier: 'invalid-args' }); }); if (!member.communicationDisabledUntil) return reply(message, 'The member is not timedout'); await member.timeout(null); return reply(message, `${member.user.tag} has been untimeout`); } public async chatInputRun(interaction: CommandInteraction) { const target = interaction.options.getUser('target', true); const member = await interaction.guild!.members.fetch(target.id); if (!member.communicationDisabledUntil) return interaction.reply({ content: 'The member is not timedout', ephemeral: true }); await member.timeout(null); return interaction.reply({ content: `${member.user.tag} has been untimeout`, ephemeral: true }); } }
def isHeader(line): if line[0:2] in ['AL','EP','CP']: result = True else: result = False return result
Nematicidal activity of mint aqueous extracts against the root-knot nematode Meloidogyne incognita. The nematicidal activity and chemical characterization of aqueous extracts and essential oils of three mint species, namely, Mentha × piperita , Mentha spicata , and Mentha pulegium , were investigated. The phytochemical analysis of the essential oils was performed by means of GC-MS, whereas the aqueous extracts were analyzed by LC-MS. The most abundant terpenes were isomenthone, menthone, menthol, pulegone, and carvone, and the water extracts yielded mainly chlorogenic acid, salvianolic acid B, luteolin-7-O-rutinoside, and rosmarinic acid. The water extracts exhibited significant nematicidal activity against Meloidogyne incognita , and the EC50/72h values were calculated at 1005, 745, and 300 mg/L for M. × piperita, M. pulegium, and M. spicata, respectively. Only the essential oil from M. spicata showed a nematicidal activity with an EC50/72h of 358 mg/L. Interestingly, menthofuran and carvone showed EC50/48h values of 127 and 730 mg/L, respectively. On the other hand, salicylic acid, isolated in the aqueous extracts, exhibited EC50 values at 24 and 48 h of 298 ± 92 and 288 ± 79 mg/L, respectively.
About a week and a half ago, Bandai Namco announced that Digimon World: Next 0rder would be coming to the west exclusively on PlayStation 4. For anyone that has followed the announcement closely, you should know what I mean when I say that it was handled very poorly, to say the least. Initially, the title was announced for PS4 exclusively, with a digital only release. Then, a correction was sent out that it was coming for both PS4 and Vita, with a physical release on PS4 exclusively. Finally, a second correction was sent out and the game was once again confirmed for a PS4-exclusive release in the west. The game’s producer has since went on to explain that part of the reason that the Vita release won’t come over is due to the PS4 release including extra content. (Thanks, GameReactor) Now, although the entire announcement was a mess – everything is settled now, right? Well, not quite. Just yesterday a user on GBAtemp found out that the Chinese Vita release of the title already included a full, yet inaccessible, English translation for the game. He uploaded a modified copy of the game that utilized the translation, before deleting his uploads earlier today. Needless to say, we don’t condone piracy in any shape or form here. However, this turn of events is worth mentioning, especially considering the fact that the title won’t be coming to the Vita in English officially anytime soon. We’ve reached out to Bandai Namco regarding this discovery. We’ll update you with more information if and when we learn more. Quick Take While I was disappointed to hear that Digimon World: Next 0rder would be PS4-only in the west, I understood why – especially after the title’s producer went on to explain their reasoning. That being said, I can’t think of any good reason for the events we have today. For all intents and purposes, the game seems fully translated – if not very well edited. At any rate, the game is more legible in English than some of Bandai Namco’s other Vita releases, such as Sword Art Online: Hollow Fragment. Especially considering the fact that there is an English Vita version of the title out there (albeit not available officially) it makes the whole situation with the title not coming over in the game’s original form all the more confusing. Hopefully, we can get some more light shed on the situation soon. Share Have a tip for us? Awesome! Shoot us an email at [email protected] and we'll take a look!
// *Local* function to restore view state: window size, position & dock state. // if both _stateBuf and _len are NULL, hide (see SDK) void SWS_DockWnd::LoadState(const char* cStateBuf, int iLen) { bool bDocked = IsDocked(); if (cStateBuf && iLen>=sizeof(SWS_DockWnd_State)) SWS_SetDockWndState(cStateBuf, iLen, &m_state); else m_state.state &= ~1; Dock_UpdateDockID((char*)m_id.Get(), m_state.whichdock); if (m_state.state & 1) { if (SWS_IsWindow(m_hwnd) && ((bDocked != ((m_state.state & 2) == 2)) || (bDocked && DockIsChildOfDock(m_hwnd, NULL) != m_state.whichdock))) { m_bSaveStateOnDestroy = false; DestroyWindow(m_hwnd); } Show(false, false); RECT r; GetWindowRect(m_hwnd, &r); if (!bDocked && memcmp(&r, &m_state.r, sizeof(RECT)) != 0) SetWindowPos(m_hwnd, NULL, m_state.r.left, m_state.r.top, m_state.r.right-m_state.r.left, m_state.r.bottom-m_state.r.top, SWP_NOZORDER); } else if (SWS_IsWindow(m_hwnd)) { m_bUserClosed = true; DestroyWindow(m_hwnd); } }
Has World War III begun? Some world leaders and journalists seem to think so. For example, Jordan’s King Abdullah recently said at a news conference that “we are facing a Third World War against humanity,” and that we must “act fast to tackle the response to interconnected threats.” Similarly, Roger Cohen at the New York Times wrote a poignant article in which he draws a number of parallels between the Syrian war and the beginning of World War I. And last September, Pope Francis visited a military cemetery in Italy and warned that “perhaps one can speak of a third war, one fought piecemeal, with crimes, massacres, destruction.” The idea that World War III has started isn’t crazy — although neither is it obviously true. The fact is that the Syrian conflict is an international tangle of competing interests and strange alliances. Russia and Iran, for example, both support the Bashar al-Assad regime in Syria. Meanwhile, the U.S. supports the Kurds and Syrian rebels fighting against al-Assad’s forces. The U.S. is also leading a coalition of over 60 countries, and France recently started its own coalition to fight the Islamic State, as did Russia. Making matters even more complicated, Turkey is fighting against the Kurds, and the Syrian rebels are receiving additional help from Jordan, Turkey and the Gulf states. Advertisement: These are just the state actors — there’s also a number of nonstate entities engaged in this conflict. For example, the Lebanese terrorist organization Hezbollah is on the side of Syria, Russia, and Iran, while the al-Qaeda affiliate Jabhat al-Nusra is fighting to topple Assad’s regime and replace it with an Islamic government. There have also been numerous Shia militia roaming around Iraq since the 2003 U.S.-led preemptive invasion, including the Mahdi Army and the Promised Day Brigade. According to the former director of the CIA, David Petraeus, such militias constitute an even greater longterm threat to the region than the Islamic State. And then, of course, pretty much everyone is at war with the Islamic State, which has grown into the largest and best-funded terrorist organization in human history. It now controls a huge area of real estate in Iraq and Syria (on which some 5 million people live), and has affiliates in countries like Pakistan, Afghanistan, Libya, and Nigeria. This juggernaut of terrorism has also attracted foreign fighters from countries as geographically distant as Denmark, Ireland, Australia, and the US. While its initial aim, after rising to prominence in 2014, was to establish a strong caliphate in Iraq and Syria, it recently expanded its strategy by bombing a Russian commercial plane over the Sinai Peninsula and perpetrating the Paris attacks that left 130 people dead. So, this is clearly an international war — and a messy one at that. But it’s not the first conflict of the sort since World War II. The Cold War involved countries from around the globe, divided into the Eastern and Western blocs, and the Korean War can be seen as a proxy war between the U.S. and China, backed by the UN and Soviet Union, respectively. Furthermore, the Second Congo War, which is sometimes dubbed the African World War, involved nine African nations and roughly twenty different militias. Our global village has witnessed multiple international confrontations in the seven decades since 1945. The Syrian war is just another in this series. But there is something that makes the Syrian war unique. Whereas many of the conflicts after World War I were driven by differences in political and economic ideologies — think fascism, communism, and liberal democracy — the war in Syria involves several actors that appear to hold genuinely apocalyptic worldviews. The Islamic State is perhaps the most obvious example. As the U.S. General Martin Dempsey noted during a 2014 press conference, the Islamic State is motivated by “an apocalyptic, end-of-days strategic vision” according to which its current leader, Abu Bakr al-Baghdadi, is the eighth of 12 caliphs in total before the world ends. It also believes that a grand battle — essentially Armageddon — between the Muslims and “Romans,” i.e., the Western forces, will soon occur in the small Syrian town of Dabiq. This is why the Islamic State “fought ferociously” for control of Dabiq in 2014, despite its military insignificance, and it’s why the Islamic State named its online propaganda magazine Dabiq. Each issue of this magazine opens with the quote: “The spark has been lit here in Iraq, and its heat will continue to intensify — by Allah’s permission — until it burns the crusader armies in Dabiq.” For the Islamic State, the Syrian war is one stage in an apocalyptic narrative that’s unfolding before our very eyes. The reason such beliefs matter is that movements driven by “active apocalyptic” worldviews aren’t “rational actors” in the normal sense of the term. The Islamic State, for example, wants the world to declare war against it. According to a prophetic hadith, it’s expecting a total of 80 countries to descent upon its territories — roughly 20 more than the number of countries in the U.S.-led coalition. Furthermore, the conviction that “This is the war [Muhammad] promised — it is the Grand Battle,” as a Sunni fighter told Reuters in 2014, can produce a sense of moral urgency that true believers can use to justify virtually any act of barbarism or violence, no matter how catastrophic. Consequently, apocalyptic movements like the Islamic State can be far more brutal than state or nonstate actors motivated by the ideologies behind World War II, the Cold War, and other conflicts. The Islamic State wants not just a fight, but a fight to the death. Advertisement: So, the biggest worry about the Syrian war isn’t that it’s World War III in the making, but that involves an apocalyptic component that raises the stakes considerably. The possibility of a catastrophe is perhaps much greater today than in past wars. In fact, the Islamic State has secretly explored the possibility of weaponizing the bubonic plague, as well as infecting its own members with Ebola and then flying them around the world. It’s also fantasized about purchasing a nuclear bomb from Pakistan, transporting it to South America, and sneaking it through “porous borders” into the U.S.” While this scenario may sound “far-fetched,” the Islamic State notes in a Dabiq article that it’s “infinitely more possible today than it was just one year ago.” If such a device were to be detonated in New York City or Los Angeles and the U.S. were to respond by “bomb[ing] the sh*t out of them,” to quote a presidential candidate still trying to figure out the difference between the Quds Force and the Kurds, the result would probably only reinforce Islamic extremism in the region. As Graeme Wood correctly observes in an interview with the atheist Sam Harris, more bombs in Syria and Iraq would only confirm a “clash of civilizations” narrative, thereby leading “a particular type” of Muslim who’s “already inclined to believe that the West is at war with Islam” to adopt even more radical beliefs. The war between “civilizations” would thus escalate even further. What’s the solution to the Syrian conflict — or World War III, if you’d prefer to call it that? There isn’t a good one. The U.S.-led preemptive invasion of Iraq started this mess by destabilizing the region and leading a whole generation of Sunnis and Shi’ites to believe that the end is nigh. And now we’re reaping the consequences of this foreign policy blunder, with no end in sight.
// Used to supply utility functions to the actual lstm test visitors class LstmVisitor : public TestLayerVisitor { public: explicit LstmVisitor(const LstmInputParams& params, const char* name = nullptr) : TestLayerVisitor(name) , m_InputParams(params) {} protected: template<typename LayerType> void CheckInputParameters(const LayerType* layer, const LstmInputParams& inputParams); LstmInputParams m_InputParams; }
/** * Encapsulates configuration for a Java-based atomic component * * @version $Rev$ $Date$ */ public class JavaInstanceFactoryProvider<T> implements InstanceFactoryProvider<T> { private JavaImplementation definition; private ProxyFactory proxyService; private final List<JavaElementImpl> injectionSites; private final EventInvoker<T> initInvoker; private final EventInvoker<T> destroyInvoker; private final Map<JavaElementImpl, Object> factories = new HashMap<JavaElementImpl, Object>(); public JavaInstanceFactoryProvider(JavaImplementation definition) { this.definition = definition; this.initInvoker = definition.getInitMethod() == null ? null : new MethodEventInvoker<T>(definition .getInitMethod()); this.destroyInvoker = definition.getDestroyMethod() == null ? null : new MethodEventInvoker<T>(definition .getDestroyMethod()); injectionSites = new ArrayList<JavaElementImpl>(); } ProxyFactory getProxyFactory() { return proxyService; } void setProxyFactory(ProxyFactory proxyService) { this.proxyService = proxyService; } /** * @return the definition */ JavaImplementation getImplementation() { return definition; } @SuppressWarnings("unchecked") public InstanceFactory<T> createFactory() { ObjectFactory<?>[] initArgs = getConstructorArgs(); Injector<T>[] injectors = getInjectors(); return new ReflectiveInstanceFactory<T>((Constructor<T>)definition.getConstructor().getConstructor(), initArgs, injectors, initInvoker, destroyInvoker); } private ObjectFactory<?>[] getConstructorArgs() { JavaConstructorImpl<?> constructor = definition.getConstructor(); ObjectFactory<?>[] initArgs = new ObjectFactory<?>[constructor.getParameters().length]; for (int i = 0; i < initArgs.length; i++) { ObjectFactory<?> factory = (ObjectFactory<?>)factories.get(constructor.getParameters()[i]); assert factory != null; initArgs[i] = factory; } return initArgs; } @SuppressWarnings("unchecked") private Injector<T>[] getInjectors() { // work around JDK1.5 issue with allocating generic arrays Injector<T>[] injectors = new Injector[injectionSites.size()]; int i = 0; for (JavaElementImpl element : injectionSites) { Object obj = factories.get(element); if (obj != null) { if (obj instanceof ObjectFactory) { ObjectFactory<?> factory = (ObjectFactory<?>)obj; Member member = (Member)element.getAnchor(); if (element.getElementType() == ElementType.FIELD) { injectors[i++] = new FieldInjector<T>((Field)member, factory); } else if (element.getElementType() == ElementType.PARAMETER && member instanceof Method) { injectors[i++] = new MethodInjector<T>((Method)member, factory); } else if (member instanceof Constructor) { // Ignore } else { throw new AssertionError(String.valueOf(element)); } } else { injectors[i++] = createMultiplicityInjector(element, (List<ObjectFactory<?>>)obj); } } } return injectors; } private Injector<T> createMultiplicityInjector(JavaElementImpl element, List<ObjectFactory<?>> factories) { Class<?> interfaceType = JavaIntrospectionHelper.getBaseType(element.getType(), element.getGenericType()); if (element.getAnchor() instanceof Field) { Field field = (Field)element.getAnchor(); if (field.getType().isArray()) { return new FieldInjector<T>(field, new ArrayMultiplicityObjectFactory(interfaceType, factories)); } else { return new FieldInjector<T>(field, new ListMultiplicityObjectFactory(factories)); } } else if (element.getAnchor() instanceof Method) { Method method = (Method)element.getAnchor(); if (method.getParameterTypes()[0].isArray()) { return new MethodInjector<T>(method, new ArrayMultiplicityObjectFactory(interfaceType, factories)); } else { return new MethodInjector<T>(method, new ListMultiplicityObjectFactory(factories)); } } else { throw new InvalidAccessorException("Member must be a field or method: " + element.getName()); } } @SuppressWarnings("unchecked") public Class<T> getImplementationClass() { return (Class<T>)definition.getJavaClass(); } public void setObjectFactory(JavaElementImpl element, ObjectFactory<?> objectFactory) { factories.put(element, objectFactory); } public void setObjectFactories(JavaElementImpl element, List<ObjectFactory<?>> objectFactory) { factories.put(element, objectFactory); } /** * @return the injectionSites */ List<JavaElementImpl> getInjectionSites() { return injectionSites; } /** * @return the factories */ Map<JavaElementImpl, Object> getFactories() { return factories; } }
Three people were killed and 19 people have been wounded in shootings in Chicago from late Saturday through early Sunday morning, authorities said. One of the fatal shootings was a 15- or 16-year-old boy who was killed early Sunday morning. About 12:50 a.m., two boys were shot, one of them fatally, in the Kenwood neighborhood. The two boys were walking in an alley in the 4700 block of South Ellis Avenue when a red minivan pulled up and an occupant fired shots, according to a Chicago Police Department news release. One victim was shot in the head and was dead on scene. He was either 15 or 16 years old. The other victim was a 16-year-old boy who was shot in the left leg and taken to an area hospital in an unknown condition. Michelle Fulton, 45, who lives in the apartment adjacent to the shooting, said she was in bed watching "Game of Thrones" when she heard the first shot. Her Pomeranian, Oliver, hid under the bed and started barking as Fulton walked to the window. She said she heard seven more shots ring out and immediately called 911. “My window faces the alley, and I have big windows so I saw everything,” Fulton said. “I ain’t never seen nothing like this. Nothing like this. He was dead. He dead.” Fulton said she heard the other boy yelling for help and limping, seeming like he was trying to get to a gate near her apartment. She said the sight of the dead teenager was something she’ll “never get out of her head.” “He was laying on the ground shot in the head, blood everywhere,” she said, wrapping her gray sweater around herself. “He was laying in a pool of blood from his head.” The boy’s body was left on the sidewalk until it was removed about 3:30 a.m. Fulton, who stood outside with her dog and other neighbors who had been woken up by the gunshots, has her own children and is afraid the same thing might happen to one of her kids. “I got a son, he’s 19, and the streets calling his name,” Fulton said. “So all you can do is pray. Of all the three, he’s the one that’s in the streets. … Knowing that that boy could have been my son, that’s where it gets kind of tricky because that was somebody’s son regardless of how he act or what he’s doing in the streets, he was still somebody’s son first. It’s just crazy. It’s just crazy.” Fulton said she feels frustrated because not enough people speak up or stand up for their community. A man who said he lived nearby said there aren't enough police patrolling the streets. A woman who stood talking to the man said the “real problem” in their community was “black-on-black crime.” Fulton said she saw a red van driving at a normal speed north on South Ellis Avenue, stop at a red light at the intersection of South Ellis Avenue and East 47th Street, and then drive away. “It wasn’t like they were rushing to get out of here,” Fulton said. “The light was red, and they didn’t run the light or nothing. I’m telling you. I stood right there and watched them from my window in the bedroom.” Fulton said she’s never seen anything like this in her 17 years of living in the neighborhood but isn’t surprised that it happened. “It is coming here,” she said. “It’s been happening for a long time now.” Another fatal shooting happened about 8:45 p.m. Saturday, with a 19-year-old man killed in the South Austin neighborhood. The man was driving in the 4900 block of West Augusta Boulevard when shots were fired and he was hit. The victim had three gunshot wounds to the shoulder and side, according to a Chicago Police Department news release. The victim was taken to Stroger Hospital in critical condition and was later pronounced dead. Editor's note: The man was later identified as Loyd Daniel, 19, of the 1200 block of South Independence Boulevard. He was pronounced dead at Stroger at 1:15 a.m. Suneday after suffering multiple gunshot wounds. About 11 p.m. Saturday, a 23-year-old man was shot and killed in the Washington Park neighborhood. Police responded to a call of “person down” in the 5100 block of South Calumet Avenue and arrived to discover the deceased victim lying in a vacant lot, according to a Chicago Police Department news release. A weapon was recovered on scene, and circumstances are unknown. A man was wounded about 9:30 a.m. Saturday in the 500 block of North Laramie Avenue in the South Austin neighborhood, said Officer Jose Estrada, a Chicago police spokesman. According to preliminary reports, the man was outside when he heard shots and was hit in the left hand. He ran home, then went to West Suburban Hospital in Oak Park with a wound to his index finger, Estrada said. The Laramie Avenue shooting follows a series of recent attacks in the South Austin neighborhood. Police were investigating. Another shooting took place about 1:35 p.m. Saturday in the 6900 block of South Harper Avenue in the city's Grand Crossing neighborhood, said Officer Thomas Sweeney, a police spokesman. A man was outside when he heard shots and was hit in the leg. He was taken to Jackson Park Hospital, where he was listed in good condition, Sweeney said. Another shooting happened just after 6 p.m. Saturday, when two people were shot while sitting in a car in the city’s West Garfield neighborhood, police said. A 17-year-old boy was shot in the hip and a 20-year-old woman was wounded in the leg near the 4300 block of West Jackson Boulevard, Sweeney said. The victims drove to Rush University Medical Center, where their conditions were stabilized, Sweeney said. No further details were immediately being released. In other shootings:
<filename>test/unit/storage/keyvalue/WrappedExpiringStorage.test.ts<gh_stars>100-1000 import type { KeyValueStorage } from '../../../../src/storage/keyvalue/KeyValueStorage'; import type { Expires } from '../../../../src/storage/keyvalue/WrappedExpiringStorage'; import { WrappedExpiringStorage } from '../../../../src/storage/keyvalue/WrappedExpiringStorage'; import { InternalServerError } from '../../../../src/util/errors/InternalServerError'; import clearAllTimers = jest.clearAllTimers; type Internal = Expires<string>; function createExpires(payload: string, expires?: Date): Internal { return { payload, expires: expires?.toISOString() }; } jest.useFakeTimers(); describe('A WrappedExpiringStorage', (): void => { const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); let source: jest.Mocked<KeyValueStorage<string, Internal>>; let storage: WrappedExpiringStorage<string, string>; beforeEach(async(): Promise<void> => { source = { get: jest.fn(), has: jest.fn(), set: jest.fn(), delete: jest.fn(), entries: jest.fn(), }; storage = new WrappedExpiringStorage(source); }); afterEach(async(): Promise<void> => { clearAllTimers(); }); it('does not return data if there is no result.', async(): Promise<void> => { await expect(storage.get('key')).resolves.toBeUndefined(); expect(source.get).toHaveBeenCalledTimes(1); expect(source.get).toHaveBeenLastCalledWith('key'); }); it('returns data if it has not expired.', async(): Promise<void> => { source.get.mockResolvedValueOnce(createExpires('data!', tomorrow)); await expect(storage.get('key')).resolves.toEqual('data!'); }); it('deletes expired data when trying to get it.', async(): Promise<void> => { source.get.mockResolvedValueOnce(createExpires('data!', yesterday)); await expect(storage.get('key')).resolves.toBeUndefined(); expect(source.delete).toHaveBeenCalledTimes(1); expect(source.delete).toHaveBeenLastCalledWith('key'); }); it('returns false on `has` checks if there is no data.', async(): Promise<void> => { await expect(storage.has('key')).resolves.toBe(false); expect(source.get).toHaveBeenCalledTimes(1); expect(source.get).toHaveBeenLastCalledWith('key'); }); it('true on `has` checks if there is non-expired data.', async(): Promise<void> => { source.get.mockResolvedValueOnce(createExpires('data!', tomorrow)); await expect(storage.has('key')).resolves.toBe(true); }); it('deletes expired data when checking if it exists.', async(): Promise<void> => { source.get.mockResolvedValueOnce(createExpires('data!', yesterday)); await expect(storage.has('key')).resolves.toBe(false); expect(source.delete).toHaveBeenCalledTimes(1); expect(source.delete).toHaveBeenLastCalledWith('key'); }); it('converts the expiry date to a string when storing data.', async(): Promise<void> => { await storage.set('key', 'data!', tomorrow); expect(source.set).toHaveBeenCalledTimes(1); expect(source.set).toHaveBeenLastCalledWith('key', createExpires('data!', tomorrow)); }); it('can store data with an expiration duration.', async(): Promise<void> => { await storage.set('key', 'data!', tomorrow.getTime() - Date.now()); expect(source.set).toHaveBeenCalledTimes(1); expect(source.set).toHaveBeenLastCalledWith('key', createExpires('data!', tomorrow)); }); it('can store data without expiry date.', async(): Promise<void> => { await storage.set('key', 'data!'); expect(source.set).toHaveBeenCalledTimes(1); expect(source.set).toHaveBeenLastCalledWith('key', createExpires('data!')); }); it('errors when trying to store expired data.', async(): Promise<void> => { await expect(storage.set('key', 'data!', yesterday)).rejects.toThrow(InternalServerError); }); it('directly calls delete on the source when deleting.', async(): Promise<void> => { await expect(storage.delete('key')).resolves.toBeUndefined(); expect(source.delete).toHaveBeenCalledTimes(1); expect(source.delete).toHaveBeenLastCalledWith('key'); }); it('only iterates over non-expired entries.', async(): Promise<void> => { const data = [ [ 'key1', createExpires('data1', tomorrow) ], [ 'key2', createExpires('data2', yesterday) ], [ 'key3', createExpires('data3') ], ]; source.entries.mockImplementationOnce(function* (): any { yield* data; }); const it = storage.entries(); await expect(it.next()).resolves.toEqual( expect.objectContaining({ value: [ 'key1', 'data1' ]}), ); await expect(it.next()).resolves.toEqual( expect.objectContaining({ value: [ 'key3', 'data3' ]}), ); }); it('removes expired entries after a given time.', async(): Promise<void> => { // Disable interval function and simply check it was called with the correct parameters // Otherwise it gets quite difficult to verify the async interval function gets executed const mockInterval = jest.spyOn(global, 'setInterval'); mockInterval.mockImplementation(jest.fn()); // Timeout of 1 minute storage = new WrappedExpiringStorage(source, 1); const data = [ [ 'key1', createExpires('data1', tomorrow) ], [ 'key2', createExpires('data2', yesterday) ], [ 'key3', createExpires('data3') ], ]; source.entries.mockImplementationOnce(function* (): any { yield* data; }); // Make sure interval is created correctly expect(mockInterval.mock.calls).toHaveLength(1); expect(mockInterval.mock.calls[0]).toHaveLength(2); expect(mockInterval.mock.calls[0][1]).toBe(60 * 1000); // Await the function that should have been executed by the interval await (mockInterval.mock.calls[0][0] as () => Promise<void>)(); expect(source.delete).toHaveBeenCalledTimes(1); expect(source.delete).toHaveBeenLastCalledWith('key2'); mockInterval.mockRestore(); }); it('can stop the timer.', async(): Promise<void> => { const mockInterval = jest.spyOn(global, 'setInterval'); const mockClear = jest.spyOn(global, 'clearInterval'); // Timeout of 1 minute storage = new WrappedExpiringStorage(source, 1); const data = [ [ 'key1', createExpires('data1', tomorrow) ], [ 'key2', createExpires('data2', yesterday) ], [ 'key3', createExpires('data3') ], ]; source.entries.mockImplementationOnce(function* (): any { yield* data; }); await expect(storage.finalize()).resolves.toBeUndefined(); // Make sure clearInterval was called with the interval timer expect(mockClear.mock.calls).toHaveLength(1); expect(mockClear.mock.calls[0]).toHaveLength(1); expect(mockClear.mock.calls[0][0]).toBe(mockInterval.mock.results[0].value); mockInterval.mockRestore(); mockClear.mockRestore(); }); });
<reponame>feralgoon/ThinkJavaCode public class StringUtil { public static void main(String[] args) { System.out.println("Welcome to StringUtil"); System.out.println("getFirstCharacter for 'Hello' returns " + getFirstCharacter("Hello")); System.out.println("getFirstCharacter for 'Goodbye' returns " + getFirstCharacter("Goodbye")); System.out.println("getLastCharacter for 'Hello' returns " + getLastCharacter("Hello")); System.out.println("getLastCharacter for 'Goodbye' returns " + getLastCharacter("Goodbye")); System.out.println("getFirstTwoCharacters for 'Hello' returns " + getFirstTwoCharacters("Hello")); System.out.println("getFirstTwoCharacters for 'Goodbye' returns " + getFirstTwoCharacters("Goodbye")); System.out.println("getLastTwoCharacters for 'Hello' returns " + getLastTwoCharacters("Hello")); System.out.println("getLastTwoCharacters for 'Goodbye' returns " + getLastTwoCharacters("Goodbye")); System.out.println("getAllButFirstThreeCharacters for 'Hello' returns " + getAllButFirstThreeCharacters("Hello")); System.out.println("getAllButFirstThreeCharacters for 'Goodbye' returns " + getAllButFirstThreeCharacters("Goodbye")); printCharacters("Hello"); printCharacters("Goodbye"); printPhoneNumber("234-666-8888"); printPhoneNumber("5015550100"); printPhoneNumber("555JKL21A1"); System.out.println("findFirstE for 'Hello' is " + findFirstE("Hello")); System.out.println("findFirstE for 'Goodbye' is " + findFirstE("Goodbye")); System.out.println("isFinn for 'Finn' returns " + isFinn("Finn")); System.out.println("isFinn for 'Jake' returns " + isFinn("Jake")); System.out.println("Reverse of 'Finn' is " + reverse("Finn")); System.out.println("'Hello' is a palindrome: " + isPalindrome("Hello")); System.out.println("'racecar' is a palindrome: " + isPalindrome("racecar")); System.out.println(); String[] words1 = {"Listen", "Apple", "Never", "Exclaim", "Red"}; String[] words2 = {"Sample", "Perfect", "Test", "Test", "Boop"}; String[] words3 = {"Listen", "Apple", "Never", "Exclaim", "Red", "Angry"}; System.out.println("Testing allLetters for words1: " + allLetters(words1)); System.out.println("Testing allLetters for words2: " + allLetters(words2)); System.out.println("Testing allLetters for words3: " + allLetters(words3)); System.out.println(); System.out.println("Testing allLettersNoDupes for words1: " + allLettersNoDupes(words1)); System.out.println("Testing allLettersNoDupes for words2: " + allLettersNoDupes(words2)); System.out.println("Testing allLettersNoDupes for words3: " + allLettersNoDupes(words3)); System.out.println(); String[] words4 = {"Spock", "Spock", "Kirk", "Kirk"}; String[] words5 = {"Spock", "Spock", "Kirk", "Kirk", "Spock"}; System.out.println("Testing sameCount for words4: " + sameCount(words4)); System.out.println("Testing sameCount for words5: " + sameCount(words5)); System.out.println(); String[] words6 = {"Zebra", "Ant", "Car", "Boat", "Alien", "Aardvark", "Giraffe", "Owl", "Earth"}; System.out.println("words6 initial values: "); for (String s : words6) { System.out.println(s); } System.out.println("Sorting words6 alphabetically: "); words6 = sort(words6); for (String s : words6) { System.out.println(s); } } private static String[] sort(String[] strings) { for (int i = 0; i < strings.length - 1; i++) { for (int j = i + 1; j < strings.length; j++) { if (strings[i].compareTo(strings[j]) > 0) { String temp = strings[i]; strings[i] = strings[j]; strings[j] = temp; } } } return strings; } private static boolean sameCount(String[] words) { boolean result = true; int[] counts = new int[words.length]; for (int i = 0; i < counts.length; i++) { counts[i] = countOccurences(words, words[i]); } int tempNum = counts[0]; for (int i = 0; i < counts.length; i++) { if (counts[i] != 0 && counts[i] != tempNum) { result = false; } } return result; } private static int countOccurences(String[] strings, String value) { int count = 0; for (String s : strings) { if (s.equals(value)) { count++; } } return count; } private static boolean allLettersNoDupes(String[] words) { boolean result = false; int countL = 0; int countE = 0; int countA = 0; int countR = 0; int countN = 0; for (int i = 0; i < words.length; i++) { if (words[i].charAt(0) == 'L') { countL++; } if (words[i].charAt(0) == 'E') { countE++; } if (words[i].charAt(0) == 'A') { countA++; } if (words[i].charAt(0) == 'R') { countR++; } if (words[i].charAt(0) == 'N') { countN++; } } if (countL == 1 && countE == 1 && countA == 1 && countR == 1 && countN == 1) { result = true; } return result; } private static boolean allLetters(String[] words) { boolean result = false; boolean startsWithL = false; boolean startsWithE = false; boolean startsWithA = false; boolean startsWithR = false; boolean startsWithN = false; for (int i = 0; i < words.length; i++) { if (words[i].charAt(0) == 'L') { startsWithL = true; } if (words[i].charAt(0) == 'E') { startsWithE = true; } if (words[i].charAt(0) == 'A') { startsWithA = true; } if (words[i].charAt(0) == 'R') { startsWithR = true; } if (words[i].charAt(0) == 'N') { startsWithN = true; } } if (startsWithL && startsWithE && startsWithA && startsWithR && startsWithN) { result = true; } return result; } private static boolean isPalindrome(String s) { boolean result = false; if (s.equals(reverse(s))) { result = true; } return result; } private static String reverse(String s) { String result = ""; for (int i = 0; i < s.length(); i++) { result = result + s.charAt(s.length() - 1 - i); } return result; } private static boolean isFinn(String s) { boolean result = false; if (s.equals("Finn")) { result = true; } return result; } private static int findFirstE(String s) { int result = s.indexOf('e'); return result; } private static String convertPhoneNumbers(String s) { String result = ""; for(int i = 0; i < s.length(); i++) { switch (s.charAt(i)) { case 'A' : case 'B' : case 'C' : result += "2"; break; case 'D' : case 'E' : case 'F' : result += "3"; break; case 'G' : case 'H' : case 'I' : result += "4"; break; case 'J' : case 'K' : case 'L' : result += "5"; break; case 'M' : case 'N' : case 'O' : result += "6"; break; case 'P' : case 'Q' : case 'R' : case 'S' : result += "7"; break; case 'T' : case 'U' : case 'V' : result += "8"; break; case 'W' : case 'X' : case 'Y' : case 'Z' : result += "9"; break; default : if (s.charAt(i) != '-') { result += s.charAt(i); } break; } } return result; } private static void printPhoneNumber(String s) { String number = convertPhoneNumbers(s); System.out.println("Area Code: " + number.substring(0, 3) + "\tExchange: " + number.substring(3, 6) + "\tLine Number: " + number.substring(6)); /* if (s.length() == 10) { System.out.println("Area Code: " + s.substring(0, 3) + "\tExchange: " + s.substring(3, 6) + "\tLine Number: " + s.substring(6)); } else { System.out.println("Area Code: " + s.substring(0, 3) + "\tExchange: " + s.substring(4, 7) + "\tLine Number: " + s.substring(8)); }*/ } private static void printCharacters(String s) { for (int i = 0; i < s.length(); i++) { System.out.println(s.charAt(i) + ":" + i); } } private static String getAllButFirstThreeCharacters(String s) { String result = s.substring(3); return result; } private static String getLastTwoCharacters(String s) { String result = s.substring(s.length() - 2); return result; } private static String getFirstCharacter(String s) { String result = s.substring(0, 1); return result; } private static String getLastCharacter(String s) { String result = s.substring(s.length() - 1); return result; } private static String getFirstTwoCharacters(String s) { String result = s.substring(0, 2); return result; } }
/** * Use this method to execute the command. */ void executeCommand() { List<Exception> errors = new ArrayList<>(); try { ProcessBuilder pb = new ProcessBuilder(this.commandInformation); pb.environment().clear(); pb.environment().putAll(this.environmentMap); Process process = pb.start(); InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); this.inputStreamHandler = new StreamHandler(inputStream); this.errorStreamHandler = new StreamHandler(errorStream); this.inputStreamHandler.start(); this.errorStreamHandler.start(); process.waitFor(); this.inputStreamHandler.join(); this.errorStreamHandler.join(); if(this.inputStreamHandler.getException() != null) errors.add(this.inputStreamHandler.getException()); if(this.inputStreamHandler.getCloseException() != null) errors.add(this.inputStreamHandler.getCloseException()); if(this.errorStreamHandler.getException() != null) errors.add(this.errorStreamHandler.getException()); if(this.errorStreamHandler.getCloseException() != null) errors.add(this.errorStreamHandler.getCloseException()); } catch (Exception ex) { try { if (this.inputStreamHandler != null) { if (this.inputStreamHandler.getException() != null) errors.add(this.inputStreamHandler.getException()); if (this.inputStreamHandler.getCloseException() != null) errors.add(this.inputStreamHandler.getCloseException()); } if(this.errorStreamHandler != null) { if(this.errorStreamHandler.getException() != null) errors.add(this.errorStreamHandler.getException()); if(this.errorStreamHandler.getCloseException() != null) errors.add(this.errorStreamHandler.getCloseException()); } } catch (Exception e) { System.out.println(e.getMessage()); } errors.add(ex); System.out.println(ex.getMessage()); } this.executionErrors = errors.size() > 0 ? (Exception[])errors.toArray() : null; }
<reponame>geostarling/rezolus // Copyright 2019-2020 Twitter, Inc. // Licensed under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 use nvml_wrapper::NVML; use rustcommon_atomics::*; use serde_derive::Deserialize; use strum::IntoEnumIterator; use crate::config::SamplerConfig; use super::stat::*; #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct NvidiaConfig { #[serde(default)] enabled: AtomicBool, #[serde(default)] interval: Option<AtomicUsize>, #[serde(default = "crate::common::default_percentiles")] percentiles: Vec<f64>, #[serde(default = "default_statistics")] pub(crate) statistics: Vec<NvidiaConfigStatistic>, } impl Default for NvidiaConfig { fn default() -> Self { Self { enabled: Default::default(), interval: Default::default(), percentiles: crate::common::default_percentiles(), statistics: default_statistics(), } } } fn default_statistics() -> Vec<NvidiaConfigStatistic> { NvidiaConfigStatistic::iter().collect() } impl SamplerConfig for NvidiaConfig { type Statistic = NvidiaStatistic; fn enabled(&self) -> bool { self.enabled.load(Ordering::Relaxed) } fn interval(&self) -> Option<usize> { self.interval.as_ref().map(|v| v.load(Ordering::Relaxed)) } fn percentiles(&self) -> &[f64] { &self.percentiles } fn statistics(&self) -> Vec<<Self as SamplerConfig>::Statistic> { let mut enabled = Vec::new(); if let Ok(nvml) = NVML::builder().init() { let devices = nvml.device_count().unwrap_or(0); for statistic in self.statistics.iter() { for id in 0..devices { match statistic { NvidiaConfigStatistic::GpuTemperature => { enabled.push(NvidiaStatistic::GpuTemperature(id)); } NvidiaConfigStatistic::GpuUtilization => { enabled.push(NvidiaStatistic::GpuUtilization(id)); } NvidiaConfigStatistic::MemoryEccEnabled => { enabled.push(NvidiaStatistic::MemoryEccEnabled(id)); } NvidiaConfigStatistic::MemoryEccSbe => { enabled.push(NvidiaStatistic::MemoryEccSbe(id)); } NvidiaConfigStatistic::MemoryEccDbe => { enabled.push(NvidiaStatistic::MemoryEccDbe(id)); } NvidiaConfigStatistic::MemoryUtilization => { enabled.push(NvidiaStatistic::MemoryUtilization(id)); } NvidiaConfigStatistic::EncoderUtilization => { enabled.push(NvidiaStatistic::EncoderUtilization(id)); } NvidiaConfigStatistic::DecoderUtilization => { enabled.push(NvidiaStatistic::DecoderUtilization(id)); } NvidiaConfigStatistic::PowerUsage => { enabled.push(NvidiaStatistic::PowerUsage(id)); } NvidiaConfigStatistic::PowerLimit => { enabled.push(NvidiaStatistic::PowerLimit(id)); } NvidiaConfigStatistic::EnergyConsumption => { enabled.push(NvidiaStatistic::EnergyConsumption(id)); } NvidiaConfigStatistic::ClockSMCurrent => { enabled.push(NvidiaStatistic::ClockSMCurrent(id)); } NvidiaConfigStatistic::ClockMemoryCurrent => { enabled.push(NvidiaStatistic::ClockMemoryCurrent(id)); } NvidiaConfigStatistic::PcieReplay => { enabled.push(NvidiaStatistic::PcieReplay(id)); } NvidiaConfigStatistic::PcieRxThroughput => { enabled.push(NvidiaStatistic::PcieRxThroughput(id)); } NvidiaConfigStatistic::PcieTxThroughput => { enabled.push(NvidiaStatistic::PcieTxThroughput(id)); } NvidiaConfigStatistic::MemoryFbFree => { enabled.push(NvidiaStatistic::MemoryFbFree(id)); } NvidiaConfigStatistic::MemoryFbTotal => { enabled.push(NvidiaStatistic::MemoryFbTotal(id)); } NvidiaConfigStatistic::MemoryFbUsed => { enabled.push(NvidiaStatistic::MemoryFbUsed(id)); } NvidiaConfigStatistic::MemoryRetiredSbe => { enabled.push(NvidiaStatistic::MemoryRetiredSbe(id)); } NvidiaConfigStatistic::MemoryRetiredDbe => { enabled.push(NvidiaStatistic::MemoryRetiredDbe(id)); } NvidiaConfigStatistic::MemoryRetiredPending => { enabled.push(NvidiaStatistic::MemoryRetiredPending(id)); } NvidiaConfigStatistic::ProcessesCompute => { enabled.push(NvidiaStatistic::ProcessesCompute(id)); } } } } } enabled } }
This was going to be a column just about Robert Jones, who celebrated his 44th birthday Thursday by walking out of Orleans Parish Criminal District Court a free man. Jones had spent 23 years locked up at the Louisiana State Penitentiary, but like many other poor and poorly represented defendants cornered by Harry Connick's district attorney's office, he was charged, convicted and shipped off to Angola despite significant doubts about his guilt. Robert Jones was sent to Angola for an April 1992 French Quarter crime spree that included robbery, kidnapping, rape and murder even though evidence pointed to a man named Lester Jones - no relation to Robert - as the single culprit. This was going to be a column about how Robert Jones - who was pressured into pleading guilty despite the prosecution's weak case - smiled on the courthouse steps and said that he doesn't have bitterness or resentment against anybody. After 23 years behind bars, Robert Jones' charges in 1992 crime spree dropped by DA "You have restored my faith in the justice system," Robert Jones told the judge Thursday (Jan. 26). This was going to be a column about the joy in the air at Tulane and Broad, about the looks of excitement on the faces of other men who were previously sprung from Angola. There was Calvin Duncan, who worked as an inmate lawyer with Jones and praised his commitment to helping other inmates who'd also been wrongly incarcerated. There was Jerome Morgan who - after a 20-year bid at Angola - had murder charges against him dropped last year. After Jones' first remarks as a free man, Morgan pulled him into what may have been history's tightest bear hug. This was going to be a column about how the Innocence Project of New Orleans, directed by attorney Emily Maw, keeps getting people out of prison, keeps reuniting families that have been unfairly torn assunder by our criminal justice system. But then District Attorney Leon Cannizzaro - who isn't even responsible for sending Robert Jones to prison - decided that all that joy at the courthouse was a problem in need of a fix. "In the opinion of the District Attorney," Assistant District Attorney Christopher Bowman wrote in a Thursday morning email blast, "today's proceedings did not exonerate Robert Jones. It is difficult to retry any case that is more than two decades old. The office, unfortunately, has concluded that it cannot at this time retry a complex case such as this." Bowman goes on to write that "this victim is certain that the defendant was her attacker." The "real tragedy," Bowman writes, is that Cannizzaro's office couldn't bring her a "full measure of closure." When Bowman says the case is complex, what he really means is that the case against Robert Jones is as weak as they come. All things being fair, Cannizzaro's office couldn't win a conviction against Robert Jones with these facts no matter when the crimes occurred. Police first arrested Robert Jones on the suspicion that on April 14, 1992, he murdered 27-year-old British tourist Julie Stott in the French Quarter. After his picture had been shown on the news and published on the front page of The Times-Picayune, the victims of an April 7 French Quarter robbery, kidnapping and rape picked Robert Jones out of a line-up. Robert Jones' bail hearing puts prosecutors' past tactics on trial: Jarvis DeBerry The Innocence Project of New Orleans made two arguments in an Orleans Parish courtroom Tuesday on behalf of client Robert Jones. One argument was meant to persuade Criminal District Court Judge Arthur Hunter that Jones, who is facing a retrial... But in fairly short order police realized that Lester Jones killed Stott. He's serving a life sentence for Stott's murder. Prosecutors still successfully leaned on Robert Jones to plead guilty to killing Stott. At a 2015 hearing in his case, James Stewart, a former homicide detective turned FBI agent, said he was testifying for a defendant for the first time in his law enforcement career. If Robert Jones pleaded guilty to killing Stott, Stewart said, then his attorney steered him wrong. Lester Jones killed Stott and killed her by himself, Stewart said. Stewart said he told prosecutors back then Robert Jones wasn't involved. Lester Jones' car was used to commit the April 7 crimes. An item stolen that night was found in Lester Jones' car. There's no evidence that Robert Jones and Lester Jones knew one another, and Lester Jones told authorities they didn't, but Connick's office kept that secret as they pressured Robert Jones to plead guilty. Maw said at that 2015 hearing that despite the victims of the April 7 crimes picking Robert Jones out of a line up, Lester Jones better matches their initial description of their attacker. Prosecutors had their man in Lester Jones. But why send just one man to prison if you can send two? Prosecutors didn't innocently err, Maw said. They deliberately pressured Robert Jones to plead guilty in Stott's death when they knew Lester Jones killed her. And they charged Robert Jones for a rape, robbery and kidnapping when they knew that everything except that eyewitness identification pointed to Lester Jones. Cannizzaro had an opportunity Thursday to disavow the abuses of the past and declare that he's running a different kind of office than Connick did. But he chose to display the same stubbornness and arrogance that led to Connick's epidemic of wrongful convictions. If Cannizzaro had kept quiet, we'd only be shaking our fists at Connick. But Cannizzaro chose to deny that Robert Jones was railroaded, which makes him part of the problem, too. Jarvis DeBerry is deputy opinions editor at NOLA.com | The Times-Picayune. He can be reached at [email protected]. Follow him at twitter.com/jarvisdeberry.
/** * Created by Xiamin on 2017/4/9. */ public class AppConstant { public static final String SP = "sp_setting"; public static final String Theme = "theme"; public static final String isFirstEnter = "is_first_enter"; }
// NewLocalDevServerProxy creates a http handler to proxy a local dev server setup func NewLocalDevServerProxy() (http.Handler, errorsx.Error) { originURL := os.Getenv(LocalDevServerEnvVarName) if originURL == "" { return nil, errorsx.Errorf("no %s environment variable set", LocalDevServerEnvVarName) } origin, err := url.Parse(originURL) if err != nil { return nil, errorsx.Wrap(err) } director := func(req *http.Request) { req.Header.Add("X-Forwarded-Host", req.Host) req.Header.Add("X-Origin-Host", origin.Host) req.URL.Scheme = "http" req.URL.Host = origin.Host } proxy := httputil.ReverseProxy{ Director: director, } return &proxy, nil }
The problem of how learning should be socially organized: relations between reflection and transformative action Within critical theory progressive relationships between reflection and action involve confronting contradictions within practice artistry from a dialectical view of practice as praxis and as the means whereby one can move in the direction of positive change or social transformation. Freire captures this idea of reflective praxis in his pedagogical approach to conscientization, a form of codification and the encouragement of human agency, but it is also a key feature of the work of Antonio Gramsci. Reflective praxis differs from activity in general as it is enacted through theory that is formulated on understandings of contextual (situated) practices. This is important because if or when theory and practice are separated they fall into a distorted one‐sidedness and if context is ignored the mode of existence, expression or internal organization of the content of action cannot be grasped in terms of its totality of relations and possible contradictions.
def create_exp_nexp_edge_ls(exp_ids, nexp_ids, exp_ps, nexp_ps): pdist_mat = pairwise_abs_dist(nexp_ps, exp_ps) pdist = np.ndarray.flatten(pdist_mat) cap_weight_ls = [{'capacity':1, 'weight':dist} for dist in pdist] exp_ids_comb, nexp_ids_comb= zip(*itertools.product(exp_ids, nexp_ids)) exp_nexp_edge_ls = list(zip(exp_ids_comb,nexp_ids_comb, cap_weight_ls)) return exp_nexp_edge_ls
import { Component } from '@angular/core'; import * as clipboard from 'clipboard-polyfill'; import { clamp } from 'lodash'; import { rect, RandStrFlag, randStr } from '../../../utils'; const w = 386, h = 270; @Component({ selector: 'app-rand-str', templateUrl: './randstr.html', styleUrls: ['./randstr.scss'] }) export class AppRandStr { readonly size = rect(window.innerWidth / 2 - w / 2 | 0, window.innerHeight / 2 - h / 2 | 0, w, h); readonly minSize = rect(0, 0, 386, 244); close = () => {}; flags = RandStrFlag.Number | RandStrFlag.Uppercase | RandStrFlag.Lowercase; length = 32; result = ''; get canGenerate() { return this.flags > 0 && this.length > 0; } get canCopy() { return !!this.result && this.result.length > 0; } constructor() { this.generate(); } hasFlag(flag: number) { return (this.flags & flag) !== 0; } toggleFlag(flag: number) { this.flags ^= flag; } fixLength() { this.length = clamp(this.length, 1, 100000) | 0; } generate() { if (this.canGenerate) this.result = randStr(this.length, this.flags); } clear() { this.result = ''; } copy() { if (this.canCopy) clipboard.writeText(this.result); } }
def terminate(self, token): assert token.type == '$END' while True: action, arg = self.states[self.state][token.type] self.reduce_(arg) if self.state_stack[-1] == self.end_state: text = ''.join(self.sequence) self.result = (self.value_stack[-1], text) self.terminated = True return []
/** * Resets the view to the initial defaults. */ private void init(Bundle savedInstanceState) { announceButton.setEnabled(false); listElements = new ArrayList<BaseListElement>(); listElements.add(new EatListElement(0)); listElements.add(new LocationListElement(1)); listElements.add(new PeopleListElement(2)); if (savedInstanceState != null) { for (BaseListElement listElement : listElements) { listElement.restoreState(savedInstanceState); } pendingAnnounce = savedInstanceState.getBoolean(PENDING_ANNOUNCE_KEY, false); } listView.setAdapter(new ActionListAdapter(getActivity(), R.id.selection_list, listElements)); Session session = Session.getActiveSession(); if (session != null && session.isOpened()) { makeMeRequest(session); } }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. /*============================================================================= PrimitiveSceneInfo.h: Primitive scene info definitions. =============================================================================*/ #ifndef __PRIMITIVESCENEINFO_H__ #define __PRIMITIVESCENEINFO_H__ #include "GenericOctree.h" /** Data used to track a primitive's allocation in the volume texture atlas that stores indirect lighting. */ class FIndirectLightingCacheAllocation { public: FIndirectLightingCacheAllocation() : Add(FVector(0, 0, 0)), Scale(FVector(0, 0, 0)), MinUV(FVector(0, 0, 0)), MaxUV(FVector(0, 0, 0)), MinTexel(FIntVector(-1, -1, -1)), AllocationTexelSize(0), TargetPosition(FVector(0, 0, 0)), TargetDirectionalShadowing(1), TargetSkyBentNormal(FVector4(0, 0, 1, 1)), SingleSamplePosition(FVector(0, 0, 0)), CurrentDirectionalShadowing(1), CurrentSkyBentNormal(FVector4(0, 0, 1, 1)), bHasEverUpdatedSingleSample(false), bPointSample(true), bIsDirty(false), bUnbuiltPreview(false) { for (int32 VectorIndex = 0; VectorIndex < ARRAY_COUNT(TargetSamplePacked); VectorIndex++) { TargetSamplePacked[VectorIndex] = FVector4(0, 0, 0, 0); SingleSamplePacked[VectorIndex] = FVector4(0, 0, 0, 0); } } /** Add factor for calculating UVs from position. */ FVector Add; /** Scale factor for calculating UVs from position. */ FVector Scale; /** Used to clamp lookup UV to a valid range for pixels outside the object's bounding box. */ FVector MinUV; /** Used to clamp lookup UV to a valid range for pixels outside the object's bounding box. */ FVector MaxUV; /** Block index in the volume texture atlas, can represent unallocated. */ FIntVector MinTexel; /** Size in texels of the allocation into the volume texture atlas. */ int32 AllocationTexelSize; /** Position at the new single lighting sample. Used for interpolation over time. */ FVector TargetPosition; /** SH sample at the new single lighting sample position. Used for interpolation over time. */ FVector4 TargetSamplePacked[sizeof(FSHVectorRGB2) / sizeof(FVector4)]; /** Target shadowing of the stationary directional light. */ float TargetDirectionalShadowing; /** Target directional occlusion of the sky. */ FVector4 TargetSkyBentNormal; /** Current position of the single lighting sample. Used for interpolation over time. */ FVector SingleSamplePosition; /** Current SH sample used when lighting the entire object with one sample. */ FVector4 SingleSamplePacked[sizeof(FSHVectorRGB2) / sizeof(FVector4)]; /** Current shadowing of the stationary directional light. */ float CurrentDirectionalShadowing; /** Current directional occlusion of the sky. */ FVector4 CurrentSkyBentNormal; /** Whether SingleSamplePacked has ever been populated with valid results, used to initialize. */ bool bHasEverUpdatedSingleSample; /** Whether this allocation is a point sample and therefore was not put into the volume texture atlas. */ bool bPointSample; /** Whether the primitive allocation is dirty and should be updated regardless of having moved. */ bool bIsDirty; bool bUnbuiltPreview; void SetDirty() { bIsDirty = true; } bool IsValid() const { return MinTexel.X >= 0 && MinTexel.Y >= 0 && MinTexel.Z >= 0 && AllocationTexelSize > 0; } void SetParameters(FIntVector InMinTexel, int32 InAllocationTexelSize, FVector InScale, FVector InAdd, FVector InMinUV, FVector InMaxUV, bool bInPointSample, bool bInUnbuiltPreview) { Add = InAdd; Scale = InScale; MinUV = InMinUV; MaxUV = InMaxUV; MinTexel = InMinTexel; AllocationTexelSize = InAllocationTexelSize; bIsDirty = false; bPointSample = bInPointSample; bUnbuiltPreview = bInUnbuiltPreview; } }; /** The information needed to determine whether a primitive is visible. */ class FPrimitiveSceneInfoCompact { public: FPrimitiveSceneInfo* PrimitiveSceneInfo; FPrimitiveSceneProxy* Proxy; FBoxSphereBounds Bounds; float MinDrawDistance; float MaxDrawDistance; float LpvBiasMultiplier; /** Used for precomputed visibility */ int32 VisibilityId; uint32 bHasViewDependentDPG : 1; uint32 bCastDynamicShadow : 1; uint32 bAffectDynamicIndirectLighting : 1; uint32 StaticDepthPriorityGroup : SDPG_NumBits; /** Initializes the compact scene info from the primitive's full scene info. */ void Init(FPrimitiveSceneInfo* InPrimitiveSceneInfo); /** Default constructor. */ FPrimitiveSceneInfoCompact(): PrimitiveSceneInfo(NULL), Proxy(NULL) {} /** Initialization constructor. */ FPrimitiveSceneInfoCompact(FPrimitiveSceneInfo* InPrimitiveSceneInfo) { Init(InPrimitiveSceneInfo); } }; /** The type of the octree used by FScene to find primitives. */ typedef TOctree<FPrimitiveSceneInfoCompact,struct FPrimitiveOctreeSemantics> FScenePrimitiveOctree; /** * The renderer's internal state for a single UPrimitiveComponent. This has a one to one mapping with FPrimitiveSceneProxy, which is in the engine module. */ class FPrimitiveSceneInfo : public FDeferredCleanupInterface { public: /** The render proxy for the primitive. */ FPrimitiveSceneProxy* Proxy; /** * Id for the component this primitive belongs to. * This will stay the same for the lifetime of the component, so it can be used to identify the component across re-registers. */ FPrimitiveComponentId PrimitiveComponentId; /** * Pointer to the primitive's last render time variable, which is written to by the RT and read by the GT. * The value of LastRenderTime will therefore not be deterministic due to race conditions, but the GT uses it in a way that allows this. * Storing a pointer to the UObject member variable only works because UPrimitiveComponent has a mechanism to ensure it does not get deleted before the proxy (DetachFence). * In general feedback from the renderer to the game thread like this should be avoided. */ float* ComponentLastRenderTime; /** * The root attachment component id for use with lighting, if valid. * If the root id is not valid, this is a parent primitive. */ FPrimitiveComponentId LightingAttachmentRoot; /** * The component id of the LOD parent if valid. */ FPrimitiveComponentId LODParentComponentId; /** The primitive's static meshes. */ TIndirectArray<class FStaticMesh> StaticMeshes; /** The identifier for the primitive in Scene->PrimitiveOctree. */ FOctreeElementId OctreeId; /** * Caches the primitive's indirect lighting cache allocation. * Note: This is only valid during the rendering of a frame, not just once the primitive is attached. */ const FIndirectLightingCacheAllocation* IndirectLightingCacheAllocation; /** * Reflection capture proxy that was closest to this primitive, used for the forward shading rendering path. */ const FReflectionCaptureProxy* CachedReflectionCaptureProxy; /** Mapping from instance index in this primitive to index in the global distance field object buffers. */ TArray<int32, TInlineAllocator<1>> DistanceFieldInstanceIndices; /** Whether the primitive is newly registered or moved and CachedReflectionCaptureProxy needs to be updated on the next render. */ uint32 bNeedsCachedReflectionCaptureUpdate : 1; /** This primitive has the Motion Blur explicitly disabled */ uint32 bVelocityIsSupressed : 1; /** The hit proxies used by the primitive. */ TArray<TRefCountPtr<HHitProxy> > HitProxies; /** The hit proxy which is used to represent the primitive's dynamic elements. */ HHitProxy* DefaultDynamicHitProxy; /** The ID of the hit proxy which is used to represent the primitive's dynamic elements. */ FHitProxyId DefaultDynamicHitProxyId; /** The list of lights affecting this primitive. */ class FLightPrimitiveInteraction* LightList; /** Last render time in seconds since level started play. */ float LastRenderTime; /** Last time that the primitive became visible in seconds since level started play. */ float LastVisibilityChangeTime; /** The scene the primitive is in. */ FScene* Scene; /** The number of dynamic point lights for ES2 */ int32 NumES2DynamicPointLights; /** Initialization constructor. */ FPrimitiveSceneInfo(UPrimitiveComponent* InPrimitive,FScene* InScene); /** Destructor. */ ~FPrimitiveSceneInfo(); /** Adds the primitive to the scene. */ void AddToScene(FRHICommandListImmediate& RHICmdList, bool bUpdateStaticDrawLists); /** Removes the primitive from the scene. */ void RemoveFromScene(bool bUpdateStaticDrawLists); /** return true if we need to call ConditionalUpdateStaticMeshes */ FORCEINLINE bool NeedsUpdateStaticMeshes() { return bNeedsStaticMeshUpdate; } /** return true if we need to call LazyUpdateForRendering */ FORCEINLINE bool NeedsUniformBufferUpdate() { return bNeedsUniformBufferUpdate; } /** return true if we need to call ConditionalLazyUpdateForRendering */ FORCEINLINE bool NeedsLazyUpdateForRendering() { return NeedsUniformBufferUpdate() || NeedsUpdateStaticMeshes(); } /** Updates the primitive's static meshes in the scene. */ void UpdateStaticMeshes(FRHICommandListImmediate& RHICmdList); /** Updates the primitive's static meshes in the scene. */ FORCEINLINE void ConditionalUpdateStaticMeshes(FRHICommandListImmediate& RHICmdList) { if (NeedsUpdateStaticMeshes()) { UpdateStaticMeshes(RHICmdList); } } /** Updates the primitive's uniform buffer. */ void UpdateUniformBuffer(FRHICommandListImmediate& RHICmdList); /** Updates the primitive's uniform buffer. */ FORCEINLINE void ConditionalUpdateUniformBuffer(FRHICommandListImmediate& RHICmdList) { if (NeedsUniformBufferUpdate()) { UpdateUniformBuffer(RHICmdList); } } /** Updates all lazy data for the rendering. */ FORCEINLINE void ConditionalLazyUpdateForRendering(FRHICommandListImmediate& RHICmdList) { ConditionalUpdateUniformBuffer(RHICmdList); ConditionalUpdateStaticMeshes(RHICmdList); } /** Sets a flag to update the primitive's static meshes before it is next rendered. */ void BeginDeferredUpdateStaticMeshes(); /** Adds the primitive's static meshes to the scene. */ void AddStaticMeshes(FRHICommandListImmediate& RHICmdList); /** Removes the primitive's static meshes from the scene. */ void RemoveStaticMeshes(); /** Set LOD Parent primitive information to the scene. */ void LinkLODParentComponent(); /** clear LOD parent primitive information from the scene. */ void UnlinkLODParentComponent(); /** Adds the primitive to the scene's attachment groups. */ void LinkAttachmentGroup(); /** Removes the primitive from the scene's attachment groups. */ void UnlinkAttachmentGroup(); /** * Builds an array of all primitive scene info's in this primitive's attachment group. * This only works on potential parents (!LightingAttachmentRoot.IsValid()) and will include the current primitive in the output array. */ void GatherLightingAttachmentGroupPrimitives(TArray<FPrimitiveSceneInfo*, SceneRenderingAllocator>& OutChildSceneInfos); /** * Builds a cumulative bounding box of this primitive and all the primitives in the same attachment group. * This only works on potential parents (!LightingAttachmentRoot.IsValid()). */ FBoxSphereBounds GetAttachmentGroupBounds() const; /** Size this class uses in bytes */ uint32 GetMemoryFootprint(); // FDeferredCleanupInterface implementation. virtual void FinishCleanup() { delete this; } /** * Retrieves the index of the primitive in the scene's primitives array. * This index is only valid until a primitive is added to or removed from * the scene! */ inline int32 GetIndex() const { return PackedIndex; } /* @return true if the object needs to be rendered in the velocity pass (is not moving like the world, needed for motionblur and TemporalAA) */ bool ShouldRenderVelocity(const FViewInfo& View, bool bCheckVisibility = true) const; /** * Shifts primitive position and all relevant data by an arbitrary delta. * Called on world origin changes * @param InOffset - The delta to shift by */ void ApplyWorldOffset(FVector InOffset); FORCEINLINE void SetNeedsUniformBufferUpdate(bool bInNeedsUniformBufferUpdate) { bNeedsUniformBufferUpdate = bInNeedsUniformBufferUpdate; } private: /** Let FScene have direct access to the Id. */ friend class FScene; /** * The index of the primitive in the scene's packed arrays. This value may * change as primitives are added and removed from the scene. */ int32 PackedIndex; /** * The UPrimitiveComponent this scene info is for, useful for quickly inspecting properties on the corresponding component while debugging. * This should not be dereferenced on the rendering thread. The game thread can be modifying UObject members at any time. * Use PrimitiveComponentId instead when a component identifier is needed. */ const UPrimitiveComponent* ComponentForDebuggingOnly; /** If this is TRUE, this primitive's static meshes needs to be updated before it can be rendered. */ bool bNeedsStaticMeshUpdate; /** If this is TRUE, this primitive's uniform buffer needs to be updated before it can be rendered. */ bool bNeedsUniformBufferUpdate; }; /** Defines how the primitive is stored in the scene's primitive octree. */ struct FPrimitiveOctreeSemantics { enum { MaxElementsPerLeaf = 16 }; enum { MinInclusiveElementsPerNode = 7 }; enum { MaxNodeDepth = 12 }; typedef TInlineAllocator<MaxElementsPerLeaf> ElementAllocator; FORCEINLINE static const FBoxSphereBounds& GetBoundingBox(const FPrimitiveSceneInfoCompact& PrimitiveSceneInfoCompact) { return PrimitiveSceneInfoCompact.Bounds; } FORCEINLINE static bool AreElementsEqual(const FPrimitiveSceneInfoCompact& A,const FPrimitiveSceneInfoCompact& B) { return A.PrimitiveSceneInfo == B.PrimitiveSceneInfo; } FORCEINLINE static void SetElementId(const FPrimitiveSceneInfoCompact& Element,FOctreeElementId Id) { Element.PrimitiveSceneInfo->OctreeId = Id; } FORCEINLINE static void ApplyOffset(FPrimitiveSceneInfoCompact& Element, FVector Offset) { Element.Bounds.Origin+= Offset; } }; #endif
Physiochemical Properties of Hexagonal Boron Nitride Blended Coconut Oil Lubrication plays a vital role in engineering. Now a day’s reduction in friction is a major and ongoing task for researchers. Few researches are focussing on various Nano additives that lower value of friction and hence wear can be reduced. Therefore, the main objective of this paper is to determine the anti-wear characteristics of the lubricant along with extreme pressure point. Further, also determine the physiochemical properties. In this research coconut oil is used as a lubricant and hexagonal boron nitride (h-BN) is used as friction modifier. The ultrasonic homogenizer was used for mixing of friction modifier with lubricant. Further, four ball test rig was used to obtain the extreme pressure, coefficient of friction and wear scar. After test, balls were characterized using 3D optical profilometer and scanning electron microscopy. From the results, it is observed that 2.5 wt % h-BN with coconut oil gives low coefficient of friction, high extreme pressure with moderate wear scar. Finally, Comparison with commercial mineral oil (CMO), the newly developed additive oil combination is having excellent properties and it can be used as a substitute as it is biodegradable, nontoxic, easily manufactured and environment friendly.
Here it is! The real thing! Recently I was showing my wife some of wrestling’s greatest moments and spent an inordinate amount of time trying to find the original Eric Bischoff debut segment that aired on WWE Raw back in July 2002 where he walked out to AC/DC’s Back In Black in one of the most shocking and memorable moments in wrestling history. Whew, talk about impossible. I never knew this clip was so rare. I found a few uploads across YouTube and DailyMotion, but all were the post-prod version of the segment where AC/DC was replaced with the in-house “I’m Back” song. Was a funny theme and good for Eric’s character once he got rolling in his run at WWE, but the company piping it in over the original audio not only killed the special feeling Back In Black created for the moment, but most of the overdub versions also muted the commentary of Jim Ross and Jerry Lawler which totally drains away the emotion and the genuine novelty we all felt when we first saw it. WWE.com features a flashback video where the commentary can still be heard, but again, without Back In Black, it just isn’t the same. I went into my VHS wrestling vault and found that I still had the recording of the original broadcast. Not sure why YouTube vehemently blocks the video just because of the AC/DC song, but just like the Ricky Harris situation, I have no such qualms about hosting a harmless segment from over 10 years ago. Anyone offended can kind of like, deal with it I guess. Enjoy! Comments comments
// Copyright lowRISC contributors. // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 // print.h's polyglotness is not part of its public API at the moment; we wrap // it in an `extern` here for the time being. extern "C" { #include "sw/device/lib/runtime/print.h" } // extern "C" #include <stdint.h> #include <string> #include "absl/strings/str_format.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "sw/device/lib/base/status.h" #include "sw/device/lib/dif/dif_uart.h" // NOTE: This is only present so that print.c can link without pulling in // dif_uart.c. extern "C" dif_result_t dif_uart_byte_send_polled(const dif_uart *, uint8_t) { return kDifOk; } namespace base { namespace { using ::testing::StartsWith; // A test fixture for automatiocally capturing stdout. class PrintfTest : public testing::Test { protected: void SetUp() override { base_set_stdout({ .data = static_cast<void *>(&buf_), .sink = +[](void *data, const char *buf, size_t len) { static_cast<std::string *>(data)->append(buf, len); return len; }, }); } std::string buf_; }; TEST_F(PrintfTest, EmptyFormat) { EXPECT_EQ(base_printf(""), 0); EXPECT_EQ(buf_, ""); } TEST_F(PrintfTest, TrivialText) { EXPECT_EQ(base_printf("Hello, World!\n"), 14); EXPECT_EQ(buf_, "Hello, World!\n"); } TEST_F(PrintfTest, PartialPrints) { EXPECT_EQ(base_printf("Hello, "), 7); EXPECT_EQ(buf_, "Hello, "); EXPECT_EQ(base_printf("World!\n"), 7); EXPECT_EQ(buf_, "Hello, World!\n"); } TEST_F(PrintfTest, LiteralPct) { EXPECT_EQ(base_printf("Hello, %%!\n"), 10); EXPECT_EQ(buf_, "Hello, %!\n"); } TEST_F(PrintfTest, Character) { EXPECT_EQ(base_printf("Hello, %c!\n", 'X'), 10); EXPECT_EQ(buf_, "Hello, X!\n"); } TEST_F(PrintfTest, Bool) { EXPECT_EQ(base_printf("Hello, %!b, %!b!\n", true, false), 20); EXPECT_EQ(buf_, "Hello, true, false!\n"); } TEST_F(PrintfTest, StringWithNul) { EXPECT_EQ(base_printf("Hello, %s!\n", "abcxyz"), 15); EXPECT_EQ(buf_, "Hello, abcxyz!\n"); } TEST_F(PrintfTest, StringWithLen) { EXPECT_EQ(base_printf("Hello, %!s!\n", 6, "abcxyz"), 15); EXPECT_EQ(buf_, "Hello, abcxyz!\n"); } TEST_F(PrintfTest, StringWithLenPrefix) { EXPECT_EQ(base_printf("Hello, %!s!\n", 3, "abcxyz"), 12); EXPECT_EQ(buf_, "Hello, abc!\n"); } TEST_F(PrintfTest, StringWithLenZeroLen) { EXPECT_EQ(base_printf("Hello, %!s!\n", 0, "abcxyz"), 9); EXPECT_EQ(buf_, "Hello, !\n"); } TEST_F(PrintfTest, HexStringWithLen) { uint32_t val = 0xdeadbeef; EXPECT_EQ(base_printf("Hello, %!x!\n", 4, &val), 17); EXPECT_EQ(buf_, "Hello, deadbeef!\n"); } TEST_F(PrintfTest, HexStringWithLenPrefix) { uint32_t val = 0xdeadbeef; EXPECT_EQ(base_printf("Hello, %!x!\n", 1, &val), 11); EXPECT_EQ(buf_, "Hello, ef!\n"); } TEST_F(PrintfTest, HexStringWithLenZeroLen) { uint32_t val = 0xdeadbeef; EXPECT_EQ(base_printf("Hello, %!x!\n", 0, &val), 9); EXPECT_EQ(buf_, "Hello, !\n"); } TEST_F(PrintfTest, UpperHexStringWithLen) { uint32_t val = 0xdeadbeef; EXPECT_EQ(base_printf("Hello, %!X!\n", 4, &val), 17); EXPECT_EQ(buf_, "Hello, DEADBEEF!\n"); } TEST_F(PrintfTest, UpperHexStringWithLenPrefix) { uint32_t val = 0xdeadbeef; EXPECT_EQ(base_printf("Hello, %!X!\n", 1, &val), 11); EXPECT_EQ(buf_, "Hello, EF!\n"); } TEST_F(PrintfTest, UpperHexStringWithLenZeroLen) { uint32_t val = 0xdeadbeef; EXPECT_EQ(base_printf("Hello, %!X!\n", 0, &val), 9); EXPECT_EQ(buf_, "Hello, !\n"); } TEST_F(PrintfTest, LeHexStringWithLen) { uint32_t val = 0xdeadbeef; EXPECT_EQ(base_printf("Hello, %!y!\n", 4, &val), 17); EXPECT_EQ(buf_, "Hello, efbeadde!\n"); } TEST_F(PrintfTest, UpperLeHexStringWithLen) { uint32_t val = 0xdeadbeef; EXPECT_EQ(base_printf("Hello, %!Y!\n", 4, &val), 17); EXPECT_EQ(buf_, "Hello, EFBEADDE!\n"); } TEST_F(PrintfTest, SignedInt) { EXPECT_EQ(base_printf("Hello, %i!\n", 42), 11); EXPECT_EQ(buf_, "Hello, 42!\n"); } TEST_F(PrintfTest, SignedIntZero) { EXPECT_EQ(base_printf("Hello, %d!\n", 0), 10); EXPECT_EQ(buf_, "Hello, 0!\n"); } TEST_F(PrintfTest, SignedIntAlt) { EXPECT_EQ(base_printf("Hello, %d!\n", 42), 11); EXPECT_EQ(buf_, "Hello, 42!\n"); } TEST_F(PrintfTest, SignedIntNegative) { EXPECT_EQ(base_printf("Hello, %i!\n", -800), 13); EXPECT_EQ(buf_, "Hello, -800!\n"); } TEST_F(PrintfTest, SignedIntWithWidth) { EXPECT_EQ(base_printf("Hello, %3i!\n", 42), 12); EXPECT_EQ(buf_, "Hello, 42!\n"); } TEST_F(PrintfTest, SignedIntWithWidthTooShort) { EXPECT_EQ(base_printf("Hello, %3i!\n", 9001), 13); EXPECT_EQ(buf_, "Hello, 9001!\n"); } TEST_F(PrintfTest, SignedIntWithZeros) { EXPECT_EQ(base_printf("Hello, %03i!\n", 42), 12); EXPECT_EQ(buf_, "Hello, 042!\n"); } TEST_F(PrintfTest, SignedIntWithZerosTooShort) { EXPECT_EQ(base_printf("Hello, %03i!\n", 9001), 13); EXPECT_EQ(buf_, "Hello, 9001!\n"); } TEST_F(PrintfTest, UnsignedInt) { EXPECT_EQ(base_printf("Hello, %u!\n", 42), 11); EXPECT_EQ(buf_, "Hello, 42!\n"); } TEST_F(PrintfTest, UnsignedIntNegative) { EXPECT_EQ(base_printf("Hello, %u!\n", -1), 19); EXPECT_EQ(buf_, "Hello, 4294967295!\n"); } TEST_F(PrintfTest, HexFromDec) { EXPECT_EQ(base_printf("Hello, %x!\n", 1024), 12); EXPECT_EQ(buf_, "Hello, 400!\n"); } TEST_F(PrintfTest, HexFromDecWithWidth) { EXPECT_EQ(base_printf("Hello, %08x!\n", 1024), 17); EXPECT_EQ(buf_, "Hello, 00000400!\n"); } TEST_F(PrintfTest, HexLower) { EXPECT_EQ(base_printf("Hello, %x!\n", 0xdead'beef), 17); EXPECT_EQ(buf_, "Hello, deadbeef!\n"); } TEST_F(PrintfTest, HexUpper) { EXPECT_EQ(base_printf("Hello, %X!\n", 0xdead'beef), 17); EXPECT_EQ(buf_, "Hello, DEADBEEF!\n"); } TEST_F(PrintfTest, HexNegative) { EXPECT_EQ(base_printf("Hello, %x!\n", -1), 17); EXPECT_EQ(buf_, "Hello, ffffffff!\n"); } TEST_F(PrintfTest, HexSvLower) { EXPECT_EQ(base_printf("Hello, %h!\n", 0xdead'beef), 17); EXPECT_EQ(buf_, "Hello, deadbeef!\n"); } TEST_F(PrintfTest, HexSvUpper) { EXPECT_EQ(base_printf("Hello, %H!\n", 0xdead'beef), 17); EXPECT_EQ(buf_, "Hello, DEADBEEF!\n"); } TEST_F(PrintfTest, Pointer) { auto *ptr = reinterpret_cast<uint32_t *>(0x1234); base_printf("Hello, %p!\n", ptr); switch (sizeof(uintptr_t)) { case 4: EXPECT_EQ(buf_, "Hello, 0x00001234!\n"); break; case 8: EXPECT_EQ(buf_, "Hello, 0x0000000000001234!\n"); break; default: FAIL() << "Unknown pointer size"; break; } } TEST_F(PrintfTest, NullPtr) { base_printf("Hello, %p!\n", nullptr); switch (sizeof(uintptr_t)) { case 4: EXPECT_EQ(buf_, "Hello, 0x00000000!\n"); break; case 8: EXPECT_EQ(buf_, "Hello, 0x0000000000000000!\n"); break; default: FAIL() << "Unknown pointer size"; break; } } TEST_F(PrintfTest, Octal) { EXPECT_EQ(base_printf("Hello, %o!\n", 01234567), 16); EXPECT_EQ(buf_, "Hello, 1234567!\n"); } TEST_F(PrintfTest, Binary) { EXPECT_EQ(base_printf("Hello, %b!\n", 0b1010'1010), 17); EXPECT_EQ(buf_, "Hello, 10101010!\n"); } TEST_F(PrintfTest, BinaryWithWidth) { EXPECT_EQ(base_printf("Hello, %032b!\n", 0b1010'1010), 41); EXPECT_EQ(buf_, "Hello, 00000000000000000000000010101010!\n"); } TEST_F(PrintfTest, StatusOk) { status_t value = OK_STATUS(); EXPECT_EQ(base_printf("Hello, %r\n", value), 12); EXPECT_EQ(buf_, "Hello, Ok:0\n"); } TEST_F(PrintfTest, StatusOkWithArg) { status_t value = OK_STATUS(12345); EXPECT_EQ(base_printf("Hello, %r\n", value), 16); EXPECT_EQ(buf_, "Hello, Ok:12345\n"); } TEST_F(PrintfTest, StatusError) { status_t value = UNKNOWN(); int line = __LINE__ - 1; EXPECT_EQ(base_printf("Hello, %r\n", value), 27); EXPECT_EQ(buf_, absl::StrFormat("Hello, Unknown:[\"PRI\",%d]\n", line)); } TEST_F(PrintfTest, StatusErrorAsJson) { status_t value = UNKNOWN(); int line = __LINE__ - 1; EXPECT_EQ(base_printf("Hello, %!r\n", value), 31); EXPECT_EQ(buf_, absl::StrFormat("Hello, {\"Unknown\":[\"PRI\",%d]}\n", line)); } TEST_F(PrintfTest, StatusErrorWithArg) { status_t value = INVALID_ARGUMENT(2); EXPECT_EQ(base_printf("Hello, %r\n", value), 33); EXPECT_EQ(buf_, absl::StrFormat("Hello, InvalidArgument:[\"PRI\",%d]\n", 2)); } TEST_F(PrintfTest, IncompleteSpec) { base_printf("Hello, %"); EXPECT_THAT(buf_, StartsWith("Hello, ")); } TEST_F(PrintfTest, UnknownSpec) { base_printf("Hello, %j"); EXPECT_THAT(buf_, StartsWith("Hello, ")); } TEST_F(PrintfTest, WidthTooNarrow) { base_printf("Hello, %0x"); EXPECT_THAT(buf_, StartsWith("Hello, ")); } TEST_F(PrintfTest, WidthTooWide) { base_printf("Hello, %9001x"); EXPECT_THAT(buf_, StartsWith("Hello, ")); } TEST_F(PrintfTest, ManySpecifiers) { base_printf("%d + %d == %d, also spelled 0x%x", 2, 8, 2 + 8, 2 + 8); EXPECT_THAT(buf_, StartsWith("2 + 8 == 10, also spelled 0xa")); } TEST_F(PrintfTest, HexDump) { constexpr char kStuff[] = "a very long string pot\x12\x02\xAA entially containing garbage"; base_hexdump(kStuff, sizeof(kStuff) - 1); EXPECT_THAT( buf_, R"hex(00000000: 6120 7665 7279 206c 6f6e 6720 7374 7269 a very long stri 00000010: 6e67 2070 6f74 1202 aa20 656e 7469 616c ng pot... ential 00000020: 6c79 2063 6f6e 7461 696e 696e 6720 6761 ly containing ga 00000030: 7262 6167 65 rbage )hex"); buf_.clear(); base_hexdump_with({3, 5, &kBaseHexdumpDefaultFmtAlphabet}, kStuff, sizeof(kStuff) - 1); EXPECT_THAT( buf_, R"hex(00000000: 612076 657279 206c6f 6e6720 737472 a very long str 0000000f: 696e67 20706f 741202 aa2065 6e7469 ing pot... enti 0000001e: 616c6c 792063 6f6e74 61696e 696e67 ally containing 0000002d: 206761 726261 6765 garbage )hex"); } TEST(SnprintfTest, SimpleWrite) { std::string buf(128, '\0'); auto len = base_snprintf(&buf[0], buf.size(), "Hello, World!\n"); buf.resize(len); EXPECT_EQ(len, 14); EXPECT_EQ(buf, "Hello, World!\n"); } TEST(SnprintfTest, ComplexFormating) { std::string buf(128, '\0'); auto len = base_snprintf(&buf[0], buf.size(), "%d + %d == %d, also spelled 0x%x", 2, 8, 2 + 8, 2 + 8); buf.resize(len); EXPECT_EQ(buf, "2 + 8 == 10, also spelled 0xa"); } TEST(SnprintfTest, PartialWrite) { std::string buf(16, '\0'); auto len = base_snprintf(&buf[0], buf.size(), "%d + %d == %d, also spelled 0x%x", 2, 8, 2 + 8, 2 + 8); buf.resize(len); EXPECT_EQ(len, 16); EXPECT_EQ(buf, "2 + 8 == 10, als"); } } // namespace } // namespace base
def build_discourse_tree(edu_ids, parent_ids): ids_and_parents = zip(edu_ids, parent_ids) ids_and_parents.sort(key=lambda t: t[0]) by_id = itertools.groupby(ids_and_parents, key=lambda t: t[0]) nodes = [] ids_to_nodes = {} for k, g in by_id: g = list(g) new_node = DiscourseTreeNode(k, g[0][1], len(g)) nodes.append(new_node) ids_to_nodes[k] = new_node for node in nodes: if node.parent_id != -1: parent_node = ids_to_nodes[node.parent_id] node.parent = parent_node parent_node.children.append(node) root_node = (node for node in nodes if node.parent_id == -1).next() for node in discourse_tree_depth_first_walk(root_node): if node.parent_id != -1: node.parent.total_num_leaves += node.total_num_leaves for node in nodes: if node.children: node.child_sum_tree = build_sum_tree( [(n.total_num_leaves + 1, n.node_id) for n in node.children]) add_tree_levels(root_node) return root_node
use snake::Snake; use state::WorldState; use nalgebra::{Point2, Vector2}; use ncollide::shape::{Cuboid, Ball}; use ncollide::query::{Ray, RayCast}; use nalgebra::Isometry2; use std; #[allow(unused)] /// Return a vector of all senses experienced by snake: &Snake in the world: &WorldState pub fn get(snake: &Snake, world: &WorldState) -> Vec<f64> { // If I need more senses just concatenate the Vec<f64> from that additional sense. get_vision(snake, world) } /// Finds minimum value in a vector, neded for get_vision() fn min_val(vector: Vec<f64>) -> f64 { let mut min_val = vector[0]; for val in &vector { if *val < min_val { min_val = *val; } } min_val } #[allow(unused)] /// Get vision for a &Snake in a &WorldState by ray tracing fn get_vision(snake: &Snake, world: &WorldState) -> Vec<f64> { let mut vision: Vec<f64> = Vec::new(); let head = &snake.parts[0]; let head_point = Point2::new(head.origin.x, head.origin.y); let fov = 0.6 * std::f64::consts::PI; // ~110 degrees let mut rotation = head.rotation - fov / 2.0; let rotation_inc = fov / 16.0; // Spawn 16 rays. for i in 0..16 { // You can read this part like a poetry slam and perform it high. let hits = cast_ray(snake, world, &rotation, &head_point); for hit in hits.iter() { vision.push(*hit); } rotation += rotation_inc; } vision } /// Casts a single ray for a snake and return an array containing "vision values" for all seeable /// values. Vision values are 1 if the seen object is close, and -1 if it didn't see the object. /// Index 0 in the vision values is for food_hit and index 1 is for wall_hit. fn cast_ray(snake: &Snake, world: &WorldState, rotation: &f64, head_point: &Point2<f64>) -> [f64; 2] { // Get a point on a circle, in this case a point on a circle with radius 1.0 // around our head origin rotated by the head rotation; aka our unit vector for the ray. let dir_x = head_point.x + 1.0 * rotation.cos(); // 1.0 being the radius let dir_y = head_point.y + 1.0 * rotation.sin(); let ray_direction = Vector2::new(dir_x, dir_y); // Unit vector let ray_origin = Point2::new(head_point.x, head_point.y); let ray = Ray::new(ray_origin, ray_direction); // Each ray makes 2 float values, for each visible object. // Rays can pass through objects so need to make a vector of hits and // then only use the one that is closest to to the snake. // let mut snake_hits = Vec::new(); let mut food_hits = Vec::new(); let mut wall_hit = -1.0f64; // Cant hit several walls so wont need to check. let wr = Vector2::new((world.window_rect[0] / 2) as f64, (world.window_rect[1] / 2) as f64); // Cuboid::new wants a vector2 of the cubes half extents, thats why I divide by 2. let window = Cuboid::new(Vector2::new(wr[0], wr[1])); // We need to move the windows origin to the center of the screen. let window_transform = Isometry2::new(Vector2::new(wr[0], wr[0]), 0.0); // Check if the bounds of the window transformed by window_transform is hit by our ray. // returns None if there was no hit or Some(toi) with a time of impact of the ray, less // value meaning the object is closer to the window. if let Some(toi) = window.toi_with_ray(&window_transform, &ray, false) { // False here means non-solid cast; basically math speak for a ray that can be cast from // within a object. wall_hit = 1.0 - (toi as f64 / 2.0); if wall_hit > 1.0 { wall_hit = 1.0; } else if wall_hit < -1.0 { wall_hit = -1.0; } } for _snake in &world.snakes { // For each snake if _snake.parts[0].origin != snake.parts[0].origin { // ... that is not self for part in &_snake.parts { // ... loop through each part of snake, and see if it's food. if part.is_food { // ... see if food colides with ray. let ball = Ball::new(part.radius); // Food is represented as a 2d ball. let ball_transform = Isometry2::new(Vector2::new(part.origin.x, part.origin.y), 0.0); // Gets time of impact of ray to ball transformed by ball_transform. // If ray doesn't hit ball, it returns None. if let Some(toi) = ball.toi_with_ray(&ball_transform, &ray, true) { food_hits.push(toi); } } } } } // Find smallest toi's in hits and use those, // preventing snake to have x-ray vision. // A value of 2.0 should be treated as -1, a value of 0 should be treated as 1 let mut food_hit = -1.0; if !food_hits.is_empty() { //println!("wall_hit {}", wall_hit); food_hit = 1.0 - min_val(food_hits) / 1.2; if food_hit > 1.0 { food_hit = 1.0; } else if food_hit < -1.0 { food_hit = -1.0; } } [food_hit, wall_hit] //snake_hit] }
#include "asd.MediaPlayerWMF.h" #ifdef _WIN32 #include "../../asd.Graphics.h" #include "../../asd.Graphics_Imp.h" #include <propvarutil.h> namespace asd { void MediaPlayerWMF::ThreadLoop() { while (isPlaying) { { auto now = std::chrono::system_clock::now(); auto diff = now - startTime; auto diff_micro = std::chrono::duration_cast<std::chrono::microseconds>(diff).count(); if (diff_micro + 1000 < (currentFrame / fps) * 1000 * 1000) { auto sleeping = (currentFrame / fps) * 1000 * 1000 - diff_micro; std::this_thread::sleep_for(std::chrono::microseconds((int)sleeping)); } } DWORD flags; IMFSample* sample; reader->ReadSample(MF_SOURCE_READER_FIRST_VIDEO_STREAM, 0, NULL, &flags, NULL, &sample); if (sample == nullptr) { // Loop if (isLoopingMode) { PROPVARIANT propvar; HRESULT hr = InitPropVariantFromInt64(0, &propvar); reader->SetCurrentPosition(GUID_NULL, propvar); PropVariantClear(&propvar); currentFrame = 0; startTime = std::chrono::system_clock::now(); reader->ReadSample(MF_SOURCE_READER_FIRST_VIDEO_STREAM, 0, NULL, &flags, NULL, &sample); if (sample == nullptr) { isPlaying = false; break; } } else { isPlaying = false; break; } } IMFMediaBuffer* buffer; sample->GetBufferByIndex(0, &buffer); BYTE* p; DWORD size; buffer->Lock(&p, NULL, &size); if (size != internalBufferYUY.size()) { buffer->Unlock(); buffer->Release(); sample->Release(); isPlaying = false; break; } memcpy(internalBufferYUY.data(), p, size); buffer->Unlock(); buffer->Release(); sample->Release(); for (int32_t y = 0; y < height; y++) { for (int32_t x = 0; x < width; x += 2) { auto src = internalBufferYUY.data() + (x + (y * width)) * 2; auto y0 = (int)src[0]; auto u0 = (int)src[1] - 128; auto y1 = (int)src[2]; auto v0 = (int)src[3] - 128; auto R0 = 1.000 * y0 + 1.402 * v0; auto G0 = 1.000 * y0 - 0.344 * u0 - 0.714 * v0; auto B0 = 1.000 * y0 + 1.772 * u0; auto R1 = 1.000 * y1 + 1.402 * v0; auto G1 = 1.000 * y1 - 0.344 * u0 - 0.714 * v0; auto B1 = 1.000 * y1 + 1.772 * u0; if (R0 > 255) R0 = 255; if (G0 > 255) G0 = 255; if (B0 > 255) B0 = 255; if (R1 > 255) R1 = 255; if (G1 > 255) G1 = 255; if (B1 > 255) B1 = 255; if (R0 < 0) R0 = 0; if (G0 < 0) G0 = 0; if (B0 < 0) B0 = 0; if (R1 < 0) R1 = 0; if (G1 < 0) G1 = 0; if (B1 < 0) B1 = 0; internalBufferEditing[(x + y * width) * 4 + 0] = R0; internalBufferEditing[(x + y * width) * 4 + 1] = G0; internalBufferEditing[(x + y * width) * 4 + 2] = B0; internalBufferEditing[(x + y * width) * 4 + 3] = 255; internalBufferEditing[(x + 1 + y * width) * 4 + 0] = R1; internalBufferEditing[(x + 1 + y * width) * 4 + 1] = G1; internalBufferEditing[(x + 1 + y * width) * 4 + 2] = B1; internalBufferEditing[(x + 1 + y * width) * 4 + 3] = 255; } } { std::lock_guard<std::mutex> lock(mtx); internalBuffer = internalBufferEditing; } currentFrame++; } } MediaPlayerWMF::MediaPlayerWMF(Graphics* graphics) : graphics(graphics) { SafeAddRef(graphics); CoInitialize(NULL); MFStartup(MF_VERSION); } MediaPlayerWMF::~MediaPlayerWMF() { if (isThreadRequiredToJoin) { isPlaying = false; thread_.join(); isThreadRequiredToJoin = false; } SafeRelease(reader); MFShutdown(); CoUninitialize(); SafeRelease(graphics); } bool MediaPlayerWMF::Play(bool isLoopingMode) { if (reader == nullptr) return false; this->isLoopingMode = isLoopingMode; isPlaying = true; isThreadRequiredToJoin = true; startTime = std::chrono::system_clock::now(); thread_ = std::thread( [this]()->void { this->ThreadLoop(); }); return true; } void MediaPlayerWMF::Write(void* dst) { std::lock_guard<std::mutex> lock(mtx); memcpy(dst, internalBuffer.data(), internalBuffer.size()); } bool MediaPlayerWMF::SetSourceFromPath(const char16_t* path) { HRESULT hr; hr = MFCreateSourceReaderFromURL((const wchar_t*)path, NULL, &reader); if (FAILED(hr)) { return false; } IMFMediaType* mediaType = nullptr; MFCreateMediaType(&mediaType); mediaType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video); mediaType->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_YUY2); hr = reader->SetCurrentMediaType(MF_SOURCE_READER_FIRST_VIDEO_STREAM, 0, mediaType); if (FAILED(hr)) { reader->Release(); reader = nullptr; mediaType->Release(); return false; } uint32_t nume, denom; reader->GetCurrentMediaType(MF_SOURCE_READER_FIRST_VIDEO_STREAM, &mediaType); MFGetAttributeSize(mediaType, MF_MT_FRAME_SIZE, &width, &height); MFGetAttributeRatio(mediaType, MF_MT_FRAME_RATE, &nume, &denom); fps = (float)nume / denom; mediaType->Release(); internalBufferYUY.resize(width * height * 2); internalBuffer.resize(width * height * 4); internalBufferEditing.resize(width * height * 4); return true; } int32_t MediaPlayerWMF::GetWidth() const { return width; } int32_t MediaPlayerWMF::GetHeight() const { return height; } int32_t MediaPlayerWMF::GetCurrentFrame() const { return currentFrame; } bool MediaPlayerWMF::Load(const achar* path) { return SetSourceFromPath(path); } bool MediaPlayerWMF::WriteToTexture2D(Texture2D* target) { if (target == nullptr) return false; if (target->GetSize() != GetSize()) return false; if (!(target->GetFormat() == TextureFormat::R8G8B8A8_UNORM || target->GetFormat() == TextureFormat::R8G8B8A8_UNORM_SRGB)) return false; TextureLockInfomation l; if (target->Lock(&l)) { Write(l.GetPixels()); target->Unlock(); return true; } return false; } } #endif
// Auth function for basic username/password auth implementations. Takes a // username and password and constructs the Authorization header. // Vars: // apiRequest = The ApiRequest to be used. // authParams = JWT params in the order of: // [0] => username // [1] => password func BasicAuth(apiRequest generic_structs.ApiRequest, authParams []string) generic_structs.ApiRequest { apiRequest.FullRequest.SetBasicAuth(authParams[0], authParams[1]) return apiRequest }
/** * print all binary for given digits * @param numDigits * @param intent */ void printGivenBinaryNumberDigit(int numDigits, String intent) { if (numDigits <= 0) { System.out.println(intent); } else { printGivenBinaryNumberDigit(numDigits - 1, intent + 0); printGivenBinaryNumberDigit(numDigits - 1, intent + 1); } }
import copy import numpy as np import time import torch import torch.nn as nn import torch.nn.functional as F class Actor(nn.Module): def __init__(self, state_dim, action_dim, max_action, hidden_sizes=[400, 300]): super(Actor, self).__init__() self.l1 = nn.Linear(state_dim, hidden_sizes[0]) self.l2 = nn.Linear(hidden_sizes[0], hidden_sizes[1]) self.l3 = nn.Linear(hidden_sizes[1], action_dim) self.max_action = max_action def forward(self, state): a = F.relu(self.l1(state)) a = F.relu(self.l2(a)) return self.max_action * torch.tanh(self.l3(a)) class Critic(nn.Module): def __init__(self, state_dim, action_dim, hidden_sizes=[400, 300]): super(Critic, self).__init__() self.l1 = nn.Linear(state_dim + action_dim, hidden_sizes[0]) self.l2 = nn.Linear(hidden_sizes[0], hidden_sizes[1]) self.l3 = nn.Linear(hidden_sizes[1], 1) def forward(self, state, action): if len(state.shape) == 3: sa = torch.cat([state, action], 2) else: sa = torch.cat([state, action], 1) q = F.relu(self.l1(sa)) q = F.relu(self.l2(q)) q = self.l3(q) return q class DATD3(object): def __init__( self, state_dim, action_dim, max_action, device, discount=0.99, tau=0.005, policy_noise=0.2, noise_clip=0.5, actor_lr=1e-3, critic_lr=1e-3, hidden_sizes=[400, 300], ): self.device = device self.actor1 = Actor(state_dim, action_dim, max_action, hidden_sizes).to(self.device) self.actor1_target = copy.deepcopy(self.actor1) self.actor1_optimizer = torch.optim.Adam(self.actor1.parameters(), lr=actor_lr) self.actor2 = Actor(state_dim, action_dim, max_action, hidden_sizes).to(self.device) self.actor2_target = copy.deepcopy(self.actor2) self.actor2_optimizer = torch.optim.Adam(self.actor2.parameters(), lr=actor_lr) self.critic1 = Critic(state_dim, action_dim, hidden_sizes).to(self.device) self.critic1_target = copy.deepcopy(self.critic1) self.critic1_optimizer = torch.optim.Adam(self.critic1.parameters(), lr=critic_lr) self.critic2 = Critic(state_dim, action_dim, hidden_sizes).to(self.device) self.critic2_target = copy.deepcopy(self.critic2) self.critic2_optimizer = torch.optim.Adam(self.critic2.parameters(), lr=critic_lr) self.max_action = max_action self.discount = discount self.tau = tau self.policy_noise = policy_noise self.noise_clip = noise_clip def select_action(self, state): state = torch.FloatTensor(state.reshape(1, -1)).to(self.device) action1 = self.actor1(state) action2 = self.actor2(state) q1 = self.critic1(state, action1) q2 = self.critic2(state, action2) action = action1 if q1 >= q2 else action2 return action.cpu().data.numpy().flatten() def train(self, replay_buffer, batch_size=100): ## cross update scheme self.train_one_q_and_pi(replay_buffer, True, batch_size=batch_size) self.train_one_q_and_pi(replay_buffer, False, batch_size=batch_size) def train_one_q_and_pi(self, replay_buffer, update_a1 = True, batch_size=100): state, action, next_state, reward, not_done = replay_buffer.sample(batch_size) with torch.no_grad(): next_action1 = self.actor1_target(next_state) next_action2 = self.actor2_target(next_state) noise = torch.randn( (action.shape[0], action.shape[1]), dtype=action.dtype, layout=action.layout, device=action.device ) * self.policy_noise noise = noise.clamp(-self.noise_clip, self.noise_clip) next_action1 = (next_action1 + noise).clamp(-self.max_action, self.max_action) next_action2 = (next_action2 + noise).clamp(-self.max_action, self.max_action) next_Q1_a1 = self.critic1_target(next_state, next_action1) next_Q2_a1 = self.critic2_target(next_state, next_action1) next_Q1_a2 = self.critic1_target(next_state, next_action2) next_Q2_a2 = self.critic2_target(next_state, next_action2) ## min first, max afterward to avoid underestimation bias next_Q1 = torch.min(next_Q1_a1, next_Q2_a1) next_Q2 = torch.min(next_Q1_a2, next_Q2_a2) next_Q = torch.max(next_Q1, next_Q2) target_Q = reward + not_done * self.discount * next_Q if update_a1: current_Q1 = self.critic1(state, action) critic1_loss = F.mse_loss(current_Q1, target_Q) self.critic1_optimizer.zero_grad() critic1_loss.backward() self.critic1_optimizer.step() actor1_loss = -self.critic1(state, self.actor1(state)).mean() self.actor1_optimizer.zero_grad() actor1_loss.backward() self.actor1_optimizer.step() for param, target_param in zip(self.critic1.parameters(), self.critic1_target.parameters()): target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data) for param, target_param in zip(self.actor1.parameters(), self.actor1_target.parameters()): target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data) else: current_Q2 = self.critic2(state, action) critic2_loss = F.mse_loss(current_Q2, target_Q) self.critic2_optimizer.zero_grad() critic2_loss.backward() self.critic2_optimizer.step() actor2_loss = -self.critic2(state, self.actor2(state)).mean() self.actor2_optimizer.zero_grad() actor2_loss.backward() self.actor2_optimizer.step() for param, target_param in zip(self.critic2.parameters(), self.critic2_target.parameters()): target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data) for param, target_param in zip(self.actor2.parameters(), self.actor2_target.parameters()): target_param.data.copy_(self.tau * param.data + (1 - self.tau) * target_param.data) def save(self, filename): torch.save(self.critic1.state_dict(), filename + "_critic1") torch.save(self.critic1_optimizer.state_dict(), filename + "_critic1_optimizer") torch.save(self.actor1.state_dict(), filename + "_actor1") torch.save(self.actor1_optimizer.state_dict(), filename + "_actor1_optimizer") torch.save(self.critic2.state_dict(), filename + "_critic2") torch.save(self.critic2_optimizer.state_dict(), filename + "_critic2_optimizer") torch.save(self.actor2.state_dict(), filename + "_actor2") torch.save(self.actor2_optimizer.state_dict(), filename + "_actor2_optimizer") def load(self, filename): self.critic1.load_state_dict(torch.load(filename + "_critic1")) self.critic1_optimizer.load_state_dict(torch.load(filename + "_critic1_optimizer")) self.actor1.load_state_dict(torch.load(filename + "_actor1")) self.actor1_optimizer.load_state_dict(torch.load(filename + "_actor1_optimizer")) self.critic2.load_state_dict(torch.load(filename + "_critic2")) self.critic2_optimizer.load_state_dict(torch.load(filename + "_critic2_optimizer")) self.actor2.load_state_dict(torch.load(filename + "_actor2")) self.actor2_optimizer.load_state_dict(torch.load(filename + "_actor2_optimizer"))
/****************************************************************************/ /* */ /* This file is part of QSopt_ex. */ /* */ /* (c) Copyright 2006 by David Applegate, William Cook, Sanjeeb Dash, */ /* and Daniel Espinoza. Sanjeeb Dash's ownership of copyright in */ /* QSopt_ex is derived from his copyright in QSopt. */ /* */ /* This code may be used under the terms of the GNU General Public License */ /* (Version 2.1 or later) as published by the Free Software Foundation. */ /* */ /* Alternatively, use is granted for research purposes only. */ /* */ /* It is your choice of which of these two licenses you are operating */ /* under. */ /* */ /* We make no guarantees about the correctness or usefulness of this code. */ /* */ /****************************************************************************/ /* RCSINFO $Id: dbl_lpdata.h,v 1.4 2003/11/05 17:00:56 meven Exp $ */ #ifndef dbl_ILL_LPDATA_H #define dbl_ILL_LPDATA_H #include "config.h" #include "dbl_qstruct.h" #include "dbl_iqsutil.h" #include "dbl_readline.h" #include "reporter.h" #include "dbl_format.h" #include "dbl_dstruct.h" extern double dbl_ILL_MAXDOUBLE; /* 1267650600228229401496703205376.0 this is equal to 2^100 = 1.267e30 */ extern double dbl_ILL_MINDOUBLE; /* -1267650600228229401496703205376.0 this is equal to -2^100 = -1.267e30 */ #define dbl_ILL_MAXINT (2147483647) /* this is equal to 2^31-1 */ #define dbl_ILL_MIN (1) /* Must be same as QS_MIN */ #define dbl_ILL_MAX (-1) /* Must be same as QS_MAX */ /* Setting Alg in Presolve */ #define dbl_ILL_PRE_SCALE 1 #define dbl_ILL_PRE_FIXED 2 #define dbl_ILL_PRE_SINGLE_ROW 4 #define dbl_ILL_PRE_FORCING 8 #define dbl_ILL_PRE_SINGLE_COL 16 #define dbl_ILL_PRE_DUPLICATE_ROW 32 #define dbl_ILL_PRE_DUPLICATE_COL 64 #define dbl_ILL_PRE_EMPTY_COL 128 #define dbl_ILL_PRE_ALL (dbl_ILL_PRE_SCALE | dbl_ILL_PRE_FIXED | dbl_ILL_PRE_SINGLE_ROW \ dbl_ILL_PRE_FORCING | dbl_ILL_PRE_SINGLE_COL | dbl_ILL_PRE_DUPLICATE_ROW \ dbl_ILL_PRE_DUPLICATE_COL | dbl_ILL_PRE_EMPTY_COL) #define dbl_ILL_PRE_SIMPLE (dbl_ILL_PRE_FIXED | dbl_ILL_PRE_EMPTY_COL) typedef struct dbl_ILLlpdata { /* Complete LP data filled in by mpsread. */ int nrows; int ncols; int nstruct; /* Not including logicals. */ int nzcount; int rowsize; /* Length of row arrays. */ int colsize; /* Length of col arrays. */ int structsize; /* Length of intmarker, structmap, */ /* colnames */ int objsense; char *sense; /* Original sense, not after logicals. */ double *obj; double *rhs; double *rangeval; double *lower; double *upper; dbl_ILLmatrix A; /* The coef matrix. */ struct dbl_ILLlp_rows *rA; /* Coef matrix in row form. */ char **rownames; ILLsymboltab rowtab; /* contains rownames in no particular order */ char *objname; /* if colname is not NULL it is entered into * the rowtab, see reader fcts in dbl_lp.c, dbl_mps.c*/ char **colnames; /* columns of struct variables */ ILLsymboltab coltab; /* contains colnames in no particular order */ char *probname; char *intmarker; int *structmap; /* Indices of structural variables */ int *rowmap; /* Indices of logical and range variables */ struct dbl_ILLlp_basis *basis; struct dbl_ILLlp_predata *presolve; struct dbl_ILLlp_sinfo *sinfo; /**************************************************************************/ /* these fields are currently only set by dbl_mps.c reader fcts */ /**************************************************************************/ dbl_ILLmatrix sos; /* columns are the sets, rows are the * problem's structural variables * coefficients are the weights */ char *sos_type; /* type of each set */ int *is_sos_mem; /* for each structural variable contains * -1 == not a set member * i == member of sos set i * where 0 <= i < sos.matcols */ char *refrowname; /* name of reference row */ int refind; /* index of reference row * -1 if refrow was a free row * and weights are found only in the * sos matrix * index >=0 if refrow is also a lp-row */ /************************************************************************** * dbl_QSset_reporter initializes reporter **************************************************************************/ qsstring_reporter reporter; /* used from within ILL fcts * to report dbl_feedback */ } dbl_ILLlpdata; typedef struct dbl_ILLlp_basis { int nstruct; int nrows; int rownorms_size; int colnorms_size; char *cstat; char *rstat; double *rownorms; double *colnorms; } dbl_ILLlp_basis; typedef struct dbl_ILLlp_cache { int nstruct; int nrows; int status; double val; double *x; double *pi; double *rc; double *slack; } dbl_ILLlp_cache; typedef struct dbl_ILLlp_sinfo { /* LP info returned by presolve */ int ncols; int nrows; int nzcount; int rowsize; int colsize; int objsense; double *obj; double *rhs; double *lower; double *upper; dbl_ILLmatrix A; char **colnames; /* Just for debugging - not updated */ } dbl_ILLlp_sinfo; typedef struct dbl_ILLlp_preline { double rhs; double obj; double lower; double upper; int count; int *ind; int row_or_col; /* 0 is row, 1 is col */ double *val; } dbl_ILLlp_preline; typedef struct dbl_ILLlp_preop { int ptype; int rowindex; int colindex; dbl_ILLlp_preline line; } dbl_ILLlp_preop; typedef struct dbl_ILLlp_predata { /* Data needed in un-presolve. */ int opcount; int opsize; dbl_ILLlp_preop *oplist; int r_nrows; int r_ncols; int *colmap; int *rowmap; double *rowscale; double *colscale; double *colfixval; double *rowfixval; } dbl_ILLlp_predata; typedef struct dbl_ILLlp_rows { int *rowbeg; int *rowcnt; int *rowind; double *rowval; } dbl_ILLlp_rows; /****************************************************************************/ /* */ /* dbl_lpdata.c */ /* */ /****************************************************************************/ struct dbl_qsdata *dbl_ILLread (dbl_qsline_reader * file, const char *dbl_fname, int isMps); void dbl_ILLstart (void); /**< initialize dbl_ILL_MAXDOUBLE and other constants, this funtion should be callef AFTER EGlpNumStart() */ void dbl_ILLend (void); /**< free any internal data asociated with variable dbl_precision numbers */ void dbl_ILLchange_precision (void);/**< This function re-compute the internal variables dbl_precision to the (previously set) EGLPNUM_PRECISION value (done with EGlpNumSetPrecision) */ void dbl_ILLlpdata_init (dbl_ILLlpdata * lp); void dbl_ILLlpdata_free (dbl_ILLlpdata * lp); void dbl_ILLlp_basis_init (dbl_ILLlp_basis * B); void dbl_ILLlp_basis_free (dbl_ILLlp_basis * B); void dbl_ILLlp_cache_init (dbl_ILLlp_cache * C); void dbl_ILLlp_cache_free (dbl_ILLlp_cache * C); int dbl_ILLlp_basis_alloc (dbl_ILLlp_basis * B, int ncols, int nrows); int dbl_ILLlp_cache_alloc (dbl_ILLlp_cache * C, int ncols, int nrows); int dbl_ILLlp_rows_init (dbl_ILLlp_rows * lp_rows, dbl_ILLlpdata * lp, int include_logicals); void dbl_ILLlp_rows_clear (dbl_ILLlp_rows * lp_rows); int dbl_ILLprint_report (dbl_ILLlpdata * lp, const char *format, ...); /* print to lp->reporter */ /****************************************************************************/ /* */ /* dbl_presolve.c */ /* */ /****************************************************************************/ void dbl_ILLlp_sinfo_init (dbl_ILLlp_sinfo * sinfo), dbl_ILLlp_sinfo_free (dbl_ILLlp_sinfo * sinfo), dbl_ILLlp_predata_init (dbl_ILLlp_predata * pre), dbl_ILLlp_predata_free (dbl_ILLlp_predata * pre); int dbl_ILLlp_add_logicals (dbl_ILLlpdata * lp), dbl_ILLlp_scale (dbl_ILLlpdata * lp), dbl_ILLlp_presolve (dbl_ILLlpdata * lp, int pre_types); #endif /* __ILL_LPDATA_H */
/** * Store an evidence in the "buffer". There is a buffer (in the form of a * CSV file) for each predicate that holds the DB tuple formats of its * evidence; this buffer will be flushed into the database once all evidence * has been read. * * @param a * the evidence; following Alchemy, it must be a ground atom * @see Predicate#flushEvidence() */ public void addEvidence(Atom a) { hasEvid = true; if (a.isSoftEvidence()) setHasSoftEvidence(true); addEvidenceTuple(a); }
Translation without a source text: methodological issues in news translation Although journalistic translation research has been quite successful over the past 15 years, from a methodological point of view many scholars struggle with the total or partial absence of a traceable source text. As a consequence, parallel corpora are rare and the researcher often has to rely on multilingual sets of texts that are comparable. This contribution deals in detail with that essential methodological problem. It relates the multi-source and multi-author situation of translation in journalism to this non- (or only partially) identifiable character of the source text–target text relationship. We argue that the triangulation of comparative text analysis with fieldwork adds value to this type of research. This argument is illustrated with a study triangulating textual analysis in three languages with interviews and non-participant observation. Such a triangulation also responds to earlier calls for a more elaborated contextualization of the production process and the socio-historical circumstances in journalistic translation research.
package org.jenkinsci.plugins.slave_setup; import hudson.Extension; import hudson.FilePath; import hudson.model.Computer; import hudson.model.TaskListener; import hudson.remoting.Channel; import hudson.slaves.ComputerListener; import java.io.IOException; import java.util.List; /** * @author <NAME> */ @Extension public class ComputerListenerImpl extends ComputerListener { private SetupDeployer deployer = new SetupDeployer(); @Override public void preLaunch(Computer c, TaskListener listener) throws IOException, InterruptedException { listener.getLogger().println("just before slave " + c.getName() + " gets launched ..."); SetupConfig config = SetupConfig.get(); listener.getLogger().println("executing pre-launch scripts ..."); deployer.executePreLaunchScripts(c, config, listener); } /** * Prepares the slave before it gets online by copying the given content in root and executing the configured setup script. * @param c the computer to set up * @param channel not used * @param root the root of the slave * @param listener log listener * @throws IOException * @throws InterruptedException */ @Override public void preOnline(Computer c, Channel channel, FilePath root, TaskListener listener) throws IOException, InterruptedException { listener.getLogger().println("just before slave " + c.getName() + " gets online ..."); SetupConfig config = SetupConfig.get(); listener.getLogger().println("executing prepare script ..."); deployer.executePrepareScripts(c, config, listener); listener.getLogger().println("setting up slave " + c.getName() + " ..."); deployer.deployToComputer(c, root, listener, config); listener.getLogger().println("slave setup done."); } }
Here are Monday's D-League assignments and recalls, with the latest moves added to the top of the page throughout the day: After Jeremy Lin sprained his ankle at practice today, the Rockets will recall the recently-signed Patrick Beverley from the D-League, tweets Jonathan Feigen of the Houston Chronicle. Since joining the Rio Grande Valley Vipers, Beverley has averaged 13.7 PPG, 7.0 APG, and 6.7 RPG in three contests. sprained his ankle at practice today, the Rockets will recall the recently-signed from the D-League, tweets Jonathan Feigen of the Houston Chronicle. Since joining the Rio Grande Valley Vipers, Beverley has averaged 13.7 PPG, 7.0 APG, and 6.7 RPG in three contests. After a brief stint with the Reno Bighorns, Tony Wroten has been recalled from the D-League by the Grizzlies , according to Ronald Tillery of the Memphis Commercial Appeal (via Twitter). Quincy Pondexter is out with a knee injury, and Rudy Gay will miss tonight's game while attending his grandmother's funeral, so Wroten will provide some extra depth for Memphis. has been recalled from the D-League by the , according to Ronald Tillery of the Memphis Commercial Appeal (via Twitter). is out with a knee injury, and will miss tonight's game while attending his grandmother's funeral, so Wroten will provide some extra depth for Memphis. Terrence Jones has been recalled from the D-League by the Rockets , tweets Feigen. Jones, 2012's 18th overall pick, had been on his third D-League assignment with the Rio Grande Valley Vipers, having averaged 19.2 PPG and 11.0 RPG in nine contests for the club this season. has been recalled from the D-League by the , tweets Feigen. Jones, 2012's 18th overall pick, had been on his third D-League assignment with the Rio Grande Valley Vipers, having averaged 19.2 PPG and 11.0 RPG in nine contests for the club this season. The Spurs have recalled Cory Joseph from their D-League affiliate, the team announced today in a press release. Joseph was assigned to the Austin Toros back on December 17th for the third time this season. In 14 games with the Toros, Joseph has averaged 20.7 PPG and shot 44.2% from three-point range.
// broad cast a block to all connected peers // we can only broadcast a block which is in our db // this function is trigger from 2 points, one when we receive a unknown block which can be successfully added to chain // second from the blockchain which has to relay locally mined blocks as soon as possible func Broadcast_Block(cbl *block.Complete_Block, PeerID uint64) { var request Notify_New_Objects_Struct defer func() { if r := recover(); r != nil { logger.Warnf("Recovered while broadcasting Block, Stack trace below", r) logger.Warnf("Stack trace \n%s", debug.Stack()) } }() fill_common(&request.Common) request.Command = V2_NOTIFY_NEW_BLOCK request.CBlock.Block = cbl.Bl.Serialize() for i := range cbl.Txs { request.CBlock.Txs = append(request.CBlock.Txs, cbl.Txs[i].Serialize()) } serialized, err := msgpack.Marshal(&request) if err != nil { panic(err) } our_height := chain.Get_Height() count := 0 unique_map := UniqueConnections() for _, v := range unique_map { select { case <-Exit_Event: return default: } if atomic.LoadUint32(&v.State) != HANDSHAKE_PENDING && PeerID != v.Peer_ID { peer_height := atomic.LoadInt64(&v.Height) if (our_height - peer_height) > 25 { continue } count++ go func(connection *Connection) { defer func() { if r := recover(); r != nil { rlog.Warnf("Recovered while handling connection, Stack trace below", r) rlog.Warnf("Stack trace \n%s", debug.Stack()) } }() if globals.Arguments["--lowcpuram"].(bool) == false && connection.TXpool_cache != nil { var miner_specific_request Notify_New_Objects_Struct miner_specific_request.Common = request.Common miner_specific_request.Command = V2_NOTIFY_NEW_BLOCK miner_specific_request.CBlock.Block = request.CBlock.Block sent := 0 skipped := 0 connection.TXpool_cache_lock.RLock() for i := range cbl.Bl.Tx_hashes { if _, ok := connection.TXpool_cache[binary.LittleEndian.Uint64(cbl.Bl.Tx_hashes[i][:])]; !ok { miner_specific_request.CBlock.Txs = append(miner_specific_request.CBlock.Txs, request.CBlock.Txs[i]) sent++ } else { skipped++ } } connection.TXpool_cache_lock.RUnlock() connection.logger.Debugf("Sending ultra block to peer total %d tx skipped %d sent %d", len(cbl.Bl.Tx_hashes), skipped, sent) serialized_miner_specific, err := msgpack.Marshal(&miner_specific_request) if err != nil { panic(err) } connection.Send_Message(serialized_miner_specific) } else { connection.logger.Debugf("Sending full block to peer") connection.Send_Message(serialized) } }(v) } } rlog.Infof("Broadcasted block %s to %d peers", cbl.Bl.GetHash(), count) }
Transgender activist Nisha Ayub was awarded ‘Hero of the Year’ at the second Asia LGBT Milestone Awards (ALMAs) yesterday in Bangkok. ― Picture by Choo Choy May KUALA LUMPUR, April 16 — Transgender activist Nisha Ayub, who is part of rights group Justice for Sisters (JFS), was awarded “Hero of the Year” at the second Asia LGBT Milestone Awards (ALMAs) yesterday in Bangkok. Nisha and JFS gained prominence last year for assisting three Muslim transgender women here in their constitutional challenge of a Shariah legislation in Negri Sembilan that outlaws men from cross-dressing, a watershed case that they won in the Court of Appeal. “I am of course overwhelmed, but for me I’m just happy that the issue of transgenders in Malaysia is now known. Now people hear the voices of not just me, but also the community,” Nisha told Malay Mail Online over phone today. “Personally, I feel that the hero is not supposed to be me, but the girls,” she added, referring to the three transgender women whom JFS assisted. Nisha said she hopes that the acknowledgement will motivate the transgender community here to speak up and to stand up for their rights and issues. “It gives hope not just to me as a person, but also to other trans community members in Malaysia. There is hope for us … Always voice out your issue. If you don’t, nobody will know about it,” she added. Besides Nisha, the other two individuals nominated for “Hero of the Year” were former female Indian track athlete Pinki Pramanik, and Chinese gay rights activist Wei Tingting. Pinki, an intersex, faced false allegations of rape and being a man in disguise by her housemate in 2012, before she was finally acquitted last year. Meanwhile, feminist Wei was among five women detained by China last month for their activism, and was just released on Tuesday. Other awards included “Icon of the Year”, which went to Taiwan pop star Jolin Tsai, and Entrepreneur of The Year, which went to Geng Le, a former policeman-turned-gay dating app developer. The award was held by Singapore’s gay magazine Element, with 50 nominees named by 100 members of the judging panel from 11 Asian countries. The Court of Appeal had in November last year ruled in favour of three Muslim transgenders who were convicted of cross-dressing under the Shariah enactment that punishes Muslim men who wear women’s attire with a fine not exceeding RM1,000, or jail of not more than six months, or both. The appellate court also ruled Section 66 of the enactment as unconstitutional and void, noting that the provision contravened fundamental liberties, including personal liberty, equality, freedom of movement and freedom of expression. The three-judge panel of Malaysia’s second-highest court led by Justice Datuk Mohd Hishamudin Yunus and comprising Datuk Aziah Ali and Datuk Lim Yee Lan had also said the law was discriminatory as it failed to recognise men diagnosed with gender identity disorder. In January, Negri Sembilan was allowed to appeal the case in the Federal Court, with prominent lawyer Tan Sri Muhammad Shafee Abdullah representing the applicants, which also included the state’s Islamic Religious Affairs Department, its director, its chief enforcer, and the state’s chief Shariah prosecutor. “They’re the real heroes. If they didn’t keep up the fight for the past few years, we wouldn’t have achieved what we’ve won,” Nisha added, referring to the three applicants.
def sample_frames(self, frames, interval, start_ms, skip_frames): frame_count = len(frames) if frame_count > 3: first_frame = frames[0] first_change = frames[1] last_frame = frames[-1] match = re.compile(r'ms_(?P<ms>[0-9]+)\.') matches = re.search(match, first_change) first_change_time = 0 if matches is not None: first_change_time = int(matches.groupdict().get('ms')) last_bucket = None logging.debug('Sapling frames in %d ms intervals after %d ms, ' 'skipping %d frames...', interval, first_change_time + start_ms, skip_frames) frame_count = 0 for frame in frames: matches = re.search(match, frame) if matches is not None: frame_count += 1 frame_time = int(matches.groupdict().get('ms')) frame_bucket = int(math.floor(frame_time / interval)) if (frame_time > first_change_time + start_ms and frame_bucket == last_bucket and frame != first_frame and frame != first_change and frame != last_frame and frame_count > skip_frames): logging.debug('Removing sampled frame ' + frame) os.remove(frame) last_bucket = frame_bucket
/** * Mutable extension of {@link LayoutableMatrix}. * * @param <E> Type of elements. * * @see LayoutableMatrix * @see MutableStructure */ public class MutableMatrix<E> extends LayoutableMatrix<E> implements MutableStructure<E> { /** * On addition consumers. */ private final Map<Object, List<Consumer<? super StructureChange.Addition<E>>>> addConsumers = new HashMap<>(); /** * On removal consumers. */ private final Map<Object, List<Consumer<? super StructureChange.Removal<E>>>> rmConsumers = new HashMap<>(); /** * Constructor. * * @param el Elements. */ public MutableMatrix(Collection<E> el) { super(el); } /** * Layout constructor. * * @param el Elements. * @param layoutSupplier Initial layout. */ public MutableMatrix(Collection<E> el, Function<LayoutableStructure<E>, Layout<E>> layoutSupplier) { super(el, layoutSupplier); } /** * Elements copy constructor. * * @param c Structure to copy. */ public MutableMatrix(CoordinatesStructure<E> c) { super(c); } /** * Copy constructor. * * @param m Matrix to copy. */ public MutableMatrix(CoordinatesMatrix<E> m) { super(m); } /** * Constructor. * * @param el Elements. * @param initialWidth Width. * @param initialHeight Height. * @param initialRowNumber Row number. * @param initialColNumber Column number. * @param maxRowRangeIncrease Maximum row range increase. * @param maxColRangeIncrease Maximum column range increase. * @param maxRowNumber Maximum rows. * @param maxColNumber Maximum columns. */ public MutableMatrix(Collection<E> el, double initialWidth, double initialHeight, int initialRowNumber, int initialColNumber, float maxRowRangeIncrease, float maxColRangeIncrease, int maxRowNumber, int maxColNumber) { super( el, initialWidth, initialHeight, initialRowNumber, initialColNumber, maxRowRangeIncrease, maxColRangeIncrease, maxRowNumber, maxColNumber ); } /** * Constructor. * * @param el Elements. * @param initialWidth Width. * @param initialHeight Height. * @param initialRowNumber Row number. * @param initialColNumber Column number. * @param maxRowRangeIncrease Maximum row range increase. * @param maxColRangeIncrease Maximum column range increase. * @param maxRowNumber Maximum rows. * @param maxColNumber Maximum columns. */ public MutableMatrix(CoordinatesStructure<E> el, double initialWidth, double initialHeight, int initialRowNumber, int initialColNumber, float maxRowRangeIncrease, float maxColRangeIncrease, int maxRowNumber, int maxColNumber) { super( el, initialWidth, initialHeight, initialRowNumber, initialColNumber, maxRowRangeIncrease, maxColRangeIncrease, maxRowNumber, maxColNumber ); } /** * Layout constructor. * * @param el Elements. * @param layoutSupplier Initial layout. * @param initialWidth Width. * @param initialHeight Height. * @param initialRowNumber Row number. * @param initialColNumber Column number. * @param maxRowRangeIncrease Maximum row range increase. * @param maxColRangeIncrease Maximum column range increase. * @param maxRowNumber Maximum rows. * @param maxColNumber Maximum columns. */ public MutableMatrix(Collection<E> el, Function<LayoutableStructure<E>, Layout<E>> layoutSupplier, double initialWidth, double initialHeight, int initialRowNumber, int initialColNumber, float maxRowRangeIncrease, float maxColRangeIncrease, int maxRowNumber, int maxColNumber) { super( el, layoutSupplier, initialWidth, initialHeight, initialRowNumber, initialColNumber, maxRowRangeIncrease, maxColRangeIncrease, maxRowNumber, maxColNumber ); } /** * {@inheritDoc} * * @param element The element to add. * @return {@code true} if it was successfully added. */ @Override public boolean addCoordinates(CoordinatesElement<E> element) { if(!place(element)) { return false; } fireAddEvent(List.of(element), element.getXY(), element.getXY()); return true; } /** * {@inheritDoc} * * @param coordinatesElements The elements to add. * @return {@code true} if at least one element was successfully added. */ @Override public boolean addAllCoordinates(Collection<CoordinatesElement<E>> coordinatesElements) { var l = new ArrayList<CoordinatesElement<E>>(coordinatesElements.size()); double minX = Double.MAX_VALUE; double minY = Double.MAX_VALUE; double maxX = Double.MIN_VALUE; double maxY = Double.MIN_VALUE; for(var c : coordinatesElements) { if(!place(c)) { continue; } l.add(c); minX = Math.min(minX, c.getX()); maxX = Math.max(maxX, c.getX()); minY = Math.min(minY, c.getY()); maxY = Math.max(maxY, c.getY()); } if(l.isEmpty()) { return false; } fireAddEvent(l, new Point2D(minX, minY), new Point2D(maxX, maxY)); return true; } /** * {@inheritDoc} * * @param element The element to remove. * @return {@code true} if the element was successfully removed. */ @Override public boolean removeValue(E element) { CoordinatesElement<E> c = null; for(var c2 : this) { if(c2.getElement().equals(element)) { c = c2; break; } } if(c == null) { return false; } delete(c); fireRmEvent(List.of(c), c.getXY(), c.getXY()); return true; } /** * {@inheritDoc} * * @param elements The element to remove. * @return {@code true} if at least one element was successfully removed. */ @Override public boolean removeAllValues(Collection<E> elements) { var l = new ArrayList<CoordinatesElement<E>>(elements.size()); for(var c : this) { if(elements.contains(c.getElement())) { l.add(c); } } return !(l.isEmpty()) && removeAllCoordinates(l); } /** * {@inheritDoc} * * @param element The element to remove. * @return {@code true} if the element was successfully removed. */ @Override public boolean removeCoordinates(CoordinatesElement<E> element) { if(!delete(element)) { return false; } fireRmEvent(List.of(element), element.getXY(), element.getXY()); return true; } /** * {@inheritDoc} * * @param coordinatesElements The element to remove. * @return {@code true} if at least one element was successfully removed. */ @Override public boolean removeAllCoordinates(Collection<CoordinatesElement<E>> coordinatesElements) { var l = new ArrayList<CoordinatesElement<E>>(coordinatesElements.size()); double minX = Double.MAX_VALUE; double minY = Double.MAX_VALUE; double maxX = Double.MIN_VALUE; double maxY = Double.MIN_VALUE; for(var c : coordinatesElements) { if(!delete(c)) { continue; } l.add(c); minX = Math.min(minX, c.getX()); maxX = Math.max(maxX, c.getX()); minY = Math.min(minY, c.getY()); maxY = Math.max(maxY, c.getY()); } if(l.isEmpty()) { return false; } fireRmEvent(l, new Point2D(minX, minY), new Point2D(maxX, maxY)); return true; } /** * {@inheritDoc} * * @param condition Filtering condition. * @return {@code true} if at least one element was successfully removed. */ @Override public boolean removeValuesIf(Predicate<? super E> condition) { return removeCoordinatesIf(c -> condition.test(c.getElement())); } /** * {@inheritDoc} * * @param condition Filtering condition. * @return {@code true} if at least one element was successfully removed. */ @Override public boolean removeCoordinatesIf(Predicate<? super CoordinatesElement<E>> condition) { var l = new ArrayList<CoordinatesElement<E>>(); for(var c : this) { if(condition.test(c)) { l.add(c); } } return !(l.isEmpty()) && removeAllCoordinates(l); } /** * {@inheritDoc} * * @return {@code true} if it was modified as a result of calling this. */ @Override public boolean clear() { var l = new ArrayList<CoordinatesElement<E>>(size()); var p1 = new Point2D(getMinimumWidth(), getMinimumHeight()); var p2 = new Point2D(getMaximumWidth(), getMaximumHeight()); this.forEach(l::add); emptyElements(); fireRmEvent(l, p1, p2); return true; } /** * Notifies all the addition consumers. */ private void fireAddEvent(List<CoordinatesElement<E>> elts, Point2D topLeft, Point2D bottomRight) { var e = StructureChange.added(this, elts, topLeft, bottomRight); for(var l : addConsumers.values()) { l.forEach(c -> c.accept(e)); } } /** * Notifies all the removal consumers. */ private void fireRmEvent(List<CoordinatesElement<E>> elts, Point2D topLeft, Point2D bottomRight) { var e = StructureChange.removed(this, elts, topLeft, bottomRight); for(var l : rmConsumers.values()) { l.forEach(c -> c.accept(e)); } } /** * {@inheritDoc} * * @param owner The listener owner. * @param action The action to perform. */ @Override public void addAdditionListener(Object owner, Consumer<? super StructureChange.Addition<E>> action) { addConsumers.computeIfAbsent(owner, o -> new ArrayList<>()); addConsumers.get(owner).add(action); } /** * {@inheritDoc} * * @param owner The listener owner. * @param action The action to stop doing. */ @Override public void removeAdditionListener(Object owner, Consumer<? super StructureChange.Addition<E>> action) { var l = addConsumers.get(owner); if(l != null) { l.remove(action); } } /** * {@inheritDoc} * * @param owner The listeners owner. * @return The removed listeners. */ @Override public Collection<Consumer<? super StructureChange.Addition<E>>> clearAdditionListeners(Object owner) { var l = addConsumers.remove(owner); return (l != null) ? l : List.of(); } /** * {@inheritDoc} * * @return The removed listeners. */ @Override public Collection<Consumer<? super StructureChange.Addition<E>>> clearAdditionListeners() { var l = new ArrayList<Consumer<? super StructureChange.Addition<E>>>(); addConsumers.values().forEach(l::addAll); addConsumers.clear(); return l; } /** * {@inheritDoc} * * @param owner The listener owner. * @param action The action to perform. */ @Override public void addRemovalListener(Object owner, Consumer<? super StructureChange.Removal<E>> action) { rmConsumers.computeIfAbsent(owner, o -> new ArrayList<>()); rmConsumers.get(owner).add(action); } /** * {@inheritDoc} * * @param owner The listener owner. * @param action The action to stop doing. */ @Override public void removeRemovalListener(Object owner, Consumer<? super StructureChange.Removal<E>> action) { var l = rmConsumers.get(owner); if(l != null) { l.remove(action); } } /** * {@inheritDoc} * * @param owner The listeners owner. * @return The removed listeners. */ @Override public Collection<Consumer<? super StructureChange.Removal<E>>> clearRemovalListeners(Object owner) { var l = rmConsumers.remove(owner); return (l != null) ? l : List.of(); } /** * {@inheritDoc} * * @return The removed listeners. */ @Override public Collection<Consumer<? super StructureChange.Removal<E>>> clearRemovalListeners() { var l = new ArrayList<Consumer<? super StructureChange.Removal<E>>>(); rmConsumers.values().forEach(l::addAll); rmConsumers.clear(); return l; } /** * {@inheritDoc} * * @return an Iterator. */ @Override public CoordinatesIterator<CoordinatesElement<E>> iterator() { return new RemoverIterator(); } /** * Extension of {@link io.github.vqnxiv.structure.impl.LayoutableMatrix.LayoutableIterator} * to support element removal. */ protected class RemoverIterator extends LayoutableIterator { /** * Constructor. */ protected RemoverIterator() { super(); } /** * {@inheritDoc} */ @Override public void remove() { if(getLast() == null) { throw new IllegalStateException(); } delete(getLast()); nullLast(); updateExpectedModCount(); } } }
<reponame>3ach/mattermost-webapp<filename>utils/emoji.d.ts // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import {SystemEmoji} from '@mattermost/types/emojis'; export const Emojis: SystemEmoji[]; export const EmojiIndicesByAlias: Map<string, number>; export const EmojiIndicesByUnicode: Map<string, number>; export const CategoryNames: string[]; export const CategoryMessage: Map<string, string>; export const CategoryTranslations: Map<string, string>; export const SkinTranslations: Map<string, string>; export const EmojiIndicesByCategory: Map<string, Map<string, number[]>>;
import React from "react"; import { ControlProps } from "../../form"; /** * <Input /> Props */ type InputProps<V = string | number> = ControlProps<V> & { /** * Aria pressed */ ariaPressed?: boolean | "mixed" | undefined; /** * Aria label */ ariaLabel?: string | undefined; /** * className */ className?: string; /** * Placeholder */ placeholder?: string; /** * Width */ width?: string | number; /** * Type */ type: | "color" | "hidden" | "image" | "file" | "month" | "range" | "search" | "week" | "text" | "number" | "date" | "datetime-local" | "email" | "password" | "search" | "tel" | "url" | "week"; /** * Required */ required?: boolean; /** * Disabled */ disabled?: boolean; /** * Name */ name: string; /** * Value * TODO: remove any * value: string | string[] | undefined | number; */ value: any; /** * Label */ label: string; /** * Tab index */ tabIndex?: string; /** * Max length */ maxLength?: number; /** * Pattern */ pattern?: string; /** * Error text */ errorText?: string; /** * Icon */ icon?: React.ReactNode; /** * Size */ size?: "large" | "medium"; /** * Has error */ hasError?: boolean; /** * Is valid */ isValid?: boolean; /** * onInputChange */ onInputChange: (value: string | number) => void; }; /** * <StyledInput /> Props */ type StyledInputProps<V = string | number> = ControlProps<V> & { /** * Disabled */ disabled?: boolean; /** * Size */ size: number; }; /** * <StyledLabel /> Props */ type StyledLabelProps = ControlProps<string> & { /** * Has icon */ hasIcon?: string | number | true | undefined; /** * Disabled */ disabled?: boolean; /** * Has error */ hasError?: boolean; /** * Has focus */ hasFocus: boolean; }; /** * <LabelContainer /> Props */ type LabelContainerProps = ControlProps<string> & { /** * Has focus */ hasFocus: boolean; /** * Disabled */ disabled: boolean; /** * Size */ size: number; }; export type { InputProps, StyledInputProps, StyledLabelProps, LabelContainerProps };
from cosmos_soft_packets import * from noncosmos_packets import * from packets_cf_cmd import * from packets_cf_tlm import * from packets_cs_cmd import * from packets_cs_tlm import * from packets_ds_cmd import * from packets_ds_tlm import * from packets_ephem_cmd import * from packets_ephem_tlm import * from packets_es_cmd import * from packets_es_tlm import * from packets_evs_cmd import * from packets_evs_tlm import * from packets_eyassat_if_cmd import * from packets_eyassat_if_tlm import * from packets_fm_cmd import * from packets_fm_tlm import * from packets_hk_cmd import * from packets_hk_tlm import * from packets_hs_cmd import * from packets_hs_tlm import * from packets_kit_sch_cmd import * from packets_kit_sch_tlm import * from packets_lc_cmd import * from packets_lc_tlm import * from packets_md_cmd import * from packets_md_tlm import * from packets_mm_cmd import * from packets_mm_tlm import * from packets_pl_if_cmd import * from packets_pl_if_tlm import * from packets_sb_cmd import * from packets_sb_tlm import * from packets_sc_cmd import * from packets_sc_tlm import * from packets_tbl_cmd import * from packets_tbl_tlm import * from packets_time_cmd import * from packets_time_tlm import * from packets_uart_to_ci_cmd import * from packets_uart_to_ci_tlm import * from packets_implant_cmd import * from ats import * COSMOS_TARGET_PACKETS = { 'ADCS': { 'GYRO_CAL': ADCS_GYRO_CAL_CmdPkt, 'MAG_CAL': ADCS_MAG_CAL_CmdPkt, }, 'CF': { 'CONFIG_PKT': CF_CONFIG_PKT_TlmPkt, 'DIS_DEQUEUE': CF_DIS_DEQUEUE_CmdPkt, 'DIS_DIR_POLLING': CF_DIS_DIR_POLLING_CmdPkt, 'ENA_DEQUEUE': CF_ENA_DEQUEUE_CmdPkt, 'ENA_DIR_POLLING': CF_ENA_DIR_POLLING_CmdPkt, 'GET_MIB': CF_GET_MIB_CmdPkt, 'HK_TLM_PKT': CF_HK_TLM_PKT_TlmPkt, 'KICK_START': CF_KICK_START_CmdPkt, 'NOOP': CF_NOOP_CmdPkt, 'PLAYBACK_DIR': CF_PLAYBACK_DIR_CmdPkt, 'PLAYBACK_FILE': CF_PLAYBACK_FILE_CmdPkt, 'PURGE_QUEUE': CF_PURGE_QUEUE_CmdPkt, 'QUICK_STAT': CF_QUICK_STAT_CmdPkt, 'RESET_CTRS': CF_RESET_CTRS_CmdPkt, 'SEND_CFG_PARAMS': CF_SEND_CFG_PARAMS_CmdPkt, 'SEND_TRANS_DIAG_DATA': CF_SEND_TRANS_DIAG_DATA_CmdPkt, 'SET_MIB': CF_SET_MIB_CmdPkt, 'TRANS_DIAG_PKT': CF_TRANS_DIAG_PKT_TlmPkt, 'WRITE_ACTIVE_TRANS': CF_WRITE_ACTIVE_TRANS_CmdPkt, 'WRITE_QUEUE_INFO': CF_WRITE_QUEUE_INFO_CmdPkt, }, 'CFE_ES': { 'APP_INFO_TLM_PKT': CFE_ES_APP_INFO_TLM_PKT_TlmPkt, 'CLEAR_ERLOG': CFE_ES_CLEAR_ERLOG_CmdPkt, 'CLEAR_SYSLOG': CFE_ES_CLEAR_SYSLOG_CmdPkt, 'DELETE_CDS': CFE_ES_DELETE_CDS_CmdPkt, 'HK_TLM_PKT': CFE_ES_HK_TLM_PKT_TlmPkt, 'MEM_POOL_STATS_TLM_PKT': CFE_ES_MEM_POOL_STATS_TLM_PKT_TlmPkt, 'NOOP': CFE_ES_NOOP_CmdPkt, 'OVERWRITE_SYSLOG_MODE': CFE_ES_OVERWRITE_SYSLOG_MODE_CmdPkt, 'RELOAD_APP': CFE_ES_RELOAD_APP_CmdPkt, 'RESET': CFE_ES_RESET_CmdPkt, 'RESET_CTRS': CFE_ES_RESET_CTRS_CmdPkt, 'RESET_PR_CNT': CFE_ES_RESET_PR_CNT_CmdPkt, 'RESTART_APP': CFE_ES_RESTART_APP_CmdPkt, 'SEND_APP_INFO': CFE_ES_SEND_APP_INFO_CmdPkt, 'SEND_MEM_POOL_STATS': CFE_ES_SEND_MEM_POOL_STATS_CmdPkt, 'SET_LA_FILTER_MASK': CFE_ES_SET_LA_FILTER_MASK_CmdPkt, 'SET_LA_TRIG_MASK': CFE_ES_SET_LA_TRIG_MASK_CmdPkt, 'SET_MAX_PR_CNT': CFE_ES_SET_MAX_PR_CNT_CmdPkt, 'SHELL': CFE_ES_SHELL_CmdPkt, 'SHELL_TLM_PKT': CFE_ES_SHELL_TLM_PKT_TlmPkt, 'START_APP': CFE_ES_START_APP_CmdPkt, 'START_LA_DATA': CFE_ES_START_LA_DATA_CmdPkt, 'STOP_APP': CFE_ES_STOP_APP_CmdPkt, 'STOP_LA_DATA': CFE_ES_STOP_LA_DATA_CmdPkt, 'WRITE_APP_INFO_TO_FILE': CFE_ES_WRITE_APP_INFO_TO_FILE_CmdPkt, 'WRITE_CDS_REG_TO_FILE': CFE_ES_WRITE_CDS_REG_TO_FILE_CmdPkt, 'WRITE_ERLOG_TO_FILE': CFE_ES_WRITE_ERLOG_TO_FILE_CmdPkt, 'WRITE_SYSLOG_TO_FILE': CFE_ES_WRITE_SYSLOG_TO_FILE_CmdPkt, 'WRITE_TASK_INFO_TO_FILE': CFE_ES_WRITE_TASK_INFO_TO_FILE_CmdPkt, }, 'CFE_EVS': { 'ADD_EVENT_FILTER': CFE_EVS_ADD_EVENT_FILTER_CmdPkt, 'CLEAR_LOG': CFE_EVS_CLEAR_LOG_CmdPkt, 'DEL_EVENT_FILTER': CFE_EVS_DEL_EVENT_FILTER_CmdPkt, 'DIS_APP_EVENT_GEN': CFE_EVS_DIS_APP_EVENT_GEN_CmdPkt, 'DIS_APP_EVENT_TYPE': CFE_EVS_DIS_APP_EVENT_TYPE_CmdPkt, 'DIS_EVENT_TYPE': CFE_EVS_DIS_EVENT_TYPE_CmdPkt, 'DIS_PORT': CFE_EVS_DIS_PORT_CmdPkt, 'ENA_APP_EVENT_GEN': CFE_EVS_ENA_APP_EVENT_GEN_CmdPkt, 'ENA_APP_EVENT_TYPE': CFE_EVS_ENA_APP_EVENT_TYPE_CmdPkt, 'ENA_EVENT_TYPE': CFE_EVS_ENA_EVENT_TYPE_CmdPkt, 'ENA_PORT': CFE_EVS_ENA_PORT_CmdPkt, 'EVENT_MSG_PKT': CFE_EVS_EVENT_MSG_PKT_TlmPkt, 'HK_TLM_PKT': CFE_EVS_HK_TLM_PKT_TlmPkt, 'NOOP': CFE_EVS_NOOP_CmdPkt, 'RESET_ALL_FILTERS': CFE_EVS_RESET_ALL_FILTERS_CmdPkt, 'RESET_APP_CTRS': CFE_EVS_RESET_APP_CTRS_CmdPkt, 'RESET_CTRS': CFE_EVS_RESET_CTRS_CmdPkt, 'RESET_FILTER_CTR': CFE_EVS_RESET_FILTER_CTR_CmdPkt, 'SET_EVENT_FMT': CFE_EVS_SET_EVENT_FMT_CmdPkt, 'SET_FILTER_MASK': CFE_EVS_SET_FILTER_MASK_CmdPkt, 'SET_LOG_MODE': CFE_EVS_SET_LOG_MODE_CmdPkt, 'WRITE_APP_INFO_TO_FILE': CFE_EVS_WRITE_APP_INFO_TO_FILE_CmdPkt, 'WRITE_LOG_TO_FILE': CFE_EVS_WRITE_LOG_TO_FILE_CmdPkt, }, 'CFE_SB': { 'DIS_ROUTE': CFE_SB_DIS_ROUTE_CmdPkt, 'DIS_SUB_REPORTING': CFE_SB_DIS_SUB_REPORTING_CmdPkt, 'ENA_ROUTE': CFE_SB_ENA_ROUTE_CmdPkt, 'ENA_SUB_REPORTING': CFE_SB_ENA_SUB_REPORTING_CmdPkt, 'HK_TLM_PKT': CFE_SB_HK_TLM_PKT_TlmPkt, 'NOOP': CFE_SB_NOOP_CmdPkt, 'PREV_SUBSCRIBE_TLM_PKT': CFE_SB_PREV_SUBSCRIBE_TLM_PKT_TlmPkt, 'RESET_CTRS': CFE_SB_RESET_CTRS_CmdPkt, 'SEND_PREV_SUBS': CFE_SB_SEND_PREV_SUBS_CmdPkt, 'SEND_STATS': CFE_SB_SEND_STATS_CmdPkt, 'SUBSCRIBE_REPORT_TLM_PKT': CFE_SB_SUBSCRIBE_REPORT_TLM_PKT_TlmPkt, 'WRITE_MAP_TO_FILE': CFE_SB_WRITE_MAP_TO_FILE_CmdPkt, 'WRITE_PIPE_TO_FILE': CFE_SB_WRITE_PIPE_TO_FILE_CmdPkt, }, 'CFE_TBL': { 'ABORT_LOAD': CFE_TBL_ABORT_LOAD_CmdPkt, 'ACTIVATE_TBL': CFE_TBL_ACTIVATE_TBL_CmdPkt, 'DELETE_CDS': CFE_TBL_DELETE_CDS_CmdPkt, 'DUMP_TBL': CFE_TBL_DUMP_TBL_CmdPkt, 'HK_TLM_PKT': CFE_TBL_HK_TLM_PKT_TlmPkt, 'LOAD_TBL': CFE_TBL_LOAD_TBL_CmdPkt, 'NOOP': CFE_TBL_NOOP_CmdPkt, 'RESET_CTRS': CFE_TBL_RESET_CTRS_CmdPkt, 'SEND_REGISTRY': CFE_TBL_SEND_REGISTRY_CmdPkt, 'TBL_REGISTRY_PKT': CFE_TBL_TBL_REGISTRY_PKT_TlmPkt, 'VALIDATE_TBL': CFE_TBL_VALIDATE_TBL_CmdPkt, 'WRITE_REG_TO_FILE': CFE_TBL_WRITE_REG_TO_FILE_CmdPkt, }, 'CFE_TIME': { 'ADD_1HZ_STCF_ADJ': CFE_TIME_ADD_1HZ_STCF_ADJ_CmdPkt, 'ADD_CLOCK_LAT': CFE_TIME_ADD_CLOCK_LAT_CmdPkt, 'ADD_STCF_ADJ': CFE_TIME_ADD_STCF_ADJ_CmdPkt, 'DIAG_TLM_PKT': CFE_TIME_DIAG_TLM_PKT_TlmPkt, 'HK_TLM_PKT': CFE_TIME_HK_TLM_PKT_TlmPkt, 'NOOP': CFE_TIME_NOOP_CmdPkt, 'RESET_CTRS': CFE_TIME_RESET_CTRS_CmdPkt, 'SEND_DIAG': CFE_TIME_SEND_DIAG_CmdPkt, 'SET_CLOCK': CFE_TIME_SET_CLOCK_CmdPkt, 'SET_CLOCK_LEAP': CFE_TIME_SET_CLOCK_LEAP_CmdPkt, 'SET_CLOCK_MET': CFE_TIME_SET_CLOCK_MET_CmdPkt, 'SET_CLOCK_STCF': CFE_TIME_SET_CLOCK_STCF_CmdPkt, 'SET_SIGNAL': CFE_TIME_SET_SIGNAL_CmdPkt, 'SET_SOURCE': CFE_TIME_SET_SOURCE_CmdPkt, 'SET_STATE': CFE_TIME_SET_STATE_CmdPkt, 'SUB_1HZ_STCF_ADJ': CFE_TIME_SUB_1HZ_STCF_ADJ_CmdPkt, 'SUB_CLOCK_LAT': CFE_TIME_SUB_CLOCK_LAT_CmdPkt, 'SUB_STCF_ADJ': CFE_TIME_SUB_STCF_ADJ_CmdPkt, }, 'CS': { 'CANCEL_ONESHOT': CS_CANCEL_ONESHOT_CmdPkt, 'DISABLE_ALL_CS': CS_DISABLE_ALL_CS_CmdPkt, 'DISABLE_APPS': CS_DISABLE_APPS_CmdPkt, 'DISABLE_CFECORE': CS_DISABLE_CFECORE_CmdPkt, 'DISABLE_EEPROM': CS_DISABLE_EEPROM_CmdPkt, 'DISABLE_ENTRY_EEPROM': CS_DISABLE_ENTRY_EEPROM_CmdPkt, 'DISABLE_ENTRY_MEMORY': CS_DISABLE_ENTRY_MEMORY_CmdPkt, 'DISABLE_MEMORY': CS_DISABLE_MEMORY_CmdPkt, 'DISABLE_NAME_APP': CS_DISABLE_NAME_APP_CmdPkt, 'DISABLE_NAME_TABLE': CS_DISABLE_NAME_TABLE_CmdPkt, 'DISABLE_OS': CS_DISABLE_OS_CmdPkt, 'DISABLE_TABLES': CS_DISABLE_TABLES_CmdPkt, 'ENABLE_ALL_CS': CS_ENABLE_ALL_CS_CmdPkt, 'ENABLE_APPS': CS_ENABLE_APPS_CmdPkt, 'ENABLE_CFECORE': CS_ENABLE_CFECORE_CmdPkt, 'ENABLE_EEPROM': CS_ENABLE_EEPROM_CmdPkt, 'ENABLE_ENTRY_EEPROM': CS_ENABLE_ENTRY_EEPROM_CmdPkt, 'ENABLE_ENTRY_MEMORY': CS_ENABLE_ENTRY_MEMORY_CmdPkt, 'ENABLE_MEMORY': CS_ENABLE_MEMORY_CmdPkt, 'ENABLE_NAME_APP': CS_ENABLE_NAME_APP_CmdPkt, 'ENABLE_NAME_TABLE': CS_ENABLE_NAME_TABLE_CmdPkt, 'ENABLE_OS': CS_ENABLE_OS_CmdPkt, 'ENABLE_TABLES': CS_ENABLE_TABLES_CmdPkt, 'GET_ENTRY_ID_EEPROM': CS_GET_ENTRY_ID_EEPROM_CmdPkt, 'GET_ENTRY_ID_MEMORY': CS_GET_ENTRY_ID_MEMORY_CmdPkt, 'HK_TLM_PKT': CS_HK_TLM_PKT_TlmPkt, 'NOOP': CS_NOOP_CmdPkt, 'ONESHOT': CS_ONESHOT_CmdPkt, 'RECOMPUTE_BASELINE_APP': CS_RECOMPUTE_BASELINE_APP_CmdPkt, 'RECOMPUTE_BASELINE_CFECORE': CS_RECOMPUTE_BASELINE_CFECORE_CmdPkt, 'RECOMPUTE_BASELINE_EEPROM': CS_RECOMPUTE_BASELINE_EEPROM_CmdPkt, 'RECOMPUTE_BASELINE_MEMORY': CS_RECOMPUTE_BASELINE_MEMORY_CmdPkt, 'RECOMPUTE_BASELINE_OS': CS_RECOMPUTE_BASELINE_OS_CmdPkt, 'RECOMPUTE_BASELINE_TABLE': CS_RECOMPUTE_BASELINE_TABLE_CmdPkt, 'REPORT_BASELINE_APP': CS_REPORT_BASELINE_APP_CmdPkt, 'REPORT_BASELINE_CFECORE': CS_REPORT_BASELINE_CFECORE_CmdPkt, 'REPORT_BASELINE_EEPROM': CS_REPORT_BASELINE_EEPROM_CmdPkt, 'REPORT_BASELINE_MEMORY': CS_REPORT_BASELINE_MEMORY_CmdPkt, 'REPORT_BASELINE_OS': CS_REPORT_BASELINE_OS_CmdPkt, 'REPORT_BASELINE_TABLE': CS_REPORT_BASELINE_TABLE_CmdPkt, 'RESET_CTRS': CS_RESET_CTRS_CmdPkt, }, 'DS': { 'ADD_FILTER_MID': DS_ADD_FILTER_MID_CmdPkt, 'CLOSE_ALL': DS_CLOSE_ALL_CmdPkt, 'CLOSE_FILE': DS_CLOSE_FILE_CmdPkt, 'HK_TLM_PKT': DS_HK_TLM_PKT_TlmPkt, 'NOOP': DS_NOOP_CmdPkt, 'RESET_CTRS': DS_RESET_CTRS_CmdPkt, 'SEND_FILE_INFO': DS_SEND_FILE_INFO_CmdPkt, 'SET_APP_STATE': DS_SET_APP_STATE_CmdPkt, 'SET_FILE_BASE_NAME': DS_SET_FILE_BASE_NAME_CmdPkt, 'SET_FILE_COUNT': DS_SET_FILE_COUNT_CmdPkt, 'SET_FILE_EXT': DS_SET_FILE_EXT_CmdPkt, 'SET_FILE_MAX_AGE': DS_SET_FILE_MAX_AGE_CmdPkt, 'SET_FILE_MAX_SIZE': DS_SET_FILE_MAX_SIZE_CmdPkt, 'SET_FILE_PATH_NAME': DS_SET_FILE_PATH_NAME_CmdPkt, 'SET_FILE_STATE': DS_SET_FILE_STATE_CmdPkt, 'SET_FILE_TYPE': DS_SET_FILE_TYPE_CmdPkt, 'SET_FILTER_FILE': DS_SET_FILTER_FILE_CmdPkt, 'SET_FILTER_PARAM': DS_SET_FILTER_PARAM_CmdPkt, 'SET_FILTER_TYPE': DS_SET_FILTER_TYPE_CmdPkt, }, 'EPHEM': { 'DUMP_TBL': EPHEM_DUMP_TBL_CmdPkt, 'EPHEM_PKT': EPHEM_EPHEM_PKT_TlmPkt, 'EXOBJ_STUB': EPHEM_EXOBJ_STUB_CmdPkt, 'HK_TLM_PKT': EPHEM_HK_TLM_PKT_TlmPkt, 'LOAD_TBL': EPHEM_LOAD_TBL_CmdPkt, 'NOOP': EPHEM_NOOP_CmdPkt, 'RESET_CTRS': EPHEM_RESET_CTRS_CmdPkt, }, 'EYASSAT_IF': { 'ADCS': EYASSAT_IF_ADCS_TlmPkt, 'ADCS_CTRL_ALG': EYASSAT_IF_ADCS_CTRL_ALG_CmdPkt, 'ADCS_DEADBAND': EYASSAT_IF_ADCS_DEADBAND_CmdPkt, 'ADCS_DEADBAND_SCALE_FACTOR': EYASSAT_IF_ADCS_DEADBAND_SCALE_FACTOR_CmdPkt, 'ADCS_DELTA_T': EYASSAT_IF_ADCS_DELTA_T_CmdPkt, 'ADCS_D_CONST': EYASSAT_IF_ADCS_D_CONST_CmdPkt, 'ADCS_ENABLE_IMU': EYASSAT_IF_ADCS_ENABLE_IMU_CmdPkt, 'ADCS_EXTRA': EYASSAT_IF_ADCS_EXTRA_CmdPkt, 'ADCS_I_CONST': EYASSAT_IF_ADCS_I_CONST_CmdPkt, 'ADCS_PWM_BASELINE': EYASSAT_IF_ADCS_PWM_BASELINE_CmdPkt, 'ADCS_P_CONST': EYASSAT_IF_ADCS_P_CONST_CmdPkt, 'ADCS_RESET': EYASSAT_IF_ADCS_RESET_CmdPkt, 'ADCS_RQST': EYASSAT_IF_ADCS_RQST_CmdPkt, 'ADCS_TLM': EYASSAT_IF_ADCS_TLM_CmdPkt, 'ADCS_WHEEL_SPD': EYASSAT_IF_ADCS_WHEEL_SPD_CmdPkt, 'ADCS_X_ROD': EYASSAT_IF_ADCS_X_ROD_CmdPkt, 'ADCS_YAW_CMD': EYASSAT_IF_ADCS_YAW_CMD_CmdPkt, 'ADCS_Y_ROD': EYASSAT_IF_ADCS_Y_ROD_CmdPkt, 'CALL_SIGN': EYASSAT_IF_CALL_SIGN_CmdPkt, 'CAL_TBL': EYASSAT_IF_CAL_TBL_TlmPkt, 'CMD_TIMEOUT': EYASSAT_IF_CMD_TIMEOUT_CmdPkt, 'CONNECT': EYASSAT_IF_CONNECT_CmdPkt, 'DISCONNECT': EYASSAT_IF_DISCONNECT_CmdPkt, 'DUMP_TBL': EYASSAT_IF_DUMP_TBL_CmdPkt, 'HK_TLM_PKT': EYASSAT_IF_HK_TLM_PKT_TlmPkt, 'HOUR': EYASSAT_IF_HOUR_CmdPkt, 'INTERNAL': EYASSAT_IF_INTERNAL_TlmPkt, 'LOAD_TBL': EYASSAT_IF_LOAD_TBL_CmdPkt, 'MINUTE': EYASSAT_IF_MINUTE_CmdPkt, 'NOOP': EYASSAT_IF_NOOP_CmdPkt, 'POWER': EYASSAT_IF_POWER_TlmPkt, 'PWR_3V': EYASSAT_IF_PWR_3V_CmdPkt, 'PWR_ADCS': EYASSAT_IF_PWR_ADCS_CmdPkt, 'PWR_EXP': EYASSAT_IF_PWR_EXP_CmdPkt, 'PWR_HTR1': EYASSAT_IF_PWR_HTR1_CmdPkt, 'PWR_HTR2': EYASSAT_IF_PWR_HTR2_CmdPkt, 'PWR_RESET': EYASSAT_IF_PWR_RESET_CmdPkt, 'PWR_RQST': EYASSAT_IF_PWR_RQST_CmdPkt, 'PWR_SCALE': EYASSAT_IF_PWR_SCALE_CmdPkt, 'PWR_TLM': EYASSAT_IF_PWR_TLM_CmdPkt, 'RESET_CTRS': EYASSAT_IF_RESET_CTRS_CmdPkt, 'SECOND': EYASSAT_IF_SECOND_CmdPkt, 'TEMPS': EYASSAT_IF_TEMPS_TlmPkt, 'TLM_DELAY': EYASSAT_IF_TLM_DELAY_CmdPkt, 'UART0': EYASSAT_IF_UART0_CmdPkt, }, 'FM': { 'CONCAT_FILES': FM_CONCAT_FILES_CmdPkt, 'COPY_FILE': FM_COPY_FILE_CmdPkt, 'CREATE_DIR': FM_CREATE_DIR_CmdPkt, 'DECOMPRESS_FILE': FM_DECOMPRESS_FILE_CmdPkt, 'DELETE_ALL_FILES': FM_DELETE_ALL_FILES_CmdPkt, 'DELETE_DIR': FM_DELETE_DIR_CmdPkt, 'DELETE_FILE': FM_DELETE_FILE_CmdPkt, 'DIR_LIST_PKT': FM_DIR_LIST_PKT_TlmPkt, 'FILE_INFO_PKT': FM_FILE_INFO_PKT_TlmPkt, 'GET_OPEN_FILES': FM_GET_OPEN_FILES_CmdPkt, 'HK_TLM_PKT': FM_HK_TLM_PKT_TlmPkt, 'MOVE_FILE': FM_MOVE_FILE_CmdPkt, 'NOOP': FM_NOOP_CmdPkt, 'RENAME_FILE': FM_RENAME_FILE_CmdPkt, 'RESET_CTRS': FM_RESET_CTRS_CmdPkt, 'SEND_DIR_PKT': FM_SEND_DIR_PKT_CmdPkt, 'SEND_FILE_INFO': FM_SEND_FILE_INFO_CmdPkt, 'SEND_FREE_SPACE_PKT': FM_SEND_FREE_SPACE_PKT_CmdPkt, 'SET_FILE_PERMISSIONS': FM_SET_FILE_PERMISSIONS_CmdPkt, 'SET_TABLE_STATE': FM_SET_TABLE_STATE_CmdPkt, 'WRITE_DIR_TO_FILE': FM_WRITE_DIR_TO_FILE_CmdPkt, }, 'HK': { 'COMBO_PKT_1': HK_COMBO_PKT_1_TlmPkt, 'COMBO_PKT_2': HK_COMBO_PKT_2_TlmPkt, 'HK_TLM_PKT': HK_HK_TLM_PKT_TlmPkt, 'NOOP': HK_NOOP_CmdPkt, 'RESET_CTRS': HK_RESET_CTRS_CmdPkt, }, 'HS': { 'DISABLE_ALIVENESS': HS_DISABLE_ALIVENESS_CmdPkt, 'DISABLE_APP_MON': HS_DISABLE_APP_MON_CmdPkt, 'DISABLE_CPU_HOG': HS_DISABLE_CPU_HOG_CmdPkt, 'DISABLE_EVENT_MON': HS_DISABLE_EVENT_MON_CmdPkt, 'ENABLE_ALIVENESS': HS_ENABLE_ALIVENESS_CmdPkt, 'ENABLE_APP_MON': HS_ENABLE_APP_MON_CmdPkt, 'ENABLE_CPU_HOG': HS_ENABLE_CPU_HOG_CmdPkt, 'ENABLE_EVENT_MON': HS_ENABLE_EVENT_MON_CmdPkt, 'HK_TLM_PKT': HS_HK_TLM_PKT_TlmPkt, 'NOOP': HS_NOOP_CmdPkt, 'RESET_CTRS': HS_RESET_CTRS_CmdPkt, 'RESET_RESETS_PERFORMED': HS_RESET_RESETS_PERFORMED_CmdPkt, 'SET_MAX_RESETS': HS_SET_MAX_RESETS_CmdPkt, }, 'KIT_SCH': { 'CFG_SCH_ENTRY': KIT_SCH_CFG_SCH_ENTRY_CmdPkt, 'DUMP_TBL': KIT_SCH_DUMP_TBL_CmdPkt, 'HK_TLM_PKT': KIT_SCH_HK_TLM_PKT_TlmPkt, 'LOAD_MSG_ENTRY': KIT_SCH_LOAD_MSG_ENTRY_CmdPkt, 'LOAD_SCH_ENTRY': KIT_SCH_LOAD_SCH_ENTRY_CmdPkt, 'LOAD_TBL': KIT_SCH_LOAD_TBL_CmdPkt, 'NOOP': KIT_SCH_NOOP_CmdPkt, 'RESET_CTRS': KIT_SCH_RESET_CTRS_CmdPkt, }, 'LC': { 'HK_TLM_PKT': LC_HK_TLM_PKT_TlmPkt, 'NOOP': LC_NOOP_CmdPkt, 'RESET_AP_STATS': LC_RESET_AP_STATS_CmdPkt, 'RESET_CTRS': LC_RESET_CTRS_CmdPkt, 'RESET_WP_STATS': LC_RESET_WP_STATS_CmdPkt, 'SET_APP_STATE': LC_SET_APP_STATE_CmdPkt, 'SET_AP_PERM_OFF': LC_SET_AP_PERM_OFF_CmdPkt, 'SET_AP_STATE': LC_SET_AP_STATE_CmdPkt, }, 'MD': { 'DWELL_PKT': MD_DWELL_PKT_TlmPkt, 'HK_TLM_PKT': MD_HK_TLM_PKT_TlmPkt, 'JAM_DWELL': MD_JAM_DWELL_CmdPkt, 'NOOP': MD_NOOP_CmdPkt, 'RESET_CTRS': MD_RESET_CTRS_CmdPkt, 'SET_SIGNATURE': MD_SET_SIGNATURE_CmdPkt, 'START_DWELL': MD_START_DWELL_CmdPkt, 'STOP_DWELL': MD_STOP_DWELL_CmdPkt, }, 'MM': { 'DIS_EEPROM_WRITE': MM_DIS_EEPROM_WRITE_CmdPkt, 'DUMP_IN_EVENT': MM_DUMP_IN_EVENT_CmdPkt, 'DUMP_MEM_TO_FILE': MM_DUMP_MEM_TO_FILE_CmdPkt, 'ENA_EEPROM_WRITE': MM_ENA_EEPROM_WRITE_CmdPkt, 'FILL_MEM': MM_FILL_MEM_CmdPkt, 'HK_TLM_PKT': MM_HK_TLM_PKT_TlmPkt, 'LOAD_MEM_FROM_FILE': MM_LOAD_MEM_FROM_FILE_CmdPkt, 'LOAD_MEM_WID': MM_LOAD_MEM_WID_CmdPkt, 'LOOKUP_SYMBOL': MM_LOOKUP_SYMBOL_CmdPkt, 'NOOP': MM_NOOP_CmdPkt, 'PEEK_MEM': MM_PEEK_MEM_CmdPkt, 'POKE_MEM': MM_POKE_MEM_CmdPkt, 'RESET_CTRS': MM_RESET_CTRS_CmdPkt, 'SYMBOLTBL_TO_FILE': MM_SYMBOLTBL_TO_FILE_CmdPkt, }, 'PDU': { 'CF_SPACE_TO_GND_PDU': CFDP_TlmPkt, }, 'PL_IF': { 'DLINK_IMG': PL_IF_DLINK_IMG_CmdPkt, 'DUMP_TBL': PL_IF_DUMP_TBL_CmdPkt, 'GET_IMAGE_SIZE': PL_IF_GET_IMAGE_SIZE_CmdPkt, 'HK_TLM_PKT': PL_IF_HK_TLM_PKT_TlmPkt, 'LOAD_TBL': PL_IF_LOAD_TBL_CmdPkt, 'NOOP': PL_IF_NOOP_CmdPkt, 'PL_STATUS_PKT': PL_IF_PL_STATUS_PKT_TlmPkt, 'POWER': PL_IF_POWER_CmdPkt, 'REBOOT': PL_IF_REBOOT_CmdPkt, 'RESET_CTRS': PL_IF_RESET_CTRS_CmdPkt, 'STOP': PL_IF_STOP_CmdPkt, 'TAKE_IMG': PL_IF_TAKE_IMG_CmdPkt, }, 'SB': { 'WRITE_ROUTING_TO_FILE': SB_WRITE_ROUTING_TO_FILE_CmdPkt, }, 'SC': { 'APPEND_ATS': SC_APPEND_ATS_CmdPkt, 'CONT_ATS': SC_CONT_ATS_CmdPkt, 'DISABLE_RTS': SC_DISABLE_RTS_CmdPkt, 'DISABLE_RTS_GROUP': SC_DISABLE_RTS_GROUP_CmdPkt, 'ENABLE_RTS': SC_ENABLE_RTS_CmdPkt, 'ENABLE_RTS_GROUP': SC_ENABLE_RTS_GROUP_CmdPkt, 'HK_TLM_PKT': SC_HK_TLM_PKT_TlmPkt, 'JUMP_ATS': SC_JUMP_ATS_CmdPkt, 'NOOP': SC_NOOP_CmdPkt, 'RESET_CTRS': SC_RESET_CTRS_CmdPkt, 'START_ATS': SC_START_ATS_CmdPkt, 'START_RTS': SC_START_RTS_CmdPkt, 'START_RTS_GROUP': SC_START_RTS_GROUP_CmdPkt, 'STOP_ATS': SC_STOP_ATS_CmdPkt, 'STOP_RTS': SC_STOP_RTS_CmdPkt, 'STOP_RTS_GROUP': SC_STOP_RTS_GROUP_CmdPkt, 'SWITCH_ATS': SC_SWITCH_ATS_CmdPkt, }, 'UART_TO_CI': { 'ADD_PKT': UART_TO_CI_ADD_PKT_CmdPkt, 'DISABLE_TELEMETRY': UART_TO_CI_DISABLE_TELEMETRY_CmdPkt, 'DUMP_TBL': UART_TO_CI_DUMP_TBL_CmdPkt, 'ENABLE_TELEMETRY': UART_TO_CI_ENABLE_TELEMETRY_CmdPkt, 'HK_TLM_PKT': UART_TO_CI_HK_TLM_PKT_TlmPkt, 'LOAD_TBL': UART_TO_CI_LOAD_TBL_CmdPkt, 'NOOP': UART_TO_CI_NOOP_CmdPkt, 'REMOVE_ALL_PKTS': UART_TO_CI_REMOVE_ALL_PKTS_CmdPkt, 'REMOVE_PKT': UART_TO_CI_REMOVE_PKT_CmdPkt, 'RESET_CTRS': UART_TO_CI_RESET_CTRS_CmdPkt, }, } COSMOS_TARGET_PACKETS_REV = {} for target, cmds in COSMOS_TARGET_PACKETS.items(): for cmd, pktclass in cmds.items(): COSMOS_TARGET_PACKETS_REV[pktclass] = (target, cmd)
# Copyright 2022 Cerebras Systems. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' os.environ["CUDA_VISIBLE_DEVICES"] = "-1" # Because GPU is not needed for this import argparse import json import sys import numpy as np import tensorflow as tf import torch from transformers import GPTJForCausalLM def get_runtime_args(): """Create parser for command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument( "--input_dir", type=str, required=True, help=( "Directory containing HuggingFace checkpoint. If it does not exist," " this path is used to store the downloaded checkpoint." ), ) parser.add_argument( "--output_dir", type=str, required=True, help=( "Model directory where converted checkpoints and states will be" " written. If it does not exist, it is created during runtime." ), ) parser.add_argument( "--share_embeddings", default=False, action='store_true', help=( "Remove the lm_head weights and creates a checkpoint with shared (aka. tied) embeddings." " Note: This will make the TF checkpoint differ from the original JAX model." ), ) parser.add_argument( "--debug", action='store_true', help=("Whether to check model call from HuggingFace."), ) return parser.parse_args(sys.argv[1:]) def create_tf_var(tensor: np.ndarray, name: str, session: tf.compat.v1.Session): """Takes a tensor and creates a TensorFlow Variable with same shape and dtype, initialized with the given tensor. Args: tensor (ndarray): Tensor to model as zeros name (str): Name to give the variable session (tf.Session): Session to create the variables Returns: A zero initialized TensorFlow variable """ tf_dtype = tf.dtypes.as_dtype(tensor.dtype) tf_var = tf.compat.v1.get_variable( dtype=tf_dtype, shape=tensor.shape, name=name, initializer=tf.compat.v1.zeros_initializer(), ) session.run(tf.compat.v1.variables_initializer([tf_var])) session.run(tf_var) return tf_var def dict_to_checkpoint(state_dict: dict, checkpoint_name: str): """Convert a dictionary of weights to a TF checkpoint to be used by the model during execution. Args: state_dict (dict): Dictionary containing weight names mapped to pytorch tensors from the HuggingFace checkpoint checkpoint_name (str): Path to save the TensorFlow checkpoint """ tf.compat.v1.reset_default_graph() with tf.compat.v1.Session() as session: for name, pt_tensor in state_dict.items(): np_tensor = pt_tensor.numpy() if name: tf_var = create_tf_var( tensor=np_tensor, name=name, session=session, ) tf.keras.backend.set_value(tf_var, np_tensor) tf_weight = session.run(tf_var) saver = tf.compat.v1.train.Saver(tf.compat.v1.trainable_variables()) saver.save(session, checkpoint_name) def save_mappings(tf_ckpt_path: str, variable_dict: dict, transpose_dict: dict): """Save the mapping of variables between PyTorch and TensorFlow. Args: tf_ckpt_path (str): Path for storing checkpoints and associated mappings variable_dict (dict): A mapping of variables between PyTorch and TensorFlow checkpoints names. transpose_dict (dict): A mapping of whether variables between PyTorch and TensorFlow checkpoints are transposed. """ with open(os.path.join(tf_ckpt_path, 'keys.json'), 'w') as fout: json.dump(variable_dict, fout, sort_keys=False) with open(os.path.join(tf_ckpt_path, 'shapes.json'), 'w') as fout: json.dump(transpose_dict, fout, sort_keys=False) def map_embeddings_pt_to_tf(key: str): """Map embedding layer to weights. Args: key (str): key to map from PyTorch to TensorFlow Returns: A tuple (name, transpose), where name is the equivalent TensorFlow layer name, and transpose indicates if we need to transpose the weights when mapping """ transpose = False dict_map = {"transformer.wte.weight": "input_embedding/embedding_weights"} return dict_map[key], transpose def map_outputs_pt_to_tf(key: str, shared_embeddings: bool = True): """Map final layer norm and output head bias to weights. Output weights for sharedweight layer comes from emebdding layer mapping. Args: key (str): key to map from PyTorch to TensorFlow shared_embeddings (bool): whether the model is trained with shared embeddings. Defaults to `True` Returns: A tuple (name, transpose), where name is the equivalent TensorFlow layer name, and transpose indicates if we need to transpose the weights when mapping """ transpose = False if key == "lm_head.weight": transpose = True dict_map = { "transformer.ln_f.weight": "post_decoder_layer_norm/post_decoder_layer_norm/gamma", "transformer.ln_f.bias": "post_decoder_layer_norm/post_decoder_layer_norm/beta", } embeddings_map = {} if shared_embeddings: embeddings_map = { "lm_head.bias": "bias", } else: embeddings_map = { "lm_head.weight": "lm_head/lm_head/kernel", "lm_head.bias": "lm_head/lm_head/bias", } dict_map.update(embeddings_map) return dict_map[key], transpose def map_ln_pt_to_tf(key: str): """Map LayerNorm Layer in decoder to weights. Args: key (str): key to map from PyTorch to TensorFlow Returns: A tuple (name, transpose), where name is the equivalent TensorFlow layer name, and transpose indicates if we need to transpose the weights when mapping """ transpose = False split_key = key.split('.') pt_layer_num = int(split_key[2]) final_key_dict = { "bias": "beta", "weight": "gamma", } final_key = final_key_dict[split_key[-1]] tf_key = f"gptj_decoder/{pt_layer_num}/ln_1/ln_1/{final_key}" return tf_key, transpose def map_attn_pt_to_tf(key: str): """Map Attention Block in decoder to weights. Args: key (str): key to map from PyTorch to TensorFlow Returns: A tuple (name, transpose), where name is the equivalent TensorFlow layer name, and transpose indicates if we need to transpose the weights when mapping """ transpose = False if "weight" in key: transpose = True split_key = key.split('.') pt_layer_num = int(split_key[2]) last_two = ".".join([split_key[-2], split_key[-1]]) if last_two in ["attn.bias", "attn.masked_bias"]: # Note: "attn.bias" is a 2028x2048 autoregressive mask, # and "attn.masked_bias" is a large negative number (-1.0e+09). # Neither need to be saved in the checkpoint. They are generated when they are needed. return None, False dict_map = { f"transformer.h.{pt_layer_num}": f"gptj_decoder/{pt_layer_num}", "attn": "attn", "q_proj": "q_proj/q_proj", "k_proj": "k_proj/k_proj", "v_proj": "v_proj/v_proj", "weight": "kernel", "bias": "bias", "out_proj": "out_proj/out_proj", } for k in dict_map.keys(): if k in key: key = key.replace(k, dict_map[k]) tf_key = key.replace(".", "/") return tf_key, transpose def map_mlp_pt_to_tf(key: str): """Map MLP Block in decoder to weights. Args: key (str): key to map from PyTorch to TensorFlow Returns: A tuple (name, transpose), where name is the equivalent TensorFlow layer name, and transpose indicates if we need to transpose the weights when mapping """ transpose = False if "weight" in key: transpose = True split_key = key.split('.') pt_layer_num = int(split_key[2]) final_key_dict = {"bias": "bias", "weight": "kernel"} final_key = final_key_dict[split_key[-1]] if "fc_in" in key: tf_layer_num = int(pt_layer_num * 2) elif "fc_out" in key: tf_layer_num = int(pt_layer_num * 2 + 1) tf_key = f"gptj_decoder/{pt_layer_num}/mlp/dense_layer_{tf_layer_num}/dense_layer_{tf_layer_num}/{final_key}" tf_key = tf_key.replace("_0", "") return tf_key, transpose def map_decoder_pt_to_tf(key: str): """Map decoder to weights. Args: key (str): key to map from PyTorch to TensorFlow Returns: A tuple (name, transpose), where name is the equivalent TensorFlow layer name, and transpose indicates if we need to transpose the weights when mapping """ if "ln_1" in key: output_ = map_ln_pt_to_tf(key) elif "attn" in key: output_ = map_attn_pt_to_tf(key) elif "mlp" in key: output_ = map_mlp_pt_to_tf(key) else: raise ValueError( f"expected key to have one of ln_1, attn, mlp substrings" f" got {key} instead. Check that the model definition is correct!!" ) return output_ def convert_pt_checkpoint_to_tf( input_dir: str, output_dir: str, share_embeddings: bool, debug: bool, ): """Main function to convert PyTorch weights to TensorFlow. Args: pt_ckpt_path (str): Path to PyTorch checkpoint tf_ckpt_path (str): Path to TensorFlow checkpoint directory share_embeddings (bool): Specifies whether to share embeddings for checkpoint conversion. debug (bool): Enable debug for model creation """ # Create PT model pt_checkpoint_path = os.path.join(input_dir, "pytorch_model.bin") if not os.path.exists(pt_checkpoint_path): print( f"{pt_checkpoint_path} does not exist, downloading checkpoint from HuggingFace, or loading from HugginFace cache." ) pt_model = GPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B") print(f"Model loaded. Saving checkpoint at {input_dir}") pt_model.save_pretrained(input_dir, max_shard_size="30GB") print("Checkpoint saved") else: pt_model = GPTJForCausalLM.from_pretrained(input_dir) print("Created HuggingFace model!!") if debug: # print number of parameters for debugging model_parameters = filter( lambda p: p.requires_grad, pt_model.parameters() ) num_params = sum([p.numel() for p in model_parameters]) print(f"Initialized model with param count: {num_params}") pt_weight_dict = pt_model.state_dict() weight_keys = sorted(list(pt_weight_dict.keys())) state_dict_update = {} keys_mapping = {} shape_mapping = {} # perform mapping for key in weight_keys: if "transformer.wte" in key: tf_name, transpose = map_embeddings_pt_to_tf(key) elif "transformer.h" in key: tf_name, transpose = map_decoder_pt_to_tf(key) elif "transformer.ln_f" or "lm_head" in key: if share_embeddings and key == "lm_head.weight": print( f"{key} not needed when embeddings are shared with" f" classifier. Continuing mapping for keys." ) continue tf_name, transpose = map_outputs_pt_to_tf(key, share_embeddings) if tf_name is None: if "attn.bias" or "attn.masked_bias" in key: continue raise ValueError( f"{key} mapped as None. Ignore if this is desired behavior." f" Else exercise the checkpoint saving with caution!!" ) try: val = pt_weight_dict[key] update_val = val.T if transpose else val update_val = torch.Tensor(update_val) # if valid tensor, insert to mapping state_dict_update[tf_name] = update_val keys_mapping[key] = tf_name shape_mapping[key] = transpose except TypeError: print( f"tried to map {key} to {tf_name}, but got wrong TensorType" f". Ignoring mapping for now, to be fixed later !!" ) # save mappings for verification save_mappings(output_dir, keys_mapping, shape_mapping) # convert finally dictionary to checkpoints tf_ckpt_path = os.path.join(output_dir, "tf_model.ckpt") dict_to_checkpoint(state_dict_update, tf_ckpt_path) def validate_args(args): """Validate the user specified arguments. Args: args (namespace): Argparse arguments """ if not os.path.isdir(args.output_dir): print( "Output directory does not exist. Creating it for runtime execution." ) os.makedirs(args.output_dir, exist_ok=False) def main(): args = get_runtime_args() validate_args(args) # Convert to TF checkpoint convert_pt_checkpoint_to_tf( args.input_dir, args.output_dir, args.share_embeddings, args.debug, ) print("Converted HuggingFace checkpoint successfully!!") if __name__ == "__main__": tf.compat.v1.disable_eager_execution() main()
/** * Guests Table Class -- Represents the number of guests * This class implements the GuestsDAO * therefore, has access to methods that access an arrayList of guests, as well as each individual guest * These methods are useful when accessing all records in the Guests table or individual records (by ID) * @author Farzana Moury * @version 1.0 * @since Nov 24th 2020 */ public class GuestsTable implements GuestsDAO { //properties Database db = Database.getInstance(); ArrayList<Guests> guests; /** * The purpose of this method is to retrieve all records from the Guests table and store them into an arraylist * @return Returns an arrayList of guests */ @Override public ArrayList<Guests> getAllGuests() { String query = "SELECT * FROM " + DBConst.TABLE_GUESTS; guests = new ArrayList<Guests>(); try{ Statement getGuests = db.getConnection().createStatement(); ResultSet data = getGuests.executeQuery(query); while(data.next()){ guests.add(new Guests(data.getInt(DBConst.GUESTS_COLUMN_ID),//id data.getInt(DBConst.GUESTS_COLUMN_NUMBER))); //number of guests } }catch (SQLException e){ e.printStackTrace(); } return guests; } /** * The purpose of this method is to retrieve a specific record from the Guests table * @param guestId corresponding id to the item to be retrieved * @return Returns a guest object or null if the guest_num did not exist in the database */ @Override public Guests getGuest(int guestId) { String query = "SELECT * FROM " + DBConst.TABLE_GUESTS+ " WHERE " + DBConst.GUESTS_COLUMN_ID + " = " + guestId; try{ Statement getGuest = db.getConnection().createStatement(); ResultSet data = getGuest.executeQuery(query); if(data.next()){ Guests guest = new Guests(data.getInt(DBConst.GUESTS_COLUMN_ID), data.getInt(DBConst.GUESTS_COLUMN_NUMBER)); return guest; } }catch (SQLException e) { e.printStackTrace(); } return null; } }
<filename>examples/transform/transform_set.py<gh_stars>0 """ File: examples/transform/transform_set.py Author: <NAME> Date: 22 Feb 2018 Description: Example showing how to use, save, and load TransformSet objects. """ import os from distpy import TransformSet, NullTransform, Log10Transform,\ Exp10Transform, ArcsinTransform, SineTransform transform_set = TransformSet(['log10', None, 'arcsin'], ['a', 'b', 'c']) transform_set2 = TransformSet({'a': 'log10', 'b': None, 'c': 'arcsin'}) assert transform_set == transform_set2 hdf5_file_name = 'TEST_DELETE_THIS.hdf5' transform_set.save(hdf5_file_name) try: assert transform_set == TransformSet.load(hdf5_file_name) except: os.remove(hdf5_file_name) raise else: os.remove(hdf5_file_name) assert transform_set['a'] == Log10Transform() assert transform_set['b'] == NullTransform() assert transform_set['c'] == ArcsinTransform() assert transform_set.inverse['a'] == Exp10Transform() assert transform_set.inverse['b'] == NullTransform() assert transform_set.inverse['c'] == SineTransform()
package com.onlinepayments.client.android.exampleapp.activities; import android.app.Activity; import android.content.Intent; import android.view.View; import androidx.fragment.app.FragmentActivity; import com.onlinepayments.client.android.exampleapp.view.HeaderViewImpl; import com.onlinepayments.client.android.exampleapp.configuration.Constants; import com.onlinepayments.client.android.exampleapp.model.ShoppingCart; import com.onlinepayments.client.android.exampleapp.R; import com.onlinepayments.sdk.client.android.model.PaymentContext; /** * Toggles the shoppingcart details when its clicked * * Copyright 2020 Global Collect Services B.V * */ public class ShoppingCartActivity extends FragmentActivity { private HeaderViewImpl view; private ShoppingCart shoppingCart; private PaymentContext paymentContext; // Boolean to prevent multiple renders of the shoppingcart private boolean rendered = false; public void initialize(Activity activity) { view = new HeaderViewImpl(activity, R.id.header_layout); Intent intent = getIntent(); shoppingCart = (ShoppingCart) intent.getSerializableExtra(Constants.INTENT_SHOPPINGCART); paymentContext = (PaymentContext) intent.getSerializableExtra(Constants.INTENT_PAYMENT_CONTEXT); } @Override public void onStart() { super.onStart(); if (!rendered) { view.renderShoppingCart(shoppingCart, paymentContext); rendered = true; } } public void showShoppingCartDetailView(View v) { view.showDetailView(); } public void hideShoppingCartDetailView(View v) { view.hideDetailView(); } }
<gh_stars>1-10 // Package stock :: exchange.go package stock import "fmt" // Exchange struct type Exchange struct { ID int Stocks map[int]*Stock } // ==== Exchange methods ==== // StockHeader func for stocks list header func (e *Exchange) StockHeader() string { s := &Stock{} return s.StringHeader() } // GetStocks returns sorted stocks list func (e *Exchange) GetStocks() []*Stock { i, stocks := 0, make([]*Stock, len(e.Stocks)) for _, stock := range e.Stocks { stocks[i] = stock i++ } ByStockID().Sort(stocks) return stocks } // String func for Exchange func (e *Exchange) String() string { header := fmt.Sprintf("EX: %d\n========\n%s", e.ID, e.StockHeader()) sTable := "" stocks := e.GetStocks() for _, stock := range stocks { sTable = fmt.Sprintf("%s%v\n", sTable, stock) } return fmt.Sprintf("%s\n%s\n", header, sTable) }
class Struct: """ @class Struct @brief Class with named member variables. """ def __init__(self, **entries): """ @brief Struct constructor @param entries """ self.__dict__.update(entries) def __str__(self): s = '' for d in self.__dict__: s += '%s: %s\n' % (d, self.__dict__[d]) return s[:-1]
n=int(input()) a=[int(i) for i in list(input())] m=a for i in range(1,n+1): t=a[i:]+a[:i] x=t[0] for k in range(n): t[k]=(t[k]-x)%10 m=min(m,t) print(''.join(str(i) for i in m))
def load_torrent(self, torrent, **kwargs): start = kwargs.pop('start', False) verbose = kwargs.pop('verbose', False) verify_load = kwargs.pop('verify_load', True) max_retries = kwargs.pop('max_retries', 5) params = kwargs.pop('params', []) target = kwargs.pop('target', '') p = self._get_conn() tp = TorrentParser(torrent) torrent = xmlrpc.client.Binary(tp._raw_torrent) info_hash = tp.info_hash func_name = self._get_load_function('raw', start, verbose) getattr(p, func_name)(target, torrent, *params) if verify_load: i = 0 while i < max_retries: for torrent in self.get_torrents(): if torrent.info_hash == info_hash: return True time.sleep(1) i += 1 return False return True
import sys sys.setrecursionlimit(10 ** 7) input = sys.stdin.readline n = int(input()) a = [0]* n b = [0]* n c= [(0,0)]*n for i in range(n): a[i], b[i] = map(int, input().split()) c[i] = (i, a[i]+b[i] ) c.sort(key=lambda x:x[1],reverse=True) ans = 0 for i in range(n): if i%2==0: ans+=a[c[i][0]] else: ans-=b[c[i][0]] print(ans)
def decrypt_and_check_admin(self, ciphertext): plaintext = aes_cbc_decrypt(ciphertext, self._key, self._iv) if not check_ascii_compliance(plaintext): raise Exception("The message is not valid", plaintext) return b';admin=true;' in plaintext
<filename>src/pages/Follow/index.tsx import React, { useCallback, useRef, useState } from 'react'; import { Link } from 'react-router-dom'; import { FiMail, FiSearch } from 'react-icons/fi'; import { FormHandles } from '@unform/core'; import { Form } from '@unform/web'; import * as Yup from 'yup'; import { useToast } from '../../hooks/toast'; import getValidationErrors from '../../errors/getValidationErrors'; import Header from '../../components/Header'; import Input from '../../components/Input'; import Button from '../../components/Button'; import { Container, ContainerButton, ButtonHeader, Content, Paragrafo } from './styles'; import api from '../../services/api'; interface FollowFormData { tracking: string; } interface ReportProps { id: number; hash: string; message: string; created_at: string; } const Follow: React.FC = () => { const formRef = useRef<FormHandles>(null); const [report, setReport] = useState<ReportProps>(); const { addToast } = useToast(); const handleSubmit = useCallback( async (data: FollowFormData) => { try { formRef.current?.setErrors({}); const schema = Yup.object().shape({ tracking: Yup.string() .required('Digite um código de acompanhamento válido') }); await schema.validate(data, { abortEarly: false, }); await api.post('/visualizar.php', { hash: data.tracking, }) .then((resp) => { if (resp.data.erro === false) { setReport(resp.data.records) } else { addToast({ type: 'error', title: 'Erro ao pesquisar o relato', description: resp.data.message, }); } }); } catch (err) { if (err instanceof Yup.ValidationError) { const errors = getValidationErrors(err); formRef.current?.setErrors(errors); console.log(errors) addToast({ type: 'error', title: 'Erro ao pesquisar o relato', description: errors.tracking, }); return; } addToast({ type: 'error', title: 'Erro ao pesquisar o relato', description: 'Ocorreu um erro ao pesquisar o relato, tente novamente mais tarde.', }); } }, [addToast] ); return ( <> <Header /> <Container> <ContainerButton> <Link to="/"><ButtonHeader type="button">Voltar</ButtonHeader></Link> </ContainerButton> <Content> <h1>Acompanhar relato</h1> <Form ref={formRef} onSubmit={handleSubmit}> <Input name="tracking" icon={FiMail} placeholder="Código de acompanhamento" /> <Button type="submit"><FiSearch /> Pesquisar Relato</Button> </Form> </Content> <Paragrafo><strong>Código de Acompanhamento:</strong> {report?.hash}</Paragrafo> <Paragrafo><strong>Descrição do Relato:</strong> {report?.message}</Paragrafo> <Paragrafo><strong>Data do relato:</strong> {report?.created_at}</Paragrafo> </Container> </> ); } export default Follow;
/* Register a language-switch callback function. */ void WEB_SetLanguageFn(WEB_LanguageFn fn, void *p) { webLanguageFn = fn; webLanguageFnArg = p; }
import warnings import numpy as np from dipy.utils.optpkg import optional_package from dipy.viz.horizon.tab import (HorizonTab, build_label, color_double_slider, color_single_slider) fury, has_fury, setup_module = optional_package('fury') if has_fury: from fury import colormap, ui from fury.data import read_viz_icons class SlicesTab(HorizonTab): def __init__(self, slices_visualizer, id=0): self.__visualizer = slices_visualizer self.__actors = self.__visualizer.slice_actors if id == 0: self.__name = 'Image' else: self.__name = f'Image {id}' self.__tab_id = 0 self.__tab_ui = None self.__data_shape = self.__visualizer.data_shape self.__selected_slice_x = self.__visualizer.selected_slices[0] self.__selected_slice_y = self.__visualizer.selected_slices[1] self.__selected_slice_z = self.__visualizer.selected_slices[2] self.__min_intensity = self.__visualizer.intensities_range[0] self.__max_intensity = self.__visualizer.intensities_range[1] self.__slider_label_opacity = build_label(text='Opacity') opacity = 1 length = 450 lw = 3 radius = 8 fs = 16 tt = '{ratio:.0%}' self.__slider_opacity = ui.LineSlider2D( initial_value=opacity, max_value=1., length=length, line_width=lw, outer_radius=radius, font_size=fs, text_template=tt) color_single_slider(self.__slider_opacity) self.__slices_opacity = 1 self.__slider_opacity.on_change = self.__change_opacity self.__slider_label_x = build_label(text='X Slice') self.__slider_label_y = build_label(text='Y Slice') self.__slider_label_z = build_label(text='Z Slice') tt = '{value:.0f}' self.__slider_slice_x = ui.LineSlider2D( initial_value=self.__selected_slice_x, max_value=self.__data_shape[0] - 1, length=length, line_width=lw, outer_radius=radius, font_size=fs, text_template=tt) self.__slider_slice_y = ui.LineSlider2D( initial_value=self.__selected_slice_y, max_value=self.__data_shape[1] - 1, length=length, line_width=lw, outer_radius=radius, font_size=fs, text_template=tt) self.__slider_slice_z = ui.LineSlider2D( initial_value=self.__selected_slice_z, max_value=self.__data_shape[2] - 1, length=length, line_width=lw, outer_radius=radius, font_size=fs, text_template=tt) color_single_slider(self.__slider_slice_x) color_single_slider(self.__slider_slice_y) color_single_slider(self.__slider_slice_z) self.__slider_slice_x.on_change = self.__change_slice_x self.__slider_slice_y.on_change = self.__change_slice_y self.__slider_slice_z.on_change = self.__change_slice_z icon_files = [] icon_files.append(('minus', read_viz_icons(fname='minus.png'))) icon_files.append(('plus', read_viz_icons(fname='plus.png'))) self.__button_slice_x = ui.Button2D( icon_fnames=icon_files, size=(25, 25)) self.__button_slice_y = ui.Button2D( icon_fnames=icon_files, size=(25, 25)) self.__button_slice_z = ui.Button2D( icon_fnames=icon_files, size=(25, 25)) self.__slice_visibility_x = True self.__slice_visibility_y = True self.__slice_visibility_z = True self.__button_slice_x.on_left_mouse_button_clicked = ( self.__change_slice_visibility_x) self.__button_slice_y.on_left_mouse_button_clicked = ( self.__change_slice_visibility_y) self.__button_slice_z.on_left_mouse_button_clicked = ( self.__change_slice_visibility_z) self.__slider_label_intensities = build_label(text='Intensities') self.__slider_intensities = ui.LineDoubleSlider2D( initial_values=self.__visualizer.intensities_range, min_value=self.__visualizer.volume_min, max_value=self.__visualizer.volume_max, length=length, line_width=lw, outer_radius=radius, font_size=fs, text_template=tt) color_double_slider(self.__slider_intensities) self.__slider_intensities.on_change = self.__change_intensity self.__buttons_label_colormap = build_label(text='Colormap') self.__supported_colormaps = { 'Gray': 'gray', 'Bone': 'bone', 'Cividis': 'cividis', 'Inferno': 'inferno', 'Magma': 'magma', 'Viridis': 'viridis', 'Jet': 'jet', 'Pastel 1': 'Pastel1', 'Distinct': 'dist'} self.__selected_colormap_idx = 0 selected_colormap = list(self.__supported_colormaps)[ self.__selected_colormap_idx] self.__colormap = self.__supported_colormaps[selected_colormap] self.__label_selected_colormap = build_label(text=selected_colormap) self.__button_previous_colormap = ui.Button2D( icon_fnames=[('left', read_viz_icons(fname='circle-left.png'))], size=(25, 25)) self.__button_next_colormap = ui.Button2D( icon_fnames=[('right', read_viz_icons(fname='circle-right.png'))], size=(25, 25)) self.__button_previous_colormap.on_left_mouse_button_clicked = ( self.__change_colormap_previous) self.__button_next_colormap.on_left_mouse_button_clicked = ( self.__change_colormap_next) data_ndim = len(self.__data_shape) self.__picker_label_voxel = build_label(text='Voxel') self.__label_picked_voxel = build_label(text='') self.__visualizer.register_picker_callback(self.__change_picked_voxel) if data_ndim == 4: self.__slider_label_volume = build_label(text='Volume') self.__selected_volume_idx = 0 self.__slider_volume = ui.LineSlider2D( initial_value=self.__selected_volume_idx, max_value=self.__data_shape[-1] - 1, length=length, line_width=lw, outer_radius=radius, font_size=fs, text_template=tt) color_single_slider(self.__slider_volume) self.__slider_volume.handle_events( self.__slider_volume.handle.actor) self.__slider_volume.on_left_mouse_button_released = ( self.__change_volume) def __change_colormap_next(self, i_ren, _obj, _button): selected_color_idx = self.__selected_colormap_idx + 1 if selected_color_idx >= len(self.__supported_colormaps): selected_color_idx = 0 self.__selected_colormap_idx = selected_color_idx selected_colormap = list(self.__supported_colormaps)[ self.__selected_colormap_idx] self.__label_selected_colormap.message = selected_colormap self.__colormap = self.__supported_colormaps[selected_colormap] self.__update_colormap() i_ren.force_render() def __change_colormap_previous(self, i_ren, _obj, _button): selected_colormap_idx = self.__selected_colormap_idx - 1 if selected_colormap_idx < 0: selected_colormap_idx = len(self.__supported_colormaps) - 1 self.__selected_colormap_idx = selected_colormap_idx selected_colormap = list(self.__supported_colormaps)[ self.__selected_colormap_idx] self.__label_selected_colormap.message = selected_colormap self.__colormap = self.__supported_colormaps[selected_colormap] self.__update_colormap() i_ren.force_render() def __change_intensity(self, slider): self.__min_intensity = slider.left_disk_value self.__max_intensity = slider.right_disk_value self.__update_colormap() def __change_opacity(self, slider): self.__slices_opacity = slider.value self.__update_opacities() def __change_picked_voxel(self, message): self.__label_picked_voxel.message = message def __change_slice_x(self, slider): self.__selected_slice_x = int(np.rint(slider.value)) self.__actors[0].display_extent( self.__selected_slice_x, self.__selected_slice_x, 0, self.__data_shape[1] - 1, 0, self.__data_shape[2] - 1) def __change_slice_y(self, slider): self.__selected_slice_y = int(np.rint(slider.value)) self.__actors[1].display_extent( 0, self.__data_shape[0] - 1, self.__selected_slice_y, self.__selected_slice_y, 0, self.__data_shape[2] - 1) def __change_slice_z(self, slider): self.__selected_slice_z = int(np.rint(slider.value)) self.__actors[2].display_extent( 0, self.__data_shape[0] - 1, 0, self.__data_shape[1] - 1, self.__selected_slice_z, self.__selected_slice_z) def __change_slice_visibility_x(self, i_ren, _obj, _button): self.__slice_visibility_x = not self.__slice_visibility_x self.__update_slice_visibility_x() _button.next_icon() i_ren.force_render() def __change_slice_visibility_y(self, i_ren, _obj, _button): self.__slice_visibility_y = not self.__slice_visibility_y self.__update_slice_visibility_y() _button.next_icon() i_ren.force_render() def __change_slice_visibility_z(self, i_ren, _obj, _button): self.__slice_visibility_z = not self.__slice_visibility_z self.__update_slice_visibility_z() _button.next_icon() i_ren.force_render() def __change_volume(self, istyle, obj, slider): value = int(np.rint(slider.value)) if value != self.__selected_volume_idx: visible_slices = ( self.__selected_slice_x, self.__selected_slice_y, self.__selected_slice_z) valid_vol = self.__visualizer.change_volume( self.__selected_volume_idx, value, [self.__min_intensity, self.__max_intensity], visible_slices) if not valid_vol: warnings.warn( f'Volume N°{value} does not have any contrast. Please, ' 'check the value ranges of your data. Returning to ' 'previous volume.') self.__slider_volume.value = self.__selected_volume_idx else: intensities_range = self.__visualizer.intensities_range # Updating the colormap self.__min_intensity = intensities_range[0] self.__max_intensity = intensities_range[1] self.__update_colormap() # Updating intensities slider self.__slider_intensities.initial_values = intensities_range self.__slider_intensities.min_value = ( self.__visualizer.volume_min) self.__slider_intensities.max_value = ( self.__visualizer.volume_max) self.__slider_intensities.update(0) self.__slider_intensities.update(1) # Updating opacities self.__update_opacities() # Updating visibilities self.__update_slice_visibility_x() self.__update_slice_visibility_y() self.__update_slice_visibility_z() self.__selected_volume_idx = value istyle.force_render() def __update_colormap(self): if self.__colormap == 'dist': rgb = colormap.distinguishable_colormap(nb_colors=256) rgb = np.asarray(rgb) else: rgb = colormap.create_colormap( np.linspace(self.__min_intensity, self.__max_intensity, 256), name=self.__colormap, auto=True) num_lut = rgb.shape[0] lut = colormap.LookupTable() lut.SetNumberOfTableValues(num_lut) lut.SetRange(self.__min_intensity, self.__max_intensity) for i in range(num_lut): r, g, b = rgb[i] lut.SetTableValue(i, r, g, b) lut.SetRampToLinear() lut.Build() for slice_actor in self.__actors: slice_actor.output.SetLookupTable(lut) slice_actor.output.Update() def __update_opacities(self): for slice_actor in self.__actors: slice_actor.GetProperty().SetOpacity(self.__slices_opacity) def __update_slice_visibility_x(self): self.__slider_slice_x.set_visibility(self.__slice_visibility_x) self.__actors[0].SetVisibility(self.__slice_visibility_x) def __update_slice_visibility_y(self): self.__slider_slice_y.set_visibility(self.__slice_visibility_y) self.__actors[1].SetVisibility(self.__slice_visibility_y) def __update_slice_visibility_z(self): self.__slider_slice_z.set_visibility(self.__slice_visibility_z) self.__actors[2].SetVisibility(self.__slice_visibility_z) def build(self, tab_id, tab_ui): self.__tab_id = tab_id self.__tab_ui = tab_ui x_pos = .02 self.__tab_ui.add_element( self.__tab_id, self.__slider_label_opacity, (x_pos, .85)) self.__tab_ui.add_element( self.__tab_id, self.__slider_label_x, (x_pos, .62)) self.__tab_ui.add_element( self.__tab_id, self.__slider_label_y, (x_pos, .38)) self.__tab_ui.add_element( self.__tab_id, self.__slider_label_z, (x_pos, .15)) x_pos = .1 self.__tab_ui.add_element( self.__tab_id, self.__button_slice_x, (x_pos, .60)) self.__tab_ui.add_element( self.__tab_id, self.__button_slice_y, (x_pos, .36)) self.__tab_ui.add_element( self.__tab_id, self.__button_slice_z, (x_pos, .13)) x_pos = .12 self.__tab_ui.add_element( self.__tab_id, self.__slider_opacity, (x_pos, .85)) self.__tab_ui.add_element( self.__tab_id, self.__slider_slice_x, (x_pos, .62)) self.__tab_ui.add_element( self.__tab_id, self.__slider_slice_y, (x_pos, .38)) self.__tab_ui.add_element( self.__tab_id, self.__slider_slice_z, (x_pos, .15)) x_pos = .52 self.__tab_ui.add_element( self.__tab_id, self.__slider_label_intensities, (x_pos, .85)) self.__tab_ui.add_element( self.__tab_id, self.__buttons_label_colormap, (x_pos, .56)) self.__tab_ui.add_element( self.__tab_id, self.__picker_label_voxel, (x_pos, .38)) x_pos = .60 self.__tab_ui.add_element( self.__tab_id, self.__slider_intensities, (x_pos, .85)) self.__tab_ui.add_element( self.__tab_id, self.__button_previous_colormap, (x_pos, .54)) self.__tab_ui.add_element( self.__tab_id, self.__label_selected_colormap, (.63, .56)) self.__tab_ui.add_element( self.__tab_id, self.__button_next_colormap, (.69, .54)) self.__tab_ui.add_element( self.__tab_id, self.__label_picked_voxel, (x_pos, .38)) data_ndim = len(self.__data_shape) if data_ndim == 4: x_pos = .52 self.__tab_ui.add_element( self.__tab_id, self.__slider_label_volume, (x_pos, .15)) x_pos = .60 self.__tab_ui.add_element( self.__tab_id, self.__slider_volume, (x_pos, .15)) @property def name(self): return self.__name
<gh_stars>1-10 /* { dg-do run } */ #include <limits.h> int a = 0, b = INT_MAX - 1; extern void abort(void); int main() { if (a - 1 > b + 1) abort(); return 0; }
import * as React from 'react'; const TextBold24RegularIcon = () => { return( <?xml version="1.0" encoding="UTF-8"?> <svg width="24px" height="24px" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <!-- Generator: Sketch 64 (93537) - https://sketch.com --> <title>ic_fluent_text_bold_24_regular</title> <desc>Created with Sketch.</desc> <g id="🔍-System-Icons" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="ic_fluent_text_bold_24_regular" fill="#212121" fill-rule="nonzero"> <path d="M12.38,4.00006 C15.0166,4.00006 17,6.18217 17,8.62546 C17,9.6021 16.6833,10.5368 16.1346,11.307 C17.2115,12.1341 18,13.4275 18,15.1201 C18,18.2315 15.3015,20.0001 13.12,20.0001 L8,20.0001 C7.17157,20.0001 6.5,19.3285 6.5,18.5001 L6.49658977,5.50088 C6.49637,5.10291 6.65431,4.72117 6.93564,4.43969 C7.21697,4.15821 7.59862,4.00006 7.99658977,4.00006 L12.38,4.00006 Z M13.12,13.25 L9.5,13.25 L9.5,17.0001 L13.12,17.0001 C13.9931,17.0001 15,16.2465 15,15.1201 C15,13.9902 14.0253,13.25 13.12,13.25 L13.12,13.25 Z M12.38,7.00006 L9.49741,7.00006 L9.49918,10.25 L12.38,10.25 C13.2829,10.25 14,9.49057 14,8.62546 C14,7.76006 13.2819,7.00006 12.38,7.00006 Z" id="Shape"></path> </g> </g> </svg> )}; export default TextBold24RegularIcon;
import { chromium, BrowserContext, Page } from 'playwright-chromium'; import path from 'path'; const EXTENSION_PATH = path.resolve(__dirname, './extension'); export interface Context { browserContext: BrowserContext, backgroundPage: Page, } const start = async () => { const userDataDir = '/tmp/test-user-data-dir'; const browserContext = await chromium.launchPersistentContext(userDataDir, { headless: false, args: [ `--disable-extensions-except=${EXTENSION_PATH}`, `--load-extension=${EXTENSION_PATH}`, ], }); const backgroundPages = browserContext.backgroundPages(); const backgroundPage = backgroundPages.length ? backgroundPages[0] : await browserContext.waitForEvent('backgroundpage'); await backgroundPage.waitForFunction( () => window.tsWebExtension.isStarted, null, { polling: 100 }, ); return { browserContext, backgroundPage, }; }; const config = async (context: Context, rulesText: string) => { await context.backgroundPage.evaluate(async (rulesText: string) => { await window.tsWebExtension.configure(Object.assign(window.tsWebExtension.configuration, { filters: [{ filterId: 1, content: rulesText, }], })); }, rulesText); }; export const extension = { start, config, };
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- 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. """ import os from conf import dataapi_settings_pro from pizza.settings_default import * # noqa CELERY_TIMEZONE = getattr(dataapi_settings_pro, 'CELERY_TIMEZONE', 'Asia/Shanghai') STANDARD_PROJECT_ID = getattr(dataapi_settings_pro, 'STANDARD_PROJECT_ID', 0) INSTALLED_APPS += ( # noqa 'datamanage.pro.lifecycle', 'datamanage.pro.dataquality', 'datamanage.pro.datamodel', ) LOCALE_PATHS += (os.path.join(PIZZA_ROOT, APP_NAME, 'pro', 'locale'),) # noqa # noqa BROKER_URL = "redis://{}:{}@{}:{}/0".format( getattr(dataapi_settings_pro, 'REDIS_NAME'), getattr(dataapi_settings_pro, 'REDIS_PASS'), getattr(dataapi_settings_pro, 'REDIS_HOST'), getattr(dataapi_settings_pro, 'REDIS_PORT'), ) CELERY_BROKER_URL = "redis://{}:{}@{}:{}/0".format( getattr(dataapi_settings_pro, 'REDIS_NAME'), getattr(dataapi_settings_pro, 'REDIS_PASS'), getattr(dataapi_settings_pro, 'REDIS_HOST'), getattr(dataapi_settings_pro, 'REDIS_PORT'), ) RABBITMQ_USER = getattr(dataapi_settings_pro, 'RABBITMQ_USER', '') RABBITMQ_PASS = getattr(dataapi_settings_pro, 'RABBITMQ_PASS', '') RABBITMQ_HOST = getattr(dataapi_settings_pro, 'RABBITMQ_HOST', '') RABBITMQ_PORT = getattr(dataapi_settings_pro, 'RABBITMQ_PORT', '') RABBITMQ_VHOST = getattr(dataapi_settings_pro, 'RABBITMQ_VHOST', '') CELERY_BROKER_URL = 'amqp://{user}:{password}@{host}:{port}/{vhost}'.format( user=RABBITMQ_USER, password=<PASSWORD>, host=RABBITMQ_HOST, port=RABBITMQ_PORT, vhost=RABBITMQ_VHOST ) CELERY_RESULT_BACKEND = CELERY_BROKER_URL CELERY_ENABLE_UTC = True LOGGER_FORMATTER = 'verbose' # 自定义日志 LOGGING['handlers'].update( { 'range_task': { 'class': LOG_CLASS, 'formatter': LOGGER_FORMATTER, 'filename': os.path.join(LOG_DIR, 'sys_range_task.log'), 'maxBytes': LOG_MAX_BYTES, 'backupCount': LOG_BACKUP_COUNT, }, 'heat_task': { 'class': LOG_CLASS, 'formatter': LOGGER_FORMATTER, 'filename': os.path.join(LOG_DIR, 'sys_heat_task.log'), 'maxBytes': LOG_MAX_BYTES, 'backupCount': LOG_BACKUP_COUNT, }, 'score_sort_task': { 'class': LOG_CLASS, 'formatter': LOGGER_FORMATTER, 'filename': os.path.join(LOG_DIR, 'sys_score_sort_task.log'), 'maxBytes': LOG_MAX_BYTES, 'backupCount': LOG_BACKUP_COUNT, }, 'data_inventory_task': { 'class': LOG_CLASS, 'formatter': LOGGER_FORMATTER, 'filename': os.path.join(LOG_DIR, 'sys_data_inventory_task.log'), 'maxBytes': LOG_MAX_BYTES, 'backupCount': LOG_BACKUP_COUNT, }, 'app_code_task': { 'class': LOG_CLASS, 'formatter': LOGGER_FORMATTER, 'filename': os.path.join(LOG_DIR, 'sys_app_code_task.log'), 'maxBytes': LOG_MAX_BYTES, 'backupCount': LOG_BACKUP_COUNT, }, 'data_model_sync': { 'class': LOG_CLASS, 'formatter': LOGGER_FORMATTER, 'filename': os.path.join(LOG_DIR, 'sys_data_model_sync.log'), 'maxBytes': LOG_MAX_BYTES, 'backupCount': LOG_BACKUP_COUNT, }, } ) LOGGING['loggers'].update( { 'range_task': {'handlers': ['range_task'], 'level': LOGGER_LEVEL, 'propagate': False}, 'heat_task': {'handlers': ['heat_task'], 'level': LOGGER_LEVEL, 'propagate': False}, 'score_sort_task': {'handlers': ['score_sort_task'], 'level': LOGGER_LEVEL, 'propagate': False}, 'data_inventory_task': {'handlers': ['data_inventory_task'], 'level': LOGGER_LEVEL, 'propagate': False}, 'app_code_task': {'handlers': ['app_code_task'], 'level': LOGGER_LEVEL, 'propagate': False}, 'data_model_sync': {'handlers': ['data_model_sync'], 'level': LOGGER_LEVEL, 'propagate': False}, } ) RANGE_METRIC_MEASUREMENT = 'range_metrics' HEAT_METRIC_MEASUREMENT = 'heat_metrics' HEAT_RELATED_METRIC_MEASUREMENT = 'heat_related_metric' ZK_ADDR = getattr(dataapi_settings_pro, 'ZK_ADDR', '127.0.0.1:8000') ZK_PATH = getattr(dataapi_settings_pro, 'ZK_PATH', '/metadata_access_service') META_ACCESS_RPC_ENDPOINT = getattr( dataapi_settings_pro, 'META_ACCESS_RPC_ENDPOINT', 'http://127.0.0.1:5000/jsonrpc/2.0/' ) RULE_AUDIT_TASK_QUEUE = getattr(dataapi_settings_pro, 'RULE_AUDIT_TASK_QUEUE', 'data_set_audit_tasks') CACHES['redis'] = { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://{}:{}@{}:{}/0".format( getattr(dataapi_settings_pro, 'REDIS_NAME'), getattr(dataapi_settings_pro, 'REDIS_PASS'), getattr(dataapi_settings_pro, 'REDIS_HOST'), getattr(dataapi_settings_pro, 'REDIS_PORT'), # redis的地址 ), "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS": {"max_connections": 10}, # 池的个数 }, } CACHES['default'] = CACHES['redis'] ES_USER = getattr(dataapi_settings_pro, 'ES_USER', '') ES_PASS = getattr(dataapi_settings_pro, 'ES_PASS', '') ES_HOST = getattr(dataapi_settings_pro, 'ES_HOST', '') ES_PORT = getattr(dataapi_settings_pro, 'ES_PORT', '') DATA_TRACE_ES_TOKEN = getattr(dataapi_settings_pro, 'DATA_TRACE_ES_PASS_TOKEN', '') DATA_TRACE_ES_API_HOST = getattr(dataapi_settings_pro, 'DATA_TRACE_ES_API_HOST', '') DATA_TRACE_ES_API_PORT = getattr(dataapi_settings_pro, 'DATA_TRACE_ES_API_PORT', '') DATA_TRACE_ES_API_ADDR = 'http://{}:{}'.format(DATA_TRACE_ES_API_HOST, DATA_TRACE_ES_API_PORT) ES_SETTINGS = getattr(dataapi_settings_pro, 'ES_SETTINGS', '') # 数据修正、数据剖析Session环境变量 CORRECTING_DEBUG_SESSION_KEY = 'data_correct_debug_session' DATA_PROFILING_SESSION_KEY = 'data_profiling_session' SESSION_GEOG_AREA_CODE = 'inland' DEBUG_VIRTUAL_TABLE = getattr(dataapi_settings_pro, 'DEBUG_VIRTUAL_TABLE') PARQUET_FILE_TMP_FOLDER = getattr(dataapi_settings_pro, 'PARQUET_FILE_TMP_FOLDER') ASSET_VALUE_SCORE = getattr(dataapi_settings_pro, 'ASSET_VALUE_SCORE', 0)
<gh_stars>10-100 import {NgModule} from '@angular/core'; import {FormRoutingModule} from './form-routing.module'; import {FormComponent} from './form.component'; import {ProjectShareModule} from '../project-share/project-share.module'; import {UiModule, TabModule} from '@apereo/mgmt-lib'; /** * Module to lazy-load form components for the application. * * @author <NAME> */ @NgModule({ imports: [ ProjectShareModule, FormRoutingModule, UiModule, TabModule ], declarations: [ FormComponent ] }) export class FormModule {}
<gh_stars>1-10 import s from '../error/teste'; it('s', () => { const warn = jest.spyOn(global.console, 'warn'); expect.hasAssertions(); s('Almerindo'); expect(warn).toBeCalled(); });
/** * Create a key store suitable for use as a trust store, containing only * the certificates associated with each alias in the passed in * credentialStore. * * @param credentialStore key store containing public/private credentials. * @return a key store containing only certificates. */ public static KeyStore createTrustStore(KeyStore credentialStore) throws Exception { KeyStore store = KeyStore.getInstance("JKS"); store.load(null, null); for (Enumeration<String> en = credentialStore.aliases(); en.hasMoreElements();) { String alias = en.nextElement(); store.setCertificateEntry(alias, credentialStore.getCertificate(alias)); } return store; }
def dpkgAlternatives(cls, dpkg): installed = dpkg.installed() cython3 = 'cython3', missing = [ pkg for pkg in cython3 if pkg not in installed ] if not missing: yield Cython3.flavor, cython3 cython2 = 'cython', missing = [ pkg for pkg in cython2 if pkg not in installed ] if not missing: yield Cython2.flavor, cython2 return
<reponame>jamalg/my_shops from back.utils.config_class.config import ( BaseConfig, EnvironmentVariable, IntEnvironmentVariable, FloatEnvironmentVariable, BoolEnvironmentVariable) __all__ = [BaseConfig, EnvironmentVariable, IntEnvironmentVariable, FloatEnvironmentVariable, BoolEnvironmentVariable]
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> pii; #define x first #define y second int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<pii> a(n); vector<int> p; for (int i = 0; i < n; i++) { cin >> a[i].x >> a[i].y; p.push_back(a[i].x); p.push_back(a[i].y); } sort(p.begin(), p.end()); int m = unique(p.begin(), p.end()) - p.begin(); vector<int> start(m+5), End(m+5), pre_s(m+5), rpos(m+5); for (int i = 0; i < n; i++) { int l, r; l = lower_bound(p.begin(), p.begin() + m, a[i].x) - p.begin(); r = lower_bound(p.begin(), p.begin() + m, a[i].y) - p.begin(); start[l]++; End[r]++; rpos[l] = max(rpos[l], r); } int N = m + 2; for (int i = 0; i < N-1; i++) { pre_s[i+1] = pre_s[i] + start[i]; } int res = n, left = 0; for (int i = 0; i < N-1; i++) { if (start[i]) { int r = rpos[i]; res = min(res, pre_s[N-1] - pre_s[r+1] + left); } left += End[i]; } cout << res << endl; } }
<filename>src/main/java/com/nullfish/app/jfd2/filelist/TimestampConditionEditor.java package com.nullfish.app.jfd2.filelist; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JTextField; import com.nullfish.app.jfd2.resource.JFDResource; import com.nullfish.app.jfd2.util.ResourceBundleComboBox; import com.nullfish.lib.ui.document.RestrictedDocument; import com.nullfish.lib.ui.document.YyyymmddDateRestriction; import com.nullfish.lib.vfs.impl.filelist.condition.Condition; import com.nullfish.lib.vfs.impl.filelist.condition.TimestampCondition; public class TimestampConditionEditor implements ConditionEditor { public static final String NAME = "timestamp"; public static final String LABEL = "condition_timestamp"; public static final String TAG_NAME = "timestamp"; private JPanel panel = new JPanel(new BorderLayout(3, 0)); private JComboBox operationComboBox = new ResourceBundleComboBox(JFDResource.LABELS); private RecentPanel recentPanel = new RecentPanel(); private CardLayout cardLayout = new CardLayout(); private JPanel cardPanel = new JPanel(cardLayout); private JTextField text = new JTextField(); public TimestampConditionEditor() { Dimension d = operationComboBox.getPreferredSize(); d.width = 80; operationComboBox.setPreferredSize(d); cardPanel.add(text, "absolute"); cardPanel.add(recentPanel, "recent"); panel.add(cardPanel, BorderLayout.CENTER); panel.add(operationComboBox, BorderLayout.WEST); operationComboBox.addItem("before"); operationComboBox.addItem("after"); operationComboBox.addItem("recent"); RestrictedDocument doc = new RestrictedDocument(); doc.addRestriction(new YyyymmddDateRestriction()); text.setDocument(doc); text.setText(new SimpleDateFormat("yyyyMMdd").format(new Date(System.currentTimeMillis()))); operationComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { cardLayout.show(cardPanel, "recent".equals(operationComboBox.getSelectedItem()) ? "recent" : "absolute"); } }); } public Condition getCondition() { String operation = (String)operationComboBox.getSelectedItem(); if("recent".equals(operation)) { return new TimestampCondition(operation, recentPanel.getValue()); } else { SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmm"); Date date; try { date = format1.parse(text.getText()); } catch (ParseException e) { date = new Date(); } return new TimestampCondition(operation, format2.format(date)); } } public JComponent getEditorComponent() { return panel; } public String getName() { return NAME; } public String getTagName() { return TAG_NAME; } public void init(Condition condition) { TimestampCondition cond = (TimestampCondition) condition; operationComboBox.setSelectedItem(cond.getOperation()); if("recent".equals(cond.getOperation())) { recentPanel.setValue(cond.getTime()); } else { String value = cond.getTime(); if(value.length() > 8) { value = value.substring(0, 8); } text.setText(value); } } public String getLabel() { return LABEL; } public boolean isEmpty() { return text.getText().length() == 0; } }
package com.thought.monkey.protoBuilder; import com.thought.monkey.wsmessage.MessageInfo; /** * @Auther: wei_tung * @Description: <EMAIL> */ public class NotificationMsgBuilder { public static MessageInfo.Model buildNotification(String content) { MessageInfo.MessageBody messageBody = MessageInfo.MessageBody.newBuilder() .setContent(content) .setType(0) .setTime(String.valueOf(System.currentTimeMillis())).build(); MessageInfo.Model.Builder rb = MessageInfo.Model.newBuilder() .setCmd(MessageInfo.CmdType.MESSAGE_NOTIFICATION) .setContent(messageBody.toByteString()); return rb.build(); } }
<filename>src/test/java/com/sap/oss/phosphor/fosstars/model/qa/ScoreTestVectorTest.java package com.sap.oss.phosphor.fosstars.model.qa; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; import com.sap.oss.phosphor.fosstars.model.Interval; import com.sap.oss.phosphor.fosstars.model.Score; import com.sap.oss.phosphor.fosstars.model.Value; import com.sap.oss.phosphor.fosstars.model.math.DoubleInterval; import com.sap.oss.phosphor.fosstars.model.score.example.ExampleScores; import com.sap.oss.phosphor.fosstars.util.Json; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.junit.Test; public class ScoreTestVectorTest { @Test public void testValuesFor() { Map<Class<? extends Score>, Double> values = new HashMap<>(); values.put(ExampleScores.PROJECT_ACTIVITY_SCORE_EXAMPLE.getClass(), 5.3); values.put(ExampleScores.SECURITY_TESTING_SCORE_EXAMPLE.getClass(), 4.0); Interval expectedScore = DoubleInterval.init().from(4.0).to(6.4).closed().make(); ScoreTestVector vector = new ScoreTestVector( values, expectedScore, null, "test", false, false); Set<Value<?>> set = vector.valuesFor(ExampleScores.SECURITY_SCORE_EXAMPLE); assertNotNull(set); assertEquals(2, set.size()); assertTrue(set.contains(ExampleScores.PROJECT_ACTIVITY_SCORE_EXAMPLE.value(5.3))); assertTrue(set.contains(ExampleScores.SECURITY_TESTING_SCORE_EXAMPLE.value(4.0))); } @Test public void testYamlSerializeAndDeserialize() throws IOException { Map<Class<? extends Score>, Double> values = new HashMap<>(); values.put(ExampleScores.PROJECT_ACTIVITY_SCORE_EXAMPLE.getClass(), 5.3); values.put(ExampleScores.SECURITY_TESTING_SCORE_EXAMPLE.getClass(), 4.0); Interval expectedScore = DoubleInterval.init().from(4.0).to(6.4).closed().make(); ScoreTestVector vector = new ScoreTestVector( values, expectedScore, null, "test", false, false); YAMLFactory factory = new YAMLFactory(); factory.disable(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID); byte[] bytes = Json.toBytes(vector); assertNotNull(bytes); assertTrue(bytes.length > 0); ScoreTestVector clone = Json.read(bytes, ScoreTestVector.class); assertEquals(vector, clone); assertEquals(vector.hashCode(), clone.hashCode()); } }
package com.bitdubai.sub_app.intra_user_community.adapters; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Path; import android.graphics.Rect; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import com.bitdubai.fermat_android_api.layer.definition.wallet.views.FermatTextView; import com.bitdubai.sub_app.intra_user_community.R; import java.util.List; /** * Created by <NAME> */ public class ListAdapter extends ArrayAdapter<CheckBoxListItem> { public ListAdapter(Context context, int textViewResourceId) { super(context, textViewResourceId); } public ListAdapter(Context context, int resource, List<CheckBoxListItem> items) { super(context, resource, items); } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi; vi = LayoutInflater.from(getContext()); v = vi.inflate(R.layout.itemlistrow, null); } CheckBoxListItem checkBoxListItem = getItem(position); if (checkBoxListItem != null) { ImageView imageView_Item =(ImageView) v.findViewById(R.id.imageView_Item); imageView_Item.setImageDrawable(checkBoxListItem.getIcon()); imageView_Item.setImageBitmap(getRoundedShape(BitmapFactory.decodeByteArray(checkBoxListItem.getIntraUserIdentity().getProfileImage(), 0, checkBoxListItem.getIntraUserIdentity().getProfileImage().length))); FermatTextView textView_identity = (FermatTextView) v.findViewById(R.id.textView_identity); textView_identity.setText(checkBoxListItem.getIntraUserIdentity().getAlias()); } return v; } public Bitmap getRoundedShape(Bitmap scaleBitmapImage) { int targetWidth = 50; int targetHeight = 50; Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(targetBitmap); Path path = new Path(); path.addCircle(((float) targetWidth - 1) / 2, ((float) targetHeight - 1) / 2, (Math.min(((float) targetWidth), ((float) targetHeight)) / 2), Path.Direction.CCW); canvas.clipPath(path); Bitmap sourceBitmap = scaleBitmapImage; canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight()), new Rect(0, 0, targetWidth, targetHeight), null); return targetBitmap; } }
Mobile home park lot rents are ridiculously low. In most markets, the difference between apartment rents and mobile home park rents is often $1,000 per month. But this is not going to remain the case, and smart investors are betting on the future run-up of mobile home park rents. Mobile home park rents stand to have larger increases than any other real estate sector in the U.S. Why is that? The spread between mobile home lot rents and all other forms of housing have become ridiculous The median home price in the U.S. is close to $200,000. The average apartment rent is nearly $1,200 per month. The average mobile home park rent is $275 per month. That’s not a misprint. Mobile home park rents are nearly $1,000 per month lower than apartments, and mobile homes sell for around $10,000, which is $190,000 lower than a stick-built home. How did the spreads get so huge? It’s because mom and pop owners of mobile home parks never kept their rents up to speed with their competition. Kind of like those rare occasions where you find an old vending machine in a small town where the Coke is 10 cents a can. Rents must go up for parks not to be developed into other uses At $275 per month average rent, the typical mobile home park is worth less than $5 per square foot. Virtually every other use for land out there is more than $5 per square foot. So you can basically figure on most mobile home parks being torn down and redeveloped if the rents don’t go up significantly. One day there will only be two types of mobile home parks : those that charge high rents and those that have been rebuilt into a different use. This is already happening across America. Professional owners are going to demand professional-grade rents Mobile home parks are the most fragmented segment of real estate, with 44,000 total parks and only 2,000 of those professionally owned and managed. Self-storage, which is only half as old, is already three times more consolidated. As professional investors buy out these parks, they are going to be bent on increasing rents significantly. And why not? And even twice the rent, mobile home park living is still a bargain. Higher rents are required to offer a quality product and offer quality management Mobile home park managers earn less than a half of what apartment complex managers earn. That’s got to change. In order to deliver a quality product, the rent in mobile home parks has to go up substantially. That’s the only way to provide professional management and a quality experience for the tenants. To keep a mobile home park in top condition takes money. And that money comes from rents. Look what happens to mobile home park investments when this happens If you bought a mobile home park at $275 per month rents at a 10% cap rate, did nothing with it except raised rents, and those rents doubled over time, here’s what would happen: if you bought and sold the park at a 10% cap rate, each lot would be worth $33,000 more than you paid for it. On a 50 space park, that’s a $1.6 million profit. For doing nothing but being in the right place at the right time. Conclusion Mobile home park rents are destined to go up substantially in the near future. Those who own parks are going to get unbelievably rich from this. And they don’t have to do anything but simply be sitting there.
package uk.offtopica.monerorpc; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; /** * Used for requests where the parameters are an array and not an object of key-value pairs. * * @param <T> Type of the element inside the array. */ public class MoneroRpcRequestParamsArray<T> extends ArrayList<T> implements MoneroRpcRequestParams { public MoneroRpcRequestParamsArray(int initialCapacity) { super(initialCapacity); } public MoneroRpcRequestParamsArray() { } public MoneroRpcRequestParamsArray(Collection<? extends T> c) { super(c); } @SafeVarargs public static <U> MoneroRpcRequestParamsArray<U> of(U... ts) { return new MoneroRpcRequestParamsArray<>(Arrays.asList(ts)); } }
#[allow(unused_imports)] use to_binary::{BinaryError, BinaryString}; fn main() { // A Demo For Working With Whitespace work_with_whitespace(); // Generates A New BinaryString From Hexadecimal let x = generate(); // Checks Whether The Input Is Binary let check_if_binary: bool = x.assert_binary(); // Assert Input Is Binary assert_eq!(check_if_binary, true); // Retrieve Sizes Of Binary Input (Bits and Bytes) let size_in_bits = x.bits().unwrap(); let size_in_bytes = x.bytes().unwrap(); // Verifies Sizes Of Binary Inputs let verify_bit_length: bool = x.assert_bit_length(size_in_bits); let verify_byte_length: bool = x.assert_byte_length(size_in_bytes); // Assert Sizes Are Correct assert_eq!(verify_bit_length, true); assert_eq!(verify_byte_length, true); } fn generate() -> BinaryString { return BinaryString::from_hex("321155ED37271DE1A9C1914A92A5DFE4").unwrap(); } fn work_with_whitespace() { // Generate From &str "Hello" let initial = BinaryString::from("Hello"); // Add Spaces Between Each Byte In The `BinaryString` And Unwraps Result For Error-Checking Using `BinaryError` let spaces = initial.add_spaces().unwrap(); // Removes All Whitespace In The `BinaryString` let removed_spaces = spaces.remove_spaces(); // Asserts The Initial Result And The One With Removed Spaces Are The Same assert_eq!(initial, removed_spaces); }
/******************************************************************************* Copyright (c) 1995_96 Microsoft Corporation Abstract: Declaration of Importation and Pickable result interfaces. *******************************************************************************/ #ifndef _RESULTS_H #define _RESULTS_H #include <dxtrans.h> #include <comconv.h> class __declspec(uuid("BCBB1F74-E384-11d0-9B99-00C04FC2F51D")) ATL_NO_VTABLE CDAPickableResult : public CComObjectRootEx<CComMultiThreadModel>, public CComCoClass<CDAPickableResult, &__uuidof(CDAPickableResult)>, public IDispatchImpl<IDAPickableResult, &IID_IDAPickableResult, &LIBID_DirectAnimation>, public IObjectSafetyImpl<CDAPickableResult>, public ISupportErrorInfoImpl<&IID_IDAPickableResult> { public: #if _DEBUG const char * GetName() { return "CDAPickableResult"; } #endif BEGIN_COM_MAP(CDAPickableResult) COM_INTERFACE_ENTRY(IDAPickableResult) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(ISupportErrorInfo) COM_INTERFACE_ENTRY_IMPL(IObjectSafety) END_COM_MAP() STDMETHOD(get_Image)(IDAImage **ppImg); STDMETHOD(get_Geometry)(IDAGeometry **ppGeo); STDMETHOD(get_PickEvent)(IDAEvent **ppPickEvent); static bool Create(CRPickableResult *res, IDAPickableResult **result); protected: CRPtr<CRPickableResult> _result; }; class __declspec(uuid("BCBB1F75-E384-11d0-9B99-00C04FC2F51D")) ATL_NO_VTABLE CDAImportationResult : public CComObjectRootEx<CComMultiThreadModel>, public CComCoClass<CDAImportationResult, &__uuidof(CDAImportationResult)>, public IDispatchImpl<IDAImportationResult, &IID_IDAImportationResult, &LIBID_DirectAnimation>, public IObjectSafetyImpl<CDAImportationResult>, public ISupportErrorInfoImpl<&IID_IDAImportationResult> { public: #if _DEBUG const char * GetName() { return "CDAImportationResult"; } #endif BEGIN_COM_MAP(CDAImportationResult) COM_INTERFACE_ENTRY(IDAImportationResult) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(ISupportErrorInfo) COM_INTERFACE_ENTRY_IMPL(IObjectSafety) END_COM_MAP() STDMETHOD(get_Image)(IDAImage **ppImg); STDMETHOD(get_Sound)(IDASound **ppSnd); STDMETHOD(get_Geometry)(IDAGeometry **ppGeo); STDMETHOD(get_Duration)(IDANumber **ppDuration); STDMETHOD(get_Progress)(IDANumber **ppProgress); STDMETHOD(get_Size)(IDANumber **ppSize); STDMETHOD(get_CompletionEvent)(IDAEvent **ppCompletionEvent); static HRESULT Create(CRImage *img, CRSound *snd, CRGeometry *geom, CRNumber *duration, CREvent *event, CRNumber *progress, CRNumber *size, IDAImportationResult **result); protected: CRPtr<CRBvr> _image; CRPtr<CRBvr> _sound; CRPtr<CRBvr> _geom; CRPtr<CRBvr> _duration; CRPtr<CRBvr> _progress; CRPtr<CRBvr> _size; CRPtr<CRBvr> _completionEvent; }; class __declspec(uuid("5E3BF06E-4B11-11d1-9BC8-00C04FC2F51D")) ATL_NO_VTABLE CDADXTransformResult : public CComObjectRootEx<CComMultiThreadModel>, public CComCoClass<CDADXTransformResult, &__uuidof(CDADXTransformResult)>, public IDispatchImpl<IDADXTransformResult, &IID_IDADXTransformResult, &LIBID_DirectAnimation>, public IObjectSafetyImpl<CDADXTransformResult>, public ISupportErrorInfoImpl<&IID_IDADXTransformResult> { public: #if _DEBUG const char * GetName() { return "CDADXTransformResult"; } #endif BEGIN_COM_MAP(CDADXTransformResult) COM_INTERFACE_ENTRY(IDADXTransformResult) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(ISupportErrorInfo) COM_INTERFACE_ENTRY_IMPL(IObjectSafety) END_COM_MAP() STDMETHOD(get_OutputBvr)(IDABehavior **ppOutputBvr); STDMETHOD(get_TheTransform)(IDispatch **ppTransform); STDMETHOD(PutBvrAsProperty)(BSTR property, IDABehavior *bvr); static HRESULT Create(IDispatch *theXf, CRDXTransformResultPtr bvr, IDADXTransformResult **ppResult); HRESULT Error() { return CRGetLastError(); } protected: CRPtr<CRDXTransformResult> _xfResult; CComPtr<IDispatch> _theTransform; }; #endif /* _RESULTS_H */
/** * Set whether or not debug mode is enabled. Debug mode logs all permission, option, and inheritance * checks made to the console. * * @param debug Whether to enable debug mode * @param filterPattern A pattern to filter which permissions are logged. Null for no filter. */ @Override public synchronized void debugMode(boolean debug, final @Nullable Pattern filterPattern) { if (debug) { if (this.notifier instanceof DebugPermissionCheckNotifier) { this.notifier = new DebugPermissionCheckNotifier(this.logger(), ((DebugPermissionCheckNotifier) this.notifier).getDelegate(), filterPattern == null ? null : perm -> filterPattern.matcher(perm).find()); } else { this.notifier = new DebugPermissionCheckNotifier(this.logger(), this.notifier, filterPattern == null ? null : perm -> filterPattern.matcher(perm).find()); } } else { if (this.notifier instanceof DebugPermissionCheckNotifier) { this.notifier = ((DebugPermissionCheckNotifier) this.notifier).getDelegate(); } } }
/** * Iterate over lines in a stream. */ public class LineIterable implements Iterable<String>, Closeable{ private final BufferedReader bufferedReader; /** * @param r any reader. Note. this class creates its own buffered reader so there is no need to create one in advance. */ public LineIterable(Reader r) { bufferedReader = new BufferedReader(r); } public static LineIterable openGzipFile(String fileName) throws IOException { return new LineIterable(new InputStreamReader(new GZIPInputStream(new FileInputStream(fileName)), Charset.forName("UTF-8"))); } @Override public Iterator<String> iterator() { return new Iterator<String>() { boolean hasMoreLines=true; String nextLine=null; @Override public boolean hasNext() { if(hasMoreLines && nextLine==null) { nextLine = readNextLine(); } return hasMoreLines && nextLine!=null; } @Override public String next() { if(!hasNext()) { throw new NoSuchElementException(); } else { String result=nextLine; nextLine=null; return result; } } private String readNextLine() { String line = null; if(hasMoreLines) { try { line = bufferedReader.readLine(); } catch (IOException e) { hasMoreLines=false; throw new IllegalStateException("could not read line", e); } if(line==null) { hasMoreLines=false; } } return line; } @Override public void remove() { throw new UnsupportedOperationException("cannot remove lines"); } }; } @Override public void close() throws IOException { bufferedReader.close(); } }
def round_py2_compat(what): d = Context( prec=len(str(long(what))), rounding=decimal.ROUND_HALF_UP ).create_decimal(str(what)) return long(d)
<reponame>marcellinkp/Simulador-Campeonato-Brasileiro<gh_stars>1-10 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.projeto.model; import java.time.DayOfWeek; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.Stack; import javafx.util.converter.LocalDateTimeStringConverter; /** * * @author Daylton */ public class Rodada { private List<Time> listaTime; private List<Jogo> listaJogos; private Stack<Time> timesDisponiveisParaJogo; public static int numero; private int numeroDaRodada; public static LocalDateTime data; private LocalDateTime dataAtual; public Rodada(List<Time> listaTime){ this.dataAtual = LocalDateTime.now(); this.listaTime = listaTime; timesDisponiveisParaJogo = new Stack(); numero++; if(numero==1){ data = dataAtual; }else{ data = data.plusDays(1); } this.numeroDaRodada = numero; for(Time t: this.listaTime){ //Adiciona na pilha os times que participarão da rodada. timesDisponiveisParaJogo.push(t); } this.listaJogos = this.getJogos(); } private Jogo getJogo(){ //Método que sorteia um jogo para a rodada. //Todos os dez jogos da rodada devem ser diferentes e o sorteio //deve considerar que na próxima rodada não poderá ter um jogo que já aconteceu //sendo que o campeonato só terá um turno. Jogo j = null; if(listaTime.size() > 0){ Collections.shuffle(timesDisponiveisParaJogo); Time time1, time2; time1 = timesDisponiveisParaJogo.pop(); time2 = timesDisponiveisParaJogo.pop(); List<Time> timesQue1Jogou = time1.getTimesComQuemJogou(); if(timesQue1Jogou.size()>0){ if(timesQue1Jogou.contains(time2)){ timesDisponiveisParaJogo.push(time2); for(Time t : timesDisponiveisParaJogo){ if(!timesQue1Jogou.contains(t)){ time2 = t; } } timesDisponiveisParaJogo.remove(time2); } } time1.addTimeJogado(time2); time2.addTimeJogado(time1); j = new Jogo(time1, time2); //System.out.println(j.getTime1() + " x " + j.getTime2()); }else{ System.out.println("Acabou!"); } return j; } private List<Jogo> getJogos(){ //Método que obtém os jogos da rodada atual. List<Jogo> jogos = new ArrayList<>(); for(int i = 0; i < 10; i++){ Jogo j = getJogo(); //Cria instância de um novo jogo. if(i<5){ j.setDataJogo(this.getDataJogo(data)); }else { if(i==5){ data = this.getDataJogo(data).plusDays(1); } j.setDataJogo(this.getDataJogo(data)); } jogos.add(j); //Adiciona jogo na lista de jogos da rodada. Time t1 = j.getTime1(); //Referencia instância do time 1. Time t2 = j.getTime2(); //Referencia instância do time 2. t1.addJogo(j); //Times desse jogo guardam referência ao jogo que realizaram. t2.addJogo(j); } data = data.plusDays(1); System.out.println("\n"); return jogos; } public List<Jogo> getJogosRodada(){ return this.listaJogos; } @Override public String toString(){ return "Rodada " + this.numeroDaRodada; } public static void jogoReiniciado(){ numero = 0; } public LocalDateTime getDataJogo(LocalDateTime dataAtual){ LocalDateTime dataDoJogo = dataAtual; int[] horas = {14, 16, 18, 22}; int[] minutos = {0,30,45}; if(dataAtual.getDayOfWeek().equals(DayOfWeek.MONDAY)){ dataDoJogo = dataAtual.plusDays(2); }else if(dataAtual.getDayOfWeek().equals(DayOfWeek.TUESDAY)){ dataDoJogo = dataAtual.plusDays(1); }else if(dataAtual.getDayOfWeek().equals(DayOfWeek.WEDNESDAY)){ dataDoJogo = dataAtual; }else if(dataAtual.getDayOfWeek().equals(DayOfWeek.THURSDAY)){ dataDoJogo = dataAtual; }else if(dataAtual.getDayOfWeek().equals(DayOfWeek.FRIDAY)){ dataDoJogo = dataAtual.plusDays(1); }else if(dataAtual.getDayOfWeek().equals(DayOfWeek.SATURDAY)){ dataDoJogo = dataAtual; }else if(dataAtual.getDayOfWeek().equals(DayOfWeek.SUNDAY)){ dataDoJogo = dataAtual; } LocalTime horaJogo = dataDoJogo.toLocalTime(); Random sortHoraMinuto = new Random(); horaJogo = horaJogo.withHour(horas[sortHoraMinuto.nextInt(4)]).withMinute(minutos[sortHoraMinuto.nextInt(3)]); dataDoJogo = dataDoJogo.with(horaJogo); return dataDoJogo; } }
/** * @author Michael Hagen */ public class AcrylInternalFrameTitlePane extends BaseInternalFrameTitlePane { public AcrylInternalFrameTitlePane(JInternalFrame f) { super(f); } protected LayoutManager createLayout() { return new BaseTitlePaneLayout(); } protected int getHorSpacing() { return 1; } protected int getVerSpacing() { return 3; } public void paintBorder(Graphics g) { if (isActive()) { g.setColor(AbstractLookAndFeel.getWindowBorderColor()); } else { g.setColor(AbstractLookAndFeel.getWindowInactiveBorderColor()); } g.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1); } public void paintText(Graphics g, int x, int y, String title) { if (isMacStyleWindowDecoration()) { x += paintIcon(g, x, y) + 5; } Color shadowColor = AbstractLookAndFeel.getWindowTitleColorDark(); if (isActive()) { shadowColor = ColorHelper.darker(shadowColor, 30); } g.setColor(shadowColor); JTattooUtilities.drawString(frame, g, title, x - 1, y - 2); JTattooUtilities.drawString(frame, g, title, x - 1, y ); JTattooUtilities.drawString(frame, g, title, x + 1, y - 2); JTattooUtilities.drawString(frame, g, title, x + 1, y); if (isActive()) { g.setColor(AbstractLookAndFeel.getWindowTitleForegroundColor()); } else { g.setColor(AbstractLookAndFeel.getWindowInactiveTitleForegroundColor()); } JTattooUtilities.drawString(frame, g, title, x, y - 1); } //-------------------------------------------------------------------------------------------- class BaseTitlePaneLayout extends TitlePaneLayout { public void addLayoutComponent(String name, Component c) { } public void removeLayoutComponent(Component c) { } public Dimension preferredLayoutSize(Container c) { return minimumLayoutSize(c); } public Dimension minimumLayoutSize(Container c) { int width = 30; if (frame.isClosable()) { width += 21; } if (frame.isMaximizable()) { width += 16 + (frame.isClosable() ? 10 : 4); } if (frame.isIconifiable()) { width += 16 + (frame.isMaximizable() ? 2 : (frame.isClosable() ? 10 : 4)); } FontMetrics fm = getFontMetrics(getFont()); String frameTitle = frame.getTitle(); int title_w = frameTitle != null ? fm.stringWidth(frameTitle) : 0; int title_length = frameTitle != null ? frameTitle.length() : 0; if (title_length > 2) { int subtitle_w = fm.stringWidth(frame.getTitle().substring(0, 2) + "..."); width += (title_w < subtitle_w) ? title_w : subtitle_w; } else { width += title_w; } int height = paletteTitleHeight; if (!isPalette) { int fontHeight = fm.getHeight() + 5; Icon icon = isMacStyleWindowDecoration() ? null : frame.getFrameIcon(); int iconHeight = 0; if (icon != null) { iconHeight = Math.min(icon.getIconHeight(), 18); } iconHeight += 5; height = Math.max(fontHeight, iconHeight); } return new Dimension(width, height); } public void layoutContainer(Container c) { if (AbstractLookAndFeel.getTheme().isMacStyleWindowDecorationOn()) { layoutMacStyle(c); } else { layoutDefault(c); } } public void layoutDefault(Container c) { boolean leftToRight = JTattooUtilities.isLeftToRight(frame); int spacing = getHorSpacing(); int w = getWidth(); int h = getHeight(); // assumes all buttons have the same dimensions these dimensions include the borders int btnHeight = h - getVerSpacing(); int btnWidth = btnHeight + 10; int x = leftToRight ? w - spacing : 0; int y = Math.max(0, ((h - btnHeight) / 2) - 1); if (frame.isClosable()) { x += leftToRight ? -btnWidth : spacing; closeButton.setBounds(x, y, btnWidth, btnHeight); if (!leftToRight) { x += btnWidth; } } if (frame.isMaximizable() && !isPalette) { x += leftToRight ? -spacing - btnWidth : spacing; maxButton.setBounds(x, y, btnWidth, btnHeight); if (!leftToRight) { x += btnWidth; } } if (frame.isIconifiable() && !isPalette) { x += leftToRight ? -spacing - btnWidth : spacing; iconButton.setBounds(x, y, btnWidth, btnHeight); if (!leftToRight) { x += btnWidth; } } buttonsWidth = leftToRight ? w - x : x; if (customTitlePanel != null) { int maxWidth = w - buttonsWidth - spacing - 20; Icon icon = frame.getFrameIcon(); if (icon != null) { maxWidth -= icon.getIconWidth(); maxWidth -= spacing; } int cpw = Math.min(maxWidth, customTitlePanel.getPreferredSize().width); int cph = h; int cpx = leftToRight ? w - buttonsWidth - cpw : buttonsWidth; int cpy = 0; customTitlePanel.setBounds(cpx, cpy, cpw, cph); buttonsWidth += customTitlePanel.getPreferredSize().width; } } private void layoutMacStyle(Container c) { int spacing = getHorSpacing(); int h = getHeight(); // assumes all buttons have the same dimensions these dimensions include the borders int btnHeight = h - getVerSpacing(); int btnWidth = btnHeight; int x = 0; int y = 0; if (frame.isClosable()) { closeButton.setBounds(x, y, btnWidth, btnHeight); x += btnWidth + spacing; } if (frame.isIconifiable() && !isPalette) { iconButton.setBounds(x, y, btnWidth, btnHeight); x += btnWidth + spacing; } if (frame.isMaximizable() && !isPalette) { maxButton.setBounds(x, y, btnWidth, btnHeight); x += btnWidth + spacing; } buttonsWidth = x; if (customTitlePanel != null) { int cpx = buttonsWidth + 5; int cpy = 0; int cpw = customTitlePanel.getPreferredSize().width; int cph = h; customTitlePanel.setBounds(cpx, cpy, cpw, cph); buttonsWidth += cpw + 5; } } } // end class BaseTitlePaneLayout }
#ifndef STRANGER_H #define STRANGER_H #include <string> using namespace std; class Stranger { private: bool payed = false; int itemNeeded = 0; int id_item = 0; string name = ""; string txt = ""; bool Is_visible; public: void set_true(); bool is_payed(); int get_num(); int get_id(); string get_stranger_name(); Stranger(string n, int count, int id, string t) { name = n; itemNeeded = count; id_item = id; txt = t; } void set_itemNeed(int a); string get_txt(); }; #endif
<reponame>cassmarcussen/video-vigilance // Copyright 2019 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 // // https://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.sps.servlets; import com.google.sps.servlets.DetectSafeSearchGcs; import com.google.cloud.vision.v1.AnnotateImageRequest; import com.google.cloud.vision.v1.AnnotateImageResponse; import com.google.cloud.vision.v1.BatchAnnotateImagesRequest; import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; import com.google.cloud.vision.v1.ImageAnnotatorClient; import com.google.cloud.vision.v1.Likelihood; import com.google.cloud.vision.v1.SafeSearchAnnotation; import com.google.cloud.vision.v1.SafeSearchAnnotation.Builder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.mockito.Mockito.*; import static org.mockito.Matchers.*; @RunWith(JUnit4.class) public final class DetectSafeSearchGcsTest { private MockDetectSafeSearchGcs mockDetectSafeSearch; private HashMap<String, String> mockSafeSearchResults; // List of results for all videos requested (will only contain 1) private List<AnnotateImageResponse> mockedBatchAnnotateImagesResponseList; // Mock DetectSafeSearchGcs so we can stub the detectSafeSearchGcs method for testing class MockDetectSafeSearchGcs extends DetectSafeSearchGcs { @Override public List<AnnotateImageResponse> batchAnnotateImagesResponseList(List<AnnotateImageRequest> requests) { return new ArrayList<AnnotateImageResponse>(); } } @Before public void setup() throws Exception { mockDetectSafeSearch = mock(MockDetectSafeSearchGcs.class); mockedBatchAnnotateImagesResponseList = new ArrayList<AnnotateImageResponse>(); // Specify which functions of mockDetectShots to stub when(mockDetectSafeSearch.batchAnnotateImagesResponseList(any(List.class))).thenReturn(mockedBatchAnnotateImagesResponseList); when(mockDetectSafeSearch.detectSafeSearchGcs(any(String.class))).thenCallRealMethod(); } @Test public void detectSafeSearchGcs_emptyResponse() throws Exception { // The error below comes from the empty AnnotateImageResponses being built mockSafeSearchResults = new HashMap<String, String>(); mockSafeSearchResults.put("adult", "UNKNOWN"); mockSafeSearchResults.put("medical", "UNKNOWN"); mockSafeSearchResults.put("spoofed", "UNKNOWN"); mockSafeSearchResults.put("violence", "UNKNOWN"); mockSafeSearchResults.put("racy", "UNKNOWN"); AnnotateImageResponse responseUnfilledSafeSearch = AnnotateImageResponse.newBuilder().build(); mockedBatchAnnotateImagesResponseList.add(responseUnfilledSafeSearch); HashMap<String, String> safeSearchResults = mockDetectSafeSearch.detectSafeSearchGcs("gs://keyframe-images-to-effect/AAANsUnmvLkSJZEVnYAh6DNG6O13zzRusbFKKRTwjdDj81ikKqNbo7wwYIvwYQUJd1bnQCW0XdNRjf82G21nk7yBGfqObtMJgw.R2GN-ZINyUODcEv1"); Assert.assertEquals(mockSafeSearchResults, safeSearchResults); } @Test public void detectSafeSearchGcs_workingCase() throws Exception { mockSafeSearchResults = new HashMap<String, String>(); mockSafeSearchResults.put("adult", "UNLIKELY"); mockSafeSearchResults.put("medical", "LIKELY"); mockSafeSearchResults.put("spoofed", "VERY_UNLIKELY"); mockSafeSearchResults.put("violence", "VERY_LIKELY"); mockSafeSearchResults.put("racy", "POSSIBLE"); SafeSearchAnnotation safeSearchAnnotation = SafeSearchAnnotation.newBuilder() .setAdult(Likelihood.UNLIKELY) .setMedical(Likelihood.LIKELY) .setSpoof(Likelihood.VERY_UNLIKELY) .setViolence(Likelihood.VERY_LIKELY) .setRacy(Likelihood.POSSIBLE) .build(); AnnotateImageResponse responseSafeSearch = AnnotateImageResponse.newBuilder() .setSafeSearchAnnotation(safeSearchAnnotation) .build(); mockedBatchAnnotateImagesResponseList.add(responseSafeSearch); HashMap<String, String> safeSearchResults = mockDetectSafeSearch.detectSafeSearchGcs("gs://keyframe-images-to-<KEY>"); Assert.assertEquals(mockSafeSearchResults, safeSearchResults); } }
# include<bits/stdc++.h> using namespace std; # define l long long # define db double # define rep(i,a,b) for(l i=a;i<b;i++) # define vi vector<l> # define pb push_back # define mp make_pair # define ss second # define ff first # define pii pair<l,l> # define trvi(v,it) for(vi::iterator it=v.begin();it!=v.end();++it) # define read(a) freopen(a,"r",stdin) # define write(a) freopen(a,"w",stdout) # define io ios::sync_with_stdio(false) #define vertex first.second #define dist first.first #define parent second const l MOD=1e9+7; const l N=3e5+5; const l INF=1e12; void solve() { l n,k; cin>>n>>k; string sA,sB; cin>>sA; cin>>sB; vi a(26,0), b(26,0); rep(i,0,n) { a[sA[i]-'a']++; } rep(i,0,n) { b[sB[i]-'a']++; } l aCnt=0,bCnt=0; rep(i,0,26) { l val=min(a[i],b[i]); a[i]-=val; b[i]-=val; // cout<<"i "<<a[i]<<" "<<b[i]<<" "<<val<<"\n"; if(a[i]%k!=0||b[i]%k!=0) { cout<<"No\n"; return; } aCnt+=(a[i]/k); bCnt+=(b[i]/k); if(aCnt<bCnt) { cout<<"No\n"; return; } } cout<<"Yes\n"; return; } int main(){ io; int t; cin >> t; rep(i,0,t) { solve(); } return 0; }
def gait_features_from_vertical_acceleration( timestamps, a_vert, contact_time_range=[50, 200], step_time_range=[200, 1000] ): log.debug( "[ Extracting gait features from the vertical acceleration of a motion sensor" ) from scipy.signal import find_peaks fc_peaks, _ = find_peaks(a_vert, prominence=1.5) ic_peaks, _ = find_peaks(-a_vert, prominence=1.5) log.debug("Finding initial and final contact peaks") ic_times_ns = timestamps.iloc[ic_peaks] fc_times_ns = timestamps.iloc[fc_peaks] log.debug("Found {} IC and {} FC peaks".format(len(ic_times_ns), len(fc_times_ns))) ic_times = pd.to_datetime(ic_times_ns) fc_times = pd.to_datetime(fc_times_ns) min_contact_time = pd.Timedelta(contact_time_range[0], "ms") max_contact_time = pd.Timedelta(contact_time_range[1], "ms") min_step_time = pd.Timedelta(step_time_range[0], "ms") max_step_time = pd.Timedelta(step_time_range[1], "ms") ds_ic = pd.DataFrame( { "t": ic_times, "t_contact_min": ic_times + min_contact_time, "t_step_min": ic_times + min_step_time, "t_ic": ic_times_ns, "impact": -a_vert.iloc[ic_peaks], } ).reset_index(drop=True) ds_fc = pd.DataFrame({"t": fc_times, "t_fc": fc_times_ns}).reset_index(drop=True) log.debug("Collecting contact pairs for feature extraction") df = pd.merge_asof( ds_ic, ds_fc, left_on="t_contact_min", right_on="t", direction="forward", suffixes=[None, "_fcm"], tolerance=max_contact_time - min_contact_time, ) df["contact_time"] = (df["t_fc"] - df["t_ic"]) / 1e6 df.drop(["t_fc", "t_fcm"], axis=1, inplace=True) df = pd.merge_asof( df, ds_ic[["t", "t_ic"]], left_on="t_step_min", right_on="t", suffixes=[None, "_opp"], direction="forward", tolerance=max_step_time - min_step_time, ) df["step_duration"] = (df["t_ic_opp"] - df["t_ic"]) / 1e6 df["cadence"] = 60 / df["step_duration"] df = df[ df["t"].shift(-1) - df["t"] > min_step_time ] df = df[ df["step_duration"] > df["contact_time"] ] df["stride_duration"] = pd.to_numeric(df["t"].shift(-2) - df["t"]) / 1e6 df = df[df["stride_duration"] > 0] df = df[ df["t"].shift(-2) - df["t"] < 2 * max_step_time ] df["flight_ratio"] = (df["step_duration"] - df["contact_time"]) / df[ "step_duration" ] df.drop( ["t_contact_min", "t_step_min", "t_ic", "t_opp", "t_ic_opp"], axis=1, inplace=True, ) df.reset_index(drop=True, inplace=True) log.debug("] Done, returning {} gait cycles".format(len(df))) return df, ic_times, fc_times
Diverse multi‐organ histopathologic changes in a failed Fontan patient We report multi‐organ histopathological changes in a patient with protein‐losing enteropathy (PLE) over 12 years after Fontan operation. A 14‐year‐old boy with right isomerism heart and single ventricle had undergone Fontan procedure at 19 months of age, and PLE was diagnosed at 28 months. He had several episodes of intestinal bleeding and pre‐renal failure with elevated creatine, and eventually died of pneumonia. The intrapulmonary small arteries showed medial and intimal thickening resembling pulmonary hypertension. No major ulcerative lesions were found in the small or large intestines. Dilated lymph ducts, one of the characteristic features of PLE, were not seen in mucosal and submucosal areas. Liver cirrhosis was obvious despite little increase in liver enzymes. Histological changes in bilateral kidneys were subtle despite repeated episodes of renal failure. Thus, there may be significant discrepancies between clinical manifestations and multi‐organ histological changes in failed Fontan patients.
Ranking The Lord Of The Rings & Hobbit Movies by Deffinition Two Trilogies To Rule Them All Peter Jackson completed a phenomenal task when he put the Lord Of The Rings and The Hobbit to film. Grossing billions at the box office and receiving a mass of critical acclaim, it seems like everyone LOVES journeying side by side with the Shire Hobbits. I’ve recently just completed a binge watching of all the films in the series and whilst it took a while (95 days to be exact because they were all the extended versions) I found myself to be falling in love with the series all over again. Whilst they are still all fresh in my mind I thought I’d rank them from best to worst. Let me know if you agree below, I’d love to hear your thoughts on the films! 6. The Hobbit: The Battle of the Five Armies Bringing together every element set up in the previous two films, The Hobbit: The Battle of the Five Armies ends the prequel trilogy on a high note. However, due to some padding in the mid sections it feels slightly lacklustre in comparison it’s predecessors. Thorin has felt completely unlikeable in the prior two movies and this one doesn’t really reverse that in any shape or form. However, we are treated to a breathtaking battle between the five armies with Billy Connely’s ‘Let’s Get The Bastards!’ makes me laugh everythime I see it. But it misses elements of the drama that make the other films so gripping. 5. The Hobbit: The Desolation of Smaug The Hobbit The Desolation Of Smaug drags it’s feet slightly in the beginning. Featuring the group running from the Orcs of the previous film it feels slightly by the numbers. However, upon the introduction of Legolas, the movie really picks up. Whilst the character was never in the source material, he is still woven well enough into the plot here that it isn’t too neck jerking. Featuring an absolutely outstanding performance by Benedict Cumberbatch as Smaug, the films ends on a devastating cliff hanger but just misses the mark from beating it’s former. 4. The Hobbit: An Unexpected Journey Setting off the adventure in style, An Unexpected Journey reintroduces Gandalf, features several cameos from the original cast and provides one of the best arcs for Bilbo. Starting off as an almost agrophobe, he really blossoms in this opening and feels like a completely different character by the end of it. It’s a joy to watch him grow and his encounter with the Infamous Trolls and Gollum allow the movie to rise above it’s sequels. 3. The Lord Of The Rings: The Two Towers Having one of the best openings to a movie ever (Gandalf battling the Balrog), The Two Towers packs a HELL of a punch. Helms Deep, The Battle Of The Ents and the introduction of Gollum all provide impact within the film, however, the mid section seems to plod along (I’m looking at you Merry and Pippin). Due to this it just misses out on beating the other two films in the trilogy but there is still a wealth of fun to be had here. 2. The Lord Of The Rings: The Return Of The King Ending the original trilogy, The Return of The King has one of the best battle scenes ever put to film. It’s dark, twisted and filled with despair. We see our characters grow into the legends they were destined to become and the scale of everything is unmatched in most motion pictures. Possessing edge of your seat action the drama also comes from the character’s themselves. We see betrayal and hope weaved perfectly throughout the plot and it capitalises on a lot of the ideas set up in the previous two films. Taking home Oscar after Oscar it is a well deserved second place on my list. 1.The Lord Of The Rings: The Fellowship Of The Ring The Fellowship Of The Ring changed the way we looked at fantasy films. Epic in length and ideas the movie managed to accomplish several things that no film before had accomplished. Introducing the world to Hobbits the movie broke ground in several ways. Who could forget the Cave Troll fight in the mines of Moiria, Sean Bean’s epic final battle or the first time Frodo slipped on the ring, being transported to a world of shadow. Featuring Ring Wraiths, Elves and one of the best opening exposition scenes ever, I can only place this as the best film from the series. So what did you think of the list? Do you agree? Comment below and let me know and click here for more movie reviews, games and comics.
def _filter_hit(self, hit): return (hit.relative_score >= float(self.settings.relative_score) and hit.query_identity >= float(self.settings.query_identity) and hit.query_coverage >= float(self.settings.query_coverage) and hit.base_score >= float(self.settings.base_score))
<reponame>lejonmcgowan/JohnnyTracer2<gh_stars>0 // // Created by lejonmcgowan on 1/3/17. // #include "IMedium.h"
from .models import ImagerProfile from django.forms import ModelForm class ProfileEditForm(ModelForm): """Instantiate user profile edit forms.""" class Meta: model = ImagerProfile fields = [ 'bio', 'phone', 'location', 'website', 'fee', 'camera', 'services', 'photostyles'] def __init__(self, *args, **kwargs):: username = kwargs.pop('username') super().__init__(*args, **kwargs) user = ImagerProfile.objects.get(user__username=username) self.fields['bio'].initial = user.bio self.fields['phone'].initial = user.phone self.fields['location'].initial = user.location self.fields['website'].initial = user.bio self.fields['fee'].initial = user.phone self.fields['camera'].initial = user.phone self.fields['services'].initial = user.bio self.fields['photostyles'].initial = user.phone