content
stringlengths
10
4.9M
<gh_stars>10-100 export interface IRouletteItem { id: number; title?: string; subtitle?: string; image?: string; }
/** * Race to create the persistent nodes. */ public static void createPersistentZKNodes(ZooKeeper zk) { LinkedList<ZKUtil.StringCallback> callbacks = new LinkedList<ZKUtil.StringCallback>(); for (int i=0; i < VoltZK.ZK_HIERARCHY.length; i++) { ZKUtil.StringCallback cb = new ZKUtil.StringCallback(); callbacks.add(cb); zk.create(VoltZK.ZK_HIERARCHY[i], null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, cb, null); } for (ZKUtil.StringCallback cb : callbacks) { try { cb.get(); } catch (org.apache.zookeeper_voltpatches.KeeperException.NodeExistsException e) { } catch (Exception e) { VoltDB.crashLocalVoltDB(e.getMessage(), true, e); } } }
/** * Checks if the message should be broadcasted among regions or not. * @param message target * @return flag */ public static boolean isBroadcast(Message message) { if (message instanceof CommandMessage) { CommandData commandData = ((CommandMessage) message).getData(); if (commandData instanceof PortsCommandData || commandData instanceof ConnectModeRequest) { return true; } } return false; }
// Parse parses the tracked item func (m *sankakuComplex) Parse(item *models.TrackedItem) error { downloadQueue, err := m.parseGallery(item) if err != nil { return err } return m.processDownloadQueue(downloadQueue, item) }
/** * List of all processes running on the device. * * @since TR181 v2.0 */ @CWMPObject(name = "Device.DeviceInfo.ProcessStatus.Process.{i}.", uniqueConstraints = {@CWMPUnique(names = {"PID"})}) @XmlRootElement(name = "Device.DeviceInfo.ProcessStatus.Process") @XmlType(name = "Device.DeviceInfo.ProcessStatus.Process") @XmlAccessorType(XmlAccessType.FIELD) public class Process { /** * The Process Identifier. * * @since 2.0 */ @XmlElement(name = "PID") public Long pid; /** * The name of the command that has caused the process to exist. * * @since 2.0 */ @XmlElement(name = "Command") @Size(max = 256) public String command; /** * The size in kilobytes of the memory occupied by the process. * * @since 2.0 */ @XmlElement(name = "Size") @CWMPParameter(activeNotify = "canDeny", units = "kilobytes") public Long size; /** * The priority of the process where 0 is highest. * * @since 2.0 */ @XmlElement(name = "Priority") @Size(max = 99) public Long priority; /** * The amount of time in milliseconds that the process has spent taking up CPU time since the process was started. * * @since 2.0 */ @XmlElement(name = "CPUTime") @CWMPParameter(activeNotify = "canDeny", units = "milliseconds") public Long cpuTime; /** * The current state that the process is in. * * @since 2.0 */ @XmlElement(name = "State") @CWMPParameter(activeNotify = "canDeny") public String state; public Process() { } //<editor-fold defaultstate="collapsed" desc="Getter and Setter"> /** * Get the Process Identifier. * * @since 2.0 * @return the value */ public Long getPid() { return pid; } /** * Set the Process Identifier. * * @since 2.0 * @param pid the input value */ public void setPid(Long pid) { this.pid = pid; } /** * Set the Process Identifier. * * @since 2.0 * @param pid the input value * @return this instance */ public Process withPid(Long pid) { this.pid = pid; return this; } /** * Get the name of the command that has caused the process to exist. * * @since 2.0 * @return the value */ public String getCommand() { return command; } /** * Set the name of the command that has caused the process to exist. * * @since 2.0 * @param command the input value */ public void setCommand(String command) { this.command = command; } /** * Set the name of the command that has caused the process to exist. * * @since 2.0 * @param command the input value * @return this instance */ public Process withCommand(String command) { this.command = command; return this; } /** * Get the size in kilobytes of the memory occupied by the process. * * @since 2.0 * @return the value */ public Long getSize() { return size; } /** * Set the size in kilobytes of the memory occupied by the process. * * @since 2.0 * @param size the input value */ public void setSize(Long size) { this.size = size; } /** * Set the size in kilobytes of the memory occupied by the process. * * @since 2.0 * @param size the input value * @return this instance */ public Process withSize(Long size) { this.size = size; return this; } /** * Get the priority of the process where 0 is highest. * * @since 2.0 * @return the value */ public Long getPriority() { return priority; } /** * Set the priority of the process where 0 is highest. * * @since 2.0 * @param priority the input value */ public void setPriority(Long priority) { this.priority = priority; } /** * Set the priority of the process where 0 is highest. * * @since 2.0 * @param priority the input value * @return this instance */ public Process withPriority(Long priority) { this.priority = priority; return this; } /** * Get the amount of time in milliseconds that the process has spent taking up CPU time since the process was started. * * @since 2.0 * @return the value */ public Long getCpuTime() { return cpuTime; } /** * Set the amount of time in milliseconds that the process has spent taking up CPU time since the process was started. * * @since 2.0 * @param cpuTime the input value */ public void setCpuTime(Long cpuTime) { this.cpuTime = cpuTime; } /** * Set the amount of time in milliseconds that the process has spent taking up CPU time since the process was started. * * @since 2.0 * @param cpuTime the input value * @return this instance */ public Process withCpuTime(Long cpuTime) { this.cpuTime = cpuTime; return this; } /** * Get the current state that the process is in. * * @since 2.0 * @return the value */ public String getState() { return state; } /** * Set the current state that the process is in. * * @since 2.0 * @param state the input value */ public void setState(String state) { this.state = state; } /** * Set the current state that the process is in. * * @since 2.0 * @param state the input value * @return this instance */ public Process withState(String state) { this.state = state; return this; } //</editor-fold> }
def loadCRC(verbose=False): rawHTML = get(CRC_URL).text soup = BeautifulSoup(rawHTML, 'html.parser') allTimeCards = soup.find_all("div", class_="caption program-schedule-card-caption") openings = dict() if (len(allTimeCards) != 0): for timeCard in allTimeCards: date = timeCard.find("span", class_="pull-left").text date = date.strip() smallText = timeCard.find("small") time = smallText.text time = time.strip() time = time.partition("\n")[0] spots = smallText.find(class_="pull-right").text spots = spots.strip() key = "{0} {1}".format(date, time) value = None if (spots == "No Spots Available"): value = 0 else: value = int(spots.partition(" ")[0]) openings[key] = value if verbose: print("key = {}".format(key)) print("value = {}".format(value)) if verbose: print("Total Time Cards = {}".format(len(allTimeCards))) return openings
/// Consumes the builder and constructs a [`DescribeDBSubnetGroupsOutput`](crate::output::DescribeDBSubnetGroupsOutput) pub fn build(self) -> crate::output::DescribeDBSubnetGroupsOutput { crate::output::DescribeDBSubnetGroupsOutput { marker: self.marker, db_subnet_groups: self.db_subnet_groups, } }
def MakeSyncCall(self, service, call, request, response): rpc = self.CreateRPC() rpc.MakeCall(service, call, request, response) rpc.Wait() rpc.CheckSuccess()
/* * Copyright 2014-2017, Intel Corporation * * 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 the copyright holder 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. */ /* * libpmemcto -- definitions of libpmemcto entry points * * This library exposes memory-mapped files as persistent memory heap * with malloc-like interfaces. * * See libpmemcto(3) for details. */ #ifndef LIBPMEMCTO_H #define LIBPMEMCTO_H 1 #ifdef _WIN32 #include <pmemcompat.h> #ifndef PMDK_UTF8_API #define pmemcto_open pmemcto_openW #define pmemcto_create pmemcto_createW #define pmemcto_check pmemcto_checkW #define pmemcto_check_version pmemcto_check_versionW #define pmemcto_errormsg pmemcto_errormsgW #else #define pmemcto_open pmemcto_openU #define pmemcto_create pmemcto_createU #define pmemcto_check pmemcto_checkU #define pmemcto_check_version pmemcto_check_versionU #define pmemcto_errormsg pmemcto_errormsgU #endif #endif #ifdef __cplusplus extern "C" { #endif #include <sys/types.h> #include <wchar.h> /* * opaque type, internal to libpmemcto */ typedef struct pmemcto PMEMctopool; /* * PMEMCTO_MAJOR_VERSION and PMEMCTO_MINOR_VERSION provide the current version * of the libpmemcto API as provided by this header file. Applications can * verify that the version available at run-time is compatible with the version * used at compile-time by passing these defines to pmemcto_check_version(). */ #define PMEMCTO_MAJOR_VERSION 1 #define PMEMCTO_MINOR_VERSION 0 #ifndef _WIN32 const char *pmemcto_check_version(unsigned major_required, unsigned minor_required); #else const char *pmemcto_check_versionU(unsigned major_required, unsigned minor_required); const wchar_t *pmemcto_check_versionW(unsigned major_required, unsigned minor_required); #endif /* minimum pool size: 16MB */ #define PMEMCTO_MIN_POOL ((size_t)(1024 * 1024 * 16)) /* * This limit is set arbitrary to incorporate a pool header and required * alignment plus supply. */ #define PMEMCTO_MIN_PART ((size_t)(1024 * 1024 * 2)) /* 2 MiB */ /* maximum layout size */ #define PMEMCTO_MAX_LAYOUT ((size_t)1024) #ifndef _WIN32 PMEMctopool *pmemcto_open(const char *path, const char *layout); #else PMEMctopool *pmemcto_openU(const char *path, const char *layout); PMEMctopool *pmemcto_openW(const wchar_t *path, const wchar_t *layout); #endif #ifndef _WIN32 PMEMctopool *pmemcto_create(const char *path, const char *layout, size_t poolsize, mode_t mode); #else PMEMctopool *pmemcto_createU(const char *path, const char *layout, size_t poolsize, mode_t mode); PMEMctopool *pmemcto_createW(const wchar_t *path, const wchar_t *layout, size_t poolsize, mode_t mode); #endif #ifndef _WIN32 int pmemcto_check(const char *path, const char *layout); #else int pmemcto_checkU(const char *path, const char *layout); int pmemcto_checkW(const wchar_t *path, const wchar_t *layout); #endif void pmemcto_close(PMEMctopool *pcp); void pmemcto_stats_print(PMEMctopool *pcp, const char *opts); /* * support for malloc and friends... */ void *pmemcto_malloc(PMEMctopool *pcp, size_t size); void pmemcto_free(PMEMctopool *pcp, void *ptr); void *pmemcto_calloc(PMEMctopool *pcp, size_t nmemb, size_t size); void *pmemcto_realloc(PMEMctopool *pcp, void *ptr, size_t size); void *pmemcto_aligned_alloc(PMEMctopool *pcp, size_t alignment, size_t size); char *pmemcto_strdup(PMEMctopool *pcp, const char *s); wchar_t *pmemcto_wcsdup(PMEMctopool *pcp, const wchar_t *s); size_t pmemcto_malloc_usable_size(PMEMctopool *pcp, void *ptr); /* * close-to-open persistence... */ void pmemcto_set_root_pointer(PMEMctopool *pcp, void *ptr); void *pmemcto_get_root_pointer(PMEMctopool *pcp); /* * Passing NULL to pmemcto_set_funcs() tells libpmemcto to continue to use * the default for that function. The replacement functions must * not make calls back into libpmemcto. * * The print_func is called by libpmemcto based on the environment * variable PMEMCTO_LOG_LEVEL: * 0 or unset: print_func is only called for pmemcto_stats_print() * 1: additional details are logged when errors are returned * 2: basic operations (allocations/frees) are logged * 3: produce very verbose tracing of function calls in libpmemcto * 4: also log obscure stuff used to debug the library itself * * The default print_func prints to stderr. Applications can override this * by setting the environment variable PMEMCTO_LOG_FILE, or by supplying a * replacement print function. */ void pmemcto_set_funcs( void *(*malloc_func)(size_t size), void (*free_func)(void *ptr), void *(*realloc_func)(void *ptr, size_t size), char *(*strdup_func)(const char *s), void (*print_func)(const char *s)); #ifndef _WIN32 const char *pmemcto_errormsg(void); #else const char *pmemcto_errormsgU(void); const wchar_t *pmemcto_errormsgW(void); #endif #ifdef __cplusplus } #endif #endif /* libpmemcto.h */
package bungieapigo // Mostly for historical purposes, we segregate Faction progressions from other progressions. // This is just a DestinyProgression with a shortcut for finding the DestinyFactionDefinition // of the faction related to the progression. type DestinyFactionProgression struct { // The hash identifier of the Faction related to this progression. Use it to look up the // DestinyFactionDefinition for more rendering info. FactionHash int `json:"factionHash"` // The index of the Faction vendor that is currently available. Will be set to -1 if no vendors are // available. FactionVendorIndex int `json:"factionVendorIndex"` // The hash identifier of the Progression in question. Use it to look up the // DestinyProgressionDefinition in static data. ProgressionHash int `json:"progressionHash"` // The amount of progress earned today for this progression. DailyProgress int `json:"dailyProgress"` // If this progression has a daily limit, this is that limit. DailyLimit int `json:"dailyLimit"` // The amount of progress earned toward this progression in the current week. WeeklyProgress int `json:"weeklyProgress"` // If this progression has a weekly limit, this is that limit. WeeklyLimit int `json:"weeklyLimit"` // This is the total amount of progress obtained overall for this progression (for instance, the // total amount of Character Level experience earned) CurrentProgress int `json:"currentProgress"` // This is the level of the progression (for instance, the Character Level). Level int `json:"level"` // This is the maximum possible level you can achieve for this progression (for example, the // maximum character level obtainable) LevelCap int `json:"levelCap"` // Progressions define their levels in "steps". Since the last step may be repeatable, the user // may be at a higher level than the actual Step achieved in the progression. Not necessarily // useful, but potentially interesting for those cruising the API. Relate this to the "steps" // property of the DestinyProgression to see which step the user is on, if you care about that. // (Note that this is Content Version dependent since it refers to indexes.) StepIndex int `json:"stepIndex"` // The amount of progression (i.e. "Experience") needed to reach the next level of this // Progression. Jeez, progression is such an overloaded word. ProgressToNextLevel int `json:"progressToNextLevel"` // The total amount of progression (i.e. "Experience") needed in order to reach the next level. NextLevelAt int `json:"nextLevelAt"` // The number of resets of this progression you've executed this season, if applicable to this // progression. CurrentResetCount int `json:"currentResetCount"` // Information about historical resets of this progression, if there is any data for it. SeasonResets []DestinyProgressionResetEntry `json:"seasonResets"` // Information about historical rewards for this progression, if there is any data for it. RewardItemStates []DestinyProgressionRewardItemState `json:"rewardItemStates"` }
package scavenger import ( "fmt" "github.com/PuerkitoBio/goquery" ) var ( JobQueue chan Job Quit chan bool Result chan interface{} ) type ( Parser func(doc *goquery.Document) interface{} Job struct { URL string Parser Parser } Scavenger struct { WorkerPool chan chan Job maxWorkers int } RequestResult struct { Items []interface{} } ) func init() { JobQueue = make(chan Job) Quit = make(chan bool) Result = make(chan interface{}) } func New(startURLs []string, p Parser, maxWorkers int) *Scavenger { for _, url := range startURLs { Enqueue(Job{URL: url, Parser: p}) } return &Scavenger{ WorkerPool: make(chan chan Job, maxWorkers), maxWorkers: maxWorkers, } } func (s *Scavenger) Run() { for i := 0; i < s.maxWorkers; i++ { NewWorker(s.WorkerPool).Start() } s.dispatch() } func Request(url string, p Parser) { Enqueue(Job{URL: url, Parser: p}) } func Enqueue(job Job) { go func() { JobQueue <- job }() } func (s *Scavenger) Terminate() { go func() { Quit <- true }() } func (s *Scavenger) dispatch() { for { select { case job := <-JobQueue: go func(job Job) { jobChannel := <-s.WorkerPool jobChannel <- job }(job) case <-Quit: return } } } func (s *Scavenger) Completion() { fmt.Println("finished") }
<reponame>hnord-vdx/wallet-core<filename>src/Cosmos/Entry.cpp // Copyright Β© 2017-2020 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "Entry.h" #include "Address.h" #include "Signer.h" using namespace TW::Cosmos; using namespace std; // Note: avoid business logic from here, rather just call into classes like Address, Signer, etc. bool Entry::validateAddress(TWCoinType coin, const string& address, TW::byte, TW::byte, const char* hrp) const { return Address::isValid(coin, address); } string Entry::deriveAddress(TWCoinType coin, const PublicKey& publicKey, TW::byte, const char* hrp) const { return Address(coin, publicKey).string(); } void Entry::sign(TWCoinType coin, const TW::Data& dataIn, TW::Data& dataOut) const { auto input = Proto::SigningInput(); input.ParseFromArray(dataIn.data(), (int)dataIn.size()); auto serializedOut = Signer::sign(input, coin).SerializeAsString(); dataOut.insert(dataOut.end(), serializedOut.begin(), serializedOut.end()); } string Entry::signJSON(TWCoinType coin, const std::string& json, const Data& key) const { return Signer::signJSON(json, key, coin); }
#ifndef IWBC_DAMAGE_CONTROLLER_HPP #define IWBC_DAMAGE_CONTROLLER_HPP #include <inria_wbc/controllers/talos_pos_tracker.hpp> namespace inria_wbc { namespace tasks { // contacts cannot be in the same factory std::shared_ptr<tsid::contacts::Contact6dExt> make_contact_task( const std::shared_ptr<tsid::robots::RobotWrapper>& robot, const std::shared_ptr<tsid::InverseDynamicsFormulationAccForce>& tsid, const std::string& task_name, const YAML::Node& node, const YAML::Node& controller_node); } namespace controllers { class DamageController : public TalosPosTracker { public: typedef tsid::math::Vector Vector; DamageController(const YAML::Node& config); DamageController(const DamageController& other) = delete; DamageController& operator=(const DamageController& o) const = delete; virtual ~DamageController(){}; Eigen::VectorXd tau(bool filter_mimics) const; virtual void update(const SensorData& sensor_data = {}) override; std::shared_ptr<tsid::contacts::Contact6dExt> contact_task(const std::string& str) { return contact(str); } protected: }; } // namespace controllers } // namespace inria_wbc #endif
/* * Copyright (C) 2018 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <gtest/gtest.h> #include <cstdlib> #include <ignition/common/Console.hh> #include "PeerTracker.hh" #include "ignition/gazebo/EventManager.hh" using namespace ignition::gazebo; ////////////////////////////////////////////////// TEST(PeerTracker, PeerTracker) { ignition::common::Console::SetVerbosity(4); EventManager eventMgr; std::atomic<int> peers = 0; auto added = eventMgr.Connect<PeerAdded>([&peers](PeerInfo _peer) { (void) _peer; peers++; }); auto removed = eventMgr.Connect<PeerRemoved>([&peers](PeerInfo _peer) { (void) _peer; peers--; }); auto tracker1 = std::make_shared<PeerTracker>( PeerInfo(NetworkRole::SimulationPrimary), &eventMgr); EXPECT_EQ(0, peers); auto tracker2 = std::make_shared<PeerTracker>( PeerInfo(NetworkRole::SimulationSecondary)); std::this_thread::sleep_for(std::chrono::milliseconds(10)); EXPECT_EQ(1, peers); auto tracker3 = std::make_shared<PeerTracker>( PeerInfo(NetworkRole::SimulationSecondary)); std::this_thread::sleep_for(std::chrono::milliseconds(10)); EXPECT_EQ(2, peers); auto tracker4 = std::make_shared<PeerTracker>( PeerInfo(NetworkRole::ReadOnly)); std::this_thread::sleep_for(std::chrono::milliseconds(10)); EXPECT_EQ(3, peers); auto tracker5 = std::make_shared<PeerTracker>( PeerInfo(NetworkRole::ReadOnly)); std::this_thread::sleep_for(std::chrono::milliseconds(10)); EXPECT_EQ(4, peers); auto tracker6 = std::make_shared<PeerTracker>( PeerInfo(NetworkRole::None)); std::this_thread::sleep_for(std::chrono::milliseconds(10)); EXPECT_EQ(5, peers); // Allow all the heartbeats to propagate int maxSleep{100}; int sleep{0}; for (; sleep < maxSleep && (tracker1->NumPeers() < 5 || tracker2->NumPeers() < 5 || tracker3->NumPeers() < 5 || tracker4->NumPeers() < 5 || tracker5->NumPeers() < 5); ++sleep) { std::this_thread::sleep_for(std::chrono::milliseconds(30)); } // All counts exclude self. EXPECT_EQ(5u, tracker1->NumPeers()); EXPECT_EQ(5u, tracker2->NumPeers()); EXPECT_EQ(5u, tracker3->NumPeers()); EXPECT_EQ(5u, tracker4->NumPeers()); EXPECT_EQ(5u, tracker5->NumPeers()); EXPECT_EQ(0u, tracker1->NumPeers(NetworkRole::SimulationPrimary)); EXPECT_EQ(2u, tracker1->NumPeers(NetworkRole::SimulationSecondary)); EXPECT_EQ(2u, tracker1->NumPeers(NetworkRole::ReadOnly)); EXPECT_EQ(1u, tracker1->NumPeers(NetworkRole::None)); EXPECT_EQ(1u, tracker2->NumPeers(NetworkRole::SimulationPrimary)); EXPECT_EQ(1u, tracker2->NumPeers(NetworkRole::SimulationSecondary)); EXPECT_EQ(2u, tracker2->NumPeers(NetworkRole::ReadOnly)); EXPECT_EQ(1u, tracker2->NumPeers(NetworkRole::None)); EXPECT_EQ(1u, tracker3->NumPeers(NetworkRole::SimulationPrimary)); EXPECT_EQ(1u, tracker3->NumPeers(NetworkRole::SimulationSecondary)); EXPECT_EQ(2u, tracker3->NumPeers(NetworkRole::ReadOnly)); EXPECT_EQ(1u, tracker3->NumPeers(NetworkRole::None)); EXPECT_EQ(1u, tracker4->NumPeers(NetworkRole::SimulationPrimary)); EXPECT_EQ(2u, tracker4->NumPeers(NetworkRole::SimulationSecondary)); EXPECT_EQ(1u, tracker4->NumPeers(NetworkRole::ReadOnly)); EXPECT_EQ(1u, tracker4->NumPeers(NetworkRole::None)); EXPECT_EQ(1u, tracker5->NumPeers(NetworkRole::SimulationPrimary)); EXPECT_EQ(2u, tracker5->NumPeers(NetworkRole::SimulationSecondary)); EXPECT_EQ(1u, tracker5->NumPeers(NetworkRole::ReadOnly)); EXPECT_EQ(1u, tracker5->NumPeers(NetworkRole::None)); tracker6.reset(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); EXPECT_EQ(4, peers); tracker5.reset(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); EXPECT_EQ(3, peers); tracker4.reset(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); EXPECT_EQ(2, peers); tracker3.reset(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); EXPECT_EQ(1, peers); tracker2.reset(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); EXPECT_EQ(0, peers); tracker1.reset(); } ////////////////////////////////////////////////// TEST(PeerTracker, PeerTrackerStale) { ignition::common::Console::SetVerbosity(4); EventManager eventMgr; // Tracker with artificially short timeout. auto tracker1 = std::make_shared<PeerTracker>( PeerInfo(NetworkRole::SimulationPrimary), &eventMgr); tracker1->SetHeartbeatPeriod(std::chrono::milliseconds(10)); tracker1->SetStaleMultiplier(1); auto info2 = PeerInfo(NetworkRole::SimulationSecondary); std::atomic<int> stalePeers = 0; auto stale = eventMgr.Connect<PeerStale>([&](PeerInfo _peer) { EXPECT_EQ(_peer.id, info2.id); stalePeers++; }); auto tracker2 = std::make_shared<PeerTracker>(info2); tracker2->SetHeartbeatPeriod(std::chrono::milliseconds(100)); int maxSleep{100}; int sleep{0}; for (; sleep < maxSleep && (tracker2->NumPeers() == 0 || stalePeers == 0); ++sleep) { std::this_thread::sleep_for(std::chrono::milliseconds(30)); } EXPECT_LT(sleep, maxSleep); EXPECT_EQ(1, stalePeers); // Expect while tracker1 can see tracker2, the opposite is // not true. EXPECT_EQ(0u, tracker1->NumPeers()); EXPECT_EQ(1u, tracker2->NumPeers()); // PeerTracker will print a debug message when DISCONNECTING message is // received from stale peer } ////////////////////////////////////////////////// TEST(PeerTracker, Partitioned) { ignition::common::Console::SetVerbosity(4); EventManager eventMgr; auto options1 = ignition::transport::NodeOptions(); options1.SetPartition("p1"); auto tracker1 = PeerTracker( PeerInfo(NetworkRole::SimulationPrimary), &eventMgr, options1); auto options2 = ignition::transport::NodeOptions(); options2.SetPartition("p2"); auto tracker2 = PeerTracker( PeerInfo(NetworkRole::SimulationPrimary), &eventMgr, options2); // Allow all the heartbeats to propagate std::this_thread::sleep_for(std::chrono::milliseconds(200)); // Trackers should not detect peers in different partitions EXPECT_EQ(0u, tracker1.NumPeers()); EXPECT_EQ(0u, tracker2.NumPeers()); auto tracker3 = PeerTracker( PeerInfo(NetworkRole::SimulationSecondary), &eventMgr, options1); auto tracker4 = PeerTracker( PeerInfo(NetworkRole::SimulationSecondary), &eventMgr, options2); // Allow some time for heartbeats to propagate // TODO(mjcarroll): Send heartbeats on announce for (int sleep = 0; sleep < 30 && (tracker1.NumPeers() == 0 || tracker2.NumPeers() == 0 || tracker3.NumPeers() == 0 || tracker4.NumPeers() == 0); ++sleep) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } // Trackers should detect peers in the same partition. EXPECT_EQ(1u, tracker1.NumPeers()); EXPECT_EQ(1u, tracker2.NumPeers()); EXPECT_EQ(1u, tracker3.NumPeers()); EXPECT_EQ(1u, tracker4.NumPeers()); } ////////////////////////////////////////////////// TEST(PeerTracker, Namespaced) { ignition::common::Console::SetVerbosity(4); EventManager eventMgr; auto options1 = ignition::transport::NodeOptions(); options1.SetNameSpace("ns1"); auto tracker1 = PeerTracker( PeerInfo(NetworkRole::SimulationPrimary), &eventMgr, options1); auto options2 = ignition::transport::NodeOptions(); options2.SetNameSpace("ns2"); auto tracker2 = PeerTracker( PeerInfo(NetworkRole::SimulationPrimary), &eventMgr, options2); // Allow some time for heartbeats to propagate std::this_thread::sleep_for(std::chrono::milliseconds(200)); // Trackers should not detect peers in different namespaces EXPECT_EQ(0u, tracker1.NumPeers()); EXPECT_EQ(0u, tracker2.NumPeers()); auto tracker3 = PeerTracker( PeerInfo(NetworkRole::SimulationSecondary), &eventMgr, options1); auto tracker4 = PeerTracker( PeerInfo(NetworkRole::SimulationSecondary), &eventMgr, options2); // Allow some time for heartbeats to propagate // TODO(mjcarroll): Send heartbeats on announce std::this_thread::sleep_for(std::chrono::milliseconds(200)); // Trackers should detect peers in the same partition. EXPECT_EQ(1u, tracker1.NumPeers()); EXPECT_EQ(1u, tracker2.NumPeers()); EXPECT_EQ(1u, tracker3.NumPeers()); EXPECT_EQ(1u, tracker4.NumPeers()); } ////////////////////////////////////////////////// // Only on Linux for the moment #ifdef __linux__ TEST(PeerTracker, PartitionedEnv) { ignition::common::Console::SetVerbosity(4); EventManager eventMgr; setenv("IGN_PARTITION", "p1", 1); auto tracker1 = PeerTracker( PeerInfo(NetworkRole::SimulationPrimary), &eventMgr); setenv("IGN_PARTITION", "p2", 1); auto tracker2 = PeerTracker( PeerInfo(NetworkRole::SimulationPrimary), &eventMgr); // Allow some time for heartbeats to propagate std::this_thread::sleep_for(std::chrono::milliseconds(110)); // Trackers should not detect peers in different partitions EXPECT_EQ(0u, tracker1.NumPeers()); EXPECT_EQ(0u, tracker2.NumPeers()); setenv("IGN_PARTITION", "p1", 1); auto tracker3 = PeerTracker( PeerInfo(NetworkRole::SimulationSecondary), &eventMgr); setenv("IGN_PARTITION", "p2", 1); auto tracker4 = PeerTracker( PeerInfo(NetworkRole::SimulationSecondary), &eventMgr); // Allow some time for heartbeats to propagate // TODO(mjcarroll): Send heartbeats on announce std::this_thread::sleep_for(std::chrono::milliseconds(110)); // Trackers should detect peers in the same partition. EXPECT_EQ(1u, tracker1.NumPeers()); EXPECT_EQ(1u, tracker2.NumPeers()); EXPECT_EQ(1u, tracker3.NumPeers()); EXPECT_EQ(1u, tracker4.NumPeers()); unsetenv("IGN_PARTITION"); } #endif
/// Creates a curve25519 key from an ed25519 public key. /// /// Used to derive the public key for DH key exchange. /// /// # Example /// ``` /// use ursa::signatures::ed25519::Ed25519Sha512; /// use ursa::signatures::SignatureScheme; /// /// let (pk, sk) = Ed25519Sha512::new().keypair(None).unwrap(); /// let curve_pk = Ed25519Sha512::ver_key_to_key_exchange(&pk).unwrap(); /// let curve_sk = Ed25519Sha512::sign_key_to_key_exchange(&sk).unwrap(); /// ``` pub fn ver_key_to_key_exchange(pk: &PublicKey) -> Result<PublicKey, CryptoError> { use curve25519_dalek::edwards::CompressedEdwardsY; // Verify it's a valid public key PK::from_bytes(&pk[..]).map_err(|e| CryptoError::ParseError(e.to_string()))?; // PublicKey is a CompressedEdwardsY in dalek. So we decompress it to get the // EdwardsPoint which can then be used convert to the Montgomery Form. let cey = CompressedEdwardsY::from_slice(&pk[..]); match cey.decompress() { Some(ep) => Ok(PublicKey(ep.to_montgomery().as_bytes().to_vec())), None => Err(CryptoError::ParseError(format!( "Invalid public key provided. Cannot convert to key exchange key" ))), } }
def plot_metrics(self): metrics = ['Reward', 'Transmitted packets', 'Dropped packets', 'Buffered packets'] for df, baseline in zip(self.df_list, self.titles): df = self._episode(df, self.eps[0]) fig, ax = plt.subplots(nrows=4, ncols=1, figsize=(8, 8)) ax[0].set_title(baseline + ' Episode ' + str(self.eps[0])) for i, feature in zip(range(4),metrics): ax[i].plot(df[feature]) for a, feature in zip(ax.flat, metrics): a.set(ylabel=feature) for a in ax.flat: a.label_outer() plt.xlabel('Time Steps') plt.show()
/** * @author Alexander Shakhov */ @Getter @Setter @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "GlobalType", propOrder = {"metadataGroupList", "metadataList", "graphParameters", "dictionary"}) public class Global { @XmlElement(name = "MetadataGroup") private List<MetadataGroup> metadataGroupList; @XmlElement(name = "Metadata") private List<Metadata> metadataList; @XmlElement(name = "GraphParameters", required = true) private GraphParameters graphParameters; @XmlElement(name = "Dictionary", required = true) private Dictionary dictionary; }
def switchNumber(a: str): temp = a[2:] temp += a[1:2] temp += a[0:1] return temp S1, S2 = input().split() newS1 = switchNumber(S1) newS2 = switchNumber(S2) print(max(int(newS1), int(newS2)))
<filename>src/main/java/org/helm/notation2/MoleculeProperty.java /*-- * * @(#) MoleculeInfo.java * * */ package org.helm.notation2; /** * MoleculeInfo * * @author hecht */ public class MoleculeProperty { private double molecularWeight; private String molecularFormula; private double exactMass; private float extinctionCoefficient; public double getMolecularWeight() { return molecularWeight; } public void setMolecularWeight(double molecularWeight) { this.molecularWeight = molecularWeight; } public String getMolecularFormula() { return molecularFormula; } public void setMolecularFormula(String molecularFormula) { this.molecularFormula = molecularFormula; } public double getExactMass() { return exactMass; } public void setExactMass(double exactMass) { this.exactMass = exactMass; } public void setExtinctionCoefficient(float extinctionCoefficient) { this.extinctionCoefficient = extinctionCoefficient; } public float getExtinctionCoefficient() { return extinctionCoefficient; } }
/** * Manage {@link org.rythmengine.extension.ICodeType template language} implementations */ public class CodeTypeManager { private List<ICodeType> _codeTypeList = new ArrayList<ICodeType>(); public CodeTypeManager registerCodeType(ICodeType type) { _codeTypeList.add(type); return this; } public Iterable<ICodeType> codeTypes() { return _codeTypeList; } public boolean hasCodeType() { return !_codeTypeList.isEmpty(); } }
<reponame>MasseGuillaume/scala-java8-compat<gh_stars>0 package scala.compat.java8.runtime; // No imports! All type names are fully qualified to avoid confusion! public class CollectionInternals { public static <A> Object[] getTable(scala.collection.mutable.FlatHashTable<A> fht) { return fht.hashTableContents().table(); } public static <A, E extends scala.collection.mutable.HashEntry<A,E>> scala.collection.mutable.HashEntry<A, E>[] getTable(scala.collection.mutable.HashTable<A,E> ht) { return ht.hashTableContents().table(); } public static <A> Object[] getDisplay0(scala.collection.immutable.Vector<A> v) { return v.display0(); } public static <A> Object[] getDisplay1(scala.collection.immutable.Vector<A> v) { return v.display1(); } public static <A> Object[] getDisplay2(scala.collection.immutable.Vector<A> v) { return v.display2(); } public static <A> Object[] getDisplay3(scala.collection.immutable.Vector<A> v) { return v.display3(); } public static <A> Object[] getDisplay4(scala.collection.immutable.Vector<A> v) { return v.display4(); } public static <A> Object[] getDisplay5(scala.collection.immutable.Vector<A> v) { return v.display5(); } public static <A> scala.Tuple2< scala.Tuple2< scala.collection.Iterator<A>, Object >, scala.collection.Iterator<A> > trieIteratorSplit(scala.collection.Iterator<A> it) { if (it instanceof scala.collection.immutable.TrieIterator) { scala.collection.immutable.TrieIterator<A> trie = (scala.collection.immutable.TrieIterator<A>)it; return trie.split(); } return null; } public static long[] getBitSetInternals(scala.collection.mutable.BitSet bitSet) { return bitSet.elems(); } }
<gh_stars>1-10 package com.projectseptember.RNGL; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import java.util.ArrayList; import java.util.List; public class GLData { final Integer shader; final ReadableMap uniforms; final Double width; final Double height; final Double pixelRatio; final Integer fboId; final List<GLData> contextChildren; final List<GLData> children; public GLData(Integer shader, ReadableMap uniforms, Double width, Double height, Double pixelRatio, Integer fboId, List<GLData> contextChildren, List<GLData> children) { this.shader = shader; this.uniforms = uniforms; this.width = width; this.height = height; this.pixelRatio = pixelRatio; this.fboId = fboId; this.contextChildren = contextChildren; this.children = children; } public static List<GLData> fromArray (ReadableArray arr) { ArrayList<GLData> list = new ArrayList<>(); for (int i=0; i < arr.size(); i++) { list.add(fromMap(arr.getMap(i))); } return list; } public static GLData fromMap (ReadableMap map) { Integer shader = map.getInt("shader"); ReadableMap uniforms = map.getMap("uniforms"); Double width = map.getDouble("width"); Double height = map.getDouble("height"); Double pixelRatio = map.getDouble("pixelRatio"); Integer fboId = map.getInt("fboId"); List<GLData> children = fromArray(map.getArray("children")); List<GLData> contextChildren = fromArray(map.getArray("contextChildren")); return new GLData(shader, uniforms, width, height, pixelRatio, fboId, contextChildren, children); } }
/** * Swaps 2 elements in the column defs array. * @param columnDefs reference to the column defs array * @param i first index to swap * @param j second index to swap */ private static void swap( final ColumnDef[] columnDefs, final int i, final int j ) { final ColumnDef stored = columnDefs[ i ]; columnDefs[ i ] = columnDefs[ j ]; columnDefs[ j ] = stored; }
/** * Utility class which has all the helper methods used across the application. * * @author abuabdul * */ public class FourTUtils { private static final DateFormat dd_MM_YYYY = new SimpleDateFormat("dd/MM/yyyy"); public static String simpleDateStringWithDDMMYYYY(Date date) { if (date != null) { return dd_MM_YYYY.format(date); } return ""; } public static Date simpleDateWithDDMMYYYY(String dateStr) throws FourTException { try { if (dateStr != null) { return dd_MM_YYYY.parse(dateStr); } } catch (ParseException par) { new FourTException(par.getMessage(), par); } return null; } public static Date getUTCDateTime() { return new DateTime(DateTimeZone.UTC).toDate(); } }
// Copyright (c) 2012 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 "ash/shelf/shelf_layout_manager.h" #include <memory> #include <utility> #include "ash/accelerators/accelerator_controller.h" #include "ash/accelerators/accelerator_table.h" #include "ash/app_list/test/app_list_test_helper.h" #include "ash/focus_cycler.h" #include "ash/public/cpp/app_list/app_list_features.h" #include "ash/public/cpp/config.h" #include "ash/public/cpp/shell_window_ids.h" #include "ash/root_window_controller.h" #include "ash/session/session_controller.h" #include "ash/shelf/shelf.h" #include "ash/shelf/shelf_constants.h" #include "ash/shelf/shelf_layout_manager_observer.h" #include "ash/shelf/shelf_view.h" #include "ash/shelf/shelf_widget.h" #include "ash/shell.h" #include "ash/shell_test_api.h" #include "ash/system/status_area_widget.h" #include "ash/system/tray/system_tray.h" #include "ash/system/tray/system_tray_item.h" #include "ash/system/tray/test_system_tray_item.h" #include "ash/test/ash_test_base.h" #include "ash/wm/lock_state_controller.h" #include "ash/wm/splitview/split_view_controller.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "ash/wm/window_state.h" #include "ash/wm/window_util.h" #include "ash/wm/wm_event.h" #include "base/command_line.h" #include "base/run_loop.h" #include "base/stl_util.h" #include "services/ui/public/interfaces/window_manager_constants.mojom.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/window_parenting_client.h" #include "ui/aura/window.h" #include "ui/aura/window_event_dispatcher.h" #include "ui/base/ui_base_switches.h" #include "ui/compositor/layer.h" #include "ui/compositor/layer_animator.h" #include "ui/compositor/scoped_animation_duration_scale_mode.h" #include "ui/display/display.h" #include "ui/display/display_layout.h" #include "ui/display/manager/display_manager.h" #include "ui/display/screen.h" #include "ui/display/test/display_manager_test_api.h" #include "ui/events/gesture_detection/gesture_configuration.h" #include "ui/events/test/event_generator.h" #include "ui/keyboard/keyboard_controller.h" #include "ui/keyboard/keyboard_ui.h" #include "ui/keyboard/keyboard_util.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/wm/core/window_util.h" namespace ash { namespace { void StepWidgetLayerAnimatorToEnd(views::Widget* widget) { widget->GetNativeView()->layer()->GetAnimator()->Step( base::TimeTicks::Now() + base::TimeDelta::FromSeconds(1)); } ShelfWidget* GetShelfWidget() { return AshTestBase::GetPrimaryShelf()->shelf_widget(); } ShelfLayoutManager* GetShelfLayoutManager() { return AshTestBase::GetPrimaryShelf()->shelf_layout_manager(); } // Class which waits till the shelf finishes animating to the target size and // counts the number of animation steps. class ShelfAnimationWaiter : views::WidgetObserver { public: explicit ShelfAnimationWaiter(const gfx::Rect& target_bounds) : target_bounds_(target_bounds), animation_steps_(0), done_waiting_(false) { GetShelfWidget()->AddObserver(this); } ~ShelfAnimationWaiter() override { GetShelfWidget()->RemoveObserver(this); } // Wait till the shelf finishes animating to its expected bounds. void WaitTillDoneAnimating() { if (IsDoneAnimating()) done_waiting_ = true; else base::RunLoop().Run(); } // Returns true if the animation has completed and it was valid. bool WasValidAnimation() const { return done_waiting_ && animation_steps_ > 0; } private: // Returns true if shelf has finished animating to the target size. bool IsDoneAnimating() const { ShelfLayoutManager* layout_manager = GetShelfLayoutManager(); gfx::Rect current_bounds = GetShelfWidget()->GetWindowBoundsInScreen(); int size = layout_manager->PrimaryAxisValue(current_bounds.height(), current_bounds.width()); int desired_size = layout_manager->PrimaryAxisValue(target_bounds_.height(), target_bounds_.width()); return (size == desired_size); } // views::WidgetObserver override. void OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& new_bounds) override { if (done_waiting_) return; ++animation_steps_; if (IsDoneAnimating()) { done_waiting_ = true; base::RunLoop::QuitCurrentWhenIdleDeprecated(); } } gfx::Rect target_bounds_; int animation_steps_; bool done_waiting_; DISALLOW_COPY_AND_ASSIGN(ShelfAnimationWaiter); }; class ShelfDragCallback { public: ShelfDragCallback(const gfx::Rect& not_visible, const gfx::Rect& visible) : auto_hidden_shelf_widget_bounds_(not_visible), shelf_widget_bounds_(visible), was_visible_on_drag_start_(false) { EXPECT_EQ(auto_hidden_shelf_widget_bounds_.bottom(), shelf_widget_bounds_.bottom()); } virtual ~ShelfDragCallback() = default; void ProcessScroll(ui::EventType type, const gfx::Vector2dF& delta) { if (GetShelfLayoutManager()->visibility_state() == SHELF_HIDDEN) return; if (type == ui::ET_GESTURE_SCROLL_BEGIN) { scroll_ = gfx::Vector2dF(); was_visible_on_drag_start_ = GetShelfLayoutManager()->IsVisible(); return; } // The state of the shelf at the end of the gesture is tested separately. if (type == ui::ET_GESTURE_SCROLL_END) return; if (type == ui::ET_GESTURE_SCROLL_UPDATE) scroll_.Add(delta); Shelf* shelf = AshTestBase::GetPrimaryShelf(); gfx::Rect shelf_bounds = GetShelfWidget()->GetWindowBoundsInScreen(); if (shelf->IsHorizontalAlignment()) { EXPECT_EQ(auto_hidden_shelf_widget_bounds_.bottom(), shelf_bounds.bottom()); EXPECT_EQ(shelf_widget_bounds_.bottom(), shelf_bounds.bottom()); } else if (SHELF_ALIGNMENT_RIGHT == shelf->alignment()) { EXPECT_EQ(auto_hidden_shelf_widget_bounds_.right(), shelf_bounds.right()); EXPECT_EQ(shelf_widget_bounds_.right(), shelf_bounds.right()); } else if (SHELF_ALIGNMENT_LEFT == shelf->alignment()) { EXPECT_EQ(auto_hidden_shelf_widget_bounds_.x(), shelf_bounds.x()); EXPECT_EQ(shelf_widget_bounds_.x(), shelf_bounds.x()); } float scroll_delta = GetShelfLayoutManager()->PrimaryAxisValue(scroll_.y(), scroll_.x()); bool increasing_drag = GetShelfLayoutManager()->SelectValueForShelfAlignment( scroll_delta<0, scroll_delta> 0, scroll_delta < 0); int shelf_size = GetShelfLayoutManager()->PrimaryAxisValue( shelf_bounds.height(), shelf_bounds.width()); int visible_bounds_size = GetShelfLayoutManager()->PrimaryAxisValue( shelf_widget_bounds_.height(), shelf_widget_bounds_.width()); int not_visible_bounds_size = GetShelfLayoutManager()->PrimaryAxisValue( auto_hidden_shelf_widget_bounds_.height(), auto_hidden_shelf_widget_bounds_.width()); if (was_visible_on_drag_start_) { if (increasing_drag) { // If dragging inwards from the visible state, then the shelf should // increase in size, but not more than the scroll delta. EXPECT_LE(visible_bounds_size, shelf_size); EXPECT_LE(std::abs(shelf_size - visible_bounds_size), std::abs(scroll_delta)); } else { if (shelf_size > not_visible_bounds_size) { // If dragging outwards from the visible state, then the shelf // should decrease in size, until it reaches the minimum size. EXPECT_EQ(shelf_size, visible_bounds_size - std::abs(scroll_delta)); } } } else { if (std::abs(scroll_delta) < visible_bounds_size - not_visible_bounds_size) { // Tests that the shelf sticks with the touch point during the drag // until the shelf is completely visible. EXPECT_EQ(shelf_size, not_visible_bounds_size + std::abs(scroll_delta)); } else { // Tests that after the shelf is completely visible, the shelf starts // resisting the drag. EXPECT_LT(shelf_size, not_visible_bounds_size + std::abs(scroll_delta)); } } } private: const gfx::Rect auto_hidden_shelf_widget_bounds_; const gfx::Rect shelf_widget_bounds_; gfx::Vector2dF scroll_; bool was_visible_on_drag_start_; DISALLOW_COPY_AND_ASSIGN(ShelfDragCallback); }; class ShelfLayoutObserverTest : public ShelfLayoutManagerObserver { public: ShelfLayoutObserverTest() : changed_auto_hide_state_(false) {} ~ShelfLayoutObserverTest() override = default; bool changed_auto_hide_state() const { return changed_auto_hide_state_; } private: // ShelfLayoutManagerObserver: void OnAutoHideStateChanged(ShelfAutoHideState new_state) override { changed_auto_hide_state_ = true; } bool changed_auto_hide_state_; DISALLOW_COPY_AND_ASSIGN(ShelfLayoutObserverTest); }; } // namespace class ShelfLayoutManagerTest : public AshTestBase { public: ShelfLayoutManagerTest() = default; // Calls the private SetState() function. void SetState(ShelfLayoutManager* layout_manager, ShelfVisibilityState state) { layout_manager->SetState(state); } void UpdateAutoHideStateNow() { GetShelfLayoutManager()->UpdateAutoHideStateNow(); } aura::Window* CreateTestWindow() { aura::Window* window = new aura::Window(nullptr); window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); window->SetType(aura::client::WINDOW_TYPE_NORMAL); window->Init(ui::LAYER_TEXTURED); ParentWindowInPrimaryRootWindow(window); return window; } aura::Window* CreateTestWindowInParent(aura::Window* root_window) { aura::Window* window = new aura::Window(nullptr); window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); window->SetType(aura::client::WINDOW_TYPE_NORMAL); window->Init(ui::LAYER_TEXTURED); aura::client::ParentWindowWithContext(window, root_window, gfx::Rect()); return window; } views::Widget* CreateTestWidgetWithParams( const views::Widget::InitParams& params) { views::Widget* out = new views::Widget; out->Init(params); out->Show(); return out; } // Create a simple widget in the current context (will delete on TearDown). views::Widget* CreateTestWidget() { views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW); params.bounds = gfx::Rect(0, 0, 200, 200); return CreateTestWidgetWithParams(params); } void RunGestureDragTests(gfx::Vector2d); // Turn on the lock screen. void LockScreen() { mojom::SessionInfoPtr info = mojom::SessionInfo::New(); info->state = session_manager::SessionState::LOCKED; ash::Shell::Get()->session_controller()->SetSessionInfo(std::move(info)); } // Turn off the lock screen. void UnlockScreen() { mojom::SessionInfoPtr info = mojom::SessionInfo::New(); info->state = session_manager::SessionState::ACTIVE; ash::Shell::Get()->session_controller()->SetSessionInfo(std::move(info)); } int64_t GetPrimaryDisplayId() { return display::Screen::GetScreen()->GetPrimaryDisplay().id(); } void StartScroll(gfx::Point start) { timestamp_ = base::TimeTicks::Now(); current_point_ = start; ui::GestureEvent event = ui::GestureEvent( current_point_.x(), current_point_.y(), ui::EF_NONE, timestamp_, ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN, 0, -1.0f)); GetShelfLayoutManager()->ProcessGestureEvent(event); } void UpdateScroll(float delta_y) { IncreaseTimestamp(); current_point_.set_y(current_point_.y() + delta_y); ui::GestureEvent event = ui::GestureEvent( current_point_.x(), current_point_.y(), ui::EF_NONE, timestamp_, ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE, 0, delta_y)); GetShelfLayoutManager()->ProcessGestureEvent(event); } void EndScroll(bool is_fling, float velocity_y) { IncreaseTimestamp(); ui::GestureEventDetails event_details = is_fling ? ui::GestureEventDetails(ui::ET_SCROLL_FLING_START, 0, velocity_y) : ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_END); ui::GestureEvent event = ui::GestureEvent(current_point_.x(), current_point_.y(), ui::EF_NONE, timestamp_, event_details); GetShelfLayoutManager()->ProcessGestureEvent(event); } void IncreaseTimestamp() { timestamp_ += base::TimeDelta::FromMilliseconds(25); } private: base::TimeTicks timestamp_; gfx::Point current_point_; DISALLOW_COPY_AND_ASSIGN(ShelfLayoutManagerTest); }; void ShelfLayoutManagerTest::RunGestureDragTests(gfx::Vector2d delta) { Shelf* shelf = GetPrimaryShelf(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_NEVER); views::Widget* widget = CreateTestWidget(); widget->Maximize(); // The time delta should be large enough to prevent accidental fling creation. const base::TimeDelta kTimeDelta = base::TimeDelta::FromMilliseconds(100); aura::Window* window = widget->GetNativeWindow(); ShelfLayoutManager* layout_manager = GetShelfLayoutManager(); layout_manager->LayoutShelf(); gfx::Rect shelf_shown = GetShelfWidget()->GetWindowBoundsInScreen(); gfx::Rect bounds_shelf = window->bounds(); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); layout_manager->LayoutShelf(); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); gfx::Rect bounds_noshelf = window->bounds(); gfx::Rect shelf_hidden = GetShelfWidget()->GetWindowBoundsInScreen(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_NEVER); layout_manager->LayoutShelf(); ui::test::EventGenerator& generator(GetEventGenerator()); const int kNumScrollSteps = 4; ShelfDragCallback handler(shelf_hidden, shelf_shown); // Swipe up on the shelf. This should not change any state. gfx::Point start = GetShelfWidget()->GetWindowBoundsInScreen().CenterPoint(); gfx::Point end = start + delta; // Swipe down on the shelf to hide it. generator.GestureScrollSequenceWithCallback( start, end, kTimeDelta, kNumScrollSteps, base::Bind(&ShelfDragCallback::ProcessScroll, base::Unretained(&handler))); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS, shelf->auto_hide_behavior()); EXPECT_NE(bounds_shelf.ToString(), window->bounds().ToString()); EXPECT_NE(shelf_shown.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); // Swipe up to show the shelf. generator.GestureScrollSequenceWithCallback( end, start, kTimeDelta, kNumScrollSteps, base::Bind(&ShelfDragCallback::ProcessScroll, base::Unretained(&handler))); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); EXPECT_EQ(bounds_shelf.ToString(), window->bounds().ToString()); EXPECT_EQ(shelf_shown.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); // Swipe up again. The shelf should stay visible. end = start - delta; generator.GestureScrollSequenceWithCallback( start, end, kTimeDelta, kNumScrollSteps, base::Bind(&ShelfDragCallback::ProcessScroll, base::Unretained(&handler))); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); EXPECT_EQ(shelf_shown.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); // Swipe down very little. It shouldn't change any state. end = start + delta; if (shelf->IsHorizontalAlignment()) end.set_y(start.y() + shelf_shown.height() * 3 / 10); else if (SHELF_ALIGNMENT_LEFT == shelf->alignment()) end.set_x(start.x() - shelf_shown.width() * 3 / 10); else if (SHELF_ALIGNMENT_RIGHT == shelf->alignment()) end.set_x(start.x() + shelf_shown.width() * 3 / 10); generator.GestureScrollSequence(start, end, kTimeDelta, 5); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); EXPECT_EQ(bounds_shelf.ToString(), window->bounds().ToString()); EXPECT_EQ(shelf_shown.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); // Swipe down again to hide. end = start + delta; generator.GestureScrollSequenceWithCallback( start, end, kTimeDelta, kNumScrollSteps, base::Bind(&ShelfDragCallback::ProcessScroll, base::Unretained(&handler))); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS, shelf->auto_hide_behavior()); EXPECT_EQ(bounds_noshelf.ToString(), window->bounds().ToString()); EXPECT_EQ(shelf_hidden.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); // Swipe up in extended hit region to show it. gfx::Point extended_start = start; if (shelf->IsHorizontalAlignment()) extended_start.set_y(GetShelfWidget()->GetWindowBoundsInScreen().y() - 1); else if (SHELF_ALIGNMENT_LEFT == shelf->alignment()) extended_start.set_x(GetShelfWidget()->GetWindowBoundsInScreen().right() + 1); else if (SHELF_ALIGNMENT_RIGHT == shelf->alignment()) extended_start.set_x(GetShelfWidget()->GetWindowBoundsInScreen().x() - 1); end = extended_start - delta; generator.GestureScrollSequenceWithCallback( extended_start, end, kTimeDelta, kNumScrollSteps, base::Bind(&ShelfDragCallback::ProcessScroll, base::Unretained(&handler))); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); EXPECT_EQ(bounds_shelf.ToString(), window->bounds().ToString()); EXPECT_EQ(shelf_shown.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); // Swipe down again to hide. end = start + delta; generator.GestureScrollSequenceWithCallback( start, end, kTimeDelta, kNumScrollSteps, base::Bind(&ShelfDragCallback::ProcessScroll, base::Unretained(&handler))); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS, shelf->auto_hide_behavior()); EXPECT_EQ(bounds_noshelf.ToString(), window->bounds().ToString()); EXPECT_EQ(shelf_hidden.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); // Swipe up outside the hit area. This should not change anything. gfx::Point outside_start = gfx::Point((GetShelfWidget()->GetWindowBoundsInScreen().x() + GetShelfWidget()->GetWindowBoundsInScreen().right()) / 2, GetShelfWidget()->GetWindowBoundsInScreen().y() - 50); end = outside_start + delta; generator.GestureScrollSequence(outside_start, end, kTimeDelta, kNumScrollSteps); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS, shelf->auto_hide_behavior()); EXPECT_EQ(shelf_hidden.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); // Swipe up from below the shelf where a bezel would be, this should show the // shelf. gfx::Point below_start = start; if (shelf->IsHorizontalAlignment()) below_start.set_y(GetShelfWidget()->GetWindowBoundsInScreen().bottom() + 1); else if (SHELF_ALIGNMENT_LEFT == shelf->alignment()) below_start.set_x(GetShelfWidget()->GetWindowBoundsInScreen().x() - 1); else if (SHELF_ALIGNMENT_RIGHT == shelf->alignment()) below_start.set_x(GetShelfWidget()->GetWindowBoundsInScreen().right() + 1); end = below_start - delta; generator.GestureScrollSequence(below_start, end, kTimeDelta, kNumScrollSteps); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); EXPECT_EQ(bounds_shelf.ToString(), window->bounds().ToString()); EXPECT_EQ(shelf_shown.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); // Swipe down again to hide. end = start + delta; generator.GestureScrollSequenceWithCallback( start, end, kTimeDelta, kNumScrollSteps, base::Bind(&ShelfDragCallback::ProcessScroll, base::Unretained(&handler))); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS, shelf->auto_hide_behavior()); EXPECT_EQ(bounds_noshelf.ToString(), window->bounds().ToString()); EXPECT_EQ(shelf_hidden.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); // Put |widget| into fullscreen. Set the shelf to be auto hidden when |widget| // is fullscreen. (eg browser immersive fullscreen). widget->SetFullscreen(true); wm::GetWindowState(window)->SetHideShelfWhenFullscreen(false); layout_manager->UpdateVisibilityState(); gfx::Rect bounds_fullscreen = window->bounds(); EXPECT_TRUE(widget->IsFullscreen()); EXPECT_EQ(bounds_noshelf.ToString(), bounds_fullscreen.ToString()); // Swipe up. This should show the shelf. end = below_start - delta; generator.GestureScrollSequenceWithCallback( below_start, end, kTimeDelta, kNumScrollSteps, base::Bind(&ShelfDragCallback::ProcessScroll, base::Unretained(&handler))); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); EXPECT_EQ(shelf_shown.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); EXPECT_EQ(bounds_fullscreen.ToString(), window->bounds().ToString()); // Swipe down to hide the shelf. end = start + delta; generator.GestureScrollSequenceWithCallback( start, end, kTimeDelta, kNumScrollSteps, base::Bind(&ShelfDragCallback::ProcessScroll, base::Unretained(&handler))); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS, shelf->auto_hide_behavior()); EXPECT_EQ(shelf_hidden.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); EXPECT_EQ(bounds_fullscreen.ToString(), window->bounds().ToString()); // Set the shelf to be hidden when |widget| is fullscreen. (eg tab fullscreen // with or without immersive browser fullscreen). wm::GetWindowState(window)->SetHideShelfWhenFullscreen(true); layout_manager->UpdateVisibilityState(); EXPECT_EQ(SHELF_HIDDEN, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS, shelf->auto_hide_behavior()); // Swipe-up. This should not change anything. end = start - delta; generator.GestureScrollSequenceWithCallback( below_start, end, kTimeDelta, kNumScrollSteps, base::Bind(&ShelfDragCallback::ProcessScroll, base::Unretained(&handler))); EXPECT_EQ(SHELF_HIDDEN, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS, shelf->auto_hide_behavior()); EXPECT_EQ(bounds_fullscreen.ToString(), window->bounds().ToString()); // Minimize actually, otherwise further event may be affected since widget // is fullscreen status. widget->Minimize(); RunAllPendingInMessageLoop(); EXPECT_FALSE(layout_manager->HasVisibleWindow()); // The shelf should be shown because there are no more visible windows. EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS, shelf->auto_hide_behavior()); // Swipe-up to hide. This should have no effect because there are no visible // windows. end = below_start - delta; generator.GestureScrollSequenceWithCallback( below_start, end, kTimeDelta, kNumScrollSteps, base::Bind(&ShelfDragCallback::ProcessScroll, base::Unretained(&handler))); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS, shelf->auto_hide_behavior()); EXPECT_EQ(shelf_shown.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); // Swipe-down to hide. This should have no effect because there are no visible // windows. end = start + delta; generator.GestureScrollSequenceWithCallback( start, end, kTimeDelta, kNumScrollSteps, base::Bind(&ShelfDragCallback::ProcessScroll, base::Unretained(&handler))); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS, shelf->auto_hide_behavior()); EXPECT_EQ(shelf_shown.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); widget->Restore(); RunAllPendingInMessageLoop(); EXPECT_TRUE(layout_manager->HasVisibleWindow()); // Swipe up on the shelf. This should show the shelf and disable auto-hide // since there is one visible window. end = below_start - delta; generator.GestureScrollSequenceWithCallback( below_start, end, kTimeDelta, kNumScrollSteps, base::Bind(&ShelfDragCallback::ProcessScroll, base::Unretained(&handler))); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); widget->Close(); RunAllPendingInMessageLoop(); EXPECT_FALSE(layout_manager->HasVisibleWindow()); // Swipe-up to hide. This should have no effect because there are no visible // windows. generator.GestureScrollSequenceWithCallback( below_start, end, kTimeDelta, kNumScrollSteps, base::Bind(&ShelfDragCallback::ProcessScroll, base::Unretained(&handler))); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); EXPECT_EQ(shelf_shown.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); // Swipe-down to hide. This should have no effect because there are no visible // windows. end = start + delta; generator.GestureScrollSequenceWithCallback( start, end, kTimeDelta, kNumScrollSteps, base::Bind(&ShelfDragCallback::ProcessScroll, base::Unretained(&handler))); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); EXPECT_EQ(shelf_shown.ToString(), GetShelfWidget()->GetWindowBoundsInScreen().ToString()); } // Makes sure SetVisible updates work area and widget appropriately. TEST_F(ShelfLayoutManagerTest, SetVisible) { ShelfWidget* shelf_widget = GetShelfWidget(); ShelfLayoutManager* manager = shelf_widget->shelf_layout_manager(); // Force an initial layout. manager->LayoutShelf(); EXPECT_EQ(SHELF_VISIBLE, manager->visibility_state()); gfx::Rect status_bounds( shelf_widget->status_area_widget()->GetWindowBoundsInScreen()); gfx::Rect shelf_bounds(shelf_widget->GetWindowBoundsInScreen()); int shelf_height = manager->GetIdealBounds().height(); display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay(); ASSERT_NE(-1, display.id()); // Bottom inset should be the max of widget heights. EXPECT_EQ(shelf_height, display.GetWorkAreaInsets().bottom()); // Hide the shelf. SetState(manager, SHELF_HIDDEN); // Run the animation to completion. StepWidgetLayerAnimatorToEnd(shelf_widget); StepWidgetLayerAnimatorToEnd(shelf_widget->status_area_widget()); EXPECT_EQ(SHELF_HIDDEN, manager->visibility_state()); display = display::Screen::GetScreen()->GetPrimaryDisplay(); EXPECT_EQ(0, display.GetWorkAreaInsets().bottom()); // Make sure the bounds of the two widgets changed. EXPECT_GE(shelf_widget->GetNativeView()->bounds().y(), display.bounds().bottom()); EXPECT_GE(shelf_widget->status_area_widget()->GetNativeView()->bounds().y(), display.bounds().bottom()); // And show it again. SetState(manager, SHELF_VISIBLE); // Run the animation to completion. StepWidgetLayerAnimatorToEnd(shelf_widget); StepWidgetLayerAnimatorToEnd(shelf_widget->status_area_widget()); EXPECT_EQ(SHELF_VISIBLE, manager->visibility_state()); display = display::Screen::GetScreen()->GetPrimaryDisplay(); EXPECT_EQ(shelf_height, display.GetWorkAreaInsets().bottom()); // Make sure the bounds of the two widgets changed. shelf_bounds = shelf_widget->GetNativeView()->bounds(); EXPECT_LT(shelf_bounds.y(), display.bounds().bottom()); status_bounds = shelf_widget->status_area_widget()->GetNativeView()->bounds(); EXPECT_LT(status_bounds.y(), display.bounds().bottom()); } // Makes sure LayoutShelf invoked while animating cleans things up. TEST_F(ShelfLayoutManagerTest, LayoutShelfWhileAnimating) { Shelf* shelf = GetPrimaryShelf(); ShelfLayoutManager* layout_manager = GetShelfLayoutManager(); // Force an initial layout. layout_manager->LayoutShelf(); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); // Hide the shelf. SetState(layout_manager, SHELF_HIDDEN); layout_manager->LayoutShelf(); EXPECT_EQ(SHELF_HIDDEN, shelf->GetVisibilityState()); display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay(); EXPECT_EQ(0, display.GetWorkAreaInsets().bottom()); // Make sure the bounds of the two widgets changed. ShelfWidget* shelf_widget = GetShelfWidget(); EXPECT_GE(shelf_widget->GetNativeView()->bounds().y(), display.bounds().bottom()); EXPECT_GE(shelf_widget->status_area_widget()->GetNativeView()->bounds().y(), display.bounds().bottom()); } // Test that switching to a different visibility state does not restart the // shelf show / hide animation if it is already running. (crbug.com/250918) TEST_F(ShelfLayoutManagerTest, SetStateWhileAnimating) { ShelfLayoutManager* layout_manager = GetShelfLayoutManager(); SetState(layout_manager, SHELF_VISIBLE); ShelfWidget* shelf_widget = GetShelfWidget(); gfx::Rect initial_shelf_bounds = shelf_widget->GetWindowBoundsInScreen(); gfx::Rect initial_status_bounds = shelf_widget->status_area_widget()->GetWindowBoundsInScreen(); ui::ScopedAnimationDurationScaleMode normal_animation_duration( ui::ScopedAnimationDurationScaleMode::SLOW_DURATION); SetState(layout_manager, SHELF_HIDDEN); SetState(layout_manager, SHELF_VISIBLE); gfx::Rect current_shelf_bounds = shelf_widget->GetWindowBoundsInScreen(); gfx::Rect current_status_bounds = shelf_widget->status_area_widget()->GetWindowBoundsInScreen(); const int small_change = initial_shelf_bounds.height() / 2; EXPECT_LE( std::abs(initial_shelf_bounds.height() - current_shelf_bounds.height()), small_change); EXPECT_LE( std::abs(initial_status_bounds.height() - current_status_bounds.height()), small_change); } // Makes sure the shelf is sized when the status area changes size. TEST_F(ShelfLayoutManagerTest, ShelfUpdatedWhenStatusAreaChangesSize) { Shelf* shelf = GetPrimaryShelf(); ASSERT_TRUE(shelf); ShelfWidget* shelf_widget = GetShelfWidget(); ASSERT_TRUE(shelf_widget); ASSERT_TRUE(shelf_widget->status_area_widget()); shelf_widget->status_area_widget()->SetBounds(gfx::Rect(0, 0, 200, 200)); EXPECT_EQ(200, shelf_widget->GetContentsView()->width() - shelf->GetShelfViewForTesting()->width()); } // Various assertions around auto-hide. TEST_F(ShelfLayoutManagerTest, AutoHide) { ui::test::EventGenerator& generator(GetEventGenerator()); Shelf* shelf = GetPrimaryShelf(); ShelfLayoutManager* layout_manager = GetShelfLayoutManager(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); views::Widget* widget = CreateTestWidget(); widget->Maximize(); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); // LayoutShelf() forces the animation to completion, at which point the // shelf should go off the screen. layout_manager->LayoutShelf(); display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay(); const int display_bottom = display.bounds().bottom(); EXPECT_EQ(display_bottom - kShelfAutoHideSize, GetShelfWidget()->GetWindowBoundsInScreen().y()); EXPECT_EQ(display_bottom, display.work_area().bottom()); // Move the mouse to the bottom of the screen. generator.MoveMouseTo(0, display_bottom - 1); // Shelf should be shown again (but it shouldn't have changed the work area). SetState(layout_manager, SHELF_AUTO_HIDE); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); layout_manager->LayoutShelf(); EXPECT_EQ(display_bottom - layout_manager->GetIdealBounds().height(), GetShelfWidget()->GetWindowBoundsInScreen().y()); EXPECT_EQ(display_bottom, display.work_area().bottom()); // Tap the system tray when shelf is shown should open the system tray menu. generator.GestureTapAt(GetPrimarySystemTray() ->GetWidget() ->GetWindowBoundsInScreen() .CenterPoint()); EXPECT_TRUE(GetPrimarySystemTray()->HasSystemBubble()); // Move mouse back up and click to dismiss the opened system tray menu. generator.MoveMouseTo(0, 0); generator.ClickLeftButton(); SetState(layout_manager, SHELF_AUTO_HIDE); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); layout_manager->LayoutShelf(); EXPECT_EQ(display_bottom - kShelfAutoHideSize, GetShelfWidget()->GetWindowBoundsInScreen().y()); // Drag mouse to bottom of screen. generator.PressLeftButton(); generator.MoveMouseTo(0, display_bottom - 1); UpdateAutoHideStateNow(); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); generator.ReleaseLeftButton(); generator.MoveMouseTo(1, display_bottom - 1); UpdateAutoHideStateNow(); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); generator.PressLeftButton(); generator.MoveMouseTo(1, display_bottom - 1); UpdateAutoHideStateNow(); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); } // Test the behavior of the shelf when it is auto hidden and it is on the // boundary between the primary and the secondary display. TEST_F(ShelfLayoutManagerTest, AutoHideShelfOnScreenBoundary) { UpdateDisplay("800x600,800x600"); Shell::Get()->display_manager()->SetLayoutForCurrentDisplays( display::test::CreateDisplayLayout(display_manager(), display::DisplayPlacement::RIGHT, 0)); // Put the primary monitor's shelf on the display boundary. Shelf* shelf = GetPrimaryShelf(); shelf->SetAlignment(SHELF_ALIGNMENT_RIGHT); // Create a window because the shelf is always shown when no windows are // visible. CreateTestWidget(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay(); const int right_edge = display.bounds().right() - 1; const int y = display.bounds().y(); // Start off the mouse nowhere near the shelf; the shelf should be hidden. ui::test::EventGenerator& generator(GetEventGenerator()); generator.MoveMouseTo(right_edge - 50, y); UpdateAutoHideStateNow(); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); // Moving the mouse over the light bar (but not to the edge of the screen) // should show the shelf. generator.MoveMouseTo(right_edge - 1, y); UpdateAutoHideStateNow(); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); EXPECT_EQ(right_edge - 1, display::Screen::GetScreen()->GetCursorScreenPoint().x()); // Moving the mouse off the light bar should hide the shelf. generator.MoveMouseTo(right_edge - 50, y); UpdateAutoHideStateNow(); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); // Moving the mouse to the right edge of the screen crossing the light bar // should show the shelf despite the mouse cursor getting warped to the // secondary display. generator.MoveMouseTo(right_edge - 1, y); generator.MoveMouseTo(right_edge, y); UpdateAutoHideStateNow(); EXPECT_NE(right_edge - 1, display::Screen::GetScreen()->GetCursorScreenPoint().x()); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); // Hide the shelf. generator.MoveMouseTo(right_edge - 50, y); UpdateAutoHideStateNow(); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); // Moving the mouse to the right edge of the screen crossing the light bar and // overshooting by a lot should keep the shelf hidden. generator.MoveMouseTo(right_edge - 1, y); generator.MoveMouseTo(right_edge + 50, y); UpdateAutoHideStateNow(); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); // Moving the mouse to the right edge of the screen crossing the light bar and // overshooting a bit should show the shelf. generator.MoveMouseTo(right_edge - 1, y); generator.MoveMouseTo(right_edge + 2, y); UpdateAutoHideStateNow(); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); // Keeping the mouse close to the left edge of the secondary display after the // shelf is shown should keep the shelf shown. generator.MoveMouseTo(right_edge + 2, y + 1); UpdateAutoHideStateNow(); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); // Moving the mouse far from the left edge of the secondary display should // hide the shelf. generator.MoveMouseTo(right_edge + 50, y); UpdateAutoHideStateNow(); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); // Moving to the left edge of the secondary display without first crossing // the primary display's right aligned shelf first should not show the shelf. generator.MoveMouseTo(right_edge + 2, y); UpdateAutoHideStateNow(); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); } // Assertions around the login screen. TEST_F(ShelfLayoutManagerTest, VisibleWhenLoginScreenShowing) { Shelf* shelf = GetPrimaryShelf(); mojom::SessionInfoPtr info = mojom::SessionInfo::New(); info->state = session_manager::SessionState::LOGIN_PRIMARY; ash::Shell::Get()->session_controller()->SetSessionInfo(std::move(info)); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_BACKGROUND_OVERLAP, GetShelfWidget()->GetBackgroundType()); } // Assertions around the lock screen showing. TEST_F(ShelfLayoutManagerTest, VisibleWhenLockScreenShowing) { Shelf* shelf = GetPrimaryShelf(); ShelfLayoutManager* layout_manager = GetShelfLayoutManager(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); views::Widget* widget = CreateTestWidget(); widget->Maximize(); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); // LayoutShelf() forces the animation to completion, at which point the // shelf should go off the screen. layout_manager->LayoutShelf(); display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay(); EXPECT_EQ(display.bounds().bottom() - kShelfAutoHideSize, GetShelfWidget()->GetWindowBoundsInScreen().y()); std::unique_ptr<views::Widget> lock_widget(AshTestBase::CreateTestWidget( nullptr, kShellWindowId_LockScreenContainer, gfx::Rect(200, 200))); lock_widget->Maximize(); // Lock the screen. LockScreen(); // Showing a widget in the lock screen should force the shelf to be visible. EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_BACKGROUND_OVERLAP, GetShelfWidget()->GetBackgroundType()); UnlockScreen(); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_BACKGROUND_OVERLAP, GetShelfWidget()->GetBackgroundType()); } // Assertions around SetAutoHideBehavior. TEST_F(ShelfLayoutManagerTest, SetAutoHideBehavior) { Shelf* shelf = GetPrimaryShelf(); views::Widget* widget = CreateTestWidget(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_NEVER); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); widget->Maximize(); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); display::Screen* screen = display::Screen::GetScreen(); EXPECT_EQ(screen->GetPrimaryDisplay().work_area().bottom(), widget->GetWorkAreaBoundsInScreen().bottom()); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(screen->GetPrimaryDisplay().work_area().bottom(), widget->GetWorkAreaBoundsInScreen().bottom()); ui::ScopedAnimationDurationScaleMode animation_duration( ui::ScopedAnimationDurationScaleMode::SLOW_DURATION); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_NEVER); ShelfWidget* shelf_widget = GetShelfWidget(); EXPECT_TRUE(shelf_widget->status_area_widget()->IsVisible()); StepWidgetLayerAnimatorToEnd(shelf_widget); StepWidgetLayerAnimatorToEnd(shelf_widget->status_area_widget()); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); EXPECT_EQ(screen->GetPrimaryDisplay().work_area().bottom(), widget->GetWorkAreaBoundsInScreen().bottom()); } // Verifies the shelf is visible when status/shelf is focused. TEST_F(ShelfLayoutManagerTest, VisibleWhenStatusOrShelfFocused) { Shelf* shelf = GetPrimaryShelf(); views::Widget* widget = CreateTestWidget(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); // Focus the shelf. Have to go through the focus cycler as normal focus // requests to it do nothing. GetShelfWidget()->GetFocusCycler()->RotateFocus(FocusCycler::FORWARD); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); widget->Activate(); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); // Trying to activate the status should fail, since we only allow activating // it when the user is using the keyboard (i.e. through FocusCycler). GetShelfWidget()->status_area_widget()->Activate(); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); GetShelfWidget()->GetFocusCycler()->RotateFocus(FocusCycler::FORWARD); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); } // Ensure a SHELF_VISIBLE shelf stays visible when the app list is shown. TEST_F(ShelfLayoutManagerTest, OpenAppListWithShelfVisibleState) { Shelf* shelf = GetPrimaryShelf(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_NEVER); // Create a normal unmaximized window; the shelf should be visible. aura::Window* window = CreateTestWindow(); window->SetBounds(gfx::Rect(0, 0, 100, 100)); window->Show(); GetAppListTestHelper()->CheckVisibility(false); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); // Show the app list and the shelf stays visible. GetAppListTestHelper()->ShowAndRunLoop(GetPrimaryDisplayId()); GetAppListTestHelper()->CheckVisibility(true); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); // Hide the app list and the shelf stays visible. GetAppListTestHelper()->DismissAndRunLoop(); GetAppListTestHelper()->CheckVisibility(false); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); } // Ensure a SHELF_AUTO_HIDE shelf is shown temporarily (SHELF_AUTO_HIDE_SHOWN) // when the app list is shown, but the visibility state doesn't change. TEST_F(ShelfLayoutManagerTest, OpenAppListWithShelfAutoHideState) { Shelf* shelf = GetPrimaryShelf(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); // Create a normal unmaximized window; the shelf should be hidden. aura::Window* window = CreateTestWindow(); window->SetBounds(gfx::Rect(0, 0, 100, 100)); window->Show(); GetAppListTestHelper()->CheckVisibility(false); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); // Show the app list and the shelf should be temporarily visible. GetAppListTestHelper()->ShowAndRunLoop(GetPrimaryDisplayId()); // The shelf's auto hide state won't be changed until the timer fires, so // force it to update now. GetShelfLayoutManager()->UpdateVisibilityState(); GetAppListTestHelper()->CheckVisibility(true); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); // Hide the app list and the shelf should be hidden again. GetAppListTestHelper()->DismissAndRunLoop(); GetAppListTestHelper()->CheckVisibility(false); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); } // Makes sure that when we have dual displays, with one or both shelves are set // to AutoHide, viewing the AppList on one of them doesn't unhide the other // hidden shelf. TEST_F(ShelfLayoutManagerTest, DualDisplayOpenAppListWithShelfAutoHideState) { // Create two displays. UpdateDisplay("0+0-200x200,+200+0-100x100"); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); EXPECT_EQ(root_windows.size(), 2U); // Get the shelves in both displays and set them to be 'AutoHide'. Shelf* shelf_1 = Shelf::ForWindow(root_windows[0]); Shelf* shelf_2 = Shelf::ForWindow(root_windows[1]); EXPECT_NE(shelf_1, shelf_2); EXPECT_NE(shelf_1->GetWindow()->GetRootWindow(), shelf_2->GetWindow()->GetRootWindow()); shelf_1->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); shelf_1->shelf_layout_manager()->LayoutShelf(); shelf_2->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); shelf_2->shelf_layout_manager()->LayoutShelf(); // Create a window in each display and show them in maximized state. aura::Window* window_1 = CreateTestWindowInParent(root_windows[0]); window_1->SetBounds(gfx::Rect(0, 0, 100, 100)); window_1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); window_1->Show(); aura::Window* window_2 = CreateTestWindowInParent(root_windows[1]); window_2->SetBounds(gfx::Rect(201, 0, 100, 100)); window_2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); window_2->Show(); EXPECT_EQ(shelf_1->GetWindow()->GetRootWindow(), window_1->GetRootWindow()); EXPECT_EQ(shelf_2->GetWindow()->GetRootWindow(), window_2->GetRootWindow()); // Activate one window in one display. wm::ActivateWindow(window_1); Shell::Get()->UpdateShelfVisibility(); GetAppListTestHelper()->CheckVisibility(false); EXPECT_EQ(SHELF_AUTO_HIDE, shelf_1->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE, shelf_2->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf_1->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf_2->GetAutoHideState()); // Show the app list; only the shelf on the same display should be shown. GetAppListTestHelper()->ShowAndRunLoop(GetPrimaryDisplayId()); Shell::Get()->UpdateShelfVisibility(); GetAppListTestHelper()->CheckVisibility(true); EXPECT_EQ(SHELF_AUTO_HIDE, shelf_1->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf_1->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE, shelf_2->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf_2->GetAutoHideState()); // Hide the app list, both shelves should be hidden. GetAppListTestHelper()->DismissAndRunLoop(); Shell::Get()->UpdateShelfVisibility(); GetAppListTestHelper()->CheckVisibility(false); EXPECT_EQ(SHELF_AUTO_HIDE, shelf_1->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE, shelf_2->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf_1->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf_2->GetAutoHideState()); } // Ensure a SHELF_HIDDEN shelf (for a fullscreen window) is shown temporarily // when the app list is shown, and hidden again when the app list is dismissed. TEST_F(ShelfLayoutManagerTest, OpenAppListWithShelfHiddenState) { Shelf* shelf = GetPrimaryShelf(); // Create a window and make it full screen; the shelf should be hidden. aura::Window* window = CreateTestWindow(); window->SetBounds(gfx::Rect(0, 0, 100, 100)); window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN); window->Show(); wm::ActivateWindow(window); GetAppListTestHelper()->CheckVisibility(false); EXPECT_EQ(SHELF_HIDDEN, shelf->GetVisibilityState()); // Show the app list and the shelf should be temporarily visible. GetAppListTestHelper()->ShowAndRunLoop(GetPrimaryDisplayId()); GetAppListTestHelper()->CheckVisibility(true); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); // Hide the app list and the shelf should be hidden again. GetAppListTestHelper()->DismissAndRunLoop(); GetAppListTestHelper()->CheckVisibility(false); EXPECT_EQ(SHELF_HIDDEN, shelf->GetVisibilityState()); } // Tests the correct behavior of the shelf when there is a system modal window // open when we have a single display. TEST_F(ShelfLayoutManagerTest, ShelfWithSystemModalWindowSingleDisplay) { Shelf* shelf = GetPrimaryShelf(); ShelfLayoutManager* layout_manager = GetShelfLayoutManager(); layout_manager->LayoutShelf(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); aura::Window* window = CreateTestWindow(); window->SetBounds(gfx::Rect(0, 0, 100, 100)); window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); window->Show(); wm::ActivateWindow(window); // Enable system modal dialog, and make sure shelf is still hidden. ShellTestApi().SimulateModalWindowOpenForTest(true); EXPECT_TRUE(Shell::IsSystemModalWindowOpen()); EXPECT_FALSE(wm::CanActivateWindow(window)); Shell::Get()->UpdateShelfVisibility(); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); } // Tests the correct behavior of the shelf when there is a system modal window // open when we have dual display. TEST_F(ShelfLayoutManagerTest, ShelfWithSystemModalWindowDualDisplay) { // Create two displays. UpdateDisplay("200x200,100x100"); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); EXPECT_EQ(2U, root_windows.size()); // Get the shelves in both displays and set them to be 'AutoHide'. Shelf* shelf_1 = Shelf::ForWindow(root_windows[0]); Shelf* shelf_2 = Shelf::ForWindow(root_windows[1]); EXPECT_NE(shelf_1, shelf_2); EXPECT_NE(shelf_1->GetWindow()->GetRootWindow(), shelf_2->GetWindow()->GetRootWindow()); shelf_1->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); shelf_1->shelf_layout_manager()->LayoutShelf(); shelf_2->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); shelf_2->shelf_layout_manager()->LayoutShelf(); // Create a window in each display and show them in maximized state. aura::Window* window_1 = CreateTestWindowInParent(root_windows[0]); window_1->SetBounds(gfx::Rect(0, 0, 100, 100)); window_1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); window_1->Show(); aura::Window* window_2 = CreateTestWindowInParent(root_windows[1]); window_2->SetBounds(gfx::Rect(201, 0, 100, 100)); window_2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); window_2->Show(); EXPECT_EQ(shelf_1->GetWindow()->GetRootWindow(), window_1->GetRootWindow()); EXPECT_EQ(shelf_2->GetWindow()->GetRootWindow(), window_2->GetRootWindow()); EXPECT_TRUE(window_1->IsVisible()); EXPECT_TRUE(window_2->IsVisible()); // Enable system modal dialog, and make sure both shelves are still hidden. ShellTestApi().SimulateModalWindowOpenForTest(true); EXPECT_TRUE(Shell::IsSystemModalWindowOpen()); EXPECT_FALSE(wm::CanActivateWindow(window_1)); EXPECT_FALSE(wm::CanActivateWindow(window_2)); Shell::Get()->UpdateShelfVisibility(); EXPECT_EQ(SHELF_AUTO_HIDE, shelf_1->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf_1->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE, shelf_2->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf_2->GetAutoHideState()); } // Tests that the shelf is only hidden for a fullscreen window at the front and // toggles visibility when another window is activated. TEST_F(ShelfLayoutManagerTest, FullscreenWindowInFrontHidesShelf) { Shelf* shelf = GetPrimaryShelf(); // Create a window and make it full screen. aura::Window* window1 = CreateTestWindow(); window1->SetBounds(gfx::Rect(0, 0, 100, 100)); window1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN); window1->Show(); aura::Window* window2 = CreateTestWindow(); window2->SetBounds(gfx::Rect(0, 0, 100, 100)); window2->Show(); wm::GetWindowState(window1)->Activate(); EXPECT_EQ(SHELF_HIDDEN, shelf->GetVisibilityState()); wm::GetWindowState(window2)->Activate(); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); wm::GetWindowState(window1)->Activate(); EXPECT_EQ(SHELF_HIDDEN, shelf->GetVisibilityState()); } // Test the behavior of the shelf when a window on one display is fullscreen // but the other display has the active window. TEST_F(ShelfLayoutManagerTest, FullscreenWindowOnSecondDisplay) { UpdateDisplay("800x600,800x600"); aura::Window::Windows root_windows = Shell::GetAllRootWindows(); // Create windows on either display. aura::Window* window1 = CreateTestWindow(); window1->SetBoundsInScreen(gfx::Rect(0, 0, 100, 100), display::Screen::GetScreen()->GetAllDisplays()[0]); window1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_FULLSCREEN); window1->Show(); aura::Window* window2 = CreateTestWindow(); window2->SetBoundsInScreen(gfx::Rect(800, 0, 100, 100), display::Screen::GetScreen()->GetAllDisplays()[1]); window2->Show(); EXPECT_EQ(root_windows[0], window1->GetRootWindow()); EXPECT_EQ(root_windows[1], window2->GetRootWindow()); wm::GetWindowState(window2)->Activate(); EXPECT_EQ( SHELF_HIDDEN, Shelf::ForWindow(window1)->shelf_layout_manager()->visibility_state()); EXPECT_EQ( SHELF_VISIBLE, Shelf::ForWindow(window2)->shelf_layout_manager()->visibility_state()); } // Test for Pinned mode. TEST_F(ShelfLayoutManagerTest, PinnedWindowHidesShelf) { Shelf* shelf = GetPrimaryShelf(); aura::Window* window1 = CreateTestWindow(); window1->SetBounds(gfx::Rect(0, 0, 100, 100)); window1->Show(); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); wm::PinWindow(window1, /* trusted */ false); EXPECT_EQ(SHELF_HIDDEN, shelf->GetVisibilityState()); wm::GetWindowState(window1)->Restore(); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); } // Tests SHELF_ALIGNMENT_(LEFT, RIGHT). TEST_F(ShelfLayoutManagerTest, SetAlignment) { Shelf* shelf = GetPrimaryShelf(); ShelfLayoutManager* layout_manager = GetShelfLayoutManager(); // Force an initial layout. shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_NEVER); layout_manager->LayoutShelf(); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); shelf->SetAlignment(SHELF_ALIGNMENT_LEFT); gfx::Rect shelf_bounds(GetShelfWidget()->GetWindowBoundsInScreen()); display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay(); ASSERT_NE(-1, display.id()); EXPECT_EQ(layout_manager->GetIdealBounds().width(), display.GetWorkAreaInsets().left()); EXPECT_GE(shelf_bounds.width(), GetShelfWidget()->GetContentsView()->GetPreferredSize().width()); EXPECT_EQ(SHELF_ALIGNMENT_LEFT, GetPrimarySystemTray()->shelf()->alignment()); StatusAreaWidget* status_area_widget = GetShelfWidget()->status_area_widget(); gfx::Rect status_bounds(status_area_widget->GetWindowBoundsInScreen()); // TODO(estade): Re-enable this check. See crbug.com/660928. // EXPECT_GE( // status_bounds.width(), // status_area_widget->GetContentsView()->GetPreferredSize().width()); EXPECT_EQ(layout_manager->GetIdealBounds().width(), display.GetWorkAreaInsets().left()); EXPECT_EQ(0, display.GetWorkAreaInsets().top()); EXPECT_EQ(0, display.GetWorkAreaInsets().bottom()); EXPECT_EQ(0, display.GetWorkAreaInsets().right()); EXPECT_EQ(display.bounds().x(), shelf_bounds.x()); EXPECT_EQ(display.bounds().y(), shelf_bounds.y()); EXPECT_EQ(display.bounds().height(), shelf_bounds.height()); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); display = display::Screen::GetScreen()->GetPrimaryDisplay(); EXPECT_EQ(0, display.GetWorkAreaInsets().left()); EXPECT_EQ(0, display.work_area().x()); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_NEVER); shelf->SetAlignment(SHELF_ALIGNMENT_RIGHT); shelf_bounds = GetShelfWidget()->GetWindowBoundsInScreen(); display = display::Screen::GetScreen()->GetPrimaryDisplay(); ASSERT_NE(-1, display.id()); EXPECT_EQ(layout_manager->GetIdealBounds().width(), display.GetWorkAreaInsets().right()); EXPECT_GE(shelf_bounds.width(), GetShelfWidget()->GetContentsView()->GetPreferredSize().width()); EXPECT_EQ(SHELF_ALIGNMENT_RIGHT, GetPrimarySystemTray()->shelf()->alignment()); status_bounds = gfx::Rect(status_area_widget->GetWindowBoundsInScreen()); // TODO(estade): Re-enable this check. See crbug.com/660928. // EXPECT_GE( // status_bounds.width(), // status_area_widget->GetContentsView()->GetPreferredSize().width()); EXPECT_EQ(layout_manager->GetIdealBounds().width(), display.GetWorkAreaInsets().right()); EXPECT_EQ(0, display.GetWorkAreaInsets().top()); EXPECT_EQ(0, display.GetWorkAreaInsets().bottom()); EXPECT_EQ(0, display.GetWorkAreaInsets().left()); EXPECT_EQ(display.work_area().right(), shelf_bounds.x()); EXPECT_EQ(display.bounds().y(), shelf_bounds.y()); EXPECT_EQ(display.bounds().height(), shelf_bounds.height()); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); display = display::Screen::GetScreen()->GetPrimaryDisplay(); EXPECT_EQ(0, display.GetWorkAreaInsets().right()); EXPECT_EQ(0, display.bounds().right() - display.work_area().right()); } TEST_F(ShelfLayoutManagerTest, GestureDrag) { // Slop is an implementation detail of gesture recognition, and complicates // these tests. Ignore it. ui::GestureConfiguration::GetInstance() ->set_max_touch_move_in_pixels_for_click(0); Shelf* shelf = GetPrimaryShelf(); { SCOPED_TRACE("BOTTOM"); shelf->SetAlignment(SHELF_ALIGNMENT_BOTTOM); RunGestureDragTests(gfx::Vector2d(0, 120)); GetAppListTestHelper()->WaitUntilIdle(); } { SCOPED_TRACE("LEFT"); shelf->SetAlignment(SHELF_ALIGNMENT_LEFT); RunGestureDragTests(gfx::Vector2d(-120, 0)); GetAppListTestHelper()->WaitUntilIdle(); } { SCOPED_TRACE("RIGHT"); shelf->SetAlignment(SHELF_ALIGNMENT_RIGHT); RunGestureDragTests(gfx::Vector2d(120, 0)); GetAppListTestHelper()->WaitUntilIdle(); } } // If swiping up on shelf ends with fling event, the app list state should // depends on the fling velocity. TEST_F(ShelfLayoutManagerTest, FlingUpOnShelfForFullscreenAppList) { Shelf* shelf = GetPrimaryShelf(); EXPECT_EQ(SHELF_ALIGNMENT_BOTTOM, shelf->alignment()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); // Starts the drag from the center of the shelf's bottom. gfx::Rect shelf_widget_bounds = GetShelfWidget()->GetWindowBoundsInScreen(); gfx::Point start = gfx::Point(shelf_widget_bounds.x() + shelf_widget_bounds.width() / 2, shelf_widget_bounds.bottom()); // Fling up that exceeds the velocity threshold should show the fullscreen app // list. StartScroll(start); UpdateScroll(-ShelfLayoutManager::kAppListDragSnapToPeekingThreshold); EndScroll(true /* is_fling */, -(ShelfLayoutManager::kAppListDragVelocityThreshold + 10)); GetAppListTestHelper()->WaitUntilIdle(); GetAppListTestHelper()->CheckVisibility(true); GetAppListTestHelper()->CheckState( app_list::AppListViewState::FULLSCREEN_ALL_APPS); // Closing the app list. GetAppListTestHelper()->DismissAndRunLoop(); GetAppListTestHelper()->CheckVisibility(false); GetAppListTestHelper()->CheckState(app_list::AppListViewState::CLOSED); // Fling down that exceeds the velocity threshold should close the app list. StartScroll(start); UpdateScroll(-ShelfLayoutManager::kAppListDragSnapToPeekingThreshold); EndScroll(true /* is_fling */, ShelfLayoutManager::kAppListDragVelocityThreshold + 10); GetAppListTestHelper()->WaitUntilIdle(); GetAppListTestHelper()->CheckVisibility(false); GetAppListTestHelper()->CheckState(app_list::AppListViewState::CLOSED); // Fling the app list not exceed the velocity threshold, the state depends on // the drag amount. StartScroll(start); UpdateScroll(-(ShelfLayoutManager::kAppListDragSnapToPeekingThreshold - 10)); EndScroll(true /* is_fling */, -(ShelfLayoutManager::kAppListDragVelocityThreshold - 10)); GetAppListTestHelper()->WaitUntilIdle(); GetAppListTestHelper()->CheckVisibility(true); GetAppListTestHelper()->CheckState(app_list::AppListViewState::PEEKING); } // Change the shelf alignment during dragging should dismiss the app list. TEST_F(ShelfLayoutManagerTest, ChangeShelfAlignmentDuringAppListDragging) { Shelf* shelf = GetPrimaryShelf(); EXPECT_EQ(SHELF_ALIGNMENT_BOTTOM, shelf->alignment()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); StartScroll(GetShelfWidget()->GetWindowBoundsInScreen().CenterPoint()); UpdateScroll(-ShelfLayoutManager::kAppListDragSnapToPeekingThreshold); GetAppListTestHelper()->WaitUntilIdle(); shelf->SetAlignment(SHELF_ALIGNMENT_LEFT); // Note, value -10 here has no specific meaning, it only used to make the // event scroll up a little bit. UpdateScroll(-10); EndScroll(false /* is_fling */, 0.f); GetAppListTestHelper()->WaitUntilIdle(); GetAppListTestHelper()->CheckVisibility(false); } TEST_F(ShelfLayoutManagerTest, SwipingUpOnShelfInTabletModeForFullscreenAppList) { Shell* shell = Shell::Get(); shell->tablet_mode_controller()->EnableTabletModeWindowManager(true); Shelf* shelf = GetPrimaryShelf(); GetShelfLayoutManager()->LayoutShelf(); EXPECT_EQ(SHELF_ALIGNMENT_BOTTOM, shelf->alignment()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); // Note: A window must be visible in order to hide the shelf. The test will // make the window fullscreened, so make the window resizeable and // maximizable. std::unique_ptr<aura::Window> window( AshTestBase::CreateTestWindow(gfx::Rect(0, 0, 400, 400))); window->SetProperty(aura::client::kResizeBehaviorKey, ui::mojom::kResizeBehaviorCanResize | ui::mojom::kResizeBehaviorCanMaximize); wm::ActivateWindow(window.get()); ui::test::EventGenerator& generator(GetEventGenerator()); constexpr base::TimeDelta kTimeDelta = base::TimeDelta::FromMilliseconds(100); constexpr int kNumScrollSteps = 4; // Starts the drag from the center of the shelf's bottom. gfx::Rect shelf_widget_bounds = GetShelfWidget()->GetWindowBoundsInScreen(); gfx::Point start = gfx::Point(shelf_widget_bounds.x() + shelf_widget_bounds.width() / 2, shelf_widget_bounds.bottom()); gfx::Vector2d delta; // Swiping up more than the threshold should show the app list. delta.set_y(ShelfLayoutManager::kAppListDragSnapToFullscreenThreshold + 10); gfx::Point end = start - delta; generator.GestureScrollSequence(start, end, kTimeDelta, kNumScrollSteps); GetAppListTestHelper()->WaitUntilIdle(); GetAppListTestHelper()->CheckVisibility(true); GetAppListTestHelper()->CheckState( app_list::AppListViewState::FULLSCREEN_ALL_APPS); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); // Closing the app list. GetAppListTestHelper()->DismissAndRunLoop(); GetAppListTestHelper()->CheckVisibility(false); GetAppListTestHelper()->CheckState(app_list::AppListViewState::CLOSED); // Swiping up less or equal to the threshold should dismiss the app list. delta.set_y(ShelfLayoutManager::kAppListDragSnapToFullscreenThreshold - 10); end = start - delta; // TODO(minch): investigate failure without EnableMaximizeMode again here. // http://crbug.com/746481. shell->tablet_mode_controller()->EnableTabletModeWindowManager(true); generator.GestureScrollSequence(start, end, kTimeDelta, kNumScrollSteps); GetAppListTestHelper()->WaitUntilIdle(); GetAppListTestHelper()->CheckVisibility(false); GetAppListTestHelper()->CheckState(app_list::AppListViewState::CLOSED); GetShelfLayoutManager()->UpdateVisibilityState(); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); // Swiping down on the shelf should do nothing as tablet mode disables auto // hiding the shelf by swiping down. end = start + delta; generator.GestureScrollSequence(start, end, kTimeDelta, kNumScrollSteps); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); // Verify that the shelf can still enter auto hide if the window requests to // be fullscreened. wm::WindowState* window_state = wm::GetWindowState(window.get()); const wm::WMEvent event(wm::WM_EVENT_TOGGLE_FULLSCREEN); window_state->OnWMEvent(&event); window_state->SetHideShelfWhenFullscreen(false); window_state->SetInImmersiveFullscreen(true); GetShelfLayoutManager()->UpdateVisibilityState(); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); // Swiping up should show the shelf but not the app list if shelf is hidden. generator.GestureScrollSequence(end, start, kTimeDelta, kNumScrollSteps); GetAppListTestHelper()->WaitUntilIdle(); GetAppListTestHelper()->CheckVisibility(false); GetAppListTestHelper()->CheckState(app_list::AppListViewState::CLOSED); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); // Swiping down should hide the shelf. generator.GestureScrollSequence(start, end, kTimeDelta, kNumScrollSteps); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); // Verify that after toggling fullscreen to off, the shelf is visible. window_state->OnWMEvent(&event); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); // Minimize the visible window, the shelf should be shown if there are no // visible windows, even in auto-hide mode. window_state->Minimize(); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); // Swiping up on the shelf in this state should open the app list. delta.set_y(ShelfLayoutManager::kAppListDragSnapToFullscreenThreshold + 10); end = start - delta; generator.GestureScrollSequence(start, end, kTimeDelta, kNumScrollSteps); GetAppListTestHelper()->WaitUntilIdle(); GetAppListTestHelper()->CheckVisibility(true); GetAppListTestHelper()->CheckState( app_list::AppListViewState::FULLSCREEN_ALL_APPS); } TEST_F(ShelfLayoutManagerTest, SwipingUpOnShelfInLaptopModeForFullscreenAppList) { Shelf* shelf = GetPrimaryShelf(); EXPECT_EQ(SHELF_ALIGNMENT_BOTTOM, shelf->alignment()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); ui::test::EventGenerator& generator(GetEventGenerator()); constexpr base::TimeDelta kTimeDelta = base::TimeDelta::FromMilliseconds(100); constexpr int kNumScrollSteps = 4; // Starts the drag from the center of the shelf's bottom. gfx::Rect shelf_widget_bounds = GetShelfWidget()->GetWindowBoundsInScreen(); gfx::Point start = gfx::Point(shelf_widget_bounds.x() + shelf_widget_bounds.width() / 2, shelf_widget_bounds.bottom()); gfx::Vector2d delta; // Swiping up less than the close threshold should close the app list. delta.set_y(ShelfLayoutManager::kAppListDragSnapToClosedThreshold - 10); gfx::Point end = start - delta; generator.GestureScrollSequence(start, end, kTimeDelta, kNumScrollSteps); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); GetAppListTestHelper()->WaitUntilIdle(); GetAppListTestHelper()->CheckVisibility(false); GetAppListTestHelper()->CheckState(app_list::AppListViewState::CLOSED); // Swiping up more than the close threshold but less than peeking threshold // should keep the app list at PEEKING state. delta.set_y(ShelfLayoutManager::kAppListDragSnapToPeekingThreshold - 10); end = start - delta; generator.GestureScrollSequence(start, end, kTimeDelta, kNumScrollSteps); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); GetAppListTestHelper()->WaitUntilIdle(); GetAppListTestHelper()->CheckVisibility(true); GetAppListTestHelper()->CheckState(app_list::AppListViewState::PEEKING); // Closing the app list. GetAppListTestHelper()->DismissAndRunLoop(); GetAppListTestHelper()->CheckVisibility(false); GetAppListTestHelper()->CheckState(app_list::AppListViewState::CLOSED); // Swiping up more than the peeking threshold should keep the app list at // FULLSCREEN_ALL_APPS state. delta.set_y(ShelfLayoutManager::kAppListDragSnapToPeekingThreshold + 10); end = start - delta; generator.GestureScrollSequence(start, end, kTimeDelta, kNumScrollSteps); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); GetAppListTestHelper()->WaitUntilIdle(); GetAppListTestHelper()->CheckVisibility(true); GetAppListTestHelper()->CheckState( app_list::AppListViewState::FULLSCREEN_ALL_APPS); } // Swiping on shelf when fullscreen app list is opened should have no effect. TEST_F(ShelfLayoutManagerTest, SwipingOnShelfIfFullscreenAppListOpened) { Shelf* shelf = GetPrimaryShelf(); ShelfLayoutManager* layout_manager = GetShelfLayoutManager(); aura::Window* root_window = RootWindowController::ForTargetRootWindow()->GetRootWindow(); layout_manager->OnAppListVisibilityChanged(true, root_window); EXPECT_EQ(SHELF_ALIGNMENT_BOTTOM, shelf->alignment()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); // Note: A window must be visible in order to hide the shelf. CreateTestWidget(); ui::test::EventGenerator& generator(GetEventGenerator()); constexpr base::TimeDelta kTimeDelta = base::TimeDelta::FromMilliseconds(100); constexpr int kNumScrollSteps = 4; gfx::Point start = GetShelfWidget()->GetWindowBoundsInScreen().CenterPoint(); // Swiping down on shelf when the fullscreen app list is opened // should not hide the shelf. gfx::Point end = start + gfx::Vector2d(0, 120); generator.GestureScrollSequence(start, end, kTimeDelta, kNumScrollSteps); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); // Swiping left on shelf when the fullscreen app list is opened // should not hide the shelf. shelf->SetAlignment(SHELF_ALIGNMENT_LEFT); end = start + gfx::Vector2d(-120, 0); generator.GestureScrollSequence(start, end, kTimeDelta, kNumScrollSteps); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); // Swiping right on shelf when the fullscreen app list is opened // should not hide the shelf. shelf->SetAlignment(SHELF_ALIGNMENT_RIGHT); end = start + gfx::Vector2d(120, 0); generator.GestureScrollSequence(start, end, kTimeDelta, kNumScrollSteps); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_BEHAVIOR_NEVER, shelf->auto_hide_behavior()); } TEST_F(ShelfLayoutManagerTest, WindowVisibilityDisablesAutoHide) { UpdateDisplay("800x600,800x600"); Shelf* shelf = GetPrimaryShelf(); ShelfLayoutManager* layout_manager = GetShelfLayoutManager(); layout_manager->LayoutShelf(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); // Create a visible window so auto-hide behavior is enforced views::Widget* dummy = CreateTestWidget(); // Window visible => auto hide behaves normally. layout_manager->UpdateVisibilityState(); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); // Window minimized => auto hide disabled. dummy->Minimize(); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); // Window closed => auto hide disabled. dummy->CloseNow(); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); // Multiple window test views::Widget* window1 = CreateTestWidget(); views::Widget* window2 = CreateTestWidget(); // both visible => normal autohide EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); // either minimzed => normal autohide window2->Minimize(); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); window2->Restore(); window1->Minimize(); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); // both minimized => disable auto hide window2->Minimize(); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); // Test moving windows to/from other display. window2->Restore(); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); // Move to second display. window2->SetBounds(gfx::Rect(850, 50, 50, 50)); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); // Move back to primary display. window2->SetBounds(gfx::Rect(50, 50, 50, 50)); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); } // Test that the shelf animates back to its normal position upon a user // completing a gesture drag. TEST_F(ShelfLayoutManagerTest, ShelfAnimatesWhenGestureComplete) { // Test the shelf animates back to its original visible bounds when it is // dragged when there are no visible windows. Shelf* shelf = GetPrimaryShelf(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); gfx::Rect visible_bounds = GetShelfWidget()->GetWindowBoundsInScreen(); { // Enable animations so that we can make sure that they occur. ui::ScopedAnimationDurationScaleMode regular_animations( ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); ui::test::EventGenerator& generator(GetEventGenerator()); gfx::Rect shelf_bounds_in_screen = GetShelfWidget()->GetWindowBoundsInScreen(); gfx::Point start(shelf_bounds_in_screen.CenterPoint()); gfx::Point end(start.x(), shelf_bounds_in_screen.bottom()); generator.GestureScrollSequence(start, end, base::TimeDelta::FromMilliseconds(10), 5); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); ShelfAnimationWaiter waiter(visible_bounds); // Wait till the animation completes and check that it occurred. waiter.WaitTillDoneAnimating(); EXPECT_TRUE(waiter.WasValidAnimation()); } // Create a visible window so auto-hide behavior is enforced. CreateTestWidget(); // Get the bounds of the shelf when it is hidden. EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); gfx::Rect auto_hidden_bounds = GetShelfWidget()->GetWindowBoundsInScreen(); { // Enable the animations so that we can make sure they do occur. ui::ScopedAnimationDurationScaleMode regular_animations( ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); gfx::Point start = GetShelfWidget()->GetWindowBoundsInScreen().CenterPoint(); gfx::Point end(start.x(), start.y() - 100); ui::test::EventGenerator& generator(GetEventGenerator()); // Test that the shelf animates to the visible bounds after a swipe up on // the auto hidden shelf. generator.GestureScrollSequence(start, end, base::TimeDelta::FromMilliseconds(10), 1); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); ShelfAnimationWaiter waiter1(visible_bounds); waiter1.WaitTillDoneAnimating(); EXPECT_TRUE(waiter1.WasValidAnimation()); // Test that the shelf animates to the auto hidden bounds after a swipe down // on the visible shelf. end = gfx::Point(start.x(), start.y() + 100); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); generator.GestureScrollSequence(start, end, base::TimeDelta::FromMilliseconds(10), 1); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); ShelfAnimationWaiter waiter2(auto_hidden_bounds); waiter2.WaitTillDoneAnimating(); EXPECT_TRUE(waiter2.WasValidAnimation()); } } TEST_F(ShelfLayoutManagerTest, AutohideShelfForAutohideWhenActiveWindow) { Shelf* shelf = GetPrimaryShelf(); views::Widget* widget_one = CreateTestWidget(); views::Widget* widget_two = CreateTestWidget(); aura::Window* window_two = widget_two->GetNativeWindow(); // Turn on hide_shelf_when_active behavior for window two - shelf should // still be visible when window two is made active since it is not yet // maximized. widget_one->Activate(); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); wm::GetWindowState(window_two) ->set_autohide_shelf_when_maximized_or_fullscreen(true); widget_two->Activate(); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); // Now the flag takes effect once window two is maximized. widget_two->Maximize(); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); // The hide_shelf_when_active flag should override the behavior of the // hide_shelf_when_fullscreen flag even if the window is currently fullscreen. wm::GetWindowState(window_two)->SetHideShelfWhenFullscreen(false); widget_two->SetFullscreen(true); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); wm::GetWindowState(window_two)->Restore(); // With the flag off, shelf no longer auto-hides. widget_one->Activate(); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); wm::GetWindowState(window_two) ->set_autohide_shelf_when_maximized_or_fullscreen(false); widget_two->Activate(); EXPECT_EQ(SHELF_VISIBLE, shelf->GetVisibilityState()); wm::GetWindowState(window_two) ->set_autohide_shelf_when_maximized_or_fullscreen(true); window_two->SetProperty(aura::client::kAlwaysOnTopKey, true); auto* shelf_window = shelf->GetWindow(); aura::Window* container = shelf_window->GetRootWindow()->GetChildById( kShellWindowId_AlwaysOnTopContainer); EXPECT_TRUE(base::ContainsValue(container->children(), window_two)); widget_two->Maximize(); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); wm::WorkspaceWindowState window_state = RootWindowController::ForWindow(shelf_window)->GetWorkspaceWindowState(); EXPECT_EQ(wm::WORKSPACE_WINDOW_STATE_MAXIMIZED, window_state); } TEST_F(ShelfLayoutManagerTest, ShelfFlickerOnTrayActivation) { Shelf* shelf = GetPrimaryShelf(); // Create a visible window so auto-hide behavior is enforced. CreateTestWidget(); // Turn on auto-hide for the shelf. shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_HIDDEN, shelf->GetAutoHideState()); // Show the status menu. That should make the shelf visible again. Shell::Get()->accelerator_controller()->PerformActionIfEnabled( TOGGLE_SYSTEM_TRAY_BUBBLE); EXPECT_EQ(SHELF_AUTO_HIDE, shelf->GetVisibilityState()); EXPECT_EQ(SHELF_AUTO_HIDE_SHOWN, shelf->GetAutoHideState()); EXPECT_TRUE(GetPrimarySystemTray()->HasSystemBubble()); } TEST_F(ShelfLayoutManagerTest, WorkAreaChangeWorkspace) { // Make sure the shelf is always visible. Shelf* shelf = GetPrimaryShelf(); ShelfLayoutManager* layout_manager = GetShelfLayoutManager(); shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_NEVER); layout_manager->LayoutShelf(); views::Widget* widget_one = CreateTestWidget(); widget_one->Maximize(); views::Widget* widget_two = CreateTestWidget(); widget_two->Maximize(); widget_two->Activate(); // Both windows are maximized. They should be of the same size. EXPECT_EQ(widget_one->GetNativeWindow()->bounds().ToString(), widget_two->GetNativeWindow()->bounds().ToString()); int area_when_shelf_shown = widget_one->GetNativeWindow()->bounds().size().GetArea(); // Now hide the shelf. shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); // Both windows should be resized according to the shelf status. EXPECT_EQ(widget_one->GetNativeWindow()->bounds().ToString(), widget_two->GetNativeWindow()->bounds().ToString()); // Resized to small. EXPECT_LT(area_when_shelf_shown, widget_one->GetNativeWindow()->bounds().size().GetArea()); // Now show the shelf. shelf->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_NEVER); // Again both windows should be of the same size. EXPECT_EQ(widget_one->GetNativeWindow()->bounds().ToString(), widget_two->GetNativeWindow()->bounds().ToString()); EXPECT_EQ(area_when_shelf_shown, widget_one->GetNativeWindow()->bounds().size().GetArea()); } TEST_F(ShelfLayoutManagerTest, BackgroundTypeWhenLockingScreen) { // Creates a maximized window to have a background type other than default. std::unique_ptr<aura::Window> window(CreateTestWindow()); window->Show(); wm::ActivateWindow(window.get()); EXPECT_EQ(SHELF_BACKGROUND_DEFAULT, GetShelfWidget()->GetBackgroundType()); window->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); EXPECT_EQ(SHELF_BACKGROUND_MAXIMIZED, GetShelfWidget()->GetBackgroundType()); Shell::Get()->lock_state_controller()->StartLockAnimationAndLockImmediately(); EXPECT_EQ(SHELF_BACKGROUND_DEFAULT, GetShelfWidget()->GetBackgroundType()); } TEST_F(ShelfLayoutManagerTest, ShelfBackgroundColor) { EXPECT_EQ(SHELF_BACKGROUND_DEFAULT, GetShelfWidget()->GetBackgroundType()); std::unique_ptr<aura::Window> w1(CreateTestWindow()); w1->Show(); wm::ActivateWindow(w1.get()); EXPECT_EQ(SHELF_BACKGROUND_DEFAULT, GetShelfWidget()->GetBackgroundType()); w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); EXPECT_EQ(SHELF_BACKGROUND_MAXIMIZED, GetShelfWidget()->GetBackgroundType()); std::unique_ptr<aura::Window> w2(CreateTestWindow()); w2->Show(); wm::ActivateWindow(w2.get()); // Overlaps with shelf. w2->SetBounds(GetShelfLayoutManager()->GetIdealBounds()); // Still background is 'maximized'. EXPECT_EQ(SHELF_BACKGROUND_MAXIMIZED, GetShelfWidget()->GetBackgroundType()); w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MINIMIZED); EXPECT_EQ(SHELF_BACKGROUND_OVERLAP, GetShelfWidget()->GetBackgroundType()); w2->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MINIMIZED); EXPECT_EQ(SHELF_BACKGROUND_DEFAULT, GetShelfWidget()->GetBackgroundType()); w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); EXPECT_EQ(SHELF_BACKGROUND_MAXIMIZED, GetShelfWidget()->GetBackgroundType()); std::unique_ptr<aura::Window> w3(CreateTestWindow()); w3->SetProperty(aura::client::kModalKey, ui::MODAL_TYPE_WINDOW); ::wm::AddTransientChild(w1.get(), w3.get()); w3->Show(); wm::ActivateWindow(w3.get()); wm::WorkspaceWindowState window_state = RootWindowController::ForWindow(GetShelfWidget()->GetNativeWindow()) ->GetWorkspaceWindowState(); EXPECT_EQ(wm::WORKSPACE_WINDOW_STATE_MAXIMIZED, window_state); w3.reset(); w1.reset(); EXPECT_EQ(SHELF_BACKGROUND_DEFAULT, GetShelfWidget()->GetBackgroundType()); } // Test the background color for split view mode. TEST_F(ShelfLayoutManagerTest, ShelfBackgroundColorInSplitView) { // Split view is only enabled in tablet mode. Shell::Get()->tablet_mode_controller()->EnableTabletModeWindowManager(true); std::unique_ptr<aura::Window> window1(CreateTestWindow()); window1->SetProperty(aura::client::kResizeBehaviorKey, ui::mojom::kResizeBehaviorCanResize | ui::mojom::kResizeBehaviorCanMaximize); window1->Show(); SplitViewController* split_view_controller = Shell::Get()->split_view_controller(); split_view_controller->SnapWindow(window1.get(), SplitViewController::LEFT); EXPECT_EQ(SHELF_BACKGROUND_SPLIT_VIEW, GetShelfWidget()->GetBackgroundType()); std::unique_ptr<aura::Window> window2(CreateTestWindow()); window2->SetProperty(aura::client::kResizeBehaviorKey, ui::mojom::kResizeBehaviorCanResize | ui::mojom::kResizeBehaviorCanMaximize); window2->Show(); split_view_controller->SnapWindow(window2.get(), SplitViewController::RIGHT); EXPECT_EQ(SHELF_BACKGROUND_SPLIT_VIEW, GetShelfWidget()->GetBackgroundType()); // Ending split view mode will maximize the two windows. split_view_controller->EndSplitView(); EXPECT_EQ(SHELF_BACKGROUND_MAXIMIZED, GetShelfWidget()->GetBackgroundType()); } // Verify that the shelf doesn't have the opaque background if it's auto-hide // status. TEST_F(ShelfLayoutManagerTest, ShelfBackgroundColorAutoHide) { EXPECT_EQ(SHELF_BACKGROUND_DEFAULT, GetShelfWidget()->GetBackgroundType()); GetPrimaryShelf()->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); std::unique_ptr<aura::Window> w1(CreateTestWindow()); w1->Show(); wm::ActivateWindow(w1.get()); EXPECT_EQ(SHELF_BACKGROUND_OVERLAP, GetShelfWidget()->GetBackgroundType()); w1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); EXPECT_EQ(SHELF_BACKGROUND_OVERLAP, GetShelfWidget()->GetBackgroundType()); } // Verify the hit bounds of the status area extend to the edge of the shelf. TEST_F(ShelfLayoutManagerTest, StatusAreaHitBoxCoversEdge) { StatusAreaWidget* status_area_widget = GetShelfWidget()->status_area_widget(); ui::test::EventGenerator& generator(GetEventGenerator()); display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay(); gfx::Rect inset_display_bounds = display.bounds(); inset_display_bounds.Inset(0, 0, 1, 1); // Test bottom right pixel for bottom alignment. GetPrimaryShelf()->SetAlignment(SHELF_ALIGNMENT_BOTTOM); generator.MoveMouseTo(inset_display_bounds.bottom_right()); EXPECT_FALSE(status_area_widget->IsMessageBubbleShown()); generator.ClickLeftButton(); EXPECT_TRUE(status_area_widget->IsMessageBubbleShown()); generator.ClickLeftButton(); EXPECT_FALSE(status_area_widget->IsMessageBubbleShown()); // Test bottom right pixel for right alignment. GetPrimaryShelf()->SetAlignment(SHELF_ALIGNMENT_RIGHT); generator.MoveMouseTo(inset_display_bounds.bottom_right()); EXPECT_FALSE(status_area_widget->IsMessageBubbleShown()); generator.ClickLeftButton(); EXPECT_TRUE(status_area_widget->IsMessageBubbleShown()); generator.ClickLeftButton(); EXPECT_FALSE(status_area_widget->IsMessageBubbleShown()); // Test bottom left pixel for left alignment. generator.MoveMouseTo(inset_display_bounds.bottom_left()); GetPrimaryShelf()->SetAlignment(SHELF_ALIGNMENT_LEFT); EXPECT_FALSE(status_area_widget->IsMessageBubbleShown()); generator.ClickLeftButton(); EXPECT_TRUE(status_area_widget->IsMessageBubbleShown()); generator.ClickLeftButton(); EXPECT_FALSE(status_area_widget->IsMessageBubbleShown()); } // Tests that when the auto-hide behaviour is changed during an animation the // target bounds are updated to reflect the new state. TEST_F(ShelfLayoutManagerTest, ShelfAutoHideToggleDuringAnimationUpdatesBounds) { aura::Window* status_window = GetShelfWidget()->status_area_widget()->GetNativeView(); gfx::Rect initial_bounds = status_window->bounds(); ui::ScopedAnimationDurationScaleMode regular_animations( ui::ScopedAnimationDurationScaleMode::SLOW_DURATION); GetPrimaryShelf()->SetAutoHideBehavior(SHELF_AUTO_HIDE_ALWAYS_HIDDEN); gfx::Rect hide_target_bounds = status_window->GetTargetBounds(); EXPECT_GT(hide_target_bounds.y(), initial_bounds.y()); GetPrimaryShelf()->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_NEVER); gfx::Rect reshow_target_bounds = status_window->GetTargetBounds(); EXPECT_EQ(initial_bounds, reshow_target_bounds); } // Tests that during shutdown, that window activation changes are properly // handled, and do not crash (crbug.com/458768) TEST_F(ShelfLayoutManagerTest, ShutdownHandlesWindowActivation) { GetPrimaryShelf()->SetAutoHideBehavior(SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS); aura::Window* window1 = CreateTestWindowInShellWithId(0); window1->SetBounds(gfx::Rect(0, 0, 100, 100)); window1->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); window1->Show(); std::unique_ptr<aura::Window> window2(CreateTestWindowInShellWithId(0)); window2->SetBounds(gfx::Rect(0, 0, 100, 100)); window2->Show(); wm::ActivateWindow(window1); GetShelfLayoutManager()->PrepareForShutdown(); // Deleting a focused maximized window will switch focus to |window2|. This // would normally cause the ShelfLayoutManager to update its state. However // during shutdown we want to handle this without crashing. delete window1; } TEST_F(ShelfLayoutManagerTest, ShelfLayoutInUnifiedDesktop) { Shell::Get()->display_manager()->SetUnifiedDesktopEnabled(true); UpdateDisplay("500x400, 500x400"); StatusAreaWidget* status_area_widget = GetShelfWidget()->status_area_widget(); EXPECT_TRUE(status_area_widget->IsVisible()); // Shelf should be in the first display's area. gfx::Rect status_area_bounds(status_area_widget->GetWindowBoundsInScreen()); EXPECT_TRUE(gfx::Rect(0, 0, 500, 400).Contains(status_area_bounds)); EXPECT_EQ(gfx::Point(500, 400), status_area_bounds.bottom_right()); } class ShelfLayoutManagerKeyboardTest : public AshTestBase { public: ShelfLayoutManagerKeyboardTest() = default; ~ShelfLayoutManagerKeyboardTest() override = default; // AshTestBase: void SetUp() override { AshTestBase::SetUp(); UpdateDisplay("800x600"); keyboard::SetTouchKeyboardEnabled(true); keyboard::SetAccessibilityKeyboardEnabled(true); Shell::Get()->CreateKeyboard(); } // AshTestBase: void TearDown() override { keyboard::SetAccessibilityKeyboardEnabled(false); keyboard::SetTouchKeyboardEnabled(false); AshTestBase::TearDown(); } void InitKeyboardBounds() { gfx::Rect work_area( display::Screen::GetScreen()->GetPrimaryDisplay().work_area()); keyboard_bounds_.SetRect(work_area.x(), work_area.y() + work_area.height() / 2, work_area.width(), work_area.height() / 2); } void NotifyKeyboardChanging(ShelfLayoutManager* layout_manager, bool is_locked, const gfx::Rect& bounds) { keyboard::KeyboardStateDescriptor state; state.visual_bounds = bounds; state.occluded_bounds = bounds; state.displaced_bounds = is_locked ? bounds : gfx::Rect(); state.is_locked = is_locked; state.is_available = !bounds.IsEmpty(); layout_manager->OnKeyboardAvailabilityChanged(state.is_available); layout_manager->OnKeyboardAppearanceChanged(state); } const gfx::Rect& keyboard_bounds() const { return keyboard_bounds_; } private: gfx::Rect keyboard_bounds_; DISALLOW_COPY_AND_ASSIGN(ShelfLayoutManagerKeyboardTest); }; TEST_F(ShelfLayoutManagerKeyboardTest, ShelfNotMoveOnKeyboardOpen) { gfx::Rect orig_bounds = GetShelfWidget()->GetWindowBoundsInScreen(); ShelfLayoutManager* layout_manager = GetShelfLayoutManager(); InitKeyboardBounds(); keyboard::KeyboardController* kb_controller = keyboard::KeyboardController::GetInstance(); // Open keyboard in non-sticky mode. kb_controller->ShowKeyboard(false); NotifyKeyboardChanging(layout_manager, false, keyboard_bounds()); layout_manager->LayoutShelf(); // Shelf position should not be changed. EXPECT_EQ(orig_bounds, GetShelfWidget()->GetWindowBoundsInScreen()); } // When kAshUseNewVKWindowBehavior flag enabled, do not change accessibility // keyboard work area in non-sticky mode. TEST_F(ShelfLayoutManagerKeyboardTest, ShelfIgnoreWorkAreaChangeInNonStickyMode) { ShelfLayoutManager* layout_manager = GetShelfLayoutManager(); InitKeyboardBounds(); keyboard::KeyboardController* kb_controller = keyboard::KeyboardController::GetInstance(); gfx::Rect orig_work_area( display::Screen::GetScreen()->GetPrimaryDisplay().work_area()); // Open keyboard in non-sticky mode. kb_controller->ShowKeyboard(false); NotifyKeyboardChanging(layout_manager, false, keyboard_bounds()); layout_manager->LayoutShelf(); // Work area should not be changed. EXPECT_EQ(orig_work_area, display::Screen::GetScreen()->GetPrimaryDisplay().work_area()); kb_controller->HideKeyboard( keyboard::KeyboardController::HIDE_REASON_AUTOMATIC); NotifyKeyboardChanging(layout_manager, false, gfx::Rect()); layout_manager->LayoutShelf(); EXPECT_EQ(orig_work_area, display::Screen::GetScreen()->GetPrimaryDisplay().work_area()); } // Change accessibility keyboard work area in sticky mode. TEST_F(ShelfLayoutManagerKeyboardTest, ShelfShouldChangeWorkAreaInStickyMode) { ShelfLayoutManager* layout_manager = GetShelfLayoutManager(); InitKeyboardBounds(); keyboard::KeyboardController* kb_controller = keyboard::KeyboardController::GetInstance(); gfx::Rect orig_work_area( display::Screen::GetScreen()->GetPrimaryDisplay().work_area()); // Open keyboard in sticky mode. kb_controller->ShowKeyboard(true); NotifyKeyboardChanging(layout_manager, true, keyboard_bounds()); layout_manager->LayoutShelf(); // Work area should be changed. EXPECT_NE(orig_work_area, display::Screen::GetScreen()->GetPrimaryDisplay().work_area()); } } // namespace ash
class Access: """A generic access to the database.""" def __init__(self, inner: RawIndexAccess): self._inner = inner self._valid = False def __enter__(self) -> "Access": self._valid = True return self def __exit__(self, exc_type: Optional[type], exc_value: Optional[Any], exc_traceback: Optional[object]) -> None: self._valid = False def set_always_valid(self) -> None: """Marks Access as always valid (meaning that with kind of Access database can be accessed anytime)""" self._valid = True def valid(self) -> bool: """Returns True if access is valid and can be used.""" return self._valid def inner(self) -> RawIndexAccess: """Returns the inner access pointer.""" if not self.valid(): raise RuntimeError("Access is not valid anymore") return self._inner
Sustainable Leadership Supporting Educational Transformation The world, influenced by 21st century technologies and ecological challenges, has rapidly changed with more ability to β€œconnect” locally and globally and more opportunities to learn from a range of sources. As a result, our learners and their needs have changed. With such rapid changes, conceptions of educational leadership need to reflect these changes utilizing the complexities of the role in society. As a group of educators who work in a School District, Ministry of Education and University teacher education programs, we ask how educational leaders in school districts and teacher education programs can design spaces that engage everyone, recognize everyone’s expertise and share responsibility for growth and development, and how in teacher education we can begin to move away from the hierarchical, industrialized model of management to one where everyone feels engaged, valued, and heard. In this paper, we draw on sustainable and distributed leadership ideas, termed by Wheatley (2010) as the β€œnew sciences,” informed by tenets from complexity theory. Using a case study approach and narrative insights, this paper elucidates how an ongoing Professional Learning Network (PLN) called Link-to-Practice (L2P) offers an alternative conception of educational leadership. Keywords: case study; narrative, qualitative research, complexity theory
// writePythonConfig writes the .netrc contents for authenticating to AR. func writePythonConfig(wr io.Writer, tok string) error { const pythonConfig = ` {{- range $entry := .Hosts}} machine {{$entry}} login oauth2accesstoken password {{$.Token}} {{- end}} ` type authEntry struct { Token string Hosts []string } t, err := template.New("netrc").Parse(pythonConfig) if err != nil { return err } cfg := authEntry{ Token: tok, Hosts: arRepositories(), } if err := t.Execute(wr, cfg); err != nil { return fmt.Errorf("creating python netrc template: %w", err) } return nil }
It takes a certain kind of human β€” a superhuman, perhaps β€” to take on a challenge as daunting as running seven marathons in seven days on seven continents. Calgary accountant and runner Stephen Park, 44, said he’d always dreamed of running a marathon on every continent, but when he signed up for the Triple 7 Quest run, he never imagined completing such a monumental task in only a week. β€œWhen I found out about the race, I was intrigued,” Park said. β€œI’ve always loved travel, and it was so far out there I knew it would be a huge challenge for my mind and body.” An avid marathoner in the early 2000s, Park said he took a 12-year hiatus from running after he got married (he actually proposed to his wife at the finish line of the New York City Marathon) and had children. β€œThings were busy with family life, raising three kids and I gained some weight,” Park said. β€œIn 2015 I made a New Year’s resolution, and I signed up for the Great Wall (of China) Marathon. That’s when I got addicted to running again.” And run Park did, flying around the world to complete races in Perth, Singapore, Cairo, Amsterdam, New York, Chile and Antarctica in just seven days. β€œIt was quite an amazing experience,” he said. β€œI’d never run a back-to-back marathon in my life. Usually when you run, you have all sorts of strategies and get time to recover, but I didn’t have any of those luxuries.” The marathon in Perth turned out to be a tough starting point for Park. He had spent more than 20 hours on a plane, and then had to race in unforgiving 35 degree heat. β€œIt was a very tough race β€” I was literally running through sprinklers and dumping water on my head to stay cool,” Park said. β€œSingapore was hard too, it was really humid and we got rained on a bit.” Of all places in all continents, Park said the most memorable race was in Cairo, Egypt. Starting the race when night fell, Park said runners had to navigate the chaotic streets of Cairo, dodging cars and people carrying guns, boosted by fear of the unknown and the energy of cheering bystanders. β€œWe started racing and I realized I had forgotten to use the bathroom. I went to a mosque, but they wouldn’t let me in,” he said with a laugh. β€œIt was pretty scary in the dark; there was quite a military presence there, guns everywhere. β€œGoing through major intersections, we had to play Frogger through traffic to get to the other side. We even witnessed a car hit a pedestrian,” Park said. β€œYou were always a bit scared for your life.” Zigzagging across the globe, pounding pavement in Amsterdam, New York and Punta Arenas, Park said Antarctica was the most beautiful place they could have finished. β€œRunning through Antarctica, you would go through Russian and Chilean bases, and we even saw some fellow Canadian expedition leaders there cheering us on as we went by,” he said. β€œWe got to see a bunch of penguins, and after the race I went to the Southern Ocean and iced my feet.” Chasing the clock right down to the last few minutes, Park is the first Canadian to complete the feat for an official public marathon, finishing the race in six days, 23 hours and 42 minutes. After seven days of planes, sleeping in tents and marathoning in just about every climate imaginable, Park said it was a relief to be back home with his family and resting in snowy Calgary. β€œMy ankles are a bit swollen, but overall, I’m not in too bad of shape,” he said. β€œIt was an amazing experience, and it’s great to be home.” As part of his run, Park set up a donation page for the Alberta Cancer Foundation, raising more than $5,500 so far. For more information or to donate, please visit: albertacancer.ca/page.aspx?pid=747&tab=0&frsid=20980 [email protected]
The Promethean biohacker: on consumer biohacking as a labour of love ABSTRACT Just as the mythical Greek Titan Prometheus created humans and brought them the technology of fire, the biohackers studied here seek to recreate humanity and bring us technologies that make us god-like. In this paper, we explore how and why biohackers have been integrating technologies into their bodies. Drawing on Transhumanism, biohacking, and consumer sentiments literature, we depict three avatars of Promethean biohackers. While distinct from one another, their biohackings are tied by a single sentiment: that of love. Here, love is what energises biohackers’ actions on their Promethean journey to become transhumans. This study challenges prior discussions on human-technology relationships framed in largely instrumental terms. Our research also highlights the importance for scholars and practitioners to address ethical issues around eugenics and human commodification.
WASHINGTON (AP/The Huffington Post) -- Massachusetts Sen. Scott Brown blamed his staff Thursday for passages about his upbringing on his official Senate website that were lifted word for word from a 2002 speech by former senator and presidential candidate Elizabeth Dole. β€œIt was a summer intern that put together the site, we corrected it once we found out," he told the Boston Globe. His office had β€œvery little time and resources to put things up" at the time of the site's launch, he said. "They did it, we were notified of it, we fixed it -- end of story,” Brown told the Globe. The Democratic group American Bridge, which discovered the matching words, accused the Massachusetts Republican of plagiarism. "This is just further proof that Scott Brown is not who the people of Massachusetts think he is," Rodell Mollineau, president of American Bridge, said in a written statement. "The fact that he has plagiarized a personal values statement in a message to students really raises questions about just how genuine Scott Brown is." Brown's spokesman, John Donnelly, said excerpts of the speech were on Dole's website, which aides used as a template for his, and that the passages were transferred inadvertently without being rewritten. Donnelly denied any plagiarism, saying it was an innocent mistake by staffers. "Senator Dole's website served as one of the models for Senator Brown's website when he first took office ... It was a staff level oversight which we regret and has been corrected," Donnelly said in a statement. The passages were about the values that parents instill in their children. "I was raised to believe that there are no limits to individual achievement and no excuses to justify indifference," was the message on Brown's website that has since been removed. "From an early age, I was taught that success is measured not in material accumulations, but in service to others. I was encouraged to join causes larger than myself, to pursue positive change through a sense of mission, and to stand up for what I believe." Passages from Dole's speech were included in a message to students on her website. "I am Mary and John Hanford's daughter, raised to believe that there are no limits to individual achievement and no excuses to justify indifference," was the message on Dole's website. "From an early age, I was taught that success is measured, not in material accumulations, but in service to others. I was encouraged to join causes larger than myself, to pursue positive change through a sense of mission, and to stand up for what I believe." In his biography, "Against All Odds: A Life From Hardship to Hope," Brown described a difficult childhood, including moving 17 times by the time he turned age 18, an absent father and sexual abuse by a camp counselor and a beating by a stepfather. "I look back on my life now, though, and I can honestly say that there isn't one thing I would change: not the arrest, not the violence, not the hunger, not the beatings and brute struggles," Brown wrote, adding that such experiences made him what he is today. Brian Nick, a spokesman for the former North Carolina senator, said Dole viewed the episode as "an innocent mistake" by staff. Nick said that a lot of Senate offices use generic language from time to time. Brown, a Republican, is running for re-election in 2012 for the seat long held by the late Democratic Sen. Edward Kennedy.
Marine Who Survived Beirut Bombing Sends Powerful Letter On Behalf of Sgt. Derrick Miller Marine Who Survived Beirut Bombing Sends Powerful Letter On Behalf of Sgt. Derrick Miller In prior posts we have brought you the infuriating details about the injustice facing our American son, Sgt. Derrick Miller. Sgt. Miller sits in Leavenworth Prison with a life sentence for premeditated murder for killing an Afghan he had stopped previously for surveilling his base in a hostile zone. These actions saved the lives of Derrick’s brothers. Back in September, when supporters stood on the Capitol steps asking for help from congress for relief in Derrick’s sentence, they were joined by Retired LCpl Dave Madaras. Madaras wrote a letter to Congressman Delaney of Maryland on Derrick’s behalf (see below). Madaras’ letter is exceptionally powerful and poignant because he is a survivor of the October 23, 1983 bombing of the Marine barracks in Beirut which killed 241 and wounded 100 more of our brave men. Madaras’s letter makes the powerful point that Derrick saved the lives of his mean that day. On September 26, 2010, when the incident occurred on Derrick’s base, the base immediately went on 100% security and all our soldiers were moved from their positions. An hour later the base was attacked. We did not lose one precious American son that day because of these changes in positions. Derrick’s instincts in recognizing Atta Mohammed from the prior day (when Derrick stopped Mohammed who was driving a truck with a 50 gallon empty drum, guns, change of clothes and laptops) saved the lives of his brothers. Madaras shared with Congressman Delaney, β€œI know I am not the only one who if time was turned back would willingly sacrifice my life and do whatever it took to stop that truck!” Derrick did stop a truck, in the form of Atta Mohammed, to protect his men and instead of being held as a hero, he is languishing in prison for life. As Madaras wisely states in his letter to Delaney, β€œI am writing to bring your attention to an Army Veteran who is serving time in Ft. Leavenworth for, β€œmurder,” when he should be decorated for valor.” Please take the time to read this letter and contact your congressman and senator TODAY to ask for their help in having Sgt. Miller’s sentence reduced and allow him to return home to his two little girls. President-Elect Trump β€” Please Free this American Patriot! Derrick Miller Congressional Letter by Jim Hoft on Scribd
// Code generated by go-swagger; DO NOT EDIT. package associations // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "io" "github.com/go-openapi/runtime" "github.com/go-openapi/strfmt" "github.com/form3tech-oss/terraform-provider-form3/models" ) // GetLhvAssociationIDMasterAccountsMasterAccountIDReader is a Reader for the GetLhvAssociationIDMasterAccountsMasterAccountID structure. type GetLhvAssociationIDMasterAccountsMasterAccountIDReader struct { formats strfmt.Registry } // ReadResponse reads a server response into the received o. func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { switch response.Code() { case 200: result := NewGetLhvAssociationIDMasterAccountsMasterAccountIDOK() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return result, nil case 400: result := NewGetLhvAssociationIDMasterAccountsMasterAccountIDBadRequest() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 401: result := NewGetLhvAssociationIDMasterAccountsMasterAccountIDUnauthorized() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 403: result := NewGetLhvAssociationIDMasterAccountsMasterAccountIDForbidden() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 404: result := NewGetLhvAssociationIDMasterAccountsMasterAccountIDNotFound() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 409: result := NewGetLhvAssociationIDMasterAccountsMasterAccountIDConflict() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 429: result := NewGetLhvAssociationIDMasterAccountsMasterAccountIDTooManyRequests() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 500: result := NewGetLhvAssociationIDMasterAccountsMasterAccountIDInternalServerError() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result case 503: result := NewGetLhvAssociationIDMasterAccountsMasterAccountIDServiceUnavailable() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result default: return nil, runtime.NewAPIError("unknown error", response, response.Code()) } } // NewGetLhvAssociationIDMasterAccountsMasterAccountIDOK creates a GetLhvAssociationIDMasterAccountsMasterAccountIDOK with default headers values func NewGetLhvAssociationIDMasterAccountsMasterAccountIDOK() *GetLhvAssociationIDMasterAccountsMasterAccountIDOK { return &GetLhvAssociationIDMasterAccountsMasterAccountIDOK{} } /*GetLhvAssociationIDMasterAccountsMasterAccountIDOK handles this case with default header values. Master Account details */ type GetLhvAssociationIDMasterAccountsMasterAccountIDOK struct { Payload *models.LhvMasterAccountResponse } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDOK) Error() string { return fmt.Sprintf("[GET /lhv/{associationId}/master_accounts/{masterAccountId}][%d] getLhvAssociationIdMasterAccountsMasterAccountIdOK %+v", 200, o.Payload) } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDOK) GetPayload() *models.LhvMasterAccountResponse { return o.Payload } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.LhvMasterAccountResponse) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvAssociationIDMasterAccountsMasterAccountIDBadRequest creates a GetLhvAssociationIDMasterAccountsMasterAccountIDBadRequest with default headers values func NewGetLhvAssociationIDMasterAccountsMasterAccountIDBadRequest() *GetLhvAssociationIDMasterAccountsMasterAccountIDBadRequest { return &GetLhvAssociationIDMasterAccountsMasterAccountIDBadRequest{} } /*GetLhvAssociationIDMasterAccountsMasterAccountIDBadRequest handles this case with default header values. Bad Request */ type GetLhvAssociationIDMasterAccountsMasterAccountIDBadRequest struct { Payload *models.APIError } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDBadRequest) Error() string { return fmt.Sprintf("[GET /lhv/{associationId}/master_accounts/{masterAccountId}][%d] getLhvAssociationIdMasterAccountsMasterAccountIdBadRequest %+v", 400, o.Payload) } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDBadRequest) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvAssociationIDMasterAccountsMasterAccountIDUnauthorized creates a GetLhvAssociationIDMasterAccountsMasterAccountIDUnauthorized with default headers values func NewGetLhvAssociationIDMasterAccountsMasterAccountIDUnauthorized() *GetLhvAssociationIDMasterAccountsMasterAccountIDUnauthorized { return &GetLhvAssociationIDMasterAccountsMasterAccountIDUnauthorized{} } /*GetLhvAssociationIDMasterAccountsMasterAccountIDUnauthorized handles this case with default header values. Authentication credentials were missing or incorrect */ type GetLhvAssociationIDMasterAccountsMasterAccountIDUnauthorized struct { Payload *models.APIError } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDUnauthorized) Error() string { return fmt.Sprintf("[GET /lhv/{associationId}/master_accounts/{masterAccountId}][%d] getLhvAssociationIdMasterAccountsMasterAccountIdUnauthorized %+v", 401, o.Payload) } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDUnauthorized) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvAssociationIDMasterAccountsMasterAccountIDForbidden creates a GetLhvAssociationIDMasterAccountsMasterAccountIDForbidden with default headers values func NewGetLhvAssociationIDMasterAccountsMasterAccountIDForbidden() *GetLhvAssociationIDMasterAccountsMasterAccountIDForbidden { return &GetLhvAssociationIDMasterAccountsMasterAccountIDForbidden{} } /*GetLhvAssociationIDMasterAccountsMasterAccountIDForbidden handles this case with default header values. Forbidden */ type GetLhvAssociationIDMasterAccountsMasterAccountIDForbidden struct { Payload *models.APIError } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDForbidden) Error() string { return fmt.Sprintf("[GET /lhv/{associationId}/master_accounts/{masterAccountId}][%d] getLhvAssociationIdMasterAccountsMasterAccountIdForbidden %+v", 403, o.Payload) } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDForbidden) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDForbidden) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvAssociationIDMasterAccountsMasterAccountIDNotFound creates a GetLhvAssociationIDMasterAccountsMasterAccountIDNotFound with default headers values func NewGetLhvAssociationIDMasterAccountsMasterAccountIDNotFound() *GetLhvAssociationIDMasterAccountsMasterAccountIDNotFound { return &GetLhvAssociationIDMasterAccountsMasterAccountIDNotFound{} } /*GetLhvAssociationIDMasterAccountsMasterAccountIDNotFound handles this case with default header values. Record not found */ type GetLhvAssociationIDMasterAccountsMasterAccountIDNotFound struct { Payload *models.APIError } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDNotFound) Error() string { return fmt.Sprintf("[GET /lhv/{associationId}/master_accounts/{masterAccountId}][%d] getLhvAssociationIdMasterAccountsMasterAccountIdNotFound %+v", 404, o.Payload) } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDNotFound) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvAssociationIDMasterAccountsMasterAccountIDConflict creates a GetLhvAssociationIDMasterAccountsMasterAccountIDConflict with default headers values func NewGetLhvAssociationIDMasterAccountsMasterAccountIDConflict() *GetLhvAssociationIDMasterAccountsMasterAccountIDConflict { return &GetLhvAssociationIDMasterAccountsMasterAccountIDConflict{} } /*GetLhvAssociationIDMasterAccountsMasterAccountIDConflict handles this case with default header values. Conflict */ type GetLhvAssociationIDMasterAccountsMasterAccountIDConflict struct { Payload *models.APIError } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDConflict) Error() string { return fmt.Sprintf("[GET /lhv/{associationId}/master_accounts/{masterAccountId}][%d] getLhvAssociationIdMasterAccountsMasterAccountIdConflict %+v", 409, o.Payload) } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDConflict) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDConflict) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvAssociationIDMasterAccountsMasterAccountIDTooManyRequests creates a GetLhvAssociationIDMasterAccountsMasterAccountIDTooManyRequests with default headers values func NewGetLhvAssociationIDMasterAccountsMasterAccountIDTooManyRequests() *GetLhvAssociationIDMasterAccountsMasterAccountIDTooManyRequests { return &GetLhvAssociationIDMasterAccountsMasterAccountIDTooManyRequests{} } /*GetLhvAssociationIDMasterAccountsMasterAccountIDTooManyRequests handles this case with default header values. The request cannot be served due to the application’s rate limit */ type GetLhvAssociationIDMasterAccountsMasterAccountIDTooManyRequests struct { Payload *models.APIError } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDTooManyRequests) Error() string { return fmt.Sprintf("[GET /lhv/{associationId}/master_accounts/{masterAccountId}][%d] getLhvAssociationIdMasterAccountsMasterAccountIdTooManyRequests %+v", 429, o.Payload) } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDTooManyRequests) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDTooManyRequests) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvAssociationIDMasterAccountsMasterAccountIDInternalServerError creates a GetLhvAssociationIDMasterAccountsMasterAccountIDInternalServerError with default headers values func NewGetLhvAssociationIDMasterAccountsMasterAccountIDInternalServerError() *GetLhvAssociationIDMasterAccountsMasterAccountIDInternalServerError { return &GetLhvAssociationIDMasterAccountsMasterAccountIDInternalServerError{} } /*GetLhvAssociationIDMasterAccountsMasterAccountIDInternalServerError handles this case with default header values. Internal Server Error */ type GetLhvAssociationIDMasterAccountsMasterAccountIDInternalServerError struct { Payload *models.APIError } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDInternalServerError) Error() string { return fmt.Sprintf("[GET /lhv/{associationId}/master_accounts/{masterAccountId}][%d] getLhvAssociationIdMasterAccountsMasterAccountIdInternalServerError %+v", 500, o.Payload) } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDInternalServerError) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil } // NewGetLhvAssociationIDMasterAccountsMasterAccountIDServiceUnavailable creates a GetLhvAssociationIDMasterAccountsMasterAccountIDServiceUnavailable with default headers values func NewGetLhvAssociationIDMasterAccountsMasterAccountIDServiceUnavailable() *GetLhvAssociationIDMasterAccountsMasterAccountIDServiceUnavailable { return &GetLhvAssociationIDMasterAccountsMasterAccountIDServiceUnavailable{} } /*GetLhvAssociationIDMasterAccountsMasterAccountIDServiceUnavailable handles this case with default header values. The server is up, but overloaded with requests. Try again later. */ type GetLhvAssociationIDMasterAccountsMasterAccountIDServiceUnavailable struct { Payload *models.APIError } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDServiceUnavailable) Error() string { return fmt.Sprintf("[GET /lhv/{associationId}/master_accounts/{masterAccountId}][%d] getLhvAssociationIdMasterAccountsMasterAccountIdServiceUnavailable %+v", 503, o.Payload) } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDServiceUnavailable) GetPayload() *models.APIError { return o.Payload } func (o *GetLhvAssociationIDMasterAccountsMasterAccountIDServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { o.Payload = new(models.APIError) // response payload if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF { return err } return nil }
/** * Called from the block tracker to filter the detected signs based on the skip settings. * The signs specified should contain all signs known to the minecart for proper functioning. * * @param signs (modifiable!) */ public void filterSigns(List<TrackedSign> signs) { if (!this.isLoaded) { this.loadSigns(signs); } IProperties properties = this.owner.getProperties(); final SignSkipOptions options = properties.get(StandardProperties.SIGN_SKIP); if (!options.isActive() && !this.hasSkippedSigns) { this.history.clear(); for (TrackedSign sign : signs) { this.history.put(sign, Boolean.FALSE); } return; } final SkipOptionChanges changes = new SkipOptionChanges(options); { Iterator<Map.Entry<TrackedSign, Boolean>> iter = history.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<TrackedSign, Boolean> e = iter.next(); if (!signs.contains(e.getKey())) { changes.skippedSignsChanged |= e.getValue().booleanValue(); iter.remove(); } } } this.hasSkippedSigns = false; Iterator<TrackedSign> iter = signs.iterator(); while (iter.hasNext()) { Boolean historyState = this.history.computeIfAbsent(iter.next(), sign -> { boolean passFilter = true; if (options.hasFilter()) { if (sign.sign == null) { passFilter = false; } else { passFilter = Util.getCleanLine(sign.sign, 1).toLowerCase(Locale.ENGLISH).startsWith(options.filter()); } } return passFilter ? changes.handleSkip() : Boolean.FALSE; }); if (historyState.booleanValue()) { this.hasSkippedSigns = true; iter.remove(); } } if (changes.skippedSignsChanged) { if (this.hasSkippedSigns) { Set<BlockLocation> skippedSigns = this.history.entrySet().stream() .filter(e -> e.getValue().booleanValue()) .map(e -> new BlockLocation(e.getKey().signBlock)) .collect(Collectors.toCollection(LinkedHashSet::new)); properties.set(StandardProperties.SIGN_SKIP, SignSkipOptions.create( changes.ignoreCounter, changes.skipCounter, options.filter(), Collections.unmodifiableSet(skippedSigns) )); } else { properties.set(StandardProperties.SIGN_SKIP, SignSkipOptions.create( changes.ignoreCounter, changes.skipCounter, options.filter(), Collections.emptySet() )); } } else if (changes.countersChanged) { properties.set(StandardProperties.SIGN_SKIP, SignSkipOptions.create( changes.ignoreCounter, changes.skipCounter, options.filter(), options.skippedSigns() )); } }
Deep beneath Las Vegas’ famous strip of glittering lights lies a sinister labyrinth of underground flood tunnels. The 200+ miles of flood tunnels are home to a secret community of over 1,000 homeless people who eke out a living in the strip’s dark underbelly. They’ve turned this way of living into their way of life, and they don’t feel like it’s necessary to change, when they aren’t necessarily hurting anyone by living underneath the Las Vegas Strip. Check out these photos of the interior of the Las Vegas tunnels. Despite the risks from disease, highly venomous spiders, and flooding washing them away, many of the tunnel people have put together elaborate camps with furniture, ornaments, and shelves filled with belongings. Some residents like Steven and his girlfriend Kathryn, have furnished their home with considerable care. Their 400sq ft β€˜house’ boasts a double bed, a wardrobe, and even a bookshelf. Tunnel residents have created wardrobes for their clothes and salvaged furniture to make the subterranean world more homely. Most of the people who are living here are ones who have lost their job, war veterans suffering from post-traumatic stress, drug addicts, and even criminals. They earn their money off the wildly excessive city above by begging and β€œdumpster diving”, raiding bins and skips. Some still have decent jobs in hotels and such. Here is one of the exits from the tunnels. Looking in you would not necessarily know that there were people living down here. One resident poses with her possessions. Sometimes people have to do what they have to do, and this is definitely one of those cases. Next time you see an entrance to an underground tunnel, you may be thinking twice about what is down there. It’s hard to believe something like this exists in one of the biggest cities in the world. Who would have thought that there are people actually living in these Las Vegas tunnels. It’s sad that we live in a world where this goes unnoticed. The homeless population is growing each year and it’s up to us to come up with a permanent solution so that they are not forced to sleep in the underground tunnels of our cities. Share These Underground Las Vegas Residents With Your Friends Below.
def lookup_eigentumsform(self, eigentumsform): return self.EIGENTUMSFORM_LOOKUP.get(eigentumsform, eigentumsform)
Optimal Design of Passive Permanent Magnet Bearings In this paper, for optimal using of magnetic materials in passive magnetic bearings, two modifications in passive magnetic bearing structure are investigated. These modifications include using arbitrary size PMs and air intervals between them. Two configurations of opposite magnetization structure (standard) and rotating magnetization structure (Halbach) are studied in this paper. The 2D planner model is used to calculate the magnetic fields and stiffness between two infinite rods of magnet. A straight formula for stiffness is achieved for both standard and Halbach stacking. The optimization will be performed in order to obtain maximum stiffness per magnet volume ratio.
def serialize_spec(spec: List[Union[Optional, Required]]) -> str: return "\n\n".join( [ "# Config options for unicorefuzz\n" "# Values tagged as [Optional] are autofilled by ucf if not set explicitly." ] + [stringify_spec_entry(x) for x in spec] )
/** * @author mattmann * @version $Revision$ * * <p> * A {@link WorkflowTaskConfiguration} that preserves whether or not a task config * property was envReplace'd or not. * </p>. */ public class EnvSavingConfiguration extends WorkflowTaskConfiguration { private Properties envReplaceMap; public EnvSavingConfiguration() { super(); envReplaceMap = new Properties(); } /* * (non-Javadoc) * * @see gov.nasa.jpl.oodt.cas.workflow.structs.WorkflowTaskConfiguration#addConfigProperty(java.lang.String, * java.lang.String) */ public void addConfigProperty(String propName, String propVal) { addConfigProperty(propName, propVal, false); } /** * Adds a configuration property, along with its envReplace * information. * * @param propName The workflow config property name. * @param propVal The workflow config property val. * @param isReplace Whether or not the property should be envReplaced. */ public void addConfigProperty(String propName, String propVal, boolean isReplace) { super.addConfigProperty(propName, propVal); envReplaceMap.put(propName, String.valueOf(isReplace)); } public boolean isReplace(String propName) { return Boolean.valueOf((String) this.envReplaceMap.get(propName)) .booleanValue(); } }
/* * Callback invoked immediately prior to starting a debugnet connection. */ void debugnet_mbuf_start(void) { MPASS(!dn_saved_zones.dsz_debugnet_zones_enabled); dn_saved_zones = (struct debugnet_saved_zones) { .dsz_debugnet_zones_enabled = true, .dsz_mbuf = zone_mbuf, .dsz_clust = zone_clust, .dsz_pack = zone_pack, .dsz_jumbop = zone_jumbop, .dsz_jumbo9 = zone_jumbo9, .dsz_jumbo16 = zone_jumbo16, }; printf("debugnet: overwriting mbuf zone pointers\n"); zone_mbuf = dn_zone_mbuf; zone_clust = dn_zone_clust; zone_pack = dn_zone_pack; zone_jumbop = dn_zone_clust; zone_jumbo9 = dn_zone_clust; zone_jumbo16 = dn_zone_clust; }
// NewVertex returns a new vertex which is ready to use. func (g *Graph) NewVertex() Vertex { newVertex := &vertex{VertexID: g.generateID()} newVertex.container = Vertex{ vertex: newVertex, Value: new(interface{}), } g.vertices[newVertex.VertexID] = newVertex return newVertex.container }
<gh_stars>10-100 /** * Copyright 2020 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const enum Button { Left, } class Pointer { /** x offset from the top of the document */ pageX: number; /** y offset from the top of the document */ pageY: number; /** x offset from the top of the viewport */ clientX: number; /** y offset from the top of the viewport */ clientY: number; /** Unique ID for this pointer */ id: number = -1; /** The platform object used to create this Pointer */ nativePointer: Touch | PointerEvent | MouseEvent; constructor(nativePointer: Touch | PointerEvent | MouseEvent) { this.nativePointer = nativePointer; this.pageX = nativePointer.pageX; this.pageY = nativePointer.pageY; this.clientX = nativePointer.clientX; this.clientY = nativePointer.clientY; if (self.Touch && nativePointer instanceof Touch) { this.id = nativePointer.identifier; } else if (isPointerEvent(nativePointer)) { // is PointerEvent this.id = nativePointer.pointerId; } } /** * Returns an expanded set of Pointers for high-resolution inputs. */ getCoalesced(): Pointer[] { if ('getCoalescedEvents' in this.nativePointer) { return (this.nativePointer as any).getCoalescedEvents().map((p) => new Pointer(p)); } return [this]; } } // Export the typing, but keep the class private. type PointerType = Pointer; export { PointerType as Pointer }; const isPointerEvent = (event: any): event is PointerEvent => self.PointerEvent && event instanceof PointerEvent; const noop = () => {}; export type InputEvent = TouchEvent | PointerEvent | MouseEvent; type StartCallback = (pointer: Pointer, event: InputEvent) => boolean; type MoveCallback = ( previousPointers: Pointer[], changedPointers: Pointer[], event: InputEvent, ) => void; type EndCallback = ( pointer: Pointer, event: InputEvent, cancelled: boolean, ) => void; interface PointerTrackerOptions { /** * Called when a pointer is pressed/touched within the element. * * @param pointer The new pointer. This pointer isn't included in this.currentPointers or * this.startPointers yet. * @param event The event related to this pointer. * * @returns Whether you want to track this pointer as it moves. */ start?: StartCallback; /** * Called when pointers have moved. * * @param previousPointers The state of the pointers before this event. This contains the same * number of pointers, in the same order, as this.currentPointers and this.startPointers. * @param changedPointers The pointers that have changed since the last move callback. * @param event The event related to the pointer changes. */ move?: MoveCallback; /** * Called when a pointer is released. * * @param pointer The final state of the pointer that ended. This pointer is now absent from * this.currentPointers and this.startPointers. * @param event The event related to this pointer. * @param cancelled Was the action cancelled? Actions are cancelled when the OS takes over pointer * events, for actions such as scrolling. */ end?: EndCallback; /** * Use raw pointer updates? Pointer events are usually synchronised to requestAnimationFrame. * However, if you're targeting a desynchronised canvas, then faster 'raw' updates are better. */ rawUpdates?: boolean; } /** * Track pointers across a particular element */ export default class PointerTracker { /** * State of the tracked pointers when they were pressed/touched. */ readonly startPointers: Pointer[] = []; /** * Latest state of the tracked pointers. Contains the same number of pointers, and in the same * order as this.startPointers. */ readonly currentPointers: Pointer[] = []; private _startCallback: StartCallback; private _moveCallback: MoveCallback; private _endCallback: EndCallback; private _rawUpdates: boolean; /** * Track pointers across a particular element * * @param element Element to monitor. * @param options */ constructor( private _element: HTMLElement, { start = () => true, move = noop, end = noop, rawUpdates = false, }: PointerTrackerOptions = {}, ) { this._startCallback = start; this._moveCallback = move; this._endCallback = end; this._rawUpdates = rawUpdates && 'onpointerrawupdate' in window; // Add listeners if (self.PointerEvent) { this._element.addEventListener('pointerdown', this._pointerStart); } else { this._element.addEventListener('mousedown', this._pointerStart); this._element.addEventListener('touchstart', this._touchStart); this._element.addEventListener('touchmove', this._move); this._element.addEventListener('touchend', this._touchEnd); this._element.addEventListener('touchcancel', this._touchEnd); } } /** * Remove all listeners. */ stop() { this._element.removeEventListener('pointerdown', this._pointerStart); this._element.removeEventListener('mousedown', this._pointerStart); this._element.removeEventListener('touchstart', this._touchStart); this._element.removeEventListener('touchmove', this._move); this._element.removeEventListener('touchend', this._touchEnd); this._element.removeEventListener('touchcancel', this._touchEnd); this._element.removeEventListener( this._rawUpdates ? 'pointerrawupdate' : 'pointermove', this._move, ); this._element.removeEventListener('pointerup', this._pointerEnd); this._element.removeEventListener('pointercancel', this._pointerEnd); window.removeEventListener('mousemove', this._move); window.removeEventListener('mouseup', this._pointerEnd); } /** * Call the start callback for this pointer, and track it if the user wants. * * @param pointer Pointer * @param event Related event * @returns Whether the pointer is being tracked. */ private _triggerPointerStart(pointer: Pointer, event: InputEvent): boolean { if (!this._startCallback(pointer, event)) return false; this.currentPointers.push(pointer); this.startPointers.push(pointer); return true; } /** * Listener for mouse/pointer starts. * * @param event This will only be a MouseEvent if the browser doesn't support pointer events. */ private _pointerStart = (event: PointerEvent | MouseEvent) => { // if (event.button !== Button.Left) return; if (!this._triggerPointerStart(new Pointer(event), event)) return; // Add listeners for additional events. // The listeners may already exist, but no harm in adding them again. if (isPointerEvent(event)) { const capturingElement = event.target && 'setPointerCapture' in event.target ? event.target : this._element; capturingElement.setPointerCapture(event.pointerId); this._element.addEventListener( this._rawUpdates ? 'pointerrawupdate' : 'pointermove', this._move, ); this._element.addEventListener('pointerup', this._pointerEnd); this._element.addEventListener('pointercancel', this._pointerEnd); } else { // MouseEvent window.addEventListener('mousemove', this._move); window.addEventListener('mouseup', this._pointerEnd); } }; /** * Listener for touchstart. * Only used if the browser doesn't support pointer events. */ private _touchStart = (event: TouchEvent) => { for (const touch of Array.from(event.changedTouches)) { this._triggerPointerStart(new Pointer(touch), event); } }; /** * Listener for pointer/mouse/touch move events. */ private _move = (event: PointerEvent | MouseEvent | TouchEvent) => { const previousPointers = this.currentPointers.slice(); const changedPointers = 'changedTouches' in event // Shortcut for 'is touch event'. ? Array.from(event.changedTouches).map((t) => new Pointer(t)) : [new Pointer(event)]; const trackedChangedPointers = []; for (const pointer of changedPointers) { const index = this.currentPointers.findIndex((p) => p.id === pointer.id); if (index === -1) continue; // Not a pointer we're tracking trackedChangedPointers.push(pointer); this.currentPointers[index] = pointer; } if (trackedChangedPointers.length === 0) return; this._moveCallback(previousPointers, trackedChangedPointers, event); }; /** * Call the end callback for this pointer. * * @param pointer Pointer * @param event Related event */ private _triggerPointerEnd = ( pointer: Pointer, event: InputEvent, ): boolean => { const index = this.currentPointers.findIndex((p) => p.id === pointer.id); // Not a pointer we're interested in? if (index === -1) return false; this.currentPointers.splice(index, 1); this.startPointers.splice(index, 1); const cancelled = event.type === 'touchcancel' || event.type === 'pointercancel'; this._endCallback(pointer, event, cancelled); return true; }; /** * Listener for mouse/pointer ends. * * @param event This will only be a MouseEvent if the browser doesn't support pointer events. */ private _pointerEnd = (event: PointerEvent | MouseEvent) => { if (!this._triggerPointerEnd(new Pointer(event), event)) return; if (isPointerEvent(event)) { if (this.currentPointers.length) return; this._element.removeEventListener( this._rawUpdates ? 'pointerrawupdate' : 'pointermove', this._move, ); this._element.removeEventListener('pointerup', this._pointerEnd); this._element.removeEventListener('pointercancel', this._pointerEnd); } else { // MouseEvent window.removeEventListener('mousemove', this._move); window.removeEventListener('mouseup', this._pointerEnd); } }; /** * Listener for touchend. * Only used if the browser doesn't support pointer events. */ private _touchEnd = (event: TouchEvent) => { for (const touch of Array.from(event.changedTouches)) { this._triggerPointerEnd(new Pointer(touch), event); } }; }
import { useEffect } from 'react'; import { BrowserQRCodeReader } from '@zxing/library'; import { getDeviceId } from './utils'; import { UseQrReaderHook, CodeReaderError } from '../types'; // TODO: implement dependencies in a way that video stream doesn't flashback export const useQrReader: UseQrReaderHook = ({ facingMode, scanDelay, onResult, videoId, }) => { useEffect(() => { const codeReader = new BrowserQRCodeReader(scanDelay); if (!codeReader.isMediaDevicesSuported) { if (typeof onResult === 'function') { onResult(null, 'NoMediaDevicesSupportException'); } } codeReader .listVideoInputDevices() .then((videoInputDevices) => getDeviceId(videoInputDevices, facingMode)) .then((deviceId) => codeReader.decodeFromVideoDevice(deviceId, videoId, (result, error) => { const exception = (error && (error.name as CodeReaderError)) || null; if (typeof onResult === 'function') { onResult(result, exception, codeReader); } }) ) .catch(() => { if (typeof onResult === 'function') { onResult(null, 'NoDeviceFoundException', codeReader); } }); return () => { codeReader.stopContinuousDecode(); codeReader.stopAsyncDecode(); }; }, []); };
<gh_stars>1-10 import * as fs from 'fs'; import ContentSearch from '../models/content-search.interface'; const contentFilePath = './content.json'; function save(content: ContentSearch) { const contentString = JSON.stringify(content); return fs.writeFileSync(contentFilePath, contentString); } function load(): ContentSearch { const fileBuffer = fs.readFileSync(contentFilePath, 'utf-8'); const contentJson = JSON.parse(fileBuffer); return contentJson; } export default { save, load }
A CRISPR-based approach for proteomic analysis of a single genomic locus Any given chromosomal activity (e.g., transcription) is governed predominantly by the local epiproteome. However, defining local epiproteomes has been limited by a lack of effective technologies to isolate discrete sections of chromatin and to identify with precision specific proteins and histone posttranslational modifications (PTMs). We report the use of the Cas9 and guide RNA (gRNA) components of the CRISPR system for gRNA-directed purification of a discrete section of chromatin. Quantitative mass spectrometry provides for unambiguous identification of proteins and histone PTMs specifically associated with the enriched chromatin. This CRISPR-based Chromatin Affinity Purification with Mass Spectrometry (CRISPR-ChAP-MS) approach revealed changes in the local epiproteome of a promoter during activation of transcription. CRISPR-ChAP-MS thus has broad applications for discovering molecular components and dynamic regulation of any in vivo activity at a given chromosomal location.
package com.cloudbees.jenkins.plugins.advisor.casc; import com.cloudbees.jenkins.plugins.advisor.AdvisorGlobalConfiguration; import com.cloudbees.jenkins.plugins.advisor.client.model.Recipient; import io.jenkins.plugins.casc.ConfigurationContext; import io.jenkins.plugins.casc.ConfiguratorException; import io.jenkins.plugins.casc.ConfiguratorRegistry; import io.jenkins.plugins.casc.model.CNode; import io.jenkins.plugins.casc.model.Mapping; import io.jenkins.plugins.casc.model.Scalar; import io.jenkins.plugins.casc.model.Sequence; import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.jvnet.hudson.test.JenkinsRule; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.cloudbees.jenkins.plugins.advisor.casc.AdvisorRootConfigurator.ACCEPT_TOS_ATTR; import static com.cloudbees.jenkins.plugins.advisor.casc.AdvisorRootConfigurator.CCS_ATTR; import static com.cloudbees.jenkins.plugins.advisor.casc.AdvisorRootConfigurator.EMAIL_ATTR; import static com.cloudbees.jenkins.plugins.advisor.casc.AdvisorRootConfigurator.EXCLUDED_COMPONENTS_ATTR; import static com.cloudbees.jenkins.plugins.advisor.casc.AdvisorRootConfigurator.NAG_DISABLED_ATTR; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; import static org.hamcrest.Matchers.contains; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class AdvisorRootConfiguratorTest { private final static String FAKE_EMAIL = "<EMAIL>"; private final static List<Recipient> FAKE_CC = Arrays.asList(new Recipient("<EMAIL>"), new Recipient("<EMAIL>")); private final static Set<String> EXCLUDED = new HashSet<>(Arrays.asList("ThreadDumps", "PipelineThreadDump")); private final static Boolean ACCEPT_TOS = Boolean.TRUE; private final static Boolean NAG_DISABLED = Boolean.TRUE; @ClassRule public static JenkinsRule rule = new JenkinsRule(); @Rule public final ExpectedException thrown = ExpectedException.none(); private AdvisorRootConfigurator configurator; private AdvisorGlobalConfiguration configuration; private Mapping mapping; private ConfigurationContext context; @Before public void setUpConfigurator() { context = new ConfigurationContext(ConfiguratorRegistry.get()); configurator = new AdvisorRootConfigurator(); configuration = new AdvisorGlobalConfiguration(FAKE_EMAIL, FAKE_CC, EXCLUDED); configuration.setAcceptToS(ACCEPT_TOS); configuration.setNagDisabled(NAG_DISABLED); mapping = new Mapping(); mapping.put(ACCEPT_TOS_ATTR, ACCEPT_TOS); Sequence ccs = new Sequence(); ccs.add(new Scalar("<EMAIL>")); ccs.add(new Scalar("<EMAIL>")); mapping.put(CCS_ATTR, ccs); mapping.put(EMAIL_ATTR, FAKE_EMAIL); Sequence excluded = new Sequence(); excluded.add(new Scalar("ThreadDumps")); excluded.add(new Scalar("PipelineThreadDump")); mapping.put(EXCLUDED_COMPONENTS_ATTR, excluded); mapping.put(NAG_DISABLED_ATTR, NAG_DISABLED); } @Test public void testGetName() { assertEquals("advisor", configurator.getName()); } @Test public void testGetTarget() { assertEquals("Wrong target class", configurator.getTarget(), AdvisorGlobalConfiguration.class); } @Test public void testCanConfigure() { assertTrue("Can't configure AdvisorGlobalConfiguration", configurator.canConfigure(AdvisorGlobalConfiguration.class)); assertFalse("Can configure AdvisorRootConfigurator", configurator.canConfigure(AdvisorRootConfigurator.class)); } @Test public void testGetImplementedAPI() { assertEquals("Wrong implemented API", configurator.getImplementedAPI(), AdvisorGlobalConfiguration.class); } @Test public void testGetConfigurators() { assertThat(configurator.getConfigurators(context), contains(configurator)); } @Test public void testDescribe() throws Exception { Mapping described = configurator.describe(configuration, context).asMapping(); assertNotNull(described); assertEquals(mapping.getScalarValue(EMAIL_ATTR), described.getScalarValue(EMAIL_ATTR)); List<String> ccMapping = toListValues(mapping.get(CCS_ATTR).asSequence()); List<String> ccDescribed = toListValues(described.get(CCS_ATTR).asSequence()); assertEquals(ccMapping.size(), ccDescribed.size()); assertThat(ccDescribed.toArray(), arrayContainingInAnyOrder(ccMapping.toArray())); assertEquals(mapping.getScalarValue(ACCEPT_TOS_ATTR), described.getScalarValue(ACCEPT_TOS_ATTR)); assertEquals(mapping.getScalarValue(NAG_DISABLED_ATTR), described.getScalarValue(NAG_DISABLED_ATTR)); Set<String> excludedComponentsMapping = toScalarValues(mapping.get(EXCLUDED_COMPONENTS_ATTR).asSequence()); Set<String> excludedComponentsDescribed = toScalarValues(described.get(EXCLUDED_COMPONENTS_ATTR).asSequence()); assertEquals(excludedComponentsMapping.size(), excludedComponentsDescribed.size()); assertThat(excludedComponentsDescribed.toArray(), arrayContainingInAnyOrder(excludedComponentsMapping.toArray())); } @Test public void testDescribeWithEmptyEmail() throws Exception { final AdvisorGlobalConfiguration c = new AdvisorGlobalConfiguration("", FAKE_CC, EXCLUDED); c.setAcceptToS(ACCEPT_TOS); c.setNagDisabled(NAG_DISABLED); Mapping described = configurator.describe(c, context).asMapping(); assertNotNull(described); assertTrue(described.isEmpty()); } @Test public void testDescribeWithNullEmail() throws Exception { final AdvisorGlobalConfiguration c = new AdvisorGlobalConfiguration(null, FAKE_CC, EXCLUDED); c.setAcceptToS(ACCEPT_TOS); c.setNagDisabled(NAG_DISABLED); Mapping described = configurator.describe(c, context).asMapping(); assertNotNull(described); assertTrue(described.isEmpty()); } @Test public void testDescribeWithBlankEmail() throws Exception { final AdvisorGlobalConfiguration c = new AdvisorGlobalConfiguration(" ", FAKE_CC, EXCLUDED); c.setAcceptToS(ACCEPT_TOS); c.setNagDisabled(NAG_DISABLED); Mapping described = configurator.describe(c, context).asMapping(); assertNotNull(described); assertTrue(described.isEmpty()); } @Test public void testDescribeWithEmptyCC() throws Exception { final AdvisorGlobalConfiguration c = new AdvisorGlobalConfiguration(FAKE_EMAIL, Collections.emptyList(), EXCLUDED); c.setAcceptToS(ACCEPT_TOS); c.setNagDisabled(NAG_DISABLED); Mapping described = configurator.describe(c, context).asMapping(); assertNotNull(described); assertEquals(mapping.getScalarValue(EMAIL_ATTR), described.getScalarValue(EMAIL_ATTR)); assertFalse(described.containsKey(CCS_ATTR)); assertEquals(mapping.getScalarValue(ACCEPT_TOS_ATTR), described.getScalarValue(ACCEPT_TOS_ATTR)); assertEquals(mapping.getScalarValue(NAG_DISABLED_ATTR), described.getScalarValue(NAG_DISABLED_ATTR)); Set<String> excludedComponentsMapping = toScalarValues(mapping.get(EXCLUDED_COMPONENTS_ATTR).asSequence()); Set<String> excludedComponentsDescribed = toScalarValues(described.get(EXCLUDED_COMPONENTS_ATTR).asSequence()); assertEquals(excludedComponentsMapping.size(), excludedComponentsDescribed.size()); assertThat(excludedComponentsDescribed.toArray(), arrayContainingInAnyOrder(excludedComponentsMapping.toArray())); } @Test public void testDescribeWithNullCC() throws Exception { final AdvisorGlobalConfiguration c = new AdvisorGlobalConfiguration(FAKE_EMAIL, null, EXCLUDED); c.setAcceptToS(ACCEPT_TOS); c.setNagDisabled(NAG_DISABLED); Mapping described = configurator.describe(c, context).asMapping(); assertNotNull(described); assertEquals(mapping.getScalarValue(EMAIL_ATTR), described.getScalarValue(EMAIL_ATTR)); assertFalse(described.containsKey(CCS_ATTR)); assertEquals(mapping.getScalarValue(ACCEPT_TOS_ATTR), described.getScalarValue(ACCEPT_TOS_ATTR)); assertEquals(mapping.getScalarValue(NAG_DISABLED_ATTR), described.getScalarValue(NAG_DISABLED_ATTR)); Set<String> excludedComponentsMapping = toScalarValues(mapping.get(EXCLUDED_COMPONENTS_ATTR).asSequence()); Set<String> excludedComponentsDescribed = toScalarValues(described.get(EXCLUDED_COMPONENTS_ATTR).asSequence()); assertEquals(excludedComponentsMapping.size(), excludedComponentsDescribed.size()); assertThat(excludedComponentsDescribed.toArray(), arrayContainingInAnyOrder(excludedComponentsMapping.toArray())); } @Test public void testDescribeWithNullExcluded() throws Exception { final AdvisorGlobalConfiguration c = new AdvisorGlobalConfiguration(FAKE_EMAIL, FAKE_CC, null); c.setAcceptToS(ACCEPT_TOS); c.setNagDisabled(NAG_DISABLED); Mapping described = configurator.describe(c, context).asMapping(); assertNotNull(described); assertEquals(mapping.getScalarValue(EMAIL_ATTR), described.getScalarValue(EMAIL_ATTR)); List<String> ccMapping = toListValues(mapping.get(CCS_ATTR).asSequence()); List<String> ccDescribed = toListValues(described.get(CCS_ATTR).asSequence()); assertEquals(ccMapping.size(), ccDescribed.size()); assertThat(ccDescribed.toArray(), arrayContainingInAnyOrder(ccMapping.toArray())); assertEquals(mapping.getScalarValue(ACCEPT_TOS_ATTR), described.getScalarValue(ACCEPT_TOS_ATTR)); assertEquals(mapping.getScalarValue(NAG_DISABLED_ATTR), described.getScalarValue(NAG_DISABLED_ATTR)); Set<String> excludedComponentsDescribed = toScalarValues(described.get(EXCLUDED_COMPONENTS_ATTR).asSequence()); assertEquals(1, excludedComponentsDescribed.size()); assertEquals(AdvisorGlobalConfiguration.SEND_ALL_COMPONENTS, excludedComponentsDescribed.toArray()[0]); } @Test public void testDescribeWithEmptyExcluded() throws Exception { final AdvisorGlobalConfiguration c = new AdvisorGlobalConfiguration(FAKE_EMAIL, FAKE_CC, new HashSet<>()); c.setAcceptToS(ACCEPT_TOS); c.setNagDisabled(NAG_DISABLED); Mapping described = configurator.describe(c, context).asMapping(); assertNotNull(described); assertEquals(mapping.getScalarValue(EMAIL_ATTR), described.getScalarValue(EMAIL_ATTR)); List<String> ccMapping = toListValues(mapping.get(CCS_ATTR).asSequence()); List<String> ccDescribed = toListValues(described.get(CCS_ATTR).asSequence()); assertEquals(ccMapping.size(), ccDescribed.size()); assertThat(ccDescribed.toArray(), arrayContainingInAnyOrder(ccMapping.toArray())); assertEquals(mapping.getScalarValue(ACCEPT_TOS_ATTR), described.getScalarValue(ACCEPT_TOS_ATTR)); assertEquals(mapping.getScalarValue(NAG_DISABLED_ATTR), described.getScalarValue(NAG_DISABLED_ATTR)); Set<String> excludedComponentsDescribed = toScalarValues(described.get(EXCLUDED_COMPONENTS_ATTR).asSequence()); assertEquals(1, excludedComponentsDescribed.size()); assertEquals(AdvisorGlobalConfiguration.SEND_ALL_COMPONENTS, excludedComponentsDescribed.toArray()[0]); } private Set<String> toScalarValues(Sequence s) throws Exception { Set<String> converted = new HashSet<>(s.size()); for (CNode cNode : s) { converted.add(cNode.asScalar().getValue()); } return converted; } private List<String> toListValues(Sequence s) throws Exception { List<String> converted = new ArrayList<>(s.size()); for (CNode cNode : s) { converted.add(cNode.asScalar().getValue()); } return converted; } @Test public void testInstance() throws Exception { AdvisorGlobalConfiguration instance = configurator.instance(mapping, context); assertNotNull(instance); assertEquals(configuration.getEmail(), instance.getEmail()); assertEquals(configuration.getCcs().size(), instance.getCcs().size()); assertThat(instance.getCcs().stream().map(Recipient::getEmail).toArray(), arrayContainingInAnyOrder(configuration.getCcs().stream().map(Recipient::getEmail).toArray())); assertEquals(configuration.isAcceptToS(), instance.isAcceptToS()); assertEquals(configuration.isNagDisabled(), instance.isNagDisabled()); assertEquals(configuration.getExcludedComponents().size(), instance.getExcludedComponents().size()); assertThat(instance.getExcludedComponents().toArray(), arrayContainingInAnyOrder(configuration.getExcludedComponents().toArray())); assertTrue(instance.isValid()); } @Test public void testInstanceSENDALL() throws Exception { final Mapping mappingWithDefault = new Mapping(); mappingWithDefault.put(ACCEPT_TOS_ATTR, ACCEPT_TOS); mappingWithDefault.put(EMAIL_ATTR, FAKE_EMAIL); Sequence cc = new Sequence(); cc.add(new Scalar("<EMAIL>")); cc.add(new Scalar("<EMAIL>")); mappingWithDefault.put(CCS_ATTR, cc); AdvisorGlobalConfiguration instance = configurator.instance(mappingWithDefault, context); assertNotNull(instance); assertTrue(instance.isAcceptToS()); assertFalse(instance.isNagDisabled()); assertEquals(1, instance.getExcludedComponents().size()); assertEquals(AdvisorGlobalConfiguration.SEND_ALL_COMPONENTS, instance.getExcludedComponents().toArray()[0]); assertTrue(instance.isValid()); } @Test public void testInstanceWithOutToS() throws Exception { thrown.expect(ConfiguratorException.class); final Mapping mappingWithDefault = new Mapping(); mappingWithDefault.put(EMAIL_ATTR, FAKE_EMAIL); Sequence cc = new Sequence(); cc.add(new Scalar("<EMAIL>")); cc.add(new Scalar("<EMAIL>")); mappingWithDefault.put(CCS_ATTR, cc); configurator.instance(mappingWithDefault, context); } @Test public void testInstanceNotAcceptedToS() throws Exception { thrown.expect(ConfiguratorException.class); final Mapping mappingNotAcceptingToS = new Mapping(); mappingNotAcceptingToS.put(ACCEPT_TOS_ATTR, false); mappingNotAcceptingToS.put(EMAIL_ATTR, FAKE_EMAIL); Sequence cc = new Sequence(); cc.add(new Scalar("<EMAIL>")); cc.add(new Scalar("<EMAIL>")); mappingNotAcceptingToS.put(CCS_ATTR, cc); mappingNotAcceptingToS.put(NAG_DISABLED_ATTR, NAG_DISABLED); configurator.instance(mappingNotAcceptingToS, context); } @Test public void testInstanceEmptyEmail() throws Exception { thrown.expect(ConfiguratorException.class); final Mapping m = new Mapping(); m.put(ACCEPT_TOS_ATTR, ACCEPT_TOS); m.put(EMAIL_ATTR, ""); Sequence cc = new Sequence(); cc.add(new Scalar("<EMAIL>")); cc.add(new Scalar("<EMAIL>")); m.put(CCS_ATTR, cc); m.put(NAG_DISABLED_ATTR, NAG_DISABLED); configurator.instance(m, context); } @Test public void testInstanceBadEmail() throws Exception { thrown.expect(ConfiguratorException.class); final Mapping m = new Mapping(); m.put(ACCEPT_TOS_ATTR, ACCEPT_TOS); Sequence cc = new Sequence(); cc.add(new Scalar("<EMAIL>")); cc.add(new Scalar("<EMAIL>")); m.put(CCS_ATTR, cc); m.put(EMAIL_ATTR, "bad_email"); m.put(NAG_DISABLED_ATTR, NAG_DISABLED); configurator.instance(m, context); } @Test public void testInstanceEmptyCC() throws Exception { thrown.expect(ConfiguratorException.class); final Mapping m = new Mapping(); m.put(ACCEPT_TOS_ATTR, false); m.put(EMAIL_ATTR, FAKE_EMAIL); m.put(NAG_DISABLED_ATTR, NAG_DISABLED); configurator.instance(m, context); } @Test public void testInstanceBadCC() throws Exception { thrown.expect(ConfiguratorException.class); final Mapping m = new Mapping(); m.put(ACCEPT_TOS_ATTR, false); Sequence cc = new Sequence(); cc.add(new Scalar("bad_cc")); m.put(CCS_ATTR, cc); m.put(EMAIL_ATTR, FAKE_EMAIL); m.put(NAG_DISABLED_ATTR, NAG_DISABLED); configurator.instance(m, context); } }
<reponame>kawu/concraft-pl<gh_stars>1-10 {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE LambdaCase #-} -- | DAG-aware morphosyntax data layer in Polish. module NLP.Concraft.Polish.DAG.Morphosyntax ( -- * Tag Tag -- * Edge -- , Edge (..) , Word (..) , Interp (..) , voidInterp , Space (..) -- , select -- , select' , selectWMap , selectAnno -- * Sentence , Sent , SentO (..) , restore , restore' , withOrig -- * Conversion , packSent , packSentO -- , packSeg -- -- ** From simple sentence -- , fromList ) where import Prelude hiding (Word) import Control.Applicative ((<$>), (<*>)) -- import Control.Arrow (first) -- import Control.Monad (guard) import Data.Binary (Binary, put, get) import Data.Aeson -- import qualified Data.Aeson as Aeson import qualified Data.Set as S import qualified Data.Map.Strict as M -- import Data.Maybe (catMaybes) import qualified Data.Text as T import qualified Data.Text.Lazy as L -- import qualified Data.Tagset.Positional as P import Data.DAG (DAG) import qualified Data.DAG as DAG -- import Data.CRF.Chain1.Constrained.DAG.Dataset.Internal (DAG) -- import qualified Data.CRF.Chain1.Constrained.DAG.Dataset.Internal as DAG -- import qualified NLP.Concraft.DAG2 as C import qualified NLP.Concraft.DAG.Morphosyntax as X import qualified NLP.Concraft.DAG.Segmentation as Seg -- import qualified NLP.Concraft.Polish.Morphosyntax as R import NLP.Concraft.Polish.Morphosyntax (Space(..)) -------------------------------- -- Basics -------------------------------- -- | A textual representation of a morphosyntactic tag. type Tag = T.Text -------------------------------- -- Interp -------------------------------- -- | A morphosyntactic interpretation. data Interp t = Interp { base :: T.Text -- ^ The base form (lemma) , tag :: t -- ^ The (morphosyntactic) tag , commonness :: Maybe T.Text , qualifier :: Maybe T.Text , metaInfo :: Maybe T.Text , eos :: Bool -- ^ The remaining four are ignored for the moment, but we plan to rely on -- them later on. } deriving (Show, Eq, Ord) -- | An almost empty interpretation, with only the `tag` actually specified. voidInterp :: t -> Interp t voidInterp x = Interp { base = "none" , tag = x , commonness = Nothing , qualifier = Nothing , metaInfo = Nothing , eos = False } instance (Ord t, Binary t) => Binary (Interp t) where put Interp{..} = do put base put tag put commonness put qualifier put metaInfo put eos get = Interp <$> get <*> get <*> get <*> get <*> get <*> get -------------------------------- -- Edge -------------------------------- -- -- | An edge consists of a word and a set of morphosyntactic interpretations. -- data Edge t = Edge -- { word :: Word -- -- | Interpretations of the word, each interpretation annotated -- -- with a /disamb/ Boolean value (if 'True', the interpretation -- -- is correct within the context). -- , interps :: X.WMap (Interp t) } -- deriving (Show, Eq, Ord) -- -- instance (Ord t, Binary t) => Binary (Edge t) where -- put Edge{..} = put word >> put interps -- get = Edge <$> get <*> get -- -- instance X.Word (Edge t) where -- orth = X.orth . word -- oov = X.oov . word -------------------------------- -- Word -------------------------------- -- | A word. data Word = Word { orth :: T.Text -- , space :: Space , known :: Bool , wordInfo :: Maybe T.Text -- ^ Additional word-related meta-information } deriving (Show, Eq, Ord) instance X.Word Word where orth = orth oov = not.known instance Binary Word where -- put Word{..} = put orth >> put space >> put known put Word{..} = put orth >> put known >> put wordInfo -- get = Word <$> get <*> get <*> get get = Word <$> get <*> get <*> get instance ToJSON Word where toJSON Word{..} = object [ "orth" .= orth , "known" .= known , "wordInfo" .= wordInfo ] instance FromJSON Word where parseJSON (Object v) = Word <$> v .: "orth" <*> v .: "known" <*> v .: "wordInfo" parseJSON _ = error "parseJSON [Word]" --------------------------------------------------------------------------------- -- Selection -- -- (Honestly, I don't remember what is this one about...) -- -- Update: maybe related to the fact that base forms have to be handled somehow? --------------------------------------------------------------------------------- -- -- | Select one chosen interpretation. -- select :: Ord a => a -> Edge a -> Edge a -- select = select' [] -- -- -- -- | Select multiple interpretations and one chosen interpretation. -- select' :: Ord a => [a] -> a -> Edge a -> Edge a -- select' ys x = selectWMap . X.mkWMap $ (x, 1) : map (,0) ys -- | Select interpretations. selectAnno :: Ord a => M.Map (Interp a) Double -> X.Seg Word (Interp a) -> X.Seg Word (Interp a) selectAnno = selectWMap . X.fromMap -- | Select interpretations. selectWMap :: Ord a => X.WMap (Interp a) -> X.Seg Word (Interp a) -> X.Seg Word (Interp a) selectWMap wMap seg = seg {X.tags = wMap} -- seg { X.tags = newTags } -- where -- wSet = S.fromList . map tag . M.keys . X.unWMap . X.tags $ seg -- newTags = X.mkWMap $ -- -- [ case M.lookup (tag interp) (X.unWMap wMap) of -- [ case M.lookup interp (X.unWMap wMap) of -- Just x -> (interp, x) -- Nothing -> (interp, 0) -- | interp <- (M.keys . X.unWMap) (X.tags seg) ] -- ++ catMaybes -- [ if interp `S.member` wSet -- then Nothing -- else Just (interp, x) -- | (interp, x) <- M.toList (X.unWMap wMap) -- -- | let lemma = orth $ X.word seg -- Default base form -- -- , (tag, x) <- M.toList (X.unWMap wMap) -- -- , let interp = Interp -- -- { base = lemma -- -- , tag = tag -- -- , commonness = Nothing -- -- , qualifier = Nothing -- -- , metaInfo = Nothing -- -- , eos = False } -- ] -------------------------------- -- Sentence -------------------------------- -- | A sentence. -- type Sent t = DAG Space (Edge t) type Sent t = DAG Space (X.Seg Word t) -- | A sentence with its original textual representation. data SentO t = SentO { sent :: Sent t , orig :: L.Text } -- | Restore textual representation of a sentence. The function is not very -- accurate, it could be improved if we enriched the representation of spaces. restore :: Sent t -> L.Text restore = let edgeStr = orth . X.word spaceStr None = "" spaceStr Space = " " spaceStr NewLine = "\n" in L.fromChunks . map (either spaceStr edgeStr) . pickPath -- | Use `restore` to translate `Sent` to a `SentO`. withOrig :: Sent t -> SentO t withOrig s = SentO { sent = s , orig = restore s } -- | A version of `restore` which places a space on each node. restore' :: Sent t -> L.Text restore' = let edgeStr = orth . X.word spaceStr = const " " in L.fromChunks . map (either spaceStr edgeStr) . tail . pickPath -------------------------------- -- Utils -------------------------------- -- | Pick any path from the given DAG. The result is a list -- of interleaved node and edge labels. pickPath :: (X.Word b) => DAG a b -> [Either a b] pickPath dag = fstNodeVal path : concatMap getVals path where -- Take the value on the first node on the path fstNodeVal = \case edgeID : _ -> Left $ DAG.nodeLabel (DAG.begsWith edgeID dag) dag [] -> error "Morphosyntax.pickPath: empty path" -- Select a shortest path in the DAG; thanks to edges being topologically -- sorted, this should give us the list of edge IDs in an appropriate order. path = S.toList $ Seg.findPath Seg.Min dag -- Get the labels of the nodes and labels getVals edgeID = let nodeID = DAG.endsWith edgeID dag in [ Right $ DAG.edgeLabel edgeID dag , Left $ DAG.nodeLabel nodeID dag ] --------------------------- -- Conversion --------------------------- -- -- | Convert a segment to a segment from the core library. -- packSeg :: Ord a => X.Seg Word a -> X.Seg Word a -- packSeg = id -- -- packSeg Edge{..} -- -- = X.Seg word -- -- $ X.mkWMap -- -- $ map (first tag) -- -- $ M.toList -- -- $ X.unWMap interps -- | Convert a sentence to a sentence from the core library. packSent :: Ord a => Sent a -> X.Sent Word a packSent = DAG.mapN (const ()) -- . fmap packSeg -- | Convert a sentence to a sentence from the core library. -- packSentO :: P.Tagset -> SentO Tag -> X.SentO Word P.Tag packSentO :: Ord a => SentO a -> X.SentO Word a packSentO s = X.SentO { segs = packSent (sent s) , orig = orig s } --------------------------- -- From simple sentence --------------------------- -- fromWord :: R.Word -> (Space, Word) -- fromWord R.Word{..} = (space, Word {orth=orth, known=known}) -- -- -- fromSeg :: (Ord t) => R.Seg t -> (Space, Edge t) -- fromSeg R.Seg{..} = -- (space, edge) -- where -- edge = Edge {word = newWord, interps = updateInterps interps} -- (space, newWord) = fromWord word -- -- updateInterps = X.mkWMap . map (first fromInterp) . X.unWMap -- updateInterps = X.mapWMap fromInterp -- -- -- fromInterp :: R.Interp t -> Interp t -- fromInterp R.Interp{..} = Interp -- { base = base -- , tag = tag -- , commonness = Nothing -- , qualifier = Nothing -- , metaInfo = Nothing -- , eos = False } -- -- -- -- | Create a DAG-based sentence from a list-based sentence. -- fromList :: Ord t => R.Sent t -> Sent t -- fromList = DAG.fromList' None . map fromSeg
<filename>src/domain/Seat.ts import { SeatName } from "./SeatName"; import Card from "./Card"; export class Seat { seatName: SeatName; playCard?: Card; faceCards: Card[] = []; hands: Card[] = []; score = 0; isAide = false; isLastLapWinner = false; constructor( seatName: SeatName, playCard?: Card, faceCards: Card[] = [], hands: Card[] = [], score = 0, isAide = false, isLastLapWinner = false ) { this.seatName = seatName; this.playCard = playCard; this.faceCards = faceCards; this.hands = hands; this.score = score; this.isAide = isAide; this.isLastLapWinner = isLastLapWinner; } static from(seatObj: Seat): Seat { return new Seat( seatObj.seatName, seatObj.playCard && Card.fromObj(seatObj.playCard), seatObj.faceCards.map(Card.fromObj), seatObj.hands.map(Card.fromObj), seatObj.score, seatObj.isAide, seatObj.isLastLapWinner ); } }
module Frenetic.Z3 ( -- * Data types and constructors for running Z3 Z3Input (..) , setUp , DeclConst (..) , Const (..) -- * Z3 formula components , Z3Packet (..) , Z3Int (..) , BoolExp (..) , IntExp (..) , nAnd , nOr -- * Tools to run Z3 , check , checkBool ) where import Data.List import Data.Maybe import System.Process import System.IO join = intercalate data Z3Input = Input [Declaration] [DeclConst] [BoolExp] data Declaration = PacketSort | Header String instance Show Declaration where show PacketSort = "(declare-sort Packet)" show (Header name) = "(declare-fun " ++ name ++ " (Packet) Int)" data Z3Packet = Z3Packet String deriving (Eq) data Z3Int = Z3Int String deriving (Eq) data DeclConst = DeclConst Const instance Show DeclConst where show (DeclConst (ConstPacket (Z3Packet name))) = "(declare-const " ++ name ++ " Packet)" show (DeclConst (ConstInt (Z3Int name))) = "(declare-const " ++ name ++ " Int)" data Const = ConstPacket Z3Packet | ConstInt Z3Int deriving (Eq) instance Show Const where show (ConstPacket (Z3Packet name)) = "(" ++ name ++ " Packet)" show (ConstInt (Z3Int name)) = "(" ++ name ++ " Int)" data BoolExp = ZTrue | ZFalse | ZNot BoolExp | ZAnd BoolExp BoolExp | ZOr BoolExp BoolExp | Implies BoolExp BoolExp | Equals IntExp IntExp | ForAll [Const] BoolExp | Exists [Const] BoolExp deriving (Eq) data IntExp = Primitive Integer | PktHeader String Z3Packet | Variable Z3Int deriving (Eq) setUp = [PacketSort , Header "DlSrc" , Header "DlDst" , Header "DlTyp" , Header "DlVlan" , Header "DlVlanPcp" , Header "NwSrc" , Header "NwDst" , Header "NwProto" , Header "NwTos" , Header "TpSrc" , Header "TpDst" , Header "InPort" , Header "Switch" ] instance Show Z3Input where show (Input decls consts exprs) = join "\n" lines where lines = map show decls ++ map show consts ++ (map (\ b -> "(assert " ++ b ++ ")") . map show $ exprs) ++ ["(check-sat)", "(get-model)"] instance Show BoolExp where show ZTrue = "true" show ZFalse = "false" show (ZNot b) = "(not " ++ show b ++ ")" show (ZAnd b1 b2) = "(and " ++ show b1 ++ " " ++ show b2 ++ ")" show (ZOr b1 b2) = "(or " ++ show b1 ++ " " ++ show b2 ++ ")" show (Implies b1 b2) = "(implies " ++ show b1 ++ " " ++ show b2 ++ ")" show (Equals i1 i2) = "(equals " ++ show i1 ++ " " ++ show i2 ++ ")" show (ForAll consts b) = "(forall (" ++ join " " (map show consts) ++ ") " ++ show b ++ ")" show (Exists consts b) = "(exists (" ++ join " " (map show consts) ++ ") " ++ show b ++ ")" instance Show IntExp where show (Primitive i) = show i show (PktHeader field (Z3Packet packet)) = "(" ++ field ++ " " ++ packet ++ ")" show (Variable (Z3Int name)) = name -- |Nary And, return True if empty nAnd :: [BoolExp] -> BoolExp nAnd [] = ZTrue nAnd bs = foldr1 (\ b1 b2 -> ZAnd b1 b2) bs -- |Nary Or, return False if empty nOr :: [BoolExp] -> BoolExp nOr [] = ZFalse nOr bs = foldr1 (\ b1 b2 -> ZOr b1 b2) bs -- |Convert true-is-Just-false-is-Nothing to boolean checkBool :: IO (Maybe a) -> IO Bool checkBool = fmap isJust -- use smt2 syntax, disable warnings, emit the model, use stdin z3Process = CreateProcess (ShellCommand "z3 -smt2 -nw -in") Nothing -- No working directory Nothing -- No special environment CreatePipe -- Pipe to stdin CreatePipe -- Pipe from stdout Inherit -- Propagate errors upward True -- Close other filehandles False -- Don't create a new process group -- |Determine if a formula is SAT, returning the model or nothing. check :: Z3Input -> IO (Maybe String) check z3input = do let assertions = show z3input (Just inh, Just outh, _, p) <- createProcess z3Process hPutStrLn inh assertions hClose inh output <- hGetContents outh let result : model = lines output if result == "unsat" then return Nothing else if result == "sat" then return (Just (join "\n" model)) else if result == "unknown" then error "No decision reached" else error ("Unknown status from z3: " ++ result ++ "\n" ++ "This was the input to z3: \n" ++ assertions)
/** * Sets the JDBC connection to use with the handler. * @param conn The connection * @return This object */ public Builder withConnection(JDBCDatabaseConnection conn) { handler.setConnection(conn); return this; }
/** * Sends a message. * * @param message A array of byte to send. */ private void sendMessage(byte[] message) { if (mBluetoothService.getState() != BluetoothService.STATE_CONNECTED) { Toast.makeText(this, "You are not connected to a device", Toast.LENGTH_SHORT).show(); } if (message.length > 0) { mBluetoothService.write(message); } }
def convert_wiki(df: pd.DataFrame, proc_index: int = 0) -> pd.DataFrame: df['tmp'] = f"wiki_{proc_index}_" + df.index.astype(str) df = df.rename({'id': 'wikipedia'}, axis=1) df['wikipedia'] = df['wikipedia'].astype(str) df = collapse_id_list(df, 'ID_list', ['tmp', 'wikipedia'], do_not_drop={'tmp'}) df['ID_list'] = df['ID_list'].map(stringify_id_list) df = df.rename({'page_title': 'title', 'ID_list': 'id' }, axis=1) df['author'] = None df['pub_date'] = None df['venue'] = None df['volume'] = None df['issue'] = None df['page'] = None df['type'] = None df['publisher'] = None df['editor'] = None return df
N=int(input()) A=[[tuple(map(int,input().split(' ')))for j in range(int(input()))] for i in range(N)] say_map=[[-1 for i in range(N)] for j in range(N)] ans = 0 for n,i in enumerate(A): for j,k in i: say_map[n][j-1]=k for i in range(2**N): i_bin=format(i,'0{}b'.format(N)) flg = True tmp = 0 for n,j in enumerate(i_bin): j = int(j) if j == 1: tmp += 1 for k,l in zip(i_bin,say_map[n]): if (int(k)==0 and l==1) or (int(k)==1 and l ==0): flg=False break if not flg: tmp = 0 break ans = max(ans,tmp) print(ans)
Art by Todd Lockwood Ever since I was a little kid, I’ve loved to be out in nature. Whether I’m hiking, sketching trees, observing frog spawn, or just relaxing to the sounds of birds and running water, it never fails to inspire my imagination. In fact, the ideas for several of my stories came to me while trekking through the forest, and many of my characters have something of a naturalist in them as well, including Kendra, the hero of my story β€œA Whole-Hearted Halfing” in the Champions of Aetaltis anthology. From Doctor Dolittle to Newt Scamander, fantasy fiction is full of naturalists and those fascinated by the creatures and plants of the world around them. Here is a list of five of my favorite books that appeal to my inner naturalist. A Natural History of Dragons by Marie Brennan This novel is told in the style of a Victorian memoir from the point of Isabella, Lady Trent, the world’s foremost authority on dragons. The style is quaint but it is by no means paced like a true Victorian book. Readers will love accompanying Isabella as she makes discoveries about both the natural world and herself. It’s a book full of thrillsβ€”Lady Trent’s enthusiasm and passion for learning about dragons is contagious, and the reader can’t help but go along with her on her expeditions. The Flight of Dragons by Peter Dickinson, Illustrated by Wayne Anderson I’m lucky enough to have a first edition copy of this now out of print (but still attainable) tome by the late Peter Dickinson. The purpose of this book is simple: to prove that dragons did indeed exist. Drawing on mythology, folk tales, and anecdotes, Dickinson creates a pretty convincing thesis. With the help of gorgeous illustrations, he explains why dragons hoard gold, how they fly and breathe fire, what their life cycle is like, and the intricacies of dragon speech. The Rankin/Bass animated movie Flight of Dragons is based on this book. The Southern Reach Trilogy by Jeff VanderMeer This trilogy (which can also be found in a gorgeous one volume hardcover book) follows a group of scientists as they study a place called Area X from both inside and out. This piece of land has been cut off from the outside world and is studied by a secret government agency called Southern Reach. Every group that has gone to Area X, save the first, has met with pretty horrid fates, and those that returned always have more questions than answers. Something about this pristine natural place, which seems to have wiped away the traces of human civilization that was once there. VanderMeer’s work in this trilogy is nothing short of amazing. Not only is the natural world in these books developed enough to where Area X could be a character in its own right, but there is enough paranoia, unanswered questions, and even some heavy emotions to keep the reader’s heart pounding to the end. The Book of Barely Imagined Beings by Caspar Henderson The creatures in this book are amazing, mysterious, puzzling … and all very real. Inspired by the medieval bestiaries and books of imagined beings, this book is arranged in alphabetical order, and includes old style illustrations as well as modern photographs of creatures. It’s a celebration of the weird and wonderful creatures of nature, many of which have become very rare. Unlike other nonfiction natural history books, Henderson keeps his book very readable yet still informative, filled with wit, inspiration, and yes, even magic. The Invention of Nature: Alexander Von Humboldt’s New World by Andrea Wulf As I read this book, I felt like I was journeying around the world with Humbolt, climbing mountains and volcanoes, making connections between previously unrelated things, inventing new tools to aid in the study of nature, and scratching the brains of his contemporaries, Jefferson, Goethe, Schiller, and Bolivar. It’s no wonder such a man inspired people like Darwin, Thoreau, and Muir. Reading this book hardly felt like a biography. I felt like I was in an adventure novel full of war and dangerous creatures, illnesses, and harrowing journeys. Humbolt had a revolutionary vision of nature that changed the world and still inspires millions to this day. After reading even a couple chapters of this book, readers will not wonder why. Melanie R. Meadors is the author of fantasy and science fiction stories where heroes don’t always carry swords and knights in shining armor often lose to nerds who study their weaknesses. Her work has been published in Circle Magazine, The Wheel, and Prick of the Spindle, and she was a finalist in the 2014 Jim Baen Memorial Science Fiction Contest. Melanie is also a freelance author publicist and publicity/marketing coordinator for both Ragnarok Publications and Mechanical Muse. She blogs regularly for GeekMom and The Once and Future Podcast. Her short story β€œA Whole-Hearted Halfling” is in the anthology Champions of Aetaltis.
Key evolution-based tamper resistance: a subgroup extension The number and magnitude of hostile attacks against software has drastically increased. One class of attacks of particular concern to the software industry is tampering to circumvent protection technologies such as license checks. A variety of hardware- and software-base techniques have been developed to address the issue. These include, but are not limited to, dongles, smartcards, and code obfuscation. In this paper we examine two previously proposed software-based tamper resistance techniques which are both based on the same key evolution mechanism: Event Log-Based and Branch-Based tamper resistance. As proposed the techniques offer many advantages over other software-based algorithms, however, they still suffer from a common limitation. Through our analysis we identify this limitation and propose an extension to the schemes which improves the overall strength.
Anthony Hopkins Lives Out A Long-Deferred Musical Dream Enlarge this image toggle caption Courtesy of the artist Courtesy of the artist Hear The Music Bracken Road And The Waltz Goes On Anthony Hopkins has been knighted by Queen Elizabeth II, and has played Richard I, Richard Nixon, monarchs, statesmen, geniuses and heroes. He won an Academy Award playing one of the most notorious movie villains in history: Hannibal Lecter, the criminal cannibal with an affinity for Bach. Now, Hopkins is making his own music. The City of Birmingham Symphony Orchestra of England performed original classical music written by Anthony Hopkins last year in the U.K. A recording of those live performances, called Composer, was recently released there and rocketed to the top of the U.K. classical charts. Hopkins tells NPR's Scott Simon that he's been writing music for some time, improvising on pianos and writing bits and pieces on manuscripts for more than 50 years. "I just did it for the sheer fun of it," Hopkins says. "My wife, Stella, said [I] should take this and orchestrate it and get it performed by a major symphony orchestra. It took me about a year to put all the pieces together." Learn More Hopkins discusses his forgotten 1986 single. Outtake - "Distant Star" Growing up in Wales, Hopkins found his entry into the arts when his mother bought an old cottage piano for 5 pounds, and he started music lessons. "She, of course, wanted me to be a concert pianist, and I had different plans," he says. "I just wanted to be a composer; I became an actor by default, really. I got a scholarship to a college of music and drama, hoping to take a scholarship in music. But I ended up as an acting student, so I've stuck with that for the last 50-odd years." "When you're a certain age and becoming conscious that you're inadequate in school β€” which I was β€” it's a lonely feeling," Hopkins adds. "You feel isolated and bullied and all the rest of it. I was pretty strong, so nobody bullied me, but I did feel isolated. And I look back on it all now as the greatest gift that I could have been given, because it was the rocket fuel that sort of drove me to do something with my life. So life and destiny are very peculiar. God, whatever God is, has a great sense of humor. And here I am, composing at the age of 74."
def table_query( self, table: pd.DataFrame, aggregator: Optional[callable] = None, k: Optional[int] = None, verbose: bool = False, ) -> Union[Iterable[Tuple], Tuple[Iterable[Tuple], Iterable[Tuple]]]: extended_table_results = None score_distributions = {} for column in table.columns: column_results = self.column_query( column=table[column], aggregator=None, k=None ) score_distributions[column] = np.sort( np.array([scores for _, scores in column_results]), axis=0 ) extended_table_results = self.group_results_by_table( target_id=column, results=column_results, table_groups=extended_table_results, ) table_results = {} for candidate in extended_table_results.keys(): candidate_scores = np.array( [details[1] for details in extended_table_results[candidate]] ) distributions = [ score_distributions[details[0][0]] for details in extended_table_results[candidate] ] weighted_scores = self.get_cdf_scores(distributions, candidate_scores) if aggregator is None: table_results[candidate] = weighted_scores.tolist() else: table_results[candidate] = aggregator(weighted_scores.tolist()) table_results = sorted(table_results.items(), key=lambda pair: pair[1], reverse=True) if k is not None: table_results = table_results[:k] if verbose: extended_table_results = [(cand, extended_table_results[cand]) for cand, _ in table_results] return table_results, extended_table_results return table_results
/** * Greet the customer * @param name * @return String */ public String greet(String name) { try { MyWebService myService = service.getPort(MyWebService.class); String message = myService.greetCustomer(name); System.out.println(message); return message; } catch (Exception exception) { exception.printStackTrace(); } return "empty string"; }
export * from "./src/pkce.ts";
import { server } from './http'; import './websocket/ChatService'; server.listen(3333, () => console.log('Server Started on Port 3000.'));
Metacarpophalangeal pattern profiles in the evaluation of skeletal malformations. Metacarpophalangeal pattern profile analysis is a graphic method of depicting lengthening and shortening of the tubular bones of the hand and their relationship to one another. The lengths of the tubular bones are plotted in terms of standard deviation units. These data are derived from simple measurements from hand radiographs and related to age and sex norms. Comparison of these patterns is a more sensitive index for detecting similarity of hand radiographs than is simple inspection of the radiograph. Since many congenital malformations have characteristic metacarpophalangeal pattern profiles, the method can be useful in the diagnosis and definition of these conditions.
/** * Test config data */ public class TestConfig { public static final String TESTS_FOLDER; static { String tmpDir = System.getProperty("java.io.tmpdir"); if (!tmpDir.endsWith(File.separator)) { tmpDir = tmpDir.concat(File.separator); } TESTS_FOLDER = tmpDir.concat("Fitpay").concat(File.separator); } @FPLog.LogLevel int logLevel = FPLog.DEBUG; boolean showHTTPLogs = false; boolean useRealTests = false; boolean saveRealTests = false; String testsVersion = "0.0.1"; @FPLog.LogLevel public int getLogLevel() { return logLevel; } public boolean showHTTPLogs() { return showHTTPLogs; } public boolean useRealTests() { return useRealTests; } public boolean saveRealTests() { return saveRealTests; } public String testsVersion() { return testsVersion; } public static TestConfig init(Class clazz) { InputStream inputStream = clazz.getClassLoader().getResourceAsStream("test_config.json"); TestConfig configModel = null; try { BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); configModel = Constants.getGson().fromJson(in, TestConfig.class); } catch (IOException e) { configModel = new TestConfig(); } return configModel; } }
<reponame>Phorkyas/advent-of-code2021<filename>day4/bingo.py #!/usr/bin/env python3 numbers = [] with open('numbers', 'r') as data: numbers = data.read().split(',') boards = [] with open('boards', 'r') as data: stuff = data.read() boardsplit = stuff.split("\n\n") for board in boardsplit: intboard = [] lines = board.split("\n") if len(lines) != 5: continue for line in lines: intboard.append([int(n) for n in line.split()]) boards.append(intboard) print("parsed " + str(len(boards)) + " boards") def mark_number(number, board, count): for y in range(len(board)): for x in range(len(board[y])): if board[x][y] == number: #print("Zahl da in: " + str(x) + " " + str(y) + " - brett: " + str(count)) board[x][y] += 100 def hat_bingo(zahlen): for zahl in zahlen: if zahl < 100: return False return True def score(board): res = 0 for y in range(len(board)): for el in board[y]: # sum all unmarked elements if el < 100: res += el return res def gewonnen(board, number): for y in range(len(board)): spalte = [board[x][y] for x in range(len(board[0]))] if hat_bingo(spalte): real_col = [n - 100 for n in spalte] print("bingo in spalte: " + str(real_col)) print("score: " + str(score(board))) print("result: " + str(number * score(board))) return True for zeile in board: if hat_bingo(zeile): print(str(board)) real_row = [n - 100 for n in zeile] print("bingo in zeile: " + str(real_row)) print("score: " + str(score(board))) print("result: " + str(number * score(board))) return True return False winner_boards = [] for num in numbers: print("<NAME>: " + num + " in Brett") count = 0 for board in boards: count += 1 mark_number(int(num), board, count) if count not in winner_boards and gewonnen(board, int(num)): print("BINGO!!") print("Board " + str(count) + " hat gewonnen") winner_boards.append(count) print("finished - there where: " + str(len(winner_boards)) + " winner boards")
def enter_button(self): if self.system == "Windows": self.configure(background="DimGrey") self.v_link["var_status"].set(self.tip)
// NewShiba returns a new instance of Shiba. func NewShiba(client kubernetes.Interface, nodeName, cniConfigPath string, options ShibaOptions) (*Shiba, error) { shiba := &Shiba{ client: client, cniConfigPath: cniConfigPath, nodeName: nodeName, nodeMap: make(model.NodeMap), nodeGatewayMap: make(map[string]bool), fireCh: make(chan struct{}, 1), apiTimeout: options.APITimeout, clusterPodCIDRs: options.ClusterPodCIDRs, } if err := shiba.initSelf(); err != nil { return nil, fmt.Errorf("failed to get info about self: %w", err) } if err := shiba.initCluster(); err != nil { return nil, fmt.Errorf("failed to get info about the cluster: %w", err) } if err := shiba.initCNI(); err != nil { return nil, fmt.Errorf("failed to init cni: %w", err) } if err := shiba.initNAT(); err != nil { return nil, fmt.Errorf("failed to init nat: %w", err) } shiba.loadNodeMap() shiba.fireCh <- struct{}{} log.Info("shiba initialized") return shiba, nil }
/** Look up the user and return if they were found */ func (repo *RepoMemory) GetUserByEmail(email string) (User, error) { for _, v := range repo.usersList { if v.Email() == email { return v, nil } } return nil, errors.New("no user with email") }
// GetDateAdded returns the DateAdded field value func (o *EnabledProviderAccount) GetDateAdded() string { if o == nil { var ret string return ret } return o.DateAdded }
/** * Uses a given tensorFlow model as input from assets, takes a RGB array of an image and returns * a json array with the corresponding weights the model returns. */ public class TensorWeights extends TensorFlowInferenceInterface { // Note: Only supports armeabi-v7a as pr // https://github.com/miyosuda/TensorFlowAndroidDemo/tree/master/app/src/main/jniLibs/ // This is hopefully not an issue.. except for robolectric emulator ofc... private static final String INPUT_NODE = "input:0"; private static final String OUTPUT_NODE = "out:0"; private static final int PIXEL_SIZE = 96; private static final int INPUT_SIZE = 3; private static final String[] OUTPUT_NODES = new String[]{OUTPUT_NODE}; public TensorWeights(AssetManager assetManager, String s) { super(assetManager, s); } public JsonArray getWeights(Bitmap bitmap, long timestamp) { float[] result = new float[128]; feed(INPUT_NODE, bitmapToFloatArray(bitmap), 1, PIXEL_SIZE, PIXEL_SIZE, INPUT_SIZE); run(OUTPUT_NODES); fetch(OUTPUT_NODE, result); JsonArray data = new JsonArray(); data.add("" + timestamp); for (float weight : result) { data.add("" + weight); } return data; } static float[] bitmapToFloatArray(Bitmap image) { int width = image.getWidth(); int height = image.getHeight(); int[] pixels = new int[width * height]; image.getPixels(pixels, 0, width, 0, 0, width, height); if (width != height) { throw new java.lang.Error("BitmapToIntArray only makes sense on square images"); } float[] array = new float[width * width * 3]; for (int i = 0; i < width; i++) { for (int j = 0; j < width; j++) { array[i * width + 3 * j] = (pixels[i * j] >> 16) & 0xff; array[i * width + 3 * j + 1] = (pixels[i * j] >> 8) & 0xff; array[i * width + 3 * j + 2] = pixels[i * j] & 0xff; } } return array; } }
#include "application.h" #include "view.h" #include <Awesomium/WebCore.h> #include <Awesomium/STLHelpers.h> #ifdef _WIN32 #include <Windows.h> #endif using namespace Awesomium; class TutorialApp : public Application::Listener { Application* app_; View* view_; public: TutorialApp() : app_(Application::Create()), view_(0) { app_->set_listener(this); } virtual ~TutorialApp() { if (view_) app_->DestroyView(view_); if (app_) delete app_; } void Run() { app_->Run(); } // Inherited from Application::Listener virtual void OnLoaded() { view_ = View::Create(500, 300); // < Set up your View here. > } // Inherited from Application::Listener virtual void OnUpdate() { } // Inherited from Application::Listener virtual void OnShutdown() { } }; #ifdef _WIN32 int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE, wchar_t*, int nCmdShow) { #else int main() { #endif TutorialApp app; app.Run(); return 0; }
S = input() keyence = "keyence" answer = 'NO' if keyence in S: if S[:7] == keyence: answer = "YES" elif S[-7:] == keyence: answer = "YES" else: for i in range(6): if (S[:i+1] == keyence[:i+1]) & (S[-6+i:] == keyence[-6+i:]): answer = "YES" print(answer)
package config import ( "errors" "fmt" "strings" ) // SchemaConfig defines the schema migration resources // configurations. type SchemaConfig struct { Directory string `toml:"directory"` Sequence []string `toml:"sequence"` } func (c *SchemaConfig) validate() error { if c.Directory == "" { return errors.New("invalid directory ''") } for id, migration := range c.Sequence { if strings.Contains(migration, " ") { return fmt.Errorf("invalid migration %d: name '%s' contains spaces", id, migration) } } return nil }
/// Creates a symlink to a dotfile. pub fn build(dotfile: &Dotfile, config: &Config) -> Result<(), Error> { let dest_path = self::path(dotfile, config); if dest_path.exists() { if dest_path.is_dir() { warn!("there is an existing directory at '{}', will not create symlink", dest_path.display()); return Ok(()); } else { let metadata = fs::symlink_metadata(&dest_path)?; if metadata.file_type().is_symlink() { let current_target = fs::read_link(&dest_path)?; if current_target.canonicalize()? == dotfile.full_path.canonicalize()? { // No harm in recreating a symlink to the same location. fs::remove_file(&dest_path)?; } else { ilog!("there is an existing symlink to a different file at '{}', deleting it", dest_path.display()); } } else { warn!("there is an existing file at '{}', will not create symlink", dest_path.display()); return Ok(()); } } } // If the dotfile is in a subdirectory, we need to // create the subdirectory inside the home directory // for the symlink to live in. if let Some(parent) = dest_path.parent() { if !parent.exists() { fs::create_dir_all(parent)?; } } println!("{} -> {}", dotfile.full_path.display(), dest_path.display()); unix::fs::symlink(&dotfile.full_path, &dest_path)?; Ok(()) }
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { Error404 } from '@dassana-io/web-components' import Layout from '@theme/Layout' import styles from './NotFound.module.css' import { useHistory } from 'react-router' import React, { FC } from 'react' const NotFound: FC = () => { const history = useHistory() return ( <Layout title='Page Not Found'> <div className={styles.wrapper}> <Error404 onBtnClick={() => history.push('/')} /> </div> </Layout> ) } export default NotFound
import copy import torch.nn as nn from torchvision.models.feature_extraction import get_graph_node_names from torchvision.models.feature_extraction import create_feature_extractor from torch.nn import functional as F class McdWrapper(nn.Module): def __init__(self, model): super().__init__() self.task = model.task self.f_extr = self.__extract_feats(model) self.classifier1 = model.classifier self.classifier2 = copy.deepcopy(model.classifier) @staticmethod def __extract_feats(model): train_nodes, eval_nodes = get_graph_node_names(model) index = [i for i, name in enumerate(train_nodes) if 'classifier' in name][0] - 1 return_nodes = [train_nodes[index]] return create_feature_extractor(model, return_nodes=return_nodes) def __fw_cl1(self, feats, input_shape): out1 = self.classifier1(feats) out1 = F.interpolate(out1, size=input_shape, mode='bilinear', align_corners=False) return out1 def __fw_cl2(self, feats, input_shape): out2 = self.classifier2(feats) out2 = F.interpolate(out2, size=input_shape, mode='bilinear', align_corners=False) return out2 def forward(self, x, classifier1=False, classifier2=False): input_shape = x.shape[-2:] feats = list(self.f_extr(x).values())[0] if classifier1 and classifier2: return self.__fw_cl1(feats, input_shape), self.__fw_cl2(feats, input_shape) if classifier1: return self.__fw_cl1(feats, input_shape) if classifier2: return self.__fw_cl2(feats, input_shape) return feats
# -*- coding: latin-1 -*- # Copyright (c) 2008 Pycircuit Development Team # See LICENSE for details. import circuit import pycircuit.utilities.param as param import sympy import sympy.printing.lambdarepr import numpy as np import inspect from copy import copy class Node(circuit.Node): @property def V(self): return Quantity('V', self) class Branch(circuit.Branch): @property def V(self): return Quantity('V', self) @property def I(self): return Quantity('I', self) class Parameter(param.Parameter, sympy.Symbol): pass class ddt(sympy.Function): """Time derivative, d(x)/dt""" pass class Quantity(circuit.Quantity, sympy.basic.Atom): pass class Statement(object): pass class Contribution(Statement): def __init__(self, lhs, rhs): self.lhs = lhs self.rhs = sympy.sympify(rhs) def nodes(self): """Return set of node objects referred to in lhs and rhs >>> a, b = Node('a'), Node('b') >>> b = Branch(a,b) >>> Contribution(b.I, 1e-3 * b.V).nodes() set([Node('a'), Node('b')]) """ nodes = set() for atom in self.lhs.atoms() | self.rhs.atoms(): if isinstance(atom, Quantity): if atom.isbranch: nodes.add(atom.branch_or_node.plus) nodes.add(atom.branch_or_node.minus) else: nodes.add(atom.branch_or_node) return nodes def contributions(self): """Return list of (node, iexpression, uexpression) tuples >>> a, b = Node('a'), Node('b') >>> b = Branch(a,b) >>> Contribution(b.I, 1e-3 * b.V).contributions() ((Node(a), 1e-3 * a.V - 1e-3 * b.V, 0), (Node(b), -1e-3 * a.V + 1e-3 * b.V), 0) """ if not isinstance(self.lhs, Quantity): raise ValueError('lhs must be a Quantity') rhs = self.rhs ## Split voltage of branches to voltages of nodes substdict = {} for atom in rhs.atoms(): if isinstance(atom, Quantity): if atom.isbranch and atom.quantity == 'V': branch = atom.branch_or_node v = Quantity('V', branch.plus) - Quantity('V', branch.minus) substdict[atom] = v rhs = rhs.subs(substdict) ## Split i and u terms rhs = rhs.expand() if rhs.is_Add: terms = rhs.args else: terms = (rhs,) iterms = [] uterms = [] qterms = [] for term in terms: if isconstant(term): uterms.append(term) elif isinstance(term, ddt): qterms.append(term.args[0]) else: iterms.append(term) ## re-join terms irhs = sympy.Add(*iterms) urhs = sympy.Add(*uterms) qrhs = sympy.Add(*qterms) if self.lhs.quantity == 'I': if self.lhs.isbranch: branch = self.lhs.branch_or_node return ((branch.plus, irhs, qrhs, urhs), (branch.minus, -irhs, -qrhs, -urhs)) class NumpyPrinter(sympy.printing.StrPrinter): def _print_Matrix(self, expr): return "np.array([%s])"%expr._format_str(self._print, ",") def methodstr(name, args, expr): """Returns a string that can be evaluated to an instance method >>> x = sympy.Symbol('x') >>> methodstr('G', x, x**2 * sympy.Symbol('self.p')) 'def G(self, x): return self.p*x**2' """ # Transform everything to strings. expr = NumpyPrinter().doprint(expr) if isinstance(args, str): pass elif hasattr(args, "__iter__"): args = ",".join(str(a) for a in args) else: args = str(args) return "def %s(self, %s): return %s" % (name, args, expr) def generate_code(cls): """Returns terminal names and i,u,q,G,C,CY method strings from class obj""" ## Get arguments (terminals) terminalnames = inspect.getargspec(cls.analog)[0] ## Create node objects of the terminals terminalnodes = [Node(terminal) for terminal in terminalnames] ## Make a copy of analog method analogfunc = copy(cls.analog) ## Inject parameters into function globals params = dict((param.name, sympy.Symbol('self.ipar.' + param.name)) for param in cls.instparams) analogfunc.func_globals.update(params) ## Call analog function statements = analogfunc(*terminalnodes) ## Create vector of current expressions for each node nodes = set() icontribs = {} ucontribs = {} qcontribs = {} for statement in statements: for node, icontrib, qcontrib, ucontrib in statement.contributions(): if node in icontribs: icontribs[node] += icontrib ucontribs[node] += ucontrib qcontribs[node] += qcontrib else: icontribs[node] = icontrib ucontribs[node] = ucontrib qcontribs[node] = qcontrib nodes.update(statement.nodes()) internalnodes = list(nodes - set(terminalnodes)) nodes = terminalnodes + internalnodes ## Create a substitution dictionary that maps node voltages ## to symbols xvector = [sympy.Symbol('x[%d]'%i) for i in range(len(nodes))] substdict = [(node.V, xsym) for node, xsym in zip(nodes, xvector)] ## Create i, u and q vectors ivector = [icontribs[node].subs(substdict) for node in nodes] qvector = [qcontribs[node].subs(substdict) for node in nodes] uvector = [ucontribs[node] for node in nodes] ## Calculate G as Jacobian of i icolvector = sympy.Matrix(ivector).T G = icolvector.jacobian(xvector) ## Calculate C as Jacobian matrix of q qcolvector = sympy.Matrix(qvector).T C = qcolvector.jacobian(xvector) CY = sympy.zeros(len(xvector)) ## Create Circuit methods ifuncstr = methodstr('i', 'x', ivector) ufuncstr = methodstr('u', 't', uvector) qfuncstr = methodstr('q', 'x', qvector) Gfuncstr = methodstr('G', 'x', G) Cfuncstr = methodstr('C', 'x', C) CYfuncstr = methodstr('CY', 'x', CY) return terminalnames, ifuncstr, ufuncstr, qfuncstr, Gfuncstr, Cfuncstr, \ CYfuncstr class BehaviouralMeta(type): def __init__(cls, name, bases, dct): if 'analog' in dct: ## Generate code for the Circuit methods as strings strings = generate_code(cls) terminalnames, ifuncstr, ufuncstr, qfuncstr, Gfuncstr, \ Cfuncstr, CYfuncstr = strings ## Create methods methodnames = ('i', 'u', 'q', 'G', 'C', 'CY') for methodname, codestring in zip(methodnames, strings[1:]): funcdef_code = compile(codestring, '<stdin>', 'exec') namespace = {'np': np} eval(funcdef_code, namespace) setattr(cls, methodname, namespace[methodname]) ## Add terminals cls.terminals = terminalnames class Behavioural(circuit.Circuit): """ Behavioral circuit model The Behavioural is an extension of the Circuit class where an analogoue circuit can be modelled at an abstract level that is similair to Verilog-A. The circuit behaviour is defined by the analog() method whose arguments are the terminal names and the voltages and currents are defined by calls to the contrib method. Example class MyResistor(Behavioural): instparams = [param.Parameter(name='r', desc='Resistance', unit='ohm')] def analog(plus, minus): b = Branch(plus, minus) return Contribution(b.I, 1/self['r'] * b.I) The i(), q(), u(), G() and C() methods are then automatically generated from symbolic analysis of the expressions given to the contrib method. Using the hdl decorator on the definition of analog() adds some syntactic sugar that makes the behavior definition look more like Verilog-A. Example class MyResistor(Behavioural): instparams = [param.Parameter(name='r', desc='Resistance', unit='ohm')] @hdl def analog(plus, minus): I(plus, minus) <= 1/self['r'] * I(plus, minus) """ __metaclass__ = BehaviouralMeta def isconstant(expr): for atom in expr.atoms(): if isinstance(atom, Quantity): return False return True class Resistor(Behavioural): instparams = [Parameter(name='r', desc='Resistance', unit='ohm')] @staticmethod def analog(plus, minus): b = Branch(plus, minus) return Contribution(b.I, 1/r * b.V + 1), if __name__ == "__main__": import doctest doctest.testmod()
/** * * @author Frank Appiah */ public class EPSHortnetq implements IEPSHornetq{ private HornetQServer hornetQServer; private IEPSMSQConfig hornetqConfig; private Configuration configuration; private Main jniServer; private InitialContext initialContext; private TransportConfiguration transportConfig; private IMSQClient sQClient; private JMSServerManager serverManager; private QueueConfiguration queueConfig; private EPSQueueManager queueManager; public EPSHortnetq() { } public EPSHortnetq(HornetQServer hornetQServer, IEPSMSQConfig hornetqConfig, Configuration configuration) { this.hornetQServer = hornetQServer; this.hornetqConfig = hornetqConfig; this.configuration = configuration; } public void setHornetqServer(HornetQServer hornetQServer) { this.hornetQServer=hornetQServer; } public HornetQServer getHornetQServer() { return this.hornetQServer; } public void setEPSHornetqConfigurator(IEPSMSQConfig hornetqConfig) { this.hornetqConfig=hornetqConfig; } public IEPSMSQConfig getEPSHornetqConfigurator() { return this.hornetqConfig; } public Configuration createConfigurator() { return this.configuration; } public Configuration createConfigurator(IEPSMSQConfig hornetqConfig) { return this.configuration; } public void setJNDIServer(Main jnpServer) { this.jniServer=jnpServer; } public Main getJNDIServer() { return this.jniServer; } public void setInitialContext(InitialContext context) { this.initialContext=context; } public InitialContext getInitialContext() { return this.initialContext; } public void setTransportConfiguration(TransportConfiguration configuration) { this.transportConfig=configuration; } public TransportConfiguration getTransportConfiguration() { return this.transportConfig; } public void setQueueConfiguration(QueueConfiguration configuration) { this.queueConfig=configuration; } public QueueConfiguration getQueueConfiguration() { return this.queueConfig; } public void setJMSServerManager(JMSServerManager serverManager) { this.serverManager=serverManager; } public JMSServerManager getJMSServerManager() { return this.serverManager; } public void setMSQClient(IMSQClient client) { this.sQClient=client; } public IMSQClient getMSQClient() { return this.sQClient; } public void setQueueManager(EPSQueueManager manager) { this.queueManager=manager; } public EPSQueueManager getQueueManager() { return this.queueManager; } public void setConfiguration(Configuration configuration) { this.configuration=configuration; } }
/* * Call SearchSelect to call callbacks, and put cursor back in original * position if putback_cursor is set. */ static void Select (Widget w, XEvent *event, String *params, Cardinal *num) { MenuShellWidget msw = (MenuShellWidget) w; (void)_Search_Select(msw); if (msw->menu.putback_cursor) XWarpPointer( XtDisplay( msw ), None, XtWindow( msw ), 0,0,0,0, msw->menu.cursor_x, msw->menu.cursor_y); }
/* * Change the owner of a type. */ void AlterTypeOwner(List* names, Oid newOwnerId, ObjectType objecttype) { TypeName* typname = NULL; Oid typeOid; Relation rel; HeapTuple tup; HeapTuple newtup; Form_pg_type typTup; AclResult aclresult; rel = heap_open(TypeRelationId, RowExclusiveLock); typname = makeTypeNameFromNameList(names); tup = LookupTypeName(NULL, typname, NULL); if (tup == NULL) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("type \"%s\" does not exist", TypeNameToString(typname)))); typeOid = typeTypeId(tup); TrForbidAccessRbObject(TypeRelationId, typeOid, NameStr(((Form_pg_type)GETSTRUCT(tup))->typname)); newtup = (HeapTuple)tableam_tops_copy_tuple(tup); ReleaseSysCache(tup); tup = newtup; typTup = (Form_pg_type)GETSTRUCT(tup); if (objecttype == OBJECT_DOMAIN && typTup->typtype != TYPTYPE_DOMAIN) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("%s is not a domain", format_type_be(typeOid)))); if (typTup->typtype == TYPTYPE_COMPOSITE && get_rel_relkind(typTup->typrelid) != RELKIND_COMPOSITE_TYPE) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("%s is a table's row type", format_type_be(typeOid)), errhint("Use ALTER TABLE instead."))); if (OidIsValid(typTup->typelem) && get_array_type(typTup->typelem) == typeOid) ereport(ERROR, (errcode(ERRCODE_WRONG_OBJECT_TYPE), errmsg("cannot alter array type %s", format_type_be(typeOid)), errhint("You can alter type %s, which will alter the array type as well.", format_type_be(typTup->typelem)))); if (typTup->typowner != newOwnerId) { if (!superuser()) { if (!pg_type_ownercheck(HeapTupleGetOid(tup), GetUserId())) aclcheck_error_type(ACLCHECK_NOT_OWNER, HeapTupleGetOid(tup)); check_is_member_of_role(GetUserId(), newOwnerId); aclresult = pg_namespace_aclcheck(typTup->typnamespace, newOwnerId, ACL_CREATE); if (aclresult != ACLCHECK_OK) aclcheck_error(aclresult, ACL_KIND_NAMESPACE, get_namespace_name(typTup->typnamespace)); } if (typTup->typtype == TYPTYPE_COMPOSITE) ATExecChangeOwner(typTup->typrelid, newOwnerId, true, AccessExclusiveLock); else { typTup->typowner = newOwnerId; simple_heap_update(rel, &tup->t_self, tup); CatalogUpdateIndexes(rel, tup); changeDependencyOnOwner(TypeRelationId, typeOid, newOwnerId); if (OidIsValid(typTup->typarray)) AlterTypeOwnerInternal(typTup->typarray, newOwnerId, false); } } heap_close(rel, RowExclusiveLock); }
A group of French conservationists have reached out to good Samaritans in the US to help them save Paris's Notre Dame Cathedral – one of France’s most visited monuments, which requires urgent repair work. ADVERTISING Read more Turning 854 years this year, Notre Dame de Paris is one of the largest and most well-known cathedrals in the world, attracting some 14 million visitors a year. But time, weather and wind have taken their toll on the unique gothic architecture, and some of the cathedral’s supporting structural elements are now at risk of crumbling. β€œThe flying buttresses are in a pretty bad state and we can’t afford them falling down because it would risk the structure of the whole cathedral. It’s urgent!” Michel Picaud, President of the Paris-based β€œFriends of Notre Dame de Paris” foundation, told FRANCE 24 in an interview on Wednesday. Aside from the main entrance, which was recently restored, large cracks have appeared across the faΓ§ade and the supporting structure holding up the cathedral’s impressive stained-glass windows could collapse in the event of a storm. β€œThe Friends of Notre Dame” foundation was established last year by the Archbishop of Paris and the Diocese of Paris in a bid to help finance the repairs of the state-owned monument after it became clear that the annual €2 million earmarked to maintain the building wasn’t nearly enough to prevent it from deteriorating beyond repair. β€œThere is no part of the building untouched by the irreparable loss of sculptural and decorative elements, let alone the alarming deterioration of structural elements,” the group said on its website. β€œThe costs are estimated at a total of €100 million,” Picaud said, noting that the work needs to be carried out within the next six to 10 years. Already, one of the cathedral’s gargoyles has partically collapsed, with another having completely fallen off, he said. American history in Paris Although a fund has already been set up in France, the foundation has recently set up another one in the United States in order to reach its fundraising target. Picaud said that aside from the fact that private American donors have a strong philanthropy tradition in general, Notre Dame Cathedral has a place of its own in American history. β€œIn World War II for example, when French and American troops liberated Paris from occupying German forces, the celebrations took place in front of Notre Dame,” he said. The idea to reach out to American donors evolved after several US visitors to Notre Dame contacted the cathedral’s management and offered to help out with financing through private means. β€œI think the Americans consider part of the history that took place in Europe as part of their own,” Picaud explained. When Andrew Tallon, co-author of the book β€œNotre-Dame de Paris” and associate professor of art at Vassar College in the state of New York, highlighted the possibilities of targeting private American donors, the real work of crossing the Atlantic for funds began. Picaud said that a first fundraiser would be held in the Parisian cathedral itself in November this year, and in April, 2018, the β€œFriends of Notre Dame” will embark on a US roadshow, with events planned in Boston, Chicago, Houston, Los Angeles and Washington, DC. The roadshow will include keynote speakers and a photo exhibition of the history of the famed cathedral. In all, β€œThe Friends of Notre Dame” aim to raise enough funds to repair and restore the gargoyles, the pinnacles, the finials, crockets and railings, as well as the stonework, the stained-glass windows, the spire and the flying buttresses. Outside financial help is nothing new to the Gothic cathedral, which was built between 1160 and 1345 and is located by the River Seine on the Île de la CitΓ© in central Paris. In 2013, it was equipped with new nine new bells thanks to private donors and in 2014, Russia helped fund the cathedral's annual Christmas tree after the parish failed to reach its financial goals.
<reponame>nanogiants/vue3-packages export { vVisible } from './v-visible';
n,s=map(int,input().split()) a=[] for i in range(n): q=list(map(int,input().split())) a.append(q[0]*60+q[1]) if a[0]>s: print(0,0) exit() for j in range(1440): for i in range(n-1): if a[i]+s<j<a[i+1]-s: print(j//60,j%60) exit() j=a[n-1]+s+1 print(j//60,j%60)
package org.springframework.samples.petclinic.product; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; @SpringBootTest(classes = {ProductDataHandlerImpl.class, ProductServiceImpl.class}) //@ExtendWith(SpringExtension.class) //@Import({ProductDataHandlerImpl.class, ProductServiceImpl.class}) class ProductServiceImplTest { @MockBean ProductDataHandler productDataHandler; @Autowired ProductService productService; @Test public void getProductTest() { //given Mockito.when(productDataHandler.getProductEntity("123")) .thenReturn(new ProductEntity("123", "pen", 2000, 3000)); //when //verify ProductDto productDto = productService.getProduct("123"); assertThat(productDto.getProductId()).isEqualTo("123"); assertThat(productDto.getProductName()).isEqualTo("pen"); assertThat(productDto.getProductPrice()).isEqualTo(2000); assertThat(productDto.getProductStock()).isEqualTo(3000); verify(productDataHandler).getProductEntity("123"); } @Test public void saveProductTest() { //given Mockito.when(productDataHandler.saveProductEntity("123", "pen", 2000, 3000)) .thenReturn(new ProductEntity("123", "pen", 2000, 3000)); ProductDto productDto = productService.saveProduct("123", "pen", 2000, 3000); Assertions.assertEquals(productDto.getProductId(), "123"); Assertions.assertEquals(productDto.getProductName(), "pen"); Assertions.assertEquals(productDto.getProductPrice(), 2000); Assertions.assertEquals(productDto.getProductStock(), 3000); verify(productDataHandler).saveProductEntity("123", "pen", 2000, 3000); } }
/** * ipa_sps_irq_tx_no_aggr_notify() - Callback function which will be called by * the SPS driver after a Tx operation is complete. * Called in an interrupt context. * @notify: SPS driver supplied notification struct * * This function defer the work for this event to the tx workqueue. * This event will be later handled by ipa_write_done. */ static void ipa_sps_irq_tx_no_aggr_notify(struct sps_event_notify *notify) { struct ipa_tx_pkt_wrapper *tx_pkt; IPADBG("event %d notified\n", notify->event_id); switch (notify->event_id) { case SPS_EVENT_EOT: tx_pkt = notify->data.transfer.user; queue_work(tx_pkt->sys->wq, &tx_pkt->work); break; default: IPAERR("recieved unexpected event id %d\n", notify->event_id); } }
//============================================================================= // e3group_display_ordered_countobjectsoftype : // Ordered Display count objects of type method. //----------------------------------------------------------------------------- static TQ3Status e3group_display_ordered_countobjectsoftype(TQ3GroupObject group, TQ3ObjectType isType, TQ3Uns32 *number) { TQ3GroupPosition pos; TQ3Status theStatus = e3group_display_ordered_getfirstpositionoftype( group, isType, &pos ); *number = 0; if ( (theStatus == kQ3Success) && (pos != nullptr) ) { *number = 1; while ( e3group_display_ordered_getnextpositionoftype( group, isType, &pos ) && (pos != nullptr) ) { *number += 1; } } return theStatus; }
package controllers import ( "github.com/zenazn/goji/web" "gopkg.in/mgo.v2" ) // InitControllers initialize all controllers func InitControllers(mux *web.Mux, database *mgo.Database) { NewTokenController(mux, database) }
package com.tenda.json.pojo; import java.io.Serializable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; public class Hibernate implements Serializable { @SerializedName("driver") @Expose private String driver; @SerializedName("dialect") @Expose private String dialect; @SerializedName("HBM2DDL_AUTO") @Expose private String hBM2DDLAUTO; @SerializedName("SHOW_SQL") @Expose private Boolean sHOWSQL; private final static long serialVersionUID = -6096396637206640794L; public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public String getDialect() { return dialect; } public void setDialect(String dialect) { this.dialect = dialect; } public String getHBM2DDLAUTO() { return hBM2DDLAUTO; } public void setHBM2DDLAUTO(String hBM2DDLAUTO) { this.hBM2DDLAUTO = hBM2DDLAUTO; } public Boolean getSHOWSQL() { return sHOWSQL; } public void setSHOWSQL(Boolean sHOWSQL) { this.sHOWSQL = sHOWSQL; } @Override public String toString() { return new ToStringBuilder(this).append("driver", driver).append("dialect", dialect).append("hBM2DDLAUTO", hBM2DDLAUTO).append("sHOWSQL", sHOWSQL).toString(); } @Override public int hashCode() { return new HashCodeBuilder().append(sHOWSQL).append(dialect).append(hBM2DDLAUTO).append(driver).toHashCode(); } @Override public boolean equals(Object other) { if (other == this) { return true; } if ((other instanceof Hibernate) == false) { return false; } Hibernate rhs = ((Hibernate) other); return new EqualsBuilder().append(sHOWSQL, rhs.sHOWSQL).append(dialect, rhs.dialect).append(hBM2DDLAUTO, rhs.hBM2DDLAUTO).append(driver, rhs.driver).isEquals(); } }
CLEVELAND, Ohio -- The jury that convicted East Cleveland serial killer Michael Madison began hearing evidence Thursday as it is now tasked with deciding whether to recommend his execution. The jury will hear from three psychologists who will describe how Madison's troubled childhood influenced his killing of three young women, part of a mitigation phase where Madison's defense attorneys try to convince a jury not to recommend a death sentence. "During the course of this hearing you will learn that Mike Madison, almost from birth, was on a predictable life trajectory that placed him where he sits today," defense attorney David Grant told the jury. Between October 2012 and July 2013, Madison strangled three women. He folded them in half and stuffed them into garbage bags, stashing the corpses near his apartment at the corner of Hayden and Shaw avenues. Previous coverage: Prosecutors open trial with details of mutilated bodies Madison's journey to the courtroom started long before 2012, Grant told the jury. Rather, the murders of Shirellda Terry, 18, Shetisha Sheeley, 28 and Angela Deskins, were part of a horror story that started when Madison was born. Madison was born October 15, 1977 to Diane Madison and John Baldwin, the result of an accidental pregnancy. Baldwin denied that he was Michael Madison's father, and never became a part of his life. Michael Madison's mother was ill-equipped to raise him from the beginning, Grant said, in part because of her own troubled childhood. Her mother left her father when she was young, eventually became a heroin addict and worked as a prostitute. As a single mother, Diane Madison rarely invited other children over to play with him and never took him to meet other children, Grant said. Holidays and birthdays often passed without fanfare or even notice. Michael Madison's early relationships were limited to his mother, her numerous transient boyfriends who disciplined him and a half-brother, Grant said. In 1980, when he was two years old, child and family services discovered that young Michael's mother had stuffed food down his throat causing him to vomit, Grant said. When he vomited, she put him in a tub of hot water. When he screamed, she took him out and beat him with an extension cord. Later that year, child and family services were again called to their home, his attorney said. Reports say that he had a large bruise and an injury on his forehead, requiring treatment at Mt. Sinai Hospital. Six months later, at age 3, one of Diane Madison's boyfriends beat Michael Madison so badly with a belt that he started vomiting and had to be hospitalized. "There was a time he was beaten so severely by a boyfriend of his mother that he lost hearing in one ear," forensic psychologist Dr. Daniel L. Davis said. Reports from social workers showed that he suffered contusions, abrasions and swelling on the shaft of his penis. Child services took him away from his mother. "Unfortunately they placed him with (his grandmother), who was a former prostitute and heroin addict," Grant said. After she received counseling, authorities returned Michael Madison to his mother's care. Still, the boy was a frequent patient at Mt. Sinai Hospital. In 1982 he was hospitalized with dehydration. A year later, social workers reported bruises and scratches on him and his half-brother. Michael Madison had little recollection of the early abuse, other than being trapped in a long room with one of his mother's boyfriends. That is not unusual for young victims, Davis told the jury. While he never recalled the extent of the abuse, psychological experts believe the helplessness and lack of nurturing relationships with adults led him to develop an alternate world in his mind where he could take control of his life. That disassociation with his childhood abuse fueled hatred toward women. Previous coverage: "I don't want this to be for nothing" He regularly lashed out at any form of female authority, according to the earlier testimony of two former girlfriends. He told one of them that he "hates the female species." As he grew, Michael Madison's inability to socialize with others got him in trouble. He was nomadic by the time he was 16 sleeping anywhere he could. At 17, he was charged with delinquency for inappropriately touching a classmate. At 20, he was sentenced jail for drug abuse. Several years later was convicted of rape. Madison was ruled competent to stand trial, meaning court psychologists believe he is able to distinguish the difference between right and wrong. A psychologist also cleared Madison of any mental illness or defects. Madison's violent upbringing left him without any moral compass, Grant said. Davis described generational patterns of abuse, so pervasive that they left Madison with no foundation other than violence. "This individual had no foundation on which to make the proper choices," Grant told the jury. "The evidence will show that Mike's life was further influenced by a disturbed family tree, comprised of generations of physical abusers, sex abusers. Literally, a family tree of abuse." If the jury recommends death, Cuyahoga County Common Pleas Judge Nancy McDonnell will have the ultimate say on whether or not to execute him or send him to life in prison.
import { Component, DebugElement, Input } from '@angular/core'; import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { CmsNavigationComponent } from '@spartacus/core'; import { CmsComponentData, NavigationNode, NavigationService, } from '@spartacus/storefront'; import { of } from 'rxjs'; import { FSNavigationComponent } from './navigation.component'; import createSpy = jasmine.createSpy; @Component({ selector: 'cx-fs-navigation-ui', template: '', }) class MockNavigationUIComponent { @Input() dropdownMode = 'list'; @Input() node: NavigationNode; } const mockCmsComponentData = <CmsNavigationComponent>{ styleClass: 'footer-styling', }; const MockCmsNavigationComponent = <CmsComponentData<any>>{ data$: of(mockCmsComponentData), }; describe('FSNavigationComponent', () => { let navigationComponent: FSNavigationComponent; let fixture: ComponentFixture<FSNavigationComponent>; let element: DebugElement; const mockNavigationService = { createNavigation: createSpy().and.returnValue(of(null)), }; beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ providers: [ { provide: NavigationService, useValue: mockNavigationService, }, { provide: CmsComponentData, useValue: MockCmsNavigationComponent, }, ], declarations: [FSNavigationComponent, MockNavigationUIComponent], }).compileComponents(); }) ); beforeEach(() => { fixture = TestBed.createComponent(FSNavigationComponent); navigationComponent = fixture.componentInstance; element = fixture.debugElement; fixture.detectChanges(); }); it('should be created', () => { expect(navigationComponent).toBeTruthy(); }); it('should add the component styleClass', () => { const navigationUI = element.query(By.css('cx-fs-navigation-ui')); expect(navigationUI.nativeElement.classList).toContain('footer-styling'); }); });
/** * This class tests the {@link BasicTokenBasedUrlGenerator} class. */ public class BasicTokenBasedUrlGeneratorTest { private Context context = InstrumentationRegistry.getTargetContext(); /** * Tests the {@link BasicTokenBasedUrlGenerator#createInstance(Context)} method. Validates * that the instance created is valid. */ @Test public void createInstanceTest() throws AObjectCreator.ObjectCreatorException, AUrlGenerator .UrlGeneratorException { assertNotNull(BasicTokenBasedUrlGenerator.createInstance(context)); assertTrue(BasicTokenBasedUrlGenerator.createInstance(context) instanceof BasicTokenBasedUrlGenerator); } /** * Tests the {@link BasicTokenBasedUrlGenerator#getUrl(Map)} method for the positive case * with a base url and a token generation url present in params. */ @Test public void testGetUrlWithKeysInParams() throws AObjectCreator .ObjectCreatorException, AUrlGenerator.UrlGeneratorException, IOException { BasicTokenBasedUrlGenerator urlGenerator = new BasicTokenBasedUrlGenerator(context); BasicTokenBasedUrlGenerator spyUrlGenerator = spy(urlGenerator); doReturn("token").when(spyUrlGenerator).requestToken("tokenGenerationUrl"); Map<String, String> params = new HashMap<>(); params.put(BasicTokenBasedUrlGenerator.BASE_URL, "baseUrlPrefix$$token$$baseUrlSuffix"); params.put(BasicTokenBasedUrlGenerator.TOKEN_GENERATION_URL, "tokenGenerationUrl"); String url = spyUrlGenerator.getUrl(params); assertEquals("baseUrlPrefixtokenbaseUrlSuffix", url); } /** * Tests the {@link BasicTokenBasedUrlGenerator#getUrl(Map)} method for the positive case with * a base url and a token generation url not present in params */ @Test public void testGetUrlWithKeysNotInParams() throws AObjectCreator .ObjectCreatorException, AUrlGenerator.UrlGeneratorException, IOException { BasicTokenBasedUrlGenerator urlGenerator = new BasicTokenBasedUrlGenerator(context); BasicTokenBasedUrlGenerator spyUrlGenerator = spy(urlGenerator); doReturn("token").when(spyUrlGenerator).requestToken("config_token_generation_url"); Map<String, String> params = new HashMap<>(); String url = spyUrlGenerator.getUrl(params); assertEquals("config_base_urltokenconfig_base_url_postfix", url); } /** * Tests the {@link BasicTokenBasedUrlGenerator#getUrl(Map)} method for the negative case with * an incorrect token url passed in params. */ @Test(expected = AUrlGenerator.UrlGeneratorException.class) public void testGetUrlWithIncorrectTokenUrl() throws AObjectCreator.ObjectCreatorException, AUrlGenerator.UrlGeneratorException { BasicTokenBasedUrlGenerator urlGenerator = new BasicTokenBasedUrlGenerator(context); Map<String, String> params = new HashMap<>(); params.put(BasicTokenBasedUrlGenerator.BASE_URL, "baseUrl"); params.put(BasicTokenBasedUrlGenerator.TOKEN_GENERATION_URL, "token"); urlGenerator.getUrl(params); } }
def notify_spool(): while True: with self._notify.get_direct() as msg: notification = return_packer.unpack(msg) if len(notification) == 3: with self._open_reqs() as open_reqs: req_id, dtype, shape = notification open_reqs[req_id]._notify(np.dtype(dtype), shape) if notify is not None: notify(open_reqs[req_id]) del open_reqs[req_id] else: notification = notification[0] if notification is QueueClosed: if notify is not None: notify(QueueClosed) with self._open_reqs() as open_reqs: for key in open_reqs.keys(): open_reqs[key]._notify(None, None, signals.QueueClosedException("This reader has been closed.")) open_reqs.clear() break elif isinstance(notification, Exception): e = notification if e.__req_id__ is None: with self._open_reqs() as open_reqs: for key in open_reqs.keys(): open_reqs[key]._notify(None, None, e) open_reqs.clear() self.close() raise signals.CreateSubprocessException(e) else: with self._open_reqs() as open_reqs: open_reqs[e.__req_id__]._notify(None, None, e) del open_reqs[e.__req_id__]
//! Definitions for supported Continuous Integration environments use crate::Context; mod circle; mod travis; impl Context { /// Try to generate a Context by sniffing the environment /// /// This will call the available CI sniffers in turn. pub fn from_env() -> Option<Self> { if let Some(travis) = travis::Env::from_env() { return Some(travis.into()); } if let Some(circle) = circle::Env::from_env() { return Some(circle.into()); } None } }
0:33 Intro. [Recording date: September 29, 2014.] Russ: You're often credited with launching growth theory, a claim you modestly dismiss. But, talk about your papers a long time ago in the 1950s, that at least launched, if not growth theory, your contributions to that theory. What were you trying to achieve, and what can we learn from that work? Guest: I think the thing to remember, if anyone can remember that far back, is that in the aftermath of the Second World War, questions about growth, about growth in various parts of the world, were in everybody's mind. Now, some of that became talk about economic development, and I, as a young economist, had no real understanding of what went on in underdeveloped countries. But I was interested in what governs--like and I was interested like everybody else--in what governs the long-term growth of an economy and why some industrial economies grow faster than others. And what there was on offer in economics was the work of Roy Harrod and Evsey Domar; and the way they had developed an understanding of economic growth had a very peculiar aspect to it, which was that the long-term growth path of an industrial economy tended to be unstable. Intrinsically unstable. And I'm not speaking now just of the fact of business cycles that everyone accepts, but the notion that the reasonably smooth growth was not an attractor for the economy. It didn't tend to be a normal state of affairs, but something that if you got anywhere near it, most of the pressure was to move away. And that seemed to me not to characterize the long-term history of modern industrial capitalism. Even the Depression of the 1930s was a depression. And it ended in the War for perfectly understandable reasons. So, I started to think about that. And there are a lot of ways one could have gone at that question, but I went at it by trying to think about the varying capital intensity of growth, the fact that if an economy that saves a lot can afford to have a capital-intense, highly capitalized kind of production, an economy that doesn't save very much can still grow, but would grow in a more labor-intensive way. So I tried to work that out using fairly standard economic ideas. And it worked out. It worked out in the sense that there was a neat way of representing that and thinking about it. And not only that, but it produced a startling result. The theory seemed to lead in a direction that I certainly hadn't anticipated, which was--and this was rather different from Harrod and Domar indicate in their way--what turned out was that the volume of saving, and therefore capital investment, was not a determinant of the long-term rate of growth. It was a determinant of whether that growth path was high or low. A country that successfully saved an invested a lot would be richer than a country that only managed to save and invest a small amount. But the growth rates would depend entirely on the demography, the rate at which the population and the labor force were growing; and on, in the broadest sense, technological progress. And what I mean by 'broadest sense' was I wasn't thinking primarily--well the truth is, I was thinking algebraically, not in terms of images--but not necessarily mechanical invention, but organizational inventions and things like that. But in any case, it turned out that the long-term rate of growth was a matter of demography and technological progress. 6:20 Russ: And this work launched a large literature. Guest: Oh, yeah. It did catch on. I think it caught on because it was neat and simple and it seemed to lead somewhere. It led to things that you hadn't thought about casually. And then, immediately after doing that, I started looking at data for the United States. And it's amazing to think about now, but what I was able to find, for the numbers that I needed to put flesh on that theory, covered the period in the United States from 1909 to 1949. A mere 40 years. And not a very long stretch. But when I analyzed those time series, those data, it turned out that what the history of that period seemed to be saying was that in fact, almost all--more than 80%--of the long-term average growth of output per person, or income per person, could be traced to this broad sense of technology progress. And that even between 1909 and 1949, very little of the fairly enormous improvement in income per head and the standard of living in the United States, even over that period, only a relatively small amount came from the nitty gritty of saving and investment. And more than [?] that you could track, at least the way I devised to track it, you could track to what an economist calls[?] shifts in the production function. Which translates in the capacity to get more output per unit of input--technology progress in the broadest sense. So, that's what I did then. And it did catch on and people worked at it, both of these aspects: the model building and empirical things. For instance, just to give one example, a good friend of mine, Padma Desai, tried to use the empirical apparatus. She was a student of the Soviet Union, what was then the Soviet Union. And what she found was that, unlike the United States--and by the way, you might remember that in the Post-War years, the fact that the Soviet economy was eventually going to collapse was not so clear, and Khrushchev's remark about how we'll bury you, and he meant economically--but Padma Desai found that the Soviet Union was just the reverse of the United States, and that what increases in income per person had been achieved there, had been achieved by grinding down consumption and investing in heavy industry, especially an enormous amount of the national income. Which suggested right away that over the long haul, Khrushchev was not going to bury us, but the other way around. Which turned out to be the case. So, this got to be a popular thing. And of course other people worked at it, and either improved it or at least elaborated it. And that goes on today. You pick up a textbook in macroeconomics or in growth theory and you find, starting with the model the way I [?] started doing it, an enormous amount of elaboration that goes on with that. 11:07 Russ: So, I have the great disadvantage--and advantage--of being first of all many years removed from studying your model in graduate school--which of course I did, in the late 1970s. But I haven't thought much about growth theory. I've thought a lot about growth and I've interviewed a lot of people about growth on this program. And the first thought that comes to me as a naive economist is one that I know you're aware of, which is: Well, then the question is, where does technological progress come from? Where does this ability to get more from less come from? And one of the thoughts that I think inevitably crosses one's mind is it comes from that investment. So, explain how that--in other words, if you have no investment, if you have no savings, if all you do is consume your current product, it seems difficult to shift the production possibility frontier or to change the production function, or to speak in laymen's terms, to get technological change. So, in your mind, both then and now, where does technological change, where does productivity come from? Guest: Well, that's not an easy thing to pin down. Technological change itself, I think, comes from, at the beginning, Research and Development activity. In a capitalist economy, our economy, business firms are always looking for an advantage, or looking for a way to increase their profits to get ahead of the competition, if there is competition. And one of the ways they try to do that is to improve, is to reduce costs--put it that way. To find cheaper ways of producing what they now produce. And another path toward improving profits and gaining competitive advantage is by inventing, designing newer and better products. Now, here I want to digress for a minute. It occurred to me very early on, and I wrote about this, that new technology often needs ordinary plain vanilla capital investment in order to become real. If you design a new way to produce whatever you are producing, it may be the case that in order to actually make good, perform, on that new method, you need different machinery, different factory layout. You need ordinary capital investment. And I tried, and succeeded in a way, very early on, in working out a way of incorporating this fact in the theory. The interesting thing is that it still turned out, when you looked at the very long run, that it was still the rate of technological improvement that governed the long term, really long term, rate of growth. And the explanation for this turned out to be that what you can--if you are trying to conceptualize this, if you are trying to think about it--the fact that you need ordinary capital investment to embody, to really have--make good on--make a new technology effective, what you are really doing is making the age distribution of the stock of capital goods, you are shifting it toward the younger end. You can think of the population of machinery and capital goods like a human population, as having an age distribution. Young ones, then middle age ones, and eventually old enough to either be obsolete or physically useless. And what this connection between new technology and plain vanilla capital investment says that in order to move toward a newer technology you have to make the age distribution of the stock of capital goods shift in the younger direction. That can't go on forever. There are limits to the capacity of any economy to product young capital goods, just as there are limits to a human population's capacity to produce young kids. And in the long enough run, what this--when you incorporate this in the story, you don't change the story about the long-term, the permanent rate of growth. But you do change the mechanics of it. So, in the end, I think what you have to say, or as it seems to me, is that the source of technological change is research and development; and then a little beyond that, the act of--I was a student of Joseph Schumpeter's, among others. And he has this half-mystical, half-real thing about innovation and entrepreneurship, as distinct from mere technological maneuvering and an entrepreneur is somewhat different from an engineer or different from an inventor, actually. And I think all that does play a role. We understand very little about innovation as distinct from the development of science and the development even of technology. But that's where the source of it all is--it's creativity and all that. And creativity is motivated, you know, in part by just sheer playfulness, the way people are, but also in very large part by the search for profit and for competitive advantage. Russ: And as you point out-- Guest: So, if you want to encourage long-term growth, somehow you've got to encourage both technological innovation and innovation. Russ: When I used to teach microeconomics, I would give a poor person's version of growth in trying to capture how our standard of living is improved over time by the fact that cost curves shift down. Firms find new ways to make stuff cheaper, the same quality at a lower cost. And through competition, to the extent there is competition, they are forced to pass those savings on to customers. That model, which I think a lot of us teach some version of in micro, doesn't capture the more revolutionary idea of finding a new way to serve that desire that is totally different. It's cheaper in some dimension, but calling it cheaper doesn't really do justice to it. Guest: Yeah. That's right. In later work, I'm doing all this as a theorist, as a modeler. I try to work out a story in which there are big-time major improvements, and then once one of those takes place, it creates an opportunity for a lot of small further improvements. And I think the story of technological progress is a lot like that. One of the things it means, of course, is that it's very rare for even apart from business cycles, it's rare for growth to be smoothly exponential, x% per year forever. There are going to be changes in the rate of growth as these major inventions occur and as experience with the major inventions allows improvement. I spent some time, by the way, a number of years on a science advisory committee to a big automobile company. And one of the pieces of enlightenment that came to me then was to realize how much day-to-day technological progress doesn't involve Research and Development people. It occurs on the shop floor. Russ: Tinkering. Guest: Yes. Somebody realizes, You know, we could attach the bumper to the chassis just as securely using many fewer fasteners than we are using now if we did it this way rather than that way. And if it works out, that lowers costs. That's an improvement in productivity and the research laboratory never thought of anything to do with it. It's done by some foreman, and by trial and error. 21:26 Russ: Talk about the work of Paul Romer in endogenous growth theory. Guest: Yeah. That's really interesting. It's interesting both in itself and as part of the history of economics. Paul Romer, a very bright guy, had the notion to try to make a fairly precise model, that is a step-by-step theory of profit motivated innovation. And this got to be popular under the name, under the label of endogenous growth theory. Endogenous meaning that you don't depend on some, as I did, on some poorly understood process of changing, improving technology, improving product, and improving productivity; but you treat creating higher productivity as itself a business, with the costs and payoffs. And you try to incorporate that in the whole story of economic growth. And it was interesting--for me it was sort of amusing in a way because people would say to me: How could you have been so stupid as not to realize that making technological improvements is itself an economic process? To which my answer was: Of course I understood--I knew that; I just had no idea how to think about it. So naturally I didn't think about it. But Romer and a number of other economists after him--and actually, a one-time colleague of mine, Karl Shell, had actually written some papers doing the same thing a decade or two before. This was an idea that was a natural for economics. And so Paul Romer and his [?]school that sprung up doing that--there was a whole proliferation of models of this kind. The interest in that seems to have fallen away. And Paul Romer himself has gone on to other things. And in a way, I almost feel as if the story of endogenous growth theory, of treating innovation, technological innovation as a business process itself, is hard. Russ: Yeah. Guest: It's just not something that [?] to theorize about it; to make a theory of it requires you have to just choose one way of looking at it, and in fact it must happen in a million different ways. And so I don't--it seems to me that endogenous growth theory didn't fulfill the promise that we all expected it would have. And there's not as much interest in it now as there was before because of the realization that it didn't unlock anything interesting that was really terribly useful. But, you know, some smart person may yet find a good way of analyzing that process. We all know that a lot of the innovation occurs as a business process. I keep telling myself we also all know that a lot of innovation comes as a matter of dumb luck. Russ: Yep. Trial and error. Guest: You set out to solve problem A, and you fail totally to solve problem A, but you solve problem B that wasn't in your head at all. And so, I don't know that we're going to get very far down that path[?]. Russ: Yeah. It seems to me it was a nice descriptive theory, but it has not, it seems to me--maybe I'm wrong--led to a much deeper understanding than Schumpeter, which you alluded to earlier. 26:25 Russ: Now, in 1987 you famously said, You can see the computer age everywhere but in the productivity statistics. Has the investment in computing made a big difference? A small difference? And have we been able to measure it? Have things changed? Guest: Yeah, that line of mine, which was in a book review in a newspaper, gets talked about more than anything else. Russ: Yeah. Sorry. Guest: Well, that's all right. It's interesting: it was true when I said it. There was talk, and the book I was reviewing at the time was talking about the vast computer revolution and how it changed our lives; and, as I said, we were all very conscious that there were computers and things were going differently. But there was no measured increase in productivity. Well, over the years, there came a measured increase in productivity. And when that happened, it happened in an interesting way. It turned out when there were first clear indications, maybe 8 or 10 years later, of improvements in productivity on a national scale that could be traced to computers statistically, it turned out a large part of those gains came not in the use of the computer, but in the production of computers. Because the cost of an item of computing machinery was falling like a stone, and the quality was at the same time, the capacity at the same time was improving. And people were buying a lot of computers, so this was not a trivial industry, although not an abnormal [?] industry at the time. And you got big productivity gains in the production of computers and [?] and whatnot. But you could also begin to see productivity improvements on a national scale that traced to the use of computers. Interestingly, I got involved in some work, quite a lot of work, actually, with the McKinsey Global Institute, and we discovered that on the national scale, an awful lot of the improvements or the acceleration of the productivity trends that came from computers, came, surprisingly, in wholesale and retail industry. It was not the most sophisticated [?] use of the computer, but it gave you small improvements in output per person, and there are an awful lot of persons working in the retail level sale trade. Russ: The control of inventory costs just as an example was incredible. Guest: Yeah. Inventory costs; at checkout counters. All kinds of gains. And so, eventually you got to see the computer also in the productivity statistics. And you still do. Now the question is, today, this doesn't involve me any more, particularly, but as an observer: today there are beginning to be questions as to whether the main productivity gains from information technology may not be behind us. May not have passed. And the low-hanging fruit so to speak have already been plucked. And what we're doing now is refinement. And so, maybe the decades of substantial gains in productivity as a consequence of information technology and computational capacity have gone by. But I don't know about that. Russ: What do you think about this issue--we've talked about this on EconTalk before--that many of the benefits of the computer revolution and the Internet are not particularly monetary? So, for example, Wikipedia, Facebook, Twitter, Google, just to pick four off the top of my head. I don't think I pay anything for any of those directly: obviously I can pay indirectly in the form of higher costs due to advertising and other things. But the change in the quality of my life from those things is very hard to measure; but it's very large. Guest: Yes. All we can do is measure GDP (Gross Domestic Product). On the other hand, keep in mind that the fact that a large part of the benefits, of the human benefits, from standard-of-living type benefits, from information technology are free and are not measured in GDP--that kind of thing is not new with information technology. My friend Bob Gordon will remind you that an awful lot of the benefits from the invention of the flush toilet don't get measured in GDP either. Russ: That's correct. Guest: And most inventions, I suppose, create what economists call 'consumer surplus.' That is, benefits beyond what you actually have to pay for. And we always seem to be impressed with what is happening to us now; but there was a time when what was happening to us now was that sewage didn't run in the streets, and they didn't stink, and you didn't get sick. And those things also weren't priced in GDP. I think that's the moot[?] point, [?] no doubt prove what is significant. 33:00 Russ: Let me ask you about your friend Bob Gordon, and Tyler Cowen and others who have--and recently Larry Summers--we're reading that we're in some period of possibly extended stagnation. Tyler's a little more optimistic, in the longer run. But some have suggested we've picked the low-hanging fruit. Others say that's absurd: there are enormous unimagined gains coming from innovations we just can't foresee. What are your thoughts on that? Guest: Well, I don't know. What am I to say, or what is anybody to say, when I'm told that there are gains coming that are unimagined--and unimaginable? If they're unimaginable, I can't imagine them. It might happen. Russ: You bet. Guest: The fact that I can't say what they might be, that comes from the fact that they're unimaginable. But some you can see--or you can see the potential of. But then you have to worry about their significance. For instance, you are now speaking to a 90-year old retired economist. The extension of the lifetime, of the longevity of people, that could continue still further. I think biologists and medical people have some notion that there is a maximum length to human life somewhere around 130; but I'm not even sure about that. It could be like taxi cabs--every part will be replaced but at least the name remains the same. But you could imagine that there will be, over the next decade, when my children and grandchildren are still around, there will be gains in longevity beyond the very substantial gains that we have. I never expected to live to be 90 and be talking on the phone to you, for that matter. So, they could live longer. You want, hope that they'll live a lot longer productive lives, as well, or at least enjoy their lives as well. And that's hard to foresee. So I don't really know how to answer the people who say, You shouldn't worry about the possibility of a much lower growth of capacity, of potential output in the future because there will be these marvelous technological changes that nobody can think of. If nobody can think of them, then you can't think of them. But that doesn't mean they won't happen. They might. But I don't know what--you're just testing whether you are an optimist or a pessimist. Russ: Yeah. I think there's a lot of truth to that. But as you point out, to combine your earlier remark to what you just said, we do see credible increases and effective changes in Research and Development in the biotech world that do promise to create some serious changes in our life in a good way. So, I am an optimist, I guess. That's probably why I'm not so worried. 36:35 Russ: Now, let's shift gears a little bit. We'll get a little more contentious here. You've written recently that Milton Friedman was "bad for economics and bad for society." I want to leave out the society part for the moment; I want to focus on the economics part. Why do you think he was bad for economics? His contributions to the role of money in the economy, his skepticism about the Phillips Curve and the ability to fine-tune the economy--those seem to be kind of good for economics. Do you disagree? Guest: No. Well, the question was a little different. I have no interest at all in denying that Milton Friedman who was a friend made contributions to economics. What I was being asked about was the--the question was asked in this form: 'Why is there no Milton Friedman today?' Well, that can't mean--the question couldn't have meant 'Why is there nobody contributing to our analysis of consumer expenditure or contributing to our analysis of monetary policy,' and so on, because the woods are full of people who are doing that. What the question meant, and the question that I was answering, in my mind, was the things that set Milton as different from other economists; and in particular the fact that, in my mind, he was not given to doubt. And he was--the problem was that I thought an awful lot of other economists' time got spent in either real or side-table debates with Milton over broad issues of economic policy. Very broad issues of economic policy. Russ: Philosophy. Guest: Yeah, philosophy. That seemed to be a diversion, getting nowhere. And so, that's the sort of thing I had in mind. I think that--I'm perfectly happy to have arguments about monetary policy: is a constant rate of growth of the money supply a good target to give the Federal Reserve, or should you do something else? Does the globalization of finance affect the way you would instruct your Central Bank to behave? Should you license taxi cabs in New York City? All of those are questions that I'm perfectly happy to have people discuss and was perfectly happy to have Milton discuss. What I was against was the question, 'Why is there no Milton Friedman today?' is a little bit like the question, 'Why is there no Joan of Arc today?' Or whatever. And that side of Milton, as the ideologue, I thought was a waste for economics and diverted people from doing their daily jobs. Russ: Yeah, that question was raised by the Econ Journal Watch. We'll put a link up to that issue and to your contribution to it. I guess I'd have to say that I think there is a Milton Friedman alive today, of the kind you are talking about: his name is Paul Krugman. And he is also a man who is fairly free of doubt. When I say 'another Milton Friedman,' I'm talking about someone who speaks to the masses about public policy generally as well as some arcane economics and makes it accessible. Milton had many distinctive aspects, but that I think was what was particularly unusual about him. As you said, there are many great economic theorists, empirical economists; but the people who can combine their economic understanding and then speak to a general audience is only a handful of people who have been able to do that. Paul Samuelson was one. Paul Krugman is doing it today--but he isn't doing it from a free market perspective. And so in that sense he's not another Milton Friedman, I guess. Guest: By the way, Paul Samuelson, who I knew infinitely well, who was my closest friend, was utterly different from Milton in the respect that Paul Samuelson always had doubts about the truth of what he was saying. Paul was never a sort of person--in fact he changed his mind quite frequently. Something that I think Milton did not do. So, the art of speaking to a broad public with a foundation in solid economics is a very difficult art, and not many people can do it at all, and even fewer can do it well, I guess. But that's a little different from the lack of any skepticism, the ideological drive. I think there's a difference there. Russ: Well, let me defend Milton for a second; and then we'll move on. Unless you want to hit back. I think Paul Krugman, and Paul Samuelson, yourself, me--just about every economist--has an ideology. I do agree with you that Milton was very confident in his principles, and often confident in the application of those principles. So I take that as a legitimate criticism. But I think you have to consider the fact of where he was coming from. When you are a voice in the wilderness--and he was an extraordinarily lonely voice for a very long time, both philosophically and in terms of economic theory: for example in thinking about the importance of money--you do have to have perhaps a different public persona in how you present your ideas if you want to dent the consciousness of both the profession and the public. And he did that successfully. I think that was a good thing. But I can understand you might disagree. But I suspect his jovial confidence--which definitely was part of his demeanor--was a marketing point for him, as much as anything else. It may have been a personality trait as well, to deal with it. Guest: Well, I accept that it's a marketing point. I think that's right. And marketing is not something that's--the marketing of ideas is an activity that's very iffy. We all know that people who market snake oil, for instance, or market goods, are not above fooling the consumer, the customer. And we like to think that people who market ideas don't do that. And so I don't have much faith in the marketing faith[?]. I don't have much attraction to the marketing analogy at all. But I really don't want to argue about--Milton and St. Peter handle this between them as partners[?]. Russ: Uh, yeah. I'm not sure he's going to be seeing St. Peter, but not because he's heading south. 44:51 Russ: Anyway, let's talk about Keynes. You've written that Keynes's General Theory is one of the great contributions of the last 100 years. It certainly is one of the most influential; I would say it's the most influential economics work of the last 100 years. For those of us who are skeptics--of the value, rather than the impact--of Keynes's theories, what evidence might one provide to convince us? I'm really asking a broader question, which is: Why is there so much disagreement in macroeconomics over the most fundamental things? Guest: Well--the question about Keynes and the question about why there's disagreement are separate questions. Let me--I'm going to say one minute on Keynes; and then a few more minutes on the other question. What I think that in the broadest sense, the truest significance of Keynes can be stated fairly simply: For most of the history of economics there was no careful distinction drawn between the capacity of the economy to produce goods and services, and the willingness, or the ability, of the economy to sell those goods and services--to get them bought and consumed. And what, in 1936, in the middle of the Great Depression, what Keynes's fundamental achievement as far as I'm concerned--and it changed economics forever, in my mind--was to say, you really have to distinguish between these things. There is this great economic machine that can produce goods and services which are valuable and which people want. And there is also the question as to whether it will produce them. And it will produce them only if the businesses in the economy can find willing and able buyers for them. And that fact creates a possibility of glitches. You can analyze the glitches till the end of the world, and they won't be the same in one 20-year period from another 20-year period. But the fact that you start--that I start--and I hope many economists today start with that distinction in mind. But in our lingo, Aggregate Supply and Aggregate Demand, we owe that to Keynes. And I think that that's important. And it has nothing to do--it's wrong to say it has nothing to do. That's not a matter of your beliefs about how monetary policy works or how fiscal policy works. Russ: Totally agree. Can I just challenge that for one sec? Guest: Sure. Russ: I would argue that there's a better claim to Robert Solow inventing growth theory--much better claim--than claiming that Keynes invented business cycle theory. Because--I've heard this claim before. It's strange. Economists were obsessed with the business cycle: the fact that--they didn't call it 'aggregate demand didn't equal aggregate supply.' They were very aware of the fact, before Keynes, that there were times when the economy did not fulfill its potential. Going back, I'd say, at least for 50 years before Keynes. It seems to me the distinctive contribution of Keynes is you can get out of that problem by borrowing money and spending it through the government. And that to me is the central question, is whether that is true. Do you disagree? Guest: Well, I disagree with that very much. Remember, you are talking to a 90-year old guy. I was brought up reading all those business cycle theorists. I was brought up on Albert Aftalion and Arthur Spiethoff and all that sort of stuff. And I was brought up on Gottfried Haberler's Prosperity and Depression. And I will tell you that for a person of reasonable, normal intelligence, studying economics, all those business cycle theorists, Hawtrey or Pigou for example, another example; Dennis Robertson. Russ: Mises. Guest: Writing about industrial fluctuations, and optimism and pessimism and whatnot--they were not ever clarifying the fact that even apart from oscillations, from intrinsically determining ups and downs, there is this conceptual difference between [?]. You're not going to deny that most economists as of 1936 believed in Say's Law, believed that except for casual interruptions, you didn't have to distinguish between aggregate supply and aggregate demand. Russ: But I don't think they thought--but they didn't--they believed in Say's Law, but they didn't think it worked instantly. And they thought there was, particularly for labor-- Guest: Well, but they thought that it was the underlying theme that governs it. And reading or learning or in fact--you know, Gottfried Haberler was [?] Keynesian, but he added to Prosperity and Depression a last chapter, after the original edition of the book; and it's clear that without being a Keynesian or without accepting Keynes's notions of how to deal in policy terms with the Depression, it was clear in Haberler's mind The General Theory had opened up this issue in a way that he, who had written the standard, authorized textbook on business cycle, or survey rather than textbook, on business cycle theory, hadn't done before. I think there is a real achievement there. Russ: Okay, fair enough. Let's talk about the--I don't mean to deny that he changed the way people think about it. Guest: Well, that's simple.[?] Russ: I just think--I find it strange--you mentioned a number of names. You could add Mises, you could add Irving Fisher. A lot of people worried about the fact that the economy didn't work so smoothly all the time, that Say's Law didn't work instantly. Guest: Yeah. But the difference between not working in theory [?] or are you seeing clearly that you could draw a curve of potential output and then you could try to analyze demand for that output. Russ: Okay, so-- Guest: You don't like that way of doing it, then you don't like way of doing it. But I do. 52:23 Russ: Okay, so the question is, for those of us who don't like that way of doing it--which, the fact that I'm not in that group is irrelevant but a lot of illustrious people are not in that group: Why don't they accept? The real question I'm asking is, coming back to-- Guest: Well, [?] that. The question was: Why is there so much controversy in macroeconomics. And there I think you don't need to talk about specific doctrines in macroeconomics. There's controversy in macroeconomics because a). The problems are very complicated; b). There is a lot at stake. c). There are vested interests on all sides of every issue. And [?] it overflows into everyday politics. And I would have liked it a lot better to work in a branch of economics where those [?] aren't so; and you can sit quietly and do your work and go to sleep. But as a child in the Depression years, I got hooked on those macroeconomic questions. And the controversies arise for the reasons I said. You are talking about a complicated issue; you are talking about an issue in which a lot is at stake. The nature and use of the tax system, the nature and use of public budgets. You are talking about a problem in which there are important vested interests on all sides of the issue who are trying to, would like their interests exemplified in somebody's doctrine. And you are talking about issues which are part of day-to-day politics, which of course means that most of the time all anybody--one of the sayings for which I am famous is that "The length of the shortest true statement about economics is longer than the attention span of most people." And so, it's a natural for controversy. Russ: But let me ask it a different way. That's very well said. It's beautiful. Let me ask it a different way or get you to comment on the empirical side. So, I went off to graduate school in 1976 to Chicago, and my roommate in college went off to MIT (Massachusetts Institution of Technology). And we had of course a very different experience. I learned about how powerful monetary theory was, and he learned how powerful fiscal theory was. And he learned about how the government can fine-tune the economy and I learned that the government can't. And strangely enough, both of us came out of graduate school, I suspect, with a great deal of certainty about the wisdom of our views. I've become--whether this is, I don't know how exemplary this is--much more skeptical about the empirical evidence that supports my world view. And I think everybody on all sides should be skeptical about that. So my question is: The fact that empirical evidence is not decisive in settling these disputes, do you see that as just a question of time, as we get better; or do you see it as an inherent part of point a) that you mentioned: it's just a hard problem? Guest: I think it is in fact a hard problem. And it's not clear to me that the accumulation of empirical evidence will make the problem easy. Because, unlike, say, the velocity of light, the right answer changes over time. Society and the economy changes; the institutions change. The behavior, the way people behave, the way the participants, the important participants in the economy understand what they are doing may change. And so I don't think that--some fairly narrow issues are going to get cleared up with the accumulation of data, no doubt. And some have got cleared up. But I don't think that macro is going to become less controversial in any important way. For the reasons that I ranted about just a minute ago. I don't--you know, I had the experience that I had and I read the books that I read; and I can't say I was taught the macroeconomic side I accept now, because I wasn't, actually. I picked that up in the street, so to speak-- Russ: Sure-- Guest: where I pick up most of what I know-- Russ: We all do. Guest: And time--you know, I could contest your description of the difference between a Chicago education and an MIT education. How could you for instance think that your alternative MIT self would have believed that money was not an important thing to study when you were taking those courses with Franco Modigliani and Stan Fischer? Or if you'd gone to Yale, Jim Tobin? You wouldn't--those extreme versions that, you know, one side is for fiscal policy, the other side is for monetary policy--that's part of the everyday distorted discussion. That's not what goes on in the academic departments [?]. Russ: It isn't. That's a great point. It isn't what goes on. But it is what is yielded from--unfortunately, I think yielded from those departments when it gets into the public. Guest: That's because there are vested interests in politics. Russ: Yep, that's true. There's a lot more doubt in the classroom than there is in the pundit-sphere, or whatever you want to call it. That's for sure.
<filename>tests/worker/tests_api.py import mock import unittest from tests.tests_data import fake_talk_json from tests.tests_data import fake_empty_talk_json from worker.api import API def mocked_requests_get(*args, **kwargs): class MockResponse: def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = status_code def json(self): return self.json_data result = MockResponse(fake_talk_json, 200) return result def mocked_requests_get_fails(*args, **kwargs): class MockResponse: def __init__(self, json_data, status_code): self.json_data = json_data self.status_code = status_code def json(self): return self.json_data result = MockResponse(fake_empty_talk_json, 500) return result class APITest(unittest.TestCase): @mock.patch('requests.get', side_effect=mocked_requests_get) def test_get_random_talk(self, mock_get): api = API() talk_json = api.get_random_talk() self.assertIsNotNone(talk_json) self.assertIsInstance(talk_json, dict) @mock.patch('requests.get', side_effect=mocked_requests_get_fails) def test_get_random_talk_fails(self, mock_get): api = API() talk_json = api.get_random_talk() self.assertIsNone(talk_json)
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from sis_provisioner.views.admin import RESTDispatch from sis_provisioner.dao.term import get_current_active_term, get_term_after class TermListView(RESTDispatch): """ Retrieves a list of Terms. """ def get(self, request, *args, **kwargs): curr_term = get_current_active_term() terms = { 'current': curr_term.json_data(), 'next': get_term_after(curr_term).json_data(), } return self.json_response({'terms': terms})
/** A JPanel for displaying and editing kernel startup options. */ public class KernelStartupPanel extends JPanel { private static final String AUTO_SUFFIX = ".auto"; /** Create a kernel launch GUI. @param config The system configuration. @param options The kernel startup options. */ public KernelStartupPanel(Config config, final KernelStartupOptions options) { super(new BorderLayout()); final JComboBox gis = createComboBox(options.getAvailableWorldModelCreators(), options.getWorldModelCreator()); final JComboBox perception = createComboBox(options.getAvailablePerceptions(), options.getPerception()); final JComboBox comms = createComboBox(options.getAvailableCommunicationModels(), options.getCommunicationModel()); CheckboxPanel simulators = new CheckboxPanel(options.getAvailableSimulators(), options); CheckboxPanel viewers = new CheckboxPanel(options.getAvailableViewers(), options); SpinnerPanel agents = new SpinnerPanel(options.getAvailableAgents(), options); CheckboxPanel otherComponents = new CheckboxPanel(options.getAvailableComponents(), options); JScrollPane simulatorsScroll = new JScrollPane(simulators); simulatorsScroll.setBorder(BorderFactory.createTitledBorder("Simulators")); JScrollPane viewersScroll = new JScrollPane(viewers); viewersScroll.setBorder(BorderFactory.createTitledBorder("Viewers")); JScrollPane agentsScroll = new JScrollPane(agents); agentsScroll.setBorder(BorderFactory.createTitledBorder("Agents")); JScrollPane componentsScroll = new JScrollPane(otherComponents); componentsScroll.setBorder(BorderFactory.createTitledBorder("Other components")); ConfigTree configTree = new ConfigTree(config); JScrollPane configTreeScroll = new JScrollPane(configTree); configTreeScroll.setBorder(BorderFactory.createTitledBorder("Config")); GridBagLayout layout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); JPanel optionsPanel = new JPanel(layout); JSplitPane top = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, optionsPanel, configTreeScroll); add(top, BorderLayout.CENTER); c.gridx = 0; c.gridy = 0; c.gridwidth = 1; c.gridheight = 1; c.weightx = 0; c.weighty = 0; c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.CENTER; JLabel l = new JLabel("GIS:"); layout.setConstraints(l, c); optionsPanel.add(l); c.gridy = 1; l = new JLabel("Perception:"); layout.setConstraints(l, c); optionsPanel.add(l); c.gridy = 2; l = new JLabel("Communication model:"); layout.setConstraints(l, c); optionsPanel.add(l); c.gridy = 0; c.gridx = 1; c.weightx = 1; layout.setConstraints(gis, c); optionsPanel.add(gis); c.gridy = 1; layout.setConstraints(perception, c); optionsPanel.add(perception); c.gridy = 2; layout.setConstraints(comms, c); optionsPanel.add(comms); // Simulators, viewers, agents, other components c.gridx = 0; ++c.gridy; c.gridwidth = 2; c.weightx = 1; c.weighty = 1; layout.setConstraints(simulatorsScroll, c); optionsPanel.add(simulatorsScroll); ++c.gridy; layout.setConstraints(viewersScroll, c); optionsPanel.add(viewersScroll); ++c.gridy; layout.setConstraints(agentsScroll, c); optionsPanel.add(agentsScroll); ++c.gridy; layout.setConstraints(componentsScroll, c); optionsPanel.add(componentsScroll); // Event listeners gis.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { options.setWorldModelCreator((WorldModelCreator)gis.getSelectedItem()); } }); perception.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { options.setPerception((Perception)perception.getSelectedItem()); } }); comms.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { options.setCommunicationModel((CommunicationModel)comms.getSelectedItem()); } }); } private <T> JComboBox createComboBox(List<T> options, T selected) { Object[] choices = options.toArray(); JComboBox result = new JComboBox(choices); result.setSelectedItem(selected); result.setEnabled(choices.length > 1); return result; } private static final class CheckboxPanel extends JPanel { private CheckboxPanel(Collection<String> available, final KernelStartupOptions options) { GridBagLayout layout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.gridheight = 1; c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.CENTER; setLayout(layout); for (String t : available) { c.gridx = 0; c.weightx = 1; JLabel l = new JLabel(t); layout.setConstraints(l, c); add(l); c.gridx = 1; c.weightx = 0; final JCheckBox check = new JCheckBox(); check.setSelected(options.getInstanceCount(t) > 0); options.setInstanceCount(t, check.isSelected() ? 1 : 0); layout.setConstraints(check, c); add(check); ++c.gridy; final String comp = t; check.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { options.setInstanceCount(comp, check.isSelected() ? 1 : 0); } }); } } } private static final class SpinnerPanel extends JPanel { private SpinnerPanel(Collection<String> available, final KernelStartupOptions options) { GridBagLayout layout = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.CENTER; setLayout(layout); for (String t : available) { c.gridx = 0; c.weightx = 1; JLabel l = new JLabel(t); layout.setConstraints(l, c); add(l); int count = options.getInstanceCount(t); boolean all = count == Integer.MAX_VALUE; final JSpinner spinner = new JSpinner(new SpinnerNumberModel(count == Integer.MAX_VALUE ? 0 : count, 0, Integer.MAX_VALUE, 1)); final JCheckBox check = new JCheckBox("Maximum"); check.setSelected(all); spinner.setEnabled(!all); final String comp = t; check.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { spinner.setEnabled(!check.isSelected()); if (check.isSelected()) { options.setInstanceCount(comp, Integer.MAX_VALUE); } else { options.setInstanceCount(comp, ((Number)spinner.getValue()).intValue()); } } }); spinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { options.setInstanceCount(comp, ((Number)spinner.getValue()).intValue()); } }); c.gridx = 1; c.weightx = 0; layout.setConstraints(spinner, c); add(spinner); c.gridx = 2; layout.setConstraints(check, c); add(check); ++c.gridy; } } } }
Beer bottles are seen at the brewhouse of the brewery Schlossbrauerei Au-Hallertau in Au-Hallertau on July 12, 2013. (CHRISTOF STACHE/AFP via Getty Images) It is widely known that Germans love their beer. But their appreciation for the alcoholic beverage extends far beyond Munich Oktoberfest. Today, alcohol-related traffic accidents likely will multiply by three as virtually all male Germans will get jointly drunk. It's traditionally the most dangerous day of the year to be on the streets in Germany because it is Father's Day. The tradition always coincides with the Christian Feast of the Ascension of Jesus -- but Germans have a very particular understanding of how to celebrate being a father, it seems. German men traditionally meet up in large groups that are equipped with at least one carefully decorated carriage filled with beer. They then descend on a day-long hike with their very own beer vehicles, but few make it to the end. The goal for many German men today, it appears, is to get too drunk to walk. There is no deeper meaning behind this mass-drinking event which occupies Europe's largest country and economic powerhouse for one full day every year. Although many Germans simply decide to leave their phones at home for Father's Day in order not to lose them, some Twitter users shared insights into how their day had gone, so far, using the German hashtag #Vatertag. One commentator complained about the lack of beer at a forest party -- a situation he described as a "catastrophe." Public radio station Bayern 1 -- which broadcasts from the southern German beer capital of Munich -- published a short video on Thursday with "5 things one should avoid on Father's Day." The report recommended Germans to not take embarrassing photos (a proposal which was accompanied by the photo of a half naked man lying on a street). The country's public broadcaster also urged Germans not to drink hard liquor too early in the morning, but rather later in the day, and to not "forget about the way home." In a popular YouTube video which seeks to explain why Germans get so drunk so randomly on Father's Day, the narrator points out that it was Americans who invented the day officially in the 19th century, following the creation of Mother's Day which will take place on Sunday. However, the very German tradition of men celebrating themselves with beer might go back centuries. The tradition has caused debates in the past. In 2008, for instance, former German family minister and current defense minister Ursula von der Leyen urged male Germans to stop drinking in front of their kids or leaving their families for the day. "Men who want their kids to be as far away as possible are really just awful," she said in an interview. The comments sparked outrage, according to multiple reports back then. Recent research, however, has found that an increasing number of fathers now spend the day together with their families -- presumably sober. Also read: This man sued his former company because his work was β€˜too boring’ Germany welcomed more than 1 million refugees in 2015. Now, the country is searching for its soul. Don’t drive in these European countries
use endpoint_plugin::{ AssetNode, FileNode, IAssetNode, IFileNode, IProcessNode, ProcessNode, }; use rust_proto::graph_descriptions::*; use sysmon::FileCreateEvent; use crate::{ generator::SysmonGeneratorError, models::{ get_image_name, strip_file_zone_identifier, utc_to_epoch, }, }; /// Creates a subgrqph describing a `FileCreateEvent` /// /// The subgraph generation for a `FileCreateEvent` includes the following: /// * A creator `Process` node - denotes the process that created the file /// * A subject `File` node - the file that is created as part of this event pub fn generate_file_create_subgraph( file_create: &FileCreateEvent, ) -> Result<GraphDescription, SysmonGeneratorError> { let timestamp = utc_to_epoch(&file_create.event_data.creation_utc_time)?; let mut graph = GraphDescription::new(); let mut asset = AssetNode::new(AssetNode::static_strategy()); asset .with_asset_id(file_create.system.computer.computer.clone()) .with_hostname(file_create.system.computer.computer.clone()); let mut creator = ProcessNode::new(ProcessNode::session_strategy()); creator .with_asset_id(file_create.system.computer.computer.clone()) .with_process_id(file_create.event_data.process_id) .with_process_name(get_image_name(&file_create.event_data.image.clone()).unwrap()) .with_last_seen_timestamp(timestamp); let mut file = FileNode::new(FileNode::session_strategy()); file.with_asset_id(file_create.system.computer.computer.clone()) .with_file_path(strip_file_zone_identifier( &file_create.event_data.target_filename, )) .with_created_timestamp(timestamp); graph.add_edge( "process_asset", creator.clone_node_key(), asset.clone_node_key(), ); graph.add_edge( "created_files", creator.clone_node_key(), file.clone_node_key(), ); graph.add_edge( "files_on_asset", asset.clone_node_key(), file.clone_node_key(), ); graph.add_node(asset); graph.add_node(creator); graph.add_node(file); Ok(graph) }
#[doc = r" Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Start Timer"] pub tasks_start: TASKS_START, #[doc = "0x04 - Stop Timer"] pub tasks_stop: TASKS_STOP, #[doc = "0x08 - Increment Timer (Counter mode only)"] pub tasks_count: TASKS_COUNT, #[doc = "0x0c - Clear time"] pub tasks_clear: TASKS_CLEAR, #[doc = "0x10 - Deprecated register - Shut down timer"] pub tasks_shutdown: TASKS_SHUTDOWN, _reserved0: [u8; 44usize], #[doc = "0x40 - Description collection\\[n\\]: Capture Timer value to CC\\[n\\] register"] pub tasks_capture: [TASKS_CAPTURE; 6], _reserved1: [u8; 232usize], #[doc = "0x140 - Description collection\\[n\\]: Compare event on CC\\[n\\] match"] pub events_compare: [EVENTS_COMPARE; 6], _reserved2: [u8; 168usize], #[doc = "0x200 - Shortcut register"] pub shorts: SHORTS, _reserved3: [u8; 256usize], #[doc = "0x304 - Enable interrupt"] pub intenset: INTENSET, #[doc = "0x308 - Disable interrupt"] pub intenclr: INTENCLR, _reserved4: [u8; 504usize], #[doc = "0x504 - Timer mode selection"] pub mode: MODE, #[doc = "0x508 - Configure the number of bits used by the TIMER"] pub bitmode: BITMODE, _reserved5: [u8; 4usize], #[doc = "0x510 - Timer prescaler register"] pub prescaler: PRESCALER, _reserved6: [u8; 44usize], #[doc = "0x540 - Description collection\\[n\\]: Capture/Compare register n"] pub cc: [CC; 6], } #[doc = "Start Timer"] pub struct TASKS_START { register: ::vcell::VolatileCell<u32>, } #[doc = "Start Timer"] pub mod tasks_start; #[doc = "Stop Timer"] pub struct TASKS_STOP { register: ::vcell::VolatileCell<u32>, } #[doc = "Stop Timer"] pub mod tasks_stop; #[doc = "Increment Timer (Counter mode only)"] pub struct TASKS_COUNT { register: ::vcell::VolatileCell<u32>, } #[doc = "Increment Timer (Counter mode only)"] pub mod tasks_count; #[doc = "Clear time"] pub struct TASKS_CLEAR { register: ::vcell::VolatileCell<u32>, } #[doc = "Clear time"] pub mod tasks_clear; #[doc = "Deprecated register - Shut down timer"] pub struct TASKS_SHUTDOWN { register: ::vcell::VolatileCell<u32>, } #[doc = "Deprecated register - Shut down timer"] pub mod tasks_shutdown; #[doc = "Description collection\\[n\\]: Capture Timer value to CC\\[n\\] register"] pub struct TASKS_CAPTURE { register: ::vcell::VolatileCell<u32>, } #[doc = "Description collection\\[n\\]: Capture Timer value to CC\\[n\\] register"] pub mod tasks_capture; #[doc = "Description collection\\[n\\]: Compare event on CC\\[n\\] match"] pub struct EVENTS_COMPARE { register: ::vcell::VolatileCell<u32>, } #[doc = "Description collection\\[n\\]: Compare event on CC\\[n\\] match"] pub mod events_compare; #[doc = "Shortcut register"] pub struct SHORTS { register: ::vcell::VolatileCell<u32>, } #[doc = "Shortcut register"] pub mod shorts; #[doc = "Enable interrupt"] pub struct INTENSET { register: ::vcell::VolatileCell<u32>, } #[doc = "Enable interrupt"] pub mod intenset; #[doc = "Disable interrupt"] pub struct INTENCLR { register: ::vcell::VolatileCell<u32>, } #[doc = "Disable interrupt"] pub mod intenclr; #[doc = "Timer mode selection"] pub struct MODE { register: ::vcell::VolatileCell<u32>, } #[doc = "Timer mode selection"] pub mod mode; #[doc = "Configure the number of bits used by the TIMER"] pub struct BITMODE { register: ::vcell::VolatileCell<u32>, } #[doc = "Configure the number of bits used by the TIMER"] pub mod bitmode; #[doc = "Timer prescaler register"] pub struct PRESCALER { register: ::vcell::VolatileCell<u32>, } #[doc = "Timer prescaler register"] pub mod prescaler; #[doc = "Description collection\\[n\\]: Capture/Compare register n"] pub struct CC { register: ::vcell::VolatileCell<u32>, } #[doc = "Description collection\\[n\\]: Capture/Compare register n"] pub mod cc;
def stream_result_event(input_query: InputTimePeriodQuery, authorization: str = Header(None), processor: Processor = Depends(get_processor)): log.info(f'Entering /data/event/stream with input query: {input_query}') user_id = authorize_user(authorization) log.info(f"Authorized token for user: {user_id}") result_data = processor.process_event_request(input_query) buffer_stream = pa.BufferOutputStream() pq.write_table(result_data, buffer_stream) return StreamingResponse( io.BytesIO(buffer_stream.getvalue().to_pybytes()) )
On the algebraic dimension of twistor spaces over the connected sum of four complex projective planes We study the algebraic dimension of twistor spaces of positive type over $4\bbfP^2$. We show that such a twistor space is Moishezon if and only if its anticanonical class is not nef. More precisely, we show the equivalence of being Moishezon with the existence of a smooth rational curve having negative intersection number with the anticanonical class. Furthermore, we give precise information on the dimension and base locus of the fundamental linear system $|{-1/2}K|$. This implies, for example, $\dim|{-1/2}K|\leq a(Z)$. We characterize those twistor spaces over $4\bbfP^2$, which contain a pencil of divisors of degree one by the property $\dim|{-1/2}K| = 3$. Introduction Twistor spaces usually arise in four-dimensional conformal geometry. Their construction reflects the impossibility to equip in general a four-dimensional conformal manifold M with a compatible complex structure. It was shown in that the conformal metric on M is self-dual if and only if the twistor space Z associated to M carries, in a natural way, the structure of a complex manifold. Therefore, the conformal geometry of M is closely related to the holomorphic geometry of Z. Since we shall only work with methods of complex geometry, we can use the following definition: A twistor space Z is a complex three-manifold with the following additional structure: β€’ a proper differentiable submersion Ο€ : Z β†’ M onto a real differentiable fourmanifold M . The fibres of Ο€ are holomorphic curves in Z being isomorphic to CP 1 and having normal bundle in Z isomorphic to O(1) βŠ• O(1); β€’ an anti-holomorphic fixed point free involution Οƒ : Z β†’ Z with πσ = Ο€. The fibres of Ο€ are called "real twistor lines" and the involution Οƒ is called the "real structure". A geometric object will be called "real" if it is Οƒ-invariant. For example, a line bundle L on Z is real if Οƒ * L ∼ = L, and a complex subvariety D βŠ‚ Z is real if Οƒ(D) = D. Instead of Οƒ(D) we shall often writeD. We only consider compact and simply connected twistor spaces. At the beginning of the 80's, the first classification result emerged in , : There exist exactly two compact KΓ€hlerian twistor spaces. They are automatically projective algebraic. The corresponding Riemannian four-manifolds are the 4-sphere S 4 and the complex projective plane CP 2 (with Fubini-Study metric). This was generalized in to the result that a twistor space which is bimeromorphic to a compact KΓ€hler manifold must be Moishezon and simply connected. This implies (see , ) that M is homeomorphic to the connected sum nCP 2 for some n β‰₯ 0. New examples of Moishezon twistor spaces were constructed by Y.S. Poon (case n = 2) and C. LeBrun , H. Kurke (case n β‰₯ 3). Nowadays the situation is well understood for n ≀ 3 (cf. , , , , ). To become more precise, we have to introduce the notion of the "type" of a twistor space. By a result of R. Schoen , every conformal class of a compact Riemannian fourmanifold contains a metric of constant scalar curvature. Its sign will be called the type of the twistor space. This is an invariant of the conformal class, hence of the twistor space. It was shown in that a Moishezon twistor space is always of positive type. If n ≀ 3, the converse is also true. In this paper we focus on the positive type case, for two reasons. One reason is that we can then apply Hitchin's vanishing theorem (2.1). The other reason is the following: a result of P. Gauduchon implies that any twistor space of negative type has algebraic dimension zero. From the results of M. Pontecorvo we easily derive that a twistor space of type zero over nCP 2 must also have algebraic dimension zero. It is not clear whether there exist twistor spaces of non-positive type over nCP 2 . Computation of algebraic dimension is, therefore, interesting only in the case of positive type. A very important tool to compute the algebraic dimension of twistor spaces is the result of Y.S. Poon (see also ) stating that the algebraic dimension is equal to the Iitaka dimension of the anticanonical bundle (cf. Section 2). From and , it is known that the generic twistor space over nCP 2 has algebraic dimension one (if n = 4), respectively zero (if n β‰₯ 5). For the case n = 4, the characterizing property c 3 1 = 0 is of central importance. In this paper we study the following Problem: Compute the algebraic dimension a(Z) of a twistor space Z over 4CP 2 in terms of geometric or numeric properties of certain divisors on Z. A first attempt to tackle this problem was made by Y.S. Poon . He assumes, additionally, the existence of a divisor D of degree one on Z. He studies a birational map D β†’ P 2 , which is the blow-up of four points. He seems to assume that these four points are actually in P 2 (no infinitesimally near blown-up points). If these four points are in a special position he obtains a(Z) = 3. In the case of general position he can only show: a(Z) ≀ 2. We shall, in general, not assume the existence of divisors of degree one. Because in case n = 4 there exists at least a pencil of so-called fundamental divisors, we shall study their geometry to obtain our results. If S βŠ‚ Z is a real fundamental divisor, we have a birational map S β†’ P 1 Γ— P 1 which is the blow-up of eight points. We shall study in detail the possible positions for these points. We take into account that some of these points can be infinitesimally near each other. We are able to derive the algebraic dimension a(Z) from the knowledge of the positions of these eight points. Similar considerations were made for general n β‰₯ 4 in the paper . But the authors of that paper are intersted in a study of small deformations of well-known Moishezon twistor spaces, and so they investigate only the case without infinitely near blown-up points. As a consequence of our results, we give a new characterization of the twistor spaces over 4CP 2 which are first described by C. LeBrun (with methods from differential geometry). From the point of view of complex geometry the twistor space structure on these complex manifolds was found by H. Kurke . Following the literature, we call them LeBrun twistor spaces. These twistor spaces are characterized in and by the property to contain a pencil of divisors of degree one. In the case n = 4 we show (Theorem (6.5)) that they can also be characterized by the property h 0 (K βˆ’ 1 2 ) = 4 or by the structure of the base locus of | βˆ’ 1 2 K|. Besides this, our main results are a precise description of the set of irreducible curves intersecting K βˆ’ 1 2 negatively (Theorem 6.1) and the following theorems, where Z denotes always a simply connected compact twistor space of positive type over 4CP 2 : Theorem 6.3. The following conditions are equivalent: Theorem 6.7. If dim | βˆ’ 1 2 K| β‰₯ 2, then: a(Z) = 2 ⇐⇒ K βˆ’ 1 2 is nef ⇐⇒ | βˆ’ 1 2 K| does not have base points. This paper is organized as follows: In Section 2 well-known but necessary facts about simply connected compact twistor spaces of positive type are collected. Also Section 3 has preparatory character. We study there the structure of fundamental divisors for general n, using results and techniques contained in . Technically important for the following sections will be Proposition 3.6 where the structure of effective anticanonical curves on real fundamental divisors is described in detail. In the remaining three sections we assume n = 4. In Section 4 we study the case where the anti-canonical bundle K βˆ’1 Z is nef (in the sense of Mori theory). We shall prove that the algebraic dimension is, in this case, at most two. We also see how to distinguish between algebraic dimension one and two. This generalizes results of . In Section 5 we assume K βˆ’1 Z to be not nef. We collect detailed information on the fundamental linear system | βˆ’ 1 2 K| and on the set of curves which intersect K βˆ’ 1 2 negatively. In this cases the algebraic dimension is three. The final Section 6 combines the results of the previous part to prove the main theorems stated above. Acknowledgement I thank FrΓ©dΓ©ric Campana for encouragement and stimulating discussions. Preliminaries We briefly collect well-known facts which will be frequently used later. We refer the reader to , , , , and . For brevity, we assume, throughout this section, Z to be a simply connected compact twistor space of positive type. As mentioned in Section 1 the corresponding Riemannian four-manifold M is homeomorphic to nCP 2 . Cohomology ring of Z. H 2 (Z, Z) and H 4 (Z, Z) are free modules of rank n + 1. There exists a basis x 1 , . . . , x n , w of H 2 (Z, Z) such that the pull-back H 2 (Z, Z) β†’ H 2 (F, Z) ∼ = Z (for any real twistor line F βŠ‚ Z) sends x i to 0 and w to the positive generator. The cohomology ring H * (Z, Z) is isomorphic to the graded ring Z /R where R is the ideal generated by The grading is given by deg . This yields the following Chern numbers: c 3 1 = 16(4 βˆ’ n), c 1 c 2 = 24, c 3 = 2(n + 2). Cohomology of sheaves. The main reason to assume Z to be of positive type is Hitchin's vanishing theorem. We shall only use the following special case: Theorem 2.1 (Hitchin ). If Z is of positive type then we have for any L ∈ Pic (Z) On the other hand, since the twistor lines cover Z, we obtain: By Serre duality this gives the following important vanishing results: In particular, we obtain h 2 (O Z ) = h 3 (O Z ) = 0. Because Z is simply connected, we also have h 1 (O Z ) = 0. Hence, we obtain an isomorphism of abelian groups, given by the first Chern class: There exists a unique line bundle whose first Chern class is 1 2 c 1 . We shall denote it by K βˆ’ 1 2 . Following Poon, we call it the fundamental line bundle. The divisors in the linear system |βˆ’ 1 2 K| will be called fundamental divisors. The description of the cohomology ring gives (βˆ’ 1 2 K) 3 = 2(4 βˆ’ n). If S ∈ | βˆ’ 1 2 K| is a smooth fundamental divisor, we obtain by the adjunction formula K βˆ’1 If n ≀ 4, there exist smooth real fundamental divisors (cf. ). The degree of a line bundle L ∈ Pic (Z) will be by definition the degree of its restriction to a real twistor line. For example, deg(K βˆ’ 1 2 ) = 2. We obtain in this way a surjective degree map deg : Pic (Z) Φ‰ Z. From the above equations on Chern numbers we obtain, by applying the Riemann-Roch theorem, Algebraic dimension. We denote by a(Z) the algebraic dimension of Z, which is by definition the transcendence degree of the field of meromorphic functions of Z over C. If dim Z = a(Z), then Z is called Moishezon. To compute the algebraic dimension of twistor spaces we shall frequently use, without further reference, the following theorem of Y.S. Poon: Theorem 2.2. , . For any line bundle L ∈ Pic (Z) there holds: dim Z β‰₯ a(Z) β‰₯ ΞΊ(Z, L). , because any projective variety is Moishezon. If we define g := gcd{m ∈ Z | m > 0, h 0 (Z, L m ) = 0} and denote by Ξ¦ |L m | the meromorphic map given by the linear system |L m |, then ΞΊ(Z, L) = max{dim Ξ¦ |L m | (Z) | m ∈ gZ, m > 0}. If there exists a polynomial P (X) such that for all large positive m ∈ Z we have h 0 (Z, L mg ) ≀ P (m), then ΞΊ(Z, L) ≀ deg P . We apply these basic facts to obtain our first result on the algebraic dimension in case n = 4. The following proposition is a generalization of a result contained in . For convenience we introduce the following Definition: If there exists an integer m β‰₯ 1 with h 1 (K βˆ’ m 2 ) = 0 then we define Ο„ := min{m|m β‰₯ 1, h 1 (K βˆ’ m 2 ) = 0}. Otherwise we set Ο„ := ∞. Remark 2.4. If | βˆ’ K S | contains a smooth curve C, then we computed in that Ο„ is the order of N := K βˆ’1 S βŠ— O C in the Picard group Pic C of the elliptic curve C. Under this additional assumption Proposition 2.3 was shown in . The structure of fundamental divisors In this section Z always denotes a simply connected compact twistor space of positive type. Lemma 3.1. Let S ∈ |βˆ’ 1 2 K| be a smooth surface. Then the restriction map Pic Z β†’ Pic S is injective. Therefore, taking the first Chern class defines isomorphisms Pic Z ∼ β†’ H 2 (Z, Z) and Pic S ∼ β†’ H 2 (S, Z). Let us denote the inclusion of S into Z by i. The above isomorphisms transform then the restriction morphism Pic Z β†’ Pic S into the map i * on cohomology groups. We shall apply standard facts from algebraic topology to verify the injectivity of i * . Let o S ∈ H 4 (Z, Z) and o Z ∈ H 6 (Z, Z) be the fundamental classes of S and Z respectively. For any cohomology class Ξ± ∈ H 2 (Z, Z) we obtain by the associativity of cap-product The naturalness of cap-product implies Ξ± i * (o S ) = i * (i * (Ξ±) o S ). Therefore, we obtain a commutative diagram: Since, by PoincarΓ© duality, the cap-product with o Z is an isomorphism, we obtain ker(i * ) βŠ‚ ker( d Z (S)). The description of the cohomology ring given above allows us to compute the kernel of the cup-product with the dual class d Z (S) of S. With the notation of Section 2 the elements x 1 , . . . , x n , Ο‰ form a basis of the free Z-module H 2 (Z, Z). The dual class of S is d Z (S) = c 1 (K βˆ’ 1 2 ) = 2Ο‰ + x 1 + Β· Β· Β· + x n . If we use Ο‰x 1 , . . . , Ο‰x n , x 2 1 as basis of H 4 (Z, Z) then the cup-product with d Z (S) is described by the (n + 1) Γ— (n + 1)-matrix:  whose determinant is equal to 2 nβˆ’1 (n βˆ’ 4). If n = 4 we obtain the injectivity of the map Ξ± β†’ Ξ± d Z (S) and thus of the restriction map Pic Z Φ’β†’ Pic S. If n = 4 it is easy to see that Ξ± But the degree of K 1 2 is βˆ’2 and, therefore, Hitchin's vanishing theorem gives h i (K 1 2 ) = 0 for all i. Therefore, using Serre duality, Lemma 3.3 (cf. , p. 693). Let Z be as above and S ∈ | βˆ’ 1 2 K| an irreducible real divisor. Then S is smooth and contains a real twistor fibre F βŠ‚ S. The linear system |F | is one-dimensional and its real elements are precisely the real twistor fibres contained in S. Proof: The smoothness of S was shown in . If S does not contain a real twistor fibre, the restriction of the twistor fibration to S would give an unramified double cover over a simply connected manifold, since Z does not contain real points. But S is connected and must, therefore, contain a real twistor fibre F . From the adjunction formula we obtain F 2 = 0 on S. Hence, we have an exact sequence 0 Since the linear system |F | defines a flat family of curves in S, its elements form a curve in the Douady space D of curves on Z (cf. ). Since h 0 (P 1 , O(1) βŠ• O(1)) = 4 and h 1 (P 1 , O(1) βŠ• O(1)) = 0, D is a four-dimensional complex manifold near points which correspond to smooth rational curves on Z with normal bundle O(1) βŠ• O(1). The real structure of Z induces one on D. If the set of real points D(R) is non-empty, then it is a four-dimensional real manifold near points as before. Since the real twistor lines are smooth rational curves with the above normal bundle, the real manifold M = 4CP 2 is a submanifold of D(R). Since M is compact and has the same dimension as D(R), it must be a connected component. The set U of members of |F | which are smooth rational curves with normal bundle O(1) βŠ• O(1) is open and dense in P 1 ∼ = |F | with respect to the Zariski topology. Therefore, the set U (R) of real points in U is open and dense in the one-sphere of real members of |F |. M is compact and must, therefore, contain the closure of U (R) in D(R), which is the set of all real members of |F |. Therefore, any real member of |F | is a real twistor fibre and, in particular, smooth and ireducible. This proves the claim. To obtain more information on the structure of real irreducible fundamental divisors S ∈ | βˆ’ 1 2 K| one can study the morphism S β†’ P 1 given by |F | (cf. ). Since the general fibre of this morphism is a smooth rational curve it factors through a rational ruled surface. Since (βˆ’K S ) 2 = (βˆ’ 1 2 K) 3 = 8 βˆ’ 2n, the surface S is a blow-up of a ruled surface at 2n points. The exceptional curves of these blow-ups are contained in fibres of the morphism S β†’ P 1 . By Lemma 3.3 none of the exceptional curves is real and none of the blown-up points lie on a real fibre of the ruled surface. Using this, in it has been shown that the ruled surface is isomorphic to P 1 Γ—P 1 . Therefore, we obtain a morphism Οƒ : S β†’ P 1 Γ— P 1 which is a succession of blow-ups. Let us equip P 1 Γ— P 1 with the real structure given by the antipodal map on the first factor and the usual real structure on the second. Then Οƒ is equivariant (or "real"). Since we can always contract a conjugate pair of disjoint (βˆ’1)-curves, Οƒ is the succession of n blow-ups. At each step a conjugate pair of points is blown-up to give a surface without real points. We should bear in mind that it is possible to have infinitesimally near blown-up points. As in we shall call curves of type (1, 0) on P 1 Γ— P 1 "lines" and curves of type (0, 1) "fibres". Then there do not exist real lines. But the images of real twistor fibres in |F | are exactly the real "fibres". Proof: As usual, O(k, l) denotes the locally free sheaf p * 1 O P 1 (k) βŠ— p * 2 O P 1 (l) on the smooth rational surface P 1 Γ— P 1 , where p i : P 1 Γ— P 1 β†’ P 1 (i = 1, 2) are the projections and k, l are integers. The Picard group Pic (P 1 Γ— P 1 ) is free abelian of rank two with generators O(1, 0) and O(0, 1). In the proof we shall use the well-known fact that, if k < 0 or l < 0, then the linear system |O(k, l)| is empty. Let C ∈ |O(2, 2)| be a real curve and C 0 ∈ |O(a, b)| an irreducible component (with reduced scheme structure) of C. Let Ξ» β‰₯ 1 be the multiplicity of C 0 in C, that is the largest integer with Ξ»C 0 βŠ‚ C. Then we must have 0 ≀ Ξ»a ≀ 2 and 0 ≀ Ξ»b ≀ 2. The case Ξ»a = Ξ»b = 2 can only occur if Ξ»C 0 = C. Assume first Ξ»C 0 = C, hence Ξ»a ≀ 1 or Ξ»b ≀ 1. If Ξ» β‰₯ 2 or C 0 singular, there exists a point y ∈ C 0 such that any curve not contained in C 0 but containing y has intersection number at least two with Ξ»C 0 . If F ∈ |O(0, 1)| and G ∈ |O(1, 0)| are the unique curves in these linear systems containing the point y, we obtain (as C 0 is irreducible) F.(Ξ»C 0 ) = Ξ»a β‰₯ 2 or G.(Ξ»C 0 ) = Ξ»b β‰₯ 2. By the above inequalities, this means Ξ»a = 2 and 0 ≀ Ξ»b ≀ 1 or 0 ≀ Ξ»a ≀ 1 and Ξ»b = 2. If Ξ» = 1, the curve C 0 is, by assumption, irreducible, reduced, singular and a member of |O(2, 0)|, |O(2, 1)|, |O(0, 2)|, or |O(1, 2)|. But these linear systems do not contain such a curve. Hence, we must have Ξ» = 2 and, therefore, C 0 ∈ |O(0, 1)| or C 0 ∈ |O(1, 0)|. In particular, C 0 is smooth. If C 0 ∈ |O(1, 0)|, this curve is not real, since by definition of the real structure on P 1 Γ— P 1 this linear system does not contain real members. Hence, the component 2C 0 of C is not real, which implies 2C 0 + 2C 0 βŠ‚ C, since C is real. ButC 0 ∈ |O(1, 0)| and so 2C 0 + 2C 0 ∈ |O(4, 0)|. Such a curve can never be contained in C ∈ |O(2, 2)|. So we obtain Ξ»C 0 = 2F with some F ∈ |O(0, 1)|. Again, since a curve of type (0, 4) can never be a component of C, the fibre F is necessarily real. This proves the lemma in the case Ξ»C 0 = C. Assume now Ξ»C 0 = C. Then Ξ» = 1 or Ξ» = 2. If Ξ» = 2, we have, by reality of C = 2C 0 , that C 0 ∈ |O(1, 1)| is a real curve. Because C 0 is irreducible and C 0 .F = 1 for any F ∈ |O(0, 1)|, the curve C 0 would intersect each real fibre F ∈ |O(0, 1)| at a real point. But on P 1 Γ— P 1 real points do not exist. Hence Ξ» = 1, which means C = C 0 is irreducible and real. It remains to see that C must be reducible if it is not smooth. Let x ∈ C be a singular point of C. Since C is real and P 1 Γ— P 1 does not contain real points,x = x is also a singular point on C. If we embed P 1 Γ— P 1 by |O(1, 1)| as a smooth quadric into P 3 , we easily see that the linear system of curves of type (1, 1) on P 1 Γ— P 1 containing x andx is one-dimensional. It is cut out by the pencil of planes in P 3 containing the line connecting x andx. Therefore, any point of P 1 Γ— P 1 is contained in such a curve. The intersection number of C with a curve of type (1, 1) is four. Since x andx are singular points on C, any curve of type (1, 1) containing x andx and a third point of C must have a common component with C. Therefore, C cannot be irreducible and reduced. Definition 3.5. A reduced curve C on a compact complex surface S will be called a "cycle of rational curves", if the irreducible components C 1 , . . . , C m of C are smooth rational curves with the following properties: (We use the convention C m+1 = C 1 .) m = 2 and C 1 intersects C 2 transversally at two distinct points, C 1 . Proposition 3.6. Assume dim | βˆ’ 1 2 K| β‰₯ 1 and let S ∈ | βˆ’ 1 2 K| be smooth and real. Then there exists a blow-down S β†’ P 1 Γ— P 1 and a connected real member C ∈ | βˆ’ K S |, such that: β€’ Οƒ is compatible with real structures, where we use the real structure of Lemma 3.4 on P 1 Γ— P 1 , β€’ the composition pr 2 β€’Οƒ of Οƒ with the second projection P 1 Γ—P 1 βˆ’β†’ P 1 is the morphism given by the linear system | F |, where F βŠ‚ S is a real twistor fibre, β€’ the curve C is reduced and β€’ if C is not smooth, it is a "cycle of rational curves" and its image C β€² in P 1 Γ— P 1 has one of the following structures: As seen above, we can choose a real blow-down map Οƒ : contains a smooth member, we are done. Otherwise, take a reducible real C ∈ | βˆ’ K S | and let C β€² βŠ‚ P 1 Γ— P 1 be the image of C. Since Οƒ is a blow-up, C β€² is a real member of |O(2, 2)|. By Lemma 3.4 the components of C β€² are smooth and a multiple component can only be the multiple 2F of a real fibre F ∈ |O(0, 1)|. But Lemma 3.3 shows that no point on such a real fibre is blown-up. Therefore, any other member of |2F | missing the 2n blown-up points, defines a divisor in | βˆ’ K S |. Choosing, for example, a conjugate pair of appropriate fibres, we obtain a real member in | βˆ’ K S | whose image in P 1 Γ— P 1 has only reduced components. We assume for the rest of the proof that C is chosen in this way. If C β€² would be irreducible, it would be smooth by Lemma 3.4. In this case C is smooth, too. Assume C β€² is reducible. A component of type (1, a) with a ∈ {0, 1, 2} cannot be real, since, otherwise, it would intersect real fibres at real points. Therefore, such components appear in conjugate pairs, hence a ≀ 1. If a = 0 we are in case (I). If a = 0 then a = 1 and C β€² = A β€² +Δ€ β€² with two distinct curves A β€² ,Δ€ β€² of type (1, 1). This is case (III). Assume now that there is no component of type (1, a). Then we must have a component C 0 of C β€² which has type (2, a). If a = 2 it must be smooth and we are done. Therefore, a = 1, because |O(2, 0)| does not contain irreducible reduced elements. Then we have C β€² = C 0 + F with F ∈ |O(0, 1)| and C 0 ∈ |O(2, 1)|. F and C 0 must be real, since they have different types. This is case (II) of our statement. It remains to show that C is a "cycle of rational curves". We have seen this for the image C β€² in P 1 Γ— P 1 . Exceptional components of C are always rational. Furthermore, C β€² has at most ordinary nodes as singularities. To obtain C from C β€² , at every step of blowing-up, we have to subtract the exceptional locus from the total transform of C β€² . At every step we blow up either a conjugate pair of singular points or of smooth points. We obtain a curve which has again, at most, singularities of multiplicity two and is a "cycle of rational curves". So we obtain this property for C, too. Using this structure result and assuming that the fundamental linear system | βˆ’ 1 2 K| is a pencil, we can show that the structure of its base locus is closely related to the effective divisors of degree one on Z. Proposition 3.7. Assume dim | βˆ’ 1 2 K| = 1 and denote by C the base locus of the fundamental linear system. If C is smooth, then Z does not contain effective divisors of degree one. If C is not smooth, then the number of effective divisors of degree one on Z is equal to the number of components of C. Proof: Let S ∈ | βˆ’ 1 2 K| be a smooth real member. Then | βˆ’ K S | = {C} and by Proposition 3.6 C is smooth or a "cycle" of smooth rational curves. If C is smooth, there does not exist an effective divisor D of degree one, because D +D ∈ |βˆ’ 1 2 K| would produce a reducible member in | βˆ’ K S |. Let now C be singular, hence reducible. The rest of the proof is an adaption of an idea of Pedersen and Poon . Now let {P,P } be any pair of singular points on C. The image C β€² of C in P 1 Γ— P 1 does not contain a real fibre, because, otherwise, by Proposition 3.6 and Lemma 3.3 the linear system | βˆ’ K S | would be at least one-dimensional. Hence, the real twistor line L P containing P andP is not contained in S. Hence, L P meets S transversally at P and P . If Q is a point on L P distinct from P andP , then there exists a divisor S 0 ∈ | βˆ’ 1 2 K| containing Q. Since S 0 contains also C it contains three points of L P . Hence, L P βŠ‚ S 0 . Therefore, the real linear system of fundamental divisors containing L P is non-empty. This implies that we can choose a real S 0 ∈ | βˆ’ 1 2 K| containing L P . Since S 0 contains also C and P is a singular point of C, the surface S 0 contains three curves meeting at P , namely L P and two components (call them A and B) of C. On the other hand, L P intersects S precisely at P andP as we have seen above. From L P .S = 2 we infer that this is a transversal intersection. But A and B are contained in S and are transversally there. We can conclude that the tangent space of Z at P is generated by the tangent directions of A, B and L P at P . Hence, the real surface S 0 is singular at P . This implies that S 0 is singular along L P (cf. ) and by such a divisor splits into the sum of two divisors of degree one. Therefore, we have at least as many pairs of conjugate divisors of degree one as we have pairs of conjugate singular points on C. In other words, the number of distinct divisors of degree one is at least equal to the number of components of C. Let D andD be a conjugate pair of divisors of degree one on Z. Then C βŠ‚ D βˆͺD. D ∩D is a real twistor line (cf. ), and no component of C is a real twistor line. Hence, every component of C lies on exactly one of the surfaces D andD. By Lemma 3.2 C ∩ D is connected. The same is true for the conjugate curve C ∩D. Since C is a cycle of rational curves, (C ∩ D) ∩ (C ∩D) consists of a conjugate pair {P,P } of singularities of C. Since D andD are of degree one, the real twistor line L P containing P andP must be contained in D and inD. Therefore, D ∩D = L P . Let D β€² be an arbitrary divisor of degree one containing L P . Then D β€² ∩D β€² = L P and without loss of generality we may assume D β€² ∩ C = D ∩ C, since the decomposition of C into two conjugate connected curves is determined by {P,P } = L P ∩ C. By Lemma 3.1 the restriction map Pic Z β†’ Pic S is injective. , which means that D and D β€² are linearly equivalent. If D = D β€² , then dim |D| β‰₯ 1 and Z would contain infinitely many divisors of degree one and by Kurke and Poon it must be a conic-bundle twistor space. But then we should have dim | βˆ’ 1 2 K| = 3 in contradiction to our assumption. Hence, D = D β€² and we have exactly as many divisors of degree one on Z as C has components. For technical reasons we state here the following lemma needed in Section 5. Lemma 3.8. Let S be a smooth complex surface and C βŠ‚ S a reduced curve. Assume C = m i=1 C i is a "cycle of rational curves" as defined above. If L ∈ Pic (S) is a line bundle, we define l i := L.C i . Let I Β± := {i| Β± l i > 0} and C Β± := i∈I Β± C i . Let Ξ³ denote the number of connected components of C \ C βˆ’ . Assume |I βˆ’ | β‰₯ 2 and each connected component of C \ C βˆ’ contains a component of C + . Then we have: Proof: Let Ξ· :C = βŠ” i C i β†’ C be the normalization of C. By P i we denote the intersection point of C i with C i+1 (1 ≀ i ≀ m). By assumption m β‰₯ 3. Tensoring the exact be the two points onC lying over P i . To describe ρ we observe that the map Ξ· gives isomorphisms L i (P With this notation we have: ρ(s 1 , . . . , s m ) = (s 1 (P 1 ) βˆ’ s 2 (P 1 ), s 2 (P 2 ) βˆ’ s 3 (P 2 ), . . . , s m (P m ) βˆ’ s 1 (P m )). Since then we obtain by induction on r that the restriction of ρ βŠ• r Β΅=0 H 0 (C i+Β΅ , L i+Β΅ ) β†’ βŠ• r Β΅=βˆ’1 C P i+Β΅ is surjective. Because H 0 (C i , L i ) = 0 if and only if l i < 0, we obtain im (ρ) = P¡∈C 0 +C + C PΒ΅ . (Here, we denote I 0 := I \ (I βˆ’ βˆͺ I + ) and C 0 := ν∈I 0 C Ξ½ .) The number of points P Β΅ ∈ C 0 + C + is equal to |I 0 | + |I + | + Ξ³. Therefore, we obtain dim ker(ρ) = The nef case For the rest of the paper we assume n = 4. Remember that (βˆ’ 1 2 K) 3 = 0, Ο‡(K βˆ’ m 2 ) = m + 1 and h 0 (K βˆ’ 1 2 ) β‰₯ 2 in this case. Remember from Mori's theory that a line bundle L ∈ Pic (Z) is called nef, if for each irreducible curve C βŠ‚ Z there holds L.C β‰₯ 0. Theorem 4.1. The following properties are equivalent: (i) K βˆ’ 1 2 is nef; (ii) for all smooth and real S ∈ | βˆ’ 1 2 K| and all C ∈ | βˆ’ K S |, every component C 0 of C has the property C 0 .(βˆ’K S ) = 0; (iii) there exists a smooth and real S ∈ | βˆ’ 1 2 K| and a divisor C ∈ | βˆ’ K S |, such that all components C 0 of C have the property C 0 .(βˆ’K S ) = 0. Corollary 4.3. In Proposition 3.6 we can omit case (III) if K βˆ’ 1 2 is not nef. Proof: Assume C β€² = A β€² +Δ€ β€² as in the proof of Proposition 3.6. A β€² andΔ€ β€² intersect at a pair of conjugate points, say P andP . If Οƒ does not blow up P andP , then, by reality of the blown-up set, on (the strict transforms of) A β€² andΔ€ β€² exactly four points are blown-up. If we denote by A andΔ€ the strict transforms of A β€² andΔ€ β€² in S, then we have C = A +Δ€ and A 2 =Δ€ 2 = βˆ’2. Since A andΔ€ are rational we obtain, by the adjunction formula, A.(βˆ’K S ) =Δ€.(βˆ’K S ) = 0. By Theorem 4.1 this implies that K βˆ’ 1 2 is nef. If Οƒ blows up P andP , then we perform an elementary transform to arrive at case (I) as follows. Let Οƒ 1 : S (1) β†’ P 1 Γ— P 1 be the blow-up of P andP , then we have an induced real structure on S (1) . Since A β€² intersects any fibre at exactly one point, P andP lie on a conjugate pair of fibres. The strict transforms in S (1) of these fibres form a conjugate pair of disjoint (βˆ’1)-curves. Contracting them we obtain a blow-down map Οƒ β€² 1 : S (1) β†’ P 1 Γ—P 1 which is again compatible with real structures. If we denote by E andΔ’ the exceptional curves of Οƒ 1 , then the image of Here A (1) andΔ€ (1) are the strict transforms of A β€² andΔ€ β€² . The morphism Οƒ β€² 1 maps this curve onto a curve of type (I). The non-nef case Throughout this section we assume K βˆ’ 1 2 to be not nef and n = 4. By Theorem 4.1, Remark 4.2 we know that in any smooth real S ∈ |βˆ’ 1 2 K| the anticanonical system | βˆ’ K S | contains only reducible elements. By Proposition 3.6 and Corollary 4.3 we can, therefore, choose a real blow-down S β†’ P 1 Γ— P 1 and a real reduced curve C ∈ |βˆ’ K S |, whose image C β€² in P 1 Γ— P 1 is of type (I) or (II) as described there. Observe that C β€² has type (I) if and only if C contains a real irreducible component. Proof: Let S ∈ | βˆ’ 1 2 K| be smooth and real and choose C ∈ | βˆ’ K S | and Οƒ : S β†’ P 1 Γ— P 1 with the properties of Proposition 3.6. Because any irreducible curve intersecting K βˆ’ 1 2 negatively is contained in C, this curve has a real component. Therefore, the image C β€² of C in P 1 Γ— P 1 is of type (II). Let C β€² = C β€² 0 + F β€² be the decomposition of C β€² . By Lemma 3.3 none of the blown-up points lie on the real fibre F β€² . In particular, only smooth points of C β€² 0 are blown-up. Hence, C = C 0 + F where C 0 and F are the strict transforms of C β€² 0 and F β€² respectively. Therefore, the eight blown-up points lie on C β€² 0 which implies C 2 0 = C β€² 2 0 βˆ’ 8 = βˆ’4. By adjunction formula we obtain βˆ’2 = C 0 .(βˆ’K S ) = C 0 .(βˆ’ 1 2 K). Hence, |βˆ’ K S | = C 0 + |F | and we obtain: dim | βˆ’ K S | = 1 and C 0 is the base locus of | βˆ’ K S |. Since h 1 (O Z ) = 0 the restriction map H 0 (K βˆ’ 1 2 ) Φ‰ H 0 (K βˆ’1 S ) is surjective. Hence, the linear system | βˆ’ 1 2 K| has dimension two and its base locus is precisely C 0 (with multiplicity one). C 0 is the unique irreducible curve in Z having negative intersection number with βˆ’ 1 2 K, since any other such curve should be contained in the base locus of | βˆ’ 1 2 K|. If Z contains a divisor D of degree one, then D +D ∈ | βˆ’ 1 2 K|. If D 0 (D 0 respectively) denotes the restriction of D to S, then D 0 +D 0 ∈ | βˆ’ K S | = C 0 + F . In the proof of Lemma 3.3 we have seen that the real elements of |F | are irreducible. Therefore, any real element of | βˆ’ K S | consists of two distinct real irreducible curves with multiplicity one. This shows that | βˆ’ K S | cannot contain a member of the form D 0 +D 0 . It remains to show that the algebraic dimension of Z must be three in this case. Let Οƒ :Z β†’ Z be the blow-up of the smooth rational curve C 0 . By E βŠ‚Z we denote the exceptional divisor. Then we obtain a morphism Ο€ :Z β†’ P 2 defined by the linear system |βˆ’ 1 2 K| such that Ο€ * O(1) ∼ = Οƒ * K βˆ’ 1 2 βŠ—OZ (βˆ’E). Since the restriction map |βˆ’ 1 2 K| β†’ |βˆ’K S | is surjective, the restriction Ο€ |S is given by the linear system | βˆ’ K S | = C 0 + |F |. This means that Ο€ exibits S as the blow-up of a ruled surface and Ο€(S) is a line in P 2 . Since Ο€(Z) is not contained in a linear subspace, Ο€ must be surjective. If we equip P 2 with the usual real structure, Ο€ becomes compatible with real structures since the linear system | βˆ’ 1 2 K| and the blown-up curve C 0 are real. Since Z does not contain divisors of degree one, any real fundamental divisor S is irreducible and, therefore, smooth. ByS βŠ‚Z we denote the strict transform of S ∈ | βˆ’ 1 2 K|. Since C 0 is a smooth curve in a smooth surface, Οƒ :S β†’ S is an isomorphism. Furthermore, E ∩S will be mapped isomorphically onto C 0 βŠ‚ S. Since F.C 0 = 2 and the restriction of Ο€ ontoS is the map defined by the linear system |F |, the restriction of Ο€ exibits E ∩S as a double covering over Ο€(S) ∼ = P 1 . Since real lines cover P 2 the morphism Ο€ : E β†’ P 2 does not contract curves and is of degree two. Since generic fibres of Ο€ are smooth rational curves, the line bundle OZ (E) restricts to O P 1 (2) on such fibres. Hence, after replacing (if necessary) P 2 by the open dense set U of points having smooth fibre, the adjunction morphism Ο€ * Ο€ * OZ (E) β†’ OZ (E) is surjective. This defines a U -morphism Ξ¦ :Z β†’ P(Ο€ * OZ (E)), where Ο€ * OZ (E) is a locally free sheaf of rank three. The restriction of Ξ¦ to smooth fibres coincides with the Veronese embedding P 1 Φ’β†’ P 2 of degree two. Therefore, the image of Ξ¦ is a three-dimensional subvariety of the P 2 -bundle P(Ο€ * OZ (E)) β†’ U . Hence,Z is bimeromorphically equivalent to a quasiprojective variety and has, therefore, algebraic dimension three. For the rest of this section we assume that there does not exist a real irreducible curve contained in the base locus of | βˆ’ 1 2 K|. We keep the assumptions n = 4 and K βˆ’ 1 2 is not nef. In this situation, we obtain: then there exists at least a oneparameter family of real smooth divisors S ∈ |βˆ’ 1 2 K|, containing a curve C ∈ |βˆ’K S | and possessing a birational morphism Οƒ : S βˆ’β†’ P 1 Γ— P 1 as in Proposition 3.6, such that moreover: A and A are components of C and for twistor fibres F βŠ‚ S we have F.A = F.A = 1. In particular, the image A β€² of A in P 1 Γ— P 1 is a "line", that means A β€² ∈ |O(1, 0)|. Proof: Our assumptions imply that C β€² is a curve of type (I) in Proposition 3.6. The components of C β€² are curves in P 1 Γ— P 1 with self-intersection number zero. They are not real. Hence, after a succession of four blow-ups of a conjugate pair of points, each component A of C fulfills A 2 β‰₯ βˆ’4 in S. The adjunction formula, together with the rationality of A, implies A. Because a curve A with A.(βˆ’ 1 2 K) < 0 must be a component of C, the assertion (a) is shown. Let now A βŠ‚ Z be an irreducible curve with A.(βˆ’ 1 2 K) < 0. Then we have A βŠ‚ C. Let x ∈ A βŠ‚ C be a smooth point of C and x ∈ F βŠ‚ Z a twistor fibre. Since | βˆ’ 1 2 K| is at least a pencil, there exists a divisor S ∈ | βˆ’ 1 2 K| containing a given point y ∈ F \ {x, x}. Because F.S = 2 and S ∩ F βŠƒ {y, x, x} the twistor fibre F is contained in S. So the real subsystem | βˆ’ 1 2 K| F βŠ‚ | βˆ’ 1 2 K| of divisors containing F is not empty. Hence, we can choose a real smooth S ∈ | βˆ’ 1 2 K| containing F . By construction, we have F.A = F.A β‰₯ 1. But F.B β‰₯ 0 for any curve B βŠ‚ S together with F.(βˆ’K S ) = 2 implies F.A = F.A = 1. Because S contains only a real one-parameter family of real twistor lines, the intersection points with real twistor fibres form only a real one-dimensional subset of points z on A. Therefore, we obtain at least a one-parameter family of such surfaces S. Proposition 3.6 implies now the claim. Proposition 5.3. Assume the existence of an irreducible (non-real) curve A βŠ‚ Z with A.(βˆ’ 1 2 K) = βˆ’2. Then: h 0 (K βˆ’ 1 2 ) = 4 and a(Z) = 3. The curves A andΔ€ are disjoint smooth and rational. A andΔ€ are the unique irreducible reduced curves having negative intersection number with βˆ’ 1 2 K. The base locus of | βˆ’ 1 2 K| is exactly the union of A andΔ€. Z contains infinitely many divisors of degree one and is one of the twistor spaces studied by LeBrun and Kurke . Proof: We choose S ∈ | βˆ’ 1 2 K| as in Lemma 5.2(b). Then we have C ∈ | βˆ’ K S | containing A and A as smooth rational components which are mapped to "lines" A β€² and A β€² ∈ |O(1, 0)| in P 1 Γ— P 1 . We have by the adjunction formula which implies that the eight blown-up points lie on A β€² + A β€² (or the strict transforms after partial blow-ups). Hence, any member of A β€² + A β€² + |O(0, 2)| contains the eight blownup points and defines, therefore, a divisor in | βˆ’ K S |. On the other hand, any curve in | βˆ’ K S | is mapped onto a curve of type (2, 2) on P 1 Γ— P 1 containing the blown-up points. Such a curve must contain A β€² and A β€² since the intersection number with A is two, but four of the blown-up points lie on A. Hence, the image of | βˆ’ K S | is precisely the twodimensional system A β€² + A β€² + |O(0, 2)|. So we have dim | βˆ’ K S | = 2. Using the exact sequence 0 β†’ O Z β†’ K βˆ’ 1 2 β†’ K βˆ’1 S β†’ 0, this implies h 0 (K βˆ’ 1 2 ) = 4. Furthermore, we see that A +Δ€ is in the base locus of | βˆ’ K S | which coincides with the base locus of | βˆ’ 1 2 K|. To see that Z contains infinitely many divisors of degree one we modify an idea of Pedersen, Poon : The above description of the image of | βˆ’ K S | in P 1 Γ— P 1 shows that there exist infinitely many real curves C ∈ | βˆ’ K S | whose image C β€² in P 1 Γ— P 1 is of type (I) and the singular points of C β€² are not blown-up. Then C is the strict transform of such a curve and C β€² consists of four irreducible components. Let P andP denote a conjugate pair of singular points of C. Since A andΔ€ are disjoint, both points P andP are contained in A +Δ€, hence in the base locus of | βˆ’ 1 2 K|. On the twistor space Z there exists exactly one real twistor line L P connecting P withP . Let Q ∈ L P be a point different from P andP . The linear system | βˆ’ 1 2 K| Q of all fundamental divisors containing Q has at least dimension dim | βˆ’ 1 2 K| βˆ’ 1 = dim | βˆ’ K S | = 2. Since fundamental divisors have degree two and any member of | βˆ’ 1 2 K| Q contains P,P and Q it also contains L P . Hence, | βˆ’ 1 2 K| Q coincides with the real linear subsystem of divisors in | βˆ’ 1 2 K| containing L P . Choose now a point R ∈ C which is not on A+Δ€. Then the real linear system |βˆ’ 1 2 K| L P ,R,R is non-empty. Let C be decomposed as A +Δ€ + B +B. Then, by our choice of C, B.(βˆ’ 1 2 K) = 2 and A.(βˆ’ 1 2 K) = βˆ’2. These four curves intersect as indicated in the following picture:Δ€ A BB Any real member S 0 of | βˆ’ 1 2 K| L P ,R,R contains three distinct points of B, namely R and the intersection of B with A +Δ€. Hence, B βŠ‚ S 0 . But this means that S 0 contains three curves, say A, B and L P , which meet at P ∈ S 0 . As in the proof of Proposition 3.7 we obtain that S 0 is reducible, hence splits into the sum of two divisors of degree one. Since the intersection of a conjugate pair of divisors of degree one is a twistor line, we obtain in this way infinitely many divisors of degree one on Z. By the result of Kurke-Poon , we obtain that Z is a LeBrun twistor space and A +Δ€ is precisely the base locus of | βˆ’ 1 2 K|. Hence, no other curve can have negative intersection number with (βˆ’ 1 2 K). This proves that really all properties of the Propositon are fulfilled. Proof: By our assumption we obtain the existence of an irreducible curve A βŠ‚ Z with A.(βˆ’ 1 2 K) = βˆ’1. Now we choose S ∈ | βˆ’ 1 2 K| real and smooth and C ∈ | βˆ’ K S | as in Lemma 5.2(b). The curve C ∈ | βˆ’ K S | has A and A as components and the images A β€² and A β€² of A and A in P 1 Γ— P 1 are members of |O(1, 0)|. But A 2 = A.(βˆ’K S ) βˆ’ 2 = βˆ’3 implies that exactly one pair of blown-up points does not lie on A β€² + A β€² . This implies that the two components of C β€² , which are members of |O(0, 1)|, are not movable. Hence, | βˆ’ K S | = {C} and, as above, h 0 (K βˆ’ 1 2 ) = 2. Because C β€² is of type (I), the curve C consists of 2, 3, 4, 5 or 6 pairs of conjugate rational curves. By Proposition 3.7 we have: the number of components of C is equal to the number of effective divisors of degree one. It remains to be seen that the algebraic dimension is three. Since | βˆ’ 1 2 K| is a pencil we study in more detail the linear system | βˆ’ K| on Z. We need to investigate the structure of C before we can collect more information on the linear system | βˆ’ 2K S |. We know that the blow-up Οƒ : S β†’ S (0) := P 1 Γ— P 1 factors through a succession of four blow-ups S = S (4) β†’ S (3) β†’ S (2) β†’ S (1) β†’ S (0) such that at each step a conjugate pair of points is blown-up. The image of C in S (i) will be denoted by C (i) . The blown-up points in S (i) should lie on C (i) . If they are smooth points of C (i) then C (i+1) ∼ β†’ C (i) . If we blow up a conjugate pair of singular points of C (i) , the curve C (i+1) has two components more than C (i) . By assumption, C (0) = C β€² βŠ‚ P 1 Γ— P 1 is of type (I). Each C (i) is a "cycle of rational curves". We can choose the factorization of Οƒ in such a way that at the first k steps, only singular points of C (i) are blown-up and at the last 4 βˆ’ k steps, only smooth points of C (i) are blown-up. Then C will have 2(2 + k) components, where 0 ≀ k ≀ 4. If we would have a component A of C with A 2 = 0, then the image A (0) of A in S (0) would be a component of C (0) and none of the blown-up points would lie on A (0) . But then four of the blown-up points must lie on a line or on a fibre in S (0) , which implies that C has a component B with B 2 = βˆ’4. This was excluded by assumption. Therefore, for any component A of C we have βˆ’1 β‰₯ A 2 β‰₯ βˆ’3. Since A is a smooth rational curve, this means A.(βˆ’K S ) ∈ {βˆ’1, 0, +1}. By assumption C is reduced. Let C = m Ξ½=1 C Ξ½ be the decomposition of C into irreducible components. By Proposition 3.6 we have C Ξ½ ∼ = P 1 , C Ξ½ .C Ξ½+1 = 1 and C Ξ½ intersects only C Ξ½βˆ’1 and C Ξ½+1 . (This means "C is a cycle of rational curves". For convenience, we use cyclic subscripts, that is C Ξ½ = C Ξ½+m .) For Ξ΅ ∈ {βˆ’1, 0, +1} we define I Ξ΅ := {Ξ½|C Ξ½ .(βˆ’K S ) = Ξ΅} and C Ξ΅ := ν∈IΞ΅ C Ξ½ . In this way we split C into three parts C = C βˆ’ + C 0 + C + . As The assumption that K βˆ’ 1 2 is not nef implies I βˆ’ = βˆ…. The curve C has no real component, hence |I βˆ’ | = |I + | β‰₯ 2. Claim: Any two components of C + are disjoint. Let C Ξ± and C Ξ² be two distinct components of C + . Then C 2 Ξ± = C 2 Ξ² = βˆ’1. If C Ξ± and C Ξ² are both contracted to a point on S (0) , they are obviously disjoint. If C Ξ± and C Ξ² are mapped to curves in S (0) , by our choice of S both must be members of |O(0, 1)|, because A and A are components of C βˆ’ . Finally, we have to exclude the case where C Ξ± is mapped to a curve C β€² Ξ± ∈ |O(0, 1)| in P 1 Γ— P 1 and C Ξ² is contracted to a point P ∈ C β€² Ξ± . This implies C Ξ± = C Ξ² . Since C Ξ² is a component of the anticanonical divisor C βŠ‚ S, the point P must be singular on C β€² . Thus, we can take S (1) βˆ’β†’ S (0) = P 1 Γ— P 1 to be the blow-up of P and P . The curve C (1) consists then of six (βˆ’1)-curves among which we find the images of C Ξ± , C Ξ² , C Ξ± and C Ξ² . Because those are (βˆ’1)-curves on S, the remaining six blown-up points must lie on one pair of (βˆ’1)-curves giving rise to (βˆ’4)-curves in C contradicting our assumption. Thus, the claim is proved and C + is the disjoint union of an even number of smooth rational (βˆ’1)-curves. Since C is a cycle of rational curves, the curve C \ C + = C βˆ’ + C 0 has the same number of connected components as C + . We claim that each connected component of C βˆ’ + C 0 contains exactly one component of C βˆ’ . Since C βˆ’ and C + have the same number of components, this is equivalent to the statement that each connected component of C βˆ’ + C 0 contains at most one component of C βˆ’ . Assume the contary, that is there is a connected component of C βˆ’ + C 0 containing two irreducible components of C βˆ’ . Then these two components of C βˆ’ are not conjugate to each other. (Two conjugate components of C are "opposite" in the cycle C.) Therefore, C βˆ’ has at least four components and so C + . Thus C βˆ’ + C 0 has at least four connected components, hence at least six irreducible ones. Therefore, C contains at least ten irreducible components, that is k β‰₯ 3. Therefore, the image C (3) of C in S (3) consists of a cycle of ten rational curves with self-intersection numbers βˆ’2, βˆ’1, βˆ’3, βˆ’1, βˆ’2, βˆ’2, βˆ’1, βˆ’3, βˆ’1, βˆ’2 (in this order). By assumption, at the last step of blow-up, no point on a (βˆ’3)-curve is blown-up. To obtain a second pair of (βˆ’3)-curves, we have to blow up points on a conjugate pair of (βˆ’2)-curves. Such curves are not neighbours in the cycle C (3) , they are opposite to each other. Thus, one easily sees that after the last step of blow-up, between two (βˆ’3)-curves on the cycle C we always have a (βˆ’1)-curve. This means that no connected component of C \ C + contains two irreducible components of C βˆ’ , as claimed. We can now compute the dimension of | βˆ’ K| and | βˆ’ 2K S |. The Riemann-Roch formula and h 0 (K βˆ’ 1 2 ) = 2 imply h 1 (K βˆ’ 1 2 ) = 0. Hence, the exact . We can apply Lemma 3.8 with L = K βˆ’2 S , because we have seen that the components of C + are disjoint to each other and that each connected component of C \ C + contains exactly one irreducible component Next we study the base locus of | βˆ’ 2K S |. Since any component A of C βˆ’ fulfills A.(βˆ’K S ) = βˆ’1, C βˆ’ is in the base locus of | βˆ’ 2K S |. Now let A be an irreducible component of C 0 . Since, as we have shown above, any connected component of C 0 + C βˆ’ contains a curve B βŠ‚ C βˆ’ there exists a finite chain of components A 1 , . . . , it must be contained in this base locus. Hence, by induction on i, we obtain that A i is contained in the base locus of | βˆ’ 2K S | for all 1 ≀ i ≀ r. This shows that C 0 + C βˆ’ is contained in the base locus of the linear system | βˆ’ 2K S |. Therefore, we have | βˆ’ 2K S | = C 0 + C βˆ’ + | βˆ’ K S + C + | and the map defined by | βˆ’ 2K S | coincides with the map given by | βˆ’ K S + C + |. We have seen above that C + is a disjoint union of smooth rational (βˆ’1)-curves. We can, therefore, contract C + to obtain a smooth surface S β€² . If Οƒ β€² : S β†’ S β€² is this contraction, we have K βˆ’1 S βŠ— O S (C + ) ∼ = Οƒ β€² * (K βˆ’1 S β€² ). Hence, βˆ’K S β€² is nef if and only if βˆ’K S + C + is nef. First we deal with the case where C + βˆ’ K S is nef. In this case, the generic member of the moving part of | βˆ’ 2K S | is irreducible. This can be seen as follows: Observe first that S β€² can be blown down to P 2 . This follows from because βˆ’K S β€² is nef and K 2 S β€² = |I + | > 0. Because C + has 2, 4 or 6 components, S β€² β†’ P 2 is a blow-up of 7, 5 or 3 points. Therefore, we can apply a theorem of Demazure stating that | βˆ’ K S β€² | contains a smooth irreducible member and is base point free if | βˆ’ K S β€² | is nef. Hence, there exists a smooth irreducible curve in | βˆ’ K S β€² | avoiding the blown-up points. Its preimage in S is a smooth irreducible member of |Οƒ * K βˆ’1 Since dim | βˆ’ 2K S | β‰₯ 2 and the generic member of the moving part of | βˆ’ 2K S | is a smooth irreducible curve, the image of the map defined by | βˆ’ 2K S | has dimension two. We have seen before that the restriction | βˆ’ K| Φ‰ | βˆ’ 2K S | is surjective which implies that the map Ξ¦ |βˆ’K| given by | βˆ’ K| on Z coincides, after restriction to S, with the map given by | βˆ’ 2K S |. Since 2S ∈ | βˆ’ K|, the Ξ¦ |βˆ’K| -image of S is contained in a hyperplane. But the Ξ¦ |βˆ’K| -image of Z cannot be contained in a hyperplane. Therefore, the image of Ξ¦ |βˆ’K| has dimension three. This implies a(Z) = 3. We are left with the case where C + βˆ’ K S is not nef. In this case we shall see that Ξ¦ |βˆ’K| has only two-dimensional image but equips Z with a conic-bundle structure. Under the assumption that C + βˆ’ K S is not nef we study the structure of C. Let A be an irreducible curve in S with A.(C + βˆ’ K S ) < 0. If A C, then A.C + β‰₯ 0. But the base locus of | βˆ’ K S | is contained in C and this implies A.(βˆ’K S ) β‰₯ 0. Hence, we have necessarily A βŠ† C. If A βŠ† C + , then A.(βˆ’K S ) = 1 and A.C + β‰₯ A 2 , hence, So, we obtain: the irreducible curves A βŠ‚ S with A.(C + βˆ’ K S ) < 0 are exactly those components of C βˆ’ which are disjoint to C + . They fulfill A.(C + βˆ’ K S ) = βˆ’1. As we have seen above, each connected component of C \ C + contains exactly one irreducible component of C βˆ’ . Hence, if A is a component of C βˆ’ which does not meet C + , then its connected component should contain at least two curves from C 0 . Thus, using reality, we see that C has at least eight components. This means, using the convention introduced above, the image C (2) of C in S (2) (the surface obtained after two steps of blowup) consists of eight curves whose self-intersection numbers are alternately βˆ’1 and βˆ’2: One now easily sees: if we were to blow up a pair of singular points on C (2) , in the resulting curve C (3) any (βˆ’2)-curve would meet a (βˆ’1)-curve and any (βˆ’3)-curve would meet two (βˆ’1)-curves. Therfore, after the last step of blow-up, no (βˆ’3)-curve is disjoint to all (βˆ’1)-curves on C. Thus, we can only blow up smooth points in the last two steps. If we were to blow up a conjugate pair of points on (βˆ’2)-curves, the resulting (βˆ’3)-curve would intersect two (βˆ’1)-curves. Then, again, in C there would be no (βˆ’3)-curve disjoint to all (βˆ’1)-curves. So we conclude that the last two pairs of conjugate blown-up points cannot lie on (βˆ’2)-components of C (2) . If each of the four (βˆ’1)-curves in C (2) contains one of the blown-up points, then any component of C has zero intersection number with βˆ’K S . But, then by Theorem 4.1, K βˆ’ 1 2 would be nef which contradicts our general assumption. Thus, the four blown-up points lie on a pair of conjugate (βˆ’1)-curves. The structure of C is, therefore, the following: In particular, we obtain: dim | βˆ’ 2K S | = |I + | = 2 and dim | βˆ’ K| = 2 + dim | βˆ’ 2K S | = 4. Furthermore, since both components of C βˆ’ have negative intersection number with C + βˆ’ K S , the curve C βˆ’ is contained in the base locus of |C + βˆ’ K S |. This means | βˆ’ 2K S | = |2C + + C 0 | + C 0 + 2C βˆ’ . By our choice of S, the two components A and A of C βˆ’ are mapped onto lines A β€² and A β€² on P 1 Γ— P 1 . The above analysis of C shows that we can decompose Οƒ : S βˆ’β†’ P 1 Γ— P 1 into the following steps: First we blow up a conjugate pair of singular points on the curve C β€² (which is of type (I)). This produces precisely two singular fibres of the ruling (whose general fibre is the image of a twistor fibre). In the second step we blow up the two singular points of these singular fibres. The exceptional curves of this blow-up form the components of C + . Because we blow up points of multiplicity two on the fibres, the total transform of the two singular fibres contains 2C + . In the remaining two steps we have to blow up smooth points on A β€² + A β€² . Hence, we obtain C 0 + 2C + ∈ |2F |. So, we can write | βˆ’ 2K S | = C 0 + 2C βˆ’ + |2F |. Since we have dim | βˆ’ 1 2 K| = 1, this is true for the generic real surface S ∈ | βˆ’ 1 2 K| by Lemma 5.2 (b). Let us denote by Ξ¦ = Ξ¦ |βˆ’K| the meromorphic map Z P 4 defined by | βˆ’ K|. If Ο• : S β†’ P 2 is the restriction of Ξ¦ to a generic smooth real S ∈ | βˆ’ 1 2 K|, then the image of Ο• is a conic in P 2 . The general fibre of Ο• is a twistor fibre, hence a smooth rational curve intersecting C transversally at two points lying on A and A respectively. LetZ β†’ Z be a modification such that Ξ¦ becomes a morphismΞ¦ :Z β†’ P 4 . Because the smooth real fundamental divisors S sweep out a Zariski dense subset of Z, the image of this set is also Zariski dense inΞ¦(Z) βŠ‚ P 4 . As the general fibre of Ξ¦, restricted to such surfaces S, is one-dimensional, we obtain dimΞ¦(Z) = 2. SinceZ β†’ Z is a modification, there exists an open Zariski dense subset U βŠ‚Ξ¦(Z) such that the fibres ofΞ¦ are irreducible curves. Moreover, we can choose U such that the fibres ofΞ¦ over U are isomorphic to P 1 ,because this is true over a Zariski dense subset ofΞ¦(Z). LetΞ¦ :Z U β†’ U denote the restriction of Ξ¦ over U . Then the preimage inZ of the two components of C βˆ’ defines a pair of divisors Ξ£ andΞ£ inZ U which are sections ofZ U β†’ U . Therefore, E :=Ξ¦ * OZ U (Ξ£ +Ξ£) is a vector bundle of rank three on U and the canonical morphismΞ¦ * E β†’ O(Ξ£ +Ξ£) is surjective. This means that we obtain a morphismZ U β†’ P(E) which is compatible with the projections to U . Restricted to each fibre this morphism is the Veronese embedding of degree two P 1 Φ’β†’ P 2 . Hence, the image ofZ U in the quasi-projective variety P(E) is three-dimensional. This implies a(Z) = a(Z U ) = 3, which completes the proof. Conclusions In this section we collect the results of this paper to obtain a clear picture of the situation considered. By Z we always denote a simply connected compact twistor space of positive type over 4CP 2 . We call N := {C βŠ‚ Z | C irreducible curve, C.(βˆ’ 1 2 K) < 0} the set of negative curves. By definition, K βˆ’ 1 2 is nef if and only if N = βˆ…. The structure of N is described by the following Theorem 6.1. If N = βˆ… this set consists of a finite number of smooth rational curves. More precisely, only the following cases are possible: (a) N contains a real member C 0 . Then: N = {C 0 } and C 0 (βˆ’ 1 2 K) = βˆ’2, dim |βˆ’ 1 2 K| = 2 and a(Z) = 3. Proof: This is immediate from the previous theorem, because a pencil | βˆ’ 1 2 K| has always base points. Remark 6.9. The reverse implication is not true, which follows from the existence theorem in . There, twistor spaces with a(Z) = 2 and dim | βˆ’ 1 2 K| = 1 over 4CP 2 were constructed.