repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
leongold/ovirt-engine
backend/manager/modules/restapi/jaxrs/src/main/java/org/ovirt/engine/api/restapi/resource/BackendStorageDomainDiskSnapshotResource.java
package org.ovirt.engine.api.restapi.resource; import javax.ws.rs.core.Response; import org.ovirt.engine.api.model.DiskSnapshot; import org.ovirt.engine.api.model.StorageDomain; import org.ovirt.engine.api.resource.DiskSnapshotResource; import org.ovirt.engine.core.common.action.RemoveDiskSnapshotsParameters; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.businessentities.storage.Disk; import org.ovirt.engine.core.common.queries.IdQueryParameters; import org.ovirt.engine.core.common.queries.VdcQueryType; public class BackendStorageDomainDiskSnapshotResource extends AbstractBackendActionableResource<DiskSnapshot, Disk> implements DiskSnapshotResource { private final String storageDomainId; protected BackendStorageDomainDiskSnapshotResource(String id, BackendStorageDomainDiskSnapshotsResource parent) { super(id, DiskSnapshot.class, Disk.class); this.storageDomainId = parent.getStorageDomainId().toString(); } public String getStorageDomainId() { return storageDomainId; } @Override public DiskSnapshot get() { DiskSnapshot diskSnapshot = performGet(VdcQueryType.GetDiskSnapshotByImageId, new IdQueryParameters(guid)); // this code generates back-link to the corresponding SD diskSnapshot.setStorageDomain(new StorageDomain()); diskSnapshot.getStorageDomain().setId(this.storageDomainId); return diskSnapshot; } @Override public Response remove() { get(); return performAction(VdcActionType.RemoveDiskSnapshots, new RemoveDiskSnapshotsParameters(guid)); } }
cloudradar-monitoring/frontman
ssl.go
<gh_stars>10-100 package frontman import ( "context" "crypto/tls" "crypto/x509" "fmt" "math" "net" "strings" "time" "github.com/sirupsen/logrus" ) const timeoutPortLookup = time.Second * 3 func certName(cert *x509.Certificate) string { return fmt.Sprintf("'%s' issued by %s", cert.Subject.CommonName, cert.Issuer.CommonName) } func (fm *Frontman) runSSLCheck(hostname string, port int, service string) (m MeasurementsMap, err error) { service = strings.ToLower(service) if net.ParseIP(hostname) != nil { hostname = "" } if port == 0 { ctx, cancel := context.WithTimeout(context.Background(), timeoutPortLookup) defer cancel() if p, exists := defaultPortByService[service]; exists { port = p } else if p, lerr := net.DefaultResolver.LookupPort(ctx, "tcp", service); p > 0 { port = p } else if lerr != nil { err = fmt.Errorf("failed to auto-determine port for '%s': %s", service, lerr.Error()) return } } prefix := fmt.Sprintf("net.tcp.ssl.%d.", port) m = MeasurementsMap{ prefix + "success": 0, } addr := fmt.Sprintf("%s:%d", hostname, port) dialer := net.Dialer{Timeout: secToDuration(fm.Config.NetTCPTimeout)} connection, err := tls.DialWithDialer( &dialer, "tcp", addr, &tls.Config{ServerName: hostname}, ) if err != nil { logrus.Debugf("serviceCheck: SSL check %s for '%s' failed: %s", addr, hostname, err.Error()) if strings.HasPrefix(err.Error(), "tls:") { err = fmt.Errorf("service doesn't support SSL") } else { err = fmt.Errorf(strings.TrimPrefix(err.Error(), "x509: ")) } return } defer connection.Close() remainingValidity, firstCertToExpire := findCertRemainingValidity(connection.ConnectionState().VerifiedChains) m[prefix+"expiryDaysRemaining"] = remainingValidity if remainingValidity <= float64(fm.Config.SSLCertExpiryThreshold) { err = fmt.Errorf("certificate will expire soon: %s", certName(firstCertToExpire)) return } m[prefix+"success"] = 1 return } func findCertRemainingValidity(certChains [][]*x509.Certificate) (float64, *x509.Certificate) { var remainingValidity float64 var firstToExpire *x509.Certificate // find chain with max remaining validity for _, chain := range certChains { chainRemainingValidity, c := findChainRemainingValidity(chain) if chainRemainingValidity > remainingValidity { remainingValidity = chainRemainingValidity firstToExpire = c } } return remainingValidity, firstToExpire } func findChainRemainingValidity(chain []*x509.Certificate) (float64, *x509.Certificate) { var min = math.MaxFloat64 var firstToExpire *x509.Certificate // find cert that will expire first for _, cert := range chain { remainingValidity := time.Until(cert.NotAfter).Hours() / 24 if remainingValidity < min { min = remainingValidity firstToExpire = cert } } return min, firstToExpire }
ride-austin/android
app/src/rider/java/com/rideaustin/ui/splitfare/FareSplitItemViewModel.java
package com.rideaustin.ui.splitfare; import android.databinding.ObservableField; import android.graphics.drawable.Drawable; import com.rideaustin.R; import com.rideaustin.api.model.faresplit.FareSplitResponse; import com.rideaustin.utils.RxImageLoader; import rx.Subscription; import rx.subscriptions.Subscriptions; /** * Created on 18/01/2018 * * @author sdelaysam */ public class FareSplitItemViewModel { public final ObservableField<Drawable> avatar = new ObservableField<>(); public final ObservableField<String> name = new ObservableField<>(); private final FareSplitResponse response; private Subscription subscription = Subscriptions.empty(); FareSplitItemViewModel(FareSplitResponse response) { this.response = response; name.set(response.getRiderFullName()); subscription = RxImageLoader.execute(new RxImageLoader.Request(response.getRiderPhoto()) .target(avatar) .progress(R.drawable.rotating_circle) .error(R.drawable.ic_user_icon) .circular(true, 90)); } FareSplitResponse.SplitFareState getStatus() { return response.getStatus(); } long getId() { return response.getId(); } public void destroy() { subscription.unsubscribe(); } }
djgonza/Programacion
UT7/Eclipse/Juego2D/src/mapa/frame/sprite/Sprite.java
<filename>UT7/Eclipse/Juego2D/src/mapa/frame/sprite/Sprite.java package mapa.frame.sprite; import java.awt.Color; import java.util.ArrayList; public class Sprite { private ArrayList<Color[]> pixeles; private int animacion; private int tiempoAnimacion; public Sprite(int[] pixeles) { this.pixeles = new ArrayList<>(); addPixeles(pixeles); this.animacion = 0; this.tiempoAnimacion = 0; } public void addPixeles(int[] pixeles) { int ladoSprite = (int) Math.sqrt(pixeles.length); Color[] arrayColores = new Color[ladoSprite * ladoSprite]; for (int y = 0; y < ladoSprite; y++) { for (int x = 0; x < ladoSprite; x++) { int pixel = pixeles[x + y * ladoSprite]; int alpha = (pixel >> 24) & 0xff; int red = (pixel >> 16) & 0xff; int green = (pixel >> 8) & 0xff; int blue = (pixel >> 0) & 0xff; Color color = new Color(red, green, blue, alpha); arrayColores[x + y * ladoSprite] = color; } } this.pixeles.add(arrayColores); } public Color[] getPixeles() { return pixeles.get(animacion); } public void addAnimacion() { } }
stasinek/BHAPI
src/kits/shared/private/HashMap.h
<reponame>stasinek/BHAPI // HashMap.h // // Copyright (c) 2004-2007, <NAME> (<EMAIL>) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // Except as contained in this notice, the name of a copyright holder shall // not be used in advertising or otherwise to promote the sale, use or other // dealings in this Software without prior written authorization of the // copyright holder. #ifndef HASH_MAP_H #define HASH_MAP_H #include <Locker.h> #include <AutoLocker.h> #include <OpenHashTable.h> namespace BPrivate { // HashMapElement template<typename Key, typename Value> class HashMapElement : public OpenHashElement { private: typedef HashMapElement<Key, Value> Element; public: HashMapElement() : OpenHashElement(), fKey(), fValue() { fNext = -1; } inline uint32 Hash() const { return fKey.GetHashCode(); } inline bool operator==(const OpenHashElement &_element) const { const Element &element = static_cast<const Element&>(_element); return (fKey == element.fKey); } inline void Adopt(Element &element) { fKey = element.fKey; fValue = element.fValue; } Key fKey; Value fValue; }; // HashMap template<typename Key, typename Value> class HashMap { public: class Entry { public: Entry() {} Entry(const Key& key, Value value) : key(key), value(value) {} Key key; Value value; }; class Iterator { private: typedef HashMapElement<Key, Value> Element; public: Iterator(const Iterator& other) : fMap(other.fMap), fIndex(other.fIndex), fElement(other.fElement), fLastElement(other.fElement) { } bool HasNext() const { return fElement; } Entry Next() { if (!fElement) return Entry(); Entry result(fElement->fKey, fElement->fValue); _FindNext(); return result; } Value* NextValue() { if (fElement == NULL) return NULL; Value* value = &fElement->fValue; _FindNext(); return value; } Entry Remove() { if (!fLastElement) return Entry(); Entry result(fLastElement->fKey, fLastElement->fValue); fMap->fTable.Remove(fLastElement, true); fLastElement = NULL; return result; } Iterator& operator=(const Iterator& other) { fMap = other.fMap; fIndex = other.fIndex; fElement = other.fElement; fLastElement = other.fLastElement; return *this; } private: Iterator(const HashMap<Key, Value>* map) : fMap(const_cast<HashMap<Key, Value>*>(map)), fIndex(0), fElement(NULL), fLastElement(NULL) { // find first _FindNext(); } void _FindNext() { fLastElement = fElement; if (fElement && fElement->fNext >= 0) { fElement = fMap->fTable.ElementAt(fElement->fNext); return; } fElement = NULL; int32 arraySize = fMap->fTable.ArraySize(); for (; !fElement && fIndex < arraySize; fIndex++) fElement = fMap->fTable.FindFirst(fIndex); } private: friend class HashMap<Key, Value>; HashMap<Key, Value>* fMap; int32 fIndex; Element* fElement; Element* fLastElement; }; HashMap(); ~HashMap(); status_t InitCheck() const; status_t Put(const Key& key, Value value); Value Remove(const Key& key); void Clear(); Value Get(const Key& key) const; bool Get(const Key& key, Value*& _value) const; bool ContainsKey(const Key& key) const; int32 Size() const; Iterator GetIterator() const; protected: typedef HashMapElement<Key, Value> Element; friend class Iterator; private: Element *_FindElement(const Key& key) const; protected: OpenHashElementArray<Element> fElementArray; OpenHashTable<Element, OpenHashElementArray<Element> > fTable; }; // SynchronizedHashMap template<typename Key, typename Value> class SynchronizedHashMap : public BLocker { public: typedef struct HashMap<Key, Value>::Entry Entry; typedef struct HashMap<Key, Value>::Iterator Iterator; SynchronizedHashMap() : BLocker("synchronized hash map") {} ~SynchronizedHashMap() { Lock(); } status_t InitCheck() const { return fMap.InitCheck(); } status_t Put(const Key& key, Value value) { MapLocker locker(this); if (!locker.IsLocked()) return B_ERROR; return fMap.Put(key, value); } Value Remove(const Key& key) { MapLocker locker(this); if (!locker.IsLocked()) return Value(); return fMap.Remove(key); } void Clear() { MapLocker locker(this); fMap.Clear(); } Value Get(const Key& key) const { const BLocker* lock = this; MapLocker locker(const_cast<BLocker*>(lock)); if (!locker.IsLocked()) return Value(); return fMap.Get(key); } bool ContainsKey(const Key& key) const { const BLocker* lock = this; MapLocker locker(const_cast<BLocker*>(lock)); if (!locker.IsLocked()) return false; return fMap.ContainsKey(key); } int32 Size() const { const BLocker* lock = this; MapLocker locker(const_cast<BLocker*>(lock)); return fMap.Size(); } Iterator GetIterator() { return fMap.GetIterator(); } // for debugging only const HashMap<Key, Value>& GetUnsynchronizedMap() const { return fMap; } HashMap<Key, Value>& GetUnsynchronizedMap() { return fMap; } protected: typedef AutoLocker<BLocker> MapLocker; HashMap<Key, Value> fMap; }; // HashKey32 template<typename Value> struct HashKey32 { HashKey32() {} HashKey32(const Value& value) : value(value) {} uint32 GetHashCode() const { return (uint32)value; } HashKey32<Value> operator=(const HashKey32<Value>& other) { value = other.value; return *this; } bool operator==(const HashKey32<Value>& other) const { return (value == other.value); } bool operator!=(const HashKey32<Value>& other) const { return (value != other.value); } Value value; }; // HashKey64 template<typename Value> struct HashKey64 { HashKey64() {} HashKey64(const Value& value) : value(value) {} uint32 GetHashCode() const { uint64 v = (uint64)value; return (uint32)(v >> 32) ^ (uint32)v; } HashKey64<Value> operator=(const HashKey64<Value>& other) { value = other.value; return *this; } bool operator==(const HashKey64<Value>& other) const { return (value == other.value); } bool operator!=(const HashKey64<Value>& other) const { return (value != other.value); } Value value; }; // HashMap // constructor template<typename Key, typename Value> HashMap<Key, Value>::HashMap() : fElementArray(1000), fTable(1000, &fElementArray) { } // destructor template<typename Key, typename Value> HashMap<Key, Value>::~HashMap() { } // InitCheck template<typename Key, typename Value> status_t HashMap<Key, Value>::InitCheck() const { return (fTable.InitCheck() && fElementArray.InitCheck() ? B_OK : B_NO_MEMORY); } // Put template<typename Key, typename Value> status_t HashMap<Key, Value>::Put(const Key& key, Value value) { Element* element = _FindElement(key); if (element) { // already contains the key: just set the new value element->fValue = value; return B_OK; } // does not contain the key yet: add an element element = fTable.Add(key.GetHashCode()); if (!element) return B_NO_MEMORY; element->fKey = key; element->fValue = value; return B_OK; } // Remove template<typename Key, typename Value> Value HashMap<Key, Value>::Remove(const Key& key) { Value value = Value(); if (Element* element = _FindElement(key)) { value = element->fValue; fTable.Remove(element); } return value; } // Clear template<typename Key, typename Value> void HashMap<Key, Value>::Clear() { fTable.RemoveAll(); } // Get template<typename Key, typename Value> Value HashMap<Key, Value>::Get(const Key& key) const { if (Element* element = _FindElement(key)) return element->fValue; return Value(); } // Get template<typename Key, typename Value> bool HashMap<Key, Value>::Get(const Key& key, Value*& _value) const { if (Element* element = _FindElement(key)) { _value = &element->fValue; return true; } return false; } // ContainsKey template<typename Key, typename Value> bool HashMap<Key, Value>::ContainsKey(const Key& key) const { return _FindElement(key); } // Size template<typename Key, typename Value> int32 HashMap<Key, Value>::Size() const { return fTable.CountElements(); } // GetIterator template<typename Key, typename Value> struct HashMap<Key, Value>::Iterator HashMap<Key, Value>::GetIterator() const { return Iterator(this); } // _FindElement template<typename Key, typename Value> typename HashMap<Key, Value>::Element * HashMap<Key, Value>::_FindElement(const Key& key) const { Element* element = fTable.FindFirst(key.GetHashCode()); while (element && element->fKey != key) { if (element->fNext >= 0) element = fTable.ElementAt(element->fNext); else element = NULL; } return element; } } // namespace BPrivate using BPrivate::HashMap; using BPrivate::HashKey32; using BPrivate::HashKey64; using BPrivate::SynchronizedHashMap; #endif // HASH_MAP_H
Bumblecat/Bumblecore
src/main/java/dev/bumblecat/bumblecore/common/windows/IWindowProvider.java
<reponame>Bumblecat/Bumblecore package dev.bumblecat.bumblecore.common.windows; import net.minecraft.network.chat.Component; import net.minecraft.world.MenuProvider; import net.minecraft.world.entity.player.Inventory; import net.minecraft.world.entity.player.Player; import net.minecraft.world.inventory.AbstractContainerMenu; import org.jetbrains.annotations.Nullable; public interface IWindowProvider extends MenuProvider { /** * @param windowId * @param inventory * @param player * * @return */ ICommonWindow getWindow(int windowId, Inventory inventory, Player player); /** * @return */ @Override Component getDisplayName(); /** * @param windowId * @param inventory * @param player * * @return */ @Nullable @Override default AbstractContainerMenu createMenu(int windowId, Inventory inventory, Player player) { /** * re-route to getWindow(a, b, c) */ return (CommonWindow) getWindow(windowId, inventory, player); } }
ParspooyeshFanavar/pyibsng
ibsng/handler/mc/dialer_delete_message.py
<reponame>ParspooyeshFanavar/pyibsng """Message Center info API method.""" from ibsng.handler.handler import Handler class dialerDeleteMessage(Handler): """Message Center info method class.""" def setup(self, message_id): """Setup required parameters. :param int message_id: :return: void :rtype: void """ self.message_id = message_id
sebastianolmos/final-reality
src/test/java/com/github/cc3002/finalreality/controller/WinConditionsTest.java
package com.github.cc3002.finalreality.controller; import com.github.cc3002.finalreality.gui.scenes.GameOverScene; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Scene; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * Tests to check if the methods for win/lose works properly * * @author <NAME> * @see GameController */ public class WinConditionsTest { private GameController controller; /** * Create the controller and add some characters */ @BeforeEach public void setUp() { controller = new GameController(3,3,1); controller.addWhiteMageToParty("whiteMage", 150, 50); controller.addEngineerToParty("engineer", 120, 40); controller.addKnightToParty("Knight", 300, 100); controller.addEnemyToEnemies("Enemy1", 150, 40, 50, 20); controller.addEnemyToEnemies("Enemy2", 170, 40, 50, 20); controller.addEnemyToEnemies("Enemy3", 140, 40, 50, 20); } /** * Test that the defeat/lose methods work properly */ @Test public void CheckLoseTest() { assertEquals(controller.getRemainingPartyCharacters(), 3); controller.updatePartyLeft(); assertEquals(controller.getRemainingPartyCharacters(), 2); assertFalse(controller.checkWin()); assertFalse(controller.checkDefeat()); controller.updatePartyLeft(); assertEquals(controller.getRemainingPartyCharacters(), 1); assertFalse(controller.checkWin()); assertFalse(controller.checkDefeat()); controller.updatePartyLeft(); assertEquals(controller.getRemainingPartyCharacters(), 0); assertFalse(controller.checkWin()); assertTrue(controller.checkDefeat()); } /** * Test that the victory/win methods work properly */ @Test public void CheckWinTest() { assertEquals(controller.getRemainingEnemies(), 3); controller.updateEnemiesLeft(); assertEquals(controller.getRemainingEnemies(), 2); assertFalse(controller.checkWin()); assertFalse(controller.checkDefeat()); controller.updateEnemiesLeft(); assertEquals(controller.getRemainingEnemies(), 1); assertFalse(controller.checkWin()); assertFalse(controller.checkDefeat()); controller.updateEnemiesLeft(); assertEquals(controller.getRemainingEnemies(), 0); assertTrue(controller.checkWin()); assertFalse(controller.checkDefeat()); } }
Purva-Chaudhari/cmssw
Configuration/Generator/python/TauToMuMuMu_14TeV_TuneCP5_cfi.py
<reponame>Purva-Chaudhari/cmssw<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms from Configuration.Generator.Pythia8CommonSettings_cfi import * from Configuration.Generator.MCTunes2017.PythiaCP5Settings_cfi import * generator = cms.EDFilter("Pythia8ConcurrentGeneratorFilter", pythiaHepMCVerbosity = cms.untracked.bool(False), maxEventsToPrint = cms.untracked.int32(0), pythiaPylistVerbosity = cms.untracked.int32(0), filterEfficiency = cms.untracked.double(1.38e-3), crossSection = cms.untracked.double(540000000.), comEnergy = cms.double(14000.0), PythiaParameters = cms.PSet( pythia8CommonSettingsBlock, pythia8CP5SettingsBlock, processParameters = cms.vstring( 'SoftQCD:inelastic = on', '431:onMode = off', '431:onIfAny = 15', '15:addChannel = on .01 0 13 13 -13', '15:onMode = off', '15:onIfMatch = 13 13 13', ), parameterSets = cms.vstring('pythia8CommonSettings', 'pythia8CP5Settings', 'processParameters', ) ) ) configurationMetadata = cms.untracked.PSet( version = cms.untracked.string('$Revision: 1.0 $'), name = cms.untracked.string('$Source: /Configuration/Generator/python/Upsilon1SToMuMu_PhaseII_cfi.py $'), annotation = cms.untracked.string('PhaseII: Pythia8 generation of tau+- -> mu+-mu+mu-, 14TeV, Tune CP5') ) DsFilter = cms.EDFilter("PythiaFilter", ParticleID = cms.untracked.int32(431) #D_s ) MuFilter = cms.EDFilter("MCParticlePairFilter", MinPt = cms.untracked.vdouble(2.5, 2.5), MaxEta = cms.untracked.vdouble(2.9, 2.9), MinEta = cms.untracked.vdouble(-2.9, -2.9), ParticleID1 = cms.untracked.vint32(13), ParticleID2 = cms.untracked.vint32(13) ) ProductionFilterSequence = cms.Sequence(generator * DsFilter * MuFilter)
diguage/deep-in-design-patterns
src/main/java/com/diguage/didp/singleton/CorrectSerializableLazySingleton.java
package com.diguage.didp.singleton; import java.io.Serializable; /** * 可以序列化的懒汉式单例类 * * @author D瓜哥, https://www.diguage.com/ * @since 2014-5-26. */ public class CorrectSerializableLazySingleton implements Serializable { private static volatile CorrectSerializableLazySingleton instance = null; private CorrectSerializableLazySingleton() {} public static CorrectSerializableLazySingleton getInstance() { if (null == instance) { synchronized (CorrectSerializableLazySingleton.class) { if (null == instance) { instance = new CorrectSerializableLazySingleton(); } } } return instance; } private Object readResolve() { return instance; } }
vadim-isakov/fullstack-task-manager
frontend/app/app/containers/Private/containers/LoadTask/index.js
import { createSelector } from 'reselect'; import fetcher from 'fetcher'; // Key const STATE_KEY = 'LoadTask'; // Actions function loadTask(taskId) { return fetcher.fetch(STATE_KEY, taskId); } function clearTask() { return fetcher.clear(STATE_KEY); } const actions = { loadTask, clearTask }; // Selectors const makeSelectors = fetcher.createMakeSelectors(STATE_KEY); const { makeSelectErrorMsg } = makeSelectors; const { makeSelectLoading } = makeSelectors; const makeSelectTask = makeSelectors.makeSelectResponseData; const makeSelectTaskId = () => createSelector( makeSelectTask(), task => (task ? task.id : false), ); const selectors = { makeSelectTask, makeSelectTaskId, makeSelectErrorMsg, makeSelectLoading, }; // Reducer and saga injector function useInjectReducerSaga() { const REQUEST_URL = `/api/tasks/`; const METHOD = 'GET'; fetcher.inject(STATE_KEY, REQUEST_URL, METHOD); } export { useInjectReducerSaga, actions, selectors };
Andreas237/AndroidPolicyAutomation
ExtractedJars/PACT_com.pactforcure.app/javafiles/android/support/design/internal/NavigationMenuPresenter$NavigationMenuAdapter.java
// Decompiled by Jad v1.5.8g. Copyright 2001 <NAME>. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package android.support.design.internal; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.view.ViewCompat; import android.support.v7.view.menu.MenuBuilder; import android.support.v7.view.menu.MenuItemImpl; import android.util.SparseArray; import android.view.*; import android.widget.TextView; import java.util.ArrayList; // Referenced classes of package android.support.design.internal: // NavigationMenuPresenter, ParcelableSparseArray, NavigationMenuItemView private class NavigationMenuPresenter$NavigationMenuAdapter extends android.support.v7.widget.RecyclerView.Adapter { private void appendTransparentIconIfMissing(int i, int j) { for(; i < j; i++) //* 0 0:iload_1 //* 1 1:iload_2 //* 2 2:icmpge 27 (()mItems.get(i)).needsEmptyIcon = true; // 3 5:aload_0 // 4 6:getfield #45 <Field ArrayList mItems> // 5 9:iload_1 // 6 10:invokevirtual #55 <Method Object ArrayList.get(int)> // 7 13:checkcast #57 <Class NavigationMenuPresenter$NavigationMenuTextItem> // 8 16:iconst_1 // 9 17:putfield #60 <Field boolean NavigationMenuPresenter$NavigationMenuTextItem.needsEmptyIcon> // 10 20:iload_1 // 11 21:iconst_1 // 12 22:iadd // 13 23:istore_1 //* 14 24:goto 0 // 15 27:return } private void prepareMenuItems() { if(mUpdateSuspended) //* 0 0:aload_0 //* 1 1:getfield #62 <Field boolean mUpdateSuspended> //* 2 4:ifeq 8 return; // 3 7:return mUpdateSuspended = true; // 4 8:aload_0 // 5 9:iconst_1 // 6 10:putfield #62 <Field boolean mUpdateSuspended> mItems.clear(); // 7 13:aload_0 // 8 14:getfield #45 <Field ArrayList mItems> // 9 17:invokevirtual #65 <Method void ArrayList.clear()> mItems.add(((Object) (new em()))); // 10 20:aload_0 // 11 21:getfield #45 <Field ArrayList mItems> // 12 24:new #67 <Class NavigationMenuPresenter$NavigationMenuHeaderItem> // 13 27:dup // 14 28:invokespecial #68 <Method void NavigationMenuPresenter$NavigationMenuHeaderItem()> // 15 31:invokevirtual #72 <Method boolean ArrayList.add(Object)> // 16 34:pop byte byte1 = -1; // 17 35:iconst_m1 // 18 36:istore 5 int j = 0; // 19 38:iconst_0 // 20 39:istore_2 boolean flag1 = false; // 21 40:iconst_0 // 22 41:istore 11 int l = 0; // 23 43:iconst_0 // 24 44:istore 4 int j1 = mMenu.getVisibleItems().size(); // 25 46:aload_0 // 26 47:getfield #37 <Field NavigationMenuPresenter this$0> // 27 50:getfield #76 <Field MenuBuilder NavigationMenuPresenter.mMenu> // 28 53:invokevirtual #82 <Method ArrayList MenuBuilder.getVisibleItems()> // 29 56:invokevirtual #86 <Method int ArrayList.size()> // 30 59:istore 7 while(l < j1) //* 31 61:iload 4 //* 32 63:iload 7 //* 33 65:icmpge 544 { Object obj = ((Object) ((MenuItemImpl)mMenu.getVisibleItems().get(l))); // 34 68:aload_0 // 35 69:getfield #37 <Field NavigationMenuPresenter this$0> // 36 72:getfield #76 <Field MenuBuilder NavigationMenuPresenter.mMenu> // 37 75:invokevirtual #82 <Method ArrayList MenuBuilder.getVisibleItems()> // 38 78:iload 4 // 39 80:invokevirtual #55 <Method Object ArrayList.get(int)> // 40 83:checkcast #88 <Class MenuItemImpl> // 41 86:astore 12 if(((MenuItemImpl) (obj)).isChecked()) //* 42 88:aload 12 //* 43 90:invokevirtual #92 <Method boolean MenuItemImpl.isChecked()> //* 44 93:ifeq 102 setCheckedItem(((MenuItemImpl) (obj))); // 45 96:aload_0 // 46 97:aload 12 // 47 99:invokevirtual #96 <Method void setCheckedItem(MenuItemImpl)> if(((MenuItemImpl) (obj)).isCheckable()) //* 48 102:aload 12 //* 49 104:invokevirtual #99 <Method boolean MenuItemImpl.isCheckable()> //* 50 107:ifeq 116 ((MenuItemImpl) (obj)).setExclusiveCheckable(false); // 51 110:aload 12 // 52 112:iconst_0 // 53 113:invokevirtual #103 <Method void MenuItemImpl.setExclusiveCheckable(boolean)> int k; int i1; boolean flag; if(((MenuItemImpl) (obj)).hasSubMenu()) //* 54 116:aload 12 //* 55 118:invokevirtual #106 <Method boolean MenuItemImpl.hasSubMenu()> //* 56 121:ifeq 380 { SubMenu submenu = ((MenuItemImpl) (obj)).getSubMenu(); // 57 124:aload 12 // 58 126:invokevirtual #110 <Method SubMenu MenuItemImpl.getSubMenu()> // 59 129:astore 13 flag = flag1; // 60 131:iload 11 // 61 133:istore 10 k = ((int) (byte1)); // 62 135:iload 5 // 63 137:istore_3 i1 = j; // 64 138:iload_2 // 65 139:istore 6 if(submenu.hasVisibleItems()) //* 66 141:aload 13 //* 67 143:invokeinterface #115 <Method boolean SubMenu.hasVisibleItems()> //* 68 148:ifeq 361 { if(l != 0) //* 69 151:iload 4 //* 70 153:ifeq 179 mItems.add(((Object) (new rItem(mPaddingSeparator, 0)))); // 71 156:aload_0 // 72 157:getfield #45 <Field ArrayList mItems> // 73 160:new #117 <Class NavigationMenuPresenter$NavigationMenuSeparatorItem> // 74 163:dup // 75 164:aload_0 // 76 165:getfield #37 <Field NavigationMenuPresenter this$0> // 77 168:getfield #120 <Field int NavigationMenuPresenter.mPaddingSeparator> // 78 171:iconst_0 // 79 172:invokespecial #122 <Method void NavigationMenuPresenter$NavigationMenuSeparatorItem(int, int)> // 80 175:invokevirtual #72 <Method boolean ArrayList.add(Object)> // 81 178:pop mItems.add(((Object) (new (((MenuItemImpl) (obj)))))); // 82 179:aload_0 // 83 180:getfield #45 <Field ArrayList mItems> // 84 183:new #57 <Class NavigationMenuPresenter$NavigationMenuTextItem> // 85 186:dup // 86 187:aload 12 // 87 189:invokespecial #124 <Method void NavigationMenuPresenter$NavigationMenuTextItem(MenuItemImpl)> // 88 192:invokevirtual #72 <Method boolean ArrayList.add(Object)> // 89 195:pop byte byte0 = 0; // 90 196:iconst_0 // 91 197:istore_1 int k1 = mItems.size(); // 92 198:aload_0 // 93 199:getfield #45 <Field ArrayList mItems> // 94 202:invokevirtual #86 <Method int ArrayList.size()> // 95 205:istore 8 i1 = 0; // 96 207:iconst_0 // 97 208:istore 6 for(int l1 = submenu.size(); i1 < l1;) //* 98 210:aload 13 //* 99 212:invokeinterface #125 <Method int SubMenu.size()> //* 100 217:istore 9 //* 101 219:iload 6 //* 102 221:iload 9 //* 103 223:icmpge 324 { MenuItemImpl menuitemimpl = (MenuItemImpl)submenu.getItem(i1); // 104 226:aload 13 // 105 228:iload 6 // 106 230:invokeinterface #129 <Method android.view.MenuItem SubMenu.getItem(int)> // 107 235:checkcast #88 <Class MenuItemImpl> // 108 238:astore 14 k = ((int) (byte0)); // 109 240:iload_1 // 110 241:istore_3 if(menuitemimpl.isVisible()) //* 111 242:aload 14 //* 112 244:invokevirtual #132 <Method boolean MenuItemImpl.isVisible()> //* 113 247:ifeq 313 { k = ((int) (byte0)); // 114 250:iload_1 // 115 251:istore_3 if(byte0 == 0) //* 116 252:iload_1 //* 117 253:ifne 268 { k = ((int) (byte0)); // 118 256:iload_1 // 119 257:istore_3 if(menuitemimpl.getIcon() != null) //* 120 258:aload 14 //* 121 260:invokevirtual #136 <Method Drawable MenuItemImpl.getIcon()> //* 122 263:ifnull 268 k = 1; // 123 266:iconst_1 // 124 267:istore_3 } if(menuitemimpl.isCheckable()) //* 125 268:aload 14 //* 126 270:invokevirtual #99 <Method boolean MenuItemImpl.isCheckable()> //* 127 273:ifeq 282 menuitemimpl.setExclusiveCheckable(false); // 128 276:aload 14 // 129 278:iconst_0 // 130 279:invokevirtual #103 <Method void MenuItemImpl.setExclusiveCheckable(boolean)> if(((MenuItemImpl) (obj)).isChecked()) //* 131 282:aload 12 //* 132 284:invokevirtual #92 <Method boolean MenuItemImpl.isChecked()> //* 133 287:ifeq 296 setCheckedItem(((MenuItemImpl) (obj))); // 134 290:aload_0 // 135 291:aload 12 // 136 293:invokevirtual #96 <Method void setCheckedItem(MenuItemImpl)> mItems.add(((Object) (new (menuitemimpl)))); // 137 296:aload_0 // 138 297:getfield #45 <Field ArrayList mItems> // 139 300:new #57 <Class NavigationMenuPresenter$NavigationMenuTextItem> // 140 303:dup // 141 304:aload 14 // 142 306:invokespecial #124 <Method void NavigationMenuPresenter$NavigationMenuTextItem(MenuItemImpl)> // 143 309:invokevirtual #72 <Method boolean ArrayList.add(Object)> // 144 312:pop } i1++; // 145 313:iload 6 // 146 315:iconst_1 // 147 316:iadd // 148 317:istore 6 byte0 = ((byte) (k)); // 149 319:iload_3 // 150 320:istore_1 } //* 151 321:goto 219 flag = flag1; // 152 324:iload 11 // 153 326:istore 10 k = ((int) (byte1)); // 154 328:iload 5 // 155 330:istore_3 i1 = j; // 156 331:iload_2 // 157 332:istore 6 if(byte0 != 0) //* 158 334:iload_1 //* 159 335:ifeq 361 { appendTransparentIconIfMissing(k1, mItems.size()); // 160 338:aload_0 // 161 339:iload 8 // 162 341:aload_0 // 163 342:getfield #45 <Field ArrayList mItems> // 164 345:invokevirtual #86 <Method int ArrayList.size()> // 165 348:invokespecial #138 <Method void appendTransparentIconIfMissing(int, int)> i1 = j; // 166 351:iload_2 // 167 352:istore 6 k = ((int) (byte1)); // 168 354:iload 5 // 169 356:istore_3 flag = flag1; // 170 357:iload 11 // 171 359:istore 10 } } } else //* 172 361:iload 4 //* 173 363:iconst_1 //* 174 364:iadd //* 175 365:istore 4 //* 176 367:iload 10 //* 177 369:istore 11 //* 178 371:iload_3 //* 179 372:istore 5 //* 180 374:iload 6 //* 181 376:istore_2 //* 182 377:goto 61 { k = ((MenuItemImpl) (obj)).getGroupId(); // 183 380:aload 12 // 184 382:invokevirtual #141 <Method int MenuItemImpl.getGroupId()> // 185 385:istore_3 int i; if(k != byte1) //* 186 386:iload_3 //* 187 387:iload 5 //* 188 389:icmpeq 499 { j = mItems.size(); // 189 392:aload_0 // 190 393:getfield #45 <Field ArrayList mItems> // 191 396:invokevirtual #86 <Method int ArrayList.size()> // 192 399:istore_2 if(((MenuItemImpl) (obj)).getIcon() != null) //* 193 400:aload 12 //* 194 402:invokevirtual #136 <Method Drawable MenuItemImpl.getIcon()> //* 195 405:ifnull 493 flag1 = true; // 196 408:iconst_1 // 197 409:istore 11 else //* 198 411:iload 11 //* 199 413:istore 10 //* 200 415:iload_2 //* 201 416:istore_1 //* 202 417:iload 4 //* 203 419:ifeq 459 //* 204 422:iload_2 //* 205 423:iconst_1 //* 206 424:iadd //* 207 425:istore_1 //* 208 426:aload_0 //* 209 427:getfield #45 <Field ArrayList mItems> //* 210 430:new #117 <Class NavigationMenuPresenter$NavigationMenuSeparatorItem> //* 211 433:dup //* 212 434:aload_0 //* 213 435:getfield #37 <Field NavigationMenuPresenter this$0> //* 214 438:getfield #120 <Field int NavigationMenuPresenter.mPaddingSeparator> //* 215 441:aload_0 //* 216 442:getfield #37 <Field NavigationMenuPresenter this$0> //* 217 445:getfield #120 <Field int NavigationMenuPresenter.mPaddingSeparator> //* 218 448:invokespecial #122 <Method void NavigationMenuPresenter$NavigationMenuSeparatorItem(int, int)> //* 219 451:invokevirtual #72 <Method boolean ArrayList.add(Object)> //* 220 454:pop //* 221 455:iload 11 //* 222 457:istore 10 //* 223 459:new #57 <Class NavigationMenuPresenter$NavigationMenuTextItem> //* 224 462:dup //* 225 463:aload 12 //* 226 465:invokespecial #124 <Method void NavigationMenuPresenter$NavigationMenuTextItem(MenuItemImpl)> //* 227 468:astore 12 //* 228 470:aload 12 //* 229 472:iload 10 //* 230 474:putfield #60 <Field boolean NavigationMenuPresenter$NavigationMenuTextItem.needsEmptyIcon> //* 231 477:aload_0 //* 232 478:getfield #45 <Field ArrayList mItems> //* 233 481:aload 12 //* 234 483:invokevirtual #72 <Method boolean ArrayList.add(Object)> //* 235 486:pop //* 236 487:iload_1 //* 237 488:istore 6 //* 238 490:goto 361 flag1 = false; // 239 493:iconst_0 // 240 494:istore 11 flag = flag1; i = j; if(l != 0) { i = j + 1; mItems.add(((Object) (new rItem(mPaddingSeparator, mPaddingSeparator)))); flag = flag1; } } else //* 241 496:goto 411 { flag = flag1; // 242 499:iload 11 // 243 501:istore 10 i = j; // 244 503:iload_2 // 245 504:istore_1 if(!flag1) //* 246 505:iload 11 //* 247 507:ifne 459 { flag = flag1; // 248 510:iload 11 // 249 512:istore 10 i = j; // 250 514:iload_2 // 251 515:istore_1 if(((MenuItemImpl) (obj)).getIcon() != null) //* 252 516:aload 12 //* 253 518:invokevirtual #136 <Method Drawable MenuItemImpl.getIcon()> //* 254 521:ifnull 459 { flag = true; // 255 524:iconst_1 // 256 525:istore 10 appendTransparentIconIfMissing(j, mItems.size()); // 257 527:aload_0 // 258 528:iload_2 // 259 529:aload_0 // 260 530:getfield #45 <Field ArrayList mItems> // 261 533:invokevirtual #86 <Method int ArrayList.size()> // 262 536:invokespecial #138 <Method void appendTransparentIconIfMissing(int, int)> i = j; // 263 539:iload_2 // 264 540:istore_1 } } } obj = ((Object) (new (((MenuItemImpl) (obj))))); obj.needsEmptyIcon = flag; mItems.add(obj); i1 = i; } l++; flag1 = flag; byte1 = ((byte) (k)); j = i1; } //* 265 541:goto 459 mUpdateSuspended = false; // 266 544:aload_0 // 267 545:iconst_0 // 268 546:putfield #62 <Field boolean mUpdateSuspended> // 269 549:return } public Bundle createInstanceState() { Bundle bundle = new Bundle(); // 0 0:new #145 <Class Bundle> // 1 3:dup // 2 4:invokespecial #146 <Method void Bundle()> // 3 7:astore 4 if(mCheckedItem != null) //* 4 9:aload_0 //* 5 10:getfield #148 <Field MenuItemImpl mCheckedItem> //* 6 13:ifnull 30 bundle.putInt("android:menu:checked", mCheckedItem.getItemId()); // 7 16:aload 4 // 8 18:ldc1 #15 <String "android:menu:checked"> // 9 20:aload_0 // 10 21:getfield #148 <Field MenuItemImpl mCheckedItem> // 11 24:invokevirtual #151 <Method int MenuItemImpl.getItemId()> // 12 27:invokevirtual #155 <Method void Bundle.putInt(String, int)> SparseArray sparsearray = new SparseArray(); // 13 30:new #157 <Class SparseArray> // 14 33:dup // 15 34:invokespecial #158 <Method void SparseArray()> // 16 37:astore 5 int i = 0; // 17 39:iconst_0 // 18 40:istore_1 int j = mItems.size(); // 19 41:aload_0 // 20 42:getfield #45 <Field ArrayList mItems> // 21 45:invokevirtual #86 <Method int ArrayList.size()> // 22 48:istore_2 while(i < j) //* 23 49:iload_1 //* 24 50:iload_2 //* 25 51:icmpge 136 { Object obj = ((Object) ((NavigationMenuPresenter.NavigationMenuItem)mItems.get(i))); // 26 54:aload_0 // 27 55:getfield #45 <Field ArrayList mItems> // 28 58:iload_1 // 29 59:invokevirtual #55 <Method Object ArrayList.get(int)> // 30 62:checkcast #160 <Class NavigationMenuPresenter$NavigationMenuItem> // 31 65:astore_3 if(!(obj instanceof )) continue; // 32 66:aload_3 // 33 67:instanceof #57 <Class NavigationMenuPresenter$NavigationMenuTextItem> // 34 70:ifeq 124 MenuItemImpl menuitemimpl = (()obj).getMenuItem(); // 35 73:aload_3 // 36 74:checkcast #57 <Class NavigationMenuPresenter$NavigationMenuTextItem> // 37 77:invokevirtual #164 <Method MenuItemImpl NavigationMenuPresenter$NavigationMenuTextItem.getMenuItem()> // 38 80:astore 6 if(menuitemimpl != null) //* 39 82:aload 6 //* 40 84:ifnull 131 obj = ((Object) (menuitemimpl.getActionView())); // 41 87:aload 6 // 42 89:invokevirtual #168 <Method View MenuItemImpl.getActionView()> // 43 92:astore_3 else //* 44 93:aload_3 //* 45 94:ifnull 124 //* 46 97:new #170 <Class ParcelableSparseArray> //* 47 100:dup //* 48 101:invokespecial #171 <Method void ParcelableSparseArray()> //* 49 104:astore 7 //* 50 106:aload_3 //* 51 107:aload 7 //* 52 109:invokevirtual #177 <Method void View.saveHierarchyState(SparseArray)> //* 53 112:aload 5 //* 54 114:aload 6 //* 55 116:invokevirtual #151 <Method int MenuItemImpl.getItemId()> //* 56 119:aload 7 //* 57 121:invokevirtual #181 <Method void SparseArray.put(int, Object)> //* 58 124:iload_1 //* 59 125:iconst_1 //* 60 126:iadd //* 61 127:istore_1 //* 62 128:goto 49 obj = null; // 63 131:aconst_null // 64 132:astore_3 if(obj != null) { ParcelableSparseArray parcelablesparsearray = new ParcelableSparseArray(); ((View) (obj)).saveHierarchyState(((SparseArray) (parcelablesparsearray))); sparsearray.put(menuitemimpl.getItemId(), ((Object) (parcelablesparsearray))); } i++; } //* 65 133:goto 93 bundle.putSparseParcelableArray("android:menu:action_views", sparsearray); // 66 136:aload 4 // 67 138:ldc1 #12 <String "android:menu:action_views"> // 68 140:aload 5 // 69 142:invokevirtual #185 <Method void Bundle.putSparseParcelableArray(String, SparseArray)> return bundle; // 70 145:aload 4 // 71 147:areturn } public int getItemCount() { return mItems.size(); // 0 0:aload_0 // 1 1:getfield #45 <Field ArrayList mItems> // 2 4:invokevirtual #86 <Method int ArrayList.size()> // 3 7:ireturn } public long getItemId(int i) { return (long)i; // 0 0:iload_1 // 1 1:i2l // 2 2:lreturn } public int getItemViewType(int i) { NavigationMenuPresenter.NavigationMenuItem navigationmenuitem = (NavigationMenuPresenter.NavigationMenuItem)mItems.get(i); // 0 0:aload_0 // 1 1:getfield #45 <Field ArrayList mItems> // 2 4:iload_1 // 3 5:invokevirtual #55 <Method Object ArrayList.get(int)> // 4 8:checkcast #160 <Class NavigationMenuPresenter$NavigationMenuItem> // 5 11:astore_2 if(navigationmenuitem instanceof rItem) //* 6 12:aload_2 //* 7 13:instanceof #117 <Class NavigationMenuPresenter$NavigationMenuSeparatorItem> //* 8 16:ifeq 21 return 2; // 9 19:iconst_2 // 10 20:ireturn if(navigationmenuitem instanceof em) //* 11 21:aload_2 //* 12 22:instanceof #67 <Class NavigationMenuPresenter$NavigationMenuHeaderItem> //* 13 25:ifeq 30 return 3; // 14 28:iconst_3 // 15 29:ireturn if(navigationmenuitem instanceof ) //* 16 30:aload_2 //* 17 31:instanceof #57 <Class NavigationMenuPresenter$NavigationMenuTextItem> //* 18 34:ifeq 54 return !(()navigationmenuitem).getMenuItem().hasSubMenu() ? 0 : 1; // 19 37:aload_2 // 20 38:checkcast #57 <Class NavigationMenuPresenter$NavigationMenuTextItem> // 21 41:invokevirtual #164 <Method MenuItemImpl NavigationMenuPresenter$NavigationMenuTextItem.getMenuItem()> // 22 44:invokevirtual #106 <Method boolean MenuItemImpl.hasSubMenu()> // 23 47:ifeq 52 // 24 50:iconst_1 // 25 51:ireturn // 26 52:iconst_0 // 27 53:ireturn else throw new RuntimeException("Unknown item type."); // 28 54:new #191 <Class RuntimeException> // 29 57:dup // 30 58:ldc1 #193 <String "Unknown item type."> // 31 60:invokespecial #196 <Method void RuntimeException(String)> // 32 63:athrow } public void onBindViewHolder(NavigationMenuPresenter.ViewHolder viewholder, int i) { switch(getItemViewType(i)) //* 0 0:aload_0 //* 1 1:iload_2 //* 2 2:invokevirtual #200 <Method int getItemViewType(int)> { //* 3 5:tableswitch 0 2: default 32 // 0 33 // 1 158 // 2 186 default: return; // 4 32:return case 0: // '\0' NavigationMenuItemView navigationmenuitemview = (NavigationMenuItemView)viewholder.itemView; // 5 33:aload_1 // 6 34:getfield #206 <Field View NavigationMenuPresenter$ViewHolder.itemView> // 7 37:checkcast #208 <Class NavigationMenuItemView> // 8 40:astore_3 navigationmenuitemview.setIconTintList(mIconTintList); // 9 41:aload_3 // 10 42:aload_0 // 11 43:getfield #37 <Field NavigationMenuPresenter this$0> // 12 46:getfield #212 <Field android.content.res.ColorStateList NavigationMenuPresenter.mIconTintList> // 13 49:invokevirtual #216 <Method void NavigationMenuItemView.setIconTintList(android.content.res.ColorStateList)> if(mTextAppearanceSet) //* 14 52:aload_0 //* 15 53:getfield #37 <Field NavigationMenuPresenter this$0> //* 16 56:getfield #219 <Field boolean NavigationMenuPresenter.mTextAppearanceSet> //* 17 59:ifeq 73 navigationmenuitemview.setTextAppearance(mTextAppearance); // 18 62:aload_3 // 19 63:aload_0 // 20 64:getfield #37 <Field NavigationMenuPresenter this$0> // 21 67:getfield #222 <Field int NavigationMenuPresenter.mTextAppearance> // 22 70:invokevirtual #226 <Method void NavigationMenuItemView.setTextAppearance(int)> if(mTextColor != null) //* 23 73:aload_0 //* 24 74:getfield #37 <Field NavigationMenuPresenter this$0> //* 25 77:getfield #229 <Field android.content.res.ColorStateList NavigationMenuPresenter.mTextColor> //* 26 80:ifnull 94 navigationmenuitemview.setTextColor(mTextColor); // 27 83:aload_3 // 28 84:aload_0 // 29 85:getfield #37 <Field NavigationMenuPresenter this$0> // 30 88:getfield #229 <Field android.content.res.ColorStateList NavigationMenuPresenter.mTextColor> // 31 91:invokevirtual #232 <Method void NavigationMenuItemView.setTextColor(android.content.res.ColorStateList)> if(mItemBackground != null) //* 32 94:aload_0 //* 33 95:getfield #37 <Field NavigationMenuPresenter this$0> //* 34 98:getfield #236 <Field Drawable NavigationMenuPresenter.mItemBackground> //* 35 101:ifnull 153 viewholder = ((NavigationMenuPresenter.ViewHolder) (mItemBackground.getConstantState().newDrawable())); // 36 104:aload_0 // 37 105:getfield #37 <Field NavigationMenuPresenter this$0> // 38 108:getfield #236 <Field Drawable NavigationMenuPresenter.mItemBackground> // 39 111:invokevirtual #242 <Method android.graphics.drawable.Drawable$ConstantState Drawable.getConstantState()> // 40 114:invokevirtual #247 <Method Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable()> // 41 117:astore_1 else //* 42 118:aload_3 //* 43 119:aload_1 //* 44 120:invokestatic #253 <Method void ViewCompat.setBackground(View, Drawable)> //* 45 123:aload_0 //* 46 124:getfield #45 <Field ArrayList mItems> //* 47 127:iload_2 //* 48 128:invokevirtual #55 <Method Object ArrayList.get(int)> //* 49 131:checkcast #57 <Class NavigationMenuPresenter$NavigationMenuTextItem> //* 50 134:astore_1 //* 51 135:aload_3 //* 52 136:aload_1 //* 53 137:getfield #60 <Field boolean NavigationMenuPresenter$NavigationMenuTextItem.needsEmptyIcon> //* 54 140:invokevirtual #256 <Method void NavigationMenuItemView.setNeedsEmptyIcon(boolean)> //* 55 143:aload_3 //* 56 144:aload_1 //* 57 145:invokevirtual #164 <Method MenuItemImpl NavigationMenuPresenter$NavigationMenuTextItem.getMenuItem()> //* 58 148:iconst_0 //* 59 149:invokevirtual #260 <Method void NavigationMenuItemView.initialize(MenuItemImpl, int)> //* 60 152:return viewholder = null; // 61 153:aconst_null // 62 154:astore_1 ViewCompat.setBackground(((View) (navigationmenuitemview)), ((Drawable) (viewholder))); viewholder = ((NavigationMenuPresenter.ViewHolder) (()mItems.get(i))); navigationmenuitemview.setNeedsEmptyIcon((() (viewholder)).needsEmptyIcon); navigationmenuitemview.initialize((() (viewholder)).getMenuItem(), 0); return; //* 63 155:goto 118 case 1: // '\001' ((TextView)viewholder.itemView).setText((()mItems.get(i)).getMenuItem().getTitle()); // 64 158:aload_1 // 65 159:getfield #206 <Field View NavigationMenuPresenter$ViewHolder.itemView> // 66 162:checkcast #262 <Class TextView> // 67 165:aload_0 // 68 166:getfield #45 <Field ArrayList mItems> // 69 169:iload_2 // 70 170:invokevirtual #55 <Method Object ArrayList.get(int)> // 71 173:checkcast #57 <Class NavigationMenuPresenter$NavigationMenuTextItem> // 72 176:invokevirtual #164 <Method MenuItemImpl NavigationMenuPresenter$NavigationMenuTextItem.getMenuItem()> // 73 179:invokevirtual #266 <Method CharSequence MenuItemImpl.getTitle()> // 74 182:invokevirtual #270 <Method void TextView.setText(CharSequence)> return; // 75 185:return case 2: // '\002' rItem ritem = (rItem)mItems.get(i); // 76 186:aload_0 // 77 187:getfield #45 <Field ArrayList mItems> // 78 190:iload_2 // 79 191:invokevirtual #55 <Method Object ArrayList.get(int)> // 80 194:checkcast #117 <Class NavigationMenuPresenter$NavigationMenuSeparatorItem> // 81 197:astore_3 viewholder.itemView.setPadding(0, ritem.getPaddingTop(), 0, ritem.getPaddingBottom()); // 82 198:aload_1 // 83 199:getfield #206 <Field View NavigationMenuPresenter$ViewHolder.itemView> // 84 202:iconst_0 // 85 203:aload_3 // 86 204:invokevirtual #273 <Method int NavigationMenuPresenter$NavigationMenuSeparatorItem.getPaddingTop()> // 87 207:iconst_0 // 88 208:aload_3 // 89 209:invokevirtual #276 <Method int NavigationMenuPresenter$NavigationMenuSeparatorItem.getPaddingBottom()> // 90 212:invokevirtual #280 <Method void View.setPadding(int, int, int, int)> return; // 91 215:return } } public volatile void onBindViewHolder(android.support.v7.widget.RecyclerView.ViewHolder viewholder, int i) { onBindViewHolder((NavigationMenuPresenter.ViewHolder)viewholder, i); // 0 0:aload_0 // 1 1:aload_1 // 2 2:checkcast #202 <Class NavigationMenuPresenter$ViewHolder> // 3 5:iload_2 // 4 6:invokevirtual #283 <Method void onBindViewHolder(NavigationMenuPresenter$ViewHolder, int)> // 5 9:return } public NavigationMenuPresenter.ViewHolder onCreateViewHolder(ViewGroup viewgroup, int i) { switch(i) //* 0 0:iload_2 { //* 1 1:tableswitch 0 3: default 32 // 0 34 // 1 57 // 2 73 // 3 89 default: return null; // 2 32:aconst_null // 3 33:areturn case 0: // '\0' return ((NavigationMenuPresenter.ViewHolder) (new NavigationMenuPresenter.NormalViewHolder(mLayoutInflater, viewgroup, mOnClickListener))); // 4 34:new #287 <Class NavigationMenuPresenter$NormalViewHolder> // 5 37:dup // 6 38:aload_0 // 7 39:getfield #37 <Field NavigationMenuPresenter this$0> // 8 42:getfield #291 <Field android.view.LayoutInflater NavigationMenuPresenter.mLayoutInflater> // 9 45:aload_1 // 10 46:aload_0 // 11 47:getfield #37 <Field NavigationMenuPresenter this$0> // 12 50:getfield #295 <Field android.view.View$OnClickListener NavigationMenuPresenter.mOnClickListener> // 13 53:invokespecial #298 <Method void NavigationMenuPresenter$NormalViewHolder(android.view.LayoutInflater, ViewGroup, android.view.View$OnClickListener)> // 14 56:areturn case 1: // '\001' return ((NavigationMenuPresenter.ViewHolder) (new NavigationMenuPresenter.SubheaderViewHolder(mLayoutInflater, viewgroup))); // 15 57:new #300 <Class NavigationMenuPresenter$SubheaderViewHolder> // 16 60:dup // 17 61:aload_0 // 18 62:getfield #37 <Field NavigationMenuPresenter this$0> // 19 65:getfield #291 <Field android.view.LayoutInflater NavigationMenuPresenter.mLayoutInflater> // 20 68:aload_1 // 21 69:invokespecial #303 <Method void NavigationMenuPresenter$SubheaderViewHolder(android.view.LayoutInflater, ViewGroup)> // 22 72:areturn case 2: // '\002' return ((NavigationMenuPresenter.ViewHolder) (new NavigationMenuPresenter.SeparatorViewHolder(mLayoutInflater, viewgroup))); // 23 73:new #305 <Class NavigationMenuPresenter$SeparatorViewHolder> // 24 76:dup // 25 77:aload_0 // 26 78:getfield #37 <Field NavigationMenuPresenter this$0> // 27 81:getfield #291 <Field android.view.LayoutInflater NavigationMenuPresenter.mLayoutInflater> // 28 84:aload_1 // 29 85:invokespecial #306 <Method void NavigationMenuPresenter$SeparatorViewHolder(android.view.LayoutInflater, ViewGroup)> // 30 88:areturn case 3: // '\003' return ((NavigationMenuPresenter.ViewHolder) (new NavigationMenuPresenter.HeaderViewHolder(((View) (mHeaderLayout))))); // 31 89:new #308 <Class NavigationMenuPresenter$HeaderViewHolder> // 32 92:dup // 33 93:aload_0 // 34 94:getfield #37 <Field NavigationMenuPresenter this$0> // 35 97:getfield #312 <Field android.widget.LinearLayout NavigationMenuPresenter.mHeaderLayout> // 36 100:invokespecial #315 <Method void NavigationMenuPresenter$HeaderViewHolder(View)> // 37 103:areturn } } public volatile android.support.v7.widget.RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewgroup, int i) { return ((android.support.v7.widget.RecyclerView.ViewHolder) (onCreateViewHolder(viewgroup, i))); // 0 0:aload_0 // 1 1:aload_1 // 2 2:iload_2 // 3 3:invokevirtual #318 <Method NavigationMenuPresenter$ViewHolder onCreateViewHolder(ViewGroup, int)> // 4 6:areturn } public void onViewRecycled(NavigationMenuPresenter.ViewHolder viewholder) { if(viewholder instanceof NavigationMenuPresenter.NormalViewHolder) //* 0 0:aload_1 //* 1 1:instanceof #287 <Class NavigationMenuPresenter$NormalViewHolder> //* 2 4:ifeq 17 ((NavigationMenuItemView)viewholder.itemView).recycle(); // 3 7:aload_1 // 4 8:getfield #206 <Field View NavigationMenuPresenter$ViewHolder.itemView> // 5 11:checkcast #208 <Class NavigationMenuItemView> // 6 14:invokevirtual #323 <Method void NavigationMenuItemView.recycle()> // 7 17:return } public volatile void onViewRecycled(android.support.v7.widget.RecyclerView.ViewHolder viewholder) { onViewRecycled((NavigationMenuPresenter.ViewHolder)viewholder); // 0 0:aload_0 // 1 1:aload_1 // 2 2:checkcast #202 <Class NavigationMenuPresenter$ViewHolder> // 3 5:invokevirtual #326 <Method void onViewRecycled(NavigationMenuPresenter$ViewHolder)> // 4 8:return } public void restoreInstanceState(Bundle bundle) { int j = bundle.getInt("android:menu:checked", 0); // 0 0:aload_1 // 1 1:ldc1 #15 <String "android:menu:checked"> // 2 3:iconst_0 // 3 4:invokevirtual #332 <Method int Bundle.getInt(String, int)> // 4 7:istore_3 if(j == 0) goto _L2; else goto _L1 // 5 8:iload_3 // 6 9:ifeq 94 _L1: int i; int l; mUpdateSuspended = true; // 7 12:aload_0 // 8 13:iconst_1 // 9 14:putfield #62 <Field boolean mUpdateSuspended> i = 0; // 10 17:iconst_0 // 11 18:istore_2 l = mItems.size(); // 12 19:aload_0 // 13 20:getfield #45 <Field ArrayList mItems> // 14 23:invokevirtual #86 <Method int ArrayList.size()> // 15 26:istore 4 _L9: if(i >= l) goto _L4; else goto _L3 // 16 28:iload_2 // 17 29:iload 4 // 18 31:icmpge 85 _L3: Object obj = ((Object) ((NavigationMenuPresenter.NavigationMenuItem)mItems.get(i))); // 19 34:aload_0 // 20 35:getfield #45 <Field ArrayList mItems> // 21 38:iload_2 // 22 39:invokevirtual #55 <Method Object ArrayList.get(int)> // 23 42:checkcast #160 <Class NavigationMenuPresenter$NavigationMenuItem> // 24 45:astore 5 if(!(obj instanceof )) goto _L6; else goto _L5 // 25 47:aload 5 // 26 49:instanceof #57 <Class NavigationMenuPresenter$NavigationMenuTextItem> // 27 52:ifeq 148 _L5: obj = ((Object) ((()obj).getMenuItem())); // 28 55:aload 5 // 29 57:checkcast #57 <Class NavigationMenuPresenter$NavigationMenuTextItem> // 30 60:invokevirtual #164 <Method MenuItemImpl NavigationMenuPresenter$NavigationMenuTextItem.getMenuItem()> // 31 63:astore 5 if(obj == null || ((MenuItemImpl) (obj)).getItemId() != j) goto _L6; else goto _L7 // 32 65:aload 5 // 33 67:ifnull 148 // 34 70:aload 5 // 35 72:invokevirtual #151 <Method int MenuItemImpl.getItemId()> // 36 75:iload_3 // 37 76:icmpne 148 _L7: setCheckedItem(((MenuItemImpl) (obj))); // 38 79:aload_0 // 39 80:aload 5 // 40 82:invokevirtual #96 <Method void setCheckedItem(MenuItemImpl)> _L4: mUpdateSuspended = false; // 41 85:aload_0 // 42 86:iconst_0 // 43 87:putfield #62 <Field boolean mUpdateSuspended> prepareMenuItems(); // 44 90:aload_0 // 45 91:invokespecial #48 <Method void prepareMenuItems()> goto _L2 //* 46 94:aload_1 //* 47 95:ldc1 #12 <String "android:menu:action_views"> //* 48 97:invokevirtual #336 <Method SparseArray Bundle.getSparseParcelableArray(String)> //* 49 100:astore_1 //* 50 101:aload_1 //* 51 102:ifnull 211 //* 52 105:iconst_0 //* 53 106:istore_2 //* 54 107:aload_0 //* 55 108:getfield #45 <Field ArrayList mItems> //* 56 111:invokevirtual #86 <Method int ArrayList.size()> //* 57 114:istore_3 //* 58 115:iload_2 //* 59 116:iload_3 //* 60 117:icmpge 211 //* 61 120:aload_0 //* 62 121:getfield #45 <Field ArrayList mItems> //* 63 124:iload_2 //* 64 125:invokevirtual #55 <Method Object ArrayList.get(int)> //* 65 128:checkcast #160 <Class NavigationMenuPresenter$NavigationMenuItem> //* 66 131:astore 5 //* 67 133:aload 5 //* 68 135:instanceof #57 <Class NavigationMenuPresenter$NavigationMenuTextItem> //* 69 138:ifne 155 //* 70 141:iload_2 //* 71 142:iconst_1 //* 72 143:iadd //* 73 144:istore_2 //* 74 145:goto 115 _L6: i++; // 75 148:iload_2 // 76 149:iconst_1 // 77 150:iadd // 78 151:istore_2 continue; /* Loop/switch isn't completed */ // 79 152:goto 28 _L2: bundle = ((Bundle) (bundle.getSparseParcelableArray("android:menu:action_views"))); if(bundle != null) { i = 0; int k = mItems.size(); while(i < k) { NavigationMenuPresenter.NavigationMenuItem navigationmenuitem = (NavigationMenuPresenter.NavigationMenuItem)mItems.get(i); if(navigationmenuitem instanceof ) { Object obj1 = ((Object) ((()navigationmenuitem).getMenuItem())); // 80 155:aload 5 // 81 157:checkcast #57 <Class NavigationMenuPresenter$NavigationMenuTextItem> // 82 160:invokevirtual #164 <Method MenuItemImpl NavigationMenuPresenter$NavigationMenuTextItem.getMenuItem()> // 83 163:astore 6 if(obj1 != null) //* 84 165:aload 6 //* 85 167:ifnull 141 { View view = ((MenuItemImpl) (obj1)).getActionView(); // 86 170:aload 6 // 87 172:invokevirtual #168 <Method View MenuItemImpl.getActionView()> // 88 175:astore 5 if(view != null) //* 89 177:aload 5 //* 90 179:ifnull 141 { obj1 = ((Object) ((ParcelableSparseArray)((SparseArray) (bundle)).get(((MenuItemImpl) (obj1)).getItemId()))); // 91 182:aload_1 // 92 183:aload 6 // 93 185:invokevirtual #151 <Method int MenuItemImpl.getItemId()> // 94 188:invokevirtual #337 <Method Object SparseArray.get(int)> // 95 191:checkcast #170 <Class ParcelableSparseArray> // 96 194:astore 6 if(obj1 != null) //* 97 196:aload 6 //* 98 198:ifnull 141 view.restoreHierarchyState(((SparseArray) (obj1))); // 99 201:aload 5 // 100 203:aload 6 // 101 205:invokevirtual #340 <Method void View.restoreHierarchyState(SparseArray)> } } } i++; } } //* 102 208:goto 141 return; // 103 211:return if(true) goto _L9; else goto _L8 _L8: } public void setCheckedItem(MenuItemImpl menuitemimpl) { if(mCheckedItem == menuitemimpl || !menuitemimpl.isCheckable()) //* 0 0:aload_0 //* 1 1:getfield #148 <Field MenuItemImpl mCheckedItem> //* 2 4:aload_1 //* 3 5:if_acmpeq 15 //* 4 8:aload_1 //* 5 9:invokevirtual #99 <Method boolean MenuItemImpl.isCheckable()> //* 6 12:ifne 16 return; // 7 15:return if(mCheckedItem != null) //* 8 16:aload_0 //* 9 17:getfield #148 <Field MenuItemImpl mCheckedItem> //* 10 20:ifnull 32 mCheckedItem.setChecked(false); // 11 23:aload_0 // 12 24:getfield #148 <Field MenuItemImpl mCheckedItem> // 13 27:iconst_0 // 14 28:invokevirtual #344 <Method android.view.MenuItem MenuItemImpl.setChecked(boolean)> // 15 31:pop mCheckedItem = menuitemimpl; // 16 32:aload_0 // 17 33:aload_1 // 18 34:putfield #148 <Field MenuItemImpl mCheckedItem> menuitemimpl.setChecked(true); // 19 37:aload_1 // 20 38:iconst_1 // 21 39:invokevirtual #344 <Method android.view.MenuItem MenuItemImpl.setChecked(boolean)> // 22 42:pop // 23 43:return } public void setUpdateSuspended(boolean flag) { mUpdateSuspended = flag; // 0 0:aload_0 // 1 1:iload_1 // 2 2:putfield #62 <Field boolean mUpdateSuspended> // 3 5:return } public void update() { prepareMenuItems(); // 0 0:aload_0 // 1 1:invokespecial #48 <Method void prepareMenuItems()> notifyDataSetChanged(); // 2 4:aload_0 // 3 5:invokevirtual #349 <Method void notifyDataSetChanged()> // 4 8:return } private static final String STATE_ACTION_VIEWS = "android:menu:action_views"; private static final String STATE_CHECKED_ITEM = "android:menu:checked"; private static final int VIEW_TYPE_HEADER = 3; private static final int VIEW_TYPE_NORMAL = 0; private static final int VIEW_TYPE_SEPARATOR = 2; private static final int VIEW_TYPE_SUBHEADER = 1; private MenuItemImpl mCheckedItem; private final ArrayList mItems = new ArrayList(); private boolean mUpdateSuspended; final NavigationMenuPresenter this$0; NavigationMenuPresenter$NavigationMenuAdapter() { this$0 = NavigationMenuPresenter.this; // 0 0:aload_0 // 1 1:aload_1 // 2 2:putfield #37 <Field NavigationMenuPresenter this$0> super(); // 3 5:aload_0 // 4 6:invokespecial #40 <Method void android.support.v7.widget.RecyclerView$Adapter()> // 5 9:aload_0 // 6 10:new #42 <Class ArrayList> // 7 13:dup // 8 14:invokespecial #43 <Method void ArrayList()> // 9 17:putfield #45 <Field ArrayList mItems> prepareMenuItems(); // 10 20:aload_0 // 11 21:invokespecial #48 <Method void prepareMenuItems()> // 12 24:return } }
TTOFFLINE-LEAK/ttoffline
v2.5.7/toontown/parties/ToontownTimeManager.py
<filename>v2.5.7/toontown/parties/ToontownTimeManager.py import time from datetime import datetime, timedelta, tzinfo from direct.distributed import DistributedObject from direct.directnotify import DirectNotifyGlobal from toontown.toonbase import TTLocalizer class ToontownTimeZone(tzinfo): OFFSET = -8 DST_BEGIN = datetime(1, 3, 8, 2) DST_END = datetime(1, 11, 1, 1) NAMES = ('PST', 'PDT') @staticmethod def forward_to_sunday(dt): days_to_go = 6 - dt.weekday() if days_to_go: dt += timedelta(days_to_go) return dt def dst(self, dt): beginning = self.forward_to_sunday(self.DST_BEGIN.replace(year=dt.year)) ending = self.forward_to_sunday(self.DST_END.replace(year=dt.year)) if beginning <= dt.replace(tzinfo=None) < ending: return timedelta(hours=1) return timedelta(0) return def utcoffset(self, dt): offset = timedelta(hours=self.OFFSET) offset += self.dst(dt) return offset def tzname(self, dt): standard_name, dst_name = self.NAMES if self.dst(dt): return dst_name return standard_name class UTC(tzinfo): def utcoffset(self, dt): return timedelta(0) def tzname(self, dt): return 'UTC' def dst(self, dt): return timedelta(0) class ToontownTimeManager(DistributedObject.DistributedObject): notify = DirectNotifyGlobal.directNotify.newCategory('ToontownTimeManager') ClockFormat = '%I:%M:%S %p' formatStr = '%Y-%m-%d %H:%M:%S' def __init__(self, serverTimeUponLogin=0, clientTimeUponLogin=0, globalClockRealTimeUponLogin=0): self.serverTimeZone = ToontownTimeZone() self.updateLoginTimes(serverTimeUponLogin, clientTimeUponLogin, globalClockRealTimeUponLogin) self.debugSecondsAdded = 0 def updateLoginTimes(self, serverTimeUponLogin, clientTimeUponLogin, globalClockRealTimeUponLogin): self.serverTimeUponLogin = serverTimeUponLogin self.clientTimeUponLogin = clientTimeUponLogin self.globalClockRealTimeUponLogin = globalClockRealTimeUponLogin naiveTime = datetime.utcfromtimestamp(self.serverTimeUponLogin) self.serverDateTime = datetime.fromtimestamp(self.serverTimeUponLogin, self.serverTimeZone) def getCurServerDateTime(self): secondsPassed = globalClock.getRealTime() - self.globalClockRealTimeUponLogin + self.debugSecondsAdded curDateTime = (self.serverDateTime + timedelta(seconds=secondsPassed)).astimezone(self.serverTimeZone) return curDateTime def getRelativeServerDateTime(self, timeOffset): secondsPassed = globalClock.getRealTime() - self.globalClockRealTimeUponLogin + self.debugSecondsAdded secondsPassed += timeOffset curDateTime = (self.serverDateTime + timedelta(seconds=secondsPassed)).astimezone(self.serverTimeZone) return curDateTime def getCurServerDateTimeForComparison(self): secondsPassed = globalClock.getRealTime() - self.globalClockRealTimeUponLogin + self.debugSecondsAdded curDateTime = self.serverDateTime + timedelta(seconds=secondsPassed) curDateTime = curDateTime.replace(tzinfo=self.serverTimeZone) return curDateTime def getCurServerTimeStr(self): curDateTime = self.getCurServerDateTime() result = curDateTime.strftime(self.ClockFormat) if result[0] == '0': result = result[1:] return result def setDebugSecondsAdded(self, moreSeconds): self.debugSecondsAdded = moreSeconds def debugTest(self): startTime = datetime.today() serverTzInfo = self.serverTimeZone startTime = startTime.replace(tzinfo=serverTzInfo) self.notify.info('startTime = %s' % startTime) serverTime = self.getCurServerDateTime() self.notify.info('serverTime = %s' % serverTime) result = startTime <= serverTime self.notify.info('start < serverTime %s' % result) startTime1MinAgo = startTime + timedelta(minutes=-1) self.notify.info('startTime1MinAgo = %s' % startTime1MinAgo) result2 = startTime1MinAgo <= serverTime self.notify.info('startTime1MinAgo < serverTime %s' % result2) serverTimeForComparison = self.getCurServerDateTimeForComparison() self.notify.info('serverTimeForComparison = %s' % serverTimeForComparison) result3 = startTime1MinAgo <= serverTimeForComparison self.notify.info('startTime1MinAgo < serverTimeForComparison %s' % result3) def convertStrToToontownTime(self, dateStr): curDateTime = self.getCurServerDateTime() try: curDateTime = datetime.fromtimestamp(time.mktime(time.strptime(dateStr, self.formatStr)), self.serverTimeZone) except: self.notify.warning('error parsing date string=%s' % dateStr) result = curDateTime return result def convertUtcStrToToontownTime(self, dateStr): curDateTime = self.getCurServerDateTime() try: timeTuple = time.strptime(dateStr, self.formatStr) utcDateTime = datetime(timeTuple[0], timeTuple[1], timeTuple[2], timeTuple[3], timeTuple[4], timeTuple[5], timeTuple[6], UTC()) curDateTime = utcDateTime.astimezone(self.serverTimeZone) except: self.notify.warning('error parsing date string=%s' % dateStr) result = curDateTime return result
meggsimum/masterportal-mirror
src/core/maps/store/actions/actionsMapLayers.js
<reponame>meggsimum/masterportal-mirror import VectorLayer from "ol/layer/Vector.js"; import VectorSource from "ol/source/Vector.js"; export default { /** * Creates a new vector layer and adds it to the map. * If it already exists, this layer is returned. * @param {Object} param store context. * @param {Object} param.state the state. * @param {Object} param.dispatch the dispatch. * @param {String} name The name and the id for the layer. * @returns {module:ol/layer} The created or the already existing layer. */ createLayer ({state, dispatch}, name) { const layerList = state.layerList; let resultLayer = layerList.find(layer => { return layer.get("name") === name; }); if (resultLayer !== undefined) { return resultLayer; } resultLayer = new VectorLayer({ id: name, name: name, source: new VectorSource(), zIndex: 999 }); dispatch("addLayer", resultLayer); return resultLayer; }, /** * Adds a layer to the map. * Layers with the attribute "alwaysOnTop": true are set on top of the map. * @param {Object} param store context. * @param {Object} param.dispatch the dispatch. * @param {Object} param.getters the getters. * @param {module:ol/layer/Base~BaseLayer} layer The layer to add. * @returns {void} */ addLayer ({dispatch, getters}, layer) { layer.setZIndex(getters.get2DMap.getLayers().getLength()); getters.get2DMap.addLayer(layer); dispatch("setLayersAlwaysOnTop", getters.get2DMap.getLayers()); }, /** * Pushes layers with the attribute: "alwaysOnTop" to the top of the layer collection. * @param {Object} state state object * @param {module:ol/Collection~Collection} layers Layer Collection. * @returns {void} */ setLayersAlwaysOnTop (state, layers) { layers.forEach(layer => { if (layer.get("alwaysOnTop") === true) { layer.setZIndex(layers.getLength()); } }); }, /** * Adds a layer with a zIndex to the map. * If the layer already exists, only the zIndex of the layer will be reset. * Layers with the attribute "alwaysOnTop": true are set on top of the map. * @param {Object} param store context. * @param {Object} param.dispatch the dispatch. * @param {Object} param.getters the getters. * @param {Object} payload parameter object. * @param {module:ol/layer/Base~BaseLayer} payload.layer The layer to add. * @param {Number} payload.zIndex The zIndex of the layer. * @returns {void} */ addLayerToIndex ({dispatch, getters}, {layer, zIndex}) { layer.setZIndex(zIndex); if (!getters.get2DMap.getLayers().getArray().includes(layer)) { dispatch("addLayer", layer); } dispatch("setLayersAlwaysOnTop", getters.get2DMap.getLayers()); }, /** * Adds a layer on top of the map * Layers with the attribute "alwaysOnTop": true are set on top of the map. * @param {Object} param store context. * @param {Object} param.dispatch the dispatch. * @param {Object} param.getters the getters. * @param {module:ol/layer/Base~BaseLayer} layer The layer to add. * @returns {void} */ addLayerOnTop ({dispatch, getters}, layer) { dispatch("addLayerToIndex", {layer: layer, zIndex: getters.get2DMap.getLayers().getLength()}); }, /** * Checks if the layer with the given name already exists and uses it, * creates a new layer and returns it if not. * @param {Object} param store context. * @param {Object} param.getters the getters. * @param {Object} param.dispatch the dispatch. * @param {String} layerName The name of the layer to check. * @param {Boolean} [alwaysOnTop=true] Layers with the attribute "alwaysOnTop": true are set on top of the map. * @returns {module:ol/layer/Base~BaseLaye} the found layer or a new layer with the given name. */ async addNewLayerIfNotExists ({getters, dispatch}, {layerName, alwaysOnTop = true}) { let resultLayer = await getters.getLayerByName(layerName); if (!resultLayer) { resultLayer = new VectorLayer({ id: layerName, name: layerName, source: new VectorSource(), alwaysOnTop: alwaysOnTop }); dispatch("addLayer", resultLayer); } return resultLayer; } };
maicongb/gerenciamentoVeiculoPolicial
src/main/java/br/gov/df/pm/domain/repository/StatusViaturaRepository.java
<gh_stars>0 package br.gov.df.pm.domain.repository; import br.gov.df.pm.domain.model.StatusViatura; public interface StatusViaturaRepository extends CustomJpaRepository<StatusViatura, Long>{ }
edmccrea/guess_the_lines
client/src/reducers/index.js
<reponame>edmccrea/guess_the_lines import { combineReducers } from 'redux'; import auth from './auth'; import picks from './picks'; import alert from './alert'; export default combineReducers({ auth, picks, alert, });
cwright7101/llvm_sarvavid
SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/examples/debruijn/debruijn23.cpp
<reponame>cwright7101/llvm_sarvavid //! [snippet1] // We include what we need for the test #include <gatb/gatb_core.hpp> /********************************************************************************/ /* */ /********************************************************************************/ int main (int argc, char* argv[]) { return EXIT_SUCCESS; } //! [snippet1]
nizovn/luna-sysmgr
hooks/webkitpy/layout_tests/port/factory.py
<reponame>nizovn/luna-sysmgr #!/usr/bin/env python # Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Factory method to retrieve the appropriate port implementation.""" import re import sys from webkitpy.layout_tests.port import builders class BuilderOptions(object): def __init__(self, builder_name): self.configuration = "Debug" if re.search(r"[d|D](ebu|b)g", builder_name) else "Release" self.builder_name = builder_name class PortFactory(object): def __init__(self, host=None): self._host = host def _port_name_from_arguments_and_options(self, **kwargs): port_to_use = kwargs.get('port_name', None) options = kwargs.get('options', None) if port_to_use is None: if sys.platform == 'win32' or sys.platform == 'cygwin': if options and hasattr(options, 'chromium') and options.chromium: port_to_use = 'chromium-win' else: port_to_use = 'win' elif sys.platform.startswith('linux'): port_to_use = 'chromium-linux' elif sys.platform == 'darwin': if options and hasattr(options, 'chromium') and options.chromium: port_to_use = 'chromium-cg-mac' # FIXME: Add a way to select the chromium-mac port. else: port_to_use = 'mac' if port_to_use is None: raise NotImplementedError('unknown port; sys.platform = "%s"' % sys.platform) return port_to_use def _get_kwargs(self, **kwargs): port_to_use = self._port_name_from_arguments_and_options(**kwargs) if port_to_use.startswith('test'): import test maker = test.TestPort elif port_to_use.startswith('dryrun'): import dryrun maker = dryrun.DryRunPort elif port_to_use.startswith('mock-'): import mock_drt maker = mock_drt.MockDRTPort elif port_to_use.startswith('mac'): import mac maker = mac.MacPort elif port_to_use.startswith('win'): import win maker = win.WinPort elif port_to_use.startswith('gtk'): import gtk maker = gtk.GtkPort elif port_to_use.startswith('qt'): import qt maker = qt.QtPort elif port_to_use.startswith('chromium-gpu'): import chromium_gpu maker = chromium_gpu.get elif port_to_use.startswith('chromium-mac') or port_to_use.startswith('chromium-cg-mac'): import chromium_mac maker = chromium_mac.ChromiumMacPort elif port_to_use.startswith('chromium-linux'): import chromium_linux maker = chromium_linux.ChromiumLinuxPort elif port_to_use.startswith('chromium-win'): import chromium_win maker = chromium_win.ChromiumWinPort elif port_to_use.startswith('google-chrome'): import google_chrome maker = google_chrome.GetGoogleChromePort else: raise NotImplementedError('unsupported port: %s' % port_to_use) # Make sure that any Ports created by this factory inherit # the executive/user/filesystem from the provided host. # FIXME: Eventually NRWT will use a Host object and Port will no longer store these pointers. if self._host: kwargs.setdefault('executive', self._host.executive) kwargs.setdefault('user', self._host.user) kwargs.setdefault('filesystem', self._host.filesystem) return maker(**kwargs) def all_port_names(self): """Return a list of all valid, fully-specified, "real" port names. This is the list of directories that are used as actual baseline_paths() by real ports. This does not include any "fake" names like "test" or "mock-mac", and it does not include any directories that are not .""" # FIXME: There's probably a better way to generate this list ... return builders.all_port_names() def get(self, port_name=None, options=None, **kwargs): """Returns an object implementing the Port interface. If port_name is None, this routine attempts to guess at the most appropriate port on this platform.""" # Wrapped for backwards-compatibility if port_name: kwargs['port_name'] = port_name if options: kwargs['options'] = options return self._get_kwargs(**kwargs) def get_from_builder_name(self, builder_name): port_name = builders.port_name_for_builder_name(builder_name) assert(port_name) # Need to update port_name_for_builder_name port = self.get(port_name, BuilderOptions(builder_name)) assert(port) # Need to update port_name_for_builder_name return port # FIXME: These free functions are all deprecated. Callers should be using PortFactory instead. def all_port_names(): return PortFactory().all_port_names() def get(port_name=None, options=None, **kwargs): return PortFactory().get(port_name, options, **kwargs) def get_from_builder_name(builder_name): return PortFactory().get_from_builder_name(builder_name)
93million/certcache
src/extensions/certbot/normalizeMeta.js
<reponame>93million/certcache const getConfig = require('../../lib/getConfig') module.exports = async ({ ellipticCurve, keyType, isTest }) => { const config = await getConfig() ellipticCurve = ellipticCurve || config.ellipticCurve keyType = keyType || config.keyType return { ellipticCurve: (keyType === 'ecdsa') ? ellipticCurve : undefined, keyType, isTest } }
mrouffet/SPlanner
Plugins/SPlanner/Source/SPlanner/Private/SPlanner/Base/Action/SP_Action.cpp
// Copyright 2020 <NAME>. All Rights Reserved. #include <SPlanner/Base/Action/SP_Action.h>
slicht-uri/Sandshark-Beta-Lab-
vehicle/ros/src/sandshark_drivers/frontseat/bfMessage.h
#ifndef BFMESSAGE_H #define BFMESSAGE_H #include "fnmea.h" #include "ros/ros.h" #include <string> #include <vector> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> //Base for all bluefin->payload messages class bfMessage: public fMessage { public: // Format the data contained within the message into a valid NMEA message void unparse(std::string &out); // Constructor - first 2 characters are always BF, and we always send a checksum bfMessage(std::string h, int n) : fMessage(h, "BF", n, true) { } virtual ~bfMessage() { } }; // Class for the Backseat Control message // (Section 6.24 in Bluefin Standard Interface V1.12a) class ctlMessage: public bfMessage { public: void setControlState(int c); ctlMessage() : bfMessage("CTL", 1) { } }; // Class for the Navigation Update message // (Section 6.1 in Bluefin Standard Interface V1.12a) class nvgMessage: public bfMessage { public: void setLatitudeAndHemisphere(float l); void setLongitudeAndHemisphere(float l); void setPositionQuality(int q); void setAltitude(float a); void setDepth(float d); void setHeading(float h); void setRoll(float r); void setPitch(float p); void setComputedTime(ros::Time t); nvgMessage() : bfMessage("NVG", 11) { } }; // Class for the Velocity and Rate Update message // (Section 6.2 in Bluefin Standard Interface V1.12a) class nvrMessage: public bfMessage { public: void setEastVelocity(float e); void setWestVelocity(float w); void setDownVelocity(float d); void setPitchRate(float p); void setRollRate(float r); void setHeadingRate(float h); nvrMessage() : bfMessage("NVR", 6) { } }; // Class for the Payload Shutdown message // (Section 5.2 in Bluefin Standard Interface V1.12a) class shtMessage: public bfMessage { public: //sht message has no fields shtMessage() : bfMessage("SHT", 0) { } }; // Class for the Mission Status message // (Section 6.11 in Bluefin Standard Interface V1.12a) class misMessage: public bfMessage { public: void setDiveFile(std::string d); void setMissionStatus(std::string m); void setAdditionalStatus(std::string a); misMessage() : bfMessage("MIS", 3) { } }; // Class for the Message Acknowledgement message // (Section 6.21 in Bluefin Standard Interface V1.12a) class ackMessage: public bfMessage { public: void setAckHeader(std::string a); void setReceivedTimestamp(std::string t); void setCommandID(int i); void setAckStatusCode(int s); void setDescription(std::string s); ackMessage() : bfMessage("ACK", 6) { _body[4] = "0"; //field 5 is reserved for now and fixed at "0" } }; // Class for the Vehicle Interface Version message // (Section 5.7 in Bluefin Standard Interface V1.12a) class verMessageF: public bfMessage { public: void setVersionString(std::string v); verMessageF() : bfMessage("VER", 1) { } }; #endif
dialogs/dialog-web-components
src/components/SidebarMenuProfile/SidebarMenuProfile.js
<filename>src/components/SidebarMenuProfile/SidebarMenuProfile.js /* * Copyright 2019 dialog LLC <<EMAIL>> * @flow */ import type { AvatarPlaceholder, UserStatusType } from '@dlghq/dialog-types'; import React, { PureComponent } from 'react'; import classNames from 'classnames'; import Avatar from '../Avatar/Avatar'; import { PeerInfoTitle } from '../PeerInfoTitle/PeerInfoTitle'; import UserStatus from '../UserStatus/UserStatus'; import styles from './SidebarMenuProfile.css'; type Props = { className?: string, name: string, avatar: ?string, placeholder: AvatarPlaceholder, status: UserStatusType, }; class SidebarMenuProfile extends PureComponent<Props> { render() { const { name, avatar, placeholder, status } = this.props; const className = classNames(styles.container, this.props.className); return ( <div className={className}> <Avatar size={42} title={name} image={avatar} placeholder={placeholder} className={styles.avatar} /> <div className={styles.info}> <PeerInfoTitle title={name} className={styles.title} emojiSize={16} /> <UserStatus status={status} className={styles.status} dotClassName={styles.dot} statusClassName={styles.status} /> </div> </div> ); } } export default SidebarMenuProfile;
talmeym/regurgitator-core
src/main/java/com/emarte/regurgitator/core/ContainsBehaviour.java
<reponame>talmeym/regurgitator-core /* * Copyright (C) 2017 <NAME>. * Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT). */ package com.emarte.regurgitator.core; import static com.emarte.regurgitator.core.Log.getLog; public final class ContainsBehaviour implements ConditionBehaviour { private static final Log log = getLog(ContainsBehaviour.class); @Override @SuppressWarnings("unchecked") public boolean evaluate(Parameter parameter, Message message, String conditionValue, boolean expectation) { boolean contains = false; if(parameter != null) { ParameterType parameterType = parameter.getType(); contains = parameterType.contains(parameter.getValue(), parameterType.convert(conditionValue)); } log.debug("Parameter " + (contains ? "contain" : "does not contain") + " value '{}'", conditionValue); return contains == expectation; } }
HazelChen/directory-kerberos
3rdparty/not-yet-commons-ssl/src/main/java/org/apache/commons/ssl/asn1/DERUTF8String.java
<gh_stars>1-10 package org.apache.commons.ssl.asn1; import java.io.IOException; /** DER UTF8String object. */ public class DERUTF8String extends ASN1Object implements DERString { String string; /** * return an UTF8 string from the passed in object. * * @throws IllegalArgumentException if the object cannot be converted. */ public static DERUTF8String getInstance(Object obj) { if (obj == null || obj instanceof DERUTF8String) { return (DERUTF8String) obj; } if (obj instanceof ASN1OctetString) { return new DERUTF8String(((ASN1OctetString) obj).getOctets()); } if (obj instanceof ASN1TaggedObject) { return getInstance(((ASN1TaggedObject) obj).getObject()); } throw new IllegalArgumentException("illegal object in getInstance: " + obj.getClass().getName()); } /** * return an UTF8 String from a tagged object. * * @param obj the tagged object holding the object we want * @param explicit true if the object is meant to be explicitly tagged false * otherwise. * @throws IllegalArgumentException if the tagged object cannot be converted. */ public static DERUTF8String getInstance( ASN1TaggedObject obj, boolean explicit) { return getInstance(obj.getObject()); } /** basic constructor - byte encoded string. */ DERUTF8String(byte[] string) { this.string = Strings.fromUTF8ByteArray(string); } /** basic constructor */ public DERUTF8String(String string) { this.string = string; } public String getString() { return string; } public String toString() { return string; } public int hashCode() { return this.getString().hashCode(); } boolean asn1Equals(DERObject o) { if (!(o instanceof DERUTF8String)) { return false; } DERUTF8String s = (DERUTF8String) o; return this.getString().equals(s.getString()); } void encode(DEROutputStream out) throws IOException { out.writeEncoded(UTF8_STRING, Strings.toUTF8ByteArray(string)); } }
KanegaeGabriel/ye-olde-interview-prep-grind
LeetCode/0237_delete_node_in_ll.py
class Node: def __init__(self, val): self.val = val self.next = None def deleteNode(node): node.val = node.next.val node.next = node.next.next root = Node(1) root.next = Node(2) root.next.next = Node(3) root.next.next.next = Node(4) root.next.next.next.next = Node(5) deleteNode(root.next.next) p = root while p: print(p.val, end=" ") p = p.next print()
mikchaos/whoville
whoville/cloudbreak/models/reinstall_request_v2.py
<reponame>mikchaos/whoville # coding: utf-8 """ Cloudbreak API Cloudbreak is a powerful left surf that breaks over a coral reef, a mile off southwest the island of Tavarua, Fiji. Cloudbreak is a cloud agnostic Hadoop as a Service API. Abstracts the provisioning and ease management and monitoring of on-demand clusters. SequenceIQ's Cloudbreak is a RESTful application development platform with the goal of helping developers to build solutions for deploying Hadoop YARN clusters in different environments. Once it is deployed in your favourite servlet container it exposes a REST API allowing to span up Hadoop clusters of arbitary sizes and cloud providers. Provisioning Hadoop has never been easier. Cloudbreak is built on the foundation of cloud providers API (Amazon AWS, Microsoft Azure, Google Cloud Platform, Openstack), Apache Ambari, Docker lightweight containers, Swarm and Consul. For further product documentation follow the link: <a href=\"http://hortonworks.com/apache/cloudbreak/\">http://hortonworks.com/apache/cloudbreak/</a> OpenAPI spec version: 2.7.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six import iteritems import re class ReinstallRequestV2(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'instance_groups': 'list[InstanceGroupsV2]', 'ambari_stack_details': 'AmbariStackDetails', 'blueprint_name': 'str', 'kerberos_password': 'str', 'kerberos_principal': 'str' } attribute_map = { 'instance_groups': 'instanceGroups', 'ambari_stack_details': 'ambariStackDetails', 'blueprint_name': 'blueprintName', 'kerberos_password': '<PASSWORD>', 'kerberos_principal': 'kerberosPrincipal' } def __init__(self, instance_groups=None, ambari_stack_details=None, blueprint_name=None, kerberos_password=<PASSWORD>, kerberos_principal=None): """ ReinstallRequestV2 - a model defined in Swagger """ self._instance_groups = None self._ambari_stack_details = None self._blueprint_name = None self._kerberos_password = None self._kerberos_principal = None if instance_groups is not None: self.instance_groups = instance_groups if ambari_stack_details is not None: self.ambari_stack_details = ambari_stack_details self.blueprint_name = blueprint_name if kerberos_password is not None: self.kerberos_password = <PASSWORD> if kerberos_principal is not None: self.kerberos_principal = kerberos_principal @property def instance_groups(self): """ Gets the instance_groups of this ReinstallRequestV2. collection of instance groupst :return: The instance_groups of this ReinstallRequestV2. :rtype: list[InstanceGroupsV2] """ return self._instance_groups @instance_groups.setter def instance_groups(self, instance_groups): """ Sets the instance_groups of this ReinstallRequestV2. collection of instance groupst :param instance_groups: The instance_groups of this ReinstallRequestV2. :type: list[InstanceGroupsV2] """ self._instance_groups = instance_groups @property def ambari_stack_details(self): """ Gets the ambari_stack_details of this ReinstallRequestV2. details of the Ambari stack :return: The ambari_stack_details of this ReinstallRequestV2. :rtype: AmbariStackDetails """ return self._ambari_stack_details @ambari_stack_details.setter def ambari_stack_details(self, ambari_stack_details): """ Sets the ambari_stack_details of this ReinstallRequestV2. details of the Ambari stack :param ambari_stack_details: The ambari_stack_details of this ReinstallRequestV2. :type: AmbariStackDetails """ self._ambari_stack_details = ambari_stack_details @property def blueprint_name(self): """ Gets the blueprint_name of this ReinstallRequestV2. blueprint name for the cluster :return: The blueprint_name of this ReinstallRequestV2. :rtype: str """ return self._blueprint_name @blueprint_name.setter def blueprint_name(self, blueprint_name): """ Sets the blueprint_name of this ReinstallRequestV2. blueprint name for the cluster :param blueprint_name: The blueprint_name of this ReinstallRequestV2. :type: str """ if blueprint_name is None: raise ValueError("Invalid value for `blueprint_name`, must not be `None`") self._blueprint_name = blueprint_name @property def kerberos_password(self): """ Gets the kerberos_password of this ReinstallRequestV2. kerberos admin password :return: The kerberos_password of this ReinstallRequestV2. :rtype: str """ return self._kerberos_password @kerberos_password.setter def kerberos_password(self, kerberos_password): """ Sets the kerberos_password of this ReinstallRequestV2. kerberos admin password :param kerberos_password: The kerberos_password of this ReinstallRequestV2. :type: str """ if kerberos_password is not None and len(kerberos_password) > 50: raise ValueError("Invalid value for `kerberos_password`, length must be less than or equal to `50`") if kerberos_password is not None and len(kerberos_password) < 5: raise ValueError("Invalid value for `kerberos_password`, length must be greater than or equal to `5`") self._kerberos_password = kerberos_password @property def kerberos_principal(self): """ Gets the kerberos_principal of this ReinstallRequestV2. kerberos principal :return: The kerberos_principal of this ReinstallRequestV2. :rtype: str """ return self._kerberos_principal @kerberos_principal.setter def kerberos_principal(self, kerberos_principal): """ Sets the kerberos_principal of this ReinstallRequestV2. kerberos principal :param kerberos_principal: The kerberos_principal of this ReinstallRequestV2. :type: str """ self._kerberos_principal = kerberos_principal def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ if not isinstance(other, ReinstallRequestV2): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
kkuegler/a-collections
a-collections/src/main/java/com/ajjpj/acollections/immutable/ATreeSet.java
<filename>a-collections/src/main/java/com/ajjpj/acollections/immutable/ATreeSet.java package com.ajjpj.acollections.immutable; import com.ajjpj.acollections.*; import com.ajjpj.acollections.internal.ACollectionDefaults; import com.ajjpj.acollections.internal.ACollectionSupport; import com.ajjpj.acollections.internal.ASetDefaults; import com.ajjpj.acollections.internal.ASetSupport; import com.ajjpj.acollections.util.AOption; import java.io.Serializable; import java.util.*; import java.util.function.*; import java.util.stream.Collector; /** * This class implements immutable sets using a red-black tree, sorting elements based on a {@link Comparator} and providing a * {@link SortedSet}. * * <p> Since this is an immutable class, it does not support modifying methods from {@link java.util.Set}: Those methods return * {@code boolean} or a previous element, but in order to "modify" an immutable collection, they would need to return the new collection * instance. * * <p> So instances of this class rely on methods like {@link #plus(Object)} or {@link #minus(Object)} for adding / removing * elements. These methods return new sets with the new elements, leaving the original unmodified: * * <p>{@code ASet<Integer> s0 = ATreeSet.of(1, 2, 3);} * <p>{@code ASet<Integer> s1 = s0.plus(5);} * <p>{@code ASet<Integer> s2 = s1.minus(2);} * <p>{@code System.out.println(s0); // 1, 2, 3 } * <p>{@code System.out.println(s1); // 1, 2, 3, 5 } * <p>{@code System.out.println(s2); // 1, 3, 5 } * * <p> These calls can of course be chained: * <p>{@code ASet<Integer> s3 = s2.plus(8).plus(9).minus(3); } * <p>{@code System.out.println(s3); // 1, 5, 8, 9 } * * <p> This class has static factory methods (Java 9 style) for convenience creating instances. * * <p> Implementation note: This class is a port of Scala's standard library {@code TreeSet}. * * @param <T> the set's element type */ public class ATreeSet<T> extends AbstractImmutableCollection<T> implements ASortedSet<T>, ACollectionDefaults<T,ATreeSet<T>>, ASetDefaults<T,ATreeSet<T>>, Serializable { private final RedBlackTree.Tree<T,Object> root; private final Comparator<? super T> comparator; /** * Creates an empty {@link ATreeSet} with {@link Comparator#naturalOrder()}. * <p> This can later be modified by calling {@link #plus(Object)} or {@link #minus(Object)}. For creating a set with known elements, * calling one of the {@code of} factory methods is usually more concise. * * @param <T> the new set's element type * @return an empty {@link ATreeSet} */ public static <T extends Comparable<T>> ATreeSet<T> empty() { return empty(Comparator.<T>naturalOrder()); } /** * Creates an empty {@link ATreeSet} with a given {@link Comparator}. * <p> This can later be modified by calling {@link #plus(Object)} or {@link #minus(Object)}. For creating a set with known elements, * calling one of the {@code of} factory methods is usually more concise. * * @param comparator the new set's comparator * @param <T> the new set's element type * @return an empty {@link ATreeSet} */ public static <T> ATreeSet<T> empty(Comparator<? super T> comparator) { return new ATreeSet<>(null, comparator); } /** * This is an alias for {@link #empty()} for consistency with Java 9 conventions - it creates an empty {@link ATreeSet} with * {@link Comparator#naturalOrder()}. * * @param <T> the new set's element type * @return an empty {@link ATreeSet} */ public static <T extends Comparable<T>> ATreeSet<T> of() { return empty(); } /** * Convenience factory method creating an {@link ATreeSet} with exactly one element and {@link Comparator#naturalOrder()}. * * @param o the single element for the new set. It must implement {@link Comparable} to work with {@link Comparator#naturalOrder()}. * @param <T> the new set's element type (can often be inferred from the parameter by the compiler) * @return the new {@link ATreeSet} */ public static <T extends Comparable<T>> ATreeSet<T> of(T o) { return ATreeSet .<T>builder() .add(o) .build(); } /** * Convenience factory method creating an {@link ATreeSet} with exactly two elements and {@link Comparator#naturalOrder()}. * * @param o1 the first element for the new set. It must implement {@link Comparable} to work with {@link Comparator#naturalOrder()}. * @param o2 the second element for the new set. It must implement {@link Comparable} to work with {@link Comparator#naturalOrder()}. * @param <T> the new set's element type (can often be inferred from the parameter by the compiler) * @return the new {@link ATreeSet} */ public static <T extends Comparable<T>> ATreeSet<T> of(T o1, T o2) { return ATreeSet .<T>builder() .add(o1) .add(o2) .build(); } /** * Convenience factory method creating an {@link ATreeSet} with exactly three elements and {@link Comparator#naturalOrder()}. * * @param o1 the first element for the new set. It must implement {@link Comparable} to work with {@link Comparator#naturalOrder()}. * @param o2 the second element for the new set. It must implement {@link Comparable} to work with {@link Comparator#naturalOrder()}. * @param o3 the third element for the new set. It must implement {@link Comparable} to work with {@link Comparator#naturalOrder()}. * @param <T> the new set's element type (can often be inferred from the parameter by the compiler) * @return the new {@link ATreeSet} */ public static <T extends Comparable<T>> ATreeSet<T> of(T o1, T o2, T o3) { return ATreeSet .<T>builder() .add(o1) .add(o2) .add(o3) .build(); } /** * Convenience factory method creating an {@link ATreeSet} with exactly four elements and {@link Comparator#naturalOrder()}. * * @param o1 the first element for the new set. It must implement {@link Comparable} to work with {@link Comparator#naturalOrder()}. * @param o2 the second element for the new set. It must implement {@link Comparable} to work with {@link Comparator#naturalOrder()}. * @param o3 the third element for the new set. It must implement {@link Comparable} to work with {@link Comparator#naturalOrder()}. * @param o4 the fourth element for the new set. It must implement {@link Comparable} to work with {@link Comparator#naturalOrder()}. * @param <T> the new set's element type (can often be inferred from the parameter by the compiler) * @return the new {@link ATreeSet} */ public static <T extends Comparable<T>> ATreeSet<T> of(T o1, T o2, T o3, T o4) { return ATreeSet .<T>builder() .add(o1) .add(o2) .add(o3) .add(o4) .build(); } /** * Convenience factory method creating an {@link ATreeSet} with more than four elements and {@link Comparator#naturalOrder()}. * * @param o1 the first element for the new set. It must implement {@link Comparable} to work with {@link Comparator#naturalOrder()}. * @param o2 the second element for the new set. It must implement {@link Comparable} to work with {@link Comparator#naturalOrder()}. * @param o3 the third element for the new set. It must implement {@link Comparable} to work with {@link Comparator#naturalOrder()}. * @param o4 the fourth element for the new set. It must implement {@link Comparable} to work with {@link Comparator#naturalOrder()}. * @param o5 the fifth element for the new set. It must implement {@link Comparable} to work with {@link Comparator#naturalOrder()}. * @param others the (variable number of) additional elements * @param <T> the new set's element type (can often be inferred from the parameter by the compiler) * @return the new {@link ATreeSet} */ @SafeVarargs public static <T extends Comparable<T>> ATreeSet<T> of(T o1, T o2, T o3, T o4, T o5, T... others) { return ATreeSet .<T>builder() .add(o1) .add(o2) .add(o3) .add(o4) .add(o5) .addAll(others) .build(); } /** * Creates a new {@link ATreeSet} based on an array's elements. * * @param that the array from which the new set is initialized * @param <T> the set's element type * @return the new set */ public static <T extends Comparable<T>> ATreeSet<T> from(T[] that) { return from(that, Comparator.naturalOrder()); } /** * Creates a new {@link ATreeSet} based on an array's elements with a given {@link Comparator}. * * @param that the array from which the new set is initialized * @param comparator the new set's comparator * @param <T> the set's element type * @return the new set */ public static <T> ATreeSet<T> from(T[] that, Comparator<? super T> comparator) { return fromIterator(Arrays.asList(that).iterator(), comparator); } /** * Creates a new {@link ATreeSet} based on an {@link Iterable}'s elements. * * @param that the {@link Iterable} from which the new set is initialized * @param <T> the set's element type * @return the new set */ public static <T extends Comparable<T>> ATreeSet<T> from(Iterable<T> that) { return from(that, Comparator.naturalOrder()); } /** * Creates a new {@link ATreeSet} based on an {@link Iterable}'s elements with a given {@link Comparator}. * * @param that the {@link Iterable} from which the new set is initialized * @param comparator the new set's comparator * @param <T> the set's element type * @return the new set */ public static <T> ATreeSet<T> from(Iterable<T> that, Comparator<? super T> comparator) { return ATreeSet.<T>builder(comparator).addAll(that).build(); } /** * Creates a new {@link ATreeSet} based on an {@link Iterator}'s elements. * * @param it the {@link Iterator} from which the new set is initialized * @param <T> the set's element type * @return the new set */ public static <T extends Comparable<T>> ATreeSet<T> fromIterator(Iterator<T> it) { return fromIterator(it, Comparator.naturalOrder()); } /** * Creates a new {@link ATreeSet} based on an {@link Iterator}'s elements with a given {@link Comparator}. * * @param it the {@link Iterator} from which the new set is initialized * @param comparator the new set's comparator * @param <T> the set's element type * @return the new set */ public static <T> ATreeSet<T> fromIterator(Iterator<T> it, Comparator<? super T> comparator) { return ATreeSet.<T>builder(comparator).addAll(it).build(); } /** * Returns a new {@link ACollectionBuilder} for building an ATreeSet efficiently and in a generic manner. * * @param comparator the builder's comparator * @param <T> the builder's element type * @return an new {@link ACollectionBuilder} */ public static <T> Builder<T> builder(Comparator<? super T> comparator) { return new Builder<>(comparator); } private ATreeSet (RedBlackTree.Tree<T, Object> root, Comparator<? super T> comparator) { this.root = root; this.comparator = comparator; } /** * Returns a new {@link ACollectionBuilder} for building an ATreeSet efficiently and in a generic manner. The builder uses * {@link Comparator#naturalOrder()}. * * @param <T> the builder's element type * @return an new {@link ACollectionBuilder} */ public static <T extends Comparable<T>> Builder<T> builder() { return builder(Comparator.<T>naturalOrder()); } @Override public Comparator<? super T> comparator () { return comparator; } @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") @Override public boolean equals (Object o) { return ASetSupport.equals(this, o); } @Override public int hashCode() { return ASetSupport.hashCode(this); } @Override public String toString () { return ACollectionSupport.toString(ATreeSet.class, this); } @Override public AHashSet<T> toSet () { return AHashSet.from(this); } @Override public ATreeSet<T> plus (T o) { return new ATreeSet<>(RedBlackTree.update(root, o, null, true, comparator), comparator); } @Override public ATreeSet<T> minus (T o) { return new ATreeSet<>(RedBlackTree.delete(root, o, comparator), comparator); } @Override public ATreeSet<T> union (Iterable<? extends T> that) { ATreeSet<T> result = this; for (T o: that) result = result.plus(o); return result; } @Override public ATreeSet<T> intersect (Set<T> that) { return filter(that::contains); } @Override public ATreeSet<T> diff (Set<T> that) { ATreeSet<T> result = this; for (T o: that) result = result.minus(o); return result; } @Override public int countInRange (AOption<T> from, boolean fromInclusive, AOption<T> to, boolean toInclusive) { return RedBlackTree.countInRange(root, from, fromInclusive, to, toInclusive, comparator); } @Override public ATreeSet<T> range (AOption<T> from, boolean fromInclusive, AOption<T> to, boolean toInclusive) { return new ATreeSet<>(RedBlackTree.rangeImpl(root, from, fromInclusive, to, toInclusive, comparator), comparator); } @Override public ASortedSet<T> drop (int n) { return new ATreeSet<>(RedBlackTree.drop(root, n), comparator); } @Override public ASortedSet<T> take (int n) { return new ATreeSet<>(RedBlackTree.take(root, n), comparator); } /** * relative to *natural* order, which may or may not be the tree's order */ @Override public T min () { if (comparator.equals(Comparator.naturalOrder())) return smallest().orElseThrow(NoSuchElementException::new); else return ACollectionDefaults.super.min(); } /** * relative to *natural* order, which may or may not be the tree's order */ @Override public T max () { if (comparator.equals(Comparator.naturalOrder())) return greatest().orElseThrow(NoSuchElementException::new); else return ACollectionDefaults.super.max(); } @Override public AOption<T> smallest () { final RedBlackTree.Tree<T,?> raw = RedBlackTree.smallest(root); return raw == null ? AOption.none() : AOption.some(raw.key); } @Override public AOption<T> greatest () { final RedBlackTree.Tree<T,?> raw = RedBlackTree.greatest(root); return raw == null ? AOption.none() : AOption.some(raw.key); } @Override public AIterator<T> iterator (AOption<T> from, boolean fromInclusive, AOption<T> to, boolean toInclusive) { return RedBlackTree.keysIterator(root, from, fromInclusive, to, toInclusive, comparator); } @Override public AIterator<T> iterator () { return RedBlackTree.keysIterator(root, AOption.none(), true, AOption.none(), false, comparator); } @Override public <U> ACollectionBuilder<U, ATreeSet<U>> newBuilder () { //noinspection unchecked return new Builder<U>((Comparator) comparator); //TODO this is somewhat hacky - better way? } @Override public boolean isEmpty () { return root == null; } @Override public <U> ATreeSet<U> map (Function<T, U> f) { return ACollectionSupport.map(newBuilder(), this, f); } @Override public <U> ATreeSet<U> flatMap (Function<T, Iterable<U>> f) { return ACollectionSupport.flatMap(newBuilder(), this, f); } @Override public <U> ATreeSet<U> collect (Predicate<T> filter, Function<T, U> f) { return ACollectionSupport.collect(newBuilder(), this, filter, f); } @Override public ATreeSet<T> filter (Predicate<T> f) { return ACollectionDefaults.super.filter(f); } @Override public ATreeSet<T> filterNot (Predicate<T> f) { return ACollectionDefaults.super.filterNot(f); } @Override public <K> AMap<K, ATreeSet<T>> groupBy (Function<T, K> keyExtractor) { return ACollectionDefaults.super.groupBy(keyExtractor); } @Override public int size () { return RedBlackTree.count(root); } @Override public boolean contains (Object o) { //noinspection unchecked return RedBlackTree.lookup(root, (T) o, comparator) != null; } @Override public AIterator<ATreeSet<T>> subsets () { return ASetDefaults.super.subsets(); } @Override public AIterator<ATreeSet<T>> subsets (int len) { return ASetDefaults.super.subsets(len); } @Override public boolean containsAll (Collection<?> c) { return ACollectionDefaults.super.containsAll(c); } @Override public ATreeSet<T> subSet (T fromElement, T toElement) { return (ATreeSet<T>) ASortedSet.super.subSet(fromElement, toElement); } @Override public ATreeSet<T> headSet (T toElement) { return (ATreeSet<T>) ASortedSet.super.headSet(toElement); } @Override public ATreeSet<T> tailSet (T fromElement) { //TODO test this return (ATreeSet<T>) ASortedSet.super.tailSet(fromElement); } //TODO test these @Override public T lower (T t) { final AIterator<T> it = RedBlackTree.reverseKeysIterator(root, AOption.some(t), false, AOption.none(), false, comparator); return it.hasNext() ? it.next() : null; } @Override public T floor (T t) { final AIterator<T> it = RedBlackTree.reverseKeysIterator(root, AOption.some(t), true, AOption.none(), false, comparator); return it.hasNext() ? it.next() : null; } @Override public T ceiling (T t) { final AIterator<T> it = iterator(AOption.some(t), true, AOption.none(), false); if (it.hasNext()) return it.next(); return null; } @Override public T higher (T t) { final AIterator<T> it = iterator(AOption.some(t), false, AOption.none(), false); if (it.hasNext()) return it.next(); return null; } @Override public T pollFirst () { throw new UnsupportedOperationException("mutable operation on an immutable collection"); } @Override public T pollLast () { throw new UnsupportedOperationException("mutable operation on an immutable collection"); } @Override public ASortedSet<T> descendingSet () { return ATreeSet.from(this, comparator.reversed()); } @Override public AIterator<T> descendingIterator () { return RedBlackTree.reverseKeysIterator(root, AOption.none(), true, AOption.none(), false, comparator); } @Override public ASortedSet<T> subSet (T fromElement, boolean fromInclusive, T toElement, boolean toInclusive) { return new ATreeSet<>(RedBlackTree.range(root, fromElement, fromInclusive, toElement, toInclusive, comparator), comparator); } @Override public ASortedSet<T> headSet (T toElement, boolean inclusive) { return new ATreeSet<>(RedBlackTree.to(root, toElement, inclusive, comparator), comparator); } @Override public ASortedSet<T> tailSet (T fromElement, boolean inclusive) { return new ATreeSet<>(RedBlackTree.from(root, fromElement, inclusive, comparator), comparator); } /** * Returns a {@link Collector} to collect {@link java.util.stream.Stream} elements into an ATreeSet. * * @param <T> the stream's element type * @return a {@link Collector} to collect a stream's elements into an ATreeSet */ public static <T extends Comparable<T>> Collector<T, Builder<T>, ATreeSet<T>> streamCollector() { final Supplier<Builder<T>> supplier = ATreeSet::builder; final BiConsumer<Builder<T>, T> accumulator = Builder::add; final BinaryOperator<Builder<T>> combiner = (b1, b2) -> { b1.addAll(b2.build()); return b1; }; final Function<Builder<T>, ATreeSet<T>> finisher = Builder::build; return Collector.of(supplier, accumulator, combiner, finisher); } public static class Builder<T> implements ACollectionBuilder<T,ATreeSet<T>> { private RedBlackTree.Tree<T,Object> root = null; private final Comparator<? super T> comparator; public Builder (Comparator<? super T> comparator) { this.comparator = comparator; } @Override public ACollectionBuilder<T, ATreeSet<T>> add (T el) { root = RedBlackTree.update(root, el, null, true, comparator); return this; } @Override public ATreeSet<T> build () { return new ATreeSet<>(root, comparator); } } }
erick-jaimes/sistop-2020-2
proyectos/2/AlcantaraCarlosJimenezEduardo/archivosFuente/GUI/Persona.java
package GUI; // @Author: <NAME> <NAME> & <NAME> <NAME> public class Persona extends Thread{ private String nombre; private JuegoMecanico juego; private Cola colaEntrarAlJuego; private Cola colaSalirDelVagon; public Persona(String nombre,JuegoMecanico juego){ this.nombre=nombre; this.juego=juego; this.colaEntrarAlJuego=this.juego.getCola(); } public void setJuego(JuegoMecanico juego){ this.juego=juego; this.colaEntrarAlJuego=this.juego.getCola(); } @Override public void run(){ print("Voy a pasar al juego "+this.juego.getNombre()); this.colaEntrarAlJuego.formarCola(); //la persona se va a formar en la cola //decidimos que si el juego no esta operando, se va a ir. Si esta funcionando, se forma en la cola de salida del vagon if(this.juego.isJuegoOperando()==false){ print("Me voy"); }else{ this.colaSalirDelVagon=this.juego.getColaSalida(); print("Wohooooo"); this.colaSalirDelVagon.formarCola(); } //termina la visita al juego. print("Termine mi visita"); } private void print(String s){ System.out.println("++++Persona "+nombre+": "+s); } }
coypanglei/nanjinJianduo
app/src/main/java/com/shaoyue/weizhegou/module/address/adapter/ShippingAdapter.java
package com.shaoyue.weizhegou.module.address.adapter; import android.support.annotation.Nullable; import android.widget.TextView; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.shaoyue.weizhegou.R; import com.shaoyue.weizhegou.entity.center.AddressListBean; import java.util.List; /** * 作者:PangLei on 2019/4/12 0012 13:55 * <p> * 邮箱:<EMAIL> */ public class ShippingAdapter extends BaseQuickAdapter<AddressListBean, BaseViewHolder> { private String type; public ShippingAdapter(String type) { super(R.layout.item_shipping_address); this.type = type; } @Override protected void convert(BaseViewHolder helper, AddressListBean item) { helper.setText(R.id.tv_name, item.getConsignee()); helper.setText(R.id.tv_phone, item.getMobile()); helper.setText(R.id.tv_area, item.getArea().replaceAll(",", " ") + " " + item.getAddress()); TextView textView = helper.getView(R.id.tv_set_default); if (type.equals("1")) { helper.setGone(R.id.tv_delete, false); } else { helper.setVisible(R.id.tv_delete, true); } if (item.getIs_default() == 0) { textView.setText("默认地址"); textView.setTextColor(mContext.getResources().getColor(R.color.color_4a4a4a)); helper.setImageResource(R.id.iv_select, R.drawable.icon_select_cancel); } else { textView.setText("已设置为默认地址"); textView.setTextColor(mContext.getResources().getColor(R.color.color_cd0946)); helper.setImageResource(R.id.iv_select, R.drawable.icon_select_ok); } helper.addOnClickListener(R.id.tv_delete); helper.addOnClickListener(R.id.tv_edit); helper.addOnClickListener(R.id.iv_select); helper.addOnClickListener(R.id.tv_set_default); } }
vgauri1797/Eclipse
WebAppBuilderForArcGIS/client/stemapp3d/widgets/3DFx/setting/nls/id/strings.js
<filename>WebAppBuilderForArcGIS/client/stemapp3d/widgets/3DFx/setting/nls/id/strings.js define({ "viz_settings": "Pengaturan visualisasi", "viz_type": "Jenis visualisasi", "max_height": "Tinggi Simbol Maks (meter)", "max_width": "Lebar simbol Maks (meter)", "interval": "Interval (milidetik)", "show_percent": "Perlihatkan nilai sebagai persentase semua nilai", "show_jettrail_end_points": "Tampilkan titik akhir", "show_percentage_limited": "Ini dinonaktifkan karena jumlah record lebih besar dari 400.", "cycle_colors": "Ubah warna secara otomatis", "area_extrusion": "Ekstrusi area", "bounce": "Bounce", "fireball": "Fireball", "grid_surface": " Permukaan grid", "jet_trail": "Jejak jet", "point_extrusion": "Ekstrusi titik", "pulse": "Pulse", "layer_settings": "Pengaturan layer", "viz_layer": "Layer visualisasi", "display_field": "Kolom tampilan", "add_field": "Tambahkan kolom visualisasi", "field": "Kolom", "label": "Label", "actions": "Tindakan", "no_layers": " Tidak tersedia layer pada web scene terpilih.", "viz_not_supported": "Tidak didukung untuk jenis geometri dari layer terpilih." });
zyzisyz/OJ
acwing/0789.cpp
#include<iostream> #include<algorithm> #include<vector> using namespace std; int main(void){ int n,q; cin>>n>>q; vector<int> table(n, 0); for(int i=0; i<n; i++){ cin>>table[i]; } for(int i=0; i<q; i++){ int k; cin>>k; auto pos = lower_bound(table.begin(), table.end(), k); if(pos!=table.end() && *pos==k){ cout<<distance(table.begin(), pos); }else{ cout<<"-1 -1"<<endl; continue; } pos = upper_bound(table.begin(), table.end(), k); cout<<" "; cout<<distance(table.begin(), pos)-1<<endl; } }
alegione/CodonShuffle
lib/ViennaRNA-2.1.9/doc/html/structpu__out.js
var structpu__out = [ [ "len", "structpu__out.html#a314b8f43c3ee0bf6060afbeced5dbe6c", null ], [ "u_vals", "structpu__out.html#a7697bc7a46cd1b8e37e337e708cb6023", null ], [ "contribs", "structpu__out.html#a638b0de1837cfd441871d005d3ab2938", null ], [ "header", "structpu__out.html#ac9e9e30b16e7d04c770460b8487fb09d", null ], [ "u_values", "structpu__out.html#a366edbc4170d5c177908e178ff340828", null ] ];
seanders/npr_bumps
app/controllers/person_controller.rb
class PersonController < ApplicationController before_filter :require_person before_filter :require_auth, only: [:show] def show @playlists = @person.playlists end end
wyaadarsh/LeetCode-Solutions
Java/0207-Course-Schedule/soln.java
<reponame>wyaadarsh/LeetCode-Solutions class Solution { public boolean canFinish(int numCourses, int[][] prerequisites) { int[] degrees = new int[numCourses]; Stack<Integer> frees = new Stack<>(); ArrayList<Integer>[] graph = new ArrayList[numCourses]; for(int i = 0; i < numCourses; ++i) graph[i] = new ArrayList<>(); for(int [] ab : prerequisites) { int a = ab[0], b = ab[1]; ++degrees[a]; graph[b].add(a); } for(int i = 0; i < numCourses; ++i) { if (degrees[i] == 0) frees.push(i); } int cnt = 0; while (!frees.isEmpty()) { int node = frees.pop(); ++cnt; for(int nei : graph[node]) { if (--degrees[nei] == 0) frees.push(nei); } } return cnt == numCourses; } }
TinsPHP/tins-symbols
src/ch/tsphp/tinsphp/symbols/erroneous/ErroneousTypeSymbol.java
<filename>src/ch/tsphp/tinsphp/symbols/erroneous/ErroneousTypeSymbol.java /* * This file is part of the TinsPHP project published under the Apache License 2.0 * For the full copyright and license information, please have a look at LICENSE in the * root folder or visit the project's website http://tsphp.ch/wiki/display/TINS/License */ /* * This class is based on the class ErroneousTypeSymbol from the TSPHP project. * TSPHP is also published under the Apache License 2.0 * For more information see http://tsphp.ch/wiki/display/TSPHP/License */ package ch.tsphp.tinsphp.symbols.erroneous; import ch.tsphp.common.AstHelperRegistry; import ch.tsphp.common.ITSPHPAst; import ch.tsphp.common.exceptions.TSPHPException; import ch.tsphp.common.symbols.ITypeSymbol; import ch.tsphp.tinsphp.common.gen.TokenTypes; import ch.tsphp.tinsphp.common.symbols.IMethodSymbol; import ch.tsphp.tinsphp.common.symbols.erroneous.IErroneousTypeSymbol; import java.util.Set; public class ErroneousTypeSymbol extends AErroneousScopedSymbol implements IErroneousTypeSymbol { public static final String ERROR_MESSAGE = "ErroneousTypeSymbol is not a real class."; public ErroneousTypeSymbol(ITSPHPAst ast, String name, TSPHPException exception, IMethodSymbol theConstruct) { super(ast, name, exception); } @Override public Set<ITypeSymbol> getParentTypeSymbols() { throw new UnsupportedOperationException(ERROR_MESSAGE); } @Override public boolean isFalseable() { return true; } @Override public boolean isNullable() { return true; } @Override public ITSPHPAst getDefaultValue() { return AstHelperRegistry.get().createAst(TokenTypes.Null, "null"); } @Override public boolean canBeUsedInIntersection() { return false; } @Override public boolean isFinal() { return false; } }
NVoronchev/pikuli
pikuli/uia/adapter/adapter.py
# -*- coding: utf-8 -*- from .identifer_names import element_property_names, control_type_names from .helper_types import IdNameMap from .pattern_description import PatternDescriptions from .platform_init import OsAdapterMixin class AdapterMeta(type): def __new__(mcls, name, bases, dct): cls = super(AdapterMeta, mcls).__new__(mcls, name, bases, dct) """ This code targets to :class:`dotnet.DotNetAdapter` and :class:`win_native.WinAdapter`. Build-function are defined in those classses. """ cls._enums = cls._make_enums() cls._element_properties_map = IdNameMap( cls._build_properties_map, element_property_names) cls._properties_of_pattern_availability_map = IdNameMap( cls._build_properties_map, ["Is{pattern_name}Available".format(pattern_name=n) for n in PatternDescriptions.get_all_known_names()]) cls._control_type_map = IdNameMap( cls._build_control_types_map, control_type_names) cls._patterns_map = IdNameMap( cls._build_patterns_map, PatternDescriptions.get_all_known_names()) return cls class Adapter(OsAdapterMixin, metaclass=AdapterMeta): known_element_property_names = element_property_names
mlexperimentsedge/scray
scray-cassandra/src/main/scala/scray/cassandra/extractors/DomainToCQLQueryMapping.scala
// See the LICENCE.txt file distributed with this work for additional // information regarding copyright ownership. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package scray.cassandra.extractors import scray.querying.queries.DomainQuery import scray.querying.description.internal.{Domain, RangeValueDomain, SingleValueDomain} import scray.querying.description.Column import scray.querying.Registry import com.typesafe.scalalogging.LazyLogging import DomainToCQLQueryMapping.{AND_LITERAL, EMPTY_LITERAL, ORDER_LITERAL, DESC_LITERAL, LIMIT_LITERAL} import scray.cassandra.CassandraQueryableSource import scray.cassandra.extractors.DomainToCQLQueryMapping._ import scray.querying.Registry import scray.querying.description.{Column, TableIdentifier} import scray.querying.description.internal.{Domain, RangeValueDomain, SingleValueDomain} import scray.querying.queries.DomainQuery /** * performs mapping of DomainQueries to valid Cassandra CQL queries, * containing all the possible predicates for a single table as defined * in the domains */ class DomainToCQLQueryMapping[Q <: DomainQuery, S <: CassandraQueryableSource[Q]] extends LazyLogging { /** * add an ordering specification, if needed */ def addOrderMapping(orgQuery: String, store: S, query: Q, storeTableNickName: Option[String]): String = query.getOrdering.map { order => // check for the right-most clustering column. We order for this, only. val clusterCols = store.getClusteringKeyColumns val domains = clusterColumnDomains(clusterCols, store, query, storeTableNickName) if(order.column == domains.takeRight(1)(0).column) { val desc = if(order.descending) { DESC_LITERAL } else { EMPTY_LITERAL } s"${ORDER_LITERAL}${desc}" } else { EMPTY_LITERAL } }.getOrElse(orgQuery) @inline private def removeQuotes(query: String): String = query.filterNot(c => c == '"' || c == ';' || c == ''') @inline private def decideWhere(where: String): String = if(!where.isEmpty()) s"WHERE $where" else "" @inline private def decideLimit(filter: List[String]): String = if(filter.size > 0) filter.head else "" /** * returns a function mapping from Domains to CQL-Strings used in Where clauses */ def getQueryMapping(store: S, storeTableNickName: Option[String]): DomainQuery => String = { (query) => { // first check that we have fixed all partition keys val r = getRowKeyQueryMapping(store, query, storeTableNickName).map { queryStringBegin => // if this is the case the query can fix clustering keys and the last one may be a rangedomain val baseQuery = getClusterKeyQueryMapping(store, query, storeTableNickName) match { case None => queryStringBegin case Some(queryPart) => s"$queryStringBegin$AND_LITERAL$queryPart" } baseQuery }.getOrElse { // if there is not a partition and maybe a clustering column // we must make sure we have a single index for the col we select (only use one) getValueKeyQueryMapping(store, query, storeTableNickName).getOrElse("") } val limit = query.domains.map { _ match { case domain: SingleValueDomain[_] => if (query.domains.size > 1 && domain.isNull) { logger.debug("Domaine: " + domain + query.domains.size) //throw new RuntimeException("A query with a SingleValueDomain and Null expression should not have more than one domains.") "" } else { if (domain.isNull) { "" // No LIMIT for isNull queries } else { enforceLimit(query) } } case _ => enforceLimit(query) } } val result = s"""SELECT * FROM "${removeQuotes(store.ti.dbId)}"."${removeQuotes(store.ti.tableId)}" ${decideWhere(r)} ${decideLimit(limit)}""" logger.debug(s"Query String for Cassandra: $result") result } } /** * sets given limits at the provided query */ private def enforceLimit(query: DomainQuery): String = { query.getQueryRange.map { range => if(range.limit.isDefined) { val sbuf = new StringBuffer val skip = range.skip.getOrElse(0L) sbuf.append(LIMIT_LITERAL).append(skip + range.limit.get).toString } else { "" } }.getOrElse("") } private def convertValue[T](value: T) = value match { case v: String => s"'$v' " case _ => s"${value.toString} " } // private def convertDomainToTargetDomain(domain: Domain[_]): private def convertSingleValueDomain(vdomain: SingleValueDomain[_]): String = { if(vdomain.isNull) { "" } else { s""" "${vdomain.column.columnName}"=${convertValue(vdomain.value)}""" } } private def convertRangeValueDomain(vdomain: RangeValueDomain[_]): String = { vdomain.lowerBound.map { bound => val comp = bound.inclusive match { case true => ">=" case false => ">" } s""" "${vdomain.column.columnName}" $comp ${convertValue(bound.value)}""" }.getOrElse("") + vdomain.upperBound.map { bound => val and = vdomain.lowerBound.isDefined match { case true => AND_LITERAL case false => " " } val comp = bound.inclusive match { case true => "<=" case false => "<" } s"""$and"${vdomain.column.columnName}" $comp ${convertValue(bound.value)}""" }.getOrElse("") } private def getRowKeyQueryMapping(store: S, query: DomainQuery, storeTableNickName: Option[String]): Option[String] = { val rowColumns = store.getRowKeyColumns val foundRowKeyDomains = rowColumns.flatMap(col => query.domains.filter { dom => dom match { case svd: SingleValueDomain[_] => svd.column.columnName == col.columnName && compareCoordinatesWithNickname(svd.column.table, store, storeTableNickName) case _ => false }}) if(foundRowKeyDomains.size == rowColumns.size) { Some(foundRowKeyDomains.map(svd => convertSingleValueDomain(svd.asInstanceOf[SingleValueDomain[_]])).mkString(AND_LITERAL)) } else { None } } /** * efficiently compares TableIdentifiers, even under the presence of a storeNickName */ @inline final private def compareCoordinatesWithNickname(tid: TableIdentifier, store: S, storeTableNickName: Option[String]): Boolean = { val lcoordinates = store.getScrayCoordinates val ltid = storeTableNickName.map(name => TableIdentifier(lcoordinates.dbSystem, lcoordinates.dbId, name)).getOrElse(lcoordinates) tid == ltid } /** * assuming that cols are in order of definition, which should be the case for Cassandra-stores * this recursion probably never overflows the stack as it is only on a few cols or domains */ private def clusterColumnDomains(cols: Set[Column], store: S, query: DomainQuery, storeTableNickName: Option[String]): List[Domain[_]] = { if(cols == Nil || cols.isEmpty) { Nil } else { // find relevant domain val domain = query.domains.find { dom => dom.column.columnName == cols.head.columnName && compareCoordinatesWithNickname(dom.column.table, store, storeTableNickName) } domain.collect { case svd: SingleValueDomain[_] => svd :: clusterColumnDomains(cols.tail, store, query, storeTableNickName) case rvd: RangeValueDomain[_] => rvd :: Nil }.getOrElse { Nil } } } private def getClusterKeyQueryMapping(store: S, query: DomainQuery, storeTableNickName: Option[String]): Option[String] = { val clusterCols = store.getClusteringKeyColumns val domains = clusterColumnDomains(clusterCols, store, query, storeTableNickName) // map the domains to CQL strings and AND this val cqlQuery = domains.collect { case svd: SingleValueDomain[_] => convertSingleValueDomain(svd) case rvd: RangeValueDomain[_] => convertRangeValueDomain(rvd) }.mkString(AND_LITERAL) cqlQuery.size match { case 0 => None case _ => Some(cqlQuery) } } private def getValueKeyQueryMapping(store: S, query: DomainQuery, storeTableNickName: Option[String]): Option[String] = { val valueCols = store.getValueColumns.map { valueCol => Registry.getQuerySpaceColumn(query.getQueryspace, query.querySpaceVersion, valueCol) }.filter(cd => cd.isDefined && cd.get.index.isDefined && cd.get.index.get.isAutoIndexed). partition(cd => cd.get.index.get.autoIndexConfiguration.isDefined) logger.trace(s"value Columns that are indexed: $valueCols") val resultQuery = if(valueCols._1.size > 0) { // if we have lucene entries, we use those as those are supposed to be more flexible logger.debug(s"Using Lucene index on ${valueCols._1}") val ti = valueCols._1.head.get.column.table val domains = query.getWhereAST.filter { dom => valueCols._1.find{optcolDef => optcolDef.get.column.columnName == dom.column.columnName}.isDefined} DomainToJSONLuceneQueryMapper.getLuceneColumnsQueryMapping(query, domains, ti) } else { None } resultQuery.orElse { // if we a standard Cassandra index we use the first in the list of defined valuesColumns query.domains.find{dom => valueCols._2.find { valueColConf => val valueCol = valueColConf.get.column dom.column.columnName == valueCol.columnName && dom.isInstanceOf[SingleValueDomain[_]] && compareCoordinatesWithNickname(dom.column.table, store, storeTableNickName) }.isDefined}.map(svd => convertSingleValueDomain(svd.asInstanceOf[SingleValueDomain[_]])) } } } object DomainToCQLQueryMapping { val EMPTY_LITERAL: String = "" val LIMIT_LITERAL: String = " LIMIT " val AND_LITERAL: String = " AND " val ORDER_LITERAL: String = " ORDER BY " val DESC_LITERAL: String = " DESC " }
AMHOL/activejob-lock
lib/activejob/lock/version.rb
module Activejob module Lock VERSION = "0.0.2" end end
traies/paw2017a1frontend
app/scripts/i18n/translations.en.js
<filename>app/scripts/i18n/translations.en.js 'use strict'; define([], function() { return { WELCOME_MESSAGE : 'Welcome to Vapor.', SLOGAN : 'Connect with your friends \u2014 and other gamers in the world. Get in-the-moment updates on the games that interest you.', FIND_GAMES : 'Find your favorite games' , GAME_TRENDING : 'Trending', GAME_POPULAR : 'Most Popular Games', GAME_RELEASE_DATE : 'Release Date:', LOG_OUT : 'Logout', REGISTER_NOW : 'Register now!', USERNAME : 'User' , PASSWORD : 'Password', REPEAT_PASSWORD : '<PASSWORD>', REMEMBER_ME : 'Remember me', REGISTER : 'Register', SIGN_IN : 'Sign in', LOGIN : 'Log in', REGISTER_FAILED: 'User already exists', MESSAGE_BAD_CREDENTIALS : 'Incorrect username or password', USERNAME_REQUIRED : 'User name required', PASSWORD_REQUIRED : '<PASSWORD>', PICTURE : 'Avatar', PREVIEW_AVATAR : 'Preview', CHOOSE_FILE : 'Choose File', PASSWORDS_NOT_MATCH : 'Passwords do not match.', TOO_SHORT_USERNAME : 'User name should be at least 6 characters long', TOO_SHORT_PASSWORD : 'Password should be at least 6 characters long', TOO_LONG_USERNAME : 'User name too long, please choose a shorter one', TOO_LONG_PASSWORD : '<PASSWORD>', INVALID_USERNAME : 'User name should only contain alphanumeric characters , - or _', DUPLICATE_USERNAME : 'User name already exists', NEW_REPLY : 'Write a new reply', REPLY_TO : 'Reply to ', REPLY_BODY_FULL : 'Body must not exceed 1000 characters', REPLY_BODY_EMPTY : 'Body must have at least 1 character', REPLY_LINK_INVALID : 'Must be a valid Youtube\'s Link', REPLY_LINK_EMPTY : 'Please enter your Youtube \'s link', CONTENT_TEXT : 'Text', CONTENT_VIDEO : 'Video', NEW_MESSAGE : 'Write a new message', TITLE_FULL : 'Title must not exceed 100 characters', TITLE_EMPTY : 'Title must not be empty', LINK_INVALID : 'Must be a valid Youtube\'s Link', LINK_EMPTY : 'Please enter your Youtube \'s link', BODY_FULL : 'Body must not exceed 1000 characters', TAGS_FULL : 'Can\'t insert more than 5 games', TAGS_EMPTY : 'Must insert at least 1 game', TAGS_REPEATED : 'You have already inserted that game', TAGS_CONSTRAINTS_REVIEW : 'Reviews can only talk about 1 game', GAMES : 'Games', TYPE_REVIEW : 'Review', TYPE_COMMENT : 'Comment', TYPE_WALKTHROUGH : 'Walkthrough', COUNT_MESSAGES: 'MESSAGES', COUNT_FOLLOWERS: 'FOLLOWERS', COUNT_FOLLOWING: 'FOLLOWING', COUNT_GAMES: 'GAMES', GAME_DEVELOPER: 'Developer:', GAME_PUBLISHER: 'Publisher:', GAME_PLATFORMS: 'Platforms:', GAME_WINDOWS: 'Windows', GAME_MAC: 'Mac', GAME_LINUX: 'Linux', ERROR_WHILE_POSTING: 'An error ocurred while posting your message', NO_MESSAGES_FOUND: 'No messages were found', NO_USERS_FOUND: 'No users were found', NO_GAMES_FOUND: 'No games were found', SERVER_ERROR: 'Sorry, the servers are not responding.', NAV_FIRST: 'First', NAV_LAST: 'Last', NAV_PREV: 'Previous', NAV_NEXT: 'Next', SEARCH_GAMES: 'Games', SEARCH_USERS: 'Users', SEARCH_MESSAGES: 'Messages', SEARCH_RESULTS_NOT_FOUND: 'No {{type}} were found.', SEARCH_RESULTS_FOUND: '{{resultsTotal}} {{type}} were found.', SEARCH_RESULTS_FOR: 'Results for :', CHANGE_AVATAR: 'Choose your new avatar', SUBMIT: 'Submit', SELECT: 'Select', BAD_AVATAR: 'Please select a valid avatar. Avatars should not be greater than 5MB', PLEASE_CHOOSE: 'Please choose an avatar', ERROR_AVATAR: 'There was an error while uploading your avatar', STEAM_LINK: 'Steam link', STEAM_LINK_SUBTITLE: 'You may want to share your Steam profile so your friends can find you more easily.', STEAM_PROFILE_URL: 'Steam Profile URL', STEAM_OMIT: 'Omit', STEAM_SUBMIT: 'Submit', STEAM_PROFILE_CONFIRM: 'Is this your steam profile?', STEAM_PROFILE_AVATAR: 'Set this as profile picture', STEAM_CANCEL: 'Cancel', STEAM_CONFIRM: 'Confirm', STEAM_URL_ERROR: 'Please use a valid Steam Profile URL.', STEAM_IN_USE: 'Sorry, that Steam profile is already in use.', STEAM_SERVER_ERROR: 'Sorry, Steam is not responding at the moment.', STEAM_OWNED_GAMES: 'Owned games in Steam', STEAM_OWNED_GAMES_SUBTITLE: 'You may be interested in following some of your games on Steam.', STEAM_LOGO: 'Logo', STEAM_NAME: 'Name', STEAM_RELEASE_DATE: 'Release date', STEAM_FOLLOW: 'Follow?', STEAM_FRIENDS: 'Steam friends', STEAM_FRIENDS_SUBTITLE: ' These are your Steam friends who are using Vapor.', STEAM_VAPOR_AVATAR: 'Vapor avatar', STEAM_STEAM_AVATAR: 'Steam avatar', STEAM_VAPOR_NAME: 'Vapor name', STEAM_STEAM_NAME: 'Steam name', STEAM_NO_GAMES: 'You do not seem to have any games.', STEAM_NO_FRIENDS: 'We could not find any Steam friend. Be sure to make your Steam profile public so your friends can find you on Vapor.', STEAM_CONFIRM_LINK: 'Are you sure you want to link this profile?', FOLLOW: 'Follow', UNFOLLOW: 'Unfollow', REPLIES: 'Replies', REPLIES_EMPTY: 'There are no replies to this message. Be the first one.', REPLIES_EMPTY_ANON: 'You have no messages to read. We recommend you start searching for games you like.', NOTIFICATIONS: 'Notifications', NO_NOTIFICATIONS: 'You don\'t have notifications', SHARED_MESSAGE: 'shared your message', REPLIED_MESSAGE: 'replied to your message', FOLLOWED: 'followed you', AND: 'and' } });
vietpv94/files-sharing
backend/webserver/api/file.js
<filename>backend/webserver/api/file.js 'use strict'; const authMiddleware = require('../middleware/authentication'); const files = require('../controllers/files'); module.exports = function(router) { router.post('/file', authMiddleware.isAuthenticated, files.create); router.put('/file/:id', authMiddleware.isAuthenticated, files.update); router.put('/file/shared/:id', authMiddleware.isAuthenticated, files.provideReader); router.delete('/files/:id', authMiddleware.isAuthenticated, files.remove); };
iWzl/dew-rubbish-smart-community-backend
dew-smart-cloud-community-push/src/main/java/com/upuphub/dew/community/push/component/sender/MailGunSender.java
package com.upuphub.dew.community.push.component.sender; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.upuphub.dew.community.connection.common.JsonHelper; import com.upuphub.dew.community.connection.constant.PushConst; import com.upuphub.dew.community.push.bean.po.MailTemplatePO; import com.upuphub.dew.community.push.dao.MailTemplateDao; import lombok.SneakyThrows; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.Collections; import java.util.Map; import java.util.concurrent.Future; /** * Mall Gun 邮件服务的发送支持相关信息 */ @Component public class MailGunSender { @Resource private MailTemplateDao mailTemplateDao; private static final String MAIL_GUN_KEY_API = "api"; private static final String MAIL_GUN_KEY_FROM = "from"; private static final String MAIL_GUN_KEY_TO = "to"; private static final String MAIL_GUN_KEY_SUBJECT = "subject"; private static final String MAIL_GUN_KEY_TAG = "o:tag"; private static final String MAIL_GUN_KEY_VARIABLES = "recipient-variables"; private static final String MAIL_FORM_TEMPLATE = "%s<%s@%s>"; @Value("${push.mailgun.api-key}") private String mailGunApiKey; @Value("${push.mailgun.domain}") private String mailDomainName; @Value("${push.mailgun.url}") private String mailGunUrl; /** * 使用邮件ID和单个发送邮件相关信息 * * @param email 邮件地址 * @param templateCode 邮件需要的发送的模板Code * @param replaceParametersMap 邮件模板中的需要替代的模板参数 */ @SneakyThrows public Integer sendEmailWithTemplateCode(String email, String templateCode, Map<String, String> replaceParametersMap) { MailTemplatePO mailTemplate = mailTemplateDao.fetchMailTemplateByTemplateCode(templateCode); if (null == mailTemplate) { return PushConst.ERROR_CODE_TEMPLATE_NOT_EXISTS; } Future<HttpResponse<JsonNode>> request = Unirest.post(String.format(mailGunUrl, mailDomainName)) .basicAuth(MAIL_GUN_KEY_API, mailGunApiKey) .field(MAIL_GUN_KEY_FROM, String.format(MAIL_FORM_TEMPLATE, mailTemplate.getSender(), mailTemplate.getFrom(), mailDomainName)) .field(MAIL_GUN_KEY_TO, email) .field(MAIL_GUN_KEY_SUBJECT, mailTemplate.getSubject()) .field(MAIL_GUN_KEY_TAG,mailTemplate.getTag()) .field(MAIL_GUN_KEY_VARIABLES, JsonHelper.allToJson(Collections.singletonMap(email,replaceParametersMap))) .field(mailTemplate.getType(), mailTemplate.getTemplate()) .asJsonAsync(); return PushConst.ERROR_CODE_SUCCESS; } }
pierredup/sentry
tests/sentry/api/endpoints/test_monitor_checkin_details.py
<reponame>pierredup/sentry from __future__ import absolute_import, print_function from datetime import timedelta from django.utils import timezone from sentry.models import CheckInStatus, Monitor, MonitorCheckIn, MonitorStatus, MonitorType from sentry.testutils import APITestCase class UpdateMonitorCheckInTest(APITestCase): def test_passing(self): user = self.create_user() org = self.create_organization(owner=user) team = self.create_team(organization=org, members=[user]) project = self.create_project(teams=[team]) monitor = Monitor.objects.create( organization_id=org.id, project_id=project.id, next_checkin=timezone.now() - timedelta(minutes=1), type=MonitorType.CRON_JOB, config={"schedule": "* * * * *"}, date_added=timezone.now() - timedelta(minutes=1), ) checkin = MonitorCheckIn.objects.create( monitor=monitor, project_id=project.id, date_added=monitor.date_added ) self.login_as(user=user) with self.feature({"organizations:monitors": True}): resp = self.client.put( "/api/0/monitors/{}/checkins/{}/".format(monitor.guid, checkin.guid), data={"status": "ok"}, ) assert resp.status_code == 200, resp.content checkin = MonitorCheckIn.objects.get(id=checkin.id) assert checkin.status == CheckInStatus.OK monitor = Monitor.objects.get(id=monitor.id) assert monitor.next_checkin > checkin.date_added assert monitor.status == MonitorStatus.OK assert monitor.last_checkin > checkin.date_added def test_failing(self): user = self.create_user() org = self.create_organization(owner=user) team = self.create_team(organization=org, members=[user]) project = self.create_project(teams=[team]) monitor = Monitor.objects.create( organization_id=org.id, project_id=project.id, next_checkin=timezone.now() - timedelta(minutes=1), type=MonitorType.CRON_JOB, config={"schedule": "* * * * *"}, date_added=timezone.now() - timedelta(minutes=1), ) checkin = MonitorCheckIn.objects.create( monitor=monitor, project_id=project.id, date_added=monitor.date_added ) self.login_as(user=user) with self.feature({"organizations:monitors": True}): resp = self.client.put( "/api/0/monitors/{}/checkins/{}/".format(monitor.guid, checkin.guid), data={"status": "error"}, ) assert resp.status_code == 200, resp.content checkin = MonitorCheckIn.objects.get(id=checkin.id) assert checkin.status == CheckInStatus.ERROR monitor = Monitor.objects.get(id=monitor.id) assert monitor.next_checkin > checkin.date_added assert monitor.status == MonitorStatus.ERROR assert monitor.last_checkin > checkin.date_added
charlesj/Apollo
client/src/redux/financial/actions.js
<reponame>charlesj/Apollo import { createActions, } from 'redux-actions' import { basicActions, dispatchBasicActions, } from '../redux-helpers' import apolloServer from '../../services/apolloServer' import { NotifySuccess, } from '../../services/notifier' const actionCreators = createActions({ financial: { loadAccounts: basicActions(), loadTransactions: basicActions(), saveAccount: basicActions(), saveTransaction: basicActions(), selectAccount: account => account, selectTransaction: (transaction, accountId) => ({transaction, accountId,}), setAccountMode: mode => mode, }, }) export const actions = actionCreators.financial export function loadAccounts() { return dispatchBasicActions(actions.loadAccounts, async (dispatch) => { const accounts = await apolloServer.invoke('getFinancialAccounts', {}) accounts.map(a => dispatch(loadTransactions(a.id))) return { accounts, } }) } export function loadTransactions(accountId){ return dispatchBasicActions(actions.loadTransactions, async () => { const transactions = await apolloServer.invoke('getFinancialTransactions', {account_id: accountId,}) return { transactions, accountId, } }) } export function saveAccount(account){ return dispatchBasicActions(actions.saveAccount, async () => { const saved = await apolloServer.invoke('upsertFinancialAccount', { account, }) NotifySuccess('Saved Changes to Account', 'Financial') return { account: saved, } }) } export function saveTransaction(accountId, transaction){ return dispatchBasicActions(actions.saveTransaction, async () => { transaction.account_id = accountId transaction.tags = transaction.tagsDisplay.split(',') const saved = await apolloServer.invoke('upsertFinancialTransaction', {transaction,}) NotifySuccess('Saved Transaction to Account', 'Financial') return { transaction: saved, accountId, } }) } export function selectAccount(account){ return dispatch => { dispatch(actions.selectAccount(account)) dispatch(loadTransactions(account.id)) } }
Douglasdsm/web-css-html-javascript
funcao/exerciciosFuncoes/atividade10.js
/*Crie uma função que verifica se um número inteiro passado como parêmetro é divisível por 3 e retorne true ou false*/ function verificar(n){ if(n % 3 == 0){ return true }else{ return false } } console.log(verificar(2)); console.log(verificar(5)); console.log(verificar(14)); console.log(verificar(3)); console.log(verificar(9)); console.log(verificar(12));
jeanchalard/jface
Common/src/main/java/com/j/jface/FutureValue.java
<gh_stars>0 package com.j.jface; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.concurrent.Semaphore; public class FutureValue<T> implements Future<T> { private class Obj { @NonNull public static final String UNKNOWN_ERROR = "FutureValue : Unknown error"; @Nullable private final T value; private final int status; @NonNull private final String error; public Obj(@Nullable final T value, final int status, @NonNull final String error) { this.value = value; this.status = status; this.error = error; } } private Obj obj = new Obj(null, NOT_DONE, Obj.UNKNOWN_ERROR); private Semaphore sem = new Semaphore(0); public int status() { return obj.status; } @Nullable public T get() { if (NOT_DONE != obj.status) return obj.value; sem.acquireUninterruptibly(); sem.release(); return obj.value; } public void set(@Nullable final T value) { if (sem.tryAcquire()) throw new RuntimeException("FutureValue.set/fail called multiple times ; old \"" + obj.value + "\" ; new \"" + value + "\""); obj = new Obj(value, SUCCESS, Obj.UNKNOWN_ERROR); sem.release(); } public void fail(@NonNull final String error) { if (sem.tryAcquire()) throw new RuntimeException("FutureValue.fail/set called multiple times ; old \"" + obj.value + "\""); obj = new Obj(null, FAILURE, error); sem.release(); } @NonNull public String getError() { if (obj.status != FAILURE) throw new RuntimeException("Don't call error() if the FutureValue doesn't have FAILURE status."); return obj.error; } }
wiltonlazary/Nidium
tests/gunittest/unittest.cpp
<gh_stars>1000+ /* Copyright 2016 Nidium Inc. All rights reserved. Use of this source code is governed by a MIT license that can be found in the LICENSE file. */ #include "unittest.h" #include <jsapi.h> unsigned long _ape_seed = 31415961;
mavaddat-javid-education/java-debugging-DucklyFish
Chapter11/CodeInFigures/TalkingAnimalDemo.java
public class TalkingAnimalDemo { public static void main(String[] args) { Dog dog = new Dog(); Cow cow = new Cow(); dog.setName("Ginger"); cow.setName("Molly"); talkingAnimal(dog); talkingAnimal(cow); } public static void talkingAnimal(Animal animal) { System.out.println("Come one. Come all."); System.out.println ("See the amazing talking animal!"); System.out.println(animal.getName() + " says"); animal.speak(); System.out.println("***************"); } }
patriciaTel/TFG-Spread
app/src/main/java/com/ucm/informatica/spread/Presenter/ProfileFragmentPresenter.java
<gh_stars>1-10 package com.ucm.informatica.spread.Presenter; import com.ucm.informatica.spread.View.ProfileFragmentView; import com.ucm.informatica.spread.Model.Colours; public class ProfileFragmentPresenter { private Boolean editView = false; private Boolean editWatchword = false; private Colours shirtColour = Colours.NA; private Colours pantsColour = Colours.NA; private ProfileFragmentView profileFragmentView; public ProfileFragmentPresenter(ProfileFragmentView profileFragmentView){ this.profileFragmentView = profileFragmentView; } public void onEditPressed(){ editView = !editView; profileFragmentView.onRenderView(editView); } public void onSavePressed(){ onEditPressed(); profileFragmentView.saveData(); } public void onEditWatchwordPressed(){ editWatchword = !editWatchword; profileFragmentView.onRenderWatchwordView(editWatchword); } public void onSaveWatchwordPressed(){ onEditWatchwordPressed(); profileFragmentView.saveWatchwordData(); } public void onShirtPressed(){ shirtColour = Colours.values()[(shirtColour.ordinal()+1)%Colours.values().length]; profileFragmentView.changeShirt(shirtColour); } public void onPantsPressed(){ pantsColour = Colours.values()[(pantsColour.ordinal()+1)%Colours.values().length]; profileFragmentView.changePants(pantsColour); } public void onStart(){ profileFragmentView.initView(); profileFragmentView.setupListeners(); profileFragmentView.loadData(); } public void onRefreshView(Colours shirt, Colours pants){ shirtColour = shirt; pantsColour = pants; profileFragmentView.refreshView(); } }
rockspoon/soajs
test/unit/classes/MultiTenantSession.js
<filename>test/unit/classes/MultiTenantSession.js "use strict"; /** * @license * Copyright SOAJS All Rights Reserved. * * Use of this source code is governed by an Apache license that can be * found in the LICENSE file at the root of this repository */ const helper = require("../../helper.js"); const multiTenantSessionObj = helper.requireModule('./classes/MultiTenantSession'); describe("Unit test for: classes MultiTenantSession", function () { it("preserveTenantSession", function (done) { let multiTenantSession = new multiTenantSessionObj({ "tenant": { id: "123", key: "123" }, "session": { persistSession: { holder: { tenant: { id: "123", key: "123" } } }, sessions: { "123": { keys: ["key1"] }, "321": {} } } }); multiTenantSession.preserveTenantSession(); done(); }); it("setPersistSessionSTATE", function (done) { let multiTenantSession = new multiTenantSessionObj({ "tenant": { id: "123", key: "123" }, "session": { persistSession: { holder: { tenant: { id: "123", key: "123" } } }, sessions: { "123": { keys: ["key1"] }, "321": {} } } }); multiTenantSession.session = {}; multiTenantSession.setPersistSessionSTATE(); done(); }); it("setPersistSessionHOLDER", function (done) { let multiTenantSession = new multiTenantSessionObj({ "tenant": { id: "123", key: "123" }, "session": { persistSession: { holder: { tenant: { id: "123", key: "123" } } }, sessions: { "123": { keys: ["key1"] }, "321": {} } } }); multiTenantSession.session = {}; multiTenantSession.setPersistSessionHOLDER(); done(); }); it("deleteTenantSession", function (done) { let multiTenantSession = new multiTenantSessionObj({ "tenant": { id: "123", key: "123" }, "session": { persistSession: { holder: { tenant: { id: "123", key: "123" } } }, sessions: { "123": { keys: ["key1"] }, "321": {} } }, "req": { sessionStore: { set: function (sessionID, session, cb) { return cb("output"); } } } }); multiTenantSession.deleteTenantSession(function () { done(); }); }); it("setSERVICE & getSERVICE", function (done) { let multiTenantSession = new multiTenantSessionObj({ "tenant": { id: "123", key: "123" }, "request":{ "service":"urac" }, "session": { persistSession: { holder: { tenant: { id: "123", key: "123" } } }, sessions: { "123": { keys: ["key1"] }, "321": {} } }, "req": { sessionStore: { set: function (sessionID, session, cb) { return cb("output"); } } } }); multiTenantSession.setSERVICE({"a":"b"}, function () { multiTenantSession.getSERVICE(); done(); }); }); });
octonion/baseball-public
bbref/scrapers/pitching.rb
<gh_stars>10-100 #!/usr/bin/env ruby # coding: utf-8 bad = " " require "csv" require "mechanize" agent = Mechanize.new{ |agent| agent.history.max_size=0 } agent.user_agent = 'Mozilla/5.0' reports = ["standard-pitching","value-pitching","batting-pitching", "win_probability-pitching","starter-pitching","reliever-pitching", "ratio-pitching","pitches-pitching","basesituation-pitching"] #"cumulative-pitching","neutral-pitching" base = "http://www.baseball-reference.com/leagues/MLB" table_xpath = '//table[@class="sortable stats_table" and not(@data-freeze)]/tbody/tr' first_year = ARGV[0] last_year = ARGV[1] reports.each do |report| (first_year..last_year).each do |year| out = CSV.open("csv/#{report}-#{year}.csv","w") url = "#{base}/#{year}-#{report}.shtml" print "Baseball Reference #{report} (#{year})" begin page = agent.get(url) rescue retry end found = 0 page.parser.xpath(table_xpath).each do |r| row = [] r.xpath("td").each_with_index do |e,i| et = e.text et.gsub!(bad," ") if (et.size==0) et = nil end row += [et] if ([1].include?(i)) hrefs = [] e.xpath("a").each do |a| hrefs += [a.text,a.attribute("href").to_s] end if (hrefs.size==2) id = hrefs[1][/\/[a-z0-9\.\'\_]+\.shtml/] id.gsub!("/","") id.gsub!(".shtml","") row += [hrefs[1],id] end end end if (row.size > 0) and not(row[4]==nil) found += 1 out << [year]+row end end print " - found #{found}\n" out.close end end
samirans89/wcm-io-qa-galenium
modules/sampling/src/main/java/io/wcm/qa/glnm/sampling/jsoup/JsoupCookieSampler.java
/* * #%L * wcm.io * %% * Copyright (C) 2019 wcm.io * %% * 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. * #L% */ package io.wcm.qa.glnm.sampling.jsoup; import java.io.IOException; import java.net.URL; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import org.jsoup.Connection; import org.jsoup.Connection.KeyVal; import org.jsoup.Connection.Method; import org.jsoup.Connection.Request; import org.jsoup.Connection.Response; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.wcm.qa.glnm.exceptions.GaleniumException; import io.wcm.qa.glnm.sampling.jsoup.base.JsoupBasedSampler; /** * Samples cookies from a Jsoup network response. * * @since 3.0.0 */ public class JsoupCookieSampler extends JsoupBasedSampler<Map<String, String>> { private static final Logger LOG = LoggerFactory.getLogger(JsoupCookieSampler.class); /** * <p>Constructor for JsoupCookieSampler.</p> * * @param url to fetch cookies from * @since 3.0.0 */ public JsoupCookieSampler(String url) { super(url); } private Method method = Method.POST; /** {@inheritDoc} */ @Override public Map<String, String> freshSample() { return fetchCookies(); } /** * <p>Setter for the field <code>method</code>.</p> * * @param requestMethod HTTP method to use for retrieval * @since 3.0.0 */ public void setMethod(Method requestMethod) { this.method = requestMethod; } protected Map<String, String> fetchCookies() { @SuppressWarnings("PMD.CloseResource") Connection connection = getJsoupConnection(); try { connection.method(getMethod()); Request request = connection.request(); URL url = request.url(); if (LOG.isInfoEnabled()) { LOG.info("sending " + getMethod() + " request to '" + url + "'"); } logRequest(request); connection.execute(); Response response = connection.response(); if (LOG.isDebugEnabled()) { LOG.debug("response(" + response.url() + "): " + response.statusCode() + " - " + response.statusMessage()); } logResponse(response); Map<String, String> cookies = response.cookies(); if (LOG.isDebugEnabled()) { LOG.debug("got " + cookies.size() + " cookies from '" + url + "'"); } return cookies; } catch (IOException ex) { throw new GaleniumException("Could not fetch cookies", ex); } } private void logResponse(Response response) { if (LOG.isTraceEnabled()) { for (Entry<String, String> header : response.headers().entrySet()) { LOG.trace("response-header: '" + header.getKey() + "' : '" + header.getValue() + "'"); } } } private void logRequest(Request request) { if (LOG.isTraceEnabled()) { for (Entry<String, String> header : request.headers().entrySet()) { LOG.trace("request-header: '" + header.getKey() + "' : '" + header.getValue() + "'"); } Collection<KeyVal> data = request.data(); for (KeyVal keyVal : data) { LOG.trace(keyVal.contentType() + ": '" + keyVal.key() + "' : '" + keyVal.value()); } } } protected Method getMethod() { return method; } }
statisticsnorway/linked-data-store-core
src/main/java/no/ssb/lds/graphql/schemas/visitors/AddConnectionVisitor.java
package no.ssb.lds.graphql.schemas.visitors; import graphql.schema.GraphQLArgument; import graphql.schema.GraphQLDirective; import graphql.schema.GraphQLFieldDefinition; import graphql.schema.GraphQLFieldsContainer; import graphql.schema.GraphQLInterfaceType; import graphql.schema.GraphQLList; import graphql.schema.GraphQLNamedType; import graphql.schema.GraphQLNonNull; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLOutputType; import graphql.schema.GraphQLSchemaElement; import graphql.schema.GraphQLType; import graphql.schema.GraphQLTypeVisitorStub; import graphql.util.TraversalControl; import graphql.util.TraverserContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import static graphql.Scalars.GraphQLBoolean; import static graphql.Scalars.GraphQLInt; import static graphql.Scalars.GraphQLString; import static graphql.schema.GraphQLTypeUtil.isList; import static graphql.schema.GraphQLTypeUtil.simplePrint; import static graphql.schema.GraphQLTypeUtil.unwrapNonNull; import static graphql.schema.GraphQLTypeUtil.unwrapType; /** * Add a @pagination annotation to all fields marked with @link or @reverseLink. */ public class AddConnectionVisitor extends GraphQLTypeVisitorStub { private static final Logger log = LoggerFactory.getLogger(AddConnectionVisitor.class); private final Map<String, GraphQLNamedType> typeMap; public AddConnectionVisitor(Map<String, GraphQLNamedType> typeMap) { this.typeMap = Objects.requireNonNull(typeMap); } public static boolean hasLinkWithPagination(GraphQLFieldDefinition node) { for (GraphQLDirective directive : node.getDirectives()) { if ("link".equals(directive.getName()) || "reverseLink".equals(directive.getName())) { GraphQLArgument pagination = directive.getArgument("pagination"); // TODO: Figure out how arguments are supposed to be used. if (pagination == null) { return true; } Object value = pagination.getValue(); if (value == null) { return true; } return (Boolean) value; } if ("search".equals(directive.getName())) { return true; } } return false; } @Override public TraversalControl visitGraphQLInterfaceType(GraphQLInterfaceType node, TraverserContext<GraphQLSchemaElement> context) { List<GraphQLFieldDefinition> fieldsWithPagination = findFieldsWithPagination(node); if (fieldsWithPagination.isEmpty()) { log.trace("No fields marked with pagination in {}", node); return TraversalControl.CONTINUE; } log.debug("Transforming {} fields to pagination fields in {}", fieldsWithPagination.size(), node.getName()); GraphQLInterfaceType.Builder newObject = GraphQLInterfaceType.newInterface(node); for (GraphQLFieldDefinition fieldDefinition : fieldsWithPagination) { newObject.field(createConnectionField(node, fieldDefinition)); } typeMap.put(node.getName(), newObject.build()); return TraversalControl.CONTINUE; } private List<GraphQLFieldDefinition> findFieldsWithPagination(GraphQLFieldsContainer node) { List<GraphQLFieldDefinition> fieldsWithPagination = new ArrayList<>(); for (GraphQLFieldDefinition fieldDefinition : node.getFieldDefinitions()) { if (hasLinkWithPagination(fieldDefinition) && isList(unwrapNonNull(fieldDefinition.getType()))) { log.trace("Found link from {} to {} on field {}", node.getName(), simplePrint(fieldDefinition.getType()), fieldDefinition.getName()); fieldsWithPagination.add(fieldDefinition); } } return fieldsWithPagination; } @Override public TraversalControl visitGraphQLObjectType(GraphQLObjectType node, TraverserContext<GraphQLSchemaElement> context) { List<GraphQLFieldDefinition> fieldsWithPagination = findFieldsWithPagination(node); if (fieldsWithPagination.isEmpty()) { log.trace("No fields marked with pagination in {}", node); return TraversalControl.CONTINUE; } log.debug("Transforming {} fields to pagination fields in {}", fieldsWithPagination.size(), node.getName()); GraphQLObjectType.Builder newObject = GraphQLObjectType.newObject( (GraphQLObjectType) typeMap.get(node.getName())); for (GraphQLFieldDefinition fieldDefinition : fieldsWithPagination) { newObject.field(createConnectionField(node, fieldDefinition)); } // TODO: Figure out why this fails. We should have tree with same instance of all types //if (!typeMap.replace(existing.getName(), existing, newObject)) { // throw new IllegalArgumentException(String.format( // "Could not replace %s, the schema probably contains references", existing.getName() // )); //} GraphQLType oldObject = typeMap.put(node.getName(), newObject.build()); if (oldObject != null && Objects.equals(oldObject, node)) { log.debug("Existing object {} is not equal to visited object {}", node, oldObject); } return TraversalControl.CONTINUE; } private GraphQLFieldDefinition createConnectionField(GraphQLNamedType from, GraphQLFieldDefinition field) { GraphQLNamedType to = (GraphQLNamedType) unwrapType(field.getType()).pop(); GraphQLFieldDefinition.Builder newFieldDefinition = GraphQLFieldDefinition.newFieldDefinition(field); return newFieldDefinition .argument(GraphQLArgument.newArgument().name("first").type(GraphQLInt).build()) .argument(GraphQLArgument.newArgument().name("after").type(GraphQLString).build()) .argument(GraphQLArgument.newArgument().name("last").type(GraphQLInt).build()) .argument(GraphQLArgument.newArgument().name("before").type(GraphQLString).build()) .type((GraphQLOutputType) createConnectionType(from, to)) .build(); } private GraphQLType createConnectionType(GraphQLNamedType from, GraphQLNamedType to) { // We do not use Relay Connection name convertion to reduce the amount of // types. // String connectionTypeName = from.getName() + to.getName() + "Connection"; String connectionTypeName = to.getName() + "Connection"; if (!typeMap.containsKey(connectionTypeName)) { GraphQLFieldDefinition.Builder pageInfoField = GraphQLFieldDefinition.newFieldDefinition() .type(GraphQLNonNull.nonNull(createPageInfoType())).name("pageInfo"); GraphQLFieldDefinition.Builder edgesField = GraphQLFieldDefinition.newFieldDefinition() .type(GraphQLNonNull.nonNull( GraphQLList.list(GraphQLNonNull.nonNull( createEdgeType(from, to)) )) ) .name("edges"); GraphQLObjectType.Builder connectionType = GraphQLObjectType.newObject() .name(connectionTypeName) .field(edgesField) .field(pageInfoField); typeMap.put(connectionTypeName, connectionType.build()); } return typeMap.get(connectionTypeName); } private GraphQLType createEdgeType(GraphQLNamedType from, GraphQLNamedType to) { // We do not use Relay Connection name conversion to reduce the amount of // types. // String edgeTypeName = from.getName() + to.getName() + "Connection"; String edgeTypeName = to.getName() + "Edge"; if (!typeMap.containsKey(edgeTypeName)) { GraphQLFieldDefinition.Builder nodeField = GraphQLFieldDefinition.newFieldDefinition() .type(GraphQLNonNull.nonNull(to)).name("node"); GraphQLFieldDefinition.Builder cursorField = GraphQLFieldDefinition.newFieldDefinition() .type(GraphQLNonNull.nonNull(GraphQLString)).name("cursor"); GraphQLObjectType.Builder edgeType = GraphQLObjectType.newObject() .name(edgeTypeName) .field(cursorField) .field(nodeField); typeMap.put(edgeTypeName, edgeType.build()); } return typeMap.get(edgeTypeName); } private GraphQLType createPageInfoType() { if (!typeMap.containsKey("PageInfo")) { GraphQLObjectType pageInfoType = GraphQLObjectType.newObject() .name("PageInfo") .field(GraphQLFieldDefinition.newFieldDefinition().name("hasNextPage").type(GraphQLNonNull.nonNull(GraphQLBoolean))) .field(GraphQLFieldDefinition.newFieldDefinition().name("hasPreviousPage").type(GraphQLNonNull.nonNull(GraphQLBoolean))) .build(); typeMap.put("PageInfo", pageInfoType); } return typeMap.get("PageInfo"); } }
javierbrea/narval
test/integration/specs/api-coverage/docker.test-ok.specs.js
const test = require('../../../../index') const utils = require('../../../../utils') test.describe('api-docker-coverage suite execution passing tests', () => { let outerrLog test.before(async () => { outerrLog = await utils.logs.combined('package-test') }) test.it('should have passed tests', () => { return test.expect(outerrLog).to.include('[Narval] [DEBUG] Docker container "test-container" of service "test" exited with code "0"') }) test.it('should have exited api without error', () => { return test.expect(outerrLog).to.include('[Narval] [DEBUG] Docker container "api-container" of service "api-server" exited with code "0"') }) test.it('should have exited api after "exit_after" time', () => { return test.expect(outerrLog).to.include('Service timeout finished after 10000ms. Exiting...') }) })
flowarko/astrobee
tools/bag_processing/scripts/splice_bag.py
<filename>tools/bag_processing/scripts/splice_bag.py #!/usr/bin/env python # Copyright (c) 2017, United States Government, as represented by the # Administrator of the National Aeronautics and Space Administration. # # All rights reserved. # # The Astrobee platform is 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. """ Splices a bagfile at selected timestamps to create multiple smaller bagfiles which when combined span the original bagfile. Iterate through the images using the right and left arrow keys. Iterate more quickly (skipping 10 images at a time) using the up and down arrow keys. Create a splice point using the current image's timestamp using the s key. Undo adding last splice point using the u key. Print current splice points and intervals using the p key. Generate spliced bags using all selected splice points by pressing the enter key at any time. To exit without splicing, use the escape or q keys. """ import argparse import os import sys import cv2 import rosbag import rospy import utilities from cv_bridge import CvBridge, CvBridgeError from sensor_msgs.msg import Image def print_info(splice_timestamps, bag_start_time, bag_end_time): print(str(len(splice_timestamps)) + " splice timestamps selected.") print("Splicing timestamps: " + str(splice_timestamps)) print("Splicing intervals: ") starting_splice_percent = 0 for i in range(len(splice_timestamps) + 1): ending_splice_percent = ( (splice_timestamps[i] - bag_start_time) / float(bag_end_time - bag_start_time) if i < len(splice_timestamps) else 1 ) print( str(i) + ": " + "{0:.2f}".format(starting_splice_percent * 100) + "% to " + "{0:.2f}".format(ending_splice_percent * 100) + "%" ) starting_splice_percent = ending_splice_percent def sort_and_remove_repeats(splice_timestamps): # Remove repeats splice_timestamps = list(set(splice_timestamps)) splice_timestamps.sort() return splice_timestamps def show_image_with_message( image, window, title, message, origin=(50, 450), font_size=4, timeout=750 ): color_image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) splice_image = cv2.putText( color_image, message, origin, cv2.FONT_HERSHEY_SIMPLEX, font_size, (0, 0, 255), 10, ) cv2.imshow(window, splice_image) cv2.setWindowTitle(window, title) key = cv2.waitKey(timeout) def make_spliced_bag(bagfile, start_time, end_time, index): spliced_bagfile = os.path.splitext(bagfile)[0] + "_" + str(index) + ".bag" with rosbag.Bag(bagfile, "r") as bag: with rosbag.Bag(spliced_bagfile, "w") as spliced_bag: for topic, msg, t in bag.read_messages( None, rospy.Time(start_time), rospy.Time(end_time) ): spliced_bag.write(topic, msg, t) def splice_bag(bagfile, splice_timestamps): if not splice_timestamps: print("No timestamps provided, not splicing.") return start_and_end_times = [] with rosbag.Bag(bagfile, "r") as bag: # Subtract extra time from bag start time to ensure first message included start_time = bag.get_start_time() - 1.0 for i in range(len(splice_timestamps) + 1): # Add extra time to end time to ensure final message included end_time = ( splice_timestamps[i] if i < len(splice_timestamps) else bag.get_end_time() + 1.0 ) make_spliced_bag(bagfile, start_time, end_time, i) # Add slight extra time so new start time doesn't overlap with previous end time start_time = end_time + 1e-4 def select_splice_timestamps_and_splice_bag(bagfile, image_topic): splice_timestamps = [] bridge = CvBridge() with rosbag.Bag(bagfile, "r") as bag: msg_tuples = [] print("Reading msgs...") for topic, msg, t in bag.read_messages([image_topic]): msg_tuples.append((msg, t)) i = 0 num_msgs = len(msg_tuples) window = "image" cv2.namedWindow(window) cv2.moveWindow(window, 40, 30) print_string = True while True: msg = (msg_tuples[i])[0] timestamp = ((msg_tuples[i])[1]).to_sec() progress = i / float(num_msgs) * 100 msg_info_string = ( "{0:.2f}".format(progress) + "%, Image " + str(i) + "/" + str(num_msgs) + ", t: " + str(timestamp) ) if print_string: print(msg_info_string) print_string = False try: image = bridge.imgmsg_to_cv2(msg, msg.encoding) except (CvBridgeError) as e: print(e) cv2.imshow(window, image) cv2.setWindowTitle(window, msg_info_string) key = cv2.waitKey(0) if key == 83: # Right arrow key i += 1 print_string = True elif key == 81: # Left arrow key i -= 1 print_string = True if key == 82: # Up arrow key i += 10 print_string = True elif key == 84: # Down arrow key i -= 10 print_string = True elif key == ord("q") or key == 27: # Escape key print("Manually closing program, no splice operation applied.") exit(0) elif key == ord("p"): print_info(splice_timestamps, bag.get_start_time(), bag.get_end_time()) show_image_with_message( image, window, "Printing splice intervals", "Printing splice intervals", (130, 450), 3, ) elif key == ord("s"): print("Splice timestamp selected, t: " + str(timestamp)) splice_timestamps.append(timestamp) splice_timestamps = sort_and_remove_repeats(splice_timestamps) print_info(splice_timestamps, bag.get_start_time(), bag.get_end_time()) show_image_with_message( image, window, "Splice t selected! " + msg_info_string, "Saving splice time", ) elif key == ord("u"): if not splice_timestamps: message = "No splice timestamps added." print(message) show_image_with_message( image, window, message, message, (80, 450), 2.4 ) else: print( "Removing last added splice point at timestamp: " + str(timestamp) ) splice_timestamps.pop() print_info( splice_timestamps, bag.get_start_time(), bag.get_end_time() ) show_image_with_message( image, window, "Removed last splice point at timestamp " + str(timestamp), "Removed last splice time", (50, 450), 3, ) elif key == 13: # Enter key if not splice_timestamps: message = "No splice timestamps added." print(message) show_image_with_message( image, window, message, message, (80, 450), 2.4 ) else: print("Splicing bag using selected timestamps.") print_info( splice_timestamps, bag.get_start_time(), bag.get_end_time() ) show_image_with_message( image, window, "Splicing", "Splicing", (350, 450) ) splice_bag(bagfile, splice_timestamps) return if i < 0: i = 0 if i >= num_msgs: i = num_msgs - 1 show_image_with_message( image, window, "End of bag", "End of bag", (350, 450), 3 ) if __name__ == "__main__": parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument("bagfile", help="Input bagfile.") parser.add_argument( "-i", "--image-topic", default="/hw/cam_nav", help="Image topic name.", ) args = parser.parse_args() if not os.path.isfile(args.bagfile): print(("Bag file " + args.bagfile + " does not exist.")) sys.exit() select_splice_timestamps_and_splice_bag(args.bagfile, args.image_topic)
Montana-Media-Arts/120_CreativeCoding
lecture_code/10/extra_examples/01-multiple-stars/sketch.js
var location1 = 10; var location2 = 10; var starArr = [ [5, 0], [7, 11], [0, 4], [10, 4], [3, 11] ]; var idx = 0; function setup() { // createCanvas(windowWidth, windowHeight); createCanvas(windowWidth, 800); background(18, 82, 189); // frameRate(20); } function draw() { background(18, 82, 189, 30); var randomSize = random(10, 40); var randomX = random(width); var randomY = random(height); drawStar(starArr, randomSize, randomX, randomY); } function drawStar(starArray, size, loc_x, loc_y){ // set the location of the star translate(loc_x, loc_y); // create a random color for the whole star var col = color( random(255), random(255), random(255) ); // draw all five lines of the star for (var idx = 0; idx < starArray.length; idx++) { // Ensure we loop back around to idx=0 var idxPlus = (idx + 1) % starArr.length; // extract the locations for each point var x1 = starArray[idx][0] * size; var y1 = starArray[idx][1] * size; var x2 = starArray[idxPlus][0] * size; var y2 = starArray[idxPlus][1] * size; // draw a stick randomstick(x1, y1, x2, y2, col); } } function randomstick(x1, y1, x2, y2, col) { strokeWeight(10); stroke(col); line(x1, y1, x2, y2); return [x2, y2]; }
ShunjiroOsada/jsk_visualization_package
jsk_rviz_plugins/scripts/twist_stamped_add_header.py
#!/usr/bin/env python import rospy import sys from geometry_msgs.msg import Twist, TwistStamped rospy.init_node("twist_stamped_add_header") pub = rospy.Publisher("cmd_vel_stamped", TwistStamped) def callback(msg): global pub output = TwistStamped() output.header.stamp = rospy.Time.now() output.header.frame_id = sys.argv[1] output.twist = msg pub.publish(output) if len(sys.argv) != 3: print "Usage: twist_stamped_add_header frame_id topic" sub = rospy.Subscriber(sys.argv[2], Twist, callback) rospy.spin()
GabrielSturtevant/mage
Mage.Sets/src/mage/cards/a/AngelicFieldMarshal.java
package mage.cards.a; import java.util.UUID; import mage.MageInt; import mage.abilities.abilityword.LieutenantAbility; import mage.abilities.effects.ContinuousEffect; import mage.abilities.effects.common.continuous.GainAbilityControlledEffect; import mage.abilities.keyword.FlyingAbility; import mage.abilities.keyword.VigilanceAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.Duration; import mage.constants.SubType; import mage.filter.common.FilterControlledCreaturePermanent; /** * * @author emerald000 */ public final class AngelicFieldMarshal extends CardImpl { public AngelicFieldMarshal(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{2}{W}{W}"); this.subtype.add(SubType.ANGEL); this.power = new MageInt(3); this.toughness = new MageInt(3); // Flying this.addAbility(FlyingAbility.getInstance()); // Lieutenant - As long as you control your commander, Angelic Field Marshal gets +2/+2 and creatures you control have vigilance. ContinuousEffect effect = new GainAbilityControlledEffect(VigilanceAbility.getInstance(), Duration.WhileOnBattlefield, new FilterControlledCreaturePermanent()); effect.setText("and creatures you control have vigilance"); this.addAbility(new LieutenantAbility(effect)); } private AngelicFieldMarshal(final AngelicFieldMarshal card) { super(card); } @Override public AngelicFieldMarshal copy() { return new AngelicFieldMarshal(this); } }
henviso/contests
CODEFORCES/224/a.cpp
<reponame>henviso/contests #include <iostream> #include <cstdio> #include <string> #include <cstring> #include <cstdlib> #include <stack> #include <algorithm> #include <cctype> #include <vector> #include <queue> #include <tr1/unordered_map> #include <cmath> #include <map> #include <bitset> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef vector<int> vi; typedef pair<int,int> ii; ///////////////////////////////UTIL///////////////////////////////// #define ALL(x) (x).begin(),x.end() #define CLEAR0(v) memset(v, 0, sizeof(v)) #define CLEAR(v, x) memset(v, x, sizeof(v)) #define INRANGE0(x, n) ((x) > -1 && (x) < n) #define INRANGE(x, a, b) ((x) >= a && (x) <= b) #define COPY(a, b) memcpy(a, b, sizeof(a)) #define CMP(a, b) memcmp(a, b, sizeof(a)) #define REP(i,n) for(int i = 0; i<n; i++) #define REPP(i,a,n) for(int i = a; i<n; i++) #define REPD(i,n) for(int i = n-1; i>-1; i--) #define REPDP(i,a,n) for(int i = n-1; i>=a; i--) #define pb push_back #define pf push_front #define sz size() #define mp make_pair /////////////////////////////NUMERICAL////////////////////////////// #define INCMOD(a,b,c) (((a)+b)%c) #define DECMOD(a,b,c) (((a)+c-b)%c) #define ROUNDINT(a) (int)((double)(a) + 0.5) #define INF 0x3f3f3f3f #define EPS 1e-9 /////////////////////////////BITWISE//////////////////////////////// #define CHECK(S, j) (S & (1 << j)) #define CHECKFIRST(S) (S & (-S)) //PRECISA DE UMA TABELA PARA TRANSFORMAR EM INDICE #define SET(S, j) S |= (1 << j) #define SETALL(S, j) S = (1 << j)-1 //J PRIMEIROS #define UNSET(S, j) S &= ~(1 << j) #define TOOGLE(S, j) S ^= (1 << j) ///////////////////////////////64 BITS////////////////////////////// #define LCHECK(S, j) (S & (1ULL << j)) #define LSET(S, j) S |= (1ULL << j) #define LSETALL(S, j) S = (1ULL << j)-1ULL //J PRIMEIROS #define LUNSET(S, j) S &= ~(1ULL << j) #define LTOOGLE(S, j) S ^= (1ULL << j) //scanf(" %d ", &t); char a[8000000]; char b[5000000]; char c[5000000]; int main(){ cin.getline(a, 8000000); cin.getline(c, 5000000); int t = strlen(a); REP(i, t){ if(a[i] == '|'){ strcpy(&b[0], &a[i+1]); a[i] = '\0'; break; } } int x = strlen(a), y = strlen(b), z = strlen(c); int p = 0; if(x < y){ int v = min(z, y-x); REP(i, v){ a[x++] = c[p++]; } z -= v; } if(y < x){ int v = min(z, x-y); REP(i, v){ b[y++] = c[p++]; } z -= v; } a[x] = '\0'; b[y] = '\0'; if(y == x && z%2 == 0){ REP(i, z/2){ a[x++] = c[p++]; } REP(i, z/2){ b[y++] = c[p++]; } a[x] = '\0'; b[y] = '\0'; printf("%s|%s\n", &a[0], &b[0]); } else printf("Impossible\n"); }
lizij/Leetcode
src/Sum_of_Two_Integers/Solution.java
package Sum_of_Two_Integers; public class Solution { public int getSum(int a, int b) { return (b == 0) ? a : getSum(a ^ b, (a & b) << 1); } public static void main(String[] args) { } }
bieniekmateusz/forcebalance
src/tests/test_continue.py
from __future__ import absolute_import from builtins import str import os, sys, shutil from .__init__ import ForceBalanceTestCase from forcebalance.parser import parse_inputs from forcebalance.forcefield import FF from forcebalance.objective import Objective from forcebalance.optimizer import Optimizer, Counter import pytest class TestWaterTutorial(ForceBalanceTestCase): def setup_method(self, method): super(TestWaterTutorial, self).setup_method(method) self.cwd = os.path.dirname(os.path.realpath(__file__)) # copy folder 'files/test_liquid' into a new folder 'files/test_liquid.run' files_folder = os.path.join(self.cwd, 'files') tmpfolder = os.path.join(self.cwd, 'files', 'test_continue.run') source_folder = os.path.join(self.cwd, '../../studies/001_water_tutorial') if os.path.isdir(tmpfolder): shutil.rmtree(tmpfolder) os.mkdir(tmpfolder) shutil.copytree(os.path.join(source_folder, 'forcefield'), os.path.join(tmpfolder, 'forcefield')) shutil.copytree(os.path.join(source_folder, 'targets'), os.path.join(tmpfolder, 'targets')) shutil.copy(os.path.join(files_folder, "test_continue.sav"), tmpfolder) shutil.copy(os.path.join(files_folder, "test_continue.in"), tmpfolder) shutil.copytree(os.path.join(files_folder, "test_continue.tmp"), os.path.join(tmpfolder,"test_continue.tmp")) os.chdir(tmpfolder) def teardown_method(self): tmpfolder = os.path.join(self.cwd, 'files', 'test_continue.run') if os.path.isdir(tmpfolder): shutil.rmtree(tmpfolder) super(TestWaterTutorial, self).teardown_method() def test_continue(self): """Check continuation from a previous run""" if sys.version_info < (3,0): pytest.skip("Existing pickle file only works with Python 3") self.logger.debug("\nSetting input file to 'test_continue.in'\n") input_file='test_continue.in' ## The general options and target options that come from parsing the input file self.logger.debug("Parsing inputs...\n") options, tgt_opts = parse_inputs(input_file) options['continue'] = True self.logger.debug("options:\n%s\n\ntgt_opts:\n%s\n\n" % (str(options), str(tgt_opts))) assert isinstance(options, dict), "Parser gave incorrect type for options" assert isinstance(tgt_opts, list), "Parser gave incorrect type for tgt_opts" for target in tgt_opts: assert isinstance(target, dict), "Parser gave incorrect type for target dict" ## The force field component of the project forcefield = FF(options) assert isinstance(forcefield, FF), "Expected forcebalance forcefield object" ## The objective function objective = Objective(options, tgt_opts, forcefield) assert isinstance(objective, Objective), "Expected forcebalance objective object" ## The optimizer component of the project self.logger.debug("Creating optimizer: ") optimizer = Optimizer(options, objective, forcefield) assert isinstance(optimizer, Optimizer), "Expected forcebalance optimizer object" self.logger.debug(str(optimizer)+'\n') ## Actually run the optimizer. self.logger.debug("Done setting up! Running optimizer...\n") result = optimizer.Run() self.logger.debug("\nOptimizer finished. Final results:\n") self.logger.debug(str(result)+'\n') assert optimizer.iterinit == 2, "Initial iteration counter is incorrect" assert optimizer.iteration == 2, "Final iteration counter is incorrect" # self.assertNdArrayEqual(EXPECTED_WATER_RESULTS,result,delta=0.001, # msg="\nCalculation results have changed from previously calculated values.\n" # "If this seems reasonable, update EXPECTED_WATER_RESULTS in test_system.py with these values") # # Fail if calculation takes longer than previously to converge # self.assertGreaterEqual(ITERATIONS_TO_CONVERGE, Counter(), msg="\nCalculation took longer than expected to converge (%d iterations vs previous of %d)" %\ # (ITERATIONS_TO_CONVERGE, Counter()))
packtBhagyashree/Java-EE-8-High-Performance-video-
Section4/CollectionsCompare/jmh-tests/src/main/java/collections/compare/demo/cards/CartesianProductTest.java
package collections.compare.demo.cards; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import io.vavr.collection.List; import org.eclipse.collections.api.set.sorted.ImmutableSortedSet; import org.eclipse.collections.impl.collector.Collectors2; import org.eclipse.collections.impl.factory.Sets; import org.eclipse.collections.impl.factory.SortedSets; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.State; @State(Scope.Thread) @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Fork(2) public class CartesianProductTest { private EnumSet<Suit> suits = EnumSet.allOf(Suit.class); private EnumSet<Rank> ranks = EnumSet.allOf(Rank.class); @Benchmark public int cartesianProductJDKUnmodifiableSortedSet() { SortedSet<Card> set = suits.stream() .flatMap(suit -> ranks.stream().map(rank -> new Card(rank, suit))) .collect(Collectors.collectingAndThen( Collectors.toCollection(TreeSet::new), Collections::unmodifiableSortedSet)); return set.size(); } @Benchmark public int cartesianProductECImmutableSortedSet1() { ImmutableSortedSet<Card> set = ranks.stream() .flatMap(rank -> suits.stream().map(suit -> new Card(rank, suit))) .collect(Collectors2.toImmutableSortedSet()); return set.size(); } @Benchmark public int cartesianProductECImmutableSortedSet2() { ImmutableSortedSet<Card> set = SortedSets.immutable.with(ranks.stream() .flatMap(rank -> suits.stream().map(suit -> new Card(rank, suit))) .toArray(Card[]::new)); return set.size(); } @Benchmark public int cartesianProductECImmutableSortedSet3() { ImmutableSortedSet<Card> set = Sets.cartesianProduct(ranks, suits) .collect(pair -> new Card(pair.getOne(), pair.getTwo())) .reduceInPlace(Collectors2.toImmutableSortedSet()); return set.size(); } @Benchmark public int cartesianProductGuavaImmutableSortedSet() { com.google.common.collect.ImmutableSortedSet<Card> set = suits.stream() .flatMap(suit -> ranks.stream().map(rank -> new Card(rank, suit))) .collect(com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet(Comparator.naturalOrder())); return set.size(); } @Benchmark public int cartesianProductApacheUnmodifiableSortedSet() { SortedSet<Card> set = suits.stream() .flatMap(suit -> ranks.stream().map(rank -> new Card(rank, suit))) .collect(Collectors.collectingAndThen( Collectors.toCollection(TreeSet::new), Collections::unmodifiableSortedSet)); return set.size(); } @Benchmark public int cartesianProductJavaslang() { io.vavr.collection.TreeSet<Card> set = io.vavr.collection.TreeSet.ofAll(suits) .flatMap(suit -> List.ofAll(ranks).map(rank -> new Card(rank, suit))); return set.size(); } }
tizenorg/platform.core.uifw.dali-core
dali/internal/event/images/frame-buffer-image-impl.cpp
/* * Copyright (c) 2015 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali/internal/event/images/frame-buffer-image-impl.h> // INTERNAL INCLUDES #include <dali/public-api/object/type-registry.h> #include <dali/internal/event/common/thread-local-storage.h> #include <dali/internal/event/resources/resource-client.h> namespace Dali { namespace Internal { namespace { TypeRegistration mType( typeid( Dali::FrameBufferImage ), typeid( Dali::Image ), NULL ); } // unnamed namespace FrameBufferImagePtr FrameBufferImage::New( unsigned int width, unsigned int height, Pixel::Format pixelFormat, RenderBuffer::Format bufferformat ) { FrameBufferImagePtr image = new FrameBufferImage( width, height, pixelFormat, bufferformat ); image->Initialize(); return image; } FrameBufferImagePtr FrameBufferImage::New( NativeImageInterface& nativeImage ) { FrameBufferImagePtr image = new FrameBufferImage( nativeImage ); image->Initialize(); return image; } FrameBufferImage::FrameBufferImage( unsigned int width, unsigned int height, Pixel::Format pixelFormat, RenderBuffer::Format bufferformat ) : Image(), mNativeImage(0), mPixelFormat( pixelFormat ), mBufferFormat( bufferformat ), mIsNativeFbo( false ) { mWidth = width; mHeight = height; } FrameBufferImage::FrameBufferImage( NativeImageInterface& nativeImage ) : Image(), mNativeImage( &nativeImage ), mPixelFormat( Pixel::FIRST_VALID_PIXEL_FORMAT ), mBufferFormat( RenderBuffer::COLOR ), mIsNativeFbo( true ) { mWidth = nativeImage.GetWidth(); mHeight = nativeImage.GetHeight(); } void FrameBufferImage::Connect() { ++mConnectionCount; if (mConnectionCount == 1) { // ticket was thrown away when related actors went offstage if (!mTicket) { ResourceClient& resourceClient = ThreadLocalStorage::Get().GetResourceClient(); if (mNativeImage) { mTicket = resourceClient.AddFrameBufferImage(*mNativeImage); mTicket->AddObserver(*this); } else { mTicket = resourceClient.AddFrameBufferImage(mWidth, mHeight, mPixelFormat, mBufferFormat); mTicket->AddObserver(*this); } } } } void FrameBufferImage::Disconnect() { if(!mTicket) { return; } DALI_ASSERT_DEBUG(mConnectionCount > 0); --mConnectionCount; if (mConnectionCount == 0 && mReleasePolicy == Dali::Image::UNUSED) { // release image memory when it's not visible anymore (decrease ref. count of texture) mTicket->RemoveObserver(*this); mTicket.Reset(); } } bool FrameBufferImage::IsNativeFbo() const { return mIsNativeFbo; } void FrameBufferImage::SetReleasePolicy( Dali::Image::ReleasePolicy releasePolicy ) { mReleasePolicy = releasePolicy; } FrameBufferImage::~FrameBufferImage() { } } // namespace Internal } // namespace Dali
NotBjoggisAtAll/Tomato-Engine
src/Widgets/meshwidget.h
#ifndef MESHWIDGET_H #define MESHWIDGET_H #include <QWidget> #include "types.h" struct Mesh; namespace Ui { class MeshWidget; } /** * The MeshWidget shows the Mesh component in the editor. */ class MeshWidget : public QWidget { Q_OBJECT public: /** * Default constructor. * Taking in an entity when created. * @param entity - Entity. */ explicit MeshWidget(Entity entity_, QWidget *parent = nullptr); /** * Default deconstructor. */ ~MeshWidget(); private slots: /** * Called when the Visible check box is changed. * Updates the Mesh component with if it should be visible or not. * @param checked - bool. */ void on_isVisible_toggled(bool checked); /** * Called when the Change Mesh button is pressed. * Opens a filedialog so the user can pick a file to load. * Loads the file and replaces the current Mesh with the new one. */ void on_changeMeshButton_clicked(); /** * Called when the "..." button is pressed. * Used to show a menu of options. */ void on_moreButton_clicked(); /** * Called when clicked on Remove inside the options menu. * Removes the component from the entity. */ void remove(); private: Ui::MeshWidget *ui; /// The Mesh component of the entity. Mesh* component_ = nullptr; /// The entity this MeshWidget is made for. Entity entity_ = -1; }; #endif // MESHWIDGET_H
akarakoc/Communityverse
community/migrations/0021_communities_communitytags.py
<gh_stars>0 # Generated by Django 2.2.6 on 2019-11-25 20:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('community', '0020_auto_20191125_1955'), ] operations = [ migrations.AddField( model_name='communities', name='communityTags', field=models.CharField(help_text='Enter community hash', max_length=2000, null=True), ), ]
onezens/QQTweak
qqtw/qqheaders7.2/APMidasMbInputViewController.h
<gh_stars>1-10 // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // #import "UIViewController.h" #import "APMidasMbH5ViewControllerDelegate.h" #import "APMidasMbInputViewDelegate.h" #import "UIGestureRecognizerDelegate.h" @class APMidasBizManager, APMidasMbH5ViewController, APMidasMbInputView, NSString; @interface APMidasMbInputViewController : UIViewController <APMidasMbInputViewDelegate, APMidasMbH5ViewControllerDelegate, UIGestureRecognizerDelegate> { id <APMidasMbInputViewControllerDelegate> mbInputDelegate; APMidasBizManager *bizManager; APMidasMbH5ViewController *webVc; APMidasMbInputView *inputView; } - (void)dealloc; - (void)didReceiveMemoryWarning; - (_Bool)gestureRecognizer:(id)arg1 shouldRecognizeSimultaneouslyWithGestureRecognizer:(id)arg2; - (_Bool)gestureRecognizerShouldBegin:(id)arg1; - (id)init; - (void)onGetMbError:(long long)arg1 inner:(id)arg2 msg:(id)arg3; - (void)onGetMbSucceeded; - (void)onMbH5InputClose; - (void)onMbH5InputSuccess; - (void)onMbInputViewClose:(id)arg1; - (void)onMbInputViewMainBtnClicked:(id)arg1; - (void)onMbInputViewNavigateToUrl:(id)arg1 webTitle:(id)arg2 fromView:(id)arg3; - (void)onMbInputViewResendBtnClicked:(id)arg1; - (void)onNetworkError:(long long)arg1; - (void)onTapBlank; - (_Bool)shouldAutorotateToInterfaceOrientation:(long long)arg1; - (unsigned long long)supportedInterfaceOrientations; - (void)viewDidLoad; - (void)viewWillAppear:(_Bool)arg1; - (void)viewWillDisappear:(_Bool)arg1; // Remaining properties @property(readonly, copy) NSString *debugDescription; @property(readonly, copy) NSString *description; @property(readonly) unsigned long long hash; @property(readonly) Class superclass; @end
migleankstutyte/kaavapino-ui
src/__tests__/components/input/FieldAutofill.test.js
<reponame>migleankstutyte/kaavapino-ui import { EDIT_PROJECT_TIMETABLE_FORM } from '../../../constants' import { getFieldAutofillValue } from '../../../utils/projectAutofillUtils' describe('Autofill tests', () => { it('Autofill rule succeeds (string)', () => { const field = {} const conditionObject = {} conditionObject.variable = 'a' conditionObject.operator = '==' conditionObject.comparison_value = 'testitulos' conditionObject.comparison_value_type = 'string' const condition = { condition: conditionObject, then_branch: 'uusitulos' } field.autofill_rule = [condition] const formValues = { a: 'testitulos' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe('uusitulos') }) it('Autofill rule not succeeds (string)', () => { const field = {} const conditionObject = {} conditionObject.variable = 'a' conditionObject.operator = '==' conditionObject.comparison_value = 'testjotain' conditionObject.comparison_value_type = 'string' const condition = { condition: conditionObject, then_branch: 'uusitulos' } field.autofill_rule = [condition] const formValues = { a: 'testitulos' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(undefined) }) it('Autofill rule succeeds (boolean)', () => { const field = {} const conditionObject = {} conditionObject.variable = 'a' conditionObject.operator = '==' conditionObject.comparison_value = true conditionObject.comparison_value_type = 'boolean' const condition = { condition: conditionObject, then_branch: 'True' } field.autofill_rule = [condition] const formValues = { a: true } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(true) }) it('Autofill rule not succeeds (boolean)', () => { const field = {} const conditionObject = {} conditionObject.variable = 'a' conditionObject.operator = '==' conditionObject.comparison_value = true conditionObject.comparison_value_type = 'boolean' const condition = { condition: conditionObject, then_branch: 'True' } field.autofill_rule = [condition] const formValues = { a: false } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(undefined) }) it('Autofill rule succeeds (boolean)', () => { const field = {} const conditionObject = {} conditionObject.variable = 'a' conditionObject.operator = '!=' conditionObject.comparison_value = true conditionObject.comparison_value_type = 'boolean' const condition = { condition: conditionObject, then_branch: 'True' } field.autofill_rule = [condition] const formValues = { a: true } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(undefined) }) it('Autofill rule not succeeds (boolean)', () => { const field = {} const conditionObject = {} conditionObject.variable = 'a' conditionObject.operator = '!=' conditionObject.comparison_value = true conditionObject.comparison_value_type = 'boolean' const condition = { condition: conditionObject, then_branch: 'True' } field.autofill_rule = [condition] const formValues = { a: false } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(true) }) it('Autofill rule succeeds multiple (string)', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'yksikon_johtaja' conditionObject1.operator = '==' conditionObject1.comparison_value = 'Mikko' conditionObject1.comparison_value_type = 'string' const conditionObject2 = {} conditionObject2.variable = 'yksikon_johtaja' conditionObject2.operator = '==' conditionObject2.comparison_value = 'Jaakko' conditionObject2.comparison_value_type = 'string' const conditionObject3 = {} conditionObject3.variable = 'yksikon_johtaja' conditionObject3.operator = '==' conditionObject3.comparison_value = 'Ville' conditionObject3.comparison_value_type = 'string' const condition = { condition: conditionObject1, then_branch: 'Eteläinen' } const condition2 = { condition: conditionObject2, then_branch: 'Pohjoinen' } const condition3 = { condition: conditionObject3, then_branch: 'Itäinen' } field.autofill_rule = [condition, condition2, condition3] const formValues = { yksikon_johtaja: 'Jaakko' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe('Pohjoinen') }) it('Autofill rule succeeds multiple (string)', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'yksikon_johtaja' conditionObject1.operator = '==' conditionObject1.comparison_value = 'Mikko' conditionObject1.comparison_value_type = 'string' const conditionObject2 = {} conditionObject2.variable = 'yksikon_johtaja' conditionObject2.operator = '==' conditionObject2.comparison_value = 'Jaakko' conditionObject2.comparison_value_type = 'string' const conditionObject3 = {} conditionObject3.variable = 'yksikon_johtaja' conditionObject3.operator = '==' conditionObject3.comparison_value = 'Ville' conditionObject3.comparison_value_type = 'string' const condition = { condition: conditionObject1, then_branch: 'Eteläinen' } const condition2 = { condition: conditionObject2, then_branch: 'Pohjoinen' } const condition3 = { condition: conditionObject3, then_branch: 'Itäinen' } field.autofill_rule = [condition, condition2, condition3] const formValues = { yksikon_johtaja: 'Ville' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe('Itäinen') }) it('Autofill rule not succeeds multiple (string)', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'yksikon_johtaja' conditionObject1.operator = '==' conditionObject1.comparison_value = 'Mikko' conditionObject1.comparison_value_type = 'string' const conditionObject2 = {} conditionObject2.variable = 'yksikon_johtaja' conditionObject2.operator = '==' conditionObject2.comparison_value = 'Jaakko' conditionObject2.comparison_value_type = 'string' const conditionObject3 = {} conditionObject3.variable = 'yksikon_johtaja' conditionObject3.operator = '==' conditionObject3.comparison_value = 'Ville' conditionObject3.comparison_value_type = 'string' const condition = { condition: conditionObject1, then_branch: 'Eteläinen' } const condition2 = { condition: conditionObject2, then_branch: 'Pohjoinen' } const condition3 = { condition: conditionObject3, then_branch: 'Itäinen' } field.autofill_rule = [condition, condition2, condition3] const formValues = { yksikon_johtaja: 'Kalevi' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(undefined) }) it('Autofill rule succeeds multiple (string)', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'vastuuyksikko' conditionObject1.operator = '==' conditionObject1.comparison_value = 'Läntinen alueyksikkö' conditionObject1.comparison_value_type = 'string' const conditionObject2 = {} conditionObject2.variable = 'vastuuyksikko' conditionObject2.operator = '==' conditionObject2.comparison_value = 'Koivusaari-Lauttasaari' conditionObject2.comparison_value_type = 'string' const conditionObject3 = {} conditionObject3.variable = 'vastuuyksikko' conditionObject3.operator = '==' conditionObject3.comparison_value = 'Kaarela-Vihdintie' conditionObject3.comparison_value_type = 'string' const conditionObject4 = {} conditionObject4.variable = 'vastuuyksikko' conditionObject4.operator = '==' conditionObject4.comparison_value = 'Pohjoinen alueyksikko' conditionObject4.comparison_value_type = 'string' const condition = { condition: conditionObject1, then_branch: '<NAME>' } const condition2 = { condition: conditionObject2, then_branch: 'Mikko Reinikainen' } const condition3 = { condition: conditionObject3, then_branch: 'Suvi Tyynilä' } const condition4 = { condition: conditionObject4, then_branch: '<NAME>arkemaa' } field.autofill_rule = [condition, condition2, condition3, condition4] const formValues = { vastuuyksikko: 'Kaarela-Vihdintie' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe('Suvi Tyynilä') }) it('Autofill rule succeeds multiple not found (string)', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'vastuuyksikko' conditionObject1.operator = '==' conditionObject1.comparison_value = 'Läntinen alueyksikkö' conditionObject1.comparison_value_type = 'string' const conditionObject2 = {} conditionObject2.variable = 'vastuuyksikko' conditionObject2.operator = '==' conditionObject2.comparison_value = 'Koivusaari-Lauttasaari' conditionObject2.comparison_value_type = 'string' const conditionObject3 = {} conditionObject3.variable = 'vastuuyksikko' conditionObject3.operator = '==' conditionObject3.comparison_value = 'Kaarela-Vihdintie' conditionObject3.comparison_value_type = 'string' const conditionObject4 = {} conditionObject4.variable = 'vastuuyksikko' conditionObject4.operator = '==' conditionObject4.comparison_value = 'Pohjoinen alueyksikko' conditionObject4.comparison_value_type = 'string' const condition = { condition: conditionObject1, then_branch: '<NAME>' } const condition2 = { condition: conditionObject2, then_branch: 'Mikko Reinikainen' } const condition3 = { condition: conditionObject3, then_branch: 'Suvi Tyynilä' } const condition4 = { condition: conditionObject4, then_branch: '<NAME>arkemaa' } field.autofill_rule = [condition, condition2, condition3, condition4] const formValues = { vastuuyksikko: 'Eteläinen yksikkö' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(undefined) }) it('Autofill rule succeeds (list)', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'vastuuyksikko' conditionObject1.operator = 'in' conditionObject1.comparison_value = ['eka', 'toka', 'kolmas'] conditionObject1.comparison_value_type = 'list<string>' const condition = { condition: conditionObject1, then_branch: 'loytyy_listasta' } field.autofill_rule = [condition] const formValues = { vastuuyksikko: 'toka' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe('loytyy_listasta') }) it('Autofill rule not succeeds (list)', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'vastuuyksikko' conditionObject1.operator = 'in' conditionObject1.comparison_value = ['eka', 'toka', 'kolmas'] conditionObject1.comparison_value_type = 'list<string>' const condition = { condition: conditionObject1, then_branch: 'loytyy_listasta' } field.autofill_rule = [condition] const formValues = { vastuuyksikko: 'neljäs' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(undefined) }) it('Autofill rule succeeds combine rule (boolean)', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'sisaltyyko_kaavoittamatonta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'sisaltyyko_kaavoitettua' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'asemakaava ja' } const condition2 = { condition: conditionObject2, then_branch: 'asemakaavan muuttaminen' } field.autofill_rule = [condition, condition2] const formValues = { sisaltyyko_kaavoittamatonta: true, sisaltyyko_kaavoitettua: false } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(' asemakaava ja') }) it('Autofill rule combine rule (boolean) 2', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'sisaltyyko_kaavoittamatonta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'sisaltyyko_kaavoitettua' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'asemakaava ja' } const condition2 = { condition: conditionObject2, then_branch: 'asemakaavan muuttaminen' } field.autofill_rule = [condition, condition2] const formValues = { sisaltyyko_kaavoittamatonta: false, sisaltyyko_kaavoitettua: true } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe( ' asemakaavan muuttaminen' ) }) it('Autofill rule succeeds combine rule (boolean) 3', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'sisaltyyko_kaavoittamatonta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'sisaltyyko_kaavoitettua' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'asemakaava ja' } const condition2 = { condition: conditionObject2, then_branch: 'asemakaavan muuttaminen' } field.autofill_rule = [condition, condition2] const formValues = { sisaltyyko_kaavoittamatonta: true, sisaltyyko_kaavoitettua: true } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe( ' asemakaava ja asemakaavan muuttaminen' ) }) it('Autofill rule succeeds combine rule (boolean) 4', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'sisaltyyko_kaavoittamatonta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'sisaltyyko_kaavoitettua' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'asemakaava ja' } const condition2 = { condition: conditionObject2, then_branch: 'asemakaavan muuttaminen' } field.autofill_rule = [condition, condition2] const formValues = { sisaltyyko_kaavoittamatonta: false, sisaltyyko_kaavoitettua: false } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(undefined) }) it('Autofill rule succeeds combine rule with variables (boolean) 1', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'sisaltyyko_kaavoittamatonta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'sisaltyyko_kaavoitettua' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'asemakaava ja', variables: ['projektin_nimi'] } const condition2 = { condition: conditionObject2, then_branch: 'asemakaavan muuttaminen', variables: ['projektin_nimi'] } field.autofill_rule = [condition, condition2] const formValues = { sisaltyyko_kaavoittamatonta: true, sisaltyyko_kaavoitettua: true, projektin_nimi: 'testiprojekti' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe( 'testiprojekti asemakaava ja asemakaavan muuttaminen' ) }) it('Autofill rule succeeds combine rule with variables (boolean) 2', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'sisaltyyko_kaavoittamatonta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'sisaltyyko_kaavoitettua' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'asemakaava ja', variables: ['projektin_nimi'] } const condition2 = { condition: conditionObject2, then_branch: 'asemakaavan muuttaminen', variables: ['projektin_nimi'] } const variables = { variables: ['projektin_nimi'] } field.autofill_rule = [condition, condition2, variables] const formValues = { sisaltyyko_kaavoittamatonta: false, sisaltyyko_kaavoitettua: true, projektin_nimi: 'testiprojekti' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe( 'testiprojekti asemakaavan muuttaminen' ) }) it('Autofill rule succeeds combine rule with variables (boolean) 3', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'sisaltyyko_kaavoittamatonta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'sisaltyyko_kaavoitettua' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'asemakaava ja', variables: ['projektin_nimi'] } const condition2 = { condition: conditionObject2, then_branch: 'asemakaavan muuttaminen', variables: ['projektin_nimi'] } field.autofill_rule = [condition, condition2] const formValues = { sisaltyyko_kaavoittamatonta: true, sisaltyyko_kaavoitettua: false, projektin_nimi: 'testiprojekti' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe( 'testiprojekti asemakaava ja' ) }) it('Autofill rule succeeds combine rule with variables (boolean) 4', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'sisaltyyko_kaavoittamatonta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'sisaltyyko_kaavoitettua' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'asemakaava ja', variables: ['projektin_nimi'] } const condition2 = { condition: conditionObject2, then_branch: 'asemakaavan muuttaminen', variables: ['projektin_nimi'] } field.autofill_rule = [condition, condition2] const formValues = { sisaltyyko_kaavoittamatonta: false, sisaltyyko_kaavoitettua: false, projektin_nimi: 'testiprojekti' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe('testiprojekti') }) it('Autofill rule succeeds combine rule with variables (boolean) 5', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'sisaltyyko_kaavoittamatonta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'sisaltyyko_kaavoitettua' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'asemakaava ja', variables: ['projektin_nimi'] } const condition2 = { condition: conditionObject2, then_branch: 'asemakaavan muuttaminen', variables: ['projektin_nimi'] } field.autofill_rule = [condition, condition2] const formValues = { sisaltyyko_kaavoittamatonta: true, sisaltyyko_kaavoitettua: true } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe( ' asemakaava ja asemakaavan muuttaminen' ) }) it('Autofill rule fails boolean if/else', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'maanomistus_yksityinen' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'maanomistus_yksityinen' conditionObject2.operator = '!=' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'False' } field.autofill_rule = [condition, condition2] const formValues = { maanomistus_yksityinen: false } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(false) }) it('Autofill rule succeeds boolean if/else', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'maanomistus_yksityinen' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'maanomistus_yksityinen' conditionObject2.operator = '!=' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'False' } field.autofill_rule = [condition, condition2] const formValues = { maanomistus_yksityinen: true } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(true) }) it('Autofill list', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'oasvaiheen_dokumentin_nimi' conditionObject1.operator = 'in' conditionObject1.comparison_value = ['OAS', 'saatekirje'] conditionObject1.comparison_value_type = 'list<string>' const conditionObject2 = {} conditionObject2.variable = 'oasvaiheen_dokumentin_nimi' conditionObject2.operator = 'in' conditionObject2.comparison_value = [ 'osallisten_osoitelista', 'Lehti-ilmoitus', 'oas_jatai_luonnosvaiheessa_mielipiteen_esittaneet', 'kirje_hakijalle_maksusta' ] conditionObject2.comparison_value_type = 'list<string>' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'False' } field.autofill_rule = [condition, condition2, []] const formValues = { oasvaiheen_dokumentin_nimi: 'Lehti-ilmoitus' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(false) }) it('Autofill rule list 2', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'oasvaiheen_dokumentin_nimi' conditionObject1.operator = 'in' conditionObject1.comparison_value = ['OAS', 'saatekirje'] conditionObject1.comparison_value_type = 'list<string>' const conditionObject2 = {} conditionObject2.variable = 'oasvaiheen_dokumentin_nimi' conditionObject2.operator = 'in' conditionObject2.comparison_value = [ 'osallisten_osoitelista', 'Lehti-ilmoitus', 'oas_jatai_luonnosvaiheessa_mielipiteen_esittaneet', 'kirje_hakijalle_maksusta' ] conditionObject2.comparison_value_type = 'list<string>' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'False' } field.autofill_rule = [condition, condition2, []] const formValues = { oasvaiheen_dokumentin_nimi: 'saatekirje' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(true) }) it('Autofill rule list 3', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'oasvaiheen_dokumentin_nimi' conditionObject1.operator = 'in' conditionObject1.comparison_value = ['OAS', 'saatekirje'] conditionObject1.comparison_value_type = 'list<string>' const conditionObject2 = {} conditionObject2.variable = 'oasvaiheen_dokumentin_nimi' conditionObject2.operator = 'in' conditionObject2.comparison_value = [ 'osallisten_osoitelista', 'Lehti-ilmoitus', 'oas_jatai_luonnosvaiheessa_mielipiteen_esittaneet', 'kirje_hakijalle_maksusta' ] conditionObject2.comparison_value_type = 'list<string>' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'False' } field.autofill_rule = [condition, condition2, []] const formValues = { oasvaiheen_dokumentin_nimi: 'tadaa' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(undefined) }) it('Autofill rule list 4', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'oasvaiheen_dokumentin_nimi' conditionObject1.operator = 'in' conditionObject1.comparison_value = ['OAS', 'saatekirje'] conditionObject1.comparison_value_type = 'list<string>' const conditionObject2 = {} conditionObject2.variable = 'oasvaiheen_dokumentin_nimi' conditionObject2.operator = 'in' conditionObject2.comparison_value = [ 'osallisten_osoitelista', 'Lehti-ilmoitus', 'oas_jatai_luonnosvaiheessa_mielipiteen_esittaneet', 'kirje_hakijalle_maksusta' ] conditionObject2.comparison_value_type = 'list<string>' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'False' } field.autofill_rule = [condition, condition2, []] const formValues = { oasvaiheen_dokumentin_nimi: 'kirje_hakijalle_maksusta' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(false) }) it('Autofill rule list 4', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'oasvaiheen_dokumentin_nimi' conditionObject1.operator = 'in' conditionObject1.comparison_value = ['OAS', 'saatekirje'] conditionObject1.comparison_value_type = 'list<string>' const conditionObject2 = {} conditionObject2.variable = 'oasvaiheen_dokumentin_nimi' conditionObject2.operator = 'in' conditionObject2.comparison_value = [ 'osallisten_osoitelista', 'Lehti-ilmoitus', 'oas_jatai_luonnosvaiheessa_mielipiteen_esittaneet', 'kirje_hakijalle_maksusta' ] conditionObject2.comparison_value_type = 'list<string>' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'False' } field.autofill_rule = [condition, condition2, []] const formValues = { oasvaiheen_dokumentin_nimi: 'kirje_hakijalle_maksusta' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(false) }) it('Autofill rule list 4', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'oasvaiheen_dokumentin_nimi' conditionObject1.operator = 'in' conditionObject1.comparison_value = ['OAS', 'saatekirje'] conditionObject1.comparison_value_type = 'list<string>' const conditionObject2 = {} conditionObject2.variable = 'oasvaiheen_dokumentin_nimi' conditionObject2.operator = 'in' conditionObject2.comparison_value = [ 'osallisten_osoitelista', 'Lehti-ilmoitus', 'oas_jatai_luonnosvaiheessa_mielipiteen_esittaneet', 'kirje_hakijalle_maksusta' ] conditionObject2.comparison_value_type = 'list<string>' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'False' } field.autofill_rule = [condition, condition2, []] const formValues = { testfieldset: { 0: { oasvaiheen_dokumentin_nimi: 'saatekirje' } } } const current = 'testfieldset[0].test' expect(getFieldAutofillValue(field.autofill_rule, formValues, current)).toBe(true) }) it('Autofill rule list 4 deeper', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'oasvaiheen_dokumentin_nimi' conditionObject1.operator = 'in' conditionObject1.comparison_value = ['OAS', 'saatekirje'] conditionObject1.comparison_value_type = 'list<string>' const conditionObject2 = {} conditionObject2.variable = 'oasvaiheen_dokumentin_nimi' conditionObject2.operator = 'in' conditionObject2.comparison_value = [ 'osallisten_osoitelista', 'Lehti-ilmoitus', 'oas_jatai_luonnosvaiheessa_mielipiteen_esittaneet', 'kirje_hakijalle_maksusta' ] conditionObject2.comparison_value_type = 'list<string>' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'False' } field.autofill_rule = [condition, condition2, []] const formValues = { testfieldset: { 0: { oasvaiheen_dokumentin_nimi: 'saatekirje' } } } const current = 'testfieldset[0].test' expect(getFieldAutofillValue(field.autofill_rule, formValues, current )).toBe(true) }) it('Autofill rule list 5 fails', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'oasvaiheen_dokumentin_nimi' conditionObject1.operator = 'in' conditionObject1.comparison_value = ['OAS', 'saatekirje'] conditionObject1.comparison_value_type = 'list<string>' const conditionObject2 = {} conditionObject2.variable = 'oasvaiheen_dokumentin_nimi' conditionObject2.operator = 'in' conditionObject2.comparison_value = [ 'osallisten_osoitelista', 'Lehti-ilmoitus', 'oas_jatai_luonnosvaiheessa_mielipiteen_esittaneet', 'kirje_hakijalle_maksusta' ] conditionObject2.comparison_value_type = 'list<string>' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'False' } field.autofill_rule = [condition, condition2, []] const formValues = { testfieldset: { 0: { oasvaiheen_dokumentin_nimi: 'saatkirje' } } } const current = 'testfieldset[0].test' expect(getFieldAutofillValue(field.autofill_rule, formValues,current)).toBe(undefined) }) it('Autofill rule list 6 false', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'oasvaiheen_dokumentin_nimi' conditionObject1.operator = 'in' conditionObject1.comparison_value = ['OAS', 'saatekirje'] conditionObject1.comparison_value_type = 'list<string>' const conditionObject2 = {} conditionObject2.variable = 'oasvaiheen_dokumentin_nimi' conditionObject2.operator = 'in' conditionObject2.comparison_value = [ 'osallisten_osoitelista', 'Lehti-ilmoitus', 'oas_jatai_luonnosvaiheessa_mielipiteen_esittaneet', 'kirje_hakijalle_maksusta' ] conditionObject2.comparison_value_type = 'list<string>' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'False' } field.autofill_rule = [condition, condition2, []] const formValues = { testfieldset: { 0: { oasvaiheen_dokumentin_nimi: 'kirje_hakijalle_maksusta' } } } const current = 'testfieldset[0].test' expect(getFieldAutofillValue(field.autofill_rule, formValues, current)).toBe(false) }) it('Autofill rule list 7 kaupunkiympäristölautakunta', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'kaavaprosessin_kokoluokka' conditionObject1.operator = 'in' conditionObject1.comparison_value = ['S', 'XS'] conditionObject1.comparison_value_type = 'list<string>' const conditionObject2 = {} conditionObject2.variable = 'kaavaprosessin_kokoluokka' conditionObject2.operator = 'in' conditionObject2.comparison_value = ['M', 'L', 'XL'] conditionObject2.comparison_value_type = 'list<string>' const condition = { condition: conditionObject1, then_branch : 'kaupunkiympäristölautakunta' } const condition2 = { condition: conditionObject2, then_branch : 'kaupunginvaltuusto' } field.autofill_rule =[condition, condition2, []] const formValues = { kaavaprosessin_kokoluokka: 'XS' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe('kaupunkiympäristölautakunta') }) it('Autofill rule list 8 kaupunginvaltuusto', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'kaavaprosessin_kokoluokka' conditionObject1.operator = 'in' conditionObject1.comparison_value = ['S', 'XS'] conditionObject1.comparison_value_type = 'list<string>' const conditionObject2 = {} conditionObject2.variable = 'kaavaprosessin_kokoluokka' conditionObject2.operator = 'in' conditionObject2.comparison_value = ['M', 'L', 'XL'] conditionObject2.comparison_value_type = 'list<string>' const condition = { condition: conditionObject1, then_branch : 'kaupunkiympäristölautakunta' } const condition2 = { condition: conditionObject2, then_branch : 'kaupunginvaltuusto' } field.autofill_rule =[condition, condition2, []] const formValues = { kaavaprosessin_kokoluokka: 'L' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe('kaupunginvaltuusto') }) it('Autofill rule list 7 variables', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'aloituskokous_suunniteltu_pvm' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: '', variables: ['aloituskokous_suunniteltu_pvm'] } field.autofill_rule = [condition] const formValues = { testfieldset: { 0: { aloituskokous_suunniteltu_pvm: '12.12.2012' } } } const current = 'testfieldset[0].test' expect(getFieldAutofillValue(field.autofill_rule, formValues, current)).toBe('12.12.2012') }) it('Autofill rule list 8 variables', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'aloituskokous_suunniteltu_pvm' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: '', variables: ['aloituskokous_suunniteltu_pvm'] } field.autofill_rule = [condition] const formValues = { testfieldset: { aloituskokous_suunniteltu_pvm: '12.12.2012' } } expect(getFieldAutofillValue(field.autofill_rule, formValues, undefined, EDIT_PROJECT_TIMETABLE_FORM)).toBe('12.12.2012') }) it('Autofill rule number bigger than', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'mielipiteiden_maara' conditionObject1.operator = '>' conditionObject1.comparison_value = 0 conditionObject1.comparison_value_type = 'number' const condition = { condition: conditionObject1, then_branch: 'True' } field.autofill_rule = [condition] const formValues = { mielipiteiden_maara: 2 } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(true) }) it('Autofill rule number bigger than', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'mielipiteiden_maara' conditionObject1.operator = '>' conditionObject1.comparison_value = 0 conditionObject1.comparison_value_type = 'number' const condition = { condition: conditionObject1, then_branch: true } field.autofill_rule = [condition] const formValues = { mielipiteiden_maara: 0 } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(false) }) it('Autofill multiple rule number bigger than', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'mielipiteiden_maara' conditionObject1.operator = '>' conditionObject1.comparison_value = 0 conditionObject1.comparison_value_type = 'number' const conditionObject2 = {} conditionObject2.variable = 'vaarien_mielipiteiden_maara' conditionObject2.operator = '>' conditionObject2.comparison_value = 0 conditionObject2.comparison_value_type = 'number' const condition = { condition: conditionObject1, then_branch: true } const condition2 = { condition: conditionObject2, then_branch: true } field.autofill_rule = [condition, condition2] const formValues = { mielipiteiden_maara: null, vaarien_mielipiteiden_maara: 1 } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(true) }) it('Autofill multiple rule number bigger than', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'mielipiteiden_maara' conditionObject1.operator = '>' conditionObject1.comparison_value = 0 conditionObject1.comparison_value_type = 'number' const conditionObject2 = {} conditionObject2.variable = 'vaarien_mielipiteiden_maara' conditionObject2.operator = '>' conditionObject2.comparison_value = 0 conditionObject2.comparison_value_type = 'number' const condition = { condition: conditionObject1, then_branch: true } const condition2 = { condition: conditionObject2, then_branch: true } field.autofill_rule = [condition, condition2] const formValues = { vaarien_mielipiteiden_maara: 1 } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(true) }) it('Autofill multiple rule number bigger than', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'mielipiteiden_maara' conditionObject1.operator = '>' conditionObject1.comparison_value = 0 conditionObject1.comparison_value_type = 'number' const conditionObject2 = {} conditionObject2.variable = 'vaarien_mielipiteiden_maara' conditionObject2.operator = '>' conditionObject2.comparison_value = 0 conditionObject2.comparison_value_type = 'number' const condition = { condition: conditionObject1, then_branch: true } const condition2 = { condition: conditionObject2, then_branch: true } field.autofill_rule = [condition, condition2] const formValues = { mielipiteiden_maara: 0, vaarien_mielipiteiden_maara: 1 } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(true) }) it('Autofill multiple rule number bigger than', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'mielipiteiden_maara' conditionObject1.operator = '>' conditionObject1.comparison_value = 0 conditionObject1.comparison_value_type = 'number' const conditionObject2 = {} conditionObject2.variable = 'vaarien_mielipiteiden_maara' conditionObject2.operator = '>' conditionObject2.comparison_value = 0 conditionObject2.comparison_value_type = 'number' const condition = { condition: conditionObject1, then_branch: true } const condition2 = { condition: conditionObject2, then_branch: true } field.autofill_rule = [condition, condition2] const formValues = {} expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(false) }) it('Autofill multiple rule three (1) number bigger than', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'mielipiteiden_maara' conditionObject1.operator = '>' conditionObject1.comparison_value = 0 conditionObject1.comparison_value_type = 'number' const conditionObject2 = {} conditionObject2.variable = 'vaarien_mielipiteiden_maara' conditionObject2.operator = '>' conditionObject2.comparison_value = 0 conditionObject2.comparison_value_type = 'number' const conditionObject3 = {} conditionObject3.variable = 'taas_vaarien_mielipiteiden_maara' conditionObject3.operator = '>' conditionObject3.comparison_value = 0 conditionObject3.comparison_value_type = 'number' const condition = { condition: conditionObject1, then_branch: true } const condition2 = { condition: conditionObject2, then_branch: true } const condition3 = { condition: conditionObject3, then_branch: 'True' } field.autofill_rule = [condition, condition2, condition3] const formValues = { mielipiteiden_maara: 0, vaarien_mielipiteiden_maara: 1, taas_vaarien_mielipiteiden_maara: 0 } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(true) }) it('Autofill multiple rule three (2) number bigger than', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'mielipiteiden_maara' conditionObject1.operator = '>' conditionObject1.comparison_value = 0 conditionObject1.comparison_value_type = 'number' const conditionObject2 = {} conditionObject2.variable = 'vaarien_mielipiteiden_maara' conditionObject2.operator = '>' conditionObject2.comparison_value = 0 conditionObject2.comparison_value_type = 'number' const conditionObject3 = {} conditionObject3.variable = 'taas_vaarien_mielipiteiden_maara' conditionObject3.operator = '>' conditionObject3.comparison_value = 0 conditionObject3.comparison_value_type = 'number' const condition = { condition: conditionObject1, then_branch: true } const condition2 = { condition: conditionObject2, then_branch: true } const condition3 = { condition: conditionObject3, then_branch: 'True' } field.autofill_rule = [condition, condition2, condition3] const formValues = { mielipiteiden_maara: 0, vaarien_mielipiteiden_maara: 0, taas_vaarien_mielipiteiden_maara: 1 } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(true) }) it('Autofill multiple rule three (3) number bigger than', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'mielipiteiden_maara' conditionObject1.operator = '>' conditionObject1.comparison_value = 0 conditionObject1.comparison_value_type = 'number' const conditionObject2 = {} conditionObject2.variable = 'vaarien_mielipiteiden_maara' conditionObject2.operator = '>' conditionObject2.comparison_value = 0 conditionObject2.comparison_value_type = 'number' const conditionObject3 = {} conditionObject3.variable = 'taas_vaarien_mielipiteiden_maara' conditionObject3.operator = '>' conditionObject3.comparison_value = 0 conditionObject3.comparison_value_type = 'number' const condition = { condition: conditionObject1, then_branch: true } const condition2 = { condition: conditionObject2, then_branch: true } const condition3 = { condition: conditionObject3, then_branch: 'True' } field.autofill_rule = [condition, condition2, condition3] const formValues = { mielipiteiden_maara: 0, vaarien_mielipiteiden_maara: 0, taas_vaarien_mielipiteiden_maara: 0 } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(false) }) it('Autofill rule succeeds string with formvalue', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'yksikon_johtaja' conditionObject1.operator = '==' conditionObject1.comparison_value = 'Mikko' conditionObject1.comparison_value_type = 'string' const condition = { condition: conditionObject1, then_branch: 'yksikon_johtaja' } field.autofill_rule = [condition] const formValues = { yksikon_johtaja: 'Mikko' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe('Mikko') }) it('Autofill rule fails string with formvalue', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'yksikon_johtaja_1' conditionObject1.operator = '==' conditionObject1.comparison_value = 'Mikko' conditionObject1.comparison_value_type = 'string' const condition = { condition: conditionObject1, then_branch: 'yksikon_johtaja' } field.autofill_rule = [condition] const formValues = { yksikon_johtaja_1: 'Jaska' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(undefined) }) it('Autofill rule fails string with formvalue', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'yksikon_johtaja' conditionObject1.operator = '==' conditionObject1.comparison_value = 'Mikko' conditionObject1.comparison_value_type = 'string' const condition = { condition: conditionObject1, then_branch: 'yksikon_johtaja' } field.autofill_rule = [condition] const formValues = { yksikon_johtaja: 'Jaska' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(undefined) }) it('New autofill radiobutton rule', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'tehty_muutos_muistutusten_johdosta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'tehty_muutos_lausuntojen_johdosta' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const conditionObject3 = {} conditionObject3.variable = 'ehty_muutos_muistutusten_johdosta' conditionObject3.operator = '!=' conditionObject3.comparison_value = true conditionObject3.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'True' } const condition3 = { condition: conditionObject3, then_branch: 'True' } field.autofill_rule = [condition, condition2, condition3] const formValues = { tehty_muutos_muistutusten_johdosta: 'joo, muutos tehty', tehty_muutos_lausuntojen_johdosta: 'joo' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(true) }) it('New autofill radiobutton rule 2', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'tehty_muutos_muistutusten_johdosta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'tehty_muutos_lausuntojen_johdosta' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const conditionObject3 = {} conditionObject3.variable = 'ehty_muutos_muistutusten_johdosta' conditionObject3.operator = '!=' conditionObject3.comparison_value = true conditionObject3.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'True' } const condition3 = { condition: conditionObject3, then_branch: 'True' } field.autofill_rule = [condition, condition2, condition3] const formValues = { tehty_muutos_lausuntojen_johdosta: 'joo, muutos tehty' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(true) }) it('New autofill radiobutton rule 3', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'tehty_muutos_muistutusten_johdosta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'tehty_muutos_lausuntojen_johdosta' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const conditionObject3 = {} conditionObject3.variable = 'tehty_muutos_muistutusten_johdosta' conditionObject3.operator = '!=' conditionObject3.comparison_value = true conditionObject3.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'True' } const condition3 = { condition: conditionObject3, then_branch: 'False' } field.autofill_rule = [condition, condition2, condition3] const formValues = {} expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(false) }) it('New autofill radiobutton rule 4', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'tehty_muutos_muistutusten_johdosta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'tehty_muutos_lausuntojen_johdosta' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const conditionObject3 = {} conditionObject3.variable = 'tehty_muutos_muistutusten_johdosta' conditionObject3.operator = '!=' conditionObject3.comparison_value = true conditionObject3.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'True' } const condition3 = { condition: conditionObject3, then_branch: 'False' } field.autofill_rule = [condition, condition2, condition3] const formValues = { tehty_muutos_muistutusten_johdosta: '', tehty_muutos_lausuntojen_johdosta: 'jee' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(true) }) it('New autofill radiobutton rule 5', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'tehty_muutos_muistutusten_johdosta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'tehty_muutos_lausuntojen_johdosta' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const conditionObject3 = {} conditionObject3.variable = 'tehty_muutos_muistutusten_johdosta' conditionObject3.operator = '!=' conditionObject3.comparison_value = true conditionObject3.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'True' } const condition3 = { condition: conditionObject3, then_branch: 'False' } field.autofill_rule = [condition, condition2, condition3] const formValues = { tehty_muutos_muistutusten_johdosta: null, tehty_muutos_lausuntojen_johdosta: 'jee' } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(true) }) it('New autofill radiobutton rule 6', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'tehty_muutos_muistutusten_johdosta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'tehty_muutos_lausuntojen_johdosta' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const conditionObject3 = {} conditionObject3.variable = 'tehty_muutos_muistutusten_johdosta' conditionObject3.operator = '!=' conditionObject3.comparison_value = true conditionObject3.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'True' } const condition3 = { condition: conditionObject3, then_branch: 'False' } field.autofill_rule = [condition, condition2, condition3] const formValues = { tehty_muutos_muistutusten_johdosta: null, tehty_muutos_lausuntojen_johdosta: null } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(false) }) it('New autofill radiobutton rule 7', () => { const field = {} const conditionObject1 = {} conditionObject1.variable = 'tehty_muutos_muistutusten_johdosta' conditionObject1.operator = '==' conditionObject1.comparison_value = true conditionObject1.comparison_value_type = 'boolean' const conditionObject2 = {} conditionObject2.variable = 'tehty_muutos_lausuntojen_johdosta' conditionObject2.operator = '==' conditionObject2.comparison_value = true conditionObject2.comparison_value_type = 'boolean' const conditionObject3 = {} conditionObject3.variable = 'tehty_muutos_muistutusten_johdosta' conditionObject3.operator = '!=' conditionObject3.comparison_value = true conditionObject3.comparison_value_type = 'boolean' const conditionObject4 = {} conditionObject3.variable = 'tehty_muutos_muistutusten_johdosta' conditionObject3.operator = '!=' conditionObject3.comparison_value = true conditionObject3.comparison_value_type = 'boolean' const condition = { condition: conditionObject1, then_branch: 'True' } const condition2 = { condition: conditionObject2, then_branch: 'True' } const condition3 = { condition: conditionObject3, then_branch: 'False' } const condition4 = { condition: conditionObject4, then_branch: 'False' } field.autofill_rule = [condition, condition2, condition3, condition4] const formValues = { tehty_muutos_muistutusten_johdosta: undefined } expect(getFieldAutofillValue(field.autofill_rule, formValues)).toBe(false) }) })
guyi-maple/message-stream
message-stream-api/src/main/java/tech/guyi/component/message/stream/api/stream/MessageStream.java
package tech.guyi.component.message.stream.api.stream; import lombok.NonNull; import tech.guyi.component.message.stream.api.attach.AttachKey; import java.util.Map; import java.util.Optional; /** * <p>消息流接口.</p> * <p>实现此接口,获取不同来源的消息</p> * @author guyi * @param <T> 消息推送返回类型 */ public interface MessageStream<T> { /** * <p>消息流名称.</p> * <p>用来标识不同的消息流, 不可重复或返回NULL</p> * @return 消息流名称 */ @NonNull String getName(); /** * 关闭消息流 */ void close(); /** * <p>注册消息主题</p> * <p>消息流实现支持Topic匹配时, 可重写此方法</p> * @param topic 消息主题 * @param attach 消息消费者传递的额外参数 */ default void register(String topic, Map<Class<? extends AttachKey>,Object> attach){ } /** * <p>取消消息主题的注册</p> * <p>消息流实现支持Topic匹配时, 可重写此方法</p> * @param topic 消息主题 * @param attach 消息消费者传递的额外参数 */ default void unregister(String topic, Map<Class<? extends AttachKey>,Object> attach){ } /** * 打开消息流 * @param receiver 消息接收者 */ void open(MessageReceiver receiver); /** * 发布消息 * @param topic Topic * @param bytes 消息内容 * @param attach 消息附加信息 */ Optional<T> publish(String topic, byte[] bytes, Map<Class<? extends AttachKey>,Object> attach); }
uni-william/prime
src/main/java/br/com/sis/bean/PesquisaTipoDespesaBean.java
<reponame>uni-william/prime package br.com.sis.bean; import java.io.Serializable; import java.util.List; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import org.primefaces.event.SelectEvent; import org.primefaces.event.UnselectEvent; import br.com.sis.entity.TipoDespesa; import br.com.sis.repository.TipoDespesaRepository; import br.com.sis.util.jsf.FacesUtil; @Named @ViewScoped public class PesquisaTipoDespesaBean implements Serializable { private static final long serialVersionUID = 1L; @Inject private TipoDespesaRepository repository; private List<TipoDespesa> listaTipoDespesas; private TipoDespesa tipoDespesaSelecionado; private boolean desabilitarBotoes; public boolean isDesabilitarBotoes() { return desabilitarBotoes; } public void setDesabilitarBotoes(boolean desabilitarBotoes) { this.desabilitarBotoes = desabilitarBotoes; } public TipoDespesa getTipoDespesaSelecionado() { return tipoDespesaSelecionado; } public void setTipoDespesaSelecionado(TipoDespesa tipoDespesaSelecionado) { this.tipoDespesaSelecionado = tipoDespesaSelecionado; } public List<TipoDespesa> getlistaTipoDespesas() { return listaTipoDespesas; } public void inicializar() { listaTipoDespesas = repository.listAll(); tipoDespesaSelecionado = new TipoDespesa(); this.desabilitarBotoes = true; } public void excluir() { if (repository.remover(tipoDespesaSelecionado) == true) { tipoDespesaSelecionado = new TipoDespesa(); listaTipoDespesas = repository.listAll(); FacesUtil.addInfoMessage("Registro excluído com sucesso!"); setDesabilitarBotoes(true); } } public void onRowSelect(SelectEvent event) { desabilitarBotoes = false; } public void onRowUnSelect(UnselectEvent event) { desabilitarBotoes = true; } }
luciano/studying_android
Views/app/src/main/java/android/teste/arquivos/views/MainActivity.java
package android.teste.arquivos.views; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends Activity { private static String CATEGORIA = "ViewsDep"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //usar para mudar tema em tempo de execucao PESQUISAR //setTheme(); setContentView(R.layout.activity_main); Log.i(CATEGORIA, "Antes listView"); final ListView listView = (ListView) findViewById(R.id.lista); String[] itens = new String[] { "Theme.AppCompat", "2", "3", "4", "5", "6", "7", "8"}; Log.i(CATEGORIA, "Criou string"); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, itens); listView.setAdapter(adapter); Log.i(CATEGORIA, "Criou arrayadapter e setou"); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.i("depuracao", "Click reconhecido"); switch (position) { case 0: startActivity(new Intent(MainActivity.this, Tema1.class)); break; case 1: startActivity(new Intent(MainActivity.this, Tema2.class)); break; case 2: startActivity(new Intent(MainActivity.this, Tema3.class)); break; case 3: startActivity(new Intent(MainActivity.this, Tema4.class)); break; case 4: startActivity(new Intent(MainActivity.this, Tema5.class)); break; case 5: startActivity(new Intent(MainActivity.this, Tema6.class)); break; case 6: startActivity(new Intent(MainActivity.this, Tema7.class)); break; case 7: startActivity(new Intent(MainActivity.this, Tema8.class)); break; case 8: startActivity(new Intent(MainActivity.this, Tema9.class)); break; } } }); /* listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.i("depuracao","Click reconhecido"); switch (position) { case 0: startActivity(new Intent(MainActivity.this, Tema1.class)); break; case 1: startActivity(new Intent(MainActivity.this, Tema2.class)); break; case 2: startActivity(new Intent(MainActivity.this, Tema3.class)); break; case 3: startActivity(new Intent(MainActivity.this, Tema4.class)); break; case 4: startActivity(new Intent(MainActivity.this, Tema5.class)); break; case 5: startActivity(new Intent(MainActivity.this, Tema6.class)); break; case 6: startActivity(new Intent(MainActivity.this, Tema7.class)); break; case 7: startActivity(new Intent(MainActivity.this, Tema8.class)); break; case 8: startActivity(new Intent(MainActivity.this, Tema9.class)); break; case 9: startActivity(new Intent(MainActivity.this, Tema10.class)); break; case 10: startActivity(new Intent(MainActivity.this, Tema11.class)); break; case 11: startActivity(new Intent(MainActivity.this, Tema12.class)); break; case 12: startActivity(new Intent(MainActivity.this, Tema13.class)); break; case 13: startActivity(new Intent(MainActivity.this, Tema14.class)); break; case 14: startActivity(new Intent(MainActivity.this, Tema15.class)); break; case 15: startActivity(new Intent(MainActivity.this, Tema16.class)); break; case 16: startActivity(new Intent(MainActivity.this, Tema17.class)); break; case 17: startActivity(new Intent(MainActivity.this, Tema18.class)); break; case 18: startActivity(new Intent(MainActivity.this, Tema19.class)); break; case 19: startActivity(new Intent(MainActivity.this, Tema20.class)); break; case 20: startActivity(new Intent(MainActivity.this, Tema21.class)); break; case 21: startActivity(new Intent(MainActivity.this, Tema22.class)); break; case 22: startActivity(new Intent(MainActivity.this, Tema23.class)); break; } } }); */ } }
wesulee/http-server
src/http_server/Request.java
package http_server; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; public class Request { public final Connection conn; public final Response resp; public RequestMethod method = RequestMethod.INVALID; public String URI = null; // request-URI public ArrayList<String> uriPath = null; public int uriPathIndex = -1; public final HashMap<String, String> queryParam; public final HashMap<RequestHeaderField, String> headerFields; public PostRequest post = null; public long contentLength = -1; public int versionMajor = 0; public int versionMinor = 0; public Request(Connection conn) { this.conn = conn; this.resp = new Response(this); this.queryParam = new HashMap<String, String>(); this.headerFields = new HashMap<RequestHeaderField, String>(); } void parseBody() throws HTTPException, IOException { if (method == RequestMethod.POST) { post = new PostRequest(this); } } public ArrayList<String> getRelativeURIPath() { if (uriPathIndex >= uriPath.size()) return new ArrayList<String>(0); else return new ArrayList<String>(uriPath.subList(uriPathIndex, uriPath.size())); } public String getRelativeURIPathStr() { ArrayList<String> relPath = getRelativeURIPath(); if (relPath.isEmpty()) return ""; else return String.join(File.separator, relPath); } }
ricardyn/ironpython-stubs
stubs.min/System/Windows/Controls/__init___parts/ViewBase.py
<filename>stubs.min/System/Windows/Controls/__init___parts/ViewBase.py class ViewBase(DependencyObject): """ Represents the base class for views that define the appearance of data in a System.Windows.Controls.ListView control. """ def ClearItem(self,*args): """ ClearItem(self: ViewBase,item: ListViewItem) Removes all bindings and styling that are set for an item. item: The System.Windows.Controls.ListViewItem to remove settings from. """ pass def GetAutomationPeer(self,*args): """ GetAutomationPeer(self: ViewBase,parent: ListView) -> IViewAutomationPeer Is called when a System.Windows.Controls.ListView control creates a System.Windows.Automation.Peers.ListViewAutomationPeer for its System.Windows.Controls.ListView.View. parent: The System.Windows.Controls.ListView control to use to create the System.Windows.Automation.Peers.ListViewAutomationPeer. Returns: The System.Windows.Automation.Peers.IViewAutomationPeer interface that implements the System.Windows.Automation.Peers.ListViewAutomationPeer for a custom System.Windows.Controls.ListView.View. """ pass def PrepareItem(self,*args): """ PrepareItem(self: ViewBase,item: ListViewItem) Prepares an item in the view for display,by setting bindings and styles. item: The item to prepare for display. """ pass DefaultStyleKey=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the object that is associated with the style for the view mode. """ ItemContainerDefaultStyleKey=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the style to use for the items in the view mode. """
yanagi0324/design_patterns_ruby
interpreter/or.rb
require 'expression' class Or < Expression def initialize(expr1, expr2) @expr1, @expr2 = expr1, expr2 end def evaluate(dir) result1 = @expr1.evaluate(dir) result2 = @expr2.evaluate(dir) (result1 + result2).sort.uniq end end
baocaixue/spring-dk
chapter15/jmx/src/main/java/com/isaac/ch15/AppStatistics.java
<reponame>baocaixue/spring-dk<filename>chapter15/jmx/src/main/java/com/isaac/ch15/AppStatistics.java<gh_stars>1-10 package com.isaac.ch15; public interface AppStatistics { int getTotalSingerCount(); }
liying2008/XDPlayer
app/src/main/java/lxy/liying/hdtvneu/db/XDVideoService.java
<filename>app/src/main/java/lxy/liying/hdtvneu/db/XDVideoService.java<gh_stars>1-10 package lxy.liying.hdtvneu.db; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.List; import lxy.liying.hdtvneu.domain.XDVideo; /** * ======================================================= * 作者:liying * 日期:2016/7/24 13:07 * 版本:1.0 * 描述:数据库操作层——操作表 xd_video * 备注: * ======================================================= */ public class XDVideoService extends BaseDbService { private DatabaseHelper dbHelper; /** * 构造方法 * * @param context */ public XDVideoService(Context context) { super(context); dbHelper = super.dbHelper; } /** * 将视频信息添加到数据库中 <br/> * * @param video */ public void addXDVideo(XDVideo video) { long position = getPosition(video.get_id()); SQLiteDatabase db = this.dbHelper.getWritableDatabase(); String sql = "INSERT INTO " + DBInfo.Table.TB_VIDEO_NAME + " VALUES (" + video.get_id() + ",'" + video.getFolder() + "','" + video.getVideoThumbnail() + "','" + video.getTitle() + "'," + video.getSize() + "," + video.getDuration() + ",'" + video.getData() + "','" + video.getDisplayName() + "','" + video.getMimeType() + "'," + video.getDateAdded() + "," + video.getDateModified() + ",'" + video.getArtist() + "','" + video.getAlbum() + "','" + video.getResolution() + "','" + video.getDescription() + "'," + position + ");"; db.execSQL(sql); db.close(); } /** * 获取缓存的视频信息 <br/> * * @return */ public List<XDVideo> getAllXDVideos() { SQLiteDatabase db = this.dbHelper.getReadableDatabase(); List<XDVideo> lists = null; Cursor cursor = db.query(DBInfo.Table.TB_VIDEO_NAME, null, null, null, null, null, XDVideo.FOLDER); if (cursor.getCount() > 0) { lists = new ArrayList<>(cursor.getCount()); XDVideo xdVideo = null; while (cursor.moveToNext()) { long _id = cursor.getLong(cursor.getColumnIndex(XDVideo._ID)); String folder = cursor.getString(cursor.getColumnIndex(XDVideo.FOLDER)); String videoThumbnail = cursor.getString(cursor.getColumnIndex(XDVideo.VIDEO_THUMBNAIL)); String title = cursor.getString(cursor.getColumnIndex(XDVideo.TITLE)); long size = cursor.getLong(cursor.getColumnIndex(XDVideo.SIZE)); long duration = cursor.getLong(cursor.getColumnIndex(XDVideo.DURATION)); String data = cursor.getString(cursor.getColumnIndex(XDVideo.DATA)); String displayName = cursor.getString(cursor.getColumnIndex(XDVideo.DISPLAY_NAME)); String mimeType = cursor.getString(cursor.getColumnIndex(XDVideo.MIME_TYPE)); long dateAdded = cursor.getLong(cursor.getColumnIndex(XDVideo.DATE_ADDED)); long dateModified = cursor.getLong(cursor.getColumnIndex(XDVideo.DATE_MODIFIED)); String artist = cursor.getString(cursor.getColumnIndex(XDVideo.ARTIST)); String album = cursor.getString(cursor.getColumnIndex(XDVideo.ALBUM)); String resolution = cursor.getString(cursor.getColumnIndex(XDVideo.RESOLUTION)); String description = cursor.getString(cursor.getColumnIndex(XDVideo.DESCRIPTION)); long position = cursor.getLong(cursor.getColumnIndex(XDVideo.POSITION)); xdVideo = new XDVideo(_id, folder, videoThumbnail, title, size, duration, data, displayName, mimeType, dateAdded, dateModified, artist, album, resolution, description, position); lists.add(xdVideo); } cursor.close(); } db.close(); return lists; } /** * 删除所有视频信息 */ public void removeAllVideoInfo() { SQLiteDatabase db = this.dbHelper.getWritableDatabase(); String sql = "DELETE FROM " + DBInfo.Table.TB_VIDEO_NAME; db.execSQL(sql); db.close(); } /** * 获取符合要求的缓存的视频信息 <br/> * * @param keyword * @return */ public List<XDVideo> getXDVideos(String keyword) { SQLiteDatabase db = this.dbHelper.getReadableDatabase(); List<XDVideo> lists = null; Cursor cursor = db.query(DBInfo.Table.TB_VIDEO_NAME, null, XDVideo.TITLE + " like '%" + keyword + "%'", null, null, null, XDVideo.FOLDER); if (cursor.getCount() > 0) { lists = new ArrayList<>(cursor.getCount()); XDVideo xdVideo = null; while (cursor.moveToNext()) { long _id = cursor.getLong(cursor.getColumnIndex(XDVideo._ID)); String folder = cursor.getString(cursor.getColumnIndex(XDVideo.FOLDER)); String videoThumbnail = cursor.getString(cursor.getColumnIndex(XDVideo.VIDEO_THUMBNAIL)); String title = cursor.getString(cursor.getColumnIndex(XDVideo.TITLE)); long size = cursor.getLong(cursor.getColumnIndex(XDVideo.SIZE)); long duration = cursor.getLong(cursor.getColumnIndex(XDVideo.DURATION)); String data = cursor.getString(cursor.getColumnIndex(XDVideo.DATA)); String displayName = cursor.getString(cursor.getColumnIndex(XDVideo.DISPLAY_NAME)); String mimeType = cursor.getString(cursor.getColumnIndex(XDVideo.MIME_TYPE)); long dateAdded = cursor.getLong(cursor.getColumnIndex(XDVideo.DATE_ADDED)); long dateModified = cursor.getLong(cursor.getColumnIndex(XDVideo.DATE_MODIFIED)); String artist = cursor.getString(cursor.getColumnIndex(XDVideo.ARTIST)); String album = cursor.getString(cursor.getColumnIndex(XDVideo.ALBUM)); String resolution = cursor.getString(cursor.getColumnIndex(XDVideo.RESOLUTION)); String description = cursor.getString(cursor.getColumnIndex(XDVideo.DESCRIPTION)); long position = cursor.getLong(cursor.getColumnIndex(XDVideo.POSITION)); xdVideo = new XDVideo(_id, folder, videoThumbnail, title, size, duration, data, displayName, mimeType, dateAdded, dateModified, artist, album, resolution, description, position); lists.add(xdVideo); } cursor.close(); } db.close(); return lists; } /** * 查询播放位置 * * @param _id * @return */ public long getPosition(long _id) { SQLiteDatabase db = this.dbHelper.getReadableDatabase(); Cursor cursor = db.query(DBInfo.Table.TB_VIDEO_NAME, new String[]{XDVideo.POSITION}, XDVideo._ID + "=" + _id, null, null, null, null); long position = 0L; if (cursor.getCount() > 0) { cursor.moveToFirst(); position = cursor.getLong(cursor.getColumnIndex(XDVideo.POSITION)); cursor.close(); } db.close(); return position; } /** * 更新播放进度 * * @param _id 本地视频ID * @param newPosition 新进度 */ public void updatePosition(long _id, long newPosition) { SQLiteDatabase db = this.dbHelper.getReadableDatabase(); String sql = "UPDATE " + DBInfo.Table.TB_VIDEO_NAME + " SET " + XDVideo.POSITION + "=" + newPosition + " WHERE " + XDVideo._ID + "=" + _id; db.execSQL(sql); db.close(); } /** * 获取某一视频信息 <br/> * * @param _id * @return */ public XDVideo getXDVideo(long _id) { SQLiteDatabase db = this.dbHelper.getReadableDatabase(); XDVideo xdVideo = null; Cursor cursor = db.query(DBInfo.Table.TB_VIDEO_NAME, null, XDVideo._ID + "=" + _id, null, null, null, XDVideo.FOLDER); if (cursor.getCount() > 0) { cursor.moveToFirst(); String folder = cursor.getString(cursor.getColumnIndex(XDVideo.FOLDER)); String videoThumbnail = cursor.getString(cursor.getColumnIndex(XDVideo.VIDEO_THUMBNAIL)); String title = cursor.getString(cursor.getColumnIndex(XDVideo.TITLE)); long size = cursor.getLong(cursor.getColumnIndex(XDVideo.SIZE)); long duration = cursor.getLong(cursor.getColumnIndex(XDVideo.DURATION)); String data = cursor.getString(cursor.getColumnIndex(XDVideo.DATA)); String displayName = cursor.getString(cursor.getColumnIndex(XDVideo.DISPLAY_NAME)); String mimeType = cursor.getString(cursor.getColumnIndex(XDVideo.MIME_TYPE)); long dateAdded = cursor.getLong(cursor.getColumnIndex(XDVideo.DATE_ADDED)); long dateModified = cursor.getLong(cursor.getColumnIndex(XDVideo.DATE_MODIFIED)); String artist = cursor.getString(cursor.getColumnIndex(XDVideo.ARTIST)); String album = cursor.getString(cursor.getColumnIndex(XDVideo.ALBUM)); String resolution = cursor.getString(cursor.getColumnIndex(XDVideo.RESOLUTION)); String description = cursor.getString(cursor.getColumnIndex(XDVideo.DESCRIPTION)); long position = cursor.getLong(cursor.getColumnIndex(XDVideo.POSITION)); xdVideo = new XDVideo(_id, folder, videoThumbnail, title, size, duration, data, displayName, mimeType, dateAdded, dateModified, artist, album, resolution, description, position); cursor.close(); } db.close(); return xdVideo; } /** * 删除指定的视频信息 * * @param _id 视频ID */ public void removeVideo(long _id) { SQLiteDatabase db = this.dbHelper.getWritableDatabase(); String sql = "DELETE FROM " + DBInfo.Table.TB_VIDEO_NAME + " WHERE " + XDVideo._ID + " = " + _id; db.execSQL(sql); db.close(); } /** * 删除指定文件夹里的视频信息 * * @param folder 视频文件夹 */ public void removeVideos(String folder) { SQLiteDatabase db = this.dbHelper.getWritableDatabase(); String sql = "DELETE FROM " + DBInfo.Table.TB_VIDEO_NAME + " WHERE " + XDVideo.FOLDER + " = '" + folder + "'"; db.execSQL(sql); db.close(); } }
Haakenlid/grenselandet
applications/tickets/migrations/0011_auto_20140919_2338.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('tickets', '0010_payment_currency'), ] operations = [ migrations.AlterField( model_name='payment', name='payment_time', field=models.DateTimeField(auto_now=True, help_text='Time the ticket was paid.'), ), migrations.AlterField( model_name='payment', name='transaction_id', field=models.CharField(null=True, editable=False, help_text='payment provider transaction id', max_length=50), ), ]
tmpsantos/chromium
components/component_updater/component_updater_service.cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/component_updater/component_updater_service.h" #include <algorithm> #include <set> #include <vector> #include "base/at_exit.h" #include "base/bind.h" #include "base/callback.h" #include "base/compiler_specific.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop_proxy.h" #include "base/observer_list.h" #include "base/sequenced_task_runner.h" #include "base/stl_util.h" #include "base/threading/sequenced_worker_pool.h" #include "base/threading/thread_checker.h" #include "base/timer/timer.h" #include "components/component_updater/component_patcher_operation.h" #include "components/component_updater/component_unpacker.h" #include "components/component_updater/component_updater_configurator.h" #include "components/component_updater/component_updater_ping_manager.h" #include "components/component_updater/component_updater_utils.h" #include "components/component_updater/crx_downloader.h" #include "components/component_updater/crx_update_item.h" #include "components/component_updater/update_checker.h" #include "components/component_updater/update_response.h" #include "url/gurl.h" namespace component_updater { // The component updater is designed to live until process shutdown, so // base::Bind() calls are not refcounted. namespace { // Returns true if the |proposed| version is newer than |current| version. bool IsVersionNewer(const Version& current, const std::string& proposed) { Version proposed_ver(proposed); return proposed_ver.IsValid() && current.CompareTo(proposed_ver) < 0; } // Returns true if a differential update is available, it has not failed yet, // and the configuration allows it. bool CanTryDiffUpdate(const CrxUpdateItem* update_item, const Configurator& config) { return HasDiffUpdate(update_item) && !update_item->diff_update_failed && config.DeltasEnabled(); } void AppendDownloadMetrics( const std::vector<CrxDownloader::DownloadMetrics>& source, std::vector<CrxDownloader::DownloadMetrics>* destination) { destination->insert(destination->end(), source.begin(), source.end()); } } // namespace CrxUpdateItem::CrxUpdateItem() : status(kNew), on_demand(false), diff_update_failed(false), error_category(0), error_code(0), extra_code1(0), diff_error_category(0), diff_error_code(0), diff_extra_code1(0) { } CrxUpdateItem::~CrxUpdateItem() { } CrxComponent::CrxComponent() : installer(NULL), allow_background_download(true) { } CrxComponent::~CrxComponent() { } ////////////////////////////////////////////////////////////////////////////// // The one and only implementation of the ComponentUpdateService interface. In // charge of running the show. The main method is ProcessPendingItems() which // is called periodically to do the upgrades/installs or the update checks. // An important consideration here is to be as "low impact" as we can to the // rest of the browser, so even if we have many components registered and // eligible for update, we only do one thing at a time with pauses in between // the tasks. Also when we do network requests there is only one |url_fetcher_| // in flight at a time. // There are no locks in this code, the main structure |work_items_| is mutated // only from the main thread. The unpack and installation is done in a blocking // pool thread. The network requests are done in the IO thread or in the file // thread. class CrxUpdateService : public ComponentUpdateService, public OnDemandUpdater { public: explicit CrxUpdateService(Configurator* config); virtual ~CrxUpdateService(); // Overrides for ComponentUpdateService. virtual void AddObserver(Observer* observer) OVERRIDE; virtual void RemoveObserver(Observer* observer) OVERRIDE; virtual Status Start() OVERRIDE; virtual Status Stop() OVERRIDE; virtual Status RegisterComponent(const CrxComponent& component) OVERRIDE; virtual std::vector<std::string> GetComponentIDs() const OVERRIDE; virtual OnDemandUpdater& GetOnDemandUpdater() OVERRIDE; virtual void MaybeThrottle(const std::string& crx_id, const base::Closure& callback) OVERRIDE; virtual scoped_refptr<base::SequencedTaskRunner> GetSequencedTaskRunner() OVERRIDE; // Context for a crx download url request. struct CRXContext { ComponentInstaller* installer; std::vector<uint8> pk_hash; std::string id; std::string fingerprint; CRXContext() : installer(NULL) {} }; private: enum ErrorCategory { kErrorNone = 0, kNetworkError, kUnpackError, kInstallError, }; enum StepDelayInterval { kStepDelayShort = 0, kStepDelayMedium, kStepDelayLong, }; // Overrides for ComponentUpdateService. virtual bool GetComponentDetails(const std::string& component_id, CrxUpdateItem* item) const OVERRIDE; // Overrides for OnDemandUpdater. virtual Status OnDemandUpdate(const std::string& component_id) OVERRIDE; void UpdateCheckComplete(int error, const std::string& error_message, const UpdateResponse::Results& results); void OnUpdateCheckSucceeded(const UpdateResponse::Results& results); void OnUpdateCheckFailed(int error, const std::string& error_message); void DownloadProgress(const std::string& component_id, const CrxDownloader::Result& download_result); void DownloadComplete(scoped_ptr<CRXContext> crx_context, const CrxDownloader::Result& download_result); Status OnDemandUpdateInternal(CrxUpdateItem* item); Status OnDemandUpdateWithCooldown(CrxUpdateItem* item); void ProcessPendingItems(); // Find a component that is ready to update. CrxUpdateItem* FindReadyComponent() const; // Prepares the components for an update check and initiates the request. // Returns true if an update check request has been made. Returns false if // no update check was needed or an error occured. bool CheckForUpdates(); void UpdateComponent(CrxUpdateItem* workitem); void ScheduleNextRun(StepDelayInterval step_delay); void ParseResponse(const std::string& xml); void Install(scoped_ptr<CRXContext> context, const base::FilePath& crx_path); void EndUnpacking(const std::string& component_id, const base::FilePath& crx_path, ComponentUnpacker::Error error, int extended_error); void DoneInstalling(const std::string& component_id, ComponentUnpacker::Error error, int extended_error); void ChangeItemState(CrxUpdateItem* item, CrxUpdateItem::Status to); size_t ChangeItemStatus(CrxUpdateItem::Status from, CrxUpdateItem::Status to); CrxUpdateItem* FindUpdateItemById(const std::string& id) const; void NotifyObservers(Observer::Events event, const std::string& id); bool HasOnDemandItems() const; Status GetServiceStatus(const CrxUpdateItem::Status status); scoped_ptr<Configurator> config_; scoped_ptr<UpdateChecker> update_checker_; scoped_ptr<PingManager> ping_manager_; scoped_refptr<ComponentUnpacker> unpacker_; scoped_ptr<CrxDownloader> crx_downloader_; // A collection of every work item. typedef std::vector<CrxUpdateItem*> UpdateItems; UpdateItems work_items_; base::OneShotTimer<CrxUpdateService> timer_; base::ThreadChecker thread_checker_; // Used to post responses back to the main thread. scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_; scoped_refptr<base::SequencedTaskRunner> blocking_task_runner_; bool running_; ObserverList<Observer> observer_list_; DISALLOW_COPY_AND_ASSIGN(CrxUpdateService); }; ////////////////////////////////////////////////////////////////////////////// CrxUpdateService::CrxUpdateService(Configurator* config) : config_(config), ping_manager_(new PingManager(*config)), main_task_runner_(base::MessageLoopProxy::current()), blocking_task_runner_(config->GetSequencedTaskRunner()), running_(false) { } CrxUpdateService::~CrxUpdateService() { // Because we are a singleton, at this point only the main thread should be // alive, this simplifies the management of the work that could be in // flight in other threads. Stop(); STLDeleteElements(&work_items_); } void CrxUpdateService::AddObserver(Observer* observer) { DCHECK(thread_checker_.CalledOnValidThread()); observer_list_.AddObserver(observer); } void CrxUpdateService::RemoveObserver(Observer* observer) { DCHECK(thread_checker_.CalledOnValidThread()); observer_list_.RemoveObserver(observer); } ComponentUpdateService::Status CrxUpdateService::Start() { // Note that RegisterComponent will call Start() when the first // component is registered, so it can be called twice. This way // we avoid scheduling the timer if there is no work to do. VLOG(1) << "CrxUpdateService starting up"; running_ = true; if (work_items_.empty()) return kOk; NotifyObservers(Observer::COMPONENT_UPDATER_STARTED, ""); VLOG(1) << "First update attempt will take place in " << config_->InitialDelay() << " seconds"; timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(config_->InitialDelay()), this, &CrxUpdateService::ProcessPendingItems); return kOk; } // Stop the main check + update loop. In flight operations will be // completed. ComponentUpdateService::Status CrxUpdateService::Stop() { VLOG(1) << "CrxUpdateService stopping"; running_ = false; timer_.Stop(); return kOk; } bool CrxUpdateService::HasOnDemandItems() const { class Helper { public: static bool IsOnDemand(CrxUpdateItem* item) { return item->on_demand; } }; return std::find_if(work_items_.begin(), work_items_.end(), Helper::IsOnDemand) != work_items_.end(); } // This function sets the timer which will call ProcessPendingItems() or // ProcessRequestedItem() if there is an on_demand item. There // are three kinds of waits: // - a short delay, when there is immediate work to be done. // - a medium delay, when there are updates to be applied within the current // update cycle, or there are components that are still unchecked. // - a long delay when a full check/update cycle has completed for all // components. void CrxUpdateService::ScheduleNextRun(StepDelayInterval step_delay) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(!update_checker_); CHECK(!timer_.IsRunning()); // It could be the case that Stop() had been called while a url request // or unpacking was in flight, if so we arrive here but |running_| is // false. In that case do not loop again. if (!running_) return; // Keep the delay short if in the middle of an update (step_delay), // or there are new requested_work_items_ that have not been processed yet. int64 delay_seconds = 0; if (!HasOnDemandItems()) { switch (step_delay) { case kStepDelayShort: delay_seconds = config_->StepDelay(); break; case kStepDelayMedium: delay_seconds = config_->StepDelayMedium(); break; case kStepDelayLong: delay_seconds = config_->NextCheckDelay(); break; } } else { delay_seconds = config_->StepDelay(); } if (step_delay != kStepDelayShort) { NotifyObservers(Observer::COMPONENT_UPDATER_SLEEPING, ""); // Zero is only used for unit tests. if (0 == delay_seconds) return; } VLOG(1) << "Scheduling next run to occur in " << delay_seconds << " seconds"; timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(delay_seconds), this, &CrxUpdateService::ProcessPendingItems); } // Given a extension-like component id, find the associated component. CrxUpdateItem* CrxUpdateService::FindUpdateItemById( const std::string& id) const { DCHECK(thread_checker_.CalledOnValidThread()); CrxUpdateItem::FindById finder(id); UpdateItems::const_iterator it = std::find_if(work_items_.begin(), work_items_.end(), finder); return it != work_items_.end() ? *it : NULL; } // Changes a component's status, clearing on_demand and firing notifications as // necessary. By convention, this is the only function that can change a // CrxUpdateItem's |status|. // TODO(waffles): Do we want to add DCHECKS for valid state transitions here? void CrxUpdateService::ChangeItemState(CrxUpdateItem* item, CrxUpdateItem::Status to) { DCHECK(thread_checker_.CalledOnValidThread()); if (to == CrxUpdateItem::kNoUpdate || to == CrxUpdateItem::kUpdated || to == CrxUpdateItem::kUpToDate) { item->on_demand = false; } item->status = to; switch (to) { case CrxUpdateItem::kCanUpdate: NotifyObservers(Observer::COMPONENT_UPDATE_FOUND, item->id); break; case CrxUpdateItem::kUpdatingDiff: case CrxUpdateItem::kUpdating: NotifyObservers(Observer::COMPONENT_UPDATE_READY, item->id); break; case CrxUpdateItem::kUpdated: NotifyObservers(Observer::COMPONENT_UPDATED, item->id); break; case CrxUpdateItem::kUpToDate: case CrxUpdateItem::kNoUpdate: NotifyObservers(Observer::COMPONENT_NOT_UPDATED, item->id); break; case CrxUpdateItem::kNew: case CrxUpdateItem::kChecking: case CrxUpdateItem::kDownloading: case CrxUpdateItem::kDownloadingDiff: case CrxUpdateItem::kLastStatus: // No notification for these states. break; } // Free possible pending network requests. if ((to == CrxUpdateItem::kUpdated) || (to == CrxUpdateItem::kUpToDate) || (to == CrxUpdateItem::kNoUpdate)) { for (std::vector<base::Closure>::iterator it = item->ready_callbacks.begin(); it != item->ready_callbacks.end(); ++it) { it->Run(); } item->ready_callbacks.clear(); } } // Changes all the components in |work_items_| that have |from| status to // |to| status and returns how many have been changed. size_t CrxUpdateService::ChangeItemStatus(CrxUpdateItem::Status from, CrxUpdateItem::Status to) { DCHECK(thread_checker_.CalledOnValidThread()); size_t count = 0; for (UpdateItems::iterator it = work_items_.begin(); it != work_items_.end(); ++it) { CrxUpdateItem* item = *it; if (item->status == from) { ChangeItemState(item, to); ++count; } } return count; } // Adds a component to be checked for upgrades. If the component exists it // it will be replaced and the return code is kReplaced. ComponentUpdateService::Status CrxUpdateService::RegisterComponent( const CrxComponent& component) { DCHECK(thread_checker_.CalledOnValidThread()); if (component.pk_hash.empty() || !component.version.IsValid() || !component.installer) return kError; std::string id(GetCrxComponentID(component)); CrxUpdateItem* uit = FindUpdateItemById(id); if (uit) { uit->component = component; return kReplaced; } uit = new CrxUpdateItem; uit->id.swap(id); uit->component = component; work_items_.push_back(uit); // If this is the first component registered we call Start to // schedule the first timer. Otherwise, reset the timer to trigger another // pass over the work items, if the component updater is sleeping, fact // indicated by a running timer. If the timer is not running, it means that // the service is busy updating something, and in that case, this component // will be picked up at the next pass. if (running_) { if (work_items_.size() == 1) { Start(); } else if (timer_.IsRunning()) { timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(config_->InitialDelay()), this, &CrxUpdateService::ProcessPendingItems); } } return kOk; } std::vector<std::string> CrxUpdateService::GetComponentIDs() const { DCHECK(thread_checker_.CalledOnValidThread()); std::vector<std::string> component_ids; for (UpdateItems::const_iterator it = work_items_.begin(); it != work_items_.end(); ++it) { const CrxUpdateItem* item = *it; component_ids.push_back(item->id); } return component_ids; } OnDemandUpdater& CrxUpdateService::GetOnDemandUpdater() { return *this; } void CrxUpdateService::MaybeThrottle(const std::string& crx_id, const base::Closure& callback) { DCHECK(thread_checker_.CalledOnValidThread()); // Check if we can on-demand update, else unblock the request anyway. CrxUpdateItem* item = FindUpdateItemById(crx_id); Status status = OnDemandUpdateWithCooldown(item); if (status == kOk || status == kInProgress) { item->ready_callbacks.push_back(callback); return; } callback.Run(); } scoped_refptr<base::SequencedTaskRunner> CrxUpdateService::GetSequencedTaskRunner() { return config_->GetSequencedTaskRunner(); } bool CrxUpdateService::GetComponentDetails(const std::string& component_id, CrxUpdateItem* item) const { DCHECK(thread_checker_.CalledOnValidThread()); const CrxUpdateItem* crx_update_item(FindUpdateItemById(component_id)); if (crx_update_item) *item = *crx_update_item; return crx_update_item != NULL; } // Start the process of checking for an update, for a particular component // that was previously registered. // |component_id| is a value returned from GetCrxComponentID(). ComponentUpdateService::Status CrxUpdateService::OnDemandUpdate( const std::string& component_id) { return OnDemandUpdateInternal(FindUpdateItemById(component_id)); } // This is the main loop of the component updater. It updates one component // at a time if updates are available. Otherwise, it does an update check or // takes a long sleep until the loop runs again. void CrxUpdateService::ProcessPendingItems() { DCHECK(thread_checker_.CalledOnValidThread()); CrxUpdateItem* ready_upgrade = FindReadyComponent(); if (ready_upgrade) { UpdateComponent(ready_upgrade); return; } if (!CheckForUpdates()) ScheduleNextRun(kStepDelayLong); } CrxUpdateItem* CrxUpdateService::FindReadyComponent() const { class Helper { public: static bool IsReadyOnDemand(CrxUpdateItem* item) { return item->on_demand && IsReady(item); } static bool IsReady(CrxUpdateItem* item) { return item->status == CrxUpdateItem::kCanUpdate; } }; std::vector<CrxUpdateItem*>::const_iterator it = std::find_if( work_items_.begin(), work_items_.end(), Helper::IsReadyOnDemand); if (it != work_items_.end()) return *it; it = std::find_if(work_items_.begin(), work_items_.end(), Helper::IsReady); if (it != work_items_.end()) return *it; return NULL; } // Prepares the components for an update check and initiates the request. // On demand components are always included in the update check request. // Otherwise, only include components that have not been checked recently. bool CrxUpdateService::CheckForUpdates() { const base::TimeDelta minimum_recheck_wait_time = base::TimeDelta::FromSeconds(config_->MinimumReCheckWait()); const base::Time now(base::Time::Now()); std::vector<CrxUpdateItem*> items_to_check; for (size_t i = 0; i != work_items_.size(); ++i) { CrxUpdateItem* item = work_items_[i]; DCHECK(item->status == CrxUpdateItem::kNew || item->status == CrxUpdateItem::kNoUpdate || item->status == CrxUpdateItem::kUpToDate || item->status == CrxUpdateItem::kUpdated); const base::TimeDelta time_since_last_checked(now - item->last_check); if (!item->on_demand && time_since_last_checked < minimum_recheck_wait_time) { VLOG(1) << "Skipping check for component update: id=" << item->id << ", time_since_last_checked=" << time_since_last_checked.InSeconds() << " seconds: too soon to check for an update"; continue; } VLOG(1) << "Scheduling update check for component id=" << item->id << ", time_since_last_checked=" << time_since_last_checked.InSeconds() << " seconds"; item->last_check = now; item->crx_urls.clear(); item->crx_diffurls.clear(); item->previous_version = item->component.version; item->next_version = Version(); item->previous_fp = item->component.fingerprint; item->next_fp.clear(); item->diff_update_failed = false; item->error_category = 0; item->error_code = 0; item->extra_code1 = 0; item->diff_error_category = 0; item->diff_error_code = 0; item->diff_extra_code1 = 0; item->download_metrics.clear(); items_to_check.push_back(item); ChangeItemState(item, CrxUpdateItem::kChecking); } if (items_to_check.empty()) return false; update_checker_ = UpdateChecker::Create(*config_, base::Bind(&CrxUpdateService::UpdateCheckComplete, base::Unretained(this))).Pass(); return update_checker_->CheckForUpdates(items_to_check, config_->ExtraRequestParams()); } void CrxUpdateService::UpdateComponent(CrxUpdateItem* workitem) { scoped_ptr<CRXContext> crx_context(new CRXContext); crx_context->pk_hash = workitem->component.pk_hash; crx_context->id = workitem->id; crx_context->installer = workitem->component.installer; crx_context->fingerprint = workitem->next_fp; const std::vector<GURL>* urls = NULL; bool allow_background_download = false; if (CanTryDiffUpdate(workitem, *config_)) { urls = &workitem->crx_diffurls; ChangeItemState(workitem, CrxUpdateItem::kDownloadingDiff); } else { // Background downloads are enabled only for selected components and // only for full downloads (see issue 340448). allow_background_download = workitem->component.allow_background_download; urls = &workitem->crx_urls; ChangeItemState(workitem, CrxUpdateItem::kDownloading); } // On demand component updates are always downloaded in foreground. const bool is_background_download = !workitem->on_demand && allow_background_download && config_->UseBackgroundDownloader(); crx_downloader_.reset( CrxDownloader::Create(is_background_download, config_->RequestContext(), blocking_task_runner_, config_->GetSingleThreadTaskRunner())); crx_downloader_->set_progress_callback( base::Bind(&CrxUpdateService::DownloadProgress, base::Unretained(this), crx_context->id)); crx_downloader_->StartDownload(*urls, base::Bind(&CrxUpdateService::DownloadComplete, base::Unretained(this), base::Passed(&crx_context))); } void CrxUpdateService::UpdateCheckComplete( int error, const std::string& error_message, const UpdateResponse::Results& results) { DCHECK(thread_checker_.CalledOnValidThread()); update_checker_.reset(); if (!error) OnUpdateCheckSucceeded(results); else OnUpdateCheckFailed(error, error_message); } // Handles a valid Omaha update check response by matching the results with // the registered components which were checked for updates. // If updates are found, prepare the components for the actual version upgrade. // One of these components will be drafted for the upgrade next time // ProcessPendingItems is called. void CrxUpdateService::OnUpdateCheckSucceeded( const UpdateResponse::Results& results) { size_t num_updates_pending = 0; DCHECK(thread_checker_.CalledOnValidThread()); VLOG(1) << "Update check succeeded."; std::vector<UpdateResponse::Result>::const_iterator it; for (it = results.list.begin(); it != results.list.end(); ++it) { CrxUpdateItem* crx = FindUpdateItemById(it->extension_id); if (!crx) continue; if (crx->status != CrxUpdateItem::kChecking) { NOTREACHED(); continue; // Not updating this component now. } if (it->manifest.version.empty()) { // No version means no update available. ChangeItemState(crx, CrxUpdateItem::kNoUpdate); VLOG(1) << "No update available for component: " << crx->id; continue; } if (!IsVersionNewer(crx->component.version, it->manifest.version)) { // The component is up to date. ChangeItemState(crx, CrxUpdateItem::kUpToDate); VLOG(1) << "Component already up-to-date: " << crx->id; continue; } if (!it->manifest.browser_min_version.empty()) { if (IsVersionNewer(config_->GetBrowserVersion(), it->manifest.browser_min_version)) { // The component is not compatible with this Chrome version. VLOG(1) << "Ignoring incompatible component: " << crx->id; ChangeItemState(crx, CrxUpdateItem::kNoUpdate); continue; } } if (it->manifest.packages.size() != 1) { // Assume one and only one package per component. VLOG(1) << "Ignoring multiple packages for component: " << crx->id; ChangeItemState(crx, CrxUpdateItem::kNoUpdate); continue; } // Parse the members of the result and queue an upgrade for this component. crx->next_version = Version(it->manifest.version); VLOG(1) << "Update found for component: " << crx->id; typedef UpdateResponse::Result::Manifest::Package Package; const Package& package(it->manifest.packages[0]); crx->next_fp = package.fingerprint; // Resolve the urls by combining the base urls with the package names. for (size_t i = 0; i != it->crx_urls.size(); ++i) { const GURL url(it->crx_urls[i].Resolve(package.name)); if (url.is_valid()) crx->crx_urls.push_back(url); } for (size_t i = 0; i != it->crx_diffurls.size(); ++i) { const GURL url(it->crx_diffurls[i].Resolve(package.namediff)); if (url.is_valid()) crx->crx_diffurls.push_back(url); } ChangeItemState(crx, CrxUpdateItem::kCanUpdate); ++num_updates_pending; } // All components that are not included in the update response are // considered up to date. ChangeItemStatus(CrxUpdateItem::kChecking, CrxUpdateItem::kUpToDate); // If there are updates pending we do a short wait, otherwise we take // a longer delay until we check the components again. ScheduleNextRun(num_updates_pending > 0 ? kStepDelayShort : kStepDelayLong); } void CrxUpdateService::OnUpdateCheckFailed(int error, const std::string& error_message) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(error); size_t count = ChangeItemStatus(CrxUpdateItem::kChecking, CrxUpdateItem::kNoUpdate); DCHECK_GT(count, 0ul); VLOG(1) << "Update check failed."; ScheduleNextRun(kStepDelayLong); } // Called when progress is being made downloading a CRX. The progress may // not monotonically increase due to how the CRX downloader switches between // different downloaders and fallback urls. void CrxUpdateService::DownloadProgress( const std::string& component_id, const CrxDownloader::Result& download_result) { DCHECK(thread_checker_.CalledOnValidThread()); NotifyObservers(Observer::COMPONENT_UPDATE_DOWNLOADING, component_id); } // Called when the CRX package has been downloaded to a temporary location. // Here we fire the notifications and schedule the component-specific installer // to be called in the file thread. void CrxUpdateService::DownloadComplete( scoped_ptr<CRXContext> crx_context, const CrxDownloader::Result& download_result) { DCHECK(thread_checker_.CalledOnValidThread()); CrxUpdateItem* crx = FindUpdateItemById(crx_context->id); DCHECK(crx->status == CrxUpdateItem::kDownloadingDiff || crx->status == CrxUpdateItem::kDownloading); AppendDownloadMetrics(crx_downloader_->download_metrics(), &crx->download_metrics); crx_downloader_.reset(); if (download_result.error) { if (crx->status == CrxUpdateItem::kDownloadingDiff) { crx->diff_error_category = kNetworkError; crx->diff_error_code = download_result.error; crx->diff_update_failed = true; size_t count = ChangeItemStatus(CrxUpdateItem::kDownloadingDiff, CrxUpdateItem::kCanUpdate); DCHECK_EQ(count, 1ul); ScheduleNextRun(kStepDelayShort); return; } crx->error_category = kNetworkError; crx->error_code = download_result.error; size_t count = ChangeItemStatus(CrxUpdateItem::kDownloading, CrxUpdateItem::kNoUpdate); DCHECK_EQ(count, 1ul); // At this point, since both the differential and the full downloads failed, // the update for this component has finished with an error. ping_manager_->OnUpdateComplete(crx); // Move on to the next update, if there is one available. ScheduleNextRun(kStepDelayMedium); } else { size_t count = 0; if (crx->status == CrxUpdateItem::kDownloadingDiff) { count = ChangeItemStatus(CrxUpdateItem::kDownloadingDiff, CrxUpdateItem::kUpdatingDiff); } else { count = ChangeItemStatus(CrxUpdateItem::kDownloading, CrxUpdateItem::kUpdating); } DCHECK_EQ(count, 1ul); // Why unretained? See comment at top of file. blocking_task_runner_->PostDelayedTask( FROM_HERE, base::Bind(&CrxUpdateService::Install, base::Unretained(this), base::Passed(&crx_context), download_result.response), base::TimeDelta::FromMilliseconds(config_->StepDelay())); } } // Install consists of digital signature verification, unpacking and then // calling the component specific installer. All that is handled by the // |unpacker_|. If there is an error this function is in charge of deleting // the files created. void CrxUpdateService::Install(scoped_ptr<CRXContext> context, const base::FilePath& crx_path) { // This function owns the file at |crx_path| and the |context| object. unpacker_ = new ComponentUnpacker(context->pk_hash, crx_path, context->fingerprint, context->installer, config_->CreateOutOfProcessPatcher(), blocking_task_runner_); unpacker_->Unpack(base::Bind(&CrxUpdateService::EndUnpacking, base::Unretained(this), context->id, crx_path)); } void CrxUpdateService::EndUnpacking(const std::string& component_id, const base::FilePath& crx_path, ComponentUnpacker::Error error, int extended_error) { if (!DeleteFileAndEmptyParentDirectory(crx_path)) NOTREACHED() << crx_path.value(); main_task_runner_->PostDelayedTask( FROM_HERE, base::Bind(&CrxUpdateService::DoneInstalling, base::Unretained(this), component_id, error, extended_error), base::TimeDelta::FromMilliseconds(config_->StepDelay())); // Reset the unpacker last, otherwise we free our own arguments. unpacker_ = NULL; } // Installation has been completed. Adjust the component status and // schedule the next check. Schedule a short delay before trying the full // update when the differential update failed. void CrxUpdateService::DoneInstalling(const std::string& component_id, ComponentUnpacker::Error error, int extra_code) { DCHECK(thread_checker_.CalledOnValidThread()); ErrorCategory error_category = kErrorNone; switch (error) { case ComponentUnpacker::kNone: break; case ComponentUnpacker::kInstallerError: error_category = kInstallError; break; default: error_category = kUnpackError; break; } const bool is_success = error == ComponentUnpacker::kNone; CrxUpdateItem* item = FindUpdateItemById(component_id); if (item->status == CrxUpdateItem::kUpdatingDiff && !is_success) { item->diff_error_category = error_category; item->diff_error_code = error; item->diff_extra_code1 = extra_code; item->diff_update_failed = true; size_t count = ChangeItemStatus(CrxUpdateItem::kUpdatingDiff, CrxUpdateItem::kCanUpdate); DCHECK_EQ(count, 1ul); ScheduleNextRun(kStepDelayShort); return; } if (is_success) { item->component.version = item->next_version; item->component.fingerprint = item->next_fp; ChangeItemState(item, CrxUpdateItem::kUpdated); } else { item->error_category = error_category; item->error_code = error; item->extra_code1 = extra_code; ChangeItemState(item, CrxUpdateItem::kNoUpdate); } ping_manager_->OnUpdateComplete(item); // Move on to the next update, if there is one available. ScheduleNextRun(kStepDelayMedium); } void CrxUpdateService::NotifyObservers(Observer::Events event, const std::string& id) { DCHECK(thread_checker_.CalledOnValidThread()); FOR_EACH_OBSERVER(Observer, observer_list_, OnEvent(event, id)); } ComponentUpdateService::Status CrxUpdateService::OnDemandUpdateWithCooldown( CrxUpdateItem* uit) { if (!uit) return kError; // Check if the request is too soon. base::TimeDelta delta = base::Time::Now() - uit->last_check; if (delta < base::TimeDelta::FromSeconds(config_->OnDemandDelay())) return kError; return OnDemandUpdateInternal(uit); } ComponentUpdateService::Status CrxUpdateService::OnDemandUpdateInternal( CrxUpdateItem* uit) { if (!uit) return kError; uit->on_demand = true; // If there is an update available for this item, then continue processing // the update. This is an artifact of how update checks are done: in addition // to the on-demand item, the update check may include other items as well. if (uit->status != CrxUpdateItem::kCanUpdate) { Status service_status = GetServiceStatus(uit->status); // If the item is already in the process of being updated, there is // no point in this call, so return kInProgress. if (service_status == kInProgress) return service_status; // Otherwise the item was already checked a while back (or it is new), // set its status to kNew to give it a slightly higher priority. ChangeItemState(uit, CrxUpdateItem::kNew); } // In case the current delay is long, set the timer to a shorter value // to get the ball rolling. if (timer_.IsRunning()) { timer_.Stop(); timer_.Start(FROM_HERE, base::TimeDelta::FromSeconds(config_->StepDelay()), this, &CrxUpdateService::ProcessPendingItems); } return kOk; } ComponentUpdateService::Status CrxUpdateService::GetServiceStatus( CrxUpdateItem::Status status) { switch (status) { case CrxUpdateItem::kChecking: case CrxUpdateItem::kCanUpdate: case CrxUpdateItem::kDownloadingDiff: case CrxUpdateItem::kDownloading: case CrxUpdateItem::kUpdatingDiff: case CrxUpdateItem::kUpdating: return kInProgress; case CrxUpdateItem::kNew: case CrxUpdateItem::kUpdated: case CrxUpdateItem::kUpToDate: case CrxUpdateItem::kNoUpdate: return kOk; case CrxUpdateItem::kLastStatus: NOTREACHED() << status; } return kError; } /////////////////////////////////////////////////////////////////////////////// // The component update factory. Using the component updater as a singleton // is the job of the browser process. ComponentUpdateService* ComponentUpdateServiceFactory(Configurator* config) { DCHECK(config); return new CrxUpdateService(config); } } // namespace component_updater
matte21/istio
istioctl/pkg/install/verify_test.go
<reponame>matte21/istio<filename>istioctl/pkg/install/verify_test.go<gh_stars>1-10 // Copyright 2019 Istio Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package install import ( "fmt" "testing" "k8s.io/api/extensions/v1beta1" ) var ( availableDeployment = v1beta1.Deployment{ Status: v1beta1.DeploymentStatus{ Conditions: []v1beta1.DeploymentCondition{ { Type: v1beta1.DeploymentAvailable, }, }, }, } scaleUpRollingDeployment = v1beta1.Deployment{ Spec: v1beta1.DeploymentSpec{ Replicas: &[]int32{3}[0], }, Status: v1beta1.DeploymentStatus{ Conditions: []v1beta1.DeploymentCondition{ { Type: v1beta1.DeploymentProgressing, }, { Type: v1beta1.DeploymentAvailable, }, }, UpdatedReplicas: 2, }, } deletingOldRollingDeployment = v1beta1.Deployment{ Spec: v1beta1.DeploymentSpec{ Replicas: &[]int32{2}[0], }, Status: v1beta1.DeploymentStatus{ Conditions: []v1beta1.DeploymentCondition{ { Type: v1beta1.DeploymentProgressing, }, { Type: v1beta1.DeploymentAvailable, }, }, UpdatedReplicas: 2, AvailableReplicas: 2, Replicas: 3, }, } failedDeployment = v1beta1.Deployment{ Spec: v1beta1.DeploymentSpec{ Replicas: &[]int32{2}[0], }, Status: v1beta1.DeploymentStatus{ Conditions: []v1beta1.DeploymentCondition{ { Type: v1beta1.DeploymentReplicaFailure, }, }, UpdatedReplicas: 2, AvailableReplicas: 0, Replicas: 3, }, } deadlineExceededDeployment = v1beta1.Deployment{ Status: v1beta1.DeploymentStatus{ Conditions: []v1beta1.DeploymentCondition{ { Type: v1beta1.DeploymentProgressing, Reason: "ProgressDeadlineExceeded", }, }, }, } ) func TestGetDeploymentStatus(t *testing.T) { errCases := []*v1beta1.Deployment{ &scaleUpRollingDeployment, &deletingOldRollingDeployment, &failedDeployment, &deadlineExceededDeployment, } for i, c := range errCases { t.Run(fmt.Sprintf("[err-%v] ", i), func(tt *testing.T) { if err := getDeploymentStatus(c, "fooDeploy"); err == nil { tt.Fatalf("unexpected nil error") } }) } okCases := []*v1beta1.Deployment{ &availableDeployment, } for i, c := range okCases { t.Run(fmt.Sprintf("[ok-%v] ", i), func(tt *testing.T) { if err := getDeploymentStatus(c, "fooDeploy"); err != nil { tt.Fatalf("unexpected error: %v", err) } }) } } func TestGetDeploymentCondition(t *testing.T) { cases := []struct { status v1beta1.DeploymentStatus condType v1beta1.DeploymentConditionType shouldFind bool }{ { // Simple "find Available in Available" status: availableDeployment.Status, condType: v1beta1.DeploymentAvailable, shouldFind: true, }, { // find Available in Progressing,Available // valid in e.g. RollingUpdate status: scaleUpRollingDeployment.Status, condType: v1beta1.DeploymentAvailable, shouldFind: true, }, { // find Available in ReplicaFailure status: failedDeployment.Status, condType: v1beta1.DeploymentAvailable, shouldFind: false, }, } for i, c := range cases { t.Run(fmt.Sprintf("[%v] ", i), func(tt *testing.T) { dc := getDeploymentCondition(c.status, c.condType) if c.shouldFind == false { if dc != nil { tt.Fatalf("unexpected condition: got %v want nil", dc) } } else { if dc.Type != c.condType { tt.Fatalf("unexpected condition: got %v want %v", dc, c.condType) } } }) } } func TestFindResourceInSpec(t *testing.T) { cases := []struct { kind string plural string }{ { // Should find Istio resourcespecs kind: "Policy", plural: "policies", }, { // Should find Kubernetes resourcespecs kind: "Service", plural: "services", }, { // Should be empty for not-found kind: "ThisIsNotAKubernetesResourceSpecKind", plural: "", }, { // Should be empty for empty input kind: "", plural: "", }, } for i, c := range cases { t.Run(fmt.Sprintf("[%v] %v ", i, c.kind), func(tt *testing.T) { plural := findResourceInSpec(c.kind) if plural != c.plural { tt.Fatalf("unexpected plural from kind: got %v want %v", plural, c.plural) } }) } }
ausbin/qcor
tools/qopt/passes/xacc-jit-pass/jit_utils.hpp
<gh_stars>10-100 #pragma once #include "llvm/ADT/StringRef.h" #include "llvm/ExecutionEngine/JITSymbol.h" #include "llvm/ExecutionEngine/Orc/CompileUtils.h" #include "llvm/ExecutionEngine/Orc/Core.h" #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h" #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h" #include "llvm/ExecutionEngine/Orc/JITTargetMachineBuilder.h" #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h" #include "llvm/ExecutionEngine/SectionMemoryManager.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/LLVMContext.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/Error.h" #include "llvm/Support/raw_ostream.h" #include <memory> using namespace llvm; using namespace llvm::orc; namespace qcor { class XACCJIT { private: ExecutionSession ES; RTDyldObjectLinkingLayer ObjectLayer; IRCompileLayer CompileLayer; DataLayout DL; MangleAndInterner Mangle; ThreadSafeContext Ctx; JITDylib &MainJD; public: XACCJIT(JITTargetMachineBuilder JTMB, DataLayout DL) : ObjectLayer(ES, []() { return std::make_unique<SectionMemoryManager>(); }), CompileLayer(ES, ObjectLayer, ConcurrentIRCompiler(std::move(JTMB))), DL(std::move(DL)), Mangle(ES, this->DL), Ctx(std::make_unique<LLVMContext>()), MainJD(ES.createJITDylib("<main>")) { MainJD.addGenerator( cantFail(DynamicLibrarySearchGenerator::GetForCurrentProcess( DL.getGlobalPrefix()))); llvm::sys::DynamicLibrary::LoadLibraryPermanently(nullptr); } static Expected<std::unique_ptr<XACCJIT>> Create() { auto JTMB = JITTargetMachineBuilder::detectHost(); if (!JTMB) return JTMB.takeError(); auto DL = JTMB->getDefaultDataLayoutForTarget(); if (!DL) return DL.takeError(); return std::make_unique<XACCJIT>(std::move(*JTMB), std::move(*DL)); } const DataLayout &getDataLayout() const { return DL; } LLVMContext &getContext() { return *Ctx.getContext(); } Error addModule(std::unique_ptr<Module> M) { MainJD.addGenerator(cantFail(DynamicLibrarySearchGenerator::Load( "/home/cades/.xacc/lib/libxacc.so", DL.getGlobalPrefix()))); MainJD.addGenerator(cantFail(DynamicLibrarySearchGenerator::Load( "/home/cades/.xacc/lib/libqrt.so", DL.getGlobalPrefix()))); MainJD.addGenerator(cantFail(DynamicLibrarySearchGenerator::Load( "/home/cades/.xacc/lib/libqcor.so", DL.getGlobalPrefix()))); MainJD.addGenerator(cantFail(DynamicLibrarySearchGenerator::Load( "/home/cades/.xacc/lib/libCppMicroServices.so", DL.getGlobalPrefix()))); return CompileLayer.add(MainJD, ThreadSafeModule(std::move(M), Ctx)); } Expected<JITEvaluatedSymbol> lookup(StringRef Name) { return ES.lookup({&MainJD}, Mangle(Name.str())); } }; } // namespace qcor
Pokecube-Development/Pokecube-Core
src/main/java/pokecube/core/interfaces/pokemob/commandhandlers/AttackLocationHandler.java
<reponame>Pokecube-Development/Pokecube-Core package pokecube.core.interfaces.pokemob.commandhandlers; import io.netty.buffer.ByteBuf; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentTranslation; import net.minecraftforge.common.MinecraftForge; import pokecube.core.events.pokemob.combat.CommandAttackEvent; import pokecube.core.interfaces.IPokemob; import pokecube.core.interfaces.Move_Base; import pokecube.core.interfaces.pokemob.ai.CombatStates; import pokecube.core.moves.MovesUtils; import pokecube.core.network.pokemobs.PacketCommand.DefaultHandler; import thut.api.maths.Vector3; public class AttackLocationHandler extends DefaultHandler { Vector3 location; public AttackLocationHandler() { } public AttackLocationHandler(Vector3 location) { this.location = location.copy(); } @Override public void handleCommand(IPokemob pokemob) { int currentMove = pokemob.getMoveIndex(); CommandAttackEvent evt = new CommandAttackEvent(pokemob.getEntity(), null); MinecraftForge.EVENT_BUS.post(evt); if (!evt.isCanceled() && currentMove != 5 && MovesUtils.canUseMove(pokemob)) { Move_Base move = MovesUtils.getMoveFromName(pokemob.getMoves()[currentMove]); // Send move use message first. ITextComponent mess = new TextComponentTranslation("pokemob.action.usemove", pokemob.getPokemonDisplayName(), new TextComponentTranslation(MovesUtils.getUnlocalizedMove(move.getName()))); if (fromOwner()) pokemob.displayMessageToOwner(mess); // If too hungry, send message about that. if (pokemob.getHungerTime() > 0) { mess = new TextComponentTranslation("pokemob.action.hungry", pokemob.getPokemonDisplayName()); if (fromOwner()) pokemob.displayMessageToOwner(mess); return; } // Otherwise set the location for execution of move. pokemob.setCombatState(CombatStates.NEWEXECUTEMOVE, true); pokemob.setTargetPos(location); } } @Override public void writeToBuf(ByteBuf buf) { super.writeToBuf(buf); location.writeToBuff(buf); } @Override public void readFromBuf(ByteBuf buf) { super.readFromBuf(buf); location = Vector3.readFromBuff(buf); } }
dhirajsb/camel
components/camel-web/src/main/webapp/js/dojox/gfx/attach.js
<reponame>dhirajsb/camel /* Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ dojo.require("dojox.gfx"); dojo.requireIf(dojox.gfx.renderer=="svg","dojox.gfx.svg_attach"); dojo.requireIf(dojox.gfx.renderer=="vml","dojox.gfx.vml_attach"); dojo.requireIf(dojox.gfx.renderer=="silverlight","dojox.gfx.silverlight_attach"); dojo.requireIf(dojox.gfx.renderer=="canvas","dojox.gfx.canvas_attach");
stereoabuse/codewars
problems/function_multiplya_b.py
<reponame>stereoabuse/codewars # function multiply(a, b){ # JavaScript: }
skapil/practice-programming
kickstart/recursion/strings_problems.py
<gh_stars>0 from types import SimpleNamespace def longest_common_substring(first_input: str, second_input: str): substring = SimpleNamespace(max_len=0, word=[]) def helper(first_idx: int, second_idx: int, slate: list, cur_len: int): if first_idx >= len(first_input) or second_idx >= len(second_input): return if substring.max_len < cur_len: substring.max_len = max(cur_len, substring.max_len) substring.word = "".join(slate.copy()) if first_input[first_idx] == second_input[second_idx]: slate.append(first_input[first_idx]) helper(first_idx + 1, second_idx + 1, slate, cur_len + 1) slate.pop() helper(first_idx + 1, second_idx, slate, 0) helper(first_idx, second_idx + 1, slate, 0) helper(0, 0, [], 0) print(substring) def test_longest_common_substring(): longest_common_substring("abdca", "cbda") longest_common_substring("passport", "ppsspt") if __name__ == "__main__": test_longest_common_substring()
pcsanwald/kibana
x-pack/test/functional/services/index.js
<reponame>pcsanwald/kibana /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ export * from './monitoring'; export { PipelineListProvider } from './pipeline_list'; export { PipelineEditorProvider } from './pipeline_editor'; export { RandomProvider } from './random'; export { AceEditorProvider } from './ace_editor'; export { GrokDebuggerProvider } from './grok_debugger'; export { UserMenuProvider } from './user_menu';
motor-dev/Motor
src/motor/scheduler/api/motor/scheduler/kernel/parameters/image3d.hh
/* Motor <<EMAIL>> see LICENSE for detail */ #ifndef MOTOR_SCHEDULER_KERNEL_PARAMETER_IMAGE3D_HH_ #define MOTOR_SCHEDULER_KERNEL_PARAMETER_IMAGE3D_HH_ /**************************************************************************************************/ #include <motor/scheduler/stdafx.h> #include <motor/scheduler/kernel/parameters/iparameter.meta.hh> #include <motor/scheduler/kernel/parameters/parametertype.hh> #include <motor/scheduler/kernel/product.hh> namespace Motor { namespace KernelScheduler { template < typename T > class Image3D : public IImage3D { private: static MOTOR_EXPORT IImage3D::ParameterRegistration s_registration; public: Image3D() { (void)s_registration; } ~Image3D() { } }; template < typename T > IImage3D::ParameterRegistration Image3D< T >::s_registration(motor_class< T >(), motor_class< Image3D< T > >()); }} // namespace Motor::KernelScheduler #include <motor/scheduler/kernel/parameters/image3d.factory.hh> /**************************************************************************************************/ #endif
jason-invision/electronegativity
test/checks/AtomicChecks/HTTP_RESOURCES_JS_CHECK_2_0.js
<reponame>jason-invision/electronegativity win = new BrowserWindow(); win.loadURL('https://doyensec.com/');
josehu07/SplitFS
kernel/linux-5.4/drivers/regulator/helpers.c
<filename>kernel/linux-5.4/drivers/regulator/helpers.c // SPDX-License-Identifier: GPL-2.0-or-later // // helpers.c -- Voltage/Current Regulator framework helper functions. // // Copyright 2007, 2008 Wolfson Microelectronics PLC. // Copyright 2008 SlimLogic Ltd. #include <linux/kernel.h> #include <linux/err.h> #include <linux/delay.h> #include <linux/regmap.h> #include <linux/regulator/consumer.h> #include <linux/regulator/driver.h> #include <linux/module.h> /** * regulator_is_enabled_regmap - standard is_enabled() for regmap users * * @rdev: regulator to operate on * * Regulators that use regmap for their register I/O can set the * enable_reg and enable_mask fields in their descriptor and then use * this as their is_enabled operation, saving some code. */ int regulator_is_enabled_regmap(struct regulator_dev *rdev) { unsigned int val; int ret; ret = regmap_read(rdev->regmap, rdev->desc->enable_reg, &val); if (ret != 0) return ret; val &= rdev->desc->enable_mask; if (rdev->desc->enable_is_inverted) { if (rdev->desc->enable_val) return val != rdev->desc->enable_val; return val == 0; } else { if (rdev->desc->enable_val) return val == rdev->desc->enable_val; return val != 0; } } EXPORT_SYMBOL_GPL(regulator_is_enabled_regmap); /** * regulator_enable_regmap - standard enable() for regmap users * * @rdev: regulator to operate on * * Regulators that use regmap for their register I/O can set the * enable_reg and enable_mask fields in their descriptor and then use * this as their enable() operation, saving some code. */ int regulator_enable_regmap(struct regulator_dev *rdev) { unsigned int val; if (rdev->desc->enable_is_inverted) { val = rdev->desc->disable_val; } else { val = rdev->desc->enable_val; if (!val) val = rdev->desc->enable_mask; } return regmap_update_bits(rdev->regmap, rdev->desc->enable_reg, rdev->desc->enable_mask, val); } EXPORT_SYMBOL_GPL(regulator_enable_regmap); /** * regulator_disable_regmap - standard disable() for regmap users * * @rdev: regulator to operate on * * Regulators that use regmap for their register I/O can set the * enable_reg and enable_mask fields in their descriptor and then use * this as their disable() operation, saving some code. */ int regulator_disable_regmap(struct regulator_dev *rdev) { unsigned int val; if (rdev->desc->enable_is_inverted) { val = rdev->desc->enable_val; if (!val) val = rdev->desc->enable_mask; } else { val = rdev->desc->disable_val; } return regmap_update_bits(rdev->regmap, rdev->desc->enable_reg, rdev->desc->enable_mask, val); } EXPORT_SYMBOL_GPL(regulator_disable_regmap); static int regulator_range_selector_to_index(struct regulator_dev *rdev, unsigned int rval) { int i; if (!rdev->desc->linear_range_selectors) return -EINVAL; rval &= rdev->desc->vsel_range_mask; for (i = 0; i < rdev->desc->n_linear_ranges; i++) { if (rdev->desc->linear_range_selectors[i] == rval) return i; } return -EINVAL; } /** * regulator_get_voltage_sel_pickable_regmap - pickable range get_voltage_sel * * @rdev: regulator to operate on * * Regulators that use regmap for their register I/O and use pickable * ranges can set the vsel_reg, vsel_mask, vsel_range_reg and vsel_range_mask * fields in their descriptor and then use this as their get_voltage_vsel * operation, saving some code. */ int regulator_get_voltage_sel_pickable_regmap(struct regulator_dev *rdev) { unsigned int r_val; int range; unsigned int val; int ret, i; unsigned int voltages_in_range = 0; if (!rdev->desc->linear_ranges) return -EINVAL; ret = regmap_read(rdev->regmap, rdev->desc->vsel_reg, &val); if (ret != 0) return ret; ret = regmap_read(rdev->regmap, rdev->desc->vsel_range_reg, &r_val); if (ret != 0) return ret; val &= rdev->desc->vsel_mask; val >>= ffs(rdev->desc->vsel_mask) - 1; range = regulator_range_selector_to_index(rdev, r_val); if (range < 0) return -EINVAL; for (i = 0; i < range; i++) voltages_in_range += (rdev->desc->linear_ranges[i].max_sel - rdev->desc->linear_ranges[i].min_sel) + 1; return val + voltages_in_range; } EXPORT_SYMBOL_GPL(regulator_get_voltage_sel_pickable_regmap); /** * regulator_set_voltage_sel_pickable_regmap - pickable range set_voltage_sel * * @rdev: regulator to operate on * @sel: Selector to set * * Regulators that use regmap for their register I/O and use pickable * ranges can set the vsel_reg, vsel_mask, vsel_range_reg and vsel_range_mask * fields in their descriptor and then use this as their set_voltage_vsel * operation, saving some code. */ int regulator_set_voltage_sel_pickable_regmap(struct regulator_dev *rdev, unsigned int sel) { unsigned int range; int ret, i; unsigned int voltages_in_range = 0; for (i = 0; i < rdev->desc->n_linear_ranges; i++) { voltages_in_range = (rdev->desc->linear_ranges[i].max_sel - rdev->desc->linear_ranges[i].min_sel) + 1; if (sel < voltages_in_range) break; sel -= voltages_in_range; } if (i == rdev->desc->n_linear_ranges) return -EINVAL; sel <<= ffs(rdev->desc->vsel_mask) - 1; sel += rdev->desc->linear_ranges[i].min_sel; range = rdev->desc->linear_range_selectors[i]; if (rdev->desc->vsel_reg == rdev->desc->vsel_range_reg) { ret = regmap_update_bits(rdev->regmap, rdev->desc->vsel_reg, rdev->desc->vsel_range_mask | rdev->desc->vsel_mask, sel | range); } else { ret = regmap_update_bits(rdev->regmap, rdev->desc->vsel_range_reg, rdev->desc->vsel_range_mask, range); if (ret) return ret; ret = regmap_update_bits(rdev->regmap, rdev->desc->vsel_reg, rdev->desc->vsel_mask, sel); } if (ret) return ret; if (rdev->desc->apply_bit) ret = regmap_update_bits(rdev->regmap, rdev->desc->apply_reg, rdev->desc->apply_bit, rdev->desc->apply_bit); return ret; } EXPORT_SYMBOL_GPL(regulator_set_voltage_sel_pickable_regmap); /** * regulator_get_voltage_sel_regmap - standard get_voltage_sel for regmap users * * @rdev: regulator to operate on * * Regulators that use regmap for their register I/O can set the * vsel_reg and vsel_mask fields in their descriptor and then use this * as their get_voltage_vsel operation, saving some code. */ int regulator_get_voltage_sel_regmap(struct regulator_dev *rdev) { unsigned int val; int ret; ret = regmap_read(rdev->regmap, rdev->desc->vsel_reg, &val); if (ret != 0) return ret; val &= rdev->desc->vsel_mask; val >>= ffs(rdev->desc->vsel_mask) - 1; return val; } EXPORT_SYMBOL_GPL(regulator_get_voltage_sel_regmap); /** * regulator_set_voltage_sel_regmap - standard set_voltage_sel for regmap users * * @rdev: regulator to operate on * @sel: Selector to set * * Regulators that use regmap for their register I/O can set the * vsel_reg and vsel_mask fields in their descriptor and then use this * as their set_voltage_vsel operation, saving some code. */ int regulator_set_voltage_sel_regmap(struct regulator_dev *rdev, unsigned sel) { int ret; sel <<= ffs(rdev->desc->vsel_mask) - 1; ret = regmap_update_bits(rdev->regmap, rdev->desc->vsel_reg, rdev->desc->vsel_mask, sel); if (ret) return ret; if (rdev->desc->apply_bit) ret = regmap_update_bits(rdev->regmap, rdev->desc->apply_reg, rdev->desc->apply_bit, rdev->desc->apply_bit); return ret; } EXPORT_SYMBOL_GPL(regulator_set_voltage_sel_regmap); /** * regulator_map_voltage_iterate - map_voltage() based on list_voltage() * * @rdev: Regulator to operate on * @min_uV: Lower bound for voltage * @max_uV: Upper bound for voltage * * Drivers implementing set_voltage_sel() and list_voltage() can use * this as their map_voltage() operation. It will find a suitable * voltage by calling list_voltage() until it gets something in bounds * for the requested voltages. */ int regulator_map_voltage_iterate(struct regulator_dev *rdev, int min_uV, int max_uV) { int best_val = INT_MAX; int selector = 0; int i, ret; /* Find the smallest voltage that falls within the specified * range. */ for (i = 0; i < rdev->desc->n_voltages; i++) { ret = rdev->desc->ops->list_voltage(rdev, i); if (ret < 0) continue; if (ret < best_val && ret >= min_uV && ret <= max_uV) { best_val = ret; selector = i; } } if (best_val != INT_MAX) return selector; else return -EINVAL; } EXPORT_SYMBOL_GPL(regulator_map_voltage_iterate); /** * regulator_map_voltage_ascend - map_voltage() for ascendant voltage list * * @rdev: Regulator to operate on * @min_uV: Lower bound for voltage * @max_uV: Upper bound for voltage * * Drivers that have ascendant voltage list can use this as their * map_voltage() operation. */ int regulator_map_voltage_ascend(struct regulator_dev *rdev, int min_uV, int max_uV) { int i, ret; for (i = 0; i < rdev->desc->n_voltages; i++) { ret = rdev->desc->ops->list_voltage(rdev, i); if (ret < 0) continue; if (ret > max_uV) break; if (ret >= min_uV && ret <= max_uV) return i; } return -EINVAL; } EXPORT_SYMBOL_GPL(regulator_map_voltage_ascend); /** * regulator_map_voltage_linear - map_voltage() for simple linear mappings * * @rdev: Regulator to operate on * @min_uV: Lower bound for voltage * @max_uV: Upper bound for voltage * * Drivers providing min_uV and uV_step in their regulator_desc can * use this as their map_voltage() operation. */ int regulator_map_voltage_linear(struct regulator_dev *rdev, int min_uV, int max_uV) { int ret, voltage; /* Allow uV_step to be 0 for fixed voltage */ if (rdev->desc->n_voltages == 1 && rdev->desc->uV_step == 0) { if (min_uV <= rdev->desc->min_uV && rdev->desc->min_uV <= max_uV) return 0; else return -EINVAL; } if (!rdev->desc->uV_step) { BUG_ON(!rdev->desc->uV_step); return -EINVAL; } if (min_uV < rdev->desc->min_uV) min_uV = rdev->desc->min_uV; ret = DIV_ROUND_UP(min_uV - rdev->desc->min_uV, rdev->desc->uV_step); if (ret < 0) return ret; ret += rdev->desc->linear_min_sel; /* Map back into a voltage to verify we're still in bounds */ voltage = rdev->desc->ops->list_voltage(rdev, ret); if (voltage < min_uV || voltage > max_uV) return -EINVAL; return ret; } EXPORT_SYMBOL_GPL(regulator_map_voltage_linear); /** * regulator_map_voltage_linear_range - map_voltage() for multiple linear ranges * * @rdev: Regulator to operate on * @min_uV: Lower bound for voltage * @max_uV: Upper bound for voltage * * Drivers providing linear_ranges in their descriptor can use this as * their map_voltage() callback. */ int regulator_map_voltage_linear_range(struct regulator_dev *rdev, int min_uV, int max_uV) { const struct regulator_linear_range *range; int ret = -EINVAL; int voltage, i; if (!rdev->desc->n_linear_ranges) { BUG_ON(!rdev->desc->n_linear_ranges); return -EINVAL; } for (i = 0; i < rdev->desc->n_linear_ranges; i++) { int linear_max_uV; range = &rdev->desc->linear_ranges[i]; linear_max_uV = range->min_uV + (range->max_sel - range->min_sel) * range->uV_step; if (!(min_uV <= linear_max_uV && max_uV >= range->min_uV)) continue; if (min_uV <= range->min_uV) min_uV = range->min_uV; /* range->uV_step == 0 means fixed voltage range */ if (range->uV_step == 0) { ret = 0; } else { ret = DIV_ROUND_UP(min_uV - range->min_uV, range->uV_step); if (ret < 0) return ret; } ret += range->min_sel; /* * Map back into a voltage to verify we're still in bounds. * If we are not, then continue checking rest of the ranges. */ voltage = rdev->desc->ops->list_voltage(rdev, ret); if (voltage >= min_uV && voltage <= max_uV) break; } if (i == rdev->desc->n_linear_ranges) return -EINVAL; return ret; } EXPORT_SYMBOL_GPL(regulator_map_voltage_linear_range); /** * regulator_map_voltage_pickable_linear_range - map_voltage, pickable ranges * * @rdev: Regulator to operate on * @min_uV: Lower bound for voltage * @max_uV: Upper bound for voltage * * Drivers providing pickable linear_ranges in their descriptor can use * this as their map_voltage() callback. */ int regulator_map_voltage_pickable_linear_range(struct regulator_dev *rdev, int min_uV, int max_uV) { const struct regulator_linear_range *range; int ret = -EINVAL; int voltage, i; unsigned int selector = 0; if (!rdev->desc->n_linear_ranges) { BUG_ON(!rdev->desc->n_linear_ranges); return -EINVAL; } for (i = 0; i < rdev->desc->n_linear_ranges; i++) { int linear_max_uV; range = &rdev->desc->linear_ranges[i]; linear_max_uV = range->min_uV + (range->max_sel - range->min_sel) * range->uV_step; if (!(min_uV <= linear_max_uV && max_uV >= range->min_uV)) { selector += (range->max_sel - range->min_sel + 1); continue; } if (min_uV <= range->min_uV) min_uV = range->min_uV; /* range->uV_step == 0 means fixed voltage range */ if (range->uV_step == 0) { ret = 0; } else { ret = DIV_ROUND_UP(min_uV - range->min_uV, range->uV_step); if (ret < 0) return ret; } ret += selector; voltage = rdev->desc->ops->list_voltage(rdev, ret); /* * Map back into a voltage to verify we're still in bounds. * We may have overlapping voltage ranges. Hence we don't * exit but retry until we have checked all ranges. */ if (voltage < min_uV || voltage > max_uV) selector += (range->max_sel - range->min_sel + 1); else break; } if (i == rdev->desc->n_linear_ranges) return -EINVAL; return ret; } EXPORT_SYMBOL_GPL(regulator_map_voltage_pickable_linear_range); /** * regulator_list_voltage_linear - List voltages with simple calculation * * @rdev: Regulator device * @selector: Selector to convert into a voltage * * Regulators with a simple linear mapping between voltages and * selectors can set min_uV and uV_step in the regulator descriptor * and then use this function as their list_voltage() operation, */ int regulator_list_voltage_linear(struct regulator_dev *rdev, unsigned int selector) { if (selector >= rdev->desc->n_voltages) return -EINVAL; if (selector < rdev->desc->linear_min_sel) return 0; selector -= rdev->desc->linear_min_sel; return rdev->desc->min_uV + (rdev->desc->uV_step * selector); } EXPORT_SYMBOL_GPL(regulator_list_voltage_linear); /** * regulator_list_voltage_pickable_linear_range - pickable range list voltages * * @rdev: Regulator device * @selector: Selector to convert into a voltage * * list_voltage() operation, intended to be used by drivers utilizing pickable * ranges helpers. */ int regulator_list_voltage_pickable_linear_range(struct regulator_dev *rdev, unsigned int selector) { const struct regulator_linear_range *range; int i; unsigned int all_sels = 0; if (!rdev->desc->n_linear_ranges) { BUG_ON(!rdev->desc->n_linear_ranges); return -EINVAL; } for (i = 0; i < rdev->desc->n_linear_ranges; i++) { unsigned int sels_in_range; range = &rdev->desc->linear_ranges[i]; sels_in_range = range->max_sel - range->min_sel; if (all_sels + sels_in_range >= selector) { selector -= all_sels; return range->min_uV + (range->uV_step * selector); } all_sels += (sels_in_range + 1); } return -EINVAL; } EXPORT_SYMBOL_GPL(regulator_list_voltage_pickable_linear_range); /** * regulator_desc_list_voltage_linear_range - List voltages for linear ranges * * @desc: Regulator desc for regulator which volatges are to be listed * @selector: Selector to convert into a voltage * * Regulators with a series of simple linear mappings between voltages * and selectors who have set linear_ranges in the regulator descriptor * can use this function prior regulator registration to list voltages. * This is useful when voltages need to be listed during device-tree * parsing. */ int regulator_desc_list_voltage_linear_range(const struct regulator_desc *desc, unsigned int selector) { const struct regulator_linear_range *range; int i; if (!desc->n_linear_ranges) { BUG_ON(!desc->n_linear_ranges); return -EINVAL; } for (i = 0; i < desc->n_linear_ranges; i++) { range = &desc->linear_ranges[i]; if (!(selector >= range->min_sel && selector <= range->max_sel)) continue; selector -= range->min_sel; return range->min_uV + (range->uV_step * selector); } return -EINVAL; } EXPORT_SYMBOL_GPL(regulator_desc_list_voltage_linear_range); /** * regulator_list_voltage_linear_range - List voltages for linear ranges * * @rdev: Regulator device * @selector: Selector to convert into a voltage * * Regulators with a series of simple linear mappings between voltages * and selectors can set linear_ranges in the regulator descriptor and * then use this function as their list_voltage() operation, */ int regulator_list_voltage_linear_range(struct regulator_dev *rdev, unsigned int selector) { return regulator_desc_list_voltage_linear_range(rdev->desc, selector); } EXPORT_SYMBOL_GPL(regulator_list_voltage_linear_range); /** * regulator_list_voltage_table - List voltages with table based mapping * * @rdev: Regulator device * @selector: Selector to convert into a voltage * * Regulators with table based mapping between voltages and * selectors can set volt_table in the regulator descriptor * and then use this function as their list_voltage() operation. */ int regulator_list_voltage_table(struct regulator_dev *rdev, unsigned int selector) { if (!rdev->desc->volt_table) { BUG_ON(!rdev->desc->volt_table); return -EINVAL; } if (selector >= rdev->desc->n_voltages) return -EINVAL; return rdev->desc->volt_table[selector]; } EXPORT_SYMBOL_GPL(regulator_list_voltage_table); /** * regulator_set_bypass_regmap - Default set_bypass() using regmap * * @rdev: device to operate on. * @enable: state to set. */ int regulator_set_bypass_regmap(struct regulator_dev *rdev, bool enable) { unsigned int val; if (enable) { val = rdev->desc->bypass_val_on; if (!val) val = rdev->desc->bypass_mask; } else { val = rdev->desc->bypass_val_off; } return regmap_update_bits(rdev->regmap, rdev->desc->bypass_reg, rdev->desc->bypass_mask, val); } EXPORT_SYMBOL_GPL(regulator_set_bypass_regmap); /** * regulator_set_soft_start_regmap - Default set_soft_start() using regmap * * @rdev: device to operate on. */ int regulator_set_soft_start_regmap(struct regulator_dev *rdev) { unsigned int val; val = rdev->desc->soft_start_val_on; if (!val) val = rdev->desc->soft_start_mask; return regmap_update_bits(rdev->regmap, rdev->desc->soft_start_reg, rdev->desc->soft_start_mask, val); } EXPORT_SYMBOL_GPL(regulator_set_soft_start_regmap); /** * regulator_set_pull_down_regmap - Default set_pull_down() using regmap * * @rdev: device to operate on. */ int regulator_set_pull_down_regmap(struct regulator_dev *rdev) { unsigned int val; val = rdev->desc->pull_down_val_on; if (!val) val = rdev->desc->pull_down_mask; return regmap_update_bits(rdev->regmap, rdev->desc->pull_down_reg, rdev->desc->pull_down_mask, val); } EXPORT_SYMBOL_GPL(regulator_set_pull_down_regmap); /** * regulator_get_bypass_regmap - Default get_bypass() using regmap * * @rdev: device to operate on. * @enable: current state. */ int regulator_get_bypass_regmap(struct regulator_dev *rdev, bool *enable) { unsigned int val; unsigned int val_on = rdev->desc->bypass_val_on; int ret; ret = regmap_read(rdev->regmap, rdev->desc->bypass_reg, &val); if (ret != 0) return ret; if (!val_on) val_on = rdev->desc->bypass_mask; *enable = (val & rdev->desc->bypass_mask) == val_on; return 0; } EXPORT_SYMBOL_GPL(regulator_get_bypass_regmap); /** * regulator_set_active_discharge_regmap - Default set_active_discharge() * using regmap * * @rdev: device to operate on. * @enable: state to set, 0 to disable and 1 to enable. */ int regulator_set_active_discharge_regmap(struct regulator_dev *rdev, bool enable) { unsigned int val; if (enable) val = rdev->desc->active_discharge_on; else val = rdev->desc->active_discharge_off; return regmap_update_bits(rdev->regmap, rdev->desc->active_discharge_reg, rdev->desc->active_discharge_mask, val); } EXPORT_SYMBOL_GPL(regulator_set_active_discharge_regmap); /** * regulator_set_current_limit_regmap - set_current_limit for regmap users * * @rdev: regulator to operate on * @min_uA: Lower bound for current limit * @max_uA: Upper bound for current limit * * Regulators that use regmap for their register I/O can set curr_table, * csel_reg and csel_mask fields in their descriptor and then use this * as their set_current_limit operation, saving some code. */ int regulator_set_current_limit_regmap(struct regulator_dev *rdev, int min_uA, int max_uA) { unsigned int n_currents = rdev->desc->n_current_limits; int i, sel = -1; if (n_currents == 0) return -EINVAL; if (rdev->desc->curr_table) { const unsigned int *curr_table = rdev->desc->curr_table; bool ascend = curr_table[n_currents - 1] > curr_table[0]; /* search for closest to maximum */ if (ascend) { for (i = n_currents - 1; i >= 0; i--) { if (min_uA <= curr_table[i] && curr_table[i] <= max_uA) { sel = i; break; } } } else { for (i = 0; i < n_currents; i++) { if (min_uA <= curr_table[i] && curr_table[i] <= max_uA) { sel = i; break; } } } } if (sel < 0) return -EINVAL; sel <<= ffs(rdev->desc->csel_mask) - 1; return regmap_update_bits(rdev->regmap, rdev->desc->csel_reg, rdev->desc->csel_mask, sel); } EXPORT_SYMBOL_GPL(regulator_set_current_limit_regmap); /** * regulator_get_current_limit_regmap - get_current_limit for regmap users * * @rdev: regulator to operate on * * Regulators that use regmap for their register I/O can set the * csel_reg and csel_mask fields in their descriptor and then use this * as their get_current_limit operation, saving some code. */ int regulator_get_current_limit_regmap(struct regulator_dev *rdev) { unsigned int val; int ret; ret = regmap_read(rdev->regmap, rdev->desc->csel_reg, &val); if (ret != 0) return ret; val &= rdev->desc->csel_mask; val >>= ffs(rdev->desc->csel_mask) - 1; if (rdev->desc->curr_table) { if (val >= rdev->desc->n_current_limits) return -EINVAL; return rdev->desc->curr_table[val]; } return -EINVAL; } EXPORT_SYMBOL_GPL(regulator_get_current_limit_regmap); /** * regulator_bulk_set_supply_names - initialize the 'supply' fields in an array * of regulator_bulk_data structs * * @consumers: array of regulator_bulk_data entries to initialize * @supply_names: array of supply name strings * @num_supplies: number of supply names to initialize * * Note: the 'consumers' array must be the size of 'num_supplies'. */ void regulator_bulk_set_supply_names(struct regulator_bulk_data *consumers, const char *const *supply_names, unsigned int num_supplies) { unsigned int i; for (i = 0; i < num_supplies; i++) consumers[i].supply = supply_names[i]; } EXPORT_SYMBOL_GPL(regulator_bulk_set_supply_names);
thilinaviraj/TrackPal
__tests__/_users_/view_shared_screen_test.js
import React from 'react'; import SharingScreen from '../../app/screens/SharingScreen/sharingScreen.js'; import renderer from 'react-test-renderer'; jest.useFakeTimers(); test('renders correctly', () => { const tree = renderer.create(<SharingScreen/>).toJSON(); expect(tree).toMatchSnapshot({ state: expect.any(String) }); });
moises-dias/hunter-adventures
arquivos .h e .cpp/Rastro.h
<reponame>moises-dias/hunter-adventures<filename>arquivos .h e .cpp/Rastro.h #ifndef RASTRO_H #define RASTRO_H #include "Efeito.h" class Rastro: public Efeito { public: Rastro(); Rastro(Vetor_R2 p, ALLEGRO_BITMAP* img, int sX, int sY, float coef, float velDes, float alphaIni, float ang,float cR, float cG, float cB); ~Rastro(); void desenha(); void atualiza(); void setPos(Vetor_R2 p); void setFrameAtual(int f); void setVelDes(float v); void setAng(int a); void resetaEntidade(); void paraTimer(); private: float cRed; float cGreen; float cBlue; float alpha; float vDes; float angulo; bool rot; }; #endif // RASTRO_H
shuwenjin/dcwlt
dcwlt-modules/dcwlt-pay-online/src/main/java/com/dcits/dcwlt/pay/online/service/CoreServiceSend.java
<gh_stars>0 //package com.dcits.dcwlt.pay.online.service; // //import com.alibaba.fastjson.JSONObject; //import com.dcits.dcwlt.common.core.constant.ServiceNameConstants; //import org.springframework.cloud.openfeign.FeignClient; //import org.springframework.web.bind.annotation.GetMapping; //import org.springframework.web.bind.annotation.PathVariable; // ///** // * 核心服务调用 // * // * @author ruoyi // */ //@FeignClient(name="coreservice",url = ServiceNameConstants.CORE_PATH_SERVICE) //public interface CoreServiceSend //{ // /** // * 调用核心接口(模拟) // * // * @param // * @return 结果 // */ // @GetMapping(value = "/core/sendBack/{tryId}") // JSONObject result(@PathVariable("tryId") String tryId); //}
hobson/ggpy
ggpy/cruft/autocode/PropNet.py
#!/usr/bin/env python """ generated source for module PropNet """ # package: org.ggp.base.util.propnet.architecture import java.io.File import java.io.FileOutputStream import java.io.OutputStreamWriter import java.util.HashMap import java.util.HashSet import java.util.List import java.util.Map import java.util.Set import org.ggp.base.util.gdl.grammar.GdlConstant import org.ggp.base.util.gdl.grammar.GdlPool import org.ggp.base.util.gdl.grammar.GdlProposition import org.ggp.base.util.gdl.grammar.GdlRelation import org.ggp.base.util.gdl.grammar.GdlSentence import org.ggp.base.util.gdl.grammar.GdlTerm import org.ggp.base.util.logging.GamerLogger import org.ggp.base.util.propnet.architecture.components.And import org.ggp.base.util.propnet.architecture.components.Not import org.ggp.base.util.propnet.architecture.components.Or import org.ggp.base.util.propnet.architecture.components.Proposition import org.ggp.base.util.propnet.architecture.components.Transition import org.ggp.base.util.statemachine.Role # # * The PropNet class is designed to represent Propositional Networks. # * # * A propositional network (also known as a "propnet") is a way of representing # * a game as a logic circuit. States of the game are represented by assignments # * of TRUE or FALSE to "base" propositions, each of which represents a single # * fact that can be true about the state of the game. For example, in a game of # * Tic-Tac-Toe, the fact (cell 1 1 x) indicates that the cell (1,1) has an 'x' # * in it. That fact would correspond to a base proposition, which would be set # * to TRUE to indicate that the fact is true in the current state of the game. # * Likewise, the base corresponding to the fact (cell 1 1 o) would be false, # * because in that state of the game there isn't an 'o' in the cell (1,1). # * # * A state of the game is uniquely determined by the assignment of truth values # * to the base propositions in the propositional network. Every assignment of # * truth values to base propositions corresponds to exactly one unique state of # * the game. # * # * Given the values of the base propositions, you can use the connections in # * the network (AND gates, OR gates, NOT gates) to determine the truth values # * of other propositions. For example, you can determine whether the terminal # * proposition is true: if that proposition is true, the game is over when it # * reaches this state. Otherwise, if it is false, the game isn't over. You can # * also determine the value of the goal propositions, which represent facts # * like (goal xplayer 100). If that proposition is true, then that fact is true # * in this state of the game, which means that xplayer has 100 points. # * # * You can also use a propositional network to determine the next state of the # * game, given the current state and the moves for each player. First, you set # * the input propositions which correspond to each move to TRUE. Once that has # * been done, you can determine the truth value of the transitions. Each base # * proposition has a "transition" component going into it. This transition has # * the truth value that its base will take on in the next state of the game. # * # * For further information about propositional networks, see: # * # * "Decomposition of Games for Efficient Reasoning" by <NAME>. # * "Factoring General Games using Propositional Automata" by <NAME> al. # * # * @author <NAME> # class PropNet(object): """ generated source for class PropNet """ components = Set() propositions = Set() # References to every BaseProposition in the PropNet, indexed by name. basePropositions = Map() # References to every InputProposition in the PropNet, indexed by name. inputPropositions = Map() # References to every LegalProposition in the PropNet, indexed by role. legalPropositions = Map() # References to every GoalProposition in the PropNet, indexed by role. goalPropositions = Map() # A reference to the single, unique, InitProposition. initProposition = Proposition() # A reference to the single, unique, TerminalProposition. terminalProposition = Proposition() # A helper mapping between input/legal propositions. legalInputMap = Map() # A helper list of all of the roles. roles = List() def addComponent(self, c): """ generated source for method addComponent """ self.components.add(c) if isinstance(c, (Proposition, )): self.propositions.add(c) # # * Creates a new PropNet from a list of Components, along with indices over # * those components. # * # * @param components # * A list of Components. # def __init__(self, roles, components): """ generated source for method __init__ """ self.roles = roles self.components = components self.propositions = recordPropositions() self.basePropositions = recordBasePropositions() self.inputPropositions = recordInputPropositions() self.legalPropositions = recordLegalPropositions() self.goalPropositions = recordGoalPropositions() self.initProposition = recordInitProposition() self.terminalProposition = recordTerminalProposition() self.legalInputMap = makeLegalInputMap() def getRoles(self): """ generated source for method getRoles """ return self.roles def getLegalInputMap(self): """ generated source for method getLegalInputMap """ return self.legalInputMap def makeLegalInputMap(self): """ generated source for method makeLegalInputMap """ legalInputMap = HashMap() # Create a mapping from Body->Input. inputPropsByBody = HashMap() for inputProp in inputPropositions.values(): inputPropsByBody.put(inputPropBody, inputProp) # Use that mapping to map Input->Legal and Legal->Input # based on having the same Body proposition. for legalProps in legalPropositions.values(): for legalProp in legalProps: if inputPropsByBody.containsKey(legalPropBody): legalInputMap.put(inputProp, legalProp) legalInputMap.put(legalProp, inputProp) return legalInputMap # # * Getter method. # * # * @return References to every BaseProposition in the PropNet, indexed by # * name. # def getBasePropositions(self): """ generated source for method getBasePropositions """ return self.basePropositions # # * Getter method. # * # def getComponents(self): """ generated source for method getComponents """ return self.components # # * Getter method. # * # * @return References to every GoalProposition in the PropNet, indexed by # * player name. # def getGoalPropositions(self): """ generated source for method getGoalPropositions """ return self.goalPropositions # # * Getter method. A reference to the single, unique, InitProposition. # * # * @return # def getInitProposition(self): """ generated source for method getInitProposition """ return self.initProposition # # * Getter method. # * # * @return References to every InputProposition in the PropNet, indexed by # * name. # def getInputPropositions(self): """ generated source for method getInputPropositions """ return self.inputPropositions # # * Getter method. # * # * @return References to every LegalProposition in the PropNet, indexed by # * player name. # def getLegalPropositions(self): """ generated source for method getLegalPropositions """ return self.legalPropositions # # * Getter method. # * # def getPropositions(self): """ generated source for method getPropositions """ return self.propositions # # * Getter method. # * # * @return A reference to the single, unique, TerminalProposition. # def getTerminalProposition(self): """ generated source for method getTerminalProposition """ return self.terminalProposition # # * Returns a representation of the PropNet in .dot format. # * # * @see java.lang.Object#toString() # def __str__(self): """ generated source for method toString """ sb = StringBuilder() sb.append("digraph propNet\n{\n") for component in components: sb.append("\t" + component.__str__() + "\n") sb.append("}") return sb.__str__() # # * Outputs the propnet in .dot format to a particular file. # * This can be viewed with tools like Graphviz and ZGRViewer. # * # * @param filename the name of the file to output to # def renderToFile(self, filename): """ generated source for method renderToFile """ try: fout.write(self.__str__()) fout.close() fos.close() except Exception as e: GamerLogger.logStackTrace("StateMachine", e) # # * # * This is done by going over every single-input proposition in the network, # * and seeing whether or not its input is a transition, which would mean that # * by definition the proposition is a base proposition. # * # def recordBasePropositions(self): """ generated source for method recordBasePropositions """ basePropositions = HashMap() for proposition in propositions: # Skip all propositions without exactly one input. if proposition.getInputs().size() != 1: continue if isinstance(component, (Transition, )): basePropositions.put(proposition.__name__, proposition) return basePropositions # # * # * This is done by going over every function proposition in the network # * where the name of the function is "goal", and extracting the name of the # * role associated with that goal proposition, and then using those role # * names as keys that map to the goal propositions in the index. # * # def recordGoalPropositions(self): """ generated source for method recordGoalPropositions """ goalPropositions = HashMap() for proposition in propositions: # Skip all propositions that aren't GdlRelations. if not (isinstance(, (GdlRelation, ))): continue if not relation.__name__.getValue() == "goal": continue if not goalPropositions.containsKey(theRole): goalPropositions.put(theRole, HashSet()) goalPropositions.get(theRole).add(proposition) return goalPropositions def recordInitProposition(self): """ generated source for method recordInitProposition """ for proposition in propositions: if not (isinstance(, (GdlProposition, ))): continue if constant.getValue().toUpperCase() == "INIT": return proposition return None def recordInputPropositions(self): """ generated source for method recordInputPropositions """ inputPropositions = HashMap() for proposition in propositions: if not (isinstance(, (GdlRelation, ))): continue if relation.__name__.getValue() == "does": inputPropositions.put(proposition.__name__, proposition) return inputPropositions def recordLegalPropositions(self): """ generated source for method recordLegalPropositions """ legalPropositions = HashMap() for proposition in propositions: if not (isinstance(, (GdlRelation, ))): continue if relation.__name__.getValue() == "legal": if not legalPropositions.containsKey(r): legalPropositions.put(r, HashSet()) legalPropositions.get(r).add(proposition) return legalPropositions def recordPropositions(self): """ generated source for method recordPropositions """ propositions = HashSet() for component in components: if isinstance(component, (Proposition, )): propositions.add(component) return propositions def recordTerminalProposition(self): """ generated source for method recordTerminalProposition """ for proposition in propositions: if isinstance(, (GdlProposition, )): if constant.getValue() == "terminal": return proposition return None def getSize(self): """ generated source for method getSize """ return len(self.components) def getNumAnds(self): """ generated source for method getNumAnds """ andCount = 0 for c in components: if isinstance(c, (And, )): andCount += 1 return andCount def getNumOrs(self): """ generated source for method getNumOrs """ orCount = 0 for c in components: if isinstance(c, (Or, )): orCount += 1 return orCount def getNumNots(self): """ generated source for method getNumNots """ notCount = 0 for c in components: if isinstance(c, (Not, )): notCount += 1 return notCount def getNumLinks(self): """ generated source for method getNumLinks """ linkCount = 0 for c in components: linkCount += c.getOutputs().size() return linkCount def removeComponent(self, c): """ generated source for method removeComponent """ if isinstance(c, (Proposition, )): if self.basePropositions.containsKey(name): self.basePropositions.remove(name) elif self.inputPropositions.containsKey(name): self.inputPropositions.remove(name) if partner != None: self.legalInputMap.remove(partner) self.legalInputMap.remove(p) elif name == GdlPool.getProposition(GdlPool.getConstant("INIT")): raise RuntimeException("The INIT component cannot be removed. Consider leaving it and ignoring it.") elif name == GdlPool.getProposition(GdlPool.getConstant("terminal")): raise RuntimeException("The terminal component cannot be removed.") else: for propositions in legalPropositions.values(): if self.propositions.contains(p): self.propositions.remove(p) if partner != None: self.legalInputMap.remove(partner) self.legalInputMap.remove(p) for propositions in goalPropositions.values(): self.propositions.remove(p) self.propositions.remove(p) self.components.remove(c) for parent in c.getInputs(): parent.removeOutput(c) for child in c.getOutputs(): child.removeInput(c) PropNet.# References to every component in the PropNet. PropNet.# References to every Proposition in the PropNet. PropNet.# * @return References to every Component in the PropNet. PropNet.# * @return References to every Proposition in the PropNet. PropNet.# * Builds an index over the BasePropositions in the PropNet. PropNet.# * @return An index over the BasePropositions in the PropNet. PropNet.# * Builds an index over the GoalPropositions in the PropNet. PropNet.# * @return An index over the GoalPropositions in the PropNet.
leegoonz/Maya-devkit
osx/devkit/plug-ins/AbcImport/main.cpp
<reponame>leegoonz/Maya-devkit //-***************************************************************************** // // Copyright (c) 2009-2011, // <NAME>, Inc. and // Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd. // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Sony Pictures Imageworks, nor // Industrial Light & Magic nor the names of their contributors may be used // to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // //-***************************************************************************** #include "AlembicNode.h" #include "AbcImport.h" #include "AlembicImportFileTranslator.h" #include "AbcImportStrings.h" #include <maya/MGlobal.h> #include <maya/MFnPlugin.h> #include <maya/MObject.h> #include <maya/MGlobal.h> // Interesting trivia: 0x2697 is the unicode character for Alembic const MTypeId AlembicNode::mMayaNodeId(0x00082697); MStatus initializePlugin(MObject obj) { const char * pluginVersion = "1.0"; MFnPlugin plugin(obj, "Alembic", pluginVersion, "Any"); MStatus status; // Register string resources // plugin.registerUIStrings( AbcImportStrings::registerMStringResources, "AbcImportInitStrings" ) ; status = plugin.registerCommand("AbcImport", AbcImport::creator, AbcImport::createSyntax); if (!status) { status.perror("registerCommand"); } status = plugin.registerNode("AlembicNode", AlembicNode::mMayaNodeId, &AlembicNode::creator, &AlembicNode::initialize); if (!status) { status.perror("registerNode"); } status = plugin.registerFileTranslator("Alembic", NULL, AlembicImportFileTranslator::creator, NULL, NULL, true); if (!status) { status.perror("registerFileTranslator"); } MGlobal::executeCommandOnIdle("AlembicCreateUI"); MString info = "AbcImport v"; info += pluginVersion; info += " using "; info += Alembic::AbcCoreAbstract::GetLibraryVersion().c_str(); MGlobal::displayInfo(info); return status; } MStatus uninitializePlugin(MObject obj) { MFnPlugin plugin(obj); MStatus status; status = plugin.deregisterFileTranslator("Alembic"); if (!status) { status.perror("deregisterFileTranslator"); } status = plugin.deregisterNode(AlembicNode::mMayaNodeId); if (!status) { status.perror("deregisterNode"); } status = plugin.deregisterCommand("AbcImport"); if (!status) { status.perror("deregisterCommand"); } MGlobal::executeCommandOnIdle("AlembicDeleteUI"); return status; }
b4hand/sauce
vendor/uncrustify-0.59/tests/input/c/global-vars.c
<reponame>b4hand/sauce static int another_try; struct something yup; align_me_t please; const char *name = "hello"; static nothing really;
kll5h/ShinetechOA
src/main/java/com/mossle/simulator/jms/MessageContext.java
<filename>src/main/java/com/mossle/simulator/jms/MessageContext.java package com.mossle.simulator.jms; import java.util.HashMap; import java.util.Map; public class MessageContext { private Map<String, Object> attributes = new HashMap<String, Object>(); public Object getAttribute(String key) { return this.attributes.get(key); } public boolean hasAttribute(String key) { return this.attributes.containsKey(key); } public void removeAttribute(String key) { this.attributes.remove(key); } public void addAttribute(String key, Object value) { this.attributes.put(key, value); } public void clear() { this.attributes.clear(); } }
gompus/gompus
rest/voice/list_regions.go
package voice import ( "github.com/gompus/gompus/models/voice" "github.com/gompus/gompus/rest/client" "github.com/gompus/gompus/rest/client/auth" ) // ListRegions retrieves a set of voice regions that can be // used when setting a voice or stage channel's rtc region. func ListRegions(token auth.Token) (regions []voice.Region, err error) { return regions, client.GET(client.Request{ Path: "/voice/regions", Token: token, Result: &regions, }) }
mbits-os/tangle
browser/include/tangle/browser/walk/std_actions.hpp
<filename>browser/include/tangle/browser/walk/std_actions.hpp // Copyright (c) 2021 midnightBITS // This code is licensed under MIT license (see LICENSE for details) #pragma once #include <tangle/browser/walk/selector_action.hpp> namespace tangle::browser::walk { struct std_action_env { virtual ~std_action_env(); virtual bool set_string(std::string const& name, std::string_view value) = 0; virtual bool set_href_text(std::string const& name, href_text const&) = 0; }; void add_std_actions(action_callbacks&, std_action_env* env); template <typename Final, typename Result, typename ParsedPages> struct page_matcher : std_action_env { Result result{}; bool set_string(std::string const&, std::string_view) override { return false; } bool set_href_text(std::string const&, href_text const&) override { return false; } static std::ostream* debug() noexcept { return nullptr; } void setup_actions(action_callbacks& actions) { add_std_actions(actions, this); } Result visit(std::string_view text) { walk::action_callbacks actions{}; static_cast<Final*>(this)->setup_actions(actions); auto const& defs = ParsedPages::get_pages(); walk::root_cursor cur{text}; if (!defs.visit(cur.root(), Final::page_name(), actions, nullptr, Final::debug())) { this->result = Result{}; } return std::move(this->result); } }; } // namespace tangle::browser::walk
FlorianPatzer/symp_security_analysis_engine
src/main/java/de/fraunhofer/iosb/svs/sae/exceptions/ResourceAlreadyExistsException.java
package de.fraunhofer.iosb.svs.sae.exceptions; public class ResourceAlreadyExistsException extends RuntimeException { public ResourceAlreadyExistsException(String item, String field, String value) { super("Resource '" + item + "' with field '" + field + "' and value '" + value + "' already exists"); } }
dined1/demo
impl/src/main/java/com/example/demo/model/Constants.java
package com.example.demo.model; public class Constants { public static final long ACCESS_TOKEN_VALIDITY_SECONDS = 3600*60*60; public static final String SIGNING_KEY = "<KEY>"; public static final String TOKEN_PREFIX = "Bearer "; public static final String HEADER_STRING = "Authorization"; public static final String AUTHORITIES_KEY = "scopes"; }
benmont/ccifra.github.io
HighDpiRenderPerformance/ni-webvi-resource-v0/Web/Elements/ni-hyperlink.js
//**************************************** // Hyperlink Custom Element // DOM Registration: No // National Instruments Copyright 2015 //**************************************** 'use strict'; JQX('ni-hyperlink', class Hyperlink extends JQX.BaseElement { // Hyperlink's properties. static get properties() { return { 'href': { value: '', type: 'string' }, 'content': { value: '', type: 'string' } }; } /** Hyperlink's Html template. */ template() { return `<a></a>`; } /** Called when the element is ready. Used for one-time configuration of the Hyperlink. */ ready() { const that = this; super.ready(); const childElement = that.firstElementChild; if (!that.disabled) { childElement.setAttribute('href', that.href); } childElement.textContent = that.content; } /** * Updates the Hyperlink when a property is changed. * @param {string} propertyName The name of the property. * @param {string} oldValue The previously entered value. * @param {string} newValue The new entered value. */ propertyChangedHandler(propertyName, oldValue, newValue) { const that = this; super.propertyChangedHandler(propertyName, oldValue, newValue); const childElement = that.firstElementChild; switch (propertyName) { case 'href': if (!that.disabled) { childElement.setAttribute('href', that.href); } break; case 'content': childElement.textContent = that.content; break; case 'disabled': if (that.disabled) { childElement.removeAttribute('href'); } else { childElement.setAttribute('href', that.href); } break; } } }); //# sourceMappingURL=ni-hyperlink.js.map
P1umer/ChakraCore
test/Object/ObjectHeaderInlining_NewPropNoInlineCache_StaticType.js
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- Object.prototype.prop0 = -4; function test0(arg) { var obj1 = {}; obj0 = obj1; obj1.prop1 += 0; if (arg) { obj1.prop1 = obj1.prop1.prop0; } else { obj1.prop1 = obj0.prop0; obj0.prop0 = obj1; } } test0(true); test0(true); test0(true); WScript.Echo("PASSED");
Logicalis/eugenio-devices
AzureMXChip/MXCHIPAZ3166/core/lib/netxduo/nx_secure/src/nx_secure_dtls_session_start.c
<filename>AzureMXChip/MXCHIPAZ3166/core/lib/netxduo/nx_secure/src/nx_secure_dtls_session_start.c<gh_stars>1-10 /**************************************************************************/ /* */ /* Copyright (c) Microsoft Corporation. All rights reserved. */ /* */ /* This software is licensed under the Microsoft Software License */ /* Terms for Microsoft Azure RTOS. Full text of the license can be */ /* found in the LICENSE file at https://aka.ms/AzureRTOS_EULA */ /* and in the root directory of this software. */ /* */ /**************************************************************************/ /**************************************************************************/ /**************************************************************************/ /** */ /** NetX Secure Component */ /** */ /** Datagram Transport Layer Security (DTLS) */ /** */ /**************************************************************************/ /**************************************************************************/ #define NX_SECURE_SOURCE_CODE #include "nx_secure_dtls.h" /**************************************************************************/ /* */ /* FUNCTION RELEASE */ /* */ /* _nx_secure_dtls_session_start PORTABLE C */ /* 6.1 */ /* AUTHOR */ /* */ /* <NAME>, Microsoft Corporation */ /* */ /* DESCRIPTION */ /* */ /* This function starts a DTLS session given a UDP socket. */ /* */ /* INPUT */ /* */ /* dtls_session DTLS control block */ /* udp_socket UDP socket pointer */ /* is_client Is client or server */ /* wait_option Suspension option */ /* */ /* OUTPUT */ /* */ /* status Completion status */ /* */ /* CALLS */ /* */ /* _nx_secure_dtls_allocate_handshake_packet */ /* Allocate DTLS handshake packet*/ /* _nx_secure_dtls_retransmit Retransmit UDP packet */ /* _nx_secure_dtls_retransmit_queue_flush */ /* Flush retransmit queue */ /* _nx_secure_dtls_send_clienthello Send ClientHello */ /* _nx_secure_dtls_send_handshake_record Send DTLS handshake record */ /* _nx_secure_dtls_session_receive Receive DTLS data */ /* nx_secure_tls_packet_release Release packet */ /* tx_mutex_get Get protection mutex */ /* tx_mutex_put Put protection mutex */ /* */ /* CALLED BY */ /* */ /* Application Code */ /* _nx_secure_dtls_client_session_start Client session start */ /* _nx_secure_dtls_server_session_start Server session start */ /* */ /* RELEASE HISTORY */ /* */ /* DATE NAME DESCRIPTION */ /* */ /* 05-19-2020 <NAME> Initial Version 6.0 */ /* 09-30-2020 <NAME> Modified comment(s), */ /* released packet securely, */ /* fixed renegotiation bug, */ /* resulting in version 6.1 */ /* */ /**************************************************************************/ UINT _nx_secure_dtls_session_start(NX_SECURE_DTLS_SESSION *dtls_session, NX_UDP_SOCKET *udp_socket, UINT is_client, UINT wait_option) { #ifdef NX_SECURE_ENABLE_DTLS UINT status = NX_NOT_SUCCESSFUL; NX_PACKET *incoming_packet; NX_SECURE_TLS_SESSION *tls_session; UINT minimum_wait_option; #ifndef NX_SECURE_TLS_CLIENT_DISABLED NX_PACKET *send_packet; #endif /* Get the protection. */ tx_mutex_get(&_nx_secure_tls_protection, TX_WAIT_FOREVER); /* Get reference to internal TLS state. */ tls_session = &dtls_session -> nx_secure_dtls_tls_session; /* Assign the packet pool from which TLS will allocate internal message packets. */ tls_session -> nx_secure_tls_packet_pool = udp_socket -> nx_udp_socket_ip_ptr -> nx_ip_default_packet_pool; /* Make sure we are starting with a fresh session. */ tls_session -> nx_secure_tls_received_remote_credentials = NX_FALSE; #ifndef NX_SECURE_TLS_DISABLE_SECURE_RENEGOTIATION /* Renegotiation is not enabled in DTLS session. */ tls_session -> nx_secure_tls_renegotation_enabled = NX_FALSE; #endif /* NX_SECURE_TLS_DISABLE_SECURE_RENEGOTIATION */ /* Assign the TCP socket to the TLS session. */ dtls_session -> nx_secure_dtls_udp_socket = udp_socket; /* Reset the record queue. */ tls_session -> nx_secure_record_queue_header = NX_NULL; tls_session -> nx_secure_record_decrypted_packet = NX_NULL; /* See if this is a TCP server started with listen/accept, or a TCP client started with connect. */ if (is_client) { /* The TCP socket is a client, so our TLS session is a TLS Client. */ tls_session -> nx_secure_tls_socket_type = NX_SECURE_TLS_SESSION_TYPE_CLIENT; } else { /* This session is now being treated as a server - indicate that fact to the TLS stack. */ tls_session -> nx_secure_tls_socket_type = NX_SECURE_TLS_SESSION_TYPE_SERVER; } /* Now process the handshake depending on the TLS session type. */ #ifndef NX_SECURE_TLS_CLIENT_DISABLED if (tls_session -> nx_secure_tls_socket_type == NX_SECURE_TLS_SESSION_TYPE_CLIENT) { /* Allocate a handshake packet so we can send the ClientHello. */ status = _nx_secure_dtls_allocate_handshake_packet(dtls_session, tls_session -> nx_secure_tls_packet_pool, &send_packet, wait_option); if (status != NX_SUCCESS) { /* Release the protection. */ tx_mutex_put(&_nx_secure_tls_protection); return(status); } /* Populate our packet with clienthello data. */ status = _nx_secure_dtls_send_clienthello(dtls_session, send_packet); if (status == NX_SUCCESS) { /* Send the ClientHello to kick things off. */ status = _nx_secure_dtls_send_handshake_record(dtls_session, send_packet, NX_SECURE_TLS_CLIENT_HELLO, wait_option, 0); /* Clear the protocol version to avoid checking the version in the HelloVerifyRequest which is always DTLS 1.0. */ tls_session->nx_secure_tls_protocol_version = 0; } /* If anything after the allocate fails, we need to release our packet. */ if (status != NX_SUCCESS) { /* Release the protection. */ tx_mutex_put(&_nx_secure_tls_protection); nx_secure_tls_packet_release(send_packet); return(status); } } #endif /* Now handle our incoming handshake messages. Continue processing until the handshake is complete * or an error/timeout occurs. */ for (;;) { #ifndef NX_SECURE_TLS_CLIENT_DISABLED if ((tls_session -> nx_secure_tls_socket_type == NX_SECURE_TLS_SESSION_TYPE_CLIENT) && (tls_session -> nx_secure_tls_client_state == NX_SECURE_TLS_CLIENT_STATE_HANDSHAKE_FINISHED)) { break; } #endif #ifndef NX_SECURE_TLS_SERVER_DISABLED if ((tls_session -> nx_secure_tls_socket_type == NX_SECURE_TLS_SESSION_TYPE_SERVER) && (tls_session -> nx_secure_tls_server_state == NX_SECURE_TLS_SERVER_STATE_HANDSHAKE_FINISHED)) { break; } #endif if ((dtls_session -> nx_secure_dtls_handshake_timeout > wait_option) || (dtls_session -> nx_secure_dtls_handshake_timeout == 0) || (dtls_session -> nx_secure_dtls_transmit_sent_head == NX_NULL)) { minimum_wait_option = wait_option; } else { minimum_wait_option = dtls_session -> nx_secure_dtls_handshake_timeout; } /* Release the protection. */ tx_mutex_put(&_nx_secure_tls_protection); status = _nx_secure_dtls_session_receive(dtls_session, &incoming_packet, minimum_wait_option); /* Get the protection. */ tx_mutex_get(&_nx_secure_tls_protection, TX_WAIT_FOREVER); /* Make sure we didn't have an error during the receive. */ if (status != NX_SUCCESS) { /* Check error status. */ if (status != NX_NO_PACKET && status != NX_CONTINUE) { break; } if (minimum_wait_option == wait_option) { break; } if (dtls_session -> nx_secure_dtls_timeout_retries >= NX_SECURE_DTLS_MAXIMUM_RETRANSMIT_RETRIES) { break; } /* Retransmit timeout. */ _nx_secure_dtls_retransmit(dtls_session); /* Decrease the wait option. */ wait_option -= minimum_wait_option; } else { /* On any error, the handshake has failed so break out of our processing loop and return. */ nx_secure_tls_packet_release(incoming_packet); } } /* This is the end of a flight, clear out the transmit queue. */ _nx_secure_dtls_retransmit_queue_flush(dtls_session); /* Release the protection. */ tx_mutex_put(&_nx_secure_tls_protection); return(status); #else NX_PARAMETER_NOT_USED(dtls_session); NX_PARAMETER_NOT_USED(udp_socket); NX_PARAMETER_NOT_USED(is_client); NX_PARAMETER_NOT_USED(wait_option); return(NX_NOT_SUPPORTED); #endif /* NX_SECURE_ENABLE_DTLS */ }