content
stringlengths
10
4.9M
// ConfigClientPermissionsToProto converts a ConfigClientPermissions object to its proto representation. func IdentitytoolkitBetaConfigClientPermissionsToProto(o *beta.ConfigClientPermissions) *betapb.IdentitytoolkitBetaConfigClientPermissions { if o == nil { return nil } p := &betapb.IdentitytoolkitBetaConfigClientPermissions{} p.SetDisabledUserSignup(dcl.ValueOrEmptyBool(o.DisabledUserSignup)) p.SetDisabledUserDeletion(dcl.ValueOrEmptyBool(o.DisabledUserDeletion)) return p }
<gh_stars>10-100 {-- EXERCISES --} import Notes ( BinTreeInt(LeafInt, NodeInt) , BinTree(Leaf, Node) , inorder , height ) import TreePrinter -- Exercise 1 -- Define a Haskell datatype Tree1 for a tree that contains a -- character and an integer in each node, along with exactly three -- subtrees. data Tree1 = Leaf1 | Node1 Integer Char Tree1 Tree1 Tree1 deriving Show -- Exercise 2 -- Define a Haskell datatype Tree2 for a free that contains an integer -- in each node, and that allows each node to have any number of subtrees data Tree2 = Leaf2 | Node2 Integer [Tree2] deriving Show -- Exercise 3 -- Calculate the inorder traversal of tree3 tree3 :: BinTreeInt tree3 = NodeInt 4 (NodeInt 2 (NodeInt 1 LeafInt LeafInt) (NodeInt 3 LeafInt LeafInt)) (NodeInt 7 (NodeInt 5 LeafInt (NodeInt 6 LeafInt LeafInt)) (NodeInt 8 LeafInt LeafInt)) inorderBinTreeInt :: BinTreeInt -> [Int] inorderBinTreeInt LeafInt = [] inorderBinTreeInt (NodeInt a l r ) = inorderBinTreeInt l ++ [a] ++ inorderBinTreeInt r tree3inorder = inorderBinTreeInt tree3 -- [1,2,3,4,5,6,7,8] -- Exercise 4. -- Suppose that a tree has type BinTree a, and we have a function -- f :: a -> b. Write a new traversal function: inorderf :: (a->b) -> BinTree a -> [b] -- that traverses the tree using inorder, but it applies f to the -- data value in each node before placing the result in the list. -- For example, inorder tree6 produces [1,2,3,4,5,6,7] but -- inorderf (2*) tree6 produces [2,4,6,8,10,12,14] inorderf _ Leaf = [] inorderf f (Node a l r) = inorderf f l ++ [f a] ++ inorderf f r inorderf' :: (a -> b) -> BinTree a -> [b] inorderf' f t = map f $ inorder t -- Exercise 5 -- Define two trees of size seven, one with the largest possible -- height and the other with the smallest possible height -- height max => 7 sevenTreeHuge :: BinTree Int sevenTreeHuge = Node 1 Leaf (Node 2 Leaf (Node 3 Leaf (Node 4 Leaf (Node 5 Leaf (Node 6 Leaf (Node 7 Leaf Leaf)))))) -- smallest height -> 3 =~ sqrt(7) sevenTreeBalanced :: BinTree Int sevenTreeBalanced = Node 1 (Node 2 (Node 4 Leaf Leaf ) (Node 6 Leaf Leaf)) (Node 3 (Node 5 Leaf Leaf) (Node 7 Leaf Leaf)) -- Exercise 6 -- Suppose that the last equation of the function balanced -- were changed to the following: -- balanced (Node x t1 t2) = balanced t1 && balanced t2 -- Give an example showing that the modified function returns -- True for an unbalanced tree unbalancedTree = Node 1 Leaf (Node 2 Leaf Leaf) {-- Hand written evaluation balanced unbalancedTree balanced (Node 1 l r) = balanced l && balanced r = balanced Leaf && balanced (Node 2 Leaf Leaf) = True && balanced Leaf && balanced Leaf = True && True && True = True --} -- Exercise 7 -- Suppose that the last equation of the function balanced -- were changed to the following: -- balanced (Node x t1 t2) = height t1 == height t2 -- Give an example showing that the modified function -- returns True for an unbalanced Tree. {-- EXAMPLE 1 / \ 2 3 / \ 4 5 --} unbalancedTree' = Node 1 (Node 2 Leaf (Node 4 Leaf Leaf)) (Node 3 Leaf (Node 5 Leaf Leaf)) {-- Hand written evaluation balanced unbalancedTree' balanced (Node 1 l r) = height l == height r = 2 == 2 = True --} -- Exercise 8 -- Define a function mapTree that takes a function and applies -- it to every node in the tree, returning a new tree of results. -- The type should be: mapTree :: (a -> b) -> BinTree a -> BinTree b -- This function is analogous to map, which operators over lists. mapTree f Leaf = Leaf mapTree f (Node a l r) = Node (f a) (mapTree f l) (mapTree f r) -- Exercise 9 -- Write concatTree, a function that takes a tree of lists -- a function that takes a tree of lists and concatenates -- the lists in order from left to right. For example, -- concatTree (Node [2] (Node [3,4] Leaf Leaf) -- (Node [5] Leaf Leaf)) -- ==> [3,4,2,5] concatTree :: BinTree [a] -> [a] concatTree Leaf = [] concatTree (Node xs l r) = concatTree l ++ xs ++ concatTree r -- Exercise 10 -- Write zipTree, a functino that takes two trees and pairs each -- of the corresponding elements in a list. Your function should -- return Nothing if the two trees do not have the same shape. -- For example sameShape :: BinTree a -> BinTree b -> Bool sameShape Leaf Leaf = True sameShape (Node _ l1 r1) (Node _ l2 r2) = sameHeight l1 l2 && sameHeight r1 r2 && sameShape l1 l2 && sameShape r1 r2 where sameHeight l r = height l == height r zipTree :: BinTree a -> BinTree b -> Maybe [(a,b)] zipTree t1 t2 | sameShape t1 t2 = Just $ zip (inorder t1) (inorder t2) | otherwise = Nothing -- Exercise 11. Write zipWithTree, a function that is like zipWith -- except that it takes trees instead of lists. The first argument is -- a function of type (a->b->c) the second argument is a tree with elements -- of type a and the third argument is a tree with elements of type b. -- The function returns a list with type [c] -- IN THIS VERSIONS IS USED THE MAYBE MONAD BECAUSE... YES! -- Why not use monads after all? -- Monads ARE MONADS (most precise definition known) zipWithTree :: (a -> b -> c) -> BinTree a -> BinTree b -> Maybe [c] zipWithTree f t1 t2 = let z = zipTree t1 t2 in zipMaybe z where zipMaybe Nothing = Nothing zipMaybe (Just xs) = Just [f a b | (a,b) <- xs] -- Exercise 12. Write appendTree, a function that takes a binary tree and a -- list, and appends the contents of the tree (traversed from left to right) to -- the front of the list. For example, -- appendTree (BinNode 2 (BinNode 1 BinLeaf BinLeaf) -- (BinNode 3 BinLeaf BinLeaf)) -- [4,5] -- evaluates to [1,2,3,4,5]. Try to find an efficient solution that minimises -- recopying. appendTree :: BinTree a -> [a] -> [a] appendTree Leaf xs = xs appendTree (Node x l r) xs = appendTree l (x : appendTree r xs) -- this is the same definition as g from inorder' on Notes.hs -- the partial function to write a inorder more efficiently
import Container from '@mui/material/Container'; import Typography from '@mui/material/Typography'; import Box from '@mui/material/Box'; import { useTheme } from '@mui/system'; import { Divider } from '@mui/material'; import AppbarComponent from '../src/components/organisms/Appbar'; export default function Swap() { const theme = useTheme(); return ( // create a swap dex with material ui and react <Container maxWidth='md'> <AppbarComponent /> <Box my={4}> <Typography variant='h4' component='h1' gutterBottom> Matisse dex swap </Typography> <Divider /> </Box> </Container> ); }
async def ensemble_forecast(): timer_wfc = Timer( text="Overall duration for preparing weather forecasts: {:.2f} seconds", logger=logger.success, ) with timer_wfc: dict_id_href_body = await get_simulation_request_bodies() timer_overall = Timer( text="Overall duration for running all simulations: {:.2f} seconds", logger=logger.success, ) with timer_overall: q_repr_all = await await_collection_of_simulatons(dict_id_href_body) return q_repr_all
package scheduler; import org.junit.Assert; import org.junit.Test; import scheduler.restaurants.Kitchen; import scheduler.restaurants.OrderDelivery; import java.util.Arrays; import java.util.Collection; public class KitchenTest { @Test public void testChefDelivery() { Kitchen kitchen = new Kitchen(); kitchen.schedule(new Order<>(1L, 0L, Resource.of(new OrderDelivery()))); kitchen.schedule(new Order<>(2L, 1L, Resource.of(new OrderDelivery()))); kitchen.schedule(new Order<>(3L, 2L, Resource.of(new OrderDelivery()))); kitchen.schedule(new Order<>(4L, 3L, Resource.of(new OrderDelivery()))); System.out.println(Arrays.toString(kitchen.deliver().stream() .flatMap(Collection::stream).toArray())); System.out.println(Arrays.toString(kitchen.deliver().stream() .flatMap(Collection::stream).toArray())); System.out.println(Arrays.toString(kitchen.deliver().stream() .flatMap(Collection::stream).toArray())); System.out.println(Arrays.toString(kitchen.deliver().stream() .flatMap(Collection::stream).toArray())); Assert.assertTrue(kitchen.isEmpty()); } }
/** * Unit tests for {@link DefaultComments}. * @author George Aristy ([email protected]) * @since 0.4.0 * @checkstyle MultipleStringLiterals (500 lines) */ public final class DefaultCommentsTest { private static final String COMMENTS = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<comments>\n" // @checkstyle LineLength (1 line) + " <comment id=\"42-306\" author=\"root\" issueId=\"HBR-63\" deleted=\"false\" text=\"comment 1!\" shownForIssueAuthor=\"false\"\n" + " created=\"1267030230127\">\n" + " <replies/>\n" + " </comment>\n" // @checkstyle LineLength (1 line) + " <comment id=\"42-307\" author=\"root\" issueId=\"HBR-63\" deleted=\"false\" text=\"comment 2?\" shownForIssueAuthor=\"false\"\n" + " created=\"1267030238721\" updated=\"1267030230127\">\n" + " <replies/>\n" + " </comment>\n" + "</comments>"; /** * Stream returns all comments. * @throws Exception unexpected */ @Test public void testStream() throws Exception { assertThat( new DefaultComments( new MockLogin(), new MockIssue( new MockProject("", "", "") ), () -> new MockHttpClient( new MockOkResponse(COMMENTS) ) ).stream().count(), new IsEqual<>(2L) ); } }
The Dancing Gaze Across Cultures: Kazuo Ohno's Admiring La Argentina Kazuo Ohno's 1977 butoh dance Admiring La Argentina is studied as a Bergsonian reflection on “pastness” in performance. As the work questions the absolute quality of the present, it is initially compared with Paul Valéry's concept of La Argentina's dance as existing in the dimension of temporal immediacy. Ohno's relation to La Argentina is discussed as spirit possession, primal identification, cultural anthropophagy, productive consumption, and memorialization. Ultimately, the analysis leads to the premise of excorporation or heteropathic identification. The essay concludes with a 2007 meditation on Yoshito Ohno's homage to his father, Emptiness ( Kuu ).
package com.robaone.taskmanager.data; import java.util.Date; import com.robaone.dbase.HDBConnectionManager; import com.robaone.taskmanager.Storage; import com.robaone.taskmanager.project.Project; import com.robaone.taskmanager.project.ProjectNote; import com.robaone.taskmanager.project.Task; public class MysqlStorage implements Storage { protected HDBConnectionManager cman; public MysqlStorage(HDBConnectionManager connectionManager){ this.cman = connectionManager; } @Override public void save(Project p) throws Exception { StoreProject store = new StoreProject((MysqlProject)p); store.run(this.getConnectionManager()); } private HDBConnectionManager getConnectionManager() { return cman; } @Override public void delete(Project p) throws Exception { DeleteProject delete = new DeleteProject((MysqlProject)p); delete.run(this.getConnectionManager()); } @Override public void delete(Task t) throws Exception { DeleteTask delete = new DeleteTask((MysqlTask)t); delete.run(this.getConnectionManager()); } @Override public Project[] getProjectList() throws Exception { GetProjects get = new GetProjects(0,100); get.run(this.getConnectionManager()); return get.getRecords().toArray(new Project[0]); } @Override public Project[] getProjectsBefore(Project p) throws Exception { GetProjectsBefore getBefore = new GetProjectsBefore((MysqlProject)p); getBefore.run(getConnectionManager()); return getBefore.getRecords().toArray(new Project[0]); } @Override public double getAvailableHours(Date time) { ProjectCalendar calendar = ProjectCalendarFactory.newInstance(); double hours = calendar.getAvailableHours(time); return hours; } @Override public Project getProject(int projectid) throws Exception { GetProject get = new GetProject(projectid); get.run(this.getConnectionManager()); return get.getRecordCount() > 0 ? get.getRecord(0) : null; } @Override public void addTask(Project projectImpl, Task t) { // TODO Auto-generated method stub } @Override public Task[] getTasks(Project projectImpl) { // TODO Auto-generated method stub return null; } @Override public Task getTask(Project projectImpl, int taskid) { // TODO Auto-generated method stub return null; } @Override public void cancel(Task taskImpl) throws Exception { // TODO Auto-generated method stub } @Override public void complete(Task taskImpl) throws Exception { // TODO Auto-generated method stub } @Override public void setStatus(Task taskImpl, String status) throws Exception { // TODO Auto-generated method stub } @Override public void addTaskNode(Task taskImpl, ProjectNote note) throws Exception { // TODO Auto-generated method stub } @Override public ProjectNote[] getTaskNotes(Task taskImpl) throws Exception { // TODO Auto-generated method stub return null; } @Override public double getTaskHoursSpent(Task taskImpl) throws Exception { // TODO Auto-generated method stub return 0; } @Override public void save(Task taskImpl) throws Exception { // TODO Auto-generated method stub } }
import * as K from 'kefir'; type Event$ = K.Property<Event, any>; export declare interface Browser { focus: Event$; } // export declare interface Keyboard { keydown: Event$; keyup: Event$; }
/// Helper method to decline order. It is used only inside this module, so it is private. pub fn decline_order(&mut self, order_id: &Hash) { if let Some(order) = self.orders().get(order_id) { if order.status() == "pending" { let new_order = Order::new( order.public_key(), order.owl_id(), "declined", order.price(), ); self.orders_mut().put(order_id, new_order); } } }
<reponame>arneboe/idea-rust package vektah.rust.ide.structure; import com.intellij.ide.structureView.StructureViewModel; import com.intellij.ide.structureView.StructureViewModelBase; import com.intellij.ide.structureView.StructureViewTreeElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; class RustStructureViewModel extends StructureViewModelBase implements StructureViewModel.ElementInfoProvider { public RustStructureViewModel(@NotNull PsiFile psiFile) { super(psiFile, new RustStructureViewNode(psiFile)); } @Override public boolean isAlwaysShowsPlus(StructureViewTreeElement structureViewTreeElement) { return false; } @Override public boolean isAlwaysLeaf(StructureViewTreeElement structureViewTreeElement) { return structureViewTreeElement instanceof RustStructureViewNode && ((RustStructureViewNode) structureViewTreeElement).isLeafNode(); } }
/** * An extended version of {@link CassandraAlertLog} that adds insert capability. */ class CassandraAlertLogImporter extends CassandraAlertLog { private static long HOUR_IN_MILLIS = 60 * 60 * 1000; private PreparedStatement statement = null; public CassandraAlertLogImporter(Session db, CrawlLog log) { super(db, log); this.statement = session.prepare( "INSERT INTO " + CassandraProperties.KEYSPACE + "." + CassandraProperties.COLLECTION_ALERT_LOG + " (" + CassandraProperties.FIELD_ALERT_LOG_TIMESTAMP + ", " + CassandraProperties.FIELD_ALERT_LOG_TIMESTAMP_HR + ", " + CassandraProperties.FIELD_ALERT_LOG_OFFENDING_HOST + ", " + CassandraProperties.FIELD_ALERT_LOG_ALERT_TYPE + ", " + CassandraProperties.FIELD_ALERT_LOG_DESCRIPTION + ") " + "VALUES (?, ?, ?, ?, ?);"); } public void insert(DefaultAlert alert) { BoundStatement boundStatement = new BoundStatement(statement); session.execute(boundStatement.bind( alert.getTimestamp(), getHour(alert.getTimestamp()), alert.getOffendingHost(), alert.getAlertType().name(), alert.getAlertDescription())); } public void insert(List<DefaultAlert> alerts) { for (DefaultAlert alert : alerts) insert(alert); } public static long getHour(long timestamp) { // Truncates the timestamp the nearest full hour (due to integer division) return (timestamp / HOUR_IN_MILLIS) * HOUR_IN_MILLIS; } }
Annie Clark's poise has only gotten more resolute over the course of her four albums, but her musical life began years before her 2007 debut, Marry Me. Born in Tulsa, Oklahoma, she moved to Dallas following her parents' divorce when she was three. Including step- and half-siblings, she has four brothers and four sisters, though she mostly grew up with her mom, stepdad, and two sisters. "It wasn't like 'The Brady Bunch'," she quips. Though she's loath to talk about her family with a recorder on—"That's not anybody's business"—Clark offers the following when asked about how her childhood may have affected her later accomplishments: "Pain and feeling unworthy is just as good a motivator of success as feeling like you're entitled to everything." At the start, she wouldn't play guitar and sing unless her family was talking amongst themselves in another room, though that shyness ended quickly. She played her first show around age 15 in Dallas, performing Jimi Hendrix's "The Wind Cries Mary". Standing in the shadows near the back of the room were two musical virtuosos who flew in just for the occasion: Tuck Andress and Patti Cathcart, aka world-touring guitar-and-vocal jazz duo Tuck & Patti, aka Clark's uncle and aunt. "Even at that early age she was able to go into an all-or-nothing performance mode," says Andress. "She was no more ridiculously outgoing than the average person, but when she was on stage she was like a fireball, even that first time." Watch an old video of Andress playing an entire band's worth of parts just with his guitar, and his influence on his niece's fingerpicking style and posture (and swirling hair) is instantly apparent. (One YouTube commenter enthused, "He's the fucking bob ross of guitar," which probably isn't too far off.) But while Andress' sister let him know that Annie was following in his footsteps early on, he stresses that he never went out of his way to guide Clark's hand. Instead, he and Cathcart invited Clark to help them out on a Japanese tour less than a year after that first Dallas show, so she could see what the life of a musician was like up-close. "She would be sitting in the dressing room playing guitar," remembers Andress, "and these Japanese rock stars would walk in and their eyes would open wide when they saw little Annie just tearing it up." Three years later, before heading off to Boston's prestigious Berklee College of Music, Clark road managed one of her aunt and uncle's European tours, handling everything from security, to press, to the equipment onstage. "I was just in awe of their musicianship," says Clark of Andress and Cathcart, whose original songs and covers of hits like Cyndi Lauper's "Time After Time" could reasonably be described as easy listening. "My tastes were more rock or pop-leaning at the time, but it's unpretentious music and it moved people to tears every night. It's far too easy in this culture to dismiss someone's life's work with arrogant snark, but it's like, 'What have you ever fucking done?'" Clark's education on the road would arguably prove to be more enlightening than her time at Berklee, where the self-taught guitarist struggled with the school's more pragmatic approach to becoming a musician. "Berklee's primary responsibility is to make you competent and employable, not to learn how to be more creative or more yourself," says Andress. "Annie found that side of it off-putting." After three years, she dropped out. On the subject of her own startling aptitude on the guitar, Clark can be strident ("I'm an actual musician—I didn't start playing guitar yesterday") and also somewhat proudly ignorant ("I can't read music"). She bristles at the idea of being a "trained" musician. "I feel lucky that when I put my fingers down on a guitar I'm not 100 percent sure what's going to happen," she explains. "Knowledge is something to fall back on if you get stuck, but ultimately the goal is to play with abandon." St. Vincent keyboardist Daniel Mintseris, who's studied various types of music since childhood, backs up Clark's philosophy. "More than most educated people I've met, Annie's able to use her education selectively, so she develops a language of her own," he tells me. "In some aspects she really can point out a specific step in the scale or a chord, but that doesn't come up all that often. Usually we're able to communicate musically directly—we don't need too many words."
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package net.microfalx.binserde.serializer; import net.microfalx.binserde.io.Encoder; import net.microfalx.binserde.metadata.DataType; import java.io.IOException; import java.time.*; class ReflectionTimeSerializer extends ReflectionFieldSerializer { ReflectionTimeSerializer(ReflectionSerializer<?> parent) { super(parent); } @Override void serialize(DataType dataType, Object value, Encoder encoder) throws IOException { switch (dataType) { case TIME_DURATION: writeDuration((Duration) value, encoder); break; case TIME_INSTANT: writeInstant((Instant) value, encoder); break; case TIME_LOCAL_DATE: writeLocalDate((LocalDate) value, encoder); break; case TIME_LOCAL_TIME: writeLocalTime((LocalTime) value, encoder); break; case TIME_LOCAL_DATETIME: writeLocalDateTime((LocalDateTime) value, encoder); break; case TIME_OFFSET_DATETIME: writeOffsetDateTime((OffsetDateTime) value, encoder); break; case TIME_ZONED_DATETIME: writeZonedDateTime((ZonedDateTime) value, encoder); break; case TIME_PERIOD: writePeriod((Period) value, encoder); break; case TIME_ZONE_ID: writeZoneId((ZoneId) value, encoder); break; case TIME_ZONE_OFFSET: writeZoneOffset((ZoneOffset) value, encoder); break; default: throw new SerializerException("Unhandled data type " + dataType); } } private void writeDuration(Duration duration, Encoder encoder) throws IOException { encoder.writeLong(duration.toMillis()); } private void writeInstant(Instant instant, Encoder encoder) throws IOException { encoder.writeLong(instant.getEpochSecond()); encoder.writeInteger(instant.getNano()); } private void writeLocalDate(LocalDate localDate, Encoder encoder) throws IOException { encoder.writeInteger(localDate.getYear()); encoder.writeByte((byte) localDate.getMonthValue()); encoder.writeByte((byte) localDate.getDayOfMonth()); } private void writeLocalTime(LocalTime localTime, Encoder encoder) throws IOException { encoder.writeByte((byte) localTime.getHour()); encoder.writeByte((byte) localTime.getMinute()); encoder.writeByte((byte) localTime.getSecond()); encoder.writeInteger(localTime.getNano()); } private void writeLocalDateTime(LocalDateTime localDataTime, Encoder encoder) throws IOException { writeLocalDate(localDataTime.toLocalDate(), encoder); writeLocalTime(localDataTime.toLocalTime(), encoder); } private void writeOffsetDateTime(OffsetDateTime offsetDataTime, Encoder encoder) throws IOException { writeLocalDateTime(offsetDataTime.toLocalDateTime(), encoder); writeZoneOffset(offsetDataTime.getOffset(), encoder); } private void writeZonedDateTime(ZonedDateTime zonedDataTime, Encoder encoder) throws IOException { writeLocalDateTime(zonedDataTime.toLocalDateTime(), encoder); writeZoneId(zonedDataTime.getZone(), encoder); } private void writeZoneOffset(ZoneOffset zoneOffset, Encoder encoder) throws IOException { encoder.writeInteger(zoneOffset.getTotalSeconds()); } private void writeZoneId(ZoneId zoneId, Encoder encoder) throws IOException { encoder.writeString(zoneId.getId()); } private void writePeriod(Period period, Encoder encoder) throws IOException { encoder.writeInteger(period.getYears()); encoder.writeByte((byte) period.getMonths()); encoder.writeByte((byte) period.getDays()); } }
German footballer Mesut Özil is no stranger to lending a helping hand. The talented midfielder has built an enviable reputation for his ability to provide teammates with deftly weighted through balls and pinpoint crosses. Yet the generosity of Özil as a footballer is only the tip of the iceberg. His charitable donations and life-saving interventions have done what few defenders could ever dream of: overshadow his world-class soccer talent. Özil is undoubtedly one of the most technically gifted players in the world of soccer. On top of that, few players today possess more creativity, vision, and soccer IQ. His sublime passes, silky smooth control of the ball, and effortless Skill are what make him my Athlete CRUSH. This past year, Özil showed his footballing prowess by notching 20 assists and 8 goals for club team Arsenal of the English Premier League (EPL), on his way to earning the Arsenal Player of the Season award. His 19 assists, in EPL games only, fell just 1 short of the all-time league record. (Click here to discover Swedish play making sensation Emil Forsberg: http://www.athletecrush.com/soccer/athlete-crush-emil-forsberg-rb-leipzig-bundesliga/) On the international stage, the 27-year-old has represented the German senior national team since 2009 and has logged 19 goals in 77 appearances. Leading up to the 2014 FIFA World Cup, Özil led Germany’s qualification run with 8 goals. During the tournament itself, he started all 7 of Germany’s matches and proved a big reason why they would eventually win the World Cup. His ability to improvise on the ball and facilitate goal scoring opportunities out of thin air mesmerized audiences all over the globe. His gift to the world that summer, however, was only just beginning. Özil is also my Athlete CRUSH for his Role Model status in the soccer community. A humble person from modest beginnings, Özil places emphasis on helping those who are less fortunate. His focus on children and instilling in them positive thoughts and beliefs has directly assisted many from Europe all the way to South America. At Arsenal home matches, he has frequently invited disadvantaged youth into his private box to enjoy games. And in Brazil, immediately before the 2014 World Cup, Özil pledged to fund surgical operations for 11 sick Brazilian children. Following Germany’s World Cup triumph, Özil further donated his tournament bonus to help cover a net total of 23 children’s operations, as this was his way of thanking Brazil for its hospitality. Over $400,000 in medical bills was given as a result to provide these kids a chance at a healthy and prosperous life. Subsequently, Özil was given the Laureus Sport for Good award for his admirable act of generosity. My hope is that Özil’s charitable work will help to set a precedent for athlete philanthropy. The social responsibility that Özil embodies is an inspiration to witness and a genuine quality, of which the world could use more. As he continues his already illustrious career, here’s to even more championship victories and lives made better all around the world. Follow Mesut Özil on Instagram @m10_official and Twitter @MesutOzil1088 Written by Athlete CRUSH Staff Posted 29 June 2016
// SPDX-License-Identifier: Apache-2.0 // Copyright 2021 - 2021, the Anboto author and contributors #include <Core/Core.h> using namespace Upp; #include <Functions4U/Functions4U.h> #include "Spreadsheet.h" bool SpreadsheetAPI::Open(const char *filename) {return false;} void SpreadsheetAPI::SetData(int row, int col, Value val) {} bool Spreadsheet::Open(const char *filename) {return (static_cast<SpreadsheetAPI *>(GetData()))->Open(filename);} void Spreadsheet::SetData(int row, int col, Value val) {return (static_cast<SpreadsheetAPI *>(GetData()))->SetData(row, col, val);} INITBLOCK { PluginRegister(Spreadsheet, SpreadsheetAPI, ""); }
<filename>models/scheduler.go package models import ( "context" "fmt" "time" "github.com/odpf/optimus/core/cron" "github.com/odpf/optimus/core/progress" ) var ( // BatchScheduler is a single unit initialized at the start of application // based on configs. This will be used to perform schedule triggered // operations to support target scheduling engine BatchScheduler SchedulerUnit // ManualScheduler is a single unit initialized at the start of application // based on configs. This will be used to execute one shot manual triggered // operations to support target scheduling engine ManualScheduler SchedulerUnit ) // SchedulerUnit is implemented by supported schedulers type SchedulerUnit interface { GetName() string VerifyJob(ctx context.Context, namespace NamespaceSpec, job JobSpec) error ListJobs(ctx context.Context, namespace NamespaceSpec, opts SchedulerListOptions) ([]Job, error) DeployJobs(ctx context.Context, namespace NamespaceSpec, jobs []JobSpec, obs progress.Observer) error DeleteJobs(ctx context.Context, namespace NamespaceSpec, jobNames []string, obs progress.Observer) error // Bootstrap will be executed per project when the application boots up // this can be used to do adhoc commands for initialization of scheduler Bootstrap(context.Context, ProjectSpec) error // GetJobStatus should return the current and previous status of job GetJobStatus(ctx context.Context, projSpec ProjectSpec, jobName string) ([]JobStatus, error) // Clear clears state of job between provided start and end dates Clear(ctx context.Context, projSpec ProjectSpec, jobName string, startDate, endDate time.Time) error // GetJobRunStatus should return batch of runs of a job GetJobRunStatus(ctx context.Context, projectSpec ProjectSpec, jobName string, startDate time.Time, endDate time.Time, batchSize int) ([]JobStatus, error) // GetJobRuns return all the job runs based on query GetJobRuns(ctx context.Context, projectSpec ProjectSpec, jobQuery *JobQuery, jobCron *cron.ScheduleSpec) ([]JobRun, error) } type SchedulerListOptions struct { OnlyName bool } type JobStatus struct { ScheduledAt time.Time State JobRunState } // progress events type ( // EventJobSpecCompile represents a specification // being compiled to a Job EventJobSpecCompiled struct{ Name string } // EventJobUpload represents the compiled Job // being uploaded EventJobUpload struct { Name string Err error } // EventJobRemoteDelete signifies that a // compiled job from a remote repository is being deleted EventJobRemoteDelete struct{ Name string } ) func (e *EventJobSpecCompiled) String() string { return fmt.Sprintf("compiling: %s", e.Name) } func (e *EventJobUpload) String() string { if e.Err != nil { return fmt.Sprintf("uploading: %s, failed with error): %s", e.Name, e.Err.Error()) } return fmt.Sprintf("uploaded: %s", e.Name) } func (e *EventJobRemoteDelete) String() string { return fmt.Sprintf("deleting: %s", e.Name) } // ExecutorUnit executes the actual job instance type ExecutorUnit interface { // Start initiates the instance execution Start(ctx context.Context, req ExecutorStartRequest) *ExecutorStartResponse // Stop aborts the execution Stop(ctx context.Context, req ExecutorStopRequest) error // WaitForFinish returns a channel that should return the exit code of execution // once it finishes WaitForFinish(ctx context.Context, id string) (chan int, error) // Stats provides current statistics of the running/finished instance Stats(ctx context.Context, id string) (*ExecutorStats, error) } type ExecutorStartRequest struct { // ID will be used for identifying the job in future calls ID string Job JobSpec Namespace NamespaceSpec } type ExecutorStopRequest struct { ID string Signal string } type ExecutorStartResponse struct{} type ExecutorStats struct { Logs []byte Status string }
<gh_stars>0 package org.objectweb.dsrg.cocome.fractal.tradingsystem.inventory.shared_data.data.store; import java.util.*; import org.objectweb.dsrg.cocome.fractal.tradingsystem.inventory.shared_data.StoreQueryIf; import org.objectweb.dsrg.cocome.fractal.tradingsystem.inventory.shared_data.PersistenceContext; import org.objectweb.dsrg.cocome.fractal.tradingsystem.inventory.shared_data.Product; import org.objectweb.dsrg.cocome.fractal.tradingsystem.inventory.shared_data.ProductOrder; import org.objectweb.dsrg.cocome.fractal.tradingsystem.inventory.shared_data.StockItem; import org.objectweb.dsrg.cocome.fractal.tradingsystem.inventory.shared_data.*; public class StoreImpl implements StoreQueryIf { public static final int NUMBEROF_ENTERPRISES = 1; public static final int NUMBEROF_STORES = 1; public static final int NUMBEROF_STOCKITEMS = 5; public static final int NUMBEROF_SUPPLIERS = 2; public static final int NUMBEROF_PRODUCTS = 5; public static final int NUMBEROF_PRODUCTORDERS = 5; public static final int NUMBEROF_ORDERENTRIES = 2; List<TradingEnterprise> enterprises; List<Store> stores; List<ProductSupplier> suppliers; List<Product> products; List<ProductOrder> productorders; List<StockItem> stockitems; List<OrderEntry> orderentries; // ----------------------------------------------------- // Constructor without parameters // ----------------------------------------------------- public StoreImpl() { enterprises = new ArrayList<TradingEnterprise>(); stores = new ArrayList<Store>(); suppliers = new ArrayList<ProductSupplier>(); products = new ArrayList<Product>(); productorders = new ArrayList<ProductOrder>(); stockitems = new ArrayList<StockItem>(); orderentries = new ArrayList<OrderEntry>(); //fill Enterprises for(int i = 0; i < NUMBEROF_ENTERPRISES; i++) { final TradingEnterprise enterprise = new TradingEnterprise(); enterprise.setName("TradingEnterprise " + i); enterprises.add(enterprise); } //fill Stores and connect to Enterprises for(int i = 0; i < NUMBEROF_STORES; i++) { final Store store = new Store(); store.setName("Store " + i); store.setLocation("StoreLocation " + i); //select randomly TradingEnterprise to connect to Store final TradingEnterprise enterprise = enterprises.get(0); store.setEnterprise(enterprise); stores.add(store); } //fill Suppliers for(int i = 0; i < NUMBEROF_SUPPLIERS; i++) { final ProductSupplier supplier = new ProductSupplier(); supplier.setName("ProductSupplier " + i); suppliers.add(supplier); } //fill Products and connect to Suppliers for(int i = 0; i < NUMBEROF_PRODUCTS; i++) { final Product product = new Product(); //each barcode is different product.setBarcode(i + 777); product.setName("Product " + i); product.setPurchasePrice(5); //select randomly ProductSupplier to connect to Product final ProductSupplier supplier = suppliers.get(i % NUMBEROF_SUPPLIERS); product.setSupplier(supplier); products.add(product); } //fill StockItems and connect to Stores and Products for(int i = 0; i < NUMBEROF_STOCKITEMS; i++) { final StockItem stockitem = new StockItem(); stockitem.setSalesPrice(5); stockitem.setAmount(8); stockitem.setMinStock(2); stockitem.setMaxStock(12); //select randomly Store to connect to StockItem final Store store = stores.get(0); stockitem.setStore(store); //select randomly Product to connect to StockItem final Product product = products.get(i); stockitem.setProduct(product); stockitems.add(stockitem); } //connect TradingEnterprise and ProductSupplier (n:m) for(int i = 0; i < enterprises.size(); i++) { final TradingEnterprise enterprise = enterprises.get(i); final List<ProductSupplier> sup = new ArrayList<ProductSupplier>(); for (int j = 0; j < suppliers.size(); j++) { final ProductSupplier supplier = suppliers.get(j); if ((j % 2) == (i % 2)) { sup.add(supplier); } } enterprise.setSuppliers(sup); } //fill ProductOrders and connect to Store for(int i = 0; i < NUMBEROF_PRODUCTORDERS; i++) { final ProductOrder productorder = new ProductOrder(); productorder.setOrderingDate(new Date(500 + i * 100)); productorder.setDeliveryDate(new Date(1000 + i * 50)); //select randomly Store to connect to ProductOrder final Store store = stores.get(0); productorder.setStore(store); productorders.add(productorder); } //fill OrderEntries and connect to Orders and Products for(int i = 0; i < NUMBEROF_ORDERENTRIES; i++) { final OrderEntry orderentry = new OrderEntry(); orderentry.setAmount(6); //select randomly ProductOrder to connect to OrderEntry final ProductOrder productorder = productorders.get(((i+1)*2) % NUMBEROF_PRODUCTORDERS); orderentry.setOrder(productorder); //select randomly Product to connect to OrderEntry final Product product = products.get(((i+1)*3) % NUMBEROF_PRODUCTS); orderentry.setProduct(product); orderentries.add(orderentry); } System.out.println("StoreImpl: Objects initialized"); } // ----------------------------------------------------- // Implementation of the StoreQueryIf interface 'StoreQueryIf' // ----------------------------------------------------- public Store queryStoreById(final long arg0, final PersistenceContext arg1) { // TODO Generated method return null; } public Collection<Product> queryProducts(final long arg0, final PersistenceContext arg1) { // TODO Generated method return null; } public Collection<StockItem> queryLowStockItems(final long arg0, final PersistenceContext arg1) { // TODO Generated method return null; } public Collection<StockItem> queryAllStockItems(final long arg0, final PersistenceContext arg1) { // TODO Generated method return null; } public ProductOrder queryOrderById(final long arg0, final PersistenceContext arg1) { // TODO Generated method return null; } public StockItem queryStockItem(final long storeId, final long productbarcode, final PersistenceContext pctx) { Product foundProduct = null; for (final Product product : products) { if (product.getBarcode() == productbarcode) { foundProduct = product; break; } } if (foundProduct == null) { return null; } for (final StockItem item : stockitems) { if (item.getProduct().equals(foundProduct) && item.getStore().getId() == storeId) { return item; } } return null; } public StockItem queryStockItemById(final long arg0, final PersistenceContext arg1) { // TODO Generated method return null; } public Product queryProductById(final long arg0, final PersistenceContext arg1) { // TODO Generated method return null; } public Collection<StockItem> getStockItems(final long arg0, final long[] arg1, final PersistenceContext arg2) { // TODO Generated method return null; } }
def delete_file(instance: object, arg: dict, verbose: bool=True) -> int: if instance.files.delete_available(): instance.files.delete(arg["instance_path"]) result = execute_command(instance, {"command":["ls", arg["instance_path"]], "expected_exit_code":"2"}, verbose=False) if result.stderr: if verbose: print(Fore.GREEN+ " File [ "+arg["instance_path"]+" ] has been deleted!" +Style.RESET_ALL) return 0 print(Fore.RED+ " File was not deleted..." +Style.RESET_ALL) return 1 print(Fore.RED+ " File was not deleted..." +Style.RESET_ALL) return 1
/** * Copyright (C) 2002 <NAME> (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.summerclouds.common.core.pojo; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Base64; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.UUID; import org.summerclouds.common.core.M; import org.summerclouds.common.core.activator.Activator; import org.summerclouds.common.core.cast.Caster; import org.summerclouds.common.core.consts.Identifier; import org.summerclouds.common.core.json.TransformHelper; import org.summerclouds.common.core.log.Log; import org.summerclouds.common.core.node.INode; import org.summerclouds.common.core.node.IProperties; import org.summerclouds.common.core.node.MNode; import org.summerclouds.common.core.node.MProperties; import org.summerclouds.common.core.node.NodeList; import org.summerclouds.common.core.tool.MCast; import org.summerclouds.common.core.tool.MCollection; import org.summerclouds.common.core.tool.MDate; import org.summerclouds.common.core.tool.MString; import org.summerclouds.common.core.tool.MSystem; import org.summerclouds.common.core.tool.MXml; import org.w3c.dom.CDATASection; import org.w3c.dom.Element; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; public class MPojo { public static final String DEEP = "deep"; private static final int MAX_LEVEL = 10; private static Log log = Log.getLog(MPojo.class); private static PojoModelFactory defaultModelFactory; private static PojoModelFactory attributesModelFactory; private static Activator defaultActivator; public static synchronized PojoModelFactory getDefaultModelFactory() { if (defaultModelFactory == null) defaultModelFactory = new PojoModelFactory() { @Override public PojoModel createPojoModel(Class<?> pojoClass) { PojoModel model = new PojoParser() .parse(pojoClass, "_") .filter( new DefaultFilter( true, false, false, false, true)) .getModel(); return model; } }; return defaultModelFactory; } public static synchronized PojoModelFactory getAttributesModelFactory() { if (attributesModelFactory == null) attributesModelFactory = new PojoModelFactory() { @Override public PojoModel createPojoModel(Class<?> pojoClass) { PojoModel model = new PojoParser() .parse( pojoClass, new AttributesStrategy(true, true, "_", null)) .filter( new DefaultFilter( true, false, false, false, true)) .getModel(); return model; } }; return attributesModelFactory; } // public static synchronized PojoModelFactory getAttributeModelFactory() { // if (defaultModelFactory == null) // defaultModelFactory = // new PojoModelFactory() { // // @Override // public PojoModel createPojoModel(Class<?> pojoClass) { // PojoModel model = // new PojoParser() // .parse( // pojoClass, // new AttributesStrategy(true, true, "_", // null)) // .filter( // new DefaultFilter( // true, false, false, false, true)) // .getModel(); // return model; // } // }; // return defaultModelFactory; // } public static INode pojoToNode(Object from) throws IOException { return pojoToNode(from, getDefaultModelFactory(), false, false); } public static INode pojoToNode(Object from, boolean verbose, boolean useAnnotations) throws IOException { return pojoToNode(from, getDefaultModelFactory(), verbose, useAnnotations); } public static INode pojoToNode( Object from, PojoModelFactory factory, boolean verbose, boolean useAnnotations) throws IOException { MNode to = new MNode(); pojoToNode(from, to, factory, verbose, useAnnotations, "", 0); return to; } public static void pojoToNode(Object from, INode to) throws IOException { pojoToNode(from, to, getDefaultModelFactory(), false, false, "", 0); } public static void pojoToNode(Object from, INode to, PojoModelFactory factory) throws IOException { pojoToNode(from, to, factory, false, false, "", 0); } public static void pojoToNode(Object from, INode to, boolean verbose, boolean useAnnotations) throws IOException { pojoToNode(from, to, getDefaultModelFactory(), verbose, useAnnotations, "", 0); } private static void pojoToNode( Object from, INode to, PojoModelFactory factory, boolean verbose, boolean useAnnotations, String prefix, int level) throws IOException { if (level > MAX_LEVEL) return; if (from == null) { to.setBoolean(INode.NULL, true); return; } if (verbose) to.setString(INode.CLASS, from.getClass().getCanonicalName()); if (from instanceof String) { to.setString(INode.CLASS, from.getClass().getCanonicalName()); to.setString(INode.NAMELESS_VALUE, (String) from); } else if (from instanceof Long) { to.setString(INode.CLASS, from.getClass().getCanonicalName()); to.setLong(INode.NAMELESS_VALUE, (Long) from); } else if (from instanceof Integer) { to.setString(INode.CLASS, from.getClass().getCanonicalName()); to.setInt(INode.NAMELESS_VALUE, (Integer) from); } else if (from instanceof Boolean) { to.setString(INode.CLASS, from.getClass().getCanonicalName()); to.setBoolean(INode.NAMELESS_VALUE, (Boolean) from); } else if (from instanceof Float) { to.setString(INode.CLASS, from.getClass().getCanonicalName()); to.setFloat(INode.NAMELESS_VALUE, (Float) from); } else if (from instanceof Short) { to.setString(INode.CLASS, from.getClass().getCanonicalName()); to.setInt(INode.NAMELESS_VALUE, (Short) from); } else if (from instanceof Byte) { to.setString(INode.CLASS, from.getClass().getCanonicalName()); to.setLong(INode.NAMELESS_VALUE, (Byte) from); } else if (from instanceof java.sql.Timestamp) { to.setString(INode.CLASS, "java.sql.Timestamp"); to.setLong(INode.NAMELESS_VALUE, ((java.sql.Timestamp) from).getTime()); } else if (from instanceof Date) { to.setString(INode.CLASS, "java.util.Date"); to.setLong(INode.NAMELESS_VALUE, ((Date) from).getTime()); } else if (from instanceof Enum) { to.setString(INode.CLASS, "java.lang.Enum"); to.setString(INode.CLASS + "_", from.getClass().getCanonicalName()); to.setInt(INode.NAMELESS_VALUE, ((Enum<?>) from).ordinal()); to.setString(INode.HELPER_VALUE, ((Enum<?>) from).toString()); } else if (from instanceof Character) { to.setString(INode.CLASS, from.getClass().getCanonicalName()); to.setInt(INode.NAMELESS_VALUE, (Character) from); } else if (from instanceof Double) { to.setString(INode.CLASS, from.getClass().getCanonicalName()); to.setDouble(INode.NAMELESS_VALUE, (Double) from); } else if (from instanceof UUID) { to.setString(INode.CLASS, "java.util.UUID"); to.setString(INode.NAMELESS_VALUE, ((UUID) from).toString()); } else { PojoModel model = factory.createPojoModel(from.getClass()); for (PojoAttribute<?> attr : model) { boolean deep = false; if (!attr.canRead()) continue; if (attr.getName().equals("class")) continue; if (useAnnotations) { Hidden hidden = attr.getAnnotation(Hidden.class); if (hidden != null) continue; Public pub = attr.getAnnotation(Public.class); if (pub != null) { if (!pub.readable()) continue; if (MCollection.contains(pub.hints(), MPojo.DEEP)) deep = true; } Embedded emb = attr.getAnnotation(Embedded.class); // experimental if (emb != null) { Object value = attr.get(from); String name = attr.getName(); pojoToNode( value, to, factory, verbose, useAnnotations, prefix + name + "_", level + 1); continue; } } Object value = attr.get(from); String name = attr.getName(); setNodeValue( to, prefix + name, value, factory, verbose, useAnnotations, deep, prefix, level + 1); } } } public static void setNodeValue( INode to, String name, Object value, PojoModelFactory factory, boolean verbose, boolean useAnnotations, boolean deep) throws IOException { setNodeValue(to, name, value, factory, verbose, useAnnotations, deep, "", 0); } @SuppressWarnings("unchecked") private static void setNodeValue( INode to, String name, Object value, PojoModelFactory factory, boolean verbose, boolean useAnnotations, boolean deep, String prefix, int level) throws IOException { if (level > MAX_LEVEL) return; try { if (verbose) { if (value != null) to.setString( INode.CLASS + "_" + prefix + name, value.getClass().getCanonicalName()); if (value == null) { to.setBoolean(INode.NULL + "_" + prefix + name, true); } } if (value instanceof Boolean) to.setBoolean(prefix + name, (boolean) value); else if (value instanceof Integer) to.setInt(prefix + name, (int) value); else if (value instanceof String) to.setString(prefix + name, (String) value); else if (value instanceof Long) to.setLong(prefix + name, (long) value); // else if (value instanceof byte[]) to.put(prefix + name, (byte[]) value); else if (value instanceof Float) to.setFloat(prefix + name, (float) value); else if (value instanceof Double) to.setDouble(prefix + name, (double) value); else if (value instanceof Short) to.setInt(prefix + name, (short) value); else if (value instanceof Date) to.setLong(prefix + name, ((Date) value).getTime()); else if (value instanceof Character) to.put(prefix + name, Character.toString((Character) value)); else if (value instanceof Date) { to.put("_" + prefix + name, MDate.toIso8601((Date) value)); to.put(prefix + name, ((Date) value).getTime()); } else if (value instanceof BigDecimal) to.put(prefix + name, (BigDecimal) value); else if (value instanceof INode) to.addObject(prefix + name, (INode) value); else if (value.getClass().isEnum()) { to.put(prefix + name, ((Enum<?>) value).ordinal()); to.put("_" + prefix + name, ((Enum<?>) value).name()); } else if (value instanceof Map) { INode obj = to.createObject(prefix + name); for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) value).entrySet()) { setNodeValue( obj, String.valueOf(entry.getKey()), entry.getValue(), factory, verbose, useAnnotations, true, prefix, level + 1); } } else if (value.getClass().isArray()) { NodeList array = to.createArray(prefix + name); for (Object o : (Object[]) value) { addNodeValue( array, o, factory, verbose, useAnnotations, true, prefix, level + 1); } } else if (value instanceof Collection) { NodeList array = to.createArray(prefix + name); for (Object o : ((Collection<Object>) value)) { addNodeValue( array, o, factory, verbose, useAnnotations, true, prefix, level + 1); } } else { if (deep) { INode too = to.createObject(prefix + name); pojoToNode(value, too, factory, verbose, useAnnotations, prefix, level + 1); } else { to.put(prefix + name, String.valueOf(value)); } } } catch (Throwable t) { log.t(t); } } public static void addNodeValue( NodeList to, Object value, PojoModelFactory factory, boolean verbose, boolean useAnnotations, boolean deep) throws IOException { addNodeValue(to, value, factory, verbose, useAnnotations, deep, "", 0); } @SuppressWarnings("unchecked") private static void addNodeValue( NodeList to, Object value, PojoModelFactory factory, boolean verbose, boolean useAnnotations, boolean deep, String prefix, int level) throws IOException { if (level > MAX_LEVEL) return; try { INode oo = to.createObject(); if (verbose) { if (value != null) oo.setString(INode.CLASS, value.getClass().getCanonicalName()); if (value == null) { oo.setBoolean(INode.NULL, true); } } else if (value instanceof Boolean) oo.setBoolean(INode.NAMELESS_VALUE, (boolean) value); else if (value instanceof Integer) oo.setInt(INode.NAMELESS_VALUE, (int) value); else if (value instanceof String) oo.setString(INode.NAMELESS_VALUE, (String) value); else if (value instanceof Long) oo.setLong(INode.NAMELESS_VALUE, (Long) value); else if (value instanceof Date) { oo.setLong(INode.NAMELESS_VALUE, ((Date) value).getTime()); oo.setString(INode.HELPER_VALUE, MDate.toIso8601((Date) value)); } // else if (value instanceof byte[]) oo.set(INode.NAMELESS_VALUE, (byte[]) // value); else if (value instanceof Float) oo.setFloat(INode.NAMELESS_VALUE, (Float) value); // else if (value instanceof BigDecimal) oo.set(INode.NAMELESS_VALUE, // (BigDecimal) value); else if (value instanceof INode) oo.addObject(INode.NAMELESS_VALUE, (INode) value); else if (value.getClass().isEnum()) { oo.setInt(INode.HELPER_VALUE, ((Enum<?>) value).ordinal()); oo.setString(INode.NAMELESS_VALUE, ((Enum<?>) value).name()); } else if (value instanceof Map) { for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) value).entrySet()) { setNodeValue( oo, String.valueOf(entry.getKey()), entry.getValue(), factory, verbose, useAnnotations, true, prefix, level + 1); } } else if (value instanceof Collection) { NodeList array = oo.createArray(INode.NAMELESS_VALUE); for (Object o : ((Collection<Object>) value)) { addNodeValue( array, o, factory, verbose, useAnnotations, true, prefix, level + 1); } } else { if (deep) { pojoToNode(value, oo, factory, verbose, useAnnotations, prefix, level + 1); } else { oo.setString(INode.NAMELESS_VALUE, String.valueOf(value)); } } } catch (Throwable t) { log.t(t); } } public static void nodeToPojo(INode from, Object to) throws IOException { nodeToPojo(from, to, getDefaultModelFactory(), false, false); } public static void nodeToPojo(INode from, Object to, boolean force) throws IOException { nodeToPojo(from, to, getDefaultModelFactory(), force, false); } public static void nodeToPojo(INode from, Object to, boolean force, boolean verbose) throws IOException { nodeToPojo(from, to, getDefaultModelFactory(), force, verbose); } public static void nodeToPojo(INode from, Object to, PojoModelFactory factory) throws IOException { nodeToPojo(from, to, factory, false, false); } public static Object nodeToPojoObject(INode from) throws Exception { return nodeToPojoObject(from, getDefaultModelFactory(), null, false, false); } public static Object nodeToPojoObject(INode from, boolean force) throws Exception { return nodeToPojoObject(from, getDefaultModelFactory(), null, force, false); } public static Object nodeToPojoObject(INode from, boolean force, boolean verbose) throws Exception { return nodeToPojoObject(from, getDefaultModelFactory(), null, force, verbose); } public static Object nodeToPojoObject(INode from, PojoModelFactory factory) throws Exception { return nodeToPojoObject(from, factory, null, false, false); } public static Object nodeToPojoObject( INode from, PojoModelFactory factory, Activator activator, boolean force, boolean verbose) throws Exception { if (activator == null) activator = getDefaultActivator(); if (from.getBoolean(INode.NULL, false)) return null; String clazz = from.getString(INode.CLASS, null); if (clazz == null) return null; switch (clazz) { case "java.lang.Boolean": return from.getBoolean(INode.NAMELESS_VALUE, false); case "java.lang.Integer": return from.getInt(INode.NAMELESS_VALUE, 0); case "java.lang.Long": return from.getLong(INode.NAMELESS_VALUE, 0); case "java.lang.Short": return (short) from.getInt(INode.NAMELESS_VALUE, 0); case "java.lang.Double": return from.getDouble(INode.NAMELESS_VALUE, 0); case "java.lang.Float": return from.getFloat(INode.NAMELESS_VALUE, 0); case "java.lang.Byte": return (byte) from.getInt(INode.NAMELESS_VALUE, 0); case "java.lang.String": return from.getString(INode.NAMELESS_VALUE); case "java.util.Date": return new Date(from.getLong(INode.NAMELESS_VALUE, 0)); case "java.lang.Character": return (char) from.getInt(INode.NAMELESS_VALUE, 0); case "java.util.UUID": return UUID.fromString(from.getString(INode.NAMELESS_VALUE)); case "java.sql.Timestamp": return new java.sql.Timestamp(from.getLong(INode.NAMELESS_VALUE, 0)); case "java.lang.Enum": String enuName = from.getString(INode.CLASS + "_"); Class<? extends Enum<?>> type = MSystem.getEnum(enuName, activator); if (type != null) { Object[] cons = type.getEnumConstants(); int ord = from.getInt(INode.NAMELESS_VALUE, 0); if (ord >= 0 && ord < cons.length) return cons[ord]; } return null; } Object obj = activator.createObject(clazz); nodeToPojo(from, obj, factory, force, verbose); return obj; } private static synchronized Activator getDefaultActivator() { if (defaultActivator == null) defaultActivator = M.l(Activator.class); return defaultActivator; } /** * @param from * @param to * @param factory * @param force * @param verbose Use verbose hints from serialization to create the correct object * @throws IOException */ @SuppressWarnings({"unchecked", "rawtypes"}) public static void nodeToPojo( INode from, Object to, PojoModelFactory factory, boolean force, boolean verbose) throws IOException { PojoModel model = factory.createPojoModel(to.getClass()); for (PojoAttribute<Object> attr : model) { if (!force && !attr.canWrite()) continue; String name = attr.getName(); Class<?> type = attr.getType(); try { if (!from.containsKey(name)) { } else if (type == Boolean.class || type == boolean.class) attr.set(to, from.getBoolean(name, false), force); else if (type == Integer.class || type == int.class) attr.set(to, from.getInt(name, 0), force); else if (type == Long.class || type == long.class) attr.set(to, from.getLong(name, 0), force); else if (type == Double.class || type == double.class) attr.set(to, from.getDouble(name, 0), force); else if (type == Float.class || type == float.class) attr.set(to, from.getFloat(name, 0), force); else if (type == Byte.class || type == byte.class) attr.set(to, (byte) from.getInt(name, 0), force); else if (type == Short.class || type == short.class) attr.set(to, (short) from.getInt(name, 0), force); else if (type == Character.class || type == char.class) attr.set(to, (char) from.getInt(name, 0), force); else if (type == Date.class) attr.set(to, new Date(from.getLong(name, 0)), force); else if (type == String.class) attr.set(to, from.getString(name, null), force); else if (type == UUID.class) try { attr.set(to, UUID.fromString(from.getString(name, null)), force); } catch (IllegalArgumentException e) { attr.set(to, null, force); } else if (type.isEnum()) { Object[] cons = type.getEnumConstants(); int ord = from.getInt(name, 0); Object c = cons.length > 0 ? cons[0] : null; if (ord >= 0 && ord < cons.length) c = cons[ord]; attr.set(to, c, force); } else if (Map.class.isAssignableFrom(type)) { INode obj = from.getObjectOrNull(name); if (obj != null) { Map inst = null; if (type == Map.class) inst = new HashMap<>(); else inst = (Map) type.getConstructor().newInstance(); if (verbose) for (Entry<String, Object> entry : obj.entrySet()) { if (!entry.getKey().startsWith("_")) { String hint = obj.getString(INode.CLASS + "_" + entry.getKey(), null); addNodeValue( inst, entry.getKey(), entry.getValue(), hint, factory, force, verbose); } } else inst.putAll(obj); attr.set(to, inst, force); } } else if (Collection.class.isAssignableFrom(type)) { NodeList array = from.getArrayOrNull(name); if (array != null) { Collection inst = null; if (type == Collection.class || type == List.class) inst = new ArrayList<>(); else inst = (Collection) type.getConstructor().newInstance(); for (INode obj : array) { if (verbose) { String hint = obj.getString(INode.CLASS, null); Object val = toNodeValue(model, hint, factory, force, verbose); if (val != null) inst.add(val); } else if (obj.containsKey(INode.NAMELESS_VALUE)) inst.add(obj.get(INode.NAMELESS_VALUE)); else { // oo = // not possible, cant // generate a complex object from no type } } attr.set(to, inst, force); } } else attr.set(to, from.getString(name, null), force); } catch (Throwable t) { log.d(MSystem.getClassName(to), name, t); } } } @SuppressWarnings({"rawtypes", "unchecked"}) public static void addNodeValue( Map inst, String name, Object value, String hint, PojoModelFactory factory, boolean force, boolean verbose) { Object val = toNodeValue(value, hint, factory, force, verbose); if (val != null) inst.put(name, val); } public static Object toNodeValue( Object value, String hint, PojoModelFactory factory, boolean force, boolean verbose) { Object val = value; if (MString.isEmptyTrim(hint)) { // nothing } else { val = MCast.to(value, hint); if (val == null && value instanceof INode) { try { val = getDefaultActivator().createObject(hint); nodeToPojo((INode) value, val, factory, force, verbose); } catch (Throwable t) { log.d(hint, t); } } else if (val == null) { try { // try enum Class<?> type = MSystem.getEnum(hint, null); if (type != null) { Object[] cons = type.getEnumConstants(); int ord = MCast.toint(value, 0); val = cons.length > 0 ? cons[0] : null; if (ord >= 0 && ord < cons.length) val = cons[ord]; } } catch (Throwable t) { log.d(hint, t); } if (val == null) val = value; // fallback } } return val; } public static void pojoToJson(Object from, ObjectNode to) throws IOException { pojoToJson(from, to, getDefaultModelFactory()); } public static void pojoToJson(Object from, ObjectNode to, PojoModelFactory factory) throws IOException { pojoToJson(from, to, factory, false, false, "", 0); } public static void pojoToJson( Object from, ObjectNode to, PojoModelFactory factory, boolean useAnnotations) throws IOException { pojoToJson(from, to, factory, false, useAnnotations, "", 0); } public static void pojoToJson( Object from, ObjectNode to, PojoModelFactory factory, boolean verbose, boolean useAnnotations) throws IOException { pojoToJson(from, to, factory, verbose, useAnnotations, "", 0); } private static void pojoToJson( Object from, ObjectNode to, PojoModelFactory factory, boolean verbose, boolean useAnnotations, String prefix, int level) throws IOException { if (level > MAX_LEVEL) return; PojoModel model = factory.createPojoModel(from.getClass()); for (PojoAttribute<?> attr : model) { boolean deep = false; if (!attr.canRead()) continue; if (useAnnotations) { Hidden hidden = attr.getAnnotation(Hidden.class); if (hidden != null) continue; Public pub = attr.getAnnotation(Public.class); if (pub != null) { if (!pub.readable()) continue; if (MCollection.contains(pub.hints(), MPojo.DEEP)) deep = true; } Embedded emb = attr.getAnnotation(Embedded.class); if (emb != null) { Object value = attr.get(from); String name = attr.getName(); pojoToJson( value, to, factory, verbose, useAnnotations, prefix + name + "_", level + 1); continue; } } Object value = attr.get(from); String name = attr.getName(); setJsonValue( to, prefix + name, value, factory, verbose, useAnnotations, deep, prefix, level + 1); } } public static void addJsonValue( ArrayNode to, Object value, PojoModelFactory factory, boolean verbose, boolean useAnnotations, boolean deep) throws IOException { addJsonValue(to, value, factory, verbose, useAnnotations, deep, "", 0); } @SuppressWarnings("unchecked") private static void addJsonValue( ArrayNode to, Object value, PojoModelFactory factory, boolean verbose, boolean useAnnotations, boolean deep, String prefix, int level) throws IOException { if (level > MAX_LEVEL) return; try { if (value == null) to.addNull(); else if (value instanceof Boolean) to.add((boolean) value); else if (value instanceof Integer) to.add((int) value); else if (value instanceof String) to.add((String) value); else if (value instanceof Long) to.add((Long) value); else if (value instanceof byte[]) to.add((byte[]) value); else if (value instanceof Float) to.add((Float) value); else if (value instanceof BigDecimal) to.add((BigDecimal) value); else if (value instanceof JsonNode) to.add((JsonNode) value); else if (value.getClass().isEnum()) { to.add(((Enum<?>) value).ordinal()); // to.put(name + "_", ((Enum<?>)value).name()); } else if (value instanceof Map) { ObjectNode obj = to.objectNode(); to.add(obj); for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) value).entrySet()) { setJsonValue( obj, String.valueOf(entry.getKey()), entry.getValue(), factory, verbose, useAnnotations, true, prefix, level + 1); } } else if (value instanceof Collection) { ArrayNode array = to.arrayNode(); to.add(array); for (Object o : ((Collection<Object>) value)) { addJsonValue( array, o, factory, verbose, useAnnotations, true, prefix, level + 1); } } else { if (deep) { ObjectNode too = to.objectNode(); to.add(too); pojoToJson(value, too, factory, verbose, useAnnotations, prefix, level + 1); } else { to.add(String.valueOf(value)); } } } catch (Throwable t) { log.t(t); } } public static void setJsonValue( ObjectNode to, String name, Object value, PojoModelFactory factory, boolean verbose, boolean useAnnotations, boolean deep) throws IOException { setJsonValue(to, name, value, factory, verbose, useAnnotations, deep, "", 0); } @SuppressWarnings("unchecked") public static void setJsonValue( ObjectNode to, String name, Object value, PojoModelFactory factory, boolean verbose, boolean useAnnotations, boolean deep, String prefix, int level) throws IOException { if (level > MAX_LEVEL) return; try { if (verbose) { if (value != null) to.put(INode.CLASS, value.getClass().getCanonicalName()); } if (value == null) to.putNull(prefix + name); else if (value instanceof Boolean) to.put(prefix + name, (boolean) value); else if (value instanceof Integer) to.put(prefix + name, (int) value); else if (value instanceof String) to.put(prefix + name, (String) value); else if (value instanceof Long) to.put(prefix + name, (long) value); else if (value instanceof byte[]) to.put(prefix + name, (byte[]) value); else if (value instanceof Float) to.put(prefix + name, (float) value); else if (value instanceof Double) to.put(prefix + name, (double) value); else if (value instanceof Short) to.put(prefix + name, (short) value); else if (value instanceof Character) to.put(prefix + name, Character.toString((Character) value)); else if (value instanceof Date) { to.put(prefix + name, ((Date) value).getTime()); to.put("_" + prefix + name, MDate.toIso8601((Date) value)); } else if (value instanceof BigDecimal) to.put(prefix + name, (BigDecimal) value); else if (value instanceof JsonNode) to.set(prefix + name, (JsonNode) value); else if (value.getClass().isEnum()) { to.put(prefix + name, ((Enum<?>) value).ordinal()); to.put("_" + prefix + name, ((Enum<?>) value).name()); } else if (value instanceof Map) { ObjectNode obj = to.objectNode(); to.set(prefix + name, obj); for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) value).entrySet()) { setJsonValue( obj, String.valueOf(entry.getKey()), entry.getValue(), factory, verbose, useAnnotations, true, prefix, level + 1); } } else if (value.getClass().isArray()) { ArrayNode array = to.arrayNode(); to.set(prefix + name, array); for (Object o : (Object[]) value) { addJsonValue( array, o, factory, verbose, useAnnotations, true, prefix, level + 1); } } else if (value instanceof Collection) { ArrayNode array = to.arrayNode(); to.set(prefix + name, array); for (Object o : ((Collection<Object>) value)) { addJsonValue( array, o, factory, verbose, useAnnotations, true, prefix, level + 1); } } else { if (deep) { ObjectNode too = to.objectNode(); to.set(prefix + name, too); pojoToJson(value, too, factory, verbose, useAnnotations, prefix, level + 1); } else { to.put(prefix + name, String.valueOf(value)); } } } catch (Throwable t) { log.t(t); } } public static void jsonToPojo(JsonNode from, Object to) throws IOException { jsonToPojo(from, to, getDefaultModelFactory(), false); } public static void jsonToPojo(JsonNode from, Object to, boolean force) throws IOException { jsonToPojo(from, to, getDefaultModelFactory(), force); } public static void jsonToPojo(JsonNode from, Object to, PojoModelFactory factory) throws IOException { jsonToPojo(from, to, factory, false); } @SuppressWarnings("unchecked") public static void jsonToPojo(JsonNode from, Object to, PojoModelFactory factory, boolean force) throws IOException { PojoModel model = factory.createPojoModel(to.getClass()); for (PojoAttribute<Object> attr : model) { if (!attr.canWrite()) continue; String name = attr.getName(); Class<?> type = attr.getType(); JsonNode json = from.get(name); try { if (json == null || !attr.canWrite()) { } else if (type == Boolean.class || type == boolean.class) attr.set(to, json.asBoolean(false), force); else if (type == Integer.class || type == int.class) attr.set(to, json.asInt(0), force); else if (type == Long.class || type == long.class) attr.set(to, json.asLong(0), force); else if (type == Double.class || type == double.class) attr.set(to, json.asDouble(0), force); else if (type == Float.class || type == float.class) attr.set(to, (float) json.asDouble(0), force); else if (type == Byte.class || type == byte.class) attr.set(to, (byte) json.asInt(0), force); else if (type == Short.class || type == short.class) attr.set(to, (short) json.asInt(0), force); else if (type == Character.class || type == char.class) attr.set(to, (char) json.asInt(0), force); else if (type == String.class) attr.set(to, json.asText(), force); else if (type == UUID.class) try { attr.set(to, UUID.fromString(json.asText()), force); } catch (IllegalArgumentException e) { attr.set(to, null, force); } else if (type.isEnum()) { Object[] cons = type.getEnumConstants(); int ord = json.asInt(0); Object c = cons.length > 0 ? cons[0] : null; if (ord >= 0 && ord < cons.length) c = cons[ord]; attr.set(to, c, force); } else attr.set(to, json.asText(), force); } catch (Throwable t) { log.d(MSystem.getClassName(to), name, t); } } } public static void pojoToXml(Object from, Element to) throws IOException { pojoToXml(from, to, getDefaultModelFactory()); } public static void pojoToXml(Object from, Element to, PojoModelFactory factory) throws IOException { pojoToXml(from, to, factory, 0); } public static void pojoToXml(Object from, Element to, PojoModelFactory factory, int level) throws IOException { if (level > MAX_LEVEL) return; PojoModel model = factory.createPojoModel(from.getClass()); for (PojoAttribute<?> attr : model) { try { if (!attr.canRead()) continue; Object value = attr.get(from); String name = attr.getName(); Element a = to.getOwnerDocument().createElement("attribute"); to.appendChild(a); a.setAttribute("name", name); if (value == null) { a.setAttribute("null", "true"); // to.setAttribute(name, (String)null); } else if (value instanceof Boolean) a.setAttribute("boolean", MCast.toString((boolean) value)); else if (value instanceof Integer) a.setAttribute("int", MCast.toString((int) value)); else if (value instanceof Long) a.setAttribute("long", MCast.toString((long) value)); else if (value instanceof Date) a.setAttribute("date", MCast.toString(((Date) value).getTime())); else if (value instanceof String) { if (hasValidChars((String) value)) a.setAttribute("string", (String) value); else { a.setAttribute("encoding", "base64"); a.setAttribute("string", Base64.getEncoder().encodeToString( ((String) value).getBytes() )); } } else if (value.getClass().isEnum()) { a.setAttribute("enum", MCast.toString(((Enum<?>) value).ordinal())); a.setAttribute("value", ((Enum<?>) value).name()); } else if (value instanceof UUID) { a.setAttribute("uuid", ((UUID) value).toString()); } else if (value instanceof Serializable) { a.setAttribute("serializable", "true"); CDATASection cdata = a.getOwnerDocument().createCDATASection(""); String data = MCast.toBinaryString(MCast.toBinary(value)); cdata.setData(data); a.appendChild(cdata); } else { a.setAttribute("type", value.getClass().getCanonicalName()); pojoToXml(value, a, factory, level + 1); } } catch (Throwable t) { log.d(MSystem.getClassName(from), attr.getName(), t); } } } private static boolean hasValidChars(String value) { for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (c == '\n' || c == '\r' || c == '\t' || c >= 32 && c <= 55295) { } else { return false; } } return true; } public static void xmlToPojo(Element from, Object to, Activator act) throws IOException { xmlToPojo(from, to, getDefaultModelFactory(), act, false); } public static void xmlToPojo(Element from, Object to, Activator act, boolean force) throws IOException { xmlToPojo(from, to, getDefaultModelFactory(), act, force); } public static void xmlToPojo(Element from, Object to, PojoModelFactory factory, Activator act) throws IOException { xmlToPojo(from, to, factory, act, false); } @SuppressWarnings("unchecked") public static void xmlToPojo( Element from, Object to, PojoModelFactory factory, Activator act, boolean force) throws IOException { PojoModel model = factory.createPojoModel(to.getClass()); HashMap<String, Element> index = new HashMap<>(); for (Element e : MXml.getLocalElementIterator(from, "attribute")) index.put(e.getAttribute("name"), e); for (PojoAttribute<Object> attr : model) { try { if (!attr.canWrite()) continue; String name = attr.getName(); // Class<?> type = attr.getType(); Element a = index.get(name); if (a == null) { log.d("attribute not found", name, to.getClass()); continue; } { String value = a.getAttribute("null"); if (MString.isSet(value) && value.equals("true")) { attr.set(to, null, force); continue; } } if (a.hasAttribute("string")) { String data = a.getAttribute("encoding"); if ("base64".equals(data)) { String value = new String(Base64.getDecoder().decode(a.getAttribute("string"))); attr.set(to, value, force); } else { String value = a.getAttribute("string"); attr.set(to, value, force); } continue; } if (a.hasAttribute("boolean")) { String value = a.getAttribute("boolean"); attr.set(to, MCast.toboolean(value, false), force); continue; } if (a.hasAttribute("int")) { String value = a.getAttribute("int"); attr.set(to, MCast.toint(value, 0), force); continue; } if (a.hasAttribute("long")) { String value = a.getAttribute("long"); attr.set(to, MCast.tolong(value, 0), force); continue; } if (a.hasAttribute("date")) { String value = a.getAttribute("date"); Date obj = new Date(); obj.setTime(MCast.tolong(value, 0)); attr.set(to, obj, force); continue; } if (a.hasAttribute("uuid")) { String value = a.getAttribute("uuid"); try { attr.set(to, UUID.fromString(value), force); } catch (Throwable t) { log.d(name, t); } continue; } if (a.hasAttribute("enum")) { String value = a.getAttribute("enum"); attr.set(to, MCast.toint(value, 0), force); continue; } if ("true".equals(a.getAttribute("serializable"))) { CDATASection cdata = MXml.findCDataSection(a); if (cdata != null) { String data = cdata.getData(); try { Object obj = MCast.fromBinary(MCast.fromBinaryString(data)); attr.set(to, obj, force); } catch (ClassNotFoundException e1) { throw new IOException(e1); } } } if (a.hasAttribute("type")) { String value = a.getAttribute("type"); try { Object obj = act.createObject(value); xmlToPojo(a, obj, factory, act); attr.set(to, obj, force); } catch (Exception e1) { log.d(name, to.getClass(), e1); } continue; } } catch (Throwable t) { log.d(MSystem.getClassName(to), attr.getName(), t); } } } /** * Functionize a String. Remove bad names and set first characters to upper. Return def if the * name can't be created, e.g. only numbers. * * @param in * @param firstUpper * @param def * @return The function name */ public static String toFunctionName(String in, boolean firstUpper, String def) { if (MString.isEmpty(in)) return def; boolean first = firstUpper; StringBuilder out = new StringBuilder(); for (int i = 0; i < in.length(); i++) { char c = in.charAt(i); if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_') { if (first) c = Character.toUpperCase(c); first = false; out.append(c); } else if (!first && c >= '0' && c <= '9') { out.append(c); } else { first = true; } } if (out.length() == 0) return def; return out.toString(); } public static IProperties pojoToProperties(Object from) throws IOException { return pojoToProperties(from, getDefaultModelFactory()); } public static IProperties pojoToProperties(Object from, PojoModelFactory factory) throws IOException { MProperties out = new MProperties(); PojoModel model = factory.createPojoModel(from.getClass()); for (PojoAttribute<?> attr : model) { try { if (!attr.canRead()) continue; Object value = attr.get(from); String name = attr.getName(); Class<?> type = attr.getType(); if (type == int.class) out.setInt(name, (int) value); else if (type == Integer.class) out.setInt(name, (Integer) value); else if (type == long.class) out.setLong(name, (long) value); else if (type == Long.class) out.setLong(name, (Long) value); else if (type == float.class) out.setFloat(name, (float) value); else if (type == Float.class) out.setFloat(name, (Float) value); else if (type == double.class) out.setDouble(name, (double) value); else if (type == Double.class) out.setDouble(name, (Double) value); else if (type == boolean.class) out.setBoolean(name, (boolean) value); else if (type == Boolean.class) out.setBoolean(name, (Boolean) value); else if (type == String.class) out.setString(name, (String) value); else if (type == Date.class) out.setDate(name, (Date) value); else out.setString(name, String.valueOf(value)); } catch (Throwable t) { log.d(MSystem.getClassName(from), attr.getName(), t); } } return out; } public static void propertiesToPojo(IProperties from, Object to) throws IOException { propertiesToPojo(from, to, getDefaultModelFactory(), null, false); } public static void propertiesToPojo(IProperties from, Object to, boolean force) throws IOException { propertiesToPojo(from, to, getDefaultModelFactory(), null, force); } public static void propertiesToPojo(IProperties from, Object to, PojoModelFactory factory) throws IOException { propertiesToPojo(from, to, factory, null, false); } @SuppressWarnings("unchecked") public static void propertiesToPojo( IProperties from, Object to, PojoModelFactory factory, Caster<Object, Object> unknownHadler, boolean force) throws IOException { PojoModel model = factory.createPojoModel(to.getClass()); for (PojoAttribute<Object> attr : model) { if (!attr.canWrite()) continue; String name = attr.getName(); Class<?> type = attr.getType(); try { if (!from.isProperty(name) || !attr.canWrite()) { } else if (type == Boolean.class || type == boolean.class) attr.set(to, from.getBoolean(name, false), force); else if (type == Integer.class || type == int.class) attr.set(to, from.getInt(name, 0), force); else if (type == String.class) attr.set(to, from.getString(name, null), force); else if (type == UUID.class) try { attr.set(to, UUID.fromString(from.getString(name)), force); } catch (IllegalArgumentException e) { attr.set(to, null, force); } else if (type.isEnum()) { Object[] cons = type.getEnumConstants(); int ord = from.getInt(name, 0); Object c = cons.length > 0 ? cons[0] : null; if (ord >= 0 && ord < cons.length) c = cons[ord]; attr.set(to, c, force); } else attr.set( to, unknownHadler == null ? from.getString(name) : unknownHadler.cast(from.get(name), null), force); } catch (Throwable t) { log.d(MSystem.getClassName(to), name, t); } } } /** * toAttributeName. * * @param idents * @return a {@link java.lang.String} object. * @since 3.3.0 */ public static String toAttributeName(Identifier... idents) { if (idents == null) return null; if (idents.length == 0) return ""; if (idents.length == 1) return idents[0].getPojoName(); StringBuilder out = new StringBuilder(); for (Identifier ident : idents) { if (out.length() > 0) out.append('_'); out.append(ident.getPojoName()); } return out.toString(); } @SuppressWarnings("unchecked") public static void propertiesToPojo(Map<String, String> from, Object to, TransformHelper helper) throws IOException { PojoModel model = helper.createPojoModel(from); for (PojoAttribute<Object> attr : model) { String name = attr.getName(); String value = from.get(name); if (value != null) { attr.set(to, value, helper.isForce()); } } } public static void pojoToObjectStream(Object from, ObjectOutputStream to) throws IOException { pojoToObjectStream(from, to, getDefaultModelFactory()); } public static void pojoToObjectStream( Object from, ObjectOutputStream to, PojoModelFactory factory) throws IOException { PojoModel model = factory.createPojoModel(from.getClass()); for (PojoAttribute<?> attr : model) { String name = attr.getName(); Object value = attr.get(from); to.writeObject(name); to.writeObject(value); } to.writeObject(" "); } public static void objectStreamToPojo(ObjectInputStream from, Object to) throws IOException, ClassNotFoundException { objectStreamToPojo(from, to, getDefaultModelFactory(), false); } public static void objectStreamToPojo(ObjectInputStream from, Object to, boolean force) throws IOException, ClassNotFoundException { objectStreamToPojo(from, to, getDefaultModelFactory(), force); } public static void objectStreamToPojo( ObjectInputStream from, Object to, PojoModelFactory factory) throws IOException, ClassNotFoundException { objectStreamToPojo(from, to, factory, false); } @SuppressWarnings("unchecked") public static void objectStreamToPojo( ObjectInputStream from, Object to, PojoModelFactory factory, boolean force) throws IOException, ClassNotFoundException { PojoModel model = factory.createPojoModel(to.getClass()); while (true) { String name = (String) from.readObject(); if (name.equals(" ")) break; Object value = from.readObject(); @SuppressWarnings("rawtypes") PojoAttribute attr = model.getAttribute(name); if (attr != null) attr.set(to, value, force); } } public static void base64ToObject(String content, Object obj, PojoModelFactory factory) throws IOException, ClassNotFoundException { ByteArrayInputStream bais = new ByteArrayInputStream(Base64.getDecoder().decode(content)); ObjectInputStream ois = new ObjectInputStream(bais); MPojo.objectStreamToPojo(ois, obj, factory); } public static String objectToBase64(Object obj, PojoModelFactory factory) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); MPojo.pojoToObjectStream(obj, oos, factory); return Base64.getEncoder().encodeToString(baos.toByteArray()); } }
<filename>frameworks/src/Framework-See/See/ImageSource.h // // ImageSource.h // Framework-See // // Created by <NAME> on 11/18/10. // Copyright 2010 Carnegie Mellon University // // This work was developed under the Rehabilitation Engineering Research // Center on Accessible Public Transportation (www.rercapt.org) and is funded // by grant number H133E080019 from the United States Department of Education // through the National Institute on Disability and Rehabilitation Research. // No endorsement should be assumed by NIDRR or the United States Government // for the content contained on this code. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #import <Foundation/Foundation.h> #import <CoreMedia/CoreMedia.h> #import <AVFoundation/AVFoundation.h> /*! Image source delegate protocol */ @protocol ImageSourceDelegate <NSObject> @optional - (void)processSampleBuffer:(CMSampleBufferRef)sampleBuffer withPresentationTime:(CMTime)time; @end /*! Image sources manager */ @interface ImageSource : NSObject <AVCaptureVideoDataOutputSampleBufferDelegate> { AVCaptureDeviceInput *cameraInput; //!< camera input AVCaptureVideoDataOutput *cameraOutput; //!< video data output // AVCaptureStillImageOutput *stillCameraOutput; //!< still image camera output AVAssetWriter *writer; //!< video writer AVAssetWriterInput *writerInput; //!< video writer input NSURL *videoPath; //!< video path CMTime recordTime; //!< record time BOOL record; //!< record? dispatch_queue_t frameGrabberQueue; //!< serial queue to save video frames } @property (nonatomic, assign) id <ImageSourceDelegate> delegate; @property (nonatomic, retain) AVCaptureSession *session; @property (nonatomic, strong) dispatch_queue_t frameGrabberQueue; - (id) init; - (BOOL) setupCaptureSessionWithPreset:(NSString *)preset error:(NSError **)error; - (BOOL) setupCaptureSessionWithPreset:(NSString *)preset videoOrientation:(AVCaptureVideoOrientation)videoOrientation error:(NSError **)error; - (BOOL) startCaptureSession; - (BOOL) stopCapturingSession; - (AVCaptureVideoPreviewLayer*) layerWithSession; - (BOOL) setupVideoWriter:(NSURL *)url width:(int)width height:(int)height error:(NSError **)error; - (BOOL) isWriting; - (BOOL) saveCurrentFrame:(CMSampleBufferRef)frameSampleBuffer path:(NSString*)framePath; - (BOOL) autofocus; //- (BOOL) saveCurrentFrameWithHandler:(void (^)(CMSampleBufferRef imageDataSampleBuffer, NSError *error))handler; @end
pub struct Account { }
Apparent pseudohyperkalemia in a Chinese Shar Pei dog. Whole blood in a serum clot tube and EDTA-anticoagulated samples from an 8-year-old spayed female Chinese Shar Pei dog were submitted by an external clinic to the diagnostic laboratory at Atlantic Veterinary College for routine biochemical and hematologic analysis prior to entropion surgery. Laboratory abnormalities included mild hyperkalemia (6.3 mmol/L, reference interval 3.6-6.0 mmol/L), mild normocytic, hypochromic, nonregenerative anemia (HCT 0.31 L/L, reference interval 0.37-0.55 L/L; MCHC 290 g/L, reference interval 320-360 g/L), and increased red cell distribution width (RDW; 26.2%, reference interval 11-14%). A small subpopulation of macrocytic, slightly hypochromic erythrocytes was noted on Wright's-Giemsa-stained blood smears. Biochemical and hematologic data obtained from this patient over the previous 7.5 years indicated that serum (and in 1 case, heparinized plasma) potassium concentration was increased (range, 6.3-10.9 mmol/L) in 5 of 8 samples (HCT ranged from 0.31-0.43 L/L, Hgb 91-124 g/L, MCHC 280-312 g/L, and RDW 18.2-26.9%). Clinical signs suggestive of hyperkalemia were not observed at any time, suggesting pseudohyperkalemia as the cause of the increased potassium concentrations. An erythrocyte lysate prepared from a heparinized blood sample had a high potassium concentration (16.8 mmol/L) compared with that of a clinically healthy, non-Shiba control dog (6.7 mmol/L). An osmotic fragility test of the patient's erythrocytes showed 50% hemolysis at 0.57% NaCl, compared with 0.48% NaCl for the control dog, indicating increased fragility. On scanning electron microscopy, a small subpopulation of erythrocytes were large, flattened, and had a tendency to fold. These findings supported the provisional diagnosis of pseudohyperkalemia due to increased intracellular RBC potassium concentration. High-potassium erythrocytes have been reported in Akitas, Shibas, Jindos, other East Asian dog breeds, and occasionally, in mixed-breed dogs. Pseudohyperkalemia should also be considered when an otherwise unexplained elevation in serum or plasma potassium concentration is observed in Chinese Shar Pei dogs, and may be accompanied by increased RDW, low MCHC, and increased osmotic fragility with or without mild anemia.
def _message_status(self, message_uuid: str) -> MessageStatus: self.logger.debug("Checking for message status: %s.", message_uuid) if message_uuid in self._uuids_received: return MessageStatus.RECEIVED else: return MessageStatus.UNKNOWN
Tribological properties of black phosphorus nanosheets as oil-based lubricant additives for titanium alloy-steel contacts The black phosphorus (BP) powders were prepared by high-energy ball milling with red phosphorus as the raw material, and then the BP nanosheets were obtained by liquid-phase exfoliation. The tribological properties of the BP nanosheets as oil-based lubricant additives were investigated by the ball-on-disc tribometer. Results show that compared with the base oil of liquid paraffin (LP), the coefficient of friction and wear rate of the BP nanosheets as the additives in liquid paraffin (BP-LP) are lower for the same loads. BP-LP lubricants could significantly improve the load-bearing capacity of the base oil for titanium alloy-steel contacts and show excellent friction-reducing and anti-wear properties. The surface morphologies and elemental compositions of the friction pairs were further analysed using an optional microscope, scanning electron microscope and X-ray photoelectron spectroscopy. The lubrication mechanism of BP-LP can be attributed to the synergistic effects between lamellar adsorption and interlayer shear of BP nanosheets. Decision letter (RSOS-200530.R0) We hope you are keeping well at this difficult and unusual time. We continue to value your support of the journal in these challenging circumstances. If Royal Society Open Science can assist you at all, please don't hesitate to let us know at the email address below. Dear Professor Wang: Title: Tribological properties of black phosphene nanosheets as oil-based lubricant additives for titanium alloy-steel contacts Manuscript ID: RSOS-200530 Thank you for submitting the above manuscript to Royal Society Open Science. On behalf of the Editors and the Royal Society of Chemistry, I am pleased to inform you that your manuscript will be accepted for publication in Royal Society Open Science subject to minor revision in accordance with the referee suggestions. Please find the reviewers' comments at the end of this email. The reviewers and handling editors have recommended publication, but also suggest some minor revisions to your manuscript. Therefore, I invite you to respond to the comments and revise your manuscript. Because the schedule for publication is very tight, it is a condition of publication that you submit the revised version of your manuscript before 11-Jul-2020. Please note that the revision deadline will expire at 00.00am on this date. If you do not think you will be able to meet this date please let me know immediately. To revise your manuscript, log into https://mc.manuscriptcentral.com/rsos and enter your Author Centre, where you will find your manuscript title listed under "Manuscripts with Decisions". Under "Actions," click on "Create a Revision." You will be unable to make your revisions on the originally submitted version of the manuscript. Instead, revise your manuscript and upload a new version through your Author Centre. When submitting your revised manuscript, you will be able to respond to the comments made by the referees and upload a file "Response to Referees" in "Section 6 -File Upload". You can use this to document any changes you make to the original manuscript. In order to expedite the processing of the revised manuscript, please be as specific as possible in your response to the referees. When uploading your revised files please make sure that you have: 1) A text file of the manuscript (tex, txt, rtf, docx or doc), references, tables (including captions) and figure captions. Do not upload a PDF as your "Main Document". 2) A separate electronic file of each figure (EPS or print-quality PDF preferred (either format should be produced directly from original creation package), or original software format) 3) Included a 100 word media summary of your paper when requested at submission. Please ensure you have entered correct contact details (email, institution and telephone) in your user account 4) Included the raw data to support the claims made in your paper. You can either include your data as electronic supplementary material or upload to a repository and include the relevant doi within your manuscript 5) All supplementary materials accompanying an accepted article will be treated as in their final form. Note that the Royal Society will neither edit nor typeset supplementary material and it will be hosted as provided. Please ensure that the supplementary material includes the paper details where possible (authors, article title, journal name). Supplementary files will be published alongside the paper on the journal website and posted on the online figshare repository (https://figshare.com). The heading and legend provided for each supplementary file during the submission process will be used to create the figshare page, so please ensure these are accurate and informative so that your files can be found in searches. Files on figshare will be made available approximately one week before the accompanying article so that the supplementary material can be attributed a unique DOI. ********************************************** RSC Subject Editor: Comments to the Author: (There are no comments.) RSC Associate Editor: Comments to the Author: NA ********************************************** Reviewer comments to Author: Reviewer: 1 Comments to the Author(s) The PDF file has been attached Reviewer: 2 Comments to the Author(s) 1) The discussion part is not strong enough, most of the articles are explaining the data. It's really difficult to persuade the author's point of view, especially for the lubricating mechanism. 2) It is recommended to calculate wear from the profile of the wear scar, so that the mechanism of wear can be more accurately observed. Recommendation? Accept as is Comments to the Author(s) The authors have carefully considered all suggestions and criticisms of both referees. I find the answers to my questions and suggestions very convincing. The present manuscript is highly likely to initiate interesting discussions and follow-up studies. I strongly recommend publication of the manuscript in its present form. Decision letter (RSOS-200530.R1) We hope you are keeping well at this difficult and unusual time. We continue to value your support of the journal in these challenging circumstances. If Royal Society Open Science can assist you at all, please don't hesitate to let us know at the email address below. Dear Professor Wang: Title: Tribological properties of black phosphene nanosheets as oil-based lubricant additives for titanium alloy-steel contacts Manuscript ID: RSOS-200530.R1 It is a pleasure to accept your manuscript in its current form for publication in Royal Society Open Science. The chemistry content of Royal Society Open Science is published in collaboration with the Royal Society of Chemistry. The comments of the reviewer(s) who reviewed your manuscript are included at the end of this email. Thank you for your fine contribution. On behalf of the Editors of Royal Society Open Science and the Royal Society of Chemistry, I look forward to your continued contributions to the Journal. Comments to the Author(s) The authors have carefully considered all suggestions and criticisms of both referees. I find the answers to my questions and suggestions very convincing. The present manuscript is highly likely to initiate interesting discussions and follow-up studies. I strongly recommend publication of the manuscript in its present form. Manuscript title: Tribological properties of black phosphene nanosheets as oil-based lubricant additives for titanium alloy-steel contacts. Manuscript ID: RSOS-200530 The authors rigorously studied the black phosphorus (BP) powders preparation by high-energy ball milling with red phosphorus as source material. Further BP nanosheets obtained by liquidphase exfoliation and studied oil-based lubricant additives of synthesised materials. The paper is rich in data, novelty, used versatile characterization tool, explain band alignment and the general conclusion of the paper sounds. These facts make the paper suitable to be published in Royal Society Open Science, in principle. However, some minor corrections must be done before its acceptance. 1) I am not satisfied with the assigned XRD planes of BP, can you please make comment on it. You can see the literature the peak~34-35 degree is always assigned as <040> plane and same for others planes. 2) In figure 2, I strongly recommend to add XRD pattern and Raman spectra of (i) red phosphorus (ii) black phosphorus powder and (iii) black phosphorus nanosheets obtained by liquid-phase exfoliation 3) Assign the vibrational mode "B2g" which is appeared~438 cm -1 according to RSC Adv., In summary, I believe this is an interesting study, and the results could potentially be interesting and useful for 2D community and Materials Science. However, the above comments should be well addressed before the paper can be considered for publication. Resubmission of RSOS-200530 Dear Dr Laura Smith, We would like to express our gratitude to your efforts devoted to evaluating our manuscript entitled "Tribological properties of black phosphene nanosheets as oilbased lubricant additives for titanium alloy-steel contacts", which have been submitted to RSOS for the first-peer review. We appreciate the reviewer's constructive comments on our manuscript and your kind consideration of publishing this manuscript in Royal Society Open Science. We have addressed all of the comments and revised the manuscript accordingly. All of the changes have been highlighted by red font in the marked-up manuscript. Details of our replies to the comments and the revisions are described in the "Detailed Responses to the Reviewer Comments". We now resubmit the manuscript for your further consideration for publication in Royal Society Open Science. Detailed Responses to the Reviewer Comments-1 The authors rigorously studied the black phosphorus (BP) powders preparation by highenergy ball milling with red phosphorus as source material. Further BP nanosheets obtained by liquid phase exfoliation and studied oil-based lubricant additives of synthesized materials. The paper is rich in data, novelty, used versatile characterization tool, explain band alignment and the general conclusion of the paper sounds. These facts make the paper suitable to be published in Royal Society Open Science, in principle. However, some minor corrections must be done before its acceptance. 1) I am not satisfied with the assigned XRD planes of BP, can you please make comment on it. You can see the literature the peak ~34-35 degree is always assigned as <040> planeand same for others planes. Response: Thank you for your suggestion. We have revised the assigned XRD planes of BP, the peak ~34-35 degree was assigned as <040> in the figure 2. The revised Fig.2 was presented in the following parts. The XRD patterns and Raman spectroscopies of RP, BP powders and BP nanosheets are shown in Fig. 2(a) and (b). It can be seen that RP has two large and broad diffraction peaks at 33° and 55°, indicating that RP has an amorphous structure. After HEBM for 2h, two broader diffraction peaks of RP were disappeared. The sharp diffraction peaks from 25° to 70° were appeared and the main characteristic peaks at 2θ =25°, 35° and 56° were presented. These results are consistent with standard orthorhombic BP (JCPDS No. 76-1957). It means that the phase transformation from RP to BP was occurred during HEBM. Compared with RP, the X-ray diffraction peak intensities of BP powers were significantly enhanced. It indicates that the crystallinity of BP powers is also improved owing to the high temperature and pressure produced during HEBM. After HEBM, the Raman characteristic peaks of RP were also changed correspondingly. The broad peak of RP near 350 cm -1 was disappeared, while three sharp diffraction peaks at 357.4 cm -1 , 438cm -1 and 460 cm -1 in the spectrum of BP were appeared . These corresponding peaks were attributed to the lattice vibration of BP crystal. Besides, there are offset in the diffraction peaks of BP nanosheets, which is due to the decreased thickness of BP nanosheets . 3) Assign the vibrational mode "B2g" which is appeared ~ 438 cm -1 according to RSC Fig.4(d), (e). It confirms that the average thickness of BP nanosheets was measured at around 8nm. The revised Fig.4 (d) and (e) are presented in the following parts. 112103-112108. Detailed Responses to the Reviewer Comments-2 1) The discussion part is not strong enough, most of the articles are explaining the data. It's really difficult to persuade the author's point of view, especially for the lubricating mechanism. Response: Thank you for your suggestion. We have revised the discussion part and enriched the lubricating mechanism. According to Hamrock-Dowson (H-D) theory, the calculated ratio of film thickness to surface roughness λ is approximately 0.16, is smaller than 1, and thereby indicating the current lubrication is in the regime of boundary lubrication. The revised parts are marked the red front. The added and revised parts are presented as follows. According to classical lubrication theories, the lubrication regimes can be identified in a lubrication regime map in terms of the two variables ( and ): 2) It is recommended to calculate wear from the profile of the wear scar, so that the mechanism of wear can be more accurately observed. Response: Thank you for your suggestion. We have given the Hertz contact model of sphere-on-disc in figure 7, according to calculate corresponding maximum Hertzian contact stress, made some detailed explanations about the mechanism of wear. The revised parts are marked the red front. The added and revised parts are presented as follows. The above phenomenon can be explained by the Hertz's theory . The tribological properties of BP-LP lubricants were investigated by sphere-on-disc friction tests. Sphere contact as object, contact stress formula of Hertz are deduced theoretically from the contact model of spheres and disc , as shown in Fig. 7. When the sphere is in contact with disk under the external loading, elliptic contact area will be produced around the contact point due to the partial deformation of sphere and disc. The corresponding contact stresses were calculated according to Eq. (1). Where, and α are maximum Hertz contact stress and Hertz contact diameter, 0 respectively. F is the normal load (8N, 10N, 12N, 15N), R is the radius of the ball (3mm), E′ is the effective elastic modulus. It can be expressed by the following formula where E 1 (110 GPa) and E 2 (210 GPa) are the elastic moduli of the TC4 and GCr15, respectively. And μ 1 (0.34) and μ 2 (0.30) are the poisson ratios of the TC4 and GCr15, respectively. Thus, the corresponding maximum Hertzian contact stress are 1039MPa, 1119MPa, 1190MPa and 1281MPa. As for the Eq. (2), the elliptic contact area is increased proportional to the F, which indicates that the contact area increased more slowly than that of load. Based on the formulae of the friction coefficient, (μ = f/ is the COF, f is the frictional force, F is the load), it can be concluded that the values of the COF may be reduced as the load increased. The wear volumes of the ball side are calculated by the following formula : V is the wear volume, r is the radius of the ball, d is the wear scar diameter. Hence, the wear rate was decreased as the load increased and reduced the wear. These results showed that adding BP nanosheets as a lubrication additive into liquid paraffin can significantly improve the lubricating properties of the base oil of liquid paraffin and effectively reduce the wear of the GCr15/TC4 friction pair.
<filename>08.goft-tutorial/ddd/application/assembler/UserResp.go<gh_stars>1-10 package assembler import ( "goft-tutorial/ddd/application/dto" "goft-tutorial/ddd/domain/aggregates" "goft-tutorial/ddd/domain/models" ) // UserResp 把用户实体映射成 DTO 展示给前端 type UserResp struct{} // M2D_SimpleUserInfo 把用户实体映射为 简单用户 DTO func (u *UserResp) M2D_SimpleUserInfo(user *models.UserModel) *dto.SimpleUserInfo { simpleUser := &dto.SimpleUserInfo{} simpleUser.Id = user.UserID simpleUser.Name = user.UserName simpleUser.City = user.Extra.UserCity return simpleUser } func (u *UserResp) M2D_UserInfo(mem *aggregates.Member) *dto.UserInfo { userInfo := &dto.UserInfo{} userInfo.Id = mem.User.UserID ///... 其他睡醒赋值 userInfo.Logs = u.M2D_UserLogs(mem.GetLogs()) return userInfo } func (u *UserResp) M2D_UserLogs(logs []*models.UserLogModel) (ret []*dto.UserLog) { return }
import math mod = 1000000007 a = raw_input() k = int(raw_input()) n = len(a) b1 = 0 pow2 = 1 for i in xrange(n): if a[i] == '5' or a[i] == '0': b1 += pow2 pow2 = pow2*2%mod inv = pow((pow(2,n,mod)-1),mod-2,mod)%mod res = b1*(pow(2,n*k,mod) - 1)%mod*(inv + mod)%mod print res%mod
class registry: """ Catalogue registry for types, preprocessors, logging configuration, and others """ # types for field specs types = catalogue.create('datagen', 'type') # schemas for field spec types schemas = catalogue.create('datagen', 'schemas') # functions to modify specs before running preprocessors = catalogue.create('datagen', 'preprocessor') # custom logging setup logging = catalogue.create('datagen', 'logging') # registered formats for output formats = catalogue.create('datagen', 'format') # different numeric distributions, normal, uniform, etc distribution = catalogue.create('datagen', 'distribution') # default values defaults = catalogue.create('datagen', 'defaults')
from yattag import indent from empugn import empugn from empugn.input import parse def test_empugn(): data = parse(''' html: - head: - title: Empugn example - link: rel: stylesheet href: foo.css - script: | alert('Hello, World'); - body: - h1: Sole text child may be specified as-is - p: - "Separating links by " - a: href: https://google.com target: _blank children: space - " may require quoting" - div: '''.strip()) assert indent(empugn(data), ' ').strip() == ''' <!DOCTYPE html> <html> <head> <title>Empugn example</title> <link rel="stylesheet" href="foo.css" /> <script>alert('Hello, World'); </script> </head> <body> <h1>Sole text child may be specified as-is</h1> <p>Separating links by <a href="https://google.com" target="_blank">space</a> may require quoting</p> <div></div> </body> </html> '''.strip()
// These tests use the path service, which uses autoreleased objects on the // Mac, so this needs to be a PlatformTest. class BZip2FilterUnitTest : public PlatformTest { protected: virtual void SetUp() { PlatformTest::SetUp(); bzip2_encode_buffer_ = NULL; std::wstring file_path; PathService::Get(base::DIR_SOURCE_ROOT, &file_path); file_util::AppendToPath(&file_path, L"net"); file_util::AppendToPath(&file_path, L"data"); file_util::AppendToPath(&file_path, L"filter_unittests"); file_util::AppendToPath(&file_path, L"google.txt"); file_util::ReadFileToString(file_path, &source_buffer_); source_buffer_.append(kExtraData, kExtraDataBufferSize); bzip2_data_stream_.reset(new bz_stream); ASSERT_TRUE(bzip2_data_stream_.get()); memset(bzip2_data_stream_.get(), 0, sizeof(bz_stream)); int result = BZ2_bzCompressInit(bzip2_data_stream_.get(), 9, 0, 0); ASSERT_EQ(BZ_OK, result); bzip2_encode_buffer_ = new char[kDefaultBufferSize]; ASSERT_TRUE(bzip2_encode_buffer_ != NULL); bzip2_encode_len_ = kDefaultBufferSize; bzip2_data_stream_->next_in = const_cast<char*>(source_buffer()); bzip2_data_stream_->avail_in = source_len(); bzip2_data_stream_->next_out = bzip2_encode_buffer_; bzip2_data_stream_->avail_out = bzip2_encode_len_; do { result = BZ2_bzCompress(bzip2_data_stream_.get(), BZ_FINISH); } while (result == BZ_FINISH_OK); ASSERT_EQ(BZ_STREAM_END, result); result = BZ2_bzCompressEnd(bzip2_data_stream_.get()); ASSERT_EQ(BZ_OK, result); bzip2_encode_len_ = bzip2_data_stream_->total_out_lo32; ASSERT_GT(bzip2_encode_len_, 0); ASSERT_LE(bzip2_encode_len_, kDefaultBufferSize); } virtual void TearDown() { delete[] bzip2_encode_buffer_; bzip2_encode_buffer_ = NULL; PlatformTest::TearDown(); } void DecodeAndCompareWithFilter(Filter* filter, const char* source, int source_len, const char* encoded_source, int encoded_source_len, int output_buffer_size, bool get_extra_data) { ASSERT_LE(source_len, kDefaultBufferSize); ASSERT_LE(output_buffer_size, kDefaultBufferSize); int total_output_len = kDefaultBufferSize; if (get_extra_data) total_output_len += kExtraDataBufferSize; char decode_buffer[kDefaultBufferSize + kExtraDataBufferSize]; char* decode_next = decode_buffer; int decode_avail_size = total_output_len; const char* encode_next = encoded_source; int encode_avail_size = encoded_source_len; Filter::FilterStatus code = Filter::FILTER_OK; while (code != Filter::FILTER_DONE) { int encode_data_len; if (get_extra_data && !encode_avail_size) break; encode_data_len = std::min(encode_avail_size, filter->stream_buffer_size()); memcpy(filter->stream_buffer(), encode_next, encode_data_len); filter->FlushStreamBuffer(encode_data_len); encode_next += encode_data_len; encode_avail_size -= encode_data_len; while (1) { int decode_data_len = std::min(decode_avail_size, output_buffer_size); code = filter->ReadData(decode_next, &decode_data_len); decode_next += decode_data_len; decode_avail_size -= decode_data_len; ASSERT_TRUE(code != Filter::FILTER_ERROR); if (code == Filter::FILTER_NEED_MORE_DATA || code == Filter::FILTER_DONE) { if (code == Filter::FILTER_DONE && get_extra_data) code = Filter::FILTER_OK; else break; } } } int decode_total_data_len = total_output_len - decode_avail_size; EXPECT_TRUE(decode_total_data_len == source_len); EXPECT_EQ(memcmp(source, decode_buffer, source_len), 0); } Filter::FilterStatus DecodeAllWithFilter(Filter* filter, const char* source, int source_len, char* dest, int* dest_len) { memcpy(filter->stream_buffer(), source, source_len); filter->FlushStreamBuffer(source_len); return filter->ReadData(dest, dest_len); } const char* source_buffer() const { return source_buffer_.data(); } int source_len() const { return static_cast<int>(source_buffer_.size()) - kExtraDataBufferSize; } std::string source_buffer_; scoped_ptr<bz_stream> bzip2_data_stream_; char* bzip2_encode_buffer_; int bzip2_encode_len_; }
#include "bits/stdc++.h" #pragma GCC optimize ("O3") #pragma GCC target ("sse4") using namespace std; const int maxk = 21; const int maxn = 100100; int cnt[maxn], L, R; long long res; long long dp[maxk][maxn]; int arr[maxn], n, k; void expandL(){ L--; res += cnt[arr[L]]; cnt[arr[L]]++; } void reduceL(){ cnt[arr[L]]--; res -= cnt[arr[L]]; L++; } void expandR(){ R++; res += cnt[arr[R]]; cnt[arr[R]]++; } void reduceR(){ cnt[arr[R]]--; res -= cnt[arr[R]]; R--; } void putInterval(int l, int r){ while(L > l) expandL(); while(R < r) expandR(); while(L < l) reduceL(); while(R > r) reduceR(); } void solve(int layer, int l, int r, int from, int to){ if(l > r) return; int mid = (l + r)>>1; long long ans = 1ll<<60; int opt = from; for(int now = from; now <= to; now++){ if(now >= mid) break; putInterval(now + 1, mid); if(dp[layer-1][now] + res <= ans){ ans = dp[layer-1][now] + res; opt = now; } } dp[layer][mid] = ans; solve(layer, mid + 1, r, opt, to); solve(layer, l, mid - 1, from, opt); } int main(){ scanf("%d %d", &n, &k); for(int e = 1; e <= n; e++) scanf("%d", arr + e); L = 1; R = 0; for(int e = 1; e <= n; e++){ expandR(); dp[0][e] = res; } for(int e = 1; e < k; e++) solve(e, 1, n, 0, n); cout << dp[k-1][n] << endl; return 0; }
// // THIS FILE IS GENERATED BY fastbin // DO NOT MODIFY BY MANUAL // package module1 import "github.com/funny/binary" func (this *AddReq) MarshalBinary() (data []byte, err error) { var buf = binary.Buffer{Data: make([]byte, this.BinarySize())} this.MarshalWriter(&buf) return buf.Data, nil } func (this *AddReq) UnmarshalBinary(data []byte) error { this.UnmarshalPacket(data) return nil } func (this *AddReq) MarshalPacket(p []byte) { var buf = binary.Buffer{Data: p} this.MarshalWriter(&buf) } func (this *AddReq) UnmarshalPacket(p []byte) { var buf = binary.Buffer{Data: p} this.UnmarshalReader(&buf) } func (this *AddReq) BinarySize() (n int) { n = 8 + 8 return n } func (this *AddReq) MarshalWriter(w binary.BinaryWriter) { w.WriteUint64LE(uint64(this.A)) w.WriteUint64LE(uint64(this.B)) } func (this *AddReq) UnmarshalReader(r binary.BinaryReader) { this.A = int(r.ReadUint64LE()) this.B = int(r.ReadUint64LE()) } func (this *AddRsp) MarshalBinary() (data []byte, err error) { var buf = binary.Buffer{Data: make([]byte, this.BinarySize())} this.MarshalWriter(&buf) return buf.Data, nil } func (this *AddRsp) UnmarshalBinary(data []byte) error { this.UnmarshalPacket(data) return nil } func (this *AddRsp) MarshalPacket(p []byte) { var buf = binary.Buffer{Data: p} this.MarshalWriter(&buf) } func (this *AddRsp) UnmarshalPacket(p []byte) { var buf = binary.Buffer{Data: p} this.UnmarshalReader(&buf) } func (this *AddRsp) BinarySize() (n int) { n = 8 return n } func (this *AddRsp) MarshalWriter(w binary.BinaryWriter) { w.WriteUint64LE(uint64(this.C)) } func (this *AddRsp) UnmarshalReader(r binary.BinaryReader) { this.C = int(r.ReadUint64LE()) }
def Extract(self, source_table, destination_uris, print_header=None, field_delimiter=None, destination_format=None, compression=None, **kwds): _Typecheck(source_table, ApiClientHelper.TableReference) uris = destination_uris.split(',') for uri in uris: if not uri.startswith(_GCS_SCHEME_PREFIX): raise BigqueryClientError( 'Illegal URI: {}. Extract URI must start with "{}".'.format( uri, _GCS_SCHEME_PREFIX)) extract_config = {'sourceTable': dict(source_table)} _ApplyParameters( extract_config, destination_uris=uris, destination_format=destination_format, print_header=print_header, field_delimiter=field_delimiter, compression=compression) return self.ExecuteJob(configuration={'extract': extract_config}, **kwds)
<filename>src/solo/SoloVertexBufferLayout.cpp /* * Copyright (c) <NAME> * MIT license */ #include "SoloVertexBufferLayout.h" using namespace solo; void VertexBufferLayout::addAttribute(u32 elementCount, const str &name, VertexAttributeUsage usage) { const auto size = static_cast<u32>(sizeof(float) * elementCount); const auto offset = attributes_.empty() ? 0 : attributes_.crbegin()->offset + attributes_.crbegin()->size; attributes_.push_back(VertexAttribute{name, elementCount, size, offset, usage}); this->elementCount_ += elementCount; this->size_ += size; } void VertexBufferLayout::addAttribute(VertexAttributeUsage usage) { switch (usage) { case VertexAttributeUsage::Position: addAttribute(3, "sl_Position", VertexAttributeUsage::Position); break; case VertexAttributeUsage::Normal: addAttribute(3, "sl_Normal", VertexAttributeUsage::Normal); break; case VertexAttributeUsage::TexCoord: addAttribute(2, "sl_TexCoord", VertexAttributeUsage::TexCoord); break; case VertexAttributeUsage::Tangent: addAttribute(3, "sl_Tangent", VertexAttributeUsage::Tangent); break; case VertexAttributeUsage::Binormal: addAttribute(3, "sl_Binormal", VertexAttributeUsage::Binormal); break; default: panic("Unsupported vertex attribute usage"); } } auto VertexBufferLayout::attributeIndex(VertexAttributeUsage usage) const -> s32 { for (s32 i = 0; i < attributes_.size(); i++) { if (attributes_[i].usage == usage) return i; } return -1; }
c=0 ar=[] arr=[] m=0 for i in range(int(input())): s=input() arr.append(s) if s not in ar: ar.append(s) for i in ar: if arr.count(i)>m: m=arr.count(i) ans=i print(ans)
//------------------------------------------- // called when parallel addition is finished //------------------------------------------- void merge() { for (int i = 0; i < max_thread; i++) { if (local_front[i].size() > 0) { data.splice(data.begin(), local_front[i]); } if (local_back[i].size() > 0) { data.splice(data.end(), local_back[i]); } } }
In the NHL, a 2-2-3 start to a team’s season may not be the most desired beginning on the quest for the Stanley Cup. For the Florida Panthers however, the 7 points in 7 games is seen only as a positive. A notoriously poor starting team, the Cats have managed points in 5 of their first 7 games despite struggling immensely to put the puck in the net. Two things that eluded the Panthers last year are turning out to be the backbone of their more respectable start. Roberto Luongo has played up to his standards and newly signed free agent Al Montoya (nicknamed “El Cubano”) has impressed so far, including a strong 27 save performance in a 2-1 shootout loss to Washington earlier this month. The Panthers have always been a team with skilled goaltenders. Names like John Vanbiesbrouck, Mike Vernon, Ed Belfour and Tomas Vokoun have all warn the Panthers red at one point in their careers, so strength in goaltending is somewhat familiar territory for the Cats. The difference that Panthers fans are noticing this year is in the defensive play of the team. No longer are they allowing easy looks in their own zone. Players are backing up their teammates with proper position, pucks are getting out of the zone much quicker, and sticks are constantly in passing lanes to prevent any sort of flow from the opposition. A lot of these improvements can be credited to newly appointed defensive coach Mark Morris. Morris joined the Panthers along with Mike Kelly in July of this year, and with him comes a sea of experience. For the prior eight seasons, Morris had been head coach of the Los Angeles Kings’ AHL affiliate, the Manchester Monarchs. During his tenure he accumulated over 350 wins, including a 49-19-2-6 record this past campaign on route to the Monarchs winning the AHL’s Regular Season Eastern Conference Championship. Manchester was consistently in the top-10 in goals against nearly every year that Morris coached the team and finished 3rd in the goals against last season. This year, the Panthers are noticeably more effective in their own zone and Morris has been a large factor in the change. Along with Morris, two new faces have joined the Panthers blue line this year. One of those is Willie Mitchell, a 37-year old veteran of the game who was also named captain of the Panthers before the start of the season. The other is Aaron Eklbad, the Panthers prize possession from this year’s NHL Entry draft. Despite being in completely opposite parts of their careers, the two have fit with the team well and are performing extremely well on the ice. Ekblad specifically has exceeded expectations thus far, playing with an aura of confidence and poise rarely seen in an 18-year-old defenseman. Whether or not much of this can be credited to Morris’ coaching is yet to be known, but one thing that is certain is that he has the entire team playing a more sound defensive game. The Panthers currently sit tied for 4th in the NHL in goals against, allowing an average of 2.28 per game. This is a significant jump from last year where they finished 29th in the league under the same category, allowing an average of 3.26 goals against per game (down almost an entire goal per game). Only the Edmonton Oilers gave up more goals than the Panthers last season. Although the sample size is small to start this season, the play of the Panthers defense has clearly improved, as evident in the aforementioned game against the Capitals earlier this month. Going into that game, Washington had scored 15 goals in their previous 3 games, not unheard of for a team featuring the likes of Alex Ovechkin and Niklas Backstrom. The Cats held them to only one goal on 28 shots and minimized the scoring chances of one of the league’s best natural goal scorers. Eventually the Panthers lost that game in the shootout due to a lack of offensive creativity, but we’re talking defense here so we should move on. Let’s do a little fantasy scenario for a moment here to finish things off. The Panthers had their worst performance of the young season in their home opener against New Jersey. The Devils scored four times in the opening stanza and never looked back on their way to a convincing 5-1 victory. If we were to remove this first period completely, the Panthers have allowed 12 goals in 7 games played, averaging out about 1.71 goals against per game. Obviously this number is not sustainable over the course of an 82-game season, but it’s clear that under the influence of Mark Morris, the Panthers have taken a gigantic step in the right direction defensively. With the additions of Willie Mitchell and youngster Aaron Ekblad, the defense as a whole seems to be rounding out well. Now if they could only get the offence going.
export * from './cassandra-options.interface';
<reponame>esquiloio/eboot /**HEADER******************************************************************** * * Copyright (c) 2008, 2013 - 2015 Freescale Semiconductor; * All Rights Reserved * *************************************************************************** * * THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESSED 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 FREESCALE OR ITS 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. * ************************************************************************** * * $FileName: khci.c$ * $Version : * $Date : * * Comments: * * This file contains KHCI-specific implementations of USB interfaces * *END************************************************************************/ #include "usb_host_config.h" #if USBCFG_HOST_KHCI #include "usb.h" #include "usb_host_stack_interface.h" #include "usb_host_common.h" #include "usb_host.h" #include "khci.h" #include "khci_prv.h" #include "usb_host_dev_mng.h" #include "fsl_usb_khci_hal.h" #define USB_ASYNC_MODE 0 #ifdef KHCI_DEBUG struct debug_messaging { char inout; tr_msg_type_t type; uint8_t ep; uint16_t size; }; volatile static uint16_t dm_index = 0; volatile static struct debug_messaging dm[1024] = { 0 }; /* note, the array is for 1024 records only */ # define KHCI_DEBUG_LOG(a, b, c, d) \ { \ dm[dm_index].inout = a; \ dm[dm_index].type = b; \ dm[dm_index].ep = c; \ dm[dm_index].size = d; \ dm_index++; \ } #else # define KHCI_DEBUG_LOG(a, b, c, d) {} #endif // KHCI task parameters #define USB_KHCI_TASK_NUM_MESSAGES 16 #define USB_KHCI_TASK_TEMPLATE_INDEX 0 #if !(USE_RTOS) #define USB_KHCI_TASK_ADDRESS _usb_khci_task #else #define USB_KHCI_TASK_ADDRESS _usb_khci_task_stun #endif #if ((OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_SDK) && USE_RTOS) /* USB stack running on MQX */ #define USB_NONBLOCKING_MODE 0 #elif ((OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_SDK) && (!USE_RTOS)) /* USB stack running on BM */ #define USB_NONBLOCKING_MODE 1 #endif #define USB_KHCI_TASK_STACKSIZE 3500 #define USB_KHCI_TASK_NAME "KHCI Task" #define USB_KHCI_TASK_ATTRIBUTES 0 #define USB_KHCI_TASK_CREATION_PARAMETER 0 #define USB_KHCI_TASK_DEFAULT_TIME_SLICE 0 #define USB_KHCI_MAX_SPEED_DETECTION_COUNT 3 // atom transaction error results #define KHCI_ATOM_TR_PID_ERROR (-1) #define KHCI_ATOM_TR_EOF_ERROR (-2) #define KHCI_ATOM_TR_CRC_ERROR (-4) #define KHCI_ATOM_TR_TO (-16) #define KHCI_ATOM_TR_DMA_ERROR (-32) #define KHCI_ATOM_TR_BTS_ERROR (-128) #define KHCI_ATOM_TR_NAK (-256) #define KHCI_ATOM_TR_DATA_ERROR (-512) #define KHCI_ATOM_TR_STALL (-1024) #define KHCI_ATOM_TR_RESET (-2048) #define KHCI_ATOM_TR_BUS_TIMEOUT (-4096) #define KHCI_ATOM_TR_INVALID (-8192) #if defined( __ICCCF__ ) || defined( __ICCARM__ ) #pragma segment="USB_BDT_Z" #pragma data_alignment=512 __no_init static uint8_t bdt[512] @ "USB_BDT_Z"; #elif defined(__GNUC__) __attribute__((aligned(512))) static uint8_t bdt[512]; #elif defined (__CC_ARM) __align(512) uint8_t bdt[512]; #else #error Unsupported compiler, please use IAR, Keil or arm gcc compiler and rebuild the project. #endif #if USBCFG_KHCI_4BYTE_ALIGN_FIX static uint8_t *_usb_khci_swap_buf_ptr = NULL; #endif #define MSG_SIZE_IN_MAX_TYPE (1 + (sizeof(tr_msg_struct_t) - 1) / sizeof(uint32_t)) usb_khci_host_state_struct_t* usb_host_global_handler; /* Prototypes of functions */ usb_status _usb_khci_host_close_interface(usb_host_handle handle); //static usb_status _usb_khci_host_close_pipe(usb_host_handle handle, pipe_struct_t* pipe_ptr); static void _usb_khci_process_tr_complete(pipe_struct_t* pipe_desc_ptr, tr_struct_t* pipe_tr_ptr, uint32_t required, uint32_t remaining, int32_t err); static int32_t _usb_khci_tr_done(usb_khci_host_state_struct_t* usb_host_ptr, tr_msg_struct_t msg); static int32_t _usb_khci_atom_noblocking_tr(usb_khci_host_state_struct_t* usb_host_ptr,uint32_t type, pipe_struct_t* pipe_desc_ptr,uint8_t *buf_ptr,uint32_t len); //extern uint8_t usb_host_dev_mng_get_address(usb_device_instance_handle dev_handle); //extern uint8_t usb_host_dev_mng_get_speed(usb_device_instance_handle dev_handle); //extern uint8_t usb_host_dev_mng_get_level(usb_device_instance_handle dev_handle); //extern usb_status usb_host_dev_mng_attach(usb_host_handle handle, uint8_t speed, uint8_t hub_no, uint8_t port_no, uint8_t level, usb_device_instance_handle* dev_handle_ptr); //extern usb_status usb_host_dev_mng_detach(usb_host_handle handle, uint8_t hub_no, uint8_t port_no); //extern usb_status USB_log_error(char* file, uint32_t line, usb_status error); //extern uint8_t usb_host_dev_mng_get_attach_state(usb_device_instance_handle dev_handle); extern uint32_t OS_MsgQ_Is_Empty(os_msgq_handle msgq, void* msg); extern uint8_t soc_get_usb_vector_number(uint8_t controller_id); extern uint32_t soc_get_usb_base_address(uint8_t controller_id); extern uint32_t soc_get_usb_host_int_level(uint8_t controller_id); // KHCI event bits #define KHCI_EVENT_ATTACH 0x01 #define KHCI_EVENT_RESET 0x02 #define KHCI_EVENT_TOK_DONE 0x04 #define KHCI_EVENT_SOF_TOK 0x08 #define KHCI_EVENT_DETACH 0x10 #define KHCI_EVENT_MSG 0x20 #define KHCI_EVENT_ISO_MSG 0x40 #define KHCI_EVENT_NAK_MSG 0x80 #define KHCI_EVENT_MASK 0xff /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_get_hot_int_tr * Returned Value : 0 successful * Comments : * Make a message copy for transaction which need evaluation *END*-----------------------------------------------------------------*/ static uint32_t _usb_khci_get_total_frame_count(usb_khci_host_state_struct_t* usb_host_ptr) { static uint32_t total_frame_number = 0; static uint16_t old_frame_number = 0; uint16_t frame_number = 0xFFFF; //frame_number = ((usb_ptr->FRMNUMH) << 8) | (usb_ptr->FRMNUML); frame_number = usb_hal_khci_get_frame_number(usb_host_ptr->usbRegBase); if(frame_number < old_frame_number) { total_frame_number += 2048; } old_frame_number = frame_number; //USB_PRINTF("t %d\n", frame_number + total_frame_number); return (frame_number + total_frame_number); } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_isr * Returned Value : None * Comments : * Service all the interrupts in the kirin usb hardware *END*-----------------------------------------------------------------*/ #ifdef USBCFG_OTG void _usb_host_khci_isr(void) #else void _usb_khci_isr(void) #endif { usb_khci_host_state_struct_t* usb_host_ptr = (usb_khci_host_state_struct_t*)usb_host_global_handler; uint8_t status; //static uint32_t index = 0; while (1) { status = (uint8_t)(usb_hal_khci_get_interrupt_status(usb_host_ptr->usbRegBase) & usb_hal_khci_get_interrupt_enable_status(usb_host_ptr->usbRegBase)); if (!status) { break; } usb_hal_khci_clr_interrupt(usb_host_ptr->usbRegBase,status); //usb_ptr->ISTAT = status; //USB_PRINTF("0x%x\n", usb_ptr->ISTAT); if (status & INTR_SOFTOK) { OS_Event_set(usb_host_ptr->khci_event_ptr, KHCI_EVENT_SOF_TOK); } if (status & INTR_ATTACH) { /* USB device is (being) attached */ usb_hal_khci_disable_interrupts(usb_host_ptr->usbRegBase, INTR_ATTACH); //USB_PRINTF("0x%x\n", usb_ptr->INTEN); OS_Event_set(usb_host_ptr->khci_event_ptr, KHCI_EVENT_ATTACH); } if (status & INTR_TOKDNE) { // atom transaction done - token done //USB_PRINTF("k\n"); OS_Event_set(usb_host_ptr->khci_event_ptr, KHCI_EVENT_TOK_DONE); } if (status & INTR_USBRST) { // usb reset //USB_PRINTF("r\n"); usb_hal_khci_disable_interrupts(usb_host_ptr->usbRegBase, INTR_USBRST); OS_Event_set(usb_host_ptr->khci_event_ptr, KHCI_EVENT_RESET); } } } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_init_int_tr * Returned Value : None * Comments : * Initialize interrupt transaction queue *END*-----------------------------------------------------------------*/ static void _usb_khci_init_tr_que(usb_khci_host_state_struct_t* usb_host_ptr) { int32_t i; tr_int_que_itm_struct_t* tr = usb_host_ptr->tr_int_que; for (i = 0; i < USBCFG_HOST_KHCI_MAX_INT_TR; i++) { tr->msg.type = TR_MSG_UNKNOWN; tr++; } tr = usb_host_ptr->tr_nak_que; for (i = 0; i < USBCFG_HOST_KHCI_MAX_INT_TR; i++) { tr->msg.type = TR_MSG_UNKNOWN; tr++; } } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_add_int_tr * Returned Value : -1 queue is full * Comments : * Add new interrupt transaction to queue *END*-----------------------------------------------------------------*/ static int32_t _usb_khci_add_tr(usb_khci_host_state_struct_t* usb_host_ptr, tr_msg_struct_t *msg, uint32_t period,que_type_t type) { int32_t i = 0; tr_int_que_itm_struct_t* tr = NULL; if (type == TYPE_INT) { tr= usb_host_ptr->tr_int_que; } else if(type == TYPE_NAK) { tr= usb_host_ptr->tr_nak_que; } //TIME_STRUCT tm; // find free position for (i = 0; i < USBCFG_HOST_KHCI_MAX_INT_TR; i++) { if (tr->msg.type == TR_MSG_UNKNOWN) { tr->period = period; tr->frame = _usb_khci_get_total_frame_count(usb_host_ptr) + period; OS_Mem_copy(msg, &tr->msg, sizeof(tr_msg_struct_t)); //USB_PRINTF("TR 0x%x added target frame is %d\n", msg->pipe_tr, tr->frame); break; } tr++; } return (i < USBCFG_HOST_KHCI_MAX_INT_TR) ? i : -1; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_rm_int_tr * Returned Value : 0 successful * Comments : * Remove interrupt transaction from queue *END*-----------------------------------------------------------------*/ static int32_t _usb_khci_rm_tr(usb_khci_host_state_struct_t* usb_host_ptr, tr_msg_struct_t *msg, que_type_t type) { int32_t i = 0; tr_int_que_itm_struct_t* tr = NULL; if (type == TYPE_INT) { tr= usb_host_ptr->tr_int_que; } else if (type == TYPE_NAK) { tr= usb_host_ptr->tr_nak_que; } // find record for (i = 0; i < USBCFG_HOST_KHCI_MAX_INT_TR; i++) { if ((tr->msg.pipe_desc == msg->pipe_desc) && (tr->msg.pipe_tr == msg->pipe_tr)) { //OS_Mem_zero(tr, sizeof(tr_int_que_itm_struct_t)); tr->msg.type = TR_MSG_UNKNOWN; //USB_PRINTF("TR 0x%x removed\n", tr->msg.pipe_tr); return 0; } tr++; } return -1; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_get_hot_int_tr * Returned Value : 0 successful * Comments : * Make a message copy for transaction which need evaluation *END*-----------------------------------------------------------------*/ static int32_t _usb_khci_get_hot_tr(usb_khci_host_state_struct_t* usb_host_ptr, tr_msg_struct_t *msg, que_type_t type) { int32_t i, res = -1; //register TIME_STRUCT hot_time; uint32_t frame_number = 0xFFFFFFFF; tr_int_que_itm_struct_t* tr = NULL; tr_int_que_itm_struct_t* hot_tr = NULL; if(type == TYPE_INT) { tr= usb_host_ptr->tr_int_que; } else if(type == TYPE_NAK) { tr= usb_host_ptr->tr_nak_que; } //TIME_STRUCT tm; for (i = 0; i < USBCFG_HOST_KHCI_MAX_INT_TR; i++) { if (tr->msg.type != TR_MSG_UNKNOWN) { if (tr->frame < frame_number) { hot_tr = tr; frame_number = hot_tr->frame; } } tr++; } if (hot_tr) { /* test if hottest transaction was the last one with timeout - if yes, don't allow to block USB transfers with this interrupt */ if (usb_host_ptr->last_to_pipe == hot_tr->msg.pipe_desc) { usb_host_ptr->last_to_pipe = NULL; //it is allowed to perform this interrupt next time, but not now return res; } if (usb_host_ptr->device_attach_phy > 0) { frame_number = _usb_khci_get_total_frame_count(usb_host_ptr); } //USB_PRINTF("%d, %d\n", frame_number, hot_tr->frame); if (frame_number >= hot_tr->frame) { OS_Mem_copy(&hot_tr->msg, msg, sizeof(tr_msg_struct_t)); res = 0; hot_tr->frame += hot_tr->period; } } return res; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_attach * Returned Value : none * Comments : * KHCI attach event *END*-----------------------------------------------------------------*/ static void _usb_khci_attach(usb_khci_host_state_struct_t* usb_host_ptr) { uint8_t speed; uint8_t temp; usb_device_instance_handle dev_handle; uint8_t index = 0; usb_hal_khci_set_device_addr(usb_host_ptr->usbRegBase, 0); #ifdef USBCFG_OTG OS_Time_delay(50); #else OS_Time_delay(150); #endif usb_hal_khci_disable_low_speed_support(usb_host_ptr->usbRegBase); do { temp = usb_hal_khci_get_line_status(usb_host_ptr->usbRegBase); OS_Time_delay(5); speed = usb_hal_khci_get_line_status(usb_host_ptr->usbRegBase); index++; } while ((temp != speed) && (index < USB_KHCI_MAX_SPEED_DETECTION_COUNT)); if (temp != speed) { #if _DEBUG USB_PRINTF("speed not match!\n"); #endif return; } if (speed == USB_SPEED_FULL) { usb_hal_khci_disable_low_speed_support(usb_host_ptr->usbRegBase); } else if (speed == USB_SPEED_LOW) { usb_hal_khci_enable_communicate_low_speed_device(usb_host_ptr->usbRegBase); usb_hal_khci_enable_low_speed_support(usb_host_ptr->usbRegBase); } usb_hal_khci_clr_all_interrupts(usb_host_ptr->usbRegBase); // clean each int flags usb_hal_khci_disable_interrupts(usb_host_ptr->usbRegBase, (INTR_TOKDNE | INTR_USBRST)); // bus reset usb_hal_khci_start_bus_reset(usb_host_ptr->usbRegBase); OS_Time_delay(30);//wait for 30 milliseconds (2.5 is minimum for reset, 10 recommended) usb_hal_khci_stop_bus_reset(usb_host_ptr->usbRegBase); // Delay after reset was provided to be sure about speed- HS / FS. Since the KHCI does not run HS, the delay is redundant. // Some kinetis devices cannot recover after the delay, so it is better not to have delayed speed detection and SOF packet generation // This is potential risk as any high priority task will get CPU now, the host will not begin the enumeration process. //OS_Time_delay(10); // enable SOF sending usb_hal_khci_enable_sof(usb_host_ptr->usbRegBase); #ifdef USBCFG_OTG OS_Time_delay(30); #else OS_Time_delay(100); #endif usb_hal_khci_enable_interrupts(usb_host_ptr->usbRegBase, (INTR_TOKDNE | INTR_USBRST)); usb_host_ptr->device_attached ++; usb_host_dev_mng_attach((void*)usb_host_ptr->upper_layer_handle, 0, speed, 0, 0, 1, &dev_handle); } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_reset * Returned Value : none * Comments : * KHCI reset event *END*-----------------------------------------------------------------*/ static void _usb_khci_reset(usb_khci_host_state_struct_t* usb_host_ptr) { volatile uint32_t i = 0xf; // clear attach flag usb_hal_khci_clr_interrupt(usb_host_ptr->usbRegBase, INTR_ATTACH); while(i--) { ; } /* Test the presence of USB device */ if( usb_hal_khci_get_interrupt_status(usb_host_ptr->usbRegBase)&INTR_ATTACH) { /* device attached, so really normal reset was performed */ usb_hal_khci_enable_interrupts(usb_host_ptr->usbRegBase, INTR_USBRST); usb_hal_khci_set_device_addr(usb_host_ptr->usbRegBase,0); usb_hal_khci_endpoint_on_hub(usb_host_ptr->usbRegBase, 0); } else { /* device was detached, the reset event is false- never mind, notify about detach */ //USB_PRINTF("d\n"); usb_hal_khci_enable_interrupts(usb_host_ptr->usbRegBase, INTR_ATTACH); OS_Event_set(usb_host_ptr->khci_event_ptr, KHCI_EVENT_DETACH); } } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_detach * Returned Value : none * Comments : * KHCI detach event *END*-----------------------------------------------------------------*/ static void _usb_khci_detach(usb_khci_host_state_struct_t* usb_host_ptr) { if (usb_host_ptr->device_attached > 0) { usb_host_ptr->device_attached--; } else { return; } usb_host_dev_mng_detach((void*)usb_host_ptr->upper_layer_handle, 0, 0); usb_hal_khci_set_host_mode(usb_host_ptr->usbRegBase); /* This will clear all pending interrupts... In fact, there shouldn't be any ** after detaching a device. */ // usb_hal_set_oddrst(usb_host_ptr->usbRegBase); usb_hal_khci_clr_all_interrupts(usb_host_ptr->usbRegBase); // usb_host_ptr->tx_bd = 1; // usb_host_ptr->rx_bd = 1; /* Now, enable only USB interrupt attach for host mode */ } void _usb_khci_handle_iso_msg(usb_khci_host_state_struct_t* usb_host_ptr, tr_msg_struct_t msg) { uint32_t remain = 0; uint32_t required = 0; int32_t res = 0; uint8_t *buf; switch (msg.type) { case TR_MSG_RECV: buf = msg.pipe_tr->rx_buffer; required = remain = msg.pipe_tr->rx_length; KHCI_DEBUG_LOG('p', msg.type, msg.pipe_desc->endpoint_number, required) do { _usb_khci_atom_noblocking_tr(usb_host_ptr, TR_IN, msg.pipe_desc, buf, remain); OS_Event_wait(usb_host_ptr->khci_event_ptr, KHCI_EVENT_TOK_DONE, FALSE, USBCFG_HOST_KHCI_WAIT_TICK); res = _usb_khci_tr_done(usb_host_ptr, msg); OS_Event_clear(usb_host_ptr->khci_event_ptr, KHCI_EVENT_TOK_DONE); if (res >= 0) { buf += res; remain -=res; } if ((res < 0) || (remain == 0) || (res < msg.pipe_desc->max_packet_size)) { if (res >= 0) { res = remain; } break; } }while (1); break; case TR_MSG_SEND: buf = msg.pipe_tr->tx_buffer; required = remain = msg.pipe_tr->tx_length; KHCI_DEBUG_LOG('p', msg.type, msg.pipe_desc->endpoint_number, required) do { _usb_khci_atom_noblocking_tr(usb_host_ptr, TR_OUT, msg.pipe_desc, buf, remain); OS_Event_wait(usb_host_ptr->khci_event_ptr, KHCI_EVENT_TOK_DONE, FALSE, USBCFG_HOST_KHCI_WAIT_TICK); res = _usb_khci_tr_done(usb_host_ptr, msg); OS_Event_clear(usb_host_ptr->khci_event_ptr, KHCI_EVENT_TOK_DONE); if (res >= 0) { buf += res; remain -=res; } if ((res < 0) || (remain == 0) || (res < msg.pipe_desc->max_packet_size)) { if (res >= 0) { res = remain; } break; } }while (1); break; default: break; } _usb_khci_process_tr_complete(msg.pipe_desc, msg.pipe_tr, required, remain, res); } #define ISO_TRANSFER_TIMERS 1 uint32_t _usb_process_iso_tr(usb_khci_host_state_struct_t* usb_host_ptr ) { tr_msg_struct_t msg; uint8_t timer = ISO_TRANSFER_TIMERS; uint8_t ret = 0; do { if (OS_MsgQ_Is_Empty(usb_host_ptr->tr_iso_que, (uint32_t *)&msg)) { if ((OS_Event_check_bit(usb_host_ptr->khci_event_ptr, KHCI_EVENT_ISO_MSG))) { OS_Event_clear(usb_host_ptr->khci_event_ptr, KHCI_EVENT_ISO_MSG); } return 0; } _usb_khci_handle_iso_msg( usb_host_ptr, msg); ret = 1; }while (timer--); return ret; } static tr_msg_struct_t curr_msg; static tr_msg_struct_t done_msg; static volatile uint32_t tr_state = KHCI_TR_GET_MSG; #if USBCFG_KHCI_4BYTE_ALIGN_FIX typedef struct { uint32_t rx_len; uint8_t *rx_buf; uint8_t *rx_buf_orig; bool is_dma_align; }khci_xfer_sts_t; static khci_xfer_sts_t s_xfer_sts = {0, NULL, NULL, TRUE}; #endif static uint32_t deattached = 0; static void _usb_khci_task(void* dev_inst_ptr) { volatile ptr_usb_khci_host_state_struct_t usb_host_ptr = (usb_khci_host_state_struct_t*) dev_inst_ptr; static uint32_t remain = 0; static uint32_t required = 0; static int32_t res; uint8_t *buf; if (usb_host_ptr->device_attached) { if (tr_state == KHCI_TR_GET_MSG) { curr_msg.type = TR_MSG_UNKNOWN; #if (USB_NONBLOCKING_MODE == 0) OS_Event_wait(usb_host_ptr->khci_event_ptr, KHCI_EVENT_NAK_MSG|KHCI_EVENT_MSG|KHCI_EVENT_SOF_TOK, FALSE,5); #else OS_Event_wait(usb_host_ptr->khci_event_ptr, KHCI_EVENT_NAK_MSG|KHCI_EVENT_MSG|KHCI_EVENT_SOF_TOK, FALSE,0); #endif if ((OS_Event_check_bit(usb_host_ptr->khci_event_ptr, KHCI_EVENT_SOF_TOK))) { if ((OS_Event_check_bit(usb_host_ptr->khci_event_ptr, KHCI_EVENT_ISO_MSG))) { _usb_process_iso_tr(usb_host_ptr); } OS_Event_clear(usb_host_ptr->khci_event_ptr, KHCI_EVENT_SOF_TOK); } if (_usb_khci_get_hot_tr(usb_host_ptr, &curr_msg, TYPE_INT) != 0) { if (_usb_khci_get_hot_tr(usb_host_ptr, &curr_msg, TYPE_NAK) != 0) { ; } if ((OS_Event_check_bit(usb_host_ptr->khci_event_ptr, KHCI_EVENT_NAK_MSG))) { OS_Event_clear(usb_host_ptr->khci_event_ptr, KHCI_EVENT_NAK_MSG); } if (curr_msg.type == TR_MSG_UNKNOWN) { if (!OS_MsgQ_Is_Empty(usb_host_ptr->tr_que,&curr_msg)) { if (curr_msg.pipe_desc->pipetype == USB_INTERRUPT_PIPE) { _usb_khci_add_tr(usb_host_ptr, &curr_msg, curr_msg.pipe_desc->interval,TYPE_INT); } } else { if ((OS_Event_check_bit(usb_host_ptr->khci_event_ptr, KHCI_EVENT_MSG))) { OS_Event_clear(usb_host_ptr->khci_event_ptr, KHCI_EVENT_MSG); } } } } if (curr_msg.type != TR_MSG_UNKNOWN) { if (usb_host_ptr->device_attach_phy > 0) { tr_state = KHCI_TR_START_TRANSMIT; } else { OS_Mem_copy(&curr_msg, &done_msg, sizeof(tr_msg_struct_t)); done_msg.retry = 0; res = KHCI_ATOM_TR_RESET; required = 0; tr_state = KHCI_TR_TRANSMIT_DONE; } } remain = 0; } if ((tr_state == KHCI_TR_START_TRANSMIT)) { if ((curr_msg.msg_state == TR_MSG_NAK )) { if((_usb_khci_get_total_frame_count(usb_host_ptr) - curr_msg.frame) > curr_msg.naktimeout ) { res = KHCI_ATOM_TR_BUS_TIMEOUT; tr_state = KHCI_TR_TRANSMIT_DONE; done_msg = curr_msg; //USB_PRINTF("1TR Timeout! %d %d\n", curr_msg.msg_state,curr_msg.naktimeout); return; } } else if ((curr_msg.msg_state == TR_BUS_TIMEOUT )) { if ((_usb_khci_get_total_frame_count(usb_host_ptr) - curr_msg.frame) > TIMEOUT_OTHER ) { res = KHCI_ATOM_TR_BUS_TIMEOUT; tr_state = KHCI_TR_TRANSMIT_DONE; done_msg = curr_msg; // USB_PRINTF("2TR Timeout! %d %d\n", curr_msg.msg_state,curr_msg.naktimeout); return; } } if (curr_msg.type != TR_MSG_UNKNOWN) { switch (curr_msg.type) { case TR_MSG_SETUP: if ((curr_msg.pipe_tr->setup_status == 0)) { _usb_khci_atom_noblocking_tr(usb_host_ptr, TR_CTRL, curr_msg.pipe_desc, (uint8_t *) &curr_msg.pipe_tr->setup_packet, 8); remain = 8; } else if ( curr_msg.pipe_tr->setup_status == 1) { if (curr_msg.pipe_tr->rx_length) { buf = curr_msg.pipe_tr->rx_buffer; required = curr_msg.pipe_tr->rx_length; remain = required - curr_msg.pipe_tr->transfered_length; buf += curr_msg.pipe_tr->transfered_length; KHCI_DEBUG_LOG('p', curr_msg.type, curr_msg.pipe_desc->endpoint_number, required) _usb_khci_atom_noblocking_tr(usb_host_ptr, TR_IN, curr_msg.pipe_desc, buf, remain); } else if (curr_msg.pipe_tr->tx_length) { buf = curr_msg.pipe_tr->tx_buffer; required = curr_msg.pipe_tr->tx_length; remain = required - curr_msg.pipe_tr->transfered_length; buf += curr_msg.pipe_tr->transfered_length; KHCI_DEBUG_LOG('p', curr_msg.type, curr_msg.pipe_desc->endpoint_number, required) _usb_khci_atom_noblocking_tr(usb_host_ptr, TR_OUT, curr_msg.pipe_desc, buf, remain); } else { curr_msg.pipe_desc->nextdata01 = 1; _usb_khci_atom_noblocking_tr(usb_host_ptr, TR_IN, curr_msg.pipe_desc, 0, 0); curr_msg.pipe_tr->setup_status = 3; } } else if( curr_msg.pipe_tr->setup_status == 2) { if (curr_msg.pipe_tr->rx_length) { curr_msg.pipe_desc->nextdata01 = 1; _usb_khci_atom_noblocking_tr(usb_host_ptr, TR_OUT, curr_msg.pipe_desc, 0, 0); } else if (curr_msg.pipe_tr->tx_length) { curr_msg.pipe_desc->nextdata01 = 1; _usb_khci_atom_noblocking_tr(usb_host_ptr, TR_IN, curr_msg.pipe_desc, 0, 0); } else { curr_msg.pipe_desc->nextdata01 = 1; _usb_khci_atom_noblocking_tr(usb_host_ptr, TR_IN, curr_msg.pipe_desc, 0, 0); } } else if ( curr_msg.pipe_tr->setup_status == 3) { curr_msg.pipe_desc->nextdata01 = 1; _usb_khci_atom_noblocking_tr(usb_host_ptr, TR_IN, curr_msg.pipe_desc, 0, 0); } break; case TR_MSG_RECV: buf = curr_msg.pipe_tr->rx_buffer; required = curr_msg.pipe_tr->rx_length; remain = required - curr_msg.pipe_tr->transfered_length; buf += curr_msg.pipe_tr->transfered_length; KHCI_DEBUG_LOG('p', curr_msg.type, curr_msg.pipe_desc->endpoint_number, required) _usb_khci_atom_noblocking_tr(usb_host_ptr, TR_IN, curr_msg.pipe_desc, buf, remain); break; case TR_MSG_SEND: buf = curr_msg.pipe_tr->tx_buffer; required = curr_msg.pipe_tr->tx_length; remain = required - curr_msg.pipe_tr->transfered_length; buf += curr_msg.pipe_tr->transfered_length; _usb_khci_atom_noblocking_tr(usb_host_ptr, TR_OUT, curr_msg.pipe_desc, buf, remain); break; default: break; } } tr_state = KHCI_TR_TRANSMITING; } else if (( tr_state == KHCI_TR_TRANSMITING)) { if (curr_msg.pipe_desc->pipetype != USB_INTERRUPT_PIPE) { if ((_usb_khci_get_total_frame_count(usb_host_ptr) - curr_msg.frame) > TIMEOUT_OTHER ) { res = KHCI_ATOM_TR_BUS_TIMEOUT; tr_state = KHCI_TR_TRANSMIT_DONE; done_msg = curr_msg; USB_PRINTF("3TR Timeout!\n"); return; } } } else if (tr_state == KHCI_TR_TRANSMIT_DONE) { if (done_msg.pipe_desc->pipetype == USB_INTERRUPT_PIPE) { /* for interrupt pipes, callback only if some data was received or serious error occurred */ if ((required != remain) || ((res != KHCI_ATOM_TR_NAK) )) { _usb_khci_process_tr_complete(done_msg.pipe_desc, done_msg.pipe_tr, required, remain, res); if (curr_msg.msg_state == TR_BUS_TIMEOUT) { _usb_khci_rm_tr(usb_host_ptr, &done_msg, TYPE_NAK); } _usb_khci_rm_tr(usb_host_ptr, &done_msg, TYPE_INT); } } else { if(done_msg.msg_state != TR_MSG_IDLE ) { _usb_khci_rm_tr(usb_host_ptr, &done_msg, TYPE_NAK); if (done_msg.pipe_desc->pipetype == USB_CONTROL_PIPE) { if ((res < 0) && (done_msg.retry)) { tr_state = KHCI_TR_GET_MSG; done_msg.type = TR_MSG_SETUP; done_msg.pipe_tr->setup_status = 0; done_msg.pipe_tr->transfered_length = 0; done_msg.retry --; if(done_msg.pipe_tr->rx_length) { done_msg.naktimeout = TIMEOUT_TOHOST; } else if(done_msg.pipe_tr->tx_length) { done_msg.naktimeout = TIMEOUT_TODEVICE; } else { done_msg.naktimeout = TIMEOUT_NODATA; } done_msg.frame = _usb_khci_get_total_frame_count(usb_host_ptr); done_msg.msg_state = TR_BUS_TIMEOUT; _usb_khci_add_tr(usb_host_ptr, &done_msg, NAK_RETRY_TIME*5,TYPE_NAK); USB_PRINTF("Retry @@\n\r"); return; } } } _usb_khci_process_tr_complete(done_msg.pipe_desc, done_msg.pipe_tr, required, remain, res); } tr_state = KHCI_TR_GET_MSG; if(deattached == 1) { _usb_khci_detach(usb_host_ptr); deattached = 0; } } } else { // wait for event if device is not attached OS_Event_wait(usb_host_ptr->khci_event_ptr, KHCI_EVENT_ATTACH, FALSE, 0); } if (OS_Event_check_bit(usb_host_ptr->khci_event_ptr, KHCI_EVENT_MASK)) { if (OS_Event_check_bit(usb_host_ptr->khci_event_ptr, KHCI_EVENT_ATTACH)) { OS_Event_clear(usb_host_ptr->khci_event_ptr, KHCI_EVENT_ATTACH); usb_host_ptr->device_attach_phy = 1; _usb_khci_init_tr_que(usb_host_ptr); usb_hal_khci_set_oddrst(usb_host_ptr->usbRegBase); usb_hal_khci_set_host_mode(usb_host_ptr->usbRegBase); _usb_khci_attach(usb_host_ptr); tr_state = KHCI_TR_GET_MSG; usb_host_ptr->tx_bd = 0; usb_host_ptr->rx_bd = 0; } if (OS_Event_check_bit(usb_host_ptr->khci_event_ptr, KHCI_EVENT_RESET)) { OS_Event_clear(usb_host_ptr->khci_event_ptr, KHCI_EVENT_RESET | KHCI_EVENT_TOK_DONE); _usb_khci_reset(usb_host_ptr); } if (OS_Event_check_bit(usb_host_ptr->khci_event_ptr, KHCI_EVENT_DETACH)) { OS_Event_clear(usb_host_ptr->khci_event_ptr, KHCI_EVENT_DETACH); usb_host_ptr->device_attach_phy = 0; if (KHCI_TR_TRANSMITING == tr_state) { tr_state = KHCI_TR_TRANSMIT_DONE; done_msg = curr_msg; deattached = 1; } else { _usb_khci_detach(usb_host_ptr); } OS_Event_clear(usb_host_ptr->khci_event_ptr, KHCI_EVENT_MSG); usb_hal_khci_clr_all_interrupts(usb_host_ptr->usbRegBase); /* Enable week pull-downs, useful for detecting detach (effectively bus discharge) */ usb_hal_khci_enable_pull_down(usb_host_ptr->usbRegBase); /* Remove suspend state */ usb_hal_khci_clr_suspend(usb_host_ptr->usbRegBase); usb_hal_khci_set_oddrst(usb_host_ptr->usbRegBase); usb_hal_khci_set_host_mode(usb_host_ptr->usbRegBase); usb_host_ptr->tx_bd = 0; usb_host_ptr->rx_bd = 0; } if (OS_Event_check_bit(usb_host_ptr->khci_event_ptr, KHCI_EVENT_TOK_DONE)) { OS_Event_clear(usb_host_ptr->khci_event_ptr, KHCI_EVENT_TOK_DONE); res = _usb_khci_tr_done(usb_host_ptr, curr_msg); //_usb_process_iso_tr(usb_host_ptr); if (res> 0) { if (curr_msg.type != TR_MSG_UNKNOWN) { switch (curr_msg.type) { case TR_MSG_SETUP: if (( curr_msg.pipe_tr->setup_status == 2)||( curr_msg.pipe_tr->setup_status == 3)) { tr_state = KHCI_TR_TRANSMIT_DONE; done_msg = curr_msg; curr_msg.pipe_tr->setup_status = 0; } else { tr_state = KHCI_TR_START_TRANSMIT; remain -= res; if(curr_msg.pipe_tr->setup_status ==1) { curr_msg.pipe_tr->transfered_length +=res; if ((remain <= 0)|| (res < curr_msg.pipe_desc->max_packet_size)) { curr_msg.pipe_tr->setup_status ++; } } else { curr_msg.pipe_tr->setup_status ++; } } break; case TR_MSG_RECV: remain -= res; curr_msg.pipe_tr->transfered_length +=res; if ((remain == 0)|| (res < curr_msg.pipe_desc->max_packet_size)) { tr_state = KHCI_TR_TRANSMIT_DONE; done_msg = curr_msg; break; } else { tr_state = KHCI_TR_START_TRANSMIT; } break; case TR_MSG_SEND: remain -= res; curr_msg.pipe_tr->transfered_length +=res; if ((remain == 0)|| (res < curr_msg.pipe_desc->max_packet_size)) { tr_state = KHCI_TR_TRANSMIT_DONE; done_msg = curr_msg; break; } else { tr_state = KHCI_TR_START_TRANSMIT; } break; default: break; } } } else { if ((res == KHCI_ATOM_TR_NAK) && (curr_msg.pipe_desc->pipetype != USB_INTERRUPT_PIPE)) { if (usb_host_dev_mng_get_attach_state(curr_msg.pipe_desc->dev_instance)) { if (curr_msg.msg_state == TR_MSG_IDLE) { curr_msg.msg_state = TR_MSG_NAK; _usb_khci_add_tr(usb_host_ptr, &curr_msg, 0, TYPE_NAK); } OS_Event_set(usb_host_ptr->khci_event_ptr, KHCI_EVENT_NAK_MSG); tr_state = KHCI_TR_GET_MSG; } else { tr_state = KHCI_TR_TRANSMIT_DONE; done_msg = curr_msg; } } else if ((res == KHCI_ATOM_TR_BUS_TIMEOUT)&& (curr_msg.pipe_desc->pipetype != USB_INTERRUPT_PIPE)) { if (curr_msg.retry == 0) { tr_state = KHCI_TR_TRANSMIT_DONE; done_msg = curr_msg; return; } if (usb_host_dev_mng_get_attach_state(curr_msg.pipe_desc->dev_instance)) { curr_msg.retry --; if (curr_msg.msg_state == TR_MSG_IDLE) { curr_msg.msg_state = TR_BUS_TIMEOUT; _usb_khci_add_tr(usb_host_ptr, &curr_msg, NAK_RETRY_TIME*5,TYPE_NAK); } tr_state = KHCI_TR_GET_MSG; } else { tr_state = KHCI_TR_TRANSMIT_DONE; done_msg = curr_msg; } } else { tr_state = KHCI_TR_TRANSMIT_DONE; done_msg = curr_msg; } } } } } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_task_stun * Returned Value : none * Comments : * KHCI task *END*-----------------------------------------------------------------*/ #if ((OS_ADAPTER_ACTIVE_OS == OS_ADAPTER_SDK) && (USE_RTOS)) static void _usb_khci_task_stun(void* dev_inst_ptr) { while (1) { _usb_khci_task(dev_inst_ptr); } } #endif /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_task_create * Returned Value : error or USB_OK * Comments : * Create KHCI task *END*-----------------------------------------------------------------*/ uint32_t task_id; static usb_status _usb_khci_task_create(usb_host_handle handle) { //usb_status status; //task_id = _task_create_blocked(0, 0, (uint32_t)&task_template); task_id = OS_Task_create(USB_KHCI_TASK_ADDRESS, (void*)handle, (uint32_t)USBCFG_HOST_KHCI_TASK_PRIORITY, USB_KHCI_TASK_STACKSIZE, USB_KHCI_TASK_NAME, NULL); if (task_id == (uint32_t)OS_TASK_ERROR) { return USBERR_ERROR; } //_task_ready(_task_get_td(task_id)); //OS_Task_resume(task_id); return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_khci_preinit * Returned Value : error or USB_OK * Comments : * Allocate the structures for KHCI *END*-----------------------------------------------------------------*/ usb_status usb_khci_preinit(usb_host_handle upper_layer_handle, usb_host_handle *handle) { usb_khci_host_state_struct_t* usb_host_ptr = (usb_khci_host_state_struct_t*) OS_Mem_alloc_zero(sizeof(usb_khci_host_state_struct_t)); pipe_struct_t* p; pipe_struct_t* pp; int32_t i; if (NULL != usb_host_ptr) { usb_host_ptr->device_attach_phy = 0; /* Allocate the USB Host Pipe Descriptors */ usb_host_ptr->pipe_descriptor_base_ptr = (pipe_struct_t*)OS_Mem_alloc_zero(sizeof(pipe_struct_t) * USBCFG_HOST_MAX_PIPES); if (usb_host_ptr->pipe_descriptor_base_ptr == NULL) { OS_Mem_free(usb_host_ptr); return USBERR_ALLOC; } p = (pipe_struct_t*) usb_host_ptr->pipe_descriptor_base_ptr; pp = NULL; for (i = 0; i < USBCFG_HOST_MAX_PIPES; i++) { if (pp != NULL) { pp->next = (pipe_struct_t*) p; } pp = p; p++; } usb_host_ptr->upper_layer_handle = upper_layer_handle; //usb_host_ptr->G.PIPE_SIZE = sizeof(KHCI_PIPE_STRUCT); //usb_host_ptr->G.TR_SIZE = sizeof(KHCI_TR_STRUCT); *handle = (usb_host_handle) usb_host_ptr; #if USBCFG_KHCI_4BYTE_ALIGN_FIX if (NULL == (_usb_khci_swap_buf_ptr = (uint8_t *)OS_Mem_alloc_uncached_zero(USBCFG_HOST_KHCI_SWAP_BUF_MAX + 4))) { #ifdef _HOST_DEBUG_ DEBUG_LOG_TRACE("_usb_khci_swap_buf_ptr- memory allocation failed"); #endif return USB_log_error(__FILE__,__LINE__,USBERR_ALLOC); } #endif return USB_OK; } else { *handle = NULL; return USBERR_ALLOC; } } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_khci_init * Returned Value : error or USB_OK * Comments : * Initialize the kirin HCI controller *END*-----------------------------------------------------------------*/ usb_status usb_khci_init(uint8_t controller_id, usb_host_handle handle) { usb_khci_host_state_struct_t* usb_host_ptr = (usb_khci_host_state_struct_t*)handle; usb_status status = USB_OK; usb_host_ptr->khci_event_ptr = OS_Event_create(0); if (usb_host_ptr->khci_event_ptr == NULL) { #if _DEBUG USB_PRINTF(" memalloc failed in usb_khci_init\n"); #endif return USBERR_ALLOC; } /* Endif */ /* The _lwmsgq_init accepts the size of tr_msg_struct_t as a multiplier of sizeof(_mqx_max_type) */ usb_host_ptr->tr_que = (os_msgq_handle)OS_MsgQ_create(USBCFG_HOST_KHCI_TR_QUE_MSG_CNT, MSG_SIZE_IN_MAX_TYPE); if (usb_host_ptr->tr_que == NULL) { return USBERR_ALLOC; } usb_host_ptr->tr_iso_que = (os_msgq_handle)OS_MsgQ_create(USBCFG_HOST_KHCI_TR_QUE_MSG_CNT, MSG_SIZE_IN_MAX_TYPE); if (usb_host_ptr->tr_iso_que == NULL) { return USBERR_ALLOC; } usb_host_ptr->tr_que_bak= (os_msgq_handle)OS_MsgQ_create(USBCFG_HOST_KHCI_TR_QUE_MSG_CNT, MSG_SIZE_IN_MAX_TYPE); if (usb_host_ptr->tr_que_bak == NULL) { return USBERR_ALLOC; } _usb_khci_init_tr_que(usb_host_ptr); usb_host_ptr->controller_id = controller_id; //usb_ptr = usb_host_ptr->DEV_PTR = soc_get_usb_base_address(controller_id); usb_host_ptr->vector_number = soc_get_usb_vector_number(controller_id); //usb_host_ptr->vector_number = INT_USB0; usb_host_ptr->usbRegBase = soc_get_usb_base_address(controller_id); _usb_khci_task_create(usb_host_ptr); usb_host_global_handler = usb_host_ptr; /* set internal register pull down */ usb_hal_khci_set_weak_pulldown(usb_host_ptr->usbRegBase); /* Reset USB CTRL register */ usb_hal_khci_reset_control_register(usb_host_ptr->usbRegBase); /* setup interrupt */ OS_intr_init((IRQn_Type)soc_get_usb_vector_number(controller_id), soc_get_usb_host_int_level(controller_id), 0, TRUE); #ifndef USBCFG_OTG /* install isr */ OS_install_isr(usb_host_ptr->vector_number, _usb_khci_isr, (void*)usb_host_ptr); #endif usb_hal_khci_clr_all_interrupts(usb_host_ptr->usbRegBase); /* Enable week pull-downs, useful for detecting detach (effectively bus discharge) */ usb_hal_khci_enable_pull_down(usb_host_ptr->usbRegBase); /* Remove suspend state */ usb_hal_khci_clr_suspend(usb_host_ptr->usbRegBase); usb_hal_khci_set_oddrst(usb_host_ptr->usbRegBase); usb_hal_khci_set_buffer_descriptor_table_addr(usb_host_ptr->usbRegBase, (uint32_t)BDT_BASE); /* Set SOF threshold */ //usb_ptr->SOFTHLD = 1; usb_hal_khci_set_sof_theshold(usb_host_ptr->usbRegBase, 255); usb_hal_khci_set_host_mode(usb_host_ptr->usbRegBase); /* Following is for OTG control instead of internal bus control */ // usb_ptr->OTGCTL = USB_OTGCTL_DMLOW_MASK | USB_OTGCTL_DPLOW_MASK | USB_OTGCTL_OTGEN_MASK; /* Wait for attach interrupt */ usb_hal_khci_enable_interrupts(usb_host_ptr->usbRegBase, INTR_ATTACH| INTR_SOFTOK); #if defined (FSL_FEATURE_USB_KHCI_DYNAMIC_SOF_THRESHOLD_COMPARE_ENABLED) && (FSL_FEATURE_USB_KHCI_DYNAMIC_SOF_THRESHOLD_COMPARE_ENABLED == 1) usb_hal_khci_enable_dynamic_sof_threshold(usb_host_ptr->usbRegBase); #endif return status; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_khci_shutdown - NOT IMPLEMENT YET * Returned Value : error or USB_OK * Comments : * The function to shutdown the host *END*-----------------------------------------------------------------*/ usb_status usb_khci_shutdown ( usb_host_handle handle ) { usb_khci_host_state_struct_t* usb_host_ptr = (usb_khci_host_state_struct_t*)handle; if (task_id != (uint32_t)OS_TASK_ERROR) { OS_Task_delete(task_id); } usb_hal_khci_disable_interrupts(usb_host_ptr->usbRegBase,0xFF); usb_hal_khci_set_device_addr(usb_host_ptr->usbRegBase,0); usb_hal_khci_clear_control_register(usb_host_ptr->usbRegBase); usb_hal_khci_enable_pull_down(usb_host_ptr->usbRegBase); usb_hal_khci_set_suspend(usb_host_ptr->usbRegBase); usb_hal_khci_disable_low_speed_support(usb_host_ptr->usbRegBase); if (NULL != usb_host_ptr->pipe_descriptor_base_ptr) { OS_Mem_free(usb_host_ptr->pipe_descriptor_base_ptr); } if (NULL != usb_host_ptr->khci_event_ptr) { OS_Event_destroy(usb_host_ptr->khci_event_ptr); } if (NULL != usb_host_ptr->tr_que) { OS_MsgQ_destroy(usb_host_ptr->tr_que); } if (NULL != usb_host_ptr->tr_iso_que) { OS_MsgQ_destroy(usb_host_ptr->tr_iso_que); } if (NULL != usb_host_ptr->tr_que_bak) { OS_MsgQ_destroy(usb_host_ptr->tr_que_bak); } usb_host_global_handler = NULL; OS_Mem_free(usb_host_ptr); #if USBCFG_KHCI_4BYTE_ALIGN_FIX if (NULL != _usb_khci_swap_buf_ptr) { OS_Mem_free(_usb_khci_swap_buf_ptr); } #endif return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_khci_open_pipe * Returned Value : error or USB_OK * Comments : * The function to open a pipe *END*-----------------------------------------------------------------*/ usb_status usb_khci_open_pipe ( usb_host_handle handle, /* [OUT] Handle of opened pipe */ usb_pipe_handle * pipe_handle_ptr, pipe_init_struct_t* pipe_init_ptr ) { usb_khci_host_state_struct_t* usb_host_ptr = (usb_khci_host_state_struct_t*) handle; pipe_struct_t* pipe_ptr; #ifdef _HOST_DEBUG_ DEBUG_LOG_TRACE("usb_khci_open_pipe"); #endif OS_Lock(); for (pipe_ptr = usb_host_ptr->pipe_descriptor_base_ptr; pipe_ptr != NULL; pipe_ptr = pipe_ptr->next) { if (!pipe_ptr->open) { pipe_ptr->open = (uint8_t)TRUE; break; } } OS_Unlock(); if (pipe_ptr == NULL) { #ifdef _HOST_DEBUG_ DEBUG_LOG_TRACE("usb_khci_open_pipe failed"); #endif return USB_log_error(__FILE__,__LINE__,USBERR_OPEN_PIPE_FAILED); } pipe_ptr->endpoint_number = pipe_init_ptr->endpoint_number; pipe_ptr->direction = pipe_init_ptr->direction; pipe_ptr->pipetype = pipe_init_ptr->pipetype; pipe_ptr->max_packet_size = pipe_init_ptr->max_packet_size & PACKET_SIZE_MASK; pipe_ptr->flags = pipe_init_ptr->flags; pipe_ptr->nak_count = pipe_init_ptr->nak_count; pipe_ptr->nextdata01 = 0; pipe_ptr->tr_list_ptr = NULL; pipe_ptr->dev_instance = pipe_init_ptr->dev_instance; if (pipe_ptr->pipetype == USB_ISOCHRONOUS_PIPE) { pipe_ptr->interval = 1 << (pipe_init_ptr->interval - 1); } else { pipe_ptr->interval = pipe_init_ptr->interval; } *pipe_handle_ptr = pipe_ptr; return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_khci_close_pipe * Returned Value : error or USB_OK * Comments : * The function to open a pipe *END*-----------------------------------------------------------------*/ usb_status usb_khci_close_pipe ( usb_host_handle handle, /* [in] Handle of opened pipe */ usb_pipe_handle pipe_handle ) { usb_khci_host_state_struct_t* usb_host_ptr = (usb_khci_host_state_struct_t*) handle; pipe_struct_t* pipe_ptr = (pipe_struct_t*)pipe_handle; uint8_t matched = (uint8_t)FALSE; #ifdef _HOST_DEBUG_ DEBUG_LOG_TRACE("usb_khci_close_pipe"); #endif OS_Lock(); if ((pipe_ptr != NULL) && (pipe_ptr->open == (uint8_t)TRUE)) { for (pipe_ptr = usb_host_ptr->pipe_descriptor_base_ptr; pipe_ptr != NULL; pipe_ptr = pipe_ptr->next) { if ((pipe_ptr->open) && (pipe_ptr == pipe_handle)) { matched = (uint8_t)TRUE; break; } } if (matched) { pipe_ptr = (pipe_struct_t*)pipe_handle; pipe_ptr->open = (uint8_t)FALSE; pipe_ptr->dev_instance = NULL; pipe_ptr->endpoint_number = 0; pipe_ptr->direction = 0; pipe_ptr->pipetype = 0; pipe_ptr->max_packet_size = 0; pipe_ptr->interval = 0; pipe_ptr->flags = 0; pipe_ptr->nak_count = 0; pipe_ptr->nextdata01 = 0; pipe_ptr->tr_list_ptr = NULL; } else { USB_PRINTF("usb_khci_close_pipe can't find target pipe\n"); } } else { USB_PRINTF("usb_khci_close_pipe invalid pipe \n"); } OS_Unlock(); return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_khci_send * Returned Value : error or USB_OK * Comments : * The function to send data *END*-----------------------------------------------------------------*/ usb_status usb_khci_send(usb_host_handle handle, pipe_struct_t* pipe_ptr, tr_struct_t* tr_ptr) { usb_status status = USB_OK; usb_khci_host_state_struct_t* usb_host_ptr = (usb_khci_host_state_struct_t*) handle; tr_msg_struct_t msg; msg.type = TR_MSG_SEND; msg.msg_state = TR_MSG_IDLE; msg.pipe_desc = pipe_ptr; msg.pipe_tr = tr_ptr; msg.pipe_tr->transfered_length = 0; if (pipe_ptr->nak_count == 0) { msg.naktimeout = TIMEOUT_DEFAULT; } else { msg.naktimeout = pipe_ptr->nak_count *NAK_RETRY_TIME; } msg.frame = _usb_khci_get_total_frame_count(usb_host_ptr); msg.retry = RETRY_TIME; KHCI_DEBUG_LOG('i', msg.type, msg.pipe_desc->endpoint_number, msg.pipe_tr->tx_length) if (pipe_ptr->pipetype ==USB_ISOCHRONOUS_PIPE ) { if (0 != OS_MsgQ_send(usb_host_ptr->tr_iso_que, (void *)&msg, 0)) { status = USBERR_TR_FAILED; } OS_Event_set(usb_host_ptr->khci_event_ptr, KHCI_EVENT_ISO_MSG); } else { if (0 != OS_MsgQ_send(usb_host_ptr->tr_que, (void *)&msg, 0)) { status = USBERR_TR_FAILED; } OS_Event_set(usb_host_ptr->khci_event_ptr, KHCI_EVENT_MSG); } return status; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_khci_send_setup * Returned Value : error or USB_OK * Comments : * The function to send setup data *END*-----------------------------------------------------------------*/ usb_status usb_khci_send_setup(usb_host_handle handle, pipe_struct_t* pipe_ptr, tr_struct_t* tr_ptr) { usb_status status = USB_OK; usb_khci_host_state_struct_t* usb_host_ptr = (usb_khci_host_state_struct_t*) handle; tr_msg_struct_t msg; #if USBCFG_KHCI_4BYTE_ALIGN_FIX if ((tr_ptr->rx_length & USB_DMA_ALIGN_MASK) || ((uint32_t)tr_ptr->rx_buffer & USB_DMA_ALIGN_MASK)) { if (_usb_khci_swap_buf_ptr == NULL) { return USBERR_LACK_OF_SWAP_BUFFER; } if (pipe_ptr->max_packet_size > USBCFG_HOST_KHCI_SWAP_BUF_MAX) { return USBERR_LEAK_OF_SWAP_BUFFER; } } #endif msg.type = TR_MSG_SETUP; msg.msg_state = TR_MSG_IDLE; msg.pipe_desc = pipe_ptr; msg.pipe_tr = tr_ptr; msg.pipe_tr->setup_status = 0; msg.pipe_tr->transfered_length = 0; msg.retry = RETRY_TIME; if (msg.pipe_tr->rx_length) { msg.naktimeout = TIMEOUT_TOHOST; } else if (msg.pipe_tr->tx_length) { msg.naktimeout = TIMEOUT_TODEVICE; } else { msg.naktimeout = TIMEOUT_NODATA; } msg.frame = _usb_khci_get_total_frame_count(usb_host_ptr); if (msg.pipe_tr->rx_length) { KHCI_DEBUG_LOG('i', msg.type, msg.pipe_desc->endpoint_number, msg.pipe_tr->rx_length) } else { KHCI_DEBUG_LOG('i', msg.type, msg.pipe_desc->endpoint_number, msg.pipe_tr->tx_length) } if(0 != OS_MsgQ_send(usb_host_ptr->tr_que, (void *)&msg, 0)) { status = USBERR_TR_FAILED; } OS_Event_set(usb_host_ptr->khci_event_ptr, KHCI_EVENT_MSG); return status; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_khci_recv * Returned Value : error or USB_OK * Comments : * The function to receive data *END*-----------------------------------------------------------------*/ usb_status usb_khci_recv(usb_host_handle handle, pipe_struct_t* pipe_ptr, tr_struct_t* tr_ptr) { usb_status status = USB_OK; usb_khci_host_state_struct_t* usb_host_ptr = (usb_khci_host_state_struct_t*) handle; tr_msg_struct_t msg; #if USBCFG_KHCI_4BYTE_ALIGN_FIX if ((tr_ptr->rx_length & USB_DMA_ALIGN_MASK) || ((uint32_t)tr_ptr->rx_buffer & USB_DMA_ALIGN_MASK)) { if (_usb_khci_swap_buf_ptr == NULL) { return USBERR_LACK_OF_SWAP_BUFFER; } if (pipe_ptr->max_packet_size > USBCFG_HOST_KHCI_SWAP_BUF_MAX) { return USBERR_LEAK_OF_SWAP_BUFFER; } } #endif msg.type = TR_MSG_RECV; msg.msg_state = TR_MSG_IDLE; msg.pipe_desc = pipe_ptr; msg.pipe_tr = tr_ptr; msg.pipe_tr->transfered_length = 0; if (pipe_ptr->nak_count == 0) { msg.naktimeout = TIMEOUT_DEFAULT; } else { msg.naktimeout = pipe_ptr->nak_count *NAK_RETRY_TIME; } msg.retry = RETRY_TIME; msg.frame = _usb_khci_get_total_frame_count(usb_host_ptr); KHCI_DEBUG_LOG('i', msg.type, msg.pipe_desc->endpoint_number, msg.pipe_tr->rx_length) if (pipe_ptr->pipetype ==USB_ISOCHRONOUS_PIPE ) { if (0 != OS_MsgQ_send(usb_host_ptr->tr_iso_que, (void *)&msg, 0)) { status = USBERR_TR_FAILED; } OS_Event_set(usb_host_ptr->khci_event_ptr, KHCI_EVENT_ISO_MSG); } else { if (0 != OS_MsgQ_send(usb_host_ptr->tr_que, (void *)&msg, 0)) { status = USBERR_TR_FAILED; } OS_Event_set(usb_host_ptr->khci_event_ptr, KHCI_EVENT_MSG); } return status; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_khci_cancel * Returned Value : error or USB_OK * Comments : * The function to cancel the transfer *END*-----------------------------------------------------------------*/ usb_status usb_khci_cancel_pipe(usb_host_handle handle, pipe_struct_t* pipe_ptr, tr_struct_t* tr_ptr) { usb_khci_host_state_struct_t* usb_host_ptr = (usb_khci_host_state_struct_t*) handle; tr_msg_struct_t msg; uint32_t required = 0; uint32_t i; tr_int_que_itm_struct_t* tr = usb_host_ptr->tr_int_que; tr_struct_t* tr_temp; while (OS_MsgQ_recv(usb_host_ptr->tr_iso_que, (void *) &msg, 0, 0) == 0) { if ((msg.type != TR_MSG_UNKNOWN) && (pipe_ptr == (pipe_struct_t*)(msg.pipe_desc))) { tr_temp = (tr_struct_t*)msg.pipe_tr; if(msg.type ==TR_MSG_RECV ) { required = curr_msg.pipe_tr->rx_length; } else if (msg.type ==TR_MSG_SEND ) { required = curr_msg.pipe_tr->tx_length; } _usb_khci_process_tr_complete(msg.pipe_desc, msg.pipe_tr, required, 0, required); /* got a valid msg */ if (tr_temp->callback != NULL) { tr_temp->callback((void*)tr_temp, tr_temp->callback_param, NULL, 0, USBERR_TR_CANCEL); } } else { /* this one should be put into the tr_que_bak and put back to tr_que later */ if(OS_MSGQ_OK != OS_MsgQ_send(usb_host_ptr->tr_que_bak, (void *)&msg, 0)) { USB_PRINTF("some error on host tr_que_bak\n"); } } } while (OS_MsgQ_recv(usb_host_ptr->tr_que_bak, (void *) &msg, 0, 0) == 0) { if (OS_MSGQ_OK != OS_MsgQ_send(usb_host_ptr->tr_iso_que, (void *)&msg, 0)) { USB_PRINTF("some error on host tr_que\n"); } } while (OS_MsgQ_recv(usb_host_ptr->tr_que, (void *) &msg, 0, 0) == 0) { if ((msg.type != TR_MSG_UNKNOWN) && (pipe_ptr == (pipe_struct_t*)(msg.pipe_desc))) { tr_temp = (tr_struct_t*)msg.pipe_tr; /* got a valid msg */ if (tr_temp->callback != NULL) { tr_temp->callback((void*)tr_temp, tr_temp->callback_param, NULL, 0, USBERR_TR_CANCEL); } } else { /* this one should be put into the tr_que_bak and put back to tr_que later */ if (OS_MSGQ_OK != OS_MsgQ_send(usb_host_ptr->tr_que_bak, (void *)&msg, 0)) { USB_PRINTF("some error on host tr_que_bak\n"); } } } while (OS_MsgQ_recv(usb_host_ptr->tr_que_bak, (void *) &msg, 0, 0) == 0) { if (OS_MSGQ_OK != OS_MsgQ_send(usb_host_ptr->tr_que, (void *)&msg, 0)) { USB_PRINTF("some error on host tr_que\n"); } } /* we also need to check the interrupt queue */ for (i = 0; i < USBCFG_HOST_KHCI_MAX_INT_TR; i++) { if ((tr->msg.type != TR_MSG_UNKNOWN) && ((pipe_struct_t*)(tr->msg.pipe_desc) == pipe_ptr)) { /* got a valid msg */ tr_temp = (tr_struct_t*)tr->msg.pipe_tr; if (tr_temp->callback != NULL) { tr_temp->callback((void*)tr_temp, tr_temp->callback_param, NULL, 0, USBERR_TR_CANCEL); } tr->msg.type = TR_MSG_UNKNOWN; } tr++; } tr = usb_host_ptr->tr_nak_que; /* we also need to check the interrupt queue */ for (i = 0; i < USBCFG_HOST_KHCI_MAX_INT_TR; i++) { if ((tr->msg.type != TR_MSG_UNKNOWN) && ((pipe_struct_t*)(tr->msg.pipe_desc) == pipe_ptr)) { /* got a valid msg */ tr_temp = (tr_struct_t*)tr->msg.pipe_tr; if (tr_temp->callback != NULL) { tr_temp->callback((void*)tr_temp, tr_temp->callback_param, NULL, 0, USBERR_TR_CANCEL); } tr->msg.type = TR_MSG_UNKNOWN; } tr++; } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_khci_bus_control * Returned Value : error or USB_OK * Comments : * The function for USB bus control *END*-----------------------------------------------------------------*/ usb_status usb_khci_bus_control(usb_host_handle handle, uint8_t bus_control) { ptr_usb_khci_host_state_struct_t usb_host_ptr = (usb_khci_host_state_struct_t*) handle; if(bus_control == 1) { usb_hal_khci_start_bus_reset(usb_host_ptr->usbRegBase); OS_Time_delay(30); //wait for 30 milliseconds (2.5 is minimum for reset, 10 recommended) usb_hal_khci_stop_bus_reset(usb_host_ptr->usbRegBase); usb_hal_khci_set_oddrst(usb_host_ptr->usbRegBase); usb_hal_khci_set_host_mode(usb_host_ptr->usbRegBase); usb_host_ptr->tx_bd = 0; usb_host_ptr->rx_bd = 0; } else if(bus_control == 2) { usb_host_ptr->device_attached = 0; usb_hal_khci_set_host_mode(usb_host_ptr->usbRegBase); usb_hal_khci_clr_all_interrupts(usb_host_ptr->usbRegBase); /* Now, enable only USB interrupt attach for host mode */ usb_hal_khci_enable_interrupts(usb_host_ptr->usbRegBase, INTR_ATTACH); } return USB_OK; } /*FUNCTION*------------------------------------------------------------- * * Function Name : usb_khci_get_frame_number * Returned Value : frame number * Comments : * The function to get frame number *END*-----------------------------------------------------------------*/ uint32_t usb_khci_get_frame_number(usb_host_handle handle) { usb_khci_host_state_struct_t* usb_host_ptr = (usb_khci_host_state_struct_t*) handle; return usb_hal_khci_get_frame_number(usb_host_ptr->usbRegBase); } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_process_tr_complete * Returned Value : none * Comments : * Transaction complete *END*-----------------------------------------------------------------*/ static void _usb_khci_process_tr_complete( pipe_struct_t* pipe_desc_ptr, tr_struct_t* pipe_tr_ptr, uint32_t required, uint32_t remaining, int32_t err ) { uint8_t * buffer_ptr = NULL; uint32_t status = 0; KHCI_DEBUG_LOG('o', TR_MSG_UNKNOWN, pipe_desc_ptr->endpoint_number, err) if (err == KHCI_ATOM_TR_STALL) { status = USBERR_ENDPOINT_STALLED; } else if ((err == KHCI_ATOM_TR_NAK) || (err >= 0)) { status = USB_OK; if (err == KHCI_ATOM_TR_NAK) { status = USBERR_TR_FAILED; } if (pipe_desc_ptr->pipetype == USB_CONTROL_PIPE) { if (pipe_tr_ptr->send_phase) { buffer_ptr = pipe_tr_ptr->tx_buffer; pipe_tr_ptr->send_phase = FALSE; } else { buffer_ptr = pipe_tr_ptr->rx_buffer; } } else { if (pipe_desc_ptr->direction) { buffer_ptr = pipe_tr_ptr->tx_buffer; } else { buffer_ptr = pipe_tr_ptr->rx_buffer; } } } else if (err < 0) { status = USBERR_TR_FAILED; } pipe_tr_ptr->status = USB_STATUS_IDLE; if (pipe_tr_ptr->status == USB_STATUS_IDLE) { /* Transfer done. Call the callback function for this ** transaction if there is one (usually true). */ if (_usb_host_unlink_tr(pipe_desc_ptr, pipe_tr_ptr) != USB_OK) { #ifdef _HOST_DEBUG_ DEBUG_LOG_TRACE("_usb_host_recv_data transfer queue failed"); #endif } if (pipe_tr_ptr->callback != NULL) { /* To ensure that the USB DMA transfer will work on a buffer that is not cached, ** we invalidate buffer cache lines. */ pipe_tr_ptr->callback((void*)pipe_tr_ptr, pipe_tr_ptr->callback_param, buffer_ptr, required - remaining, status); } } } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_tr_done * Returned Value : none * Comments : * Transaction complete *END*-----------------------------------------------------------------*/ static int32_t _usb_khci_tr_done( usb_khci_host_state_struct_t* usb_host_ptr, tr_msg_struct_t msg ) { uint32_t bd; int32_t res = 0; uint32_t type = 0; uint32_t *bd_ptr = NULL; pipe_struct_t* pipe_desc_ptr = msg.pipe_desc; switch (msg.type) { case TR_MSG_SETUP: if (msg.pipe_tr->setup_status == 0) { type = TR_CTRL; } else if (( msg.pipe_tr->setup_status ==1) ) { if (msg.pipe_tr->rx_length) { type = TR_IN; } else if (msg.pipe_tr->tx_length) { type = TR_OUT; } } else if (msg.pipe_tr->setup_status ==2) { if (msg.pipe_tr->rx_length) { type = TR_OUT; } else if (msg.pipe_tr->tx_length) { type = TR_IN; } else { type = TR_IN; } } else if (msg.pipe_tr->setup_status ==3) { type = TR_IN; } break; case TR_MSG_RECV: type = TR_IN; break; case TR_MSG_SEND: type = TR_OUT; break; default: return KHCI_ATOM_TR_INVALID; } switch (type) { case TR_CTRL: usb_host_ptr->tx_bd ^= 1; //USB_PRINTF("len %d %d\n", len, pipe_desc_ptr->max_packet_size); bd_ptr = (uint32_t*) BD_PTR(0, 1, usb_host_ptr->tx_bd); usb_host_ptr->tx_bd ^= 1; break; case TR_IN: usb_host_ptr->rx_bd ^= 1; bd_ptr = (uint32_t*) BD_PTR(0, 0, usb_host_ptr->rx_bd); usb_host_ptr->rx_bd ^= 1; break; case TR_OUT: usb_host_ptr->tx_bd ^= 1; bd_ptr = (uint32_t*) BD_PTR(0, 1, usb_host_ptr->tx_bd); usb_host_ptr->tx_bd ^= 1; break; default: bd_ptr = NULL; break; } bd = USB_LONG_LE_TO_HOST(*bd_ptr); //USB_PRINTF("bd 0x%x 0x%x\n", bd, usb_ptr->ERRSTAT); if (usb_hal_khci_is_error_happend(usb_host_ptr->usbRegBase, ERROR_PIDERR | #if defined(KHCICFG_BASIC_SCHEDULING) ERROR_CRC5EOF | #endif ERROR_CRC16 | ERROR_DFN8 | ERROR_DMAERR | ERROR_BTSERR )) { #if defined(KHCICFG_BASIC_SCHEDULING) if (usb_hal_khci_is_error_happend(usb_host_ptr->usbRegBase, ERROR_CRC5EOF)) { //retry = 0; } #endif res = -(int32_t)usb_hal_khci_get_error_interrupt_status(usb_host_ptr->usbRegBase); return res; } else { if (bd & USB_BD_OWN) { USB_PRINTF("2 BIG ERROR 0x%x\n", (unsigned int)bd); *bd_ptr = 0; USB_PRINTF("2 after change 0x%x\n", (unsigned int)USB_LONG_LE_TO_HOST(*bd_ptr)); } if((pipe_desc_ptr->pipetype == USB_ISOCHRONOUS_PIPE)) { res = (bd >> 16) & 0x3ff; } else { switch (bd >> 2 & 0xf) { case 0x03: // DATA0 case 0x0b: // DATA1 case 0x02: // ACK //retry = 0; res = (bd >> 16) & 0x3ff; pipe_desc_ptr->nextdata01 ^= 1; // switch data toggle break; case 0x0e: // STALL res = KHCI_ATOM_TR_STALL; //retry = 0; break; case 0x0a: // NAK res = KHCI_ATOM_TR_NAK; break; case 0x00: // bus timeout { //retry = 0; res = KHCI_ATOM_TR_BUS_TIMEOUT; } break; case 0x0f: // data error //if this event happens during enumeration, then return means not finished enumeration res = KHCI_ATOM_TR_DATA_ERROR; break; default: break; } } } #if USBCFG_KHCI_4BYTE_ALIGN_FIX if ((TR_IN == type) && (FALSE == s_xfer_sts.is_dma_align)) { s_xfer_sts.is_dma_align = TRUE; if (res > 0) { OS_Mem_copy(s_xfer_sts.rx_buf, s_xfer_sts.rx_buf_orig, res); } } #endif return res; } /*FUNCTION*------------------------------------------------------------- * * Function Name : _usb_khci_atom_tr * Returned Value : * Comments : * Atomic transaction *END*-----------------------------------------------------------------*/ static int32_t _usb_khci_atom_noblocking_tr( usb_khci_host_state_struct_t* usb_host_ptr, uint32_t type, pipe_struct_t* pipe_desc_ptr, uint8_t *buf_ptr, uint32_t len ) { //USB_MemMapPtr usb_ptr = (USB_MemMapPtr) usb_host_ptr->DEV_PTR; //uint32_t bd; uint32_t *bd_ptr = NULL; //uint32_t *bd_ptr_tmp = NULL; uint8_t *buf = buf_ptr; //uint8_t *buf_ptr_temp = NULL; int32_t res; //int32_t delay_const = 10; //uint32_t event_value = (uint32_t)0; uint8_t speed; uint8_t address; uint8_t level; uint8_t counter = 0; #if (USB_NONBLOCKING_MODE == 0) uint32_t ret; #endif usb_host_ptr->last_to_pipe = NULL; // at the beginning, consider that there was not timeout len = (len > pipe_desc_ptr->max_packet_size) ? pipe_desc_ptr->max_packet_size : len; level = usb_host_dev_mng_get_level(pipe_desc_ptr->dev_instance); speed = usb_host_dev_mng_get_speed(pipe_desc_ptr->dev_instance); address = usb_host_dev_mng_get_address(pipe_desc_ptr->dev_instance); if(speed == USB_SPEED_LOW) { usb_hal_khci_enable_low_speed_support(usb_host_ptr->usbRegBase); } else { usb_hal_khci_disable_low_speed_support(usb_host_ptr->usbRegBase); } usb_hal_khci_set_device_addr(usb_host_ptr->usbRegBase, USB_ADDR_ADDR(address)); usb_hal_khci_endpoint0_init(usb_host_ptr->usbRegBase, level, (pipe_desc_ptr->pipetype == USB_ISOCHRONOUS_PIPE ? 1 : 0)); res = 0; counter = 0; // wait for USB ready, but with timeout while (usb_hal_khci_is_token_busy(usb_host_ptr->usbRegBase)) { if (OS_Event_wait(usb_host_ptr->khci_event_ptr, KHCI_EVENT_MASK, FALSE, 1) == OS_EVENT_OK) { res = KHCI_ATOM_TR_RESET; break; } else { counter++; if (counter >= 3) { res = KHCI_ATOM_TR_CRC_ERROR; //usb_ptr->CTL &= ~USB_CTL_TXSUSPENDTOKENBUSY_MASK; //USB_PRINTF("big error, USB_CTL_TXSUSPENDTOKENBUSY_MASK 0x%x, %d\n", usb_ptr->CTL, retry); return res; } } } if (!res) { #if defined (FSL_FEATURE_USB_KHCI_DYNAMIC_SOF_THRESHOLD_COMPARE_ENABLED) && (FSL_FEATURE_USB_KHCI_DYNAMIC_SOF_THRESHOLD_COMPARE_ENABLED == 1) if (speed == USB_SPEED_LOW) //low speed { usb_host_ptr->sof_threshold = (len * 12 * 7 / 6 +KHCICFG_THSLD_DELAY)/8; usb_hal_khci_set_sof_theshold(usb_host_ptr->usbRegBase, usb_host_ptr->sof_threshold); } else { usb_host_ptr->sof_threshold = (len * 7 / 6 + KHCICFG_THSLD_DELAY)/8; usb_hal_khci_set_sof_theshold(usb_host_ptr->usbRegBase, usb_host_ptr->sof_threshold); } #endif //USB_PRINTF("%d %d\n", pipe_desc_ptr->max_packet_size, usb_ptr->SOFTHLD); usb_hal_khci_clr_interrupt(usb_host_ptr->usbRegBase, INTR_SOFTOK);//clear SOF usb_hal_khci_clr_all_error_interrupts(usb_host_ptr->usbRegBase);//clear error status #if USBCFG_KHCI_4BYTE_ALIGN_FIX if ((TR_IN == type) && ((len & USB_DMA_ALIGN_MASK) || ((uint32_t)buf_ptr & USB_DMA_ALIGN_MASK))) { if ((_usb_khci_swap_buf_ptr != NULL) && (len <= USBCFG_HOST_KHCI_SWAP_BUF_MAX)) { buf = (uint8_t*)USB_DMA_ALIGN((int32_t)_usb_khci_swap_buf_ptr); s_xfer_sts.rx_buf = buf; s_xfer_sts.rx_buf_orig = buf_ptr; s_xfer_sts.rx_len = len; s_xfer_sts.is_dma_align = FALSE; } } else { s_xfer_sts.is_dma_align = TRUE; } #endif switch (type) { case TR_CTRL: //USB_PRINTF("len %d %d\n", len, pipe_desc_ptr->max_packet_size); bd_ptr = (uint32_t*) BD_PTR(0, 1, usb_host_ptr->tx_bd); *(bd_ptr + 1) = USB_HOST_TO_LE_LONG((uint32_t)buf); *bd_ptr = USB_HOST_TO_LE_LONG(USB_BD_BC(len) | USB_BD_OWN); usb_hal_khci_set_target_token(usb_host_ptr->usbRegBase, USB_TOKEN_TOKENPID_SETUP, (uint8_t)pipe_desc_ptr->endpoint_number); // USB_PRINTF("2 CTRL 0x%x 0x%x 0x%x %X %x\n", *bd_ptr, *(bd_ptr+1), usb_ptr->TOKEN, usb_host_ptr->tx_bd,bd_ptr); usb_host_ptr->tx_bd ^= 1; break; case TR_IN: //bd_ptr_tmp = (uint32_t*) BD_PTR(0, 0, 0); bd_ptr = (uint32_t*) BD_PTR(0, 0, usb_host_ptr->rx_bd); *(bd_ptr + 1) = USB_HOST_TO_LE_LONG((uint32_t)buf); *bd_ptr = USB_HOST_TO_LE_LONG(USB_BD_BC(len) | USB_BD_OWN | USB_BD_DATA01(pipe_desc_ptr->nextdata01)); usb_hal_khci_set_target_token(usb_host_ptr->usbRegBase, USB_TOKEN_TOKENPID_IN, (uint8_t)pipe_desc_ptr->endpoint_number); //USB_PRINTF("B 0x%x 0x%x %d\n", *bd_ptr_tmp,*(bd_ptr_tmp+2),usb_host_ptr->rx_bd); // USB_PRINTF("IN 0x%x 0x%x 0x%x %d %x\n", *bd_ptr, *(bd_ptr+1), usb_ptr->TOKEN, usb_host_ptr->rx_bd,bd_ptr); //USB_PRINTF("0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\n", buf, *buf, *(buf+1),*(buf+2), *(buf+3),*(buf+4), *(buf+5),*(buf+6), *(buf+7)); usb_host_ptr->rx_bd ^= 1; break; case TR_OUT: bd_ptr = (uint32_t*) BD_PTR(0, 1, usb_host_ptr->tx_bd); *(bd_ptr + 1) = USB_HOST_TO_LE_LONG((uint32_t)buf); *bd_ptr = USB_HOST_TO_LE_LONG(USB_BD_BC(len) | USB_BD_OWN | USB_BD_DATA01(pipe_desc_ptr->nextdata01)); usb_hal_khci_set_target_token(usb_host_ptr->usbRegBase, USB_TOKEN_TOKENPID_OUT, (uint8_t)pipe_desc_ptr->endpoint_number); // USB_PRINTF("OUT 0x%x 0x%x 0x%x %d %x\n", *bd_ptr, *(bd_ptr+1), usb_ptr->TOKEN, usb_host_ptr->tx_bd,bd_ptr); usb_host_ptr->tx_bd ^= 1; break; default: bd_ptr = NULL; break; } // USB_PRINTF(" %x\n" ,bd_ptr); #if (USB_NONBLOCKING_MODE == 0) ret = OS_Event_wait(usb_host_ptr->khci_event_ptr, KHCI_EVENT_TOK_DONE, FALSE, USBCFG_HOST_KHCI_WAIT_TICK); if ((uint32_t)OS_EVENT_TIMEOUT == ret) { res = KHCI_ATOM_TR_TO; usb_host_ptr->last_to_pipe = pipe_desc_ptr; // remember this pipe as it had timeout last time } #endif } return res; } #endif
def Get(self, subject): filename, directory = common.ResolveSubjectDestination(subject, self.path_regexes) key = common.MakeDestinationKey(directory, filename) try: return super(SqliteConnectionCache, self).Get(key) except KeyError: dirname = utils.JoinPath(self.root_path, directory) path = utils.JoinPath(dirname, filename) + "." + SQLITE_EXTENSION dirname = utils.SmartStr(dirname) path = utils.SmartStr(path) if not os.path.isdir(dirname): try: os.makedirs(dirname) except OSError: pass self._EnsureDatabaseExists(path) connection = SqliteConnection(path) super(SqliteConnectionCache, self).Put(key, connection) return connection
// Run runs the genetic pool and finds the best creature func Run(p Pool) Creature { startTime := time.Now().UnixNano() var maxFitness, lastMaxFitness, averageFitness, lastAverageFitness float32 var t int64 iteration := 0 var bestCreature Creature fmt.Println(fmt.Sprintf("Running pool of size %d.", p.PoolSize())) for !(p.Finished(iteration, maxFitness, lastMaxFitness, averageFitness, lastAverageFitness, t)) { lastMaxFitness = maxFitness lastAverageFitness = averageFitness breeding := p.Select() newPool := make([]Creature, 0, p.PoolSize()) newPool = append(newPool, breeding...) bestCreature, maxFitness = MaxFitness(p) averageFitness = AverageFitness(p) for len(newPool) < p.Size() { first := WeightedSelect(breeding, maxFitness) other := WeightedSelect(breeding, maxFitness) for { if first != other { break } other = WeightedSelect(breeding, maxFitness) } a, b := first.CrossOver(other) newPool = append(newPool, a, b) } p.SetCreatures(newPool) for i := 0; i < p.Size(); i++ { if rand.Float32() < p.MutationProbability() { p.Get(i).Mutate() } } t = (time.Now().UnixNano() - startTime) / (int64(time.Millisecond) / int64(time.Nanosecond)) iteration++ fmt.Println(fmt.Sprintf("Iteration %d [%d ms, (av. %d ms)], max fitness %f, average fitness %f.", iteration, t, t/int64(iteration), maxFitness, averageFitness)) } fmt.Println(fmt.Sprintf("Finished after %d ms. Best fitness is %f. Best creature is %s", t, maxFitness, bestCreature)) return bestCreature }
//TODO: Add tests concerning books separated into parts public class LatexGeneratorTest { private LatexGenerator generator; private Book book; private File temp; private LatexParser parser; private TubainaBuilderData data; @Before public void setUp() throws IOException { RegexConfigurator configurator = new RegexConfigurator(); List<RegexTag> tags = configurator.read("/regex.properties", "/html.properties"); parser = new LatexParser(tags); File path = new File("src/test/resources"); ResourceLocator.initialize(path); data = new TubainaBuilderData(false, TubainaBuilder.DEFAULT_TEMPLATE_DIR, false, false, "teste"); generator = new LatexGenerator(parser, data); BookBuilder builder = builder("livro"); builder.addReaderFromString("[chapter O que é java? ]\n" + "texto da seção\n" + "[section Primeira seção]\n" + "texto da prim seção\n" + "[section Segunda seção]\n" + "texto da segunda seção\n\n"); builder.addReaderFromString("[chapter Introdução]\n" + "Algum texto de introdução\n"); book = builder.build(); temp = new File("tmp"); temp.mkdir(); } @After public void deleteTempFiles() throws IOException { // Probably not working on Windows. See HtmlGeneratorTest FileUtils.deleteDirectory(temp); } @Test public void testGenerator() throws IOException { new LatexModule().inject(book); generator.generate(book, temp); // Book LaTeX File texFile = new File(temp, "teste.tex"); Assert.assertTrue("Book file should exist", texFile.exists()); // Answer book LaTeX File answerFile = new File(temp, "answer.tex"); Assert.assertFalse("Answer file should NOT exist", answerFile.exists()); // Resources File styleFile = new File(temp, "tubaina.sty"); Assert.assertTrue("Style file should exist", styleFile.exists()); File xcolorStyleFile = new File(temp, "xcolor.sty"); Assert.assertTrue("Xcolor style file should exist", xcolorStyleFile.exists()); Assert.assertTrue(FileUtilities.contentEquals(new File(TubainaBuilder.DEFAULT_TEMPLATE_DIR, "latex"), temp, new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.contains(".png"); } })); } @Test public void testGeneratorWithCorrectImages() throws IOException { BookBuilder builder = builder("Com imagens"); builder.addReaderFromString("[chapter qualquer um]\n" + "[img baseJpgImage.jpg]"); Book b = builder.build(); new LatexModule().inject(b); generator.generate(b, temp); File[] images = temp.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.contains(".png") || name.contains(".jpg"); } }); Assert.assertEquals(2, images.length); File copied = new File(temp, "baseJpgImage.jpg"); Assert.assertTrue(copied.exists()); } @Test public void testGeneratorWithDoubledImage() throws TubainaException, IOException { BookBuilder builder = builder("Com imagens"); builder.addReaderFromString("[chapter qualquer um]\n" + "[img baseJpgImage.jpg]\n[img baseJpgImage.jpg]"); Book b = builder.build(); new LatexModule().inject(b); try { generator.generate(b, temp); } catch (TubainaException t) { Assert.fail("Should not raise an exception"); } // OK } @Test public void testGeneratorWithNonExistantImage() throws TubainaException, IOException { BookBuilder builder = builder("Com imagens"); builder.addReaderFromString("[chapter qualquer um]\n" + "[img src/test/resources/someImage.gif]"); try { Book b = builder.build(); new LatexModule().inject(b); generator.generate(b, temp); Assert.fail("Should raise an exception"); } catch (TubainaException t) { // OK } } @Test public void testGeneratorForInstructorTextbook() throws IOException { RegexConfigurator configurator = new RegexConfigurator(); List<RegexTag> tags = configurator.read("/regex.properties", "/html.properties"); LatexParser parser = new LatexParser(tags); File path = new File("src/test/resources"); ResourceLocator.initialize(path); BookBuilder builder = builder("Do Instrutor"); builder.addReaderFromString("[chapter com notas]\n" + "Algo mais no capitulo.\n\n[note]uma nota para o instrutor[/note]"); Book b = builder.build(); new LatexModule(true, true).inject(b); new LatexGenerator(parser, data).generate(b, temp); File texFile = new File(temp, "teste.tex"); Assert.assertTrue("Book file should exist", texFile.exists()); Assert.assertTrue("Should display the note", containsText(texFile, "uma nota para o instrutor")); } @Test public void testGeneratorForStudentTextbook() throws IOException { BookBuilder builder = builder("Do Aluno"); builder.addReaderFromString("[chapter com notas]\n" + "[note]uma nota para o instrutor[/note]"); Book b = builder.build(); new LatexModule(false, true).inject(b); generator.generate(b, temp); File texFile = new File(temp, "teste.tex"); Assert.assertTrue("Book file should exist", texFile.exists()); Assert.assertFalse("Should not have INSTRUCTOR TEXTBOOK on the first page", containsText(texFile, "INSTRUCTOR TEXTBOOK")); Assert.assertFalse("Should not display the note", containsText(texFile, "uma nota para o instrutor")); } @Test public void shouldCopyImagesFromIntroduction() throws IOException { BookBuilder builder = builder("With images in intro"); List<AfcFile> chapterReaders = new ArrayList<AfcFile>(); String imagePath = "introImage.jpg"; List<AfcFile> introductionReaders = Arrays.asList(new AfcFile(new StringReader("[chapter intro]\n[img " + imagePath + "]"), "file from string")); builder.addAllReaders(chapterReaders, introductionReaders); Book b = builder.build(); new LatexModule().inject(b); generator.generate(b, temp); File copied = new File(temp, imagePath); Assert.assertTrue(copied.exists()); } private boolean containsText(File texFile, String text) throws IOException { List<String> lines = FileUtils.readLines(texFile); boolean containsText = false; for (String line : lines) { if (line.contains(text)) containsText = true; } return containsText; } private BookBuilder builder(String title) { return new BookBuilder(title, new SectionsManager()); } }
/* * This file is part of i915tool * * Copyright (C) 2012 The ChromiumOS Authors. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "video.h" int verbose = 1; static unsigned short addrport, dataport; struct drm_device *i915; unsigned short vendor=0x8086, device=0x0116; struct pci_dev fake = {.vendor_id=0x8086, .device_id = 0x0116}; int dofake = 0; u8 *bios_image = NULL; u8 *mmiobase; u32 mmiophys; int mmiosize; size_t bios_image_size; /* temporary */ unsigned int i915_lvds_downclock = 0; int i915_vbt_sdvo_panel_type = -1; /* */ /* not sure how we want to do this so let's guess */ /* to make it easy, we start at zero and assume 250 hz. */ unsigned long msecs(void) { struct timeval start, now; static int first = 0; unsigned long j; if (! first++) gettimeofday(&start, NULL); gettimeofday(&now, NULL); j = (now.tv_sec - start.tv_sec)*1000 + (now.tv_usec-start.tv_usec)/1000; return j; } void mdelay(unsigned long ms) { unsigned long start; start = msecs(); while (msecs() < (start + ms)) ; } void hexdump(u8 *base, int size) { int i, j; for(i = 0; i < size/sizeof(u32); i += 8) { printf("%#x: ", i); for(j = 0; j < 8; j++) printf("%08x", base[i+j]); printf("\n"); } } void udelay(int i) { printf("UDELAY!\n"); } unsigned long io_I915_READ(unsigned long addr) { unsigned long val; if (dofake) return 0xcafebabe; outl(addr, addrport); val = inl(dataport); if (verbose) fprintf(stderr, "%s: %x <- %x\n", __func__, val, addr); return val; } void io_I915_WRITE(unsigned long addr, unsigned long val) { if (dofake) return; outl(addr, addrport); outl(val, dataport); if (verbose) fprintf(stderr, "%s: %x -> %x\n", __func__, val, addr); } unsigned long I915_READ(unsigned long addr) { volatile u32 *ptr = (u32 *)(mmiobase + addr); unsigned long val; if (dofake) return 0xcafebabe; val = *ptr; if (verbose) fprintf(stderr, "%s: %x <- %x\n", __func__, val, addr); return val; } void I915_WRITE(unsigned long addr, unsigned long val) { volatile u32 *ptr = (u32 *)(mmiobase + addr); if (dofake) return; *ptr = val; if (verbose) fprintf(stderr, "%s: %x -> %x\n", __func__, val, addr); } u16 I915_READ16(unsigned long addr) { volatile u16 *ptr = (u16 *)(mmiobase + addr); unsigned long val; if (dofake) return 0xbabe; val = *ptr; if (verbose) fprintf(stderr, "%s: %x <- %x\n", __func__, val, addr); return val; } void I915_WRITE16(unsigned long addr, u16 val) { volatile u16 *ptr = (u16 *)(mmiobase + addr); if (dofake) return; *ptr = val; if (verbose) fprintf(stderr, "%s: %x -> %x\n", __func__, val, addr); } #define GTT_RETRY 1000 static int gtt_poll(u32 reg, u32 mask, u32 value) { unsigned try = GTT_RETRY; u32 data; while (try--) { data = I915_READ(reg); if ((data & mask) == value){ printf("succeeds after %d tries\n", GTT_RETRY-try); return 1; } udelay(10); } fprintf(stderr, "GT init timeout\n"); return 0; } void *pci_map_rom(struct pci_dev *dev, size_t *size) { *size = bios_image_size; return bios_image; } void *pci_unmap_rom(struct pci_dev *dev, void *bios) { return NULL; } void *dmi_check_system(unsigned long ignore) { return NULL; } void mapit(void) { int kfd; kfd = open("/dev/mem", O_RDWR); if (kfd < 0) errx(1, "/dev/kmem"); mmiobase = mmap(NULL, mmiosize, PROT_WRITE|PROT_READ, MAP_SHARED, kfd, mmiophys); if ((void *)-1 == mmiobase) errx(1, "mmap"); } void devinit() { u32 val; /* force wake. */ I915_WRITE(0xa18c, 1); gtt_poll(0x130090, 1, 1); } int main(int argc, char *argv[]) { struct pci_dev *pci_dev_find(struct drm_device *dev); for(argc--, argv++; argc; argc--, argv++) { if (argv[0][0] != '-') break; if (!strcmp(argv[0], "-f")) dofake++; } i915 = calloc(1, sizeof(*i915)); i915->dev_private = calloc(1, sizeof(*i915->dev_private)); /* until we do a bit more w/ coccinelle */ i915->dev_private->dev = i915; if (dofake) { i915->pdev = &fake; if (! find_idlist(i915, vendor, device)) errx(1, "can't find fake device in pciidlist"); } else { if (! pci_dev_find(i915)) errx(1, "No VGA device of any kind found\n"); } if (argc) { FILE *fd; int amt; /* size it later */ bios_image = malloc(8*1048576); fd = fopen(argv[0], "r"); amt = fread(bios_image, 65536, 128, fd); if (amt < 1) { free(bios_image); } else { i915->bios_bin = bios_image; i915->dev_private->opregion.vbt = bios_image; bios_image_size = amt * 65536; fclose(fd); } } /* get the base address for the mmio indirection registers -- BAR 2 */ addrport = i915->pdev->base_addr[4] & ~3; dataport = addrport + 4; printf("Addrport is at %x, dataport at %x\n", addrport, dataport); /* get the base of the mmio space */ mmiophys = i915->pdev->base_addr[0] & ~0xf; mmiosize = i915->pdev->size[0]; printf("phys base is %#x, size %d\n", mmiophys, mmiosize); mapit(); devinit(); //hexdump(mmiobase, mmiosize); /* we should use ioperm but hey ... it's had troubles */ iopl(3); intel_setup_bios(i915); if (i915->bios_bin) intel_parse_bios(i915); }
<gh_stars>1-10 package communication.packets.request.admin; import communication.enums.PacketType; import communication.packets.AuthenticatedRequestPacket; import communication.packets.response.ValidResponsePacket; import communication.wrapper.Connection; import main.Conference; import voting.AnonymousVotingOption; import voting.NamedVotingOption; import voting.Voting; import voting.VotingOption; import java.util.LinkedList; import java.util.List; /** * This packet can be used by an admin to add a voting to the conference. This voting is not started until * a {@link StartVotingRequestPacket} is received. Responds with a {@link communication.packets.BasePacket}. */ public class AddVotingRequestPacket extends AuthenticatedRequestPacket { private String question; private List<String> options; private boolean namedVote; private int duration; /** * @param question the question which should be decided by the voting * @param options the possible voting options as a list of strings * @param namedVote if the vote is named i.e. if it is public who voted for which option * @param duration the duration of the voting after it started in seconds */ public AddVotingRequestPacket(String question, List<String> options, boolean namedVote, int duration) { super(PacketType.ADD_VOTING_REQUEST_PACKET); this.question = question; this.options = options; this.namedVote = namedVote; this.duration = duration; } @Override public void handle(Conference conference, Connection connection) { if(isPermitted(conference, connection, true)) { VotingOption votingOptionObject; List<VotingOption> optionsObjectList = new LinkedList<>(); int id = 0; for(String option : options) { if(namedVote) { votingOptionObject = new NamedVotingOption(id, option); } else { votingOptionObject = new AnonymousVotingOption(id, option); } optionsObjectList.add(votingOptionObject); id++; } Voting voting = new Voting(optionsObjectList, question, namedVote, duration); conference.addVoting(voting); new ValidResponsePacket().send(connection); } } }
def adjust_image(image, diff): data = np.asarray(image, dtype='float32') data[:, :, 0] = np.clip(data[:, :, 0] - diff[0], 0.0, 255.0) data[:, :, 1] = np.clip(data[:, :, 1] - diff[1], 0.0, 255.0) data[:, :, 2] = np.clip(data[:, :, 2] - diff[2], 0.0, 255.0) return Image.fromarray(data.astype(np.uint8))
The writers of Star Wars' next movie, Rogue One, have revealed that the villain is based on Donald Trump. The movie will be released in the United States on December 16. Scriptwriter Chris Weitz tweeted that the "Empire is a white supremacist (human) organization." He also attached an image of the rebel logo that is widely known throughout the Star Wars universe, with a safety pin through it. The symbol has gained traction in the United Kingdom since Brexit as a symbol of solidarity with so-called persecuted minorities. The tweet was not live for long. Weitz deleted the tweet later in the day. Weitz confirmed the story in Rogue One is related to the US election by praising a commentary article on CBR.com that connected the election to the next movie in the franchise. In the article, the author, Brett White, said the film was the "the most relevant movie of 2016." He continued, "when I look at the 'Rogue One' trailers, I see what I want from America. I see a multicultural group standing strong together led by a rebellious and courageous woman." The original scriptwriter of the movie, Gary Whitta, agreed with Weitz that the Empire is a white supremacist organization and retweeted: "Opposed by a multi-cultural group led by brave women." Mark Hamill, the actor who originally played as Luke Skywalker, retweeted another tweet by Weitz that included the safety pinned rebel logo with the words "Star Wars against hate. Spread it." New villain? The next Star Wars movie is placed shortly before the first Star Wars movie, also known as episode IV, where the Empire is in the process of building a gigantic planet-busting weapon known as the 'Death Star'. The hero of Rogue One is a female whose story is not yet known, but fans of the series believe she may have 'force' powers. This is not the first time that the Star Wars franchise was accused of political bias. In the 70s, Star Wars was seen as an analogy of the Cold War and Darth Vadar as a representation of the next Adolf Hitler. Also, when the next batch of movies were released in first decade of the 2000s, critics pegged a "with us or against us" speech by two characters as a commentary of President Bush's military action in Iraq. Hillary Clinton? New television spot: Rebels are Built on Hope
<reponame>rosudrag/Freemium-winner<filename>app/freemiumwebapp/twitterHook.py from TwitterAPI import TwitterAPI from app.freemiumwebapp.adminConstants import AdminConstants SEARCH_TWEETS_REQUEST = 'search/tweets' class TwitterHook(): def __init__(self): self.auth_type = "oAuth2" adminconstants = AdminConstants() self.consumer_key = adminconstants.consumer_key self.consumer_secret = adminconstants.consumer_secret self.access_key = adminconstants.access_key self.access_secret = adminconstants.access_secret self.api = TwitterAPI(self.consumer_key, self.consumer_secret, self.access_key, self.access_secret) def can_login(self): api = self.api try: request = api.request(SEARCH_TWEETS_REQUEST, {'q': 'pizza'}) if request.status_code == 200: return True except: return False def latest_tweets(self): api = self.api request = api.request('statuses/home_timeline', {'count': '200'}) tweets = self.extract_tweets_from_response(request) return tweets def search_by_query(self, query): api = self.api response = api.request(SEARCH_TWEETS_REQUEST, {'q': query}) tweets = self.extract_tweets_from_response(response) return tweets @staticmethod def extract_tweets_from_response(response): tweets = [] for tweet in response: tweets.append(tweet) return tweets
from django.conf import settings from django.contrib import admin from django.urls import re_path from django.views.generic import RedirectView from django.views.static import serve try: from django.conf.urls import url, include except ImportError: from django.conf.urls.defaults import url, include from . import views urlpatterns = [ url(r"^$", RedirectView.as_view(pattern_name="admin:index", permanent=False)), url(r"admin/doc/", include("django.contrib.admindocs.urls")), url(r"admin/", admin.site.urls), url(r"make_messages/", views.make_messages, name="make_messages"), ] if settings.DEBUG: urlpatterns.append(re_path(r"^static/(?P<path>.*)$", serve, kwargs={"document_root": settings.STATIC_ROOT})) if "debug_toolbar" in settings.INSTALLED_APPS: try: import debug_toolbar urlpatterns.append(url(r"__debug__/", include(debug_toolbar.urls))) except ImportError: pass
<reponame>SriramKodey/Automated_Localized_Strain_Analysis from cv2 import cv2 import numpy as np from tkinter import filedialog def load(): path = filedialog.askopenfilename() img = cv2.imread(path) return img
/* * Traverse a string of 1-byte tag/1-byte length/variable-length value * triples, returning a pointer to the substring whose first element * matches tag */ bcm_tlv_t * bcm_parse_tlvs(void *buf, int buflen, uint key) { bcm_tlv_t *elt; int totlen; elt = (bcm_tlv_t*)buf; totlen = buflen; while (totlen >= 2) { int len = elt->len; if ((elt->id == key) && (totlen >= (len + 2))) return (elt); elt = (bcm_tlv_t*)((uint8*)elt + (len + 2)); totlen -= (len + 2); } return NULL; }
Canadian members of Parliament should not be afraid to have their expenses audited, if it's true that the rules and regulations in place are as good as the MPs say they are, says Auditor General Sheila Fraser. "Well, I don't think MPs have anything to fear. They've certainly indicated that they have strong systems and practices in place. If that's the case, I would be very happy to report that." Fraser said the public and some MPs have clearly "misunderstood" what her intentions were when she asked to do a performance audit of the administration of the House of Commons. Fraser said a performance audit is not as detailed as a forensic audit. While she could discover inappropriate spending — as happened in Britain with members of Parliament — the performance audit she is recommending is more focused on looking at what spending rules are in place and if they are being followed. "I've heard people talking about a $4 cup of coffee. I've got, quite frankly, better things to do than look for $4 cups of coffee," Fraser said. She said she would welcome the chance to clarify her position at the Board of Internal Economy, which initially turned down her audit request. Speaker Peter Milliken, who chairs the board, said it's not up to him whether or not Fraser gets that chance; he says it's up to the board as a whole. When asked if he understands that the public is looking for accountability, Milliken said: "All Canadians have that interest. It's not a matter of what you're hiding. It's a matter of what the auditor general's report is going to reveal. It may reveal nothing. It may say everything is fine." Milliken was also asked why he believes the auditor general does not have the authority to do such an audit when previous auditors general have done them. Milliken said those auditors general were invited to do the audits. He repeated that it is not up to him to invite Fraser to do an audit. Parties sound more open to talks Meanwhile all the parties — after hearing from constituents in their ridings over this past break week — have now indicated they are willing to have further discussions with Fraser about what she would like to look at. Liberal MP Marcel Proulx, who is one of two designated spokespeople for the Board of Internal Economy, said the invitation for Fraser to come back and speak to the board was already made in the letter it sent to her declining the audit request. But it is not clear when or if Fraser will appear before the board. Fraser said it's clear Canadians want "accountability for their monies spent." "I don't think anyone likes to be audited, but it is an important part of our accountability and governance framework. It has been a very long time since an audit has been done of the House, I mean close to 20 years, and that is why we suggested it," Fraser said, adding that she already audits all departments and agencies on a regular basis.
// parse one line each time. std::pair<HttpRequest::LINE_STATUS, std::size_t> HttpRequest::ParseLine(Buffer &buff) { if(state_ == PARSE_STATE::BODY) return {LINE_STATUS::LINE_OK, buff.ReadableBytes()}; char *begin = buff.ReadBegin(); char *end = buff.WriteBegin(); std::size_t line_len = 0; for (; begin != end; ++begin) { ++line_len; if (*begin == '\r') { if(begin + 1 == end) return {LINE_STATUS::LINE_OPEN, 0}; else if(*(begin + 1) == '\n') { *(begin) = *(begin + 1) = '\0'; return {LINE_STATUS::LINE_OK, line_len + 1}; } }else if(*begin == '\n') { if(*(begin - 1) == '\r') { *(begin) = *(begin - 1) = '\0'; return {LINE_STATUS::LINE_OK, line_len + 1}; } return {LINE_STATUS::LINE_BAD, 0}; } } return {LINE_STATUS::LINE_OPEN, 0}; }
/** * Provides an iterator over Wikipedia articles. * @return an iterator over Wikipedia articles */ public Iterator<String> iterator() { return new Iterator<String>() { private String nextArticle = null; public boolean hasNext() { if (nextArticle != null) { return true; } try { nextArticle = readNext(); } catch (IOException e) { return false; } return nextArticle!= null; } public String next() { if (nextArticle == null) { try { nextArticle = readNext(); if (nextArticle == null) { throw new NoSuchElementException(); } } catch (IOException e) { throw new NoSuchElementException(); } } String article = nextArticle; nextArticle = null; return article; } public void remove() { throw new UnsupportedOperationException(); } private String readNext() throws IOException { String s; StringBuilder sb = new StringBuilder(DEFAULT_STRINGBUFFER_CAPACITY); while ((s = reader.readLine()) != null) { if (s.endsWith("<page>")) break; } if (s == null) { stream.close(); reader.close(); return null; } sb.append(s).append("\n"); while ((s = reader.readLine()) != null) { sb.append(s).append("\n"); if (s.endsWith("</page>")) break; } return sb.toString(); } }; }
// Filters a list of log file paths with a regex pattern and between given start and end dates public List<String> filterFilePathsBetweenDates( List<String> logFilePaths, String universeLogsRegexPattern, Date startDate, Date endDate) throws ParseException { logFilePaths = supportBundleUtil.filterList(logFilePaths, universeLogsRegexPattern); Collections.sort(logFilePaths, Collections.reverseOrder()); Date minDate = null; List<String> filteredLogFilePaths = new ArrayList<>(); for (String filePath : logFilePaths) { String fileName = filePath.substring(filePath.lastIndexOf('/') + 1, filePath.lastIndexOf('-')); String trimmedFilePath = filePath.split("yb-data/")[1]; Matcher fileNameMatcher = Pattern.compile(universeLogsRegexPattern).matcher(filePath); if (fileNameMatcher.matches()) { String fileNameSdfPattern = "yyyyMMdd"; Date fileDate = new SimpleDateFormat(fileNameSdfPattern).parse(fileNameMatcher.group(2)); if (supportBundleUtil.checkDateBetweenDates(fileDate, startDate, endDate)) { filteredLogFilePaths.add(trimmedFilePath); } else if ((minDate == null && fileDate.before(startDate)) || (minDate != null && fileDate.equals(minDate))) { filteredLogFilePaths.add(trimmedFilePath); minDate = fileDate; } } } return filteredLogFilePaths; }
//Function to send UDP targeted messages func udpClient(remoteaddress net.UDPAddr, command []byte) { plugaddress := remoteaddress connection, err := net.DialUDP("udp", nil, &plugaddress) if err != nil { panic(err) } defer connection.Close() connection.Write(command) udpbuffer := make([]byte, 1024) length, addr, err := connection.ReadFrom(udpbuffer) if err != nil { panic(err) } else { fmt.Printf("%s\n", addr) plaintext := hex.EncodeToString(udpbuffer[:length]) decrypted := aesEcb256Decrypt(plaintext) fmt.Printf("%s\n", decrypted) } }
// CreateResetClusterNodeRequest creates a request to invoke ResetClusterNode API func CreateResetClusterNodeRequest() (request *ResetClusterNodeRequest) { request = &ResetClusterNodeRequest{ RoaRequest: &requests.RoaRequest{}, } request.InitWithApiInfo("CS", "2015-12-15", "ResetClusterNode", "/clusters/[ClusterId]/instances/[InstanceId]/reset", "cs", "openAPI") request.Method = requests.POST return }
The Backyard Axe Throwing League (BATL Grounds) has come a long way from the backyard. So far, in fact, that its new 7,000-plus-square-foot second location is an industrial-sized space nestled between film warehouses and production studios in a complex off Cherry Street south of Lake Shore Boulevard. The popular axe hurling league opened 'BATL Grounds' at 33 Villiers Street in December 2013 and now operates two locations, effectively putting an end to the league's current waiting list. BATL Grounds has four sets of four lanes, a vast expansion from the single set at its still-open 1,400-square-foot location on Sterling Road . Upon entering, participants quickly get used to the smell of sawed wood and freshly-sharpened steel and the cacophonous sound of axes chopping or bouncing off targets, and the echoes doing the same off the high ceilings. Founder Matt Wilson didn't do a hatchet job on the construction, either. Solid, straight lines divide the space into distinct throwing areas. Many BATL staff members are league veterans, and most look like warriors from a J.R.R. Tolkien novel - adding to the sense of toughness you might expect in an axe throwing environment. But beneath the hard-bitten veneer is an organically grown, word-of-mouth community that fosters a family atmosphere at BATL Grounds. "We're doing league expansion right now in a big way," said Wilson, who started BATL in a backyard off Manning Street in Little Italy. "We could have as many as 120 people throwing every night." All 120-plus current league members who throw at Sterling Road all know each other, and Wilson hopes that will remain the case as the axe-wielding family grows. For those twiddling their axes on the sidelines while the growing waiting list kept many out of the popular sport, the chance has come to get in on league play. BATL Grounds can also help with event requests at the Sterling Road location, which books 12 weeks in advance for Saturday private parties. BATL Grounds is used for both league play and private events. Events include coaching and practice followed by a round-robin tournament and a playoff final. The cost for events is $40 per person with a 12-person minimum. A standard event at BATL lasts for about three hours. "With this place now our plan is to have three arenas operating for events and league and one arena of four lanes free for league members to come do drop in and practice, which is something we could never do at the other space," Wilson tell me. The new space, like the old, does not serve alcohol but is BYOB - the only rule is no hard liquor and no glass. Writing by Erin Obourn / Photos by Jesse Milns
<reponame>RoseLeBlood/QOpenAL /*""" This file is part of QtOpenAl (unoficiale libary) Copyright (C) 2013 <NAME> <<EMAIL>> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ */ #include "include/openalsource.h" #include "include/openalbuffer.h" #include <AL/al.h> #include <AL/alc.h> #include "include/openalsoft.h" QtOpenalSource::QtOpenalSource() : m_pContext(0) { } QtOpenalSource::QtOpenalSource(QString name, QtOpenalContext *context) : m_pContext(context), m_strName(name) { alGenSources(1, &m_iId); setGain(1.0f); setPitch(1.0f); setPosition(glm::vec3(0, 0, 0)); setVelocity(glm::vec3(0, 0, 0)); setLooping(false); } QtOpenalSource::QtOpenalSource(QtOpenalSource& other) : m_pContext(other.m_pContext), m_strName(other.m_strName), m_iId(other.handle()) { } QtOpenalSource::~QtOpenalSource() { alDeleteSources(1, &m_iId); } void QtOpenalSource::setPosition(glm::vec3 position) { // m_vecPosition = position; alSource3f(m_iId, AL_POSITION, position.x, position.y, position.z); } void QtOpenalSource::setDirection(glm::vec3 direction) { alSource3f(m_iId, AL_DIRECTION, direction.x, direction.y, direction.z); } void QtOpenalSource::setVelocity(glm::vec3 velocity) { //m_vecVelocity = velocity; alSource3f(m_iId, AL_VELOCITY, velocity.x, velocity.y, velocity.z); } void QtOpenalSource::setGain(float gain) { //m_fGain = gain; alSourcef(m_iId, AL_GAIN, gain); } void QtOpenalSource::setPitch(float pitch) { // m_fPitch = pitch; alSourcef(m_iId, AL_PITCH, pitch); } void QtOpenalSource::setLooping(bool looping) { // m_bLooping = looping; alSourcei(m_iId, AL_LOOPING, (looping ? AL_TRUE : AL_FALSE)); } void QtOpenalSource::Bind(QtOpenalBuffer* buffer) { alSourcei(m_iId, AL_BUFFER, buffer->handle()); } void QtOpenalSource::QueueBuffers(QVector<QtOpenalBuffer*> buffers) { unsigned int *_buffers = new unsigned int[buffers.size()]; for(int i= 0; i < buffers.size(); i++) _buffers[i] = buffers[i]->handle(); alSourceQueueBuffers(m_iId, buffers.size(), _buffers); } void QtOpenalSource::QueueBuffers(unsigned int size, const unsigned int *ids) { alSourceQueueBuffers(m_iId, size, ids); } void QtOpenalSource::UnqueueBuffers(QVector<QtOpenalBuffer*> buffers) { unsigned int *_buffers = new unsigned int[buffers.size()]; for(int i= 0; i < buffers.size(); i++) _buffers[i] = buffers[i]->handle(); alSourceUnqueueBuffers(m_iId, buffers.size(), _buffers); } void QtOpenalSource::UnqueueBuffers(unsigned int size, unsigned int *id) { alSourceUnqueueBuffers(m_iId, size, id); } void QtOpenalSource::Play() { alSourcePlay(m_iId); } void QtOpenalSource::Stop() { alSourceStop(m_iId); } void QtOpenalSource::Pause() { alSourcePause(m_iId); } void QtOpenalSource::Rewind() { alSourceRewind(m_iId); } SourceState::SourceState_t QtOpenalSource::getState() { int state = 0; alGetSourcei(m_iId, AL_SOURCE_STATE, &state); return (SourceState::SourceState_t)state; } void QtOpenalSource::setMaxDistance(float maxDist) { alSourcef(m_iId, AL_MAX_DISTANCE, maxDist); } void QtOpenalSource::setRollOffFactor(float rollOff) { alSourcef(m_iId, AL_ROLLOFF_FACTOR, rollOff); } void QtOpenalSource::setReferenceDistance(float refDis) { alSourcef(m_iId, AL_REFERENCE_DISTANCE, refDis); } void QtOpenalSource::setMinGain(float mGain) { alSourcef(m_iId, AL_MIN_GAIN, mGain); } void QtOpenalSource::setMaxGain(float mGain) { alSourcef(m_iId, AL_MAX_GAIN, mGain); } void QtOpenalSource::setConeOuterGain(float cone) { alSourcef(m_iId, AL_CONE_OUTER_GAIN, cone); } void QtOpenalSource::setConeInnerAngle(int angle) { alSourcei(m_iId, AL_CONE_INNER_ANGLE, angle); } void QtOpenalSource::setConeOuterAngle(int angle) { alSourcei(m_iId, AL_CONE_OUTER_ANGLE, angle); } glm::vec3 QtOpenalSource::getPosition() { float f1, f2, f3; alGetSource3f(m_iId, AL_POSITION, &f1, &f2, &f3); return glm::vec3(f1,f2,f3); } glm::vec3 QtOpenalSource::getVelocity() { float f1, f2, f3; alGetSource3f(m_iId, AL_VELOCITY, &f1, &f2, &f3); return glm::vec3(f1,f2,f3); } glm::vec3 QtOpenalSource::getDirection() { float f1, f2, f3; alGetSource3f(m_iId, AL_DIRECTION, &f1, &f2, &f3); return glm::vec3(f1,f2,f3); } float QtOpenalSource::getGain() { float f = 0; alGetSourcef(m_iId, AL_GAIN, &f ); return f; } float QtOpenalSource::getPitch() { float f = 0; alGetSourcef(m_iId, AL_PITCH, &f ); return f; } bool QtOpenalSource::getLooping() { int f = 0; alGetSourcei(m_iId, AL_LOOPING, &f ); return f == AL_TRUE; } float QtOpenalSource::getMaxDistance() { float f = 0; alGetSourcef(m_iId, AL_MAX_DISTANCE, &f ); return f; } float QtOpenalSource::getRollOffFactor() { float f = 0; alGetSourcef(m_iId, AL_ROLLOFF_FACTOR, &f ); return f; } float QtOpenalSource::getReferenceDistance() { float f = 0; alGetSourcef(m_iId, AL_REFERENCE_DISTANCE, &f ); return f; } float QtOpenalSource::getMinGain() { float f = 0; alGetSourcef(m_iId, AL_MIN_GAIN, &f ); return f; } float QtOpenalSource::getMaxGain() { float f = 0; alGetSourcef(m_iId, AL_MAX_DISTANCE, &f ); return f; } float QtOpenalSource::getConeOuterGain() { float f = 0; alGetSourcef(m_iId, AL_CONE_OUTER_GAIN, &f ); return f; } int QtOpenalSource::getConeInnerAngle() { int f = 0; alGetSourcei(m_iId, AL_CONE_INNER_ANGLE, &f ); return f; } int QtOpenalSource::getConeOuterAngle() { int f = 0; alGetSourcei(m_iId, AL_CONE_OUTER_ANGLE, &f ); return f; } double QtOpenalSource::getLatency() { double offset[2]; alGetSourcedvSOFT(m_iId, AL_SEC_OFFSET_LATENCY_SOFT, offset); return offset[0]; } double QtOpenalSource::getOffsetLastRead() { return 0; }
def elina_interval_is_leq(interval1, interval2): result = None try: elina_interval_is_leq_c = elina_auxiliary_api.elina_interval_is_leq elina_interval_is_leq_c.restype = c_bool elina_interval_is_leq_c.argtypes = [ElinaIntervalPtr, ElinaIntervalPtr] result = elina_interval_is_leq_c(interval1, interval2) except: print('Problem with loading/calling "elina_interval_is_leq" from "libelinaux.so"') print('Make sure you are passing ElinaIntervalPtr and ElinaIntervalPtr to the function') return result
import pg_import_creator def main(): tv_dir = '' movie_dir = '' print('Starting import file creation') try: import_creator = pg_import_creator.PostgressImportCreator(tv_dir, movie_dir) import_creator.create_import_files() print('Import file creation finished. Please check log files.') except Exception as e: print('An error occurred during the import file creation process: {error}'.format(error=str(e))) if __name__ == '__main__': main()
/** * Excludes base view's ir, Includes the initial view's ir only if it has a sofa defined * * @param processIr * the code to execute */ void forAllIndexRepos(Consumer<FSIndexRepositoryImpl> processIr) { final int numViews = this.getViewCount(); for (int viewNum = 1; viewNum <= numViews; viewNum++) { processIr.accept(this.getSofaIndexRepository(viewNum)); } }
#pragma once #include "common.h" class CSnmpThread : public SysBase::CCustomThread, public SysBase::CSingletonT<CSnmpThread> { public: enum SNMP_TYPE { SNMP_TYPE_RECV = 0, SNMP_TYPE_SEND, SNMP_TYPE_MAX, }; virtual ~CSnmpThread(); friend class SysBase::CSingletonT<CSnmpThread>; void Add(SNMP_TYPE snmpType); protected: virtual void Proc(); private: CSnmpThread(); LONG m_Snmp[SNMP_TYPE_MAX]; };
def send_get_user_json_request(self): if self.fail_to_get_user_json: current_app.logger.debug( 'MockFlaskDanceProvider failed to get user info' ) return MockJsonResponse(False, None) return MockJsonResponse(True, self.user_json)
/** * Makes use of the local filesystem. * * @author Martin Kouba */ @Dependent public class FileSystemResultRepository implements ResultRepository { private static final Logger LOGGER = LoggerFactory.getLogger(FileSystemResultRepository.class); @Inject private Vertx vertx; @Inject private IdGenerator idGenerator; @Inject private Configuration configuration; private File resultDir; @PostConstruct void init() { String path = configuration.getStringValue(RESULT_DIR); if (path != null && !path.isEmpty()) { File dir = new File(path); if (!dir.canRead()) { LOGGER.debug("Result dir does not exist or cannot be read: " + dir); return; } resultDir = dir; } } @Override public boolean isValid() { return resultDir != null; } @Override public int getPriority() { return DEFAULT_PRIORITY + 1; } @Override public Result get(String resultId) { return readResult(new File(resultDir, resultId + ".json")); } @Override public ResultLink getLink(String linkId) { return readLink(linkId); } @Override public Result init(RenderRequest renderRequest) { Consumer<Result> onComplete = (result) -> { writeResult(result); if (result.isSucess() && renderRequest.getLinkId() != null) { writeLink(result.getId(), renderRequest.getLinkId()); } }; SimpleResult result = SimpleResult.init("" + idGenerator.nextId(), renderRequest.getTemplate().getId(), renderRequest.getTemplate().getContentType(), onComplete); writeResult(result); if (renderRequest.getTimeout() != null && renderRequest.getTimeout() > 0) { // Schedule result removal vertx.setTimer(renderRequest.getTimeout(), (id) -> { vertx.executeBlocking((future) -> { if (deleteResult(result.getId())) { LOGGER.info("Result timed out [id: {0}]", result.getId()); } future.complete(); }, AsyncHandlers.NOOP_HANDLER); }); } LOGGER.info("Result initialized [id: {0}, template: {1}, timeout: {2}]", result.getId(), renderRequest.getTemplate().getId(), renderRequest.getTimeout()); return result; } @Override public boolean remove(String resultId) { if (deleteResult(resultId)) { LOGGER.info("Result removed [id: {0}]", resultId); return true; } return false; } @Override public int size() { try { return Files.walk(resultDir.toPath(), 1).filter((path) -> { try { BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class); return attributes.isRegularFile() && path.toString().endsWith(".json"); } catch (Exception e) { LOGGER.warn("Unable to read attributes for {0}", e, path); return false; } }).mapToInt((e) -> 1).sum(); } catch (IOException e) { LOGGER.warn("Unable to count result JSON files in {0}", e, resultDir); return 0; } } @Override public void clear() { try { Files.walk(resultDir.toPath(), 1).forEach((path) -> { try { BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class); if (attributes.isRegularFile() && path.toString().endsWith(".json")) { Files.deleteIfExists(path); } } catch (IOException e) { LOGGER.warn("Unable to delete {0}", e, path); } }); LOGGER.info("All results removed from {0}", resultDir); } catch (IOException e) { LOGGER.warn("Unable to clear result directory {0}", e, resultDir); } } private boolean deleteResult(String resultId) { File resultFile = new File(resultDir, resultId + ".json"); try { return Files.deleteIfExists(resultFile.toPath()); } catch (IOException e) { LOGGER.debug("Error deleting result file: " + resultFile, e); return false; } } private Result readResult(File resultFile) { if (resultFile.exists()) { JsonObject resulJson = readJson(resultFile); return new SimpleResult(resulJson.getString(ID), Jsons.getLong(resulJson, CREATED, null), Jsons.getLong(resulJson, COMPLETED, null), resulJson.getString(TEMPLATE_ID), resulJson.getString(CONTENT_TYPE, null), Status.valueOf(resulJson.getString(STATUS)), resulJson.getString(VALUE, null), null); } return null; } private ResultLink readLink(String linkId) { File linkFile = new File(resultDir, linkId + ".json"); if (linkFile.exists()) { JsonObject linkJson = readJson(linkFile); return new SimpleResultLink(linkId, linkJson.getString(RESULT_ID)); } return null; } private JsonObject readJson(File file) { try (JsonReader reader = Jsons.INSTANCE.createReader(new InputStreamReader(new FileInputStream(file), configuration.getStringValue(DEFAULT_FILE_ENCODING)))) { return (JsonObject) reader.read(); } catch (Exception e) { throw new IllegalStateException("Error reading JSON from: " + file, e); } } private void writeResult(Result result) { File resultFile = new File(resultDir, result.getId() + ".json"); JsonObjectBuilder resultJson = Jsons.objectBuilder(); resultJson.add(ID, result.getId()); resultJson.add(STATUS, result.getStatus().toString()); resultJson.add(TEMPLATE_ID, result.getTemplateId()); if (result.getContentType() != null) { resultJson.add(CONTENT_TYPE, result.getContentType()); } resultJson.add(CREATED, result.getCreated()); if (result.getCompleted() != null) { resultJson.add(COMPLETED, result.getCompleted()); } if (result.getValue() != null) { resultJson.add(VALUE, result.getValue()); } writeJson(resultFile, resultJson.build()); } private void writeLink(String resultId, String linkId) { File linkFile = new File(resultDir, linkId + ".json"); writeJson(linkFile, Jsons.objectBuilder().add(RESULT_ID, resultId).add(LINK_ID, linkId).build()); } private void writeJson(File file, JsonObject jsonObject) { try (JsonWriter writer = Jsons.INSTANCE.createWriter(new OutputStreamWriter(new FileOutputStream(file), configuration.getStringValue(DEFAULT_FILE_ENCODING)))) { writer.writeObject(jsonObject); } catch (Exception e) { throw new IllegalStateException("Error writing JSON to: " + file, e); } } }
package org.gooru.nucleus.search.indexers.app.index.model; import org.gooru.nucleus.search.indexers.app.constants.IndexFields; import org.gooru.nucleus.search.indexers.app.utils.JsonUtil; import io.vertx.core.json.JsonObject; public class CourseStatisticsEo extends JsonObject { public int getUnitCount() { return this.getInteger(IndexFields.UNIT_COUNT, 0); } public void setUnitCount(int unitCount) { this.put(IndexFields.UNIT_COUNT, unitCount); } public int getCollaboratorCount() { return this.getInteger(IndexFields.COLLABORATOR_COUNT, 0); } public void setCollaboratorCount(int collaboratorCount) { this.put(IndexFields.COLLABORATOR_COUNT, collaboratorCount); } public long getViewsCount() { return this.getLong(IndexFields.VIEWS_COUNT, 0l); } public void setViewsCount(long viewsCount) { this.put(IndexFields.VIEWS_COUNT, viewsCount); } public long getCourseRemixCount() { return this.getLong(IndexFields.COURSE_REMIXCOUNT, 0l); } public void setCourseRemixCount(long courseRemixCount) { this.put(IndexFields.COURSE_REMIXCOUNT, courseRemixCount); } public double getPreComputedWeight() { return this.getDouble(IndexFields.PCWEIGHT, 0.0); } public void setPreComputedWeight(double preComputedWeight) { this.put(IndexFields.PCWEIGHT, preComputedWeight); } public Boolean isFeatured() { return this.getBoolean(IndexFields.IS_FEATURED, false); } public void setFeatured(Boolean isFeatured) { if (isFeatured == null) { isFeatured = false; } this.put(IndexFields.IS_FEATURED, isFeatured); } public Long getCollectionCount() { return this.getLong(IndexFields.COLLECTION_COUNT, 0L); } public void setCollectionCount(Long collectionCount) { if (collectionCount == null) { collectionCount = 0L; } this.put(IndexFields.COLLECTION_COUNT, collectionCount); } public Long getAssessmentCount() { return this.getLong(IndexFields.ASSESMENT_COUNT, 0L); } public void setAssessmentCount(Long assessmentCount) { if (assessmentCount == null) { assessmentCount = 0L; } this.put(IndexFields.ASSESMENT_COUNT, assessmentCount); } public Long getExternalAsssessmentCount() { return this.getLong(IndexFields.EXTERNAL_ASSESSMENT_COUNT, 0L); } public void setExternalAssessmentCount(Long externalAssessmentCount) { if (externalAssessmentCount == null) { externalAssessmentCount = 0L; } this.put(IndexFields.EXTERNAL_ASSESSMENT_COUNT, externalAssessmentCount); } public Long getContainingCollectionsCount() { return this.getLong(IndexFields.CONTAINING_COLLECTIONS_COUNT, 0L); } public void setContainingCollectionsCount(Long containingCollectionsCount) { if (containingCollectionsCount == null) { containingCollectionsCount = 0L; } this.put(IndexFields.CONTAINING_COLLECTIONS_COUNT, containingCollectionsCount); } public Long getLessonCount() { return this.getLong(IndexFields.LESSON_COUNT, 0L); } public void setLessonCount(Long lessonCount) { if (lessonCount == null) { lessonCount = 0L; } this.put(IndexFields.LESSON_COUNT, lessonCount); } public Long getRemixedInClassCount() { return this.getLong(IndexFields.REMIXED_IN_CLASS_COUNT, 0L); } public void setRemixedInClassCount(Long remixedInClassCount) { if (remixedInClassCount == null) { remixedInClassCount = 0L; } this.put(IndexFields.REMIXED_IN_CLASS_COUNT, remixedInClassCount); } public Long getUsedByStudentCount() { return this.getLong(IndexFields.USED_BY_STUDENT_COUNT, 0L); } public void setUsedByStudentCount(Long usedByStudentCount) { if (usedByStudentCount == null) { usedByStudentCount = 0L; } this.put(IndexFields.USED_BY_STUDENT_COUNT, usedByStudentCount); } public Double getEfficacy() { return this.getDouble(IndexFields.EFFICACY, 0.5); } public void setEfficacy(Double efficacy) { if (efficacy == null) { efficacy = 0.5; } this.put(IndexFields.EFFICACY, efficacy); } public Double getEngagement() { return this.getDouble(IndexFields.ENGAGEMENT, 0.5); } public void setEngagement(Double engagement) { if (engagement == null) { engagement = 0.5; } this.put(IndexFields.ENGAGEMENT, engagement); } public Double getRelevance() { return this.getDouble(IndexFields.RELEVANCE, 0.5); } public void setRelevance(Double relevance) { if (relevance == null) { relevance = 0.5; } this.put(IndexFields.RELEVANCE, relevance); } public Boolean isLibraryContent() { return this.getBoolean("isLibraryContent", false); } public void setLibraryContent(Boolean isLibraryContent) { if (isLibraryContent == null) { isLibraryContent = false; } this.put("isLibraryContent", isLibraryContent); } public Boolean isLMContent() { return this.getBoolean("isLMContent", false); } public void setLMContent(Boolean isLMContent) { if (isLMContent == null) { isLMContent = false; } this.put("isLMContent", isLMContent); } public void setCollaboratorCount(Integer collaboratorCount) { if (collaboratorCount == null) { collaboratorCount = 0; } this.put("collaboratorCount", collaboratorCount); } }
Infectious Bronchitis Virus Immune Responses in the Harderian Gland upon Initial Vaccination SUMMARY. In recent years, Arkansas Delmarva Poultry Industry (ArkDPI)–derived infectious bronchitis (IB) virus (IBV) vaccines have been used to characterize the immune responses of chickens subsequent to vaccination on day of hatch or beyond. Perhaps because ArkDPI vaccines display increased heterogeneity, the results on cell immune responses have shown ambiguity. In the current study, we investigated the effects of vaccination with a highly stable and homogeneous Massachusetts (Mass)-type vaccine on days 1 or 7 of age on Harderian gland (HG) responses. Confirming previous studies, both IBV serum antibodies and lachrymal IgA levels were greater upon vaccination on day 7 compared with vaccination on day 1 of age. Unlike results with ArkDPI viruses, a clear trend was detected for both B and T cells in the HG after Mass-type vaccination. Consistent with antibody responses, B- and T-helper (CD3+CD4+) cell frequencies were higher in birds vaccinated on day 7 of age. Cytotoxic T cells (CD3+CD8+) were also increased compared with chickens vaccinated on day 1 of age. Depending on the most likely age of IB outbreaks to occur in a particular region, postponing the first IBV vaccination may optimize immune responses.
// returns initialized gamma, pi, mu, sigma fn _init(img2d: &Array2<f32>, k: u8) -> (Array2<f32>, Array1<f32>, Array2<f32>, Array1<f32>) { let n = img2d.len(); let mut gamma: Array2<f32> = Array::zeros((n as usize, k as usize)); let mut pi: Array1<f32> = Array::from_elem((k as usize,), 1_f32/k as f32); // Sample k rows from the image data without replacement (a row cannot be repeated) let mut mu = img2d.sample_axis(Axis(0), k as usize, SamplingStrategy::WithoutReplacement); // Sigma is a diagonal array which we will represent as a 1d array let img_flattened_var: f32 = (img2d.var_axis(Axis(1), 0.0)).var_axis(Axis(0), 0.0).into_scalar(); let mut sigma: Array1<f32> = Array::from_elem((k as usize,), 10f32 * img_flattened_var); (gamma, pi, mu, sigma) }
<reponame>stokkie90/octodns # # # from __future__ import absolute_import, division, print_function, \ unicode_literals from requests import HTTPError, Session, post from collections import defaultdict import logging import string import time from ..record import Record from .base import BaseProvider def add_trailing_dot(s): assert s assert s[-1] != '.' return s + '.' def remove_trailing_dot(s): assert s assert s[-1] == '.' return s[:-1] def escape_semicolon(s): assert s return string.replace(s, ';', '\\;') def unescape_semicolon(s): assert s return string.replace(s, '\\;', ';') class RackspaceProvider(BaseProvider): SUPPORTS_GEO = False SUPPORTS = set(('A', 'AAAA', 'ALIAS', 'CNAME', 'MX', 'NS', 'PTR', 'SPF', 'TXT')) TIMEOUT = 5 def __init__(self, id, username, api_key, ratelimit_delay=0.0, *args, **kwargs): ''' Rackspace API v1 Provider rackspace: class: octodns.provider.rackspace.RackspaceProvider # The the username to authenticate with (required) username: username # The api key that grants access for that user (required) api_key: api-key ''' self.log = logging.getLogger('RackspaceProvider[{}]'.format(id)) super(RackspaceProvider, self).__init__(id, *args, **kwargs) auth_token, dns_endpoint = self._get_auth_token(username, api_key) self.dns_endpoint = dns_endpoint self.ratelimit_delay = float(ratelimit_delay) sess = Session() sess.headers.update({'X-Auth-Token': auth_token}) self._sess = sess # Map record type, name, and data to an id when populating so that # we can find the id for update and delete operations. self._id_map = {} def _get_auth_token(self, username, api_key): ret = post('https://identity.api.rackspacecloud.com/v2.0/tokens', json={"auth": { "RAX-KSKEY:apiKeyCredentials": {"username": username, "apiKey": api_key}}}, ) cloud_dns_endpoint = \ [x for x in ret.json()['access']['serviceCatalog'] if x['name'] == 'cloudDNS'][0]['endpoints'][0]['publicURL'] return ret.json()['access']['token']['id'], cloud_dns_endpoint def _get_zone_id_for(self, zone): ret = self._request('GET', 'domains', pagination_key='domains') return [x for x in ret if x['name'] == zone.name[:-1]][0]['id'] def _request(self, method, path, data=None, pagination_key=None): self.log.debug('_request: method=%s, path=%s', method, path) url = '{}/{}'.format(self.dns_endpoint, path) if pagination_key: resp = self._paginated_request_for_url(method, url, data, pagination_key) else: resp = self._request_for_url(method, url, data) time.sleep(self.ratelimit_delay) return resp def _request_for_url(self, method, url, data): resp = self._sess.request(method, url, json=data, timeout=self.TIMEOUT) self.log.debug('_request: status=%d', resp.status_code) resp.raise_for_status() return resp def _paginated_request_for_url(self, method, url, data, pagination_key): acc = [] resp = self._sess.request(method, url, json=data, timeout=self.TIMEOUT) self.log.debug('_request: status=%d', resp.status_code) resp.raise_for_status() acc.extend(resp.json()[pagination_key]) next_page = [x for x in resp.json().get('links', []) if x['rel'] == 'next'] if next_page: url = next_page[0]['href'] acc.extend(self._paginated_request_for_url(method, url, data, pagination_key)) return acc else: return acc def _post(self, path, data=None): return self._request('POST', path, data=data) def _put(self, path, data=None): return self._request('PUT', path, data=data) def _delete(self, path, data=None): return self._request('DELETE', path, data=data) @classmethod def _key_for_record(cls, rs_record): return rs_record['type'], rs_record['name'], rs_record['data'] def _data_for_multiple(self, rrset): return { 'type': rrset[0]['type'], 'values': [r['data'] for r in rrset], 'ttl': rrset[0]['ttl'] } _data_for_A = _data_for_multiple _data_for_AAAA = _data_for_multiple def _data_for_NS(self, rrset): return { 'type': rrset[0]['type'], 'values': [add_trailing_dot(r['data']) for r in rrset], 'ttl': rrset[0]['ttl'] } def _data_for_single(self, record): return { 'type': record[0]['type'], 'value': add_trailing_dot(record[0]['data']), 'ttl': record[0]['ttl'] } _data_for_ALIAS = _data_for_single _data_for_CNAME = _data_for_single _data_for_PTR = _data_for_single def _data_for_textual(self, rrset): return { 'type': rrset[0]['type'], 'values': [escape_semicolon(r['data']) for r in rrset], 'ttl': rrset[0]['ttl'] } _data_for_SPF = _data_for_textual _data_for_TXT = _data_for_textual def _data_for_MX(self, rrset): values = [] for record in rrset: values.append({ 'priority': record['priority'], 'value': add_trailing_dot(record['data']), }) return { 'type': rrset[0]['type'], 'values': values, 'ttl': rrset[0]['ttl'] } def populate(self, zone, target=False, lenient=False): self.log.debug('populate: name=%s', zone.name) resp_data = None try: domain_id = self._get_zone_id_for(zone) resp_data = self._request('GET', 'domains/{}/records'.format(domain_id), pagination_key='records') self.log.debug('populate: loaded') except HTTPError as e: if e.response.status_code == 401: # Nicer error message for auth problems raise Exception('Rackspace request unauthorized') elif e.response.status_code == 404: # Zone not found leaves the zone empty instead of failing. return False raise before = len(zone.records) if resp_data: records = self._group_records(resp_data) for record_type, records_of_type in records.items(): for raw_record_name, record_set in records_of_type.items(): data_for = getattr(self, '_data_for_{}'.format(record_type)) record_name = zone.hostname_from_fqdn(raw_record_name) record = Record.new(zone, record_name, data_for(record_set), source=self) zone.add_record(record) self.log.info('populate: found %s records, exists=True', len(zone.records) - before) return True def _group_records(self, all_records): records = defaultdict(lambda: defaultdict(list)) for record in all_records: self._id_map[self._key_for_record(record)] = record['id'] records[record['type']][record['name']].append(record) return records @staticmethod def _record_for_single(record, value): return { 'name': remove_trailing_dot(record.fqdn), 'type': record._type, 'data': value, 'ttl': max(record.ttl, 300), } _record_for_A = _record_for_single _record_for_AAAA = _record_for_single @staticmethod def _record_for_named(record, value): return { 'name': remove_trailing_dot(record.fqdn), 'type': record._type, 'data': remove_trailing_dot(value), 'ttl': max(record.ttl, 300), } _record_for_NS = _record_for_named _record_for_ALIAS = _record_for_named _record_for_CNAME = _record_for_named _record_for_PTR = _record_for_named @staticmethod def _record_for_textual(record, value): return { 'name': remove_trailing_dot(record.fqdn), 'type': record._type, 'data': unescape_semicolon(value), 'ttl': max(record.ttl, 300), } _record_for_SPF = _record_for_textual _record_for_TXT = _record_for_textual @staticmethod def _record_for_MX(record, value): return { 'name': remove_trailing_dot(record.fqdn), 'type': record._type, 'data': remove_trailing_dot(value.exchange), 'ttl': max(record.ttl, 300), 'priority': value.preference } def _get_values(self, record): try: return record.values except AttributeError: return [record.value] def _mod_Create(self, change): return self._create_given_change_values(change, self._get_values(change.new)) def _create_given_change_values(self, change, values): transformer = getattr(self, "_record_for_{}".format(change.new._type)) return [transformer(change.new, v) for v in values] def _mod_Update(self, change): existing_values = self._get_values(change.existing) new_values = self._get_values(change.new) # A reduction in number of values in an update record needs # to get upgraded into a Delete change for the removed values. deleted_values = set(existing_values) - set(new_values) delete_out = self._delete_given_change_values(change, deleted_values) # An increase in number of values in an update record needs # to get upgraded into a Create change for the added values. create_values = set(new_values) - set(existing_values) create_out = self._create_given_change_values(change, create_values) update_out = [] update_values = set(new_values).intersection(set(existing_values)) for value in update_values: transformer = getattr(self, "_record_for_{}".format(change.new._type)) prior_rs_record = transformer(change.existing, value) prior_key = self._key_for_record(prior_rs_record) next_rs_record = transformer(change.new, value) next_key = self._key_for_record(next_rs_record) next_rs_record["id"] = self._id_map[prior_key] del next_rs_record["type"] update_out.append(next_rs_record) self._id_map[next_key] = self._id_map[prior_key] del self._id_map[prior_key] return create_out, update_out, delete_out def _mod_Delete(self, change): return self._delete_given_change_values(change, self._get_values( change.existing)) def _delete_given_change_values(self, change, values): transformer = getattr(self, "_record_for_{}".format( change.existing._type)) out = [] for value in values: rs_record = transformer(change.existing, value) key = self._key_for_record(rs_record) out.append('id=' + self._id_map[key]) del self._id_map[key] return out def _apply(self, plan): desired = plan.desired changes = plan.changes self.log.debug('_apply: zone=%s, len(changes)=%d', desired.name, len(changes)) # Creates, updates, and deletes are processed by different endpoints # and are broken out by record-set entries; pre-process everything # into these buckets in order to minimize the number of API calls. domain_id = self._get_zone_id_for(desired) creates = [] updates = [] deletes = [] for change in changes: if change.__class__.__name__ == 'Create': creates += self._mod_Create(change) elif change.__class__.__name__ == 'Update': add_creates, add_updates, add_deletes = self._mod_Update( change) creates += add_creates updates += add_updates deletes += add_deletes else: assert change.__class__.__name__ == 'Delete' deletes += self._mod_Delete(change) if deletes: params = "&".join(sorted(deletes)) self._delete('domains/{}/records?{}'.format(domain_id, params)) if updates: data = {"records": sorted(updates, key=lambda v: v['name'])} self._put('domains/{}/records'.format(domain_id), data=data) if creates: data = {"records": sorted(creates, key=lambda v: v['type'] + v['name'] + v.get('data', ''))} self._post('domains/{}/records'.format(domain_id), data=data)
<gh_stars>10-100 package zamorozka.notification; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.ScaledResolution; import zamorozka.ui.font.CFontRenderer; public class Notification { public static final int HEIGHT = 30; private final String title; private final String content; private final int time; private final NotificationType type; private final NotificationTimer timer; private final Translate2 translate; private final CFontRenderer fontRenderer; public double scissorBoxWidth; public Notification(String title, String content, NotificationType type, CFontRenderer fontRenderer) { this.title = title; this.content = content; this.time = 1200; this.type = type; this.timer = new NotificationTimer(); this.fontRenderer = fontRenderer; ScaledResolution sr = new ScaledResolution(Minecraft.getMinecraft()); this.translate = new Translate2((sr.getScaledWidth() - getWidth()), (sr.getScaledHeight() - 30)); } public final int getWidth() { return Math.max(100, Math.max(this.fontRenderer.getStringWidth(this.title), this.fontRenderer.getStringWidth(this.content)) + 80); } public final String getTitle() { return this.title; } public final String getContent() { return this.content; } public final int getTime() { return this.time; } public final NotificationType getType() { return this.type; } public final NotificationTimer getTimer() { return this.timer; } public Translate2 getTranslate() { return translate; } }
Trading in all securities has been temporarily suspended on the New York Stock Exchange. The exchange posted the news on its website, saying "additional information will follow as soon as possible." The halt began at 11:32 a.m. Eastern. In a statement the NYSE said it was working to restore trading activity. "We're currently experiencing a technical issue that we're working to resolve as quickly as possible. We will be providing further updates as soon as we can, and are doing our utmost to produce a swift resolution, communicate thoroughly and transparently, and ensure a timely and orderly market re-open," said a NYSE spokeswoman via email. Trading on other exchanges appeared to be normal. Have breaking news sent to your inbox. Subscribe to MarketWatch's free Bulletin emails. Sign up here.
// contentWorker processes items from contentQueue. It must run only once, // syncContent is not assured to be reentrant. func (ctrl *csiSnapshotSideCarController) contentWorker() { workFunc := func() bool { keyObj, quit := ctrl.contentQueue.Get() if quit { return true } defer ctrl.contentQueue.Done(keyObj) key := keyObj.(string) klog.V(5).Infof("contentWorker[%s]", key) _, name, err := cache.SplitMetaNamespaceKey(key) if err != nil { klog.V(4).Infof("error getting name of snapshotContent %q to get snapshotContent from informer: %v", key, err) return false } content, err := ctrl.contentLister.Get(name) if err == nil { if ctrl.isDriverMatch(content) { ctrl.updateContentInCacheStore(content) } return false } if !errors.IsNotFound(err) { klog.V(2).Infof("error getting content %q from informer: %v", key, err) return false } contentObj, found, err := ctrl.contentStore.GetByKey(key) if err != nil { klog.V(2).Infof("error getting content %q from cache: %v", key, err) return false } if !found { klog.V(2).Infof("deletion of content %q was already processed", key) return false } content, ok := contentObj.(*crdv1.VolumeSnapshotContent) if !ok { klog.Errorf("expected content, got %+v", content) return false } ctrl.deleteContentInCacheStore(content) return false } for { if quit := workFunc(); quit { klog.Infof("content worker queue shutting down") return } } }
package log import ( "os" log "github.com/sirupsen/logrus" ) func init() { customFormatter := new(log.TextFormatter) customFormatter.TimestampFormat = "2006-01-02 15:04:05.000" customFormatter.FullTimestamp = true customFormatter.DisableLevelTruncation = true log.SetFormatter(customFormatter) logLevelStr, ok := os.LookupEnv("LOG_LEVEL") if !ok { logLevelStr = "debug" } logLevel, err := log.ParseLevel(logLevelStr) if err != nil { logLevel = log.DebugLevel } log.SetLevel(logLevel) }
For GOP moderates and would-be Republican Party reformers, the 2016 presidential election is now a disaster beyond repair. Despite growing talk of a “brokered” convention, the party’s two most likely nominees are still Donald Trump and Sen. Ted Cruz – one a trainwreck of a reality TV star and the other a favorite son of the Tea Party. But when the moment finally comes to sift through the wreckage, the best guidance for GOP reformers might come from Democrats: in particular, the 1992 campaign of former President Bill Clinton. Crashing the Party, a new documentary chronicling Clinton’s ascent from unknown governor to President, is must-watch viewing for Republican reformers, were they to undertake the project of reform from within (and assuming anyone’s left to do so). But the film also shows just how far Republicans have to go – potentially decades – before the rebuilding of a post-Trump GOP can succeed. As Crashing the Party points out, it wasn’t so long ago that the Democratic Party was itself in dire electoral straits. In November 1988, Democrats had suffered their third straight humiliation at the presidential polls, with the defeat of Massachusetts governor Michael Dukakis to George H.W. Bush. Before then, President Ronald Reagan had won crushing victories over both Jimmy Carter in 1980 and Walter Mondale in 1984. In fact, the only state Mondale managed to win was his home state of Minnesota, along with the District of Columbia. Reagan’s electoral victory over Mondale was absolute, 525 to 13, and Dukakis’ performance against Bush was little better, 426 to 111. Yet just four years after Dukakis’ loss, Clinton managed to wrest the White House into Democratic hands. The behind-the-scenes story of the how and why of Clinton’s victory in 1992 is the focus of Crashing the Party, which premiered last weekend at the Annapolis Film Festival. The bulk of the film documents the instrumental role of the now-defunct Democratic Leadership Council (DLC), the organization founded by Al From that first plucked Clinton from obscurity, provided him with a national platform and groomed him for his run at the presidency. Among other factors, the film argues, the success of Clinton’s 1992 campaign depended upon three crucial ingredients: ideas, infrastructure and clarity of political mission. These are the same three ingredients that the GOP establishment currently fails to possess – and a big part of why it’s so far been unable to offer a viable alternative to Trump on the one hand and the Tea Party on the other. Clinton’s slate of ideas, developed by the DLC and its affiliated think tank, the Progressive Policy Institute (PPI), were intended to set Clinton and his fellow “New Democrats” apart from standard-issue Democrats of the era. (Disclosure: I was a staffer for PPI from 2000 to 2003 and remain a PPI Senior Fellow.) Among the ideas espoused by the New Democrats – some of which sound dated today but many of which are now part of the progressive bloodstream – were national service, community policing, welfare reform, and “making work pay” by expanding the Earned Income Tax Credit for low-income families. Unlike other Democrats, the New Democrats focused on “reinventing” government, not just expanding it. And in contrast to Dukakis, assailed as both soft on crime and soft on defense – a perception bolstered by his ill-fated photo op in a tank – the New Democrats were relatively hawkish on crime and national security. The New Democrat mantra of “opportunity, responsibility and community” – which again might sound cliché today – was a radical effort to reject the “tax and spend” branding that saddled Democrats at the time. It was enough for Clinton to win back the “Reagan Democrats” and the white working class – the same groups vulnerable to Trump’s appeal today. The second major advantage that the DLC provided Clinton was infrastructure: a robust network of federal, state and local policymakers ready to amplify the New Democratic platform and to serve as a beachhead within the Democratic Party establishment. These figures included such heavyweights as Virginia Gov. Chuck Robb, Georgia Sen. Sam Nunn, eventual Vice Presidential nominee Al Gore and Rep. Dick Gephardt. Over time, the DLC coalition in Congress included dozens of House members and senators, many of them from suburban swing districts and purple states and who had felt excluded from the shrinking Democratic tent of the 1980s. Among the innovations of the DLC was to create an annual “national conversation,” which brought together elected officials at all levels of government to cross-pollinate ideas and helped incubate up-and-coming talent. A number of the state and local officials who took part of these early efforts are now on the national stage, including New Jersey Sen. Cory Booker, Delaware Gov. Jack Markell and even Vice President Joe Biden. But while Crashing the Party is useful guidance for Republicans eager to rebuild their brand, it will be many years before there is an “RLC” capable of restoring the GOP’s credibility. For one thing, today’s mainstream GOP is bereft of fresh ideas that can capture the broad middle of the electorate. By spending the last eight years either opposing President Obama’s policies or pandering to the far right, Republicans have forgotten how to offer proactive solutions of their own. Obstruction is not an agenda. Moreover, the few ideas on social policy that have emerged from House Speaker Paul Ryan and cultural conservatives around welfare reform have done little more than to reinforce perceptions of a tightfisted, mean brand of conservatism out of step with the suffering of ordinary Americans. Nor does the GOP reform “movement” – such as there is – have a coherent infrastructure and network that can draw together likeminded thinkers and policymakers into an organized force. While the so-called “reformicons” have won some attention, they are still little more than a loosely organized group of think tankers and writers. They have no discernible power base among elected officials, no network of powerful supporters and spokesmen, and certainly no standard-bearer equivalent to Bill Clinton. But the most powerful missing ingredient might be the lack of political clarity. The DLC was founded in 1985 as the culmination of years of frustration with the Democratic Party’s increasingly narrow tilt. But it wasn’t until that third straight loss with Dukakis that the DLC was able to make its case that a presidency could not be won simply by mobilizing narrow constituencies and catering to special interests. Moderates and the middle class had to be part of the coalition. In that sense, the best thing that could happen for the GOP this November is to lose – to let Trump or Cruz be the Republicans’ Dukakis and to suffer a crushing defeat. That alone could propel the GOP’s nascent efforts at reform from “lost cause” to a true “movement.” While the ultimate result could be more discomfort for Democrats, a new, reform-minded GOP would still be a benefit for democracy.
// *********************************************** // // Simpler defs, should use more structural typing // // ************************************************ declare let Object : any; export var GRAZY_PREFIX = 'grazy'; export var GRAZY_IRI = 'https://github.com/DavidLeoni/grazy/'; /** * Usage: callConstructor(MyConstructor, arg1, arg2); */ export var callConstructor = function(constr) { var factoryFunction = constr.bind.apply(constr, arguments); return new factoryFunction(); }; /** Immutable. Adopts JsonLD tags. */ export class GraphNode { "@id": string; "@reverse": { [key: string]: GraphNode[] }; } export var EmptyGraph: GraphNode = { "@id": GRAZY_IRI + "empty-node", "@reverse": <any>[] }; /** * Usage: applyToConstructor(MyConstructor, [arg1, arg2]); */ export var applyToConstructor = function(constr, argArray) { var args = [null].concat(argArray); var factoryFunction = constr.bind.apply(constr, args); return new factoryFunction(); }; export enum ObjStatus { COMPLETED, TO_CALCULATE, ERROR } /** * Returns true if two objects are structurally equal. * todo need spec-like version, this one is already 'too efficient' */ export let eq = function (a : Obj, b : Obj) : boolean { let t = Object.is(a, b); if (!t){ for (let key of Object.keys(a)){ if (!eq(a[key], a[key])){ return false; } } } return true; } /** * todo p1 add decorator for creating withers, * see http://stackoverflow.com/questions/31224574/generate-generic-getters-and-setters-for-entity-properties-using-decorators */ export class Obj { // cannot write T extends Obj... __features : {[key:string] : boolean} private __status = ObjStatus.TO_CALCULATE; /** * Eventual error is status is 'ERROR' */ private __error: Err = Errors.NONE; private __clone(): this { let ret = {}; for (let k of Object.keys(this)) { ret[k] = this[k]; } return <any> ret; } protected _as(err: Err): this { let ret = this.__clone(); ret.__status = ObjStatus.ERROR; if (err) { ret.__error = err; } else { ret.__error = new Err(new Error(), "Tried to set error on ", this, " but forgot to pass Err object!!"); } return ret; } protected _error(): Err { return this.__error; } protected _features(): {[key:string]:Feature} { return this.__features; } protected _status(): ObjStatus { return this.__status; } constructor() { this.__status = ObjStatus.TO_CALCULATE; this.__error = Errors.NONE; } /** * Returns new object with property prop set to v. Property MUST belong to object type definition propoerties * TODO this currently doesn't do any type checking (sic), maybe maybe we can fix it. * Also, for output type, see https://github.com/Microsoft/TypeScript/issues/285 * See also 'Compile-time checking of string literal arguments based on type': https://github.com/Microsoft/TypeScript/issues/394 * 'nameof' operator support: https://github.com/Microsoft/TypeScript/issues/1579 * */ with(prop: string, v: any): this { let ret = this.__clone(); ret[prop] = v; return ret; } } export class Feature { } export interface Finite extends Feature { __features : {finite :true} } export interface Infinite extends Feature { __features : {finite : false} } /** * This class encapsulates Javascript Error object. It doesn't extend it because all the error inheritance stuff * in Javascript is really fucked up. * */ export class Err extends Obj { name: string; message: string; error: Error; params: any[]; /** * You must pass a JavaScript Error so browser can keep track of stack execution. Message in original error is not considered. * Usage example: new GrazyErr(new Error(), "We got a problem!", "This object looks fishy: ", {a:666}); * @param message Overrides message in Error. */ constructor(error: Error, message, ...params) { super(); // console.error.apply(null, params); this.name = (<any>this.constructor).name; this.message = message; this.error = error; this.params = params; } toString() { return this.allParams().join(""); } /** * Returns array with name, message plus all params */ allParams(): any[] { var ret = this.params.slice(0) var afterMsg = "\n"; if (this.params.length > 0) { afterMsg = "\n"; } ret.unshift(this.message + afterMsg); ret.unshift(this.name + ":"); return ret; } /** Reports the error to console with console.log */ consoleLog(): void { console.log.apply(console, this.allParams()); console.log(this.error); } /** Reports the error to console with console.error */ consoleError(): void { var completeParams = this.allParams().slice(0); completeParams.push(" \n", this.error); console.error.apply(console, completeParams); } } export module Errors { export let NONE = new Err(null, ""); } export class EqErr extends Err { constructor(error: Error, actual) { super(error, "Failed assertion!", " Expected something different than ->", actual, "<-\n"); this.actual = actual; } actual: any; } export class NotEqErr extends Err { constructor(error: Error, expected, actual) { super(error, "Failed assertion!", " Expected ->", expected, "<-\n", " Actual ->", actual, "<-"); this.expected = expected; this.actual = actual; } actual: any; expected: any; } export module Objs { export let empty = new Obj(); } export class Bool extends Obj { } /** * A lazy sequence, possibly infinite */ export class Seq<T extends Obj> extends Obj { first(): T { throw new Error("Subclasses must implment me!"); }; next(): Seq<T> { throw new Error("Subclasses must implment me!"); }; size(): SuperNat { throw new Error("Subclasses must implment me!"); }; } /** * A finite list */ export class List<T extends Obj> extends Seq<T> { next(): List<T> { throw new Error("Descendants should implement this method!"); }; size(): Nat { throw new Error("Descendants should implement this method!"); } } export class Cons<T extends Obj> extends List<T> { _next: List<T>; next(): List<T> { return this._next; } size(): Nat { return Nats.one.plus(this.next().size()); } } export let list = function <T extends Obj>(...args: T[]): List<T> { if (args.length === 0) { return nil; } } export class TNil<T extends Obj> extends List<T> { /** [].pop() returns undefined . I will be less forgiving. */ first(): T { return <any> this._as(new Err(new Error(), "Tried to call first() on empty list!")); }; size(): NatZero { return Nats.zero; } /** [1,2].slice(2,2) returns [] . I will be less forgiving. */ next(): List<T> { return this._as(new Err(new Error(), "Tried to call next() on empty list!")); }; } export type Nil = TNil<any>; export let nil: Nil = new TNil(); /** * A possibly infinite natural number >= 0 */ export class SuperNat extends Seq<Nil> { next(): SuperNat { throw new Error("Subclasses must implment me!"); }; plus(n: SuperNat): SuperNat { throw new Error("Subclasses must implment me!"); }; size(): SuperNat { return this; } } /** * Here it is, the evil infinity */ export class NatInfinity extends SuperNat { first(): Nil { return nil; } next(): NatInfinity { return this; } plus(n: SuperNat): NatInfinity { return this; } size() { return this; } } /* export function if_(c: Bool, th: Expr, el: Expr) { } */ /** * A finite natural number >= 0 */ export class Nat extends SuperNat { // Should return itself! size(): Nat { return this; } plus(n: Nat): Nat plus(n: SuperNat): SuperNat { return this; } } export class NatPositive extends Nat { private _next: Nat; constructor(n: Nat) { super(); this._next = n; } plus(n: Nat): NatPositive; plus(n: SuperNat): SuperNat { if (n instanceof NatInfinity) { return n; } else if (eq(this._next, Nats.zero)) { return new NatPositive(<Nat> n); } else { return new NatPositive(this._next.plus(<Nat> n)); } } first(): Nil { return <any> this._as(new Err(new Error(), "Tried to get next() of zero!")); } next(): Nat { return <any> this._as(new Err(new Error(), "Tried to get next() of zero!")); } size(): NatPositive { return this; } } export class NatZero extends Nat { constructor (){ super(); } plus(n: NatZero): NatZero plus(n: NatPositive): NatPositive plus(n: Nat): Nat plus(n: SuperNat): SuperNat { if (n instanceof NatZero) { return this; } else { return <any> n; } } first(): Nil { return <any> this._as(new Err(new Error(), "Tried to get next() of zero!")); } next(): Nat { return <any> this._as(new Err(new Error(), "Tried to get next() of zero!")); } size(): NatZero { return this; } } export class NatOne extends NatPositive { constructor(){ super(Nats.zero); } first(): Nil { return nil; } next(): NatZero { return Nats.zero; } size(): NatOne { return this; } } export module Nats { export const zero: NatZero = new NatZero(); export const one: NatOne = new NatOne(); export const two: NatPositive = <any> one.plus(one); // todo remove stupid any export const infinity: NatInfinity = new NatZero(); } /** * Takes a variable number of arguments and displays them as concatenated strings in an alert message, plus it calls console.error with the same arguments. Usage example: * signal(new Error(), "We got a problem", "Expected: ", 3, " got:", 2 + 2); * @returns {GrazyErr} */ export var report = function(error: Error, ...args) { var i; var arr = []; for (i = 0; i < arguments.length; i++) { arr.push(arguments[i]); } var exc = applyToConstructor(Err, arr); exc.toConsole(); alert(exc.toString() + "\n\nLook in the console for more details."); return exc; }; /** * Visits nodes of type N and outputs type M */ export interface TreeVisitor<N, M> { getChildren(t: N): N[]; } export module test { /** * Uses Javascript's Object.is * * Doesn't throw any exception, * @return null if no error occurred */ export function assertIs(expected, actual): Err { var res = Object.is(expected, actual); if (res) { return null; } else { return new NotEqErr(new Error(), expected, actual); } } /** * Returns EqErr in case actual is equals to notExpected. Uses Javascript Object.is * Doesn't throw any exception * @return null if no error occurred */ export function assertNotIs(notExpected, actual): Err { var res = Object.is(notExpected, actual); if (res) { return new EqErr(new Error(), actual); } else { return null; } } /** * Doesn't throw any exception, * @return null if no error occurred */ export function assertEq(expected : Obj, actual : Obj): Err { var res = eq(expected, actual); if (res) { return null; } else { return new NotEqErr(new Error(), expected, actual); } } /** * Returns EqErr in case actual is equals to notExpected. * Doesn't throw any exception * @return null if no error occurred */ export function assertNotEq(notExpected : Obj, actual : Obj): Err { var res = eq(notExpected, actual); if (res) { return new EqErr(new Error(), actual); } else { return null; } } export class TestResult { testName: string test: any; // todo should be a method sig error: Err; constructor(testName, test, error?: Err) { this.testName = testName; this.test = test; this.error = error; } } export class TestSuite { tests: any; name: string; testResults: TestResult[]; passedTests: TestResult[]; failedTests: TestResult[]; constructor(name: string, tests) { this.testResults = []; this.passedTests = []; this.failedTests = []; this.name = name; this.tests = tests; } run() { this.testResults = []; this.passedTests = []; this.failedTests = []; for (var key in this.tests) { var grazyErr: Err = null; try { grazyErr = this.tests[key](); } catch (catchedError) { if (catchedError instanceof Err) { grazyErr = catchedError; } else { grazyErr = new Err(catchedError, "Test threw an Error!"); } } var testRes = new TestResult(key, this.tests[key], grazyErr); this.testResults.push(testRes); if (grazyErr) { this.failedTests.push(testRes); } else { this.passedTests.push(testRes); } } } } } export module Trees { /** * Recursively applies function makeM to a node of type N and * M-fied children of type M, so the resulting tree will have type M * @param getChildren leaf nodes have zero children * @param makeM function that takes node to M-ify, * the field name (or index) that was holding it * and its now M-fied children */ export function fold<N, M>(rootNode: N, getChildren: (t: N) => N[], makeM: (field, t: N, children: M[]) => M): M { var processedNodesCounter = 0; /** Holds original nodes */ var stack1 = [{ key: null, node: rootNode }]; // only rootNode should have null as key /** Holds nodes-as-expressions that still need to be completely filled with M-fied children */ var stack2: { key: any; node: N; neededChildren: number; children: any[]; //[<any, M>] }[] = []; /** Inserts node to existing children container in top entry of stack2. If inserting the node fills the children container, resolves expressions popping nodes in stack2. If stack2 gets empty returns last calculated expression, otherwise return null. */ var nodeToStack2 = (key: any, node: N): M => { var toInsert = makeM(key, node, []); var curKey = key; while (stack2.length > 0) { var top2 = stack2[0]; top2.children.unshift([curKey, toInsert]); if (top2.children.length > top2.neededChildren) { throw new Err(new Error(), "Found more children in top2 than the needed ones!", "stack1: ", stack1, "top2 =", top2, "stack2: ", stack2); } if (top2.neededChildren === top2.children.length) { stack2.shift(); toInsert = makeM(top2.key, top2.node, top2.children); curKey = top2.key; } else { return null; } } return toInsert; // stack2.length = 0 } var ret: M; while (stack1.length > 0) { var el = stack1.shift(); var children = getChildren(el.node); if (children.length === 0) { // leaf node ret = nodeToStack2(el.key, el.node); if (stack1.length === 0) { if (stack2.length > 0) { throw new Err(new Error(), "Found non-empty stack2: ", stack2); } return ret; } else { if (stack2.length === 0) { return ret; } else { if (ret) { throw new Err(new Error(), "ret should be null, found instead ", ret); } } } } else { // non-leaf nosde children.forEach((c, k) => { stack1.unshift({ node: c, key: k }); }); var childrenContainer = []; var toStack2 = { node: el.node, key: el.key, neededChildren: children.length, children: childrenContainer }; stack2.unshift(toStack2); } } throw new Error("Shouldn't arrive till here..."); //return makeM(null, null, null); } export function height<N>(node: N, getChildren: (t: N) => N[]): number { return Trees.fold(node, getChildren, (parentField, n, cs: number[]) => { return cs.length === 0 ? 0 : Math.max.apply(null, cs) + 1; }) } }
<reponame>vhnatyk/vlsistuff<filename>vcd_python_c/vcd.py import os,sys,string New = os.path.expanduser('~/verification_libs3') sys.path.append(New) import logs import veri BASE = 'tb' CLK = BASE + '.clk' def peeklocal(Sig,Base=BASE): return logs.peek('%s.%s'%(Base,Sig)) Totals = {'aw':0,'ar':0,'dw':0,'dr':0} def negedge(): Time = veri.stime() awvalid = peeklocal('awvalid') awready = peeklocal('awready') if (awvalid==1)and(awready==1): veri.force('aaa',str(Time & 0x1f)) veri.force('bbb',str(~Time & 0x1f)) awaddr = peeklocal('awaddr') awsize = peeklocal('awsize') awlen = peeklocal('awlen') Totals['aw'] += (awlen+1)*(1<<awsize) logs.log_info('#%d aw addr=%x size=%s len=%s totaw=%d '%(Time,awaddr,awsize,awlen,Totals['aw'])) if (peeklocal('wvalid')==1)and(peeklocal('wready')==1): wstrb = peeklocal('wstrb') wdata = peeklocal('wdata') wlast = peeklocal('wlast') wlast = peeklocal('wlast') bytes = logs.countOnes(wstrb) Totals['dw'] += bytes logs.log_info('#%d wd data=%x wstrb=%x last=%d totdw=%d'%(Time,wdata,wstrb,wlast,Totals['dw'])) arvalid = peeklocal('arvalid') arready = peeklocal('arready') if (arvalid==1)and(arready==1): araddr = peeklocal('araddr') arsize = peeklocal('arsize') arlen = peeklocal('arlen') arid = peeklocal('arid') Keep['arid']=arsize Totals['ar'] += (arlen+1)*(1<<awsize) logs.log_info('#%d ar addr=%x size=%s len=%s totar=%d'%(Time,araddr,arsize,arlen,Totals['ar'])) if (peeklocal('rvalid')==1)and(peeklocal('rready')==1): rdata = peeklocal('rdata') rlast = peeklocal('rlast') rid = peeklocal('rid') Totals['rd'] += (1<<Keep[rid]) logs.log_info('#%d rd data=%x rlast=%x totrd=%d'%(Time,rdata,rlast,Totals['rd'])) monitorCommands(Time) def monitorCommands(Time): if peeklocal('cmd_rd')==1: bytes = peeklocal('cmd_bytes') rmt_addr = peeklocal('cmd_rmt_addr') rmt_size = peeklocal('cmd_rmt_size') logs.log_info('command read bytes=%d from=0x%x size=%d'%(bytes,rmt_addr,rmt_size)) if peeklocal('cmd_wr')==1: bytes = peeklocal('cmd_bytes') rmt_addr = peeklocal('cmd_rmt_addr') rmt_size = peeklocal('cmd_rmt_size') logs.log_info('command write bytes=%d to=0x%x size=%d'%(bytes,rmt_addr,rmt_size)) def monApb(): if peeklocal('dma_psel')!=1: return if peeklocal('penable')!=1: return pwrite = peeklocal('pwrite') paddr = peeklocal('paddr') if pwrite==1: pwdata = peeklocal('pwdata') logs.log_info('apb write addr=%04x data=%08x'%(paddr,pwdata)) else: prdata = peeklocal('prdata') logs.log_info('apb read addr=%04x data=%08x'%(paddr,prdata)) # this is how it is connected to the C engine.. veri.sensitive(CLK,'0',"negedge()")
def import_proposal(request, proposal_id, award_pk): award = get_object_or_404(Award, pk=award_pk) try: existing_proposal = Proposal.objects.get(proposal_id=proposal_id) except Proposal.DoesNotExist: existing_proposal = None if existing_proposal: if existing_proposal.award: messages.error(request, "%s is already tied to this award. If you \ need to associate it with another award, contact an administrator." % existing_proposal) return redirect(existing_proposal.award) else: existing_proposal.delete() try: cayuse_data = get_cayuse_summary(proposal_id) pi = get_cayuse_pi( cayuse_data['principal_investigator'], cayuse_data['proposal']['employee_id']) except EASMappingException as e: eas_mapping_url = reverse( 'create_eas_mapping', kwargs={ 'interface': e.interface, 'field': e.field, 'incoming_value': e.incoming_value, 'atp_model': e.atp_model.__name__}) request.session['import_url'] = request.path return HttpResponseRedirect(eas_mapping_url) proposal = Proposal.objects.create( principal_investigator=pi, award=award, **cayuse_data['proposal']) [setattr(pi, key, value) for key, value in cayuse_data['principal_investigator'].items()] pi.save() key_personnel = get_key_personnel(proposal_id) [KeyPersonnel.objects.create(proposal=proposal, **person) for person in key_personnel] performance_sites = get_performance_sites(proposal_id) [PerformanceSite.objects.create(proposal=proposal, **site) for site in performance_sites] return redirect(award)
Genotypic and allelic frequency of a mutation in the NHEJ1 gene associated with collie eye anomaly in dogs in Italy Abstract Background A 7.8‐kb deletion in intron 4 of the NHEJ1 canine gene is associated with Collie Eye Anomaly (CEA). This deletion has been described in sheep‐herding breeds related to the collie lineage and in several other dog breeds. A genetic test based on this association can distinguish three genotypes: normal, carrier and affected. The present study is a retrospective investigation of the presence of the CEA allele frequencies in selected breeds from the Italian dog population over a 10‐year time span. Methods Genotype data, for the 7.8 kb deletion in intron 4 of the NHEJ1 gene, from 496 dogs belonging to Border collie (BC, n = 334), Shetland Sheepdog (SS, n = 74), Australian Shepherd (AS, n = 52), Nova Scotia Duck Tolling Retriever (NS, n = 20) and Rough Collie (RC, n = 16) were analysed. The genetic frequency of CEA allele was estimated in breeds with higher observations (BC, SS and AS). Results Healthy carriers were 50%, 45%, 29.6%, 17.3% and 12.5% in SS, NS, BC, AS and RC, respectively. The affected recessive homozygotes were 81.3%, 10.8% and 1.5% in RC, SS and BC, respectively. The CEA allelic frequencies were 0.36, 0.16 and 0.087 in SS, BC and AS, respectively. Conclusion The results support the usefulness of this type of genetic analysis to optimize the care of dogs where the CEA mutation is present, including assessing the health risk to susceptible dogs within a breed and to provide an objective basis for breeding programmes. INTRODUCTION Collie Eye Anomaly (CEA) is a hereditary oculopathy affecting the development of the choroid and sclera. British sheep-herding breeds and their descendants are reported to frequently carry the mutation of the NHEJ gene associated with CEA. 1 The CEA mutation is also recorded in several other breeds. 2 Worldwide it is reported that CEA in collie breeds is the most common inherited retinal disease (70-90%). 1 The mode of inheritance for CEA is autosomal recessive with incomplete penetrance. 2 A 7.8-kb deletion in intron 4 of the NHEJ canine gene is associated with CEA. The clinical phenotype varies considerably: many dogs exhibit no obvious clinical signs and have normal vision throughout life, whereas other phenotypes that are defined as "severely affected" can develop secondary intraocular haemorrhage, retinal detachment and blindness. CEA may be associated with several, more evident anomalies in the eye. Microphthalmia presents with eyeballs that are reduced in size and functionality. Enophthalmia presents as eyeballs that are placed deep into the eye sockets. Mineralization in the cornea is frequently observed and leads to cloudiness. In more advanced stages of the disease, there may be a defect in some structures of the eye called coloboma. In the final stages of the disease detachment of the retina with blindness may occur. CEA is considered homologous to macular coloboma in humans. Comparative analysis of the NHEJ1 region in the genomes of dog, human, mouse and rat have demonstrated conserved binding sites for several DNA-binding proteins in this location. 3 Through the genetic test, it is possible to identify CEA affected dogs, recessive homozygotes (carriers) and clinically healthy dogs. 3 The primary aim of the present study was a retrospective investigation of the presence of the CEA mutated gene in the Italian dog population over a 10-year period (2010-2019). Secondary aims including recording the age at which testing was performed and to assess the frequency of the CEA mutation in selected breeds. To the best of the authors' knowledge, it is the first survey about breed-specific distribution of the CEA mutation in Italy. Analysis of the CEA status of the selected breeds, particularly those used for sheep farming, is important to help reduce The data used in this retrospective analysis were obtained by the Vetogene Lab, one of the official reference laboratories for the Italian Kennel Club ENCI (FCI associate) and were referred to all dogs genotyped at NHEJ locus for CEA from 1 January, 2010 to 31 March, 2019, as part of a genetic improvement and safeguard programme for dog breeds bred in Italy. Blood samples were collected from the cephalic vein and were sent for the genetic test analysis by veterinarians who officially certified the identification of the sample through microchip control. The DNA extraction was obtained from 100 to 200 µL of whole blood samples using the commercial kit Qiagen DNeasy Blood & Tissue kit (Qiagen, Hilden, Germany). The presence of the 7.8-kb deletion (37:28,697,542 -28,705,340) in the NHEJ gene (Entrez Gene ID 610570) was tested by PCR, in Vetogene Lab, using primers as previously described. 3 Analyses were conducted using the SAS 9.4 software (SAS Inc., Cary, NC, USA). First, frequencies relative to healthy, carrier, and affected dogs in the available breeds were described. Differences in age at test among breeds were analyzed by Kruskall-Wallis test using the PROC NPAR1WAY. As a second step, dogs from breeds where more than 20 dogs were sampled were considered. Annual proportions of healthy, carrier, and affected dogs for each breed were calculated and genetic frequencies were estimated. For these analyses, PROC FREQ and PROC ALLELE procedures of SAS were used. In the breeds with numbers > 20 (AS, BC, SS) the trend in the proportion of carriers for AS and BC showed a decrease towards the end the study period (Figures 1, 2 and 3). In the SS breed, the presence of carriers varied and peaked in the years 2011, 2013 and 2016 (Figure 3). For the whole study population, the blood samples were collected at an overall age of 2.44 ±1.95 years. The average age at which NS, BC, AS dogs were genotyped was 2.9 ± 2.4, 2.7 ± 2.0, and 2.2 ± 1.8 years, respectively and was statistically different (p < 0.05) from that recorded for SS (1.5 ± 1.5 years) and RC (1.1 ± 1.2 years). The age range was wide especially for the AS, BC and NS breeds, and some dogs were over 9 years of age when tested (Figure 4). Gene frequencies are reported in Table 2. Excluding the NS and RC breeds that had <20 dogs tested, it was found that the Veterinary Record Open  DISCUSSION In our study, the BC and AS breeds were the most common sheep-herding breeds recorded in Italy, at least given that they had the largest number of animals registered with the Italian Kennel Club studbook. The study population, for 2019, comprised BC 46.7%, AS 41.2%, and all of the other breeds comprised 12.1%. 4 In BC, a relatively high percentage of carriers (29.64%) was detected, compared to very few affected subjects (1.5%). Our data are in accordance with those reported in the Czech Republic (33.8% of carriers and 2% of affected). 5 In two surveys a lower percentage (equal to 9% and 1.05%) of affected BCs were respectively reported in Switzerland 6 and Belgium. 7 It is important to notice that compared to the annual numbers of animals registered every year, BC represents one of the most controlled breeds, with breeding choices aimed to exclude carriers and affected subjects through DNA testing. The BC is the most popular breed that is sampled and submitted for CEA analysis in Italy. In AS, no affected subjects were detected in our study; this is similar to results reported for the Czech 5 and Belgian 7 AS population. However, in the present study AS carriers represented 17.31% of the tested population and this percentage is higher than the one (6.25%) reported for Belgium. 7 There has been a substantial increase in registrations for the Australian Shepherd breed in the recent years in Italy, from 802 in 2011 to 2567 in 2019; 4 this was associated with the breeders recommending and arranging genetic testing with the expansion of the breed population. Regarding the SS breed, our results are in accordance with those reported in the Czech 5 and Swiss 6 dog populations. In fact, 10.81%, 15.1% and 16.3% of affected dogs were respectively found in Italian, Czech and Swiss populations. The consistent proportion of carriers discovered (50%) is very close to 53.2% as reported for a Czech SS breed study. 5 In NS dogs, no affected subjects were found, whereas a high percentage (45%) of carriers was detected. In the same retriever breed, 34.9% of carriers were described in the Czech Republic. 5 The same authors reported a percentage of 7% of affected subjects in the tested population. The data reported on this breed in Switzerland shows some peculiarities, because no carriers or affected individuals were found. 6 As the SS and NS had very small population sizes (247 and 58 entries in 2019, respectively) 4 it is possible to suppose a high risk of inbreeding, a condition which could dangerously limit genetic variation and breeders' choices and that could be the cause of the remarkable level of carriers found. F I G U R E  The situation of the RC breed is a concern given the small population size and the consequent potential use of a small number of breeding animals which could increase the risk of inbreeding and lead to an increase in the prevalence of the CEA condition. The high number of carriers found in the BC (29.64%), SS (45%) and NS (50%) breeds are probably linked to the objective of breeders to recognize heterozygous dogs with greater interest than homozygotes, the latter being clinically identifiable in the first six weeks of lif 2 and therefore often not subjected to genetic analysis. 2 The trend of reduction in the proportion of carriers in the AS and BC breeds shows the effectiveness of an accurate training and information campaign for breeders of the two breeds carried out through press releases, seminars and conferences by the Italian Kennel Club ENCI. The ENCI wanted to promote dog health and welfare through encouraging genetic testing by breeders in order to reduce the proportion of carriers in the AS and BC breeds. Given the high proportion of affected dogs in RC and of carriers in the SS breeds, it is important that DNA testing at an early age is undertaken by breeders. It should be noted that in Switzerland 53.8% of RC dogs under the age of eight months were genotyped at NHEJ locus; that in the SS breed in the same age group the percentage tested was lower at 18.7%. 6 Unfortunately, the average age at DNA test found in all the examined breeds in our study was rather late in relation to the possibility of limiting the spread of the disease (2.44 ± 1.95). Given the reproductive capability of dogs at two years of age this could lead to matings of uncontrolled pairs. It is, therefore, important to clearly communicate to breeders the need to have DNA testing performed as early as possible in the life of future sires and dams. At the same time, it should be remembered the usefulness of the ophthalmological examination of puppies before eight weeks of age as an efficient method to identify dogs with clinical signs of CEA. 8 From the evaluation of the allele frequencies relating to the mutated allele for CEA, in the AS we found a frequency of 8.65%, while lower frequencies were reported in the Czech Republic (4.5%) and in Belgium (3.1%). 5,7 From the results obtained, it appears that the Italian situation is quite similar to data from the Czech Republic 5 and Japan. 9 It should be noted that dogs bred in Belgium have a lower gene frequency. Our findings describe the frequencies of the CEA mutation in Italy over a 10-year time span, a clear interest in DNA test has been demonstrated; moreover, a reduction of the age at the test would be ideal. Population sizes, number of breeders per breed and breeding strategies, can all influence the possibility to improve population fitness through biodiversity and selective matings aimed to improve dog health and welfare. Testing for the CEA mutation is an effective tool in population management. The use of DNA testing at an early age for mendelian recessive conditions such as CEA should be considered an important target for breeders, breed associations and national clubs. A C K N O W L E D G M E N T S The authors are grateful to the Ente Nazionale della Cinofilia Italiana (ENCI -the Italian Kennel Club) and Vetogene Lab for technical support. The authors acknowledge support from the University of Milan through the APC initiative. C O N F L I C T S O F I N T E R E S T The authors declare they have no conflicts of interest. E T H I C A L A P P R O VA L All animals that were recruited for this study were clientowned; the owners provided written consent. Blood samples were collected by an authorized veterinarian.
package com.richdroid.physicsbasedanimation.ui.activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import com.richdroid.physicsbasedanimation.R; public class MainActivity extends AppCompatActivity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button translateSpringAnimBtn = (Button) findViewById(R.id.btn_translate_spring); translateSpringAnimBtn.setOnClickListener(this); Button flingAnimBtn = (Button) findViewById(R.id.btn_translate_fling); flingAnimBtn.setOnClickListener(this); Button translateRotateSpringAnimBtn = (Button) findViewById(R.id.btn_translate_rotate_spring); translateRotateSpringAnimBtn.setOnClickListener(this); Button chainedSpringAnimBtn = (Button) findViewById(R.id.btn_chained_spring); chainedSpringAnimBtn.setOnClickListener(this); } @Override public void onClick(View v) { int id = v.getId(); Intent intent; if (id == R.id.btn_translate_spring) { intent = new Intent(this, TranslateSpringAnimationActivity.class); startActivity(intent); } else if (id == R.id.btn_translate_fling) { intent = new Intent(this, TranslateFlingAnimationActivity.class); startActivity(intent); } else if (id == R.id.btn_translate_rotate_spring) { intent = new Intent(this, TranslateAndRotateSpringAnimationActivity.class); startActivity(intent); } else if (id == R.id.btn_chained_spring) { intent = new Intent(this, ChainedSpringAnimationActivity.class); startActivity(intent); } } }
// WidgetBlueprintGeneratedClass FlagSelectionModal.FlagSelectionModal_C // Size: 0x570 (Inherited: 0x548) struct UFlagSelectionModal_C : UFortFlagSelectionModal { struct FPointerToUberGraphFrame UberGraphFrame; // 0x548(0x08) struct UVerticalBox* FlagConfirmation; // 0x550(0x08) struct UVerticalBox* FlagSelection; // 0x558(0x08) struct USafeZone* SafeZone_1; // 0x560(0x08) struct UWidgetSwitcher* Switcher_Confirmation; // 0x568(0x08) void Handle Back(bool PassThrough); // Function FlagSelectionModal.FlagSelectionModal_C.Handle Back // (Public|HasOutParms|BlueprintCallable|BlueprintEvent) // @ game+0xda7c34 void BndEvt__Button_Change_K2Node_ComponentBoundEvent_0_CommonButtonClicked__DelegateSignature(struct UCommonButtonLegacy* Button); // Function FlagSelectionModal.FlagSelectionModal_C.BndEvt__Button_Change_K2Node_ComponentBoundEvent_0_CommonButtonClicked__DelegateSignature // (BlueprintEvent) // @ game+0xda7c34 void BndEvt__Button_ConfirmationCancel_K2Node_ComponentBoundEvent_1_CommonButtonClicked__DelegateSignature(struct UCommonButtonLegacy* Button); // Function FlagSelectionModal.FlagSelectionModal_C.BndEvt__Button_ConfirmationCancel_K2Node_ComponentBoundEvent_1_CommonButtonClicked__DelegateSignature // (BlueprintEvent) // @ game+0xda7c34 void BP_OnActivated(); // Function FlagSelectionModal.FlagSelectionModal_C.BP_OnActivated // (Event|Protected|BlueprintEvent) // @ game+0xda7c34 void ExecuteUbergraph_FlagSelectionModal(int32_t EntryPoint); // Function FlagSelectionModal.FlagSelectionModal_C.ExecuteUbergraph_FlagSelectionModal // (Final|UbergraphFunction) // @ game+0xda7c34 };
/* * rma_try_authcode expects a buffer that is at least RMA_AUTHCODE_CHARS long, * so copy the input string to a buffer before calling the function. */ static int rma_try_authcode_pad(const char *code) { char authcode[RMA_AUTHCODE_BUF_SIZE]; memset(authcode, 0, sizeof(authcode)); strncpy(authcode, code, sizeof(authcode)); return rma_try_authcode(authcode); }
<gh_stars>0 module org.quickstart.javase9.markdown { requires org.quickstart.javase9.api; requires org.quickstart.javase9.service; uses org.quickstart.javase9.api.EventService; uses org.quickstart.javase9.service.TalkService; uses org.quickstart.javase9.service.WorkshopService; }
/** * A Cuckoo filter for instances of {@code T}. Cuckoo filters are probabilistic * hash tables similar to Bloom filters but with several advantages. Like Bloom * filters, a Cuckoo filter can determine if an object is contained within a set * at a specified false positive rate with no false negatives. Like Bloom, a * Cuckoo filter can determine if an element is probably inserted or definitely * is not. In addition, and unlike standard Bloom filters, Cuckoo filters allow * deletions and counting. They also use less space than a Bloom filter for * similar performance. * * <p> * The false positive rate of the filter is the probability that * {@linkplain #mightContain(Object)}} will erroneously return {@code true} for * an object that was not added to the filter. Unlike Bloom filters, a Cuckoo * filter will fail to insert when it reaches capacity. If an insert fails * {@linkplain #put(Object)} will {@code return false} . * * <p> * Cuckoo filters allow deletion like counting Bloom filters using * {@code #delete(Object)}. While counting Bloom filters invariably use more * space to allow deletions, Cuckoo filters achieve this with <i>no</i> space or * time cost. Like counting variations of Bloom filters, Cuckoo filters have a * limit to the number of times you can insert duplicate items. This limit is * 8-9 in the current design, depending on internal state. You should never * exceed 7 if possible. <i>Reaching this limit can cause further inserts to * fail and degrades the performance of the filter</i>. Occasional duplicates * will not degrade the performance of the filter but will slightly reduce * capacity. * * <p> * This Cuckoo filter implementation also allows counting the number of inserts * for each item using {@code #approximateCount(Object)}. This is probabilistic * like the rest of the filter and any error is always an increase. The count * will never return less than the number of actual inserts, but may return * more. The insert limit of 7 still stands when counting so this is only useful * for small numbers. * * <p> * Once the filter reaches capacity ({@linkplain #put(Object)} returns false). * It's best to either rebuild the existing filter or create a larger one. * Deleting items in the current filter is also an option, but you should delete * at least ~2% of the items in the filter before inserting again. * * <p> * Existing items can be deleted without affecting the false positive rate or * causing false negatives. However, deleting items that were <i>not</i> * previously added to the filter can cause false negatives. * * <p> * Hash collision attacks are theoretically possible against Cuckoo filters (as * with any hash table based structure). If this is an issue for your * application, use one of the cryptographically secure (but slower) hash * functions. The default hash function, Murmer3 is <i>not</i> secure. Secure * functions include SHA and SipHash. All hashes, including non-secure, are * internally seeded and salted. Practical attacks against any of them are * unlikely. * * <p> * This implementation of a Cuckoo filter is serializable. * * @see <a href="https://www.cs.cmu.edu/~dga/papers/cuckoo-conext2014.pdf"> * paper on Cuckoo filter properties.</a> * @see <a href="https://github.com/seiflotfy/cuckoofilter">Golang Cuckoo filter * implementation</a> * @see <a href="https://github.com/efficient/cuckoofilter">C++ reference * implementation</a> * * @param <T> * the type of items that the {@code CuckooFilter} accepts * @author Mark Gunlogson */ public final class CuckooFilter<T> implements Serializable { /* * IMPORTANT THREAD SAFETY NOTES. To prevent deadlocks, all methods needing * multiple locks need to lock the victim first. This is followed by the * segment locks, which need to be locked in ascending order of segment in * the backing lock array. The bucketlocker will always lock multiple * buckets in the same order if you use it properly. * */ private static final long serialVersionUID = -1337735144654851942L; static final int INSERT_ATTEMPTS = 500; static final int BUCKET_SIZE = 4; // make sure to update getNeededBitsForFpRate() if changing this... then // again don't change this private static final double LOAD_FACTOR = 0.955; private static final double DEFAULT_FP = 0.01; private static final int DEFAULT_CONCURRENCY = 16; @VisibleForTesting final FilterTable table; @VisibleForTesting final IndexTagCalc<T> hasher; private final AtomicLong count; /** * Only stored for serialization since the bucket locker is transient. * equals() and hashcode() just check the concurrency value in the bucket * locker and ignore this */ private final int expectedConcurrency; private final StampedLock victimLock; private transient SegmentedBucketLocker bucketLocker; @VisibleForTesting Victim victim; @VisibleForTesting boolean hasVictim; /** * Creates a Cuckoo filter. */ private CuckooFilter(IndexTagCalc<T> hasher, FilterTable table, AtomicLong count, boolean hasVictim, Victim victim, int expectedConcurrency) { this.hasher = hasher; this.table = table; this.count = count; this.hasVictim = hasVictim; this.expectedConcurrency = expectedConcurrency; // no nulls even if victim hasn't been used! if (victim == null) this.victim = new Victim(); else this.victim = victim; this.victimLock = new StampedLock(); this.bucketLocker = new SegmentedBucketLocker(expectedConcurrency); } /*** * Builds a Cuckoo Filter. To Create a Cuckoo filter, construct this then * call {@code #build()}. * * @author Mark Gunlogson * * @param <T> * the type of item {@code Funnel will use} */ public static class Builder<T> { // required arguments private final Funnel<? super T> funnel; private final long maxKeys; // optional arguments private Algorithm hashAlgorithm; private double fpp = DEFAULT_FP; private int expectedConcurrency = DEFAULT_CONCURRENCY; /** * Creates a Builder interface for {@link CuckooFilter CuckooFilter} * with the expected number of insertions using the default false * positive rate, {@code #hashAlgorithm}, and concurrency. The default * false positive rate is 1%. The default hash is Murmur3, automatically * using the 32 bit version for small tables and 128 bit version for * larger ones. The default concurrency is 16 expected threads. * * <p> * Note that overflowing a {@code CuckooFilter} with significantly more * elements than specified will result in insertion failure. * * <p> * The constructed {@code BloomFilter<T>} will be serializable if the * provided {@code Funnel<T>} is. * * <p> * It is recommended that the funnel be implemented as a Java enum. This * has the benefit of ensuring proper serialization and deserialization, * which is important since {@link #equals} also relies on object * identity of funnels. * * * @param funnel * the funnel of T's that the constructed * {@code CuckooFilter<T>} will use * @param maxKeys * the number of expected insertions to the constructed * {@code CuckooFilter<T>}; must be positive * */ public Builder(Funnel<? super T> funnel, long maxKeys) { checkArgument(maxKeys > 1, "maxKeys (%s) must be > 1, increase maxKeys", maxKeys); checkNotNull(funnel); this.funnel = funnel; this.maxKeys = maxKeys; } /** * Creates a Builder interface for {@link CuckooFilter CuckooFilter} * with the expected number of insertions using the default false * positive rate, {@code #hashAlgorithm}, and concurrency. The default * false positive rate is 1%. The default hash is Murmur3, automatically * using the 32 bit version for small tables and 128 bit version for * larger ones. The default concurrency is 16 expected threads. * * <p> * Note that overflowing a {@code CuckooFilter} with significantly more * elements than specified will result in insertion failure. * * <p> * The constructed {@code BloomFilter<T>} will be serializable if the * provided {@code Funnel<T>} is. * * <p> * It is recommended that the funnel be implemented as a Java enum. This * has the benefit of ensuring proper serialization and deserialization, * which is important since {@link #equals} also relies on object * identity of funnels. * * * @param funnel * the funnel of T's that the constructed * {@code CuckooFilter<T>} will use * @param maxKeys * the number of expected insertions to the constructed * {@code CuckooFilter<T>}; must be positive * */ public Builder(Funnel<? super T> funnel, int maxKeys) { this(funnel, (long) maxKeys); } /** * Sets the false positive rate for the filter. The default is 1%. * Unrealistic values will cause filter creation to fail on * {@code #build()} due to excessively short fingerprints or memory * exhaustion. The filter becomes more space efficient than Bloom * filters below ~0.02 (2%) . * * @param fpp * false positive rate ( value is (expected %)/100 ) from 0-1 * exclusive. * @return The builder interface */ public Builder<T> withFalsePositiveRate(double fpp) { checkArgument(fpp > 0, "fpp (%s) must be > 0, increase fpp", fpp); checkArgument(fpp < .25, "fpp (%s) must be < 0.25, decrease fpp", fpp); this.fpp = fpp; return this; } /** * Sets the hashing algorithm used internally. The default is Murmur3, * 32 or 128 bit sized automatically. Calling this with a Murmur3 * variant instead of using the default will disable automatic hash * sizing of Murmur3. The size of the table will be significantly * limited with a 32 bit hash to around 270 MB. Table size is still * limited in certain circumstances when using 64 bit hashes like * SipHash. 128+ bit hashes will allow practically unlimited table size. * In any case, filter creation will fail on {@code #build()} with an * invalid configuration. * * @param hashAlgorithm the hashing algorithm used by the filter. * @return The builder interface */ public Builder<T> withHashAlgorithm(Algorithm hashAlgorithm) { checkNotNull(hashAlgorithm, "hashAlgorithm cannot be null. To use default, build without calling this method."); this.hashAlgorithm = hashAlgorithm; return this; } /*** * * Number of simultaneous threads expected to access the filter * concurrently. The default is 16 threads. It is better to overestimate * as the cost of more segments is very small and penalty for contention * is high. This number is not performance critical, any number over the * actual number of threads and within an order of magnitude will work. * <i> THIS NUMBER MUST BE A POWER OF 2</i> * * @param expectedConcurrency * expected number of threads accessing the filter * concurrently. * * @return The builder interface * */ public Builder<T> withExpectedConcurrency(int expectedConcurrency) { checkArgument(expectedConcurrency > 0, "expectedConcurrency (%s) must be > 0.", expectedConcurrency); checkArgument((expectedConcurrency & (expectedConcurrency - 1)) == 0, "expectedConcurrency (%s) must be a power of two.", expectedConcurrency); this.expectedConcurrency = expectedConcurrency; return this; } /** * Builds and returns a {@code CuckooFilter<T>}. Invalid configurations * will fail on this call. * * @return a Cuckoo filter of type T */ public CuckooFilter<T> build() { int tagBits = Utils.getBitsPerItemForFpRate(fpp, LOAD_FACTOR); long numBuckets = Utils.getBucketsNeeded(maxKeys, LOAD_FACTOR, BUCKET_SIZE); IndexTagCalc<T> hasher; if (hashAlgorithm == null) { hasher = IndexTagCalc.create(funnel, numBuckets, tagBits); } else hasher = IndexTagCalc.create(hashAlgorithm, funnel, numBuckets, tagBits); FilterTable filtertbl = FilterTable.create(tagBits, numBuckets); return new CuckooFilter<>(hasher, filtertbl, new AtomicLong(0), false, null, expectedConcurrency); } } /** * Gets the current number of items in the Cuckoo filter. Can be higher than * the max number of keys the filter was created to store if it is running * over expected maximum fill capacity. If you need to know the absolute * maximum number of items this filter can contain, call * {@code #getActualCapacity()}. If you just want to check how full the * filter is, it's better to use {@code #getLoadFactor()} than this, which * is bounded at 1.0 * * @return number of items in filter */ public long getCount() { // can return more than maxKeys if running above design limit! return count.get(); } /** * Gets the current load factor of the Cuckoo filter. Reasonably sized * filters with randomly distributed values can be expected to reach a load * factor of around 95% (0.95) before insertion failure. Note that during * simultaneous access from multiple threads this may not be exact in rare * cases. * * @return load fraction of total space used, 0-1 inclusive */ public double getLoadFactor() { return count.get() / (hasher.getNumBuckets() * (double) BUCKET_SIZE); } /** * Gets the absolute maximum number of items the filter can theoretically * hold. <i>This is NOT the maximum you can expect it to reliably hold.</i> * This should only be used if you understand the source. Internal * restrictions on backing array size and compensation for the expected * filter occupancy on first insert failure nearly always make the filter * larger than requested on creation. This method returns how big the filter * actually is (in items) <i>DO NOT EXPECT IT TO BE ABLE TO HOLD THIS MANY * </i> * * @return number of keys filter can theoretically hold at 100% fill */ public long getActualCapacity() { return hasher.getNumBuckets() * BUCKET_SIZE; } /** * Gets the size of the underlying {@code LongBitSet} table for the filter, * in bits. This should only be used if you understand the source. * * @return space used by table in bits */ public long getStorageSize() { return table.getStorageSize(); } /** * Puts an element into this {@code CuckooFilter}. Ensures that subsequent * invocations of {@link #mightContain(Object)} with the same element will * always return {@code true}. * <p> * Note that the filter should be considered full after insertion failure. * Further inserts <i>may</i> fail, although deleting items can also make * the filter usable again. * <p> * Also note that inserting the same item more than 8 times will cause an * insertion failure. * * @param item * item to insert into the filter * * @return {@code true} if the cuckoo filter inserts this item successfully. * Returns {@code false} if insertion failed. */ public boolean put(T item) { BucketAndTag pos = hasher.generate(item); long curTag = pos.tag; long curIndex = pos.index; long altIndex = hasher.altIndex(curIndex, curTag); bucketLocker.lockBucketsWrite(curIndex, altIndex); try { if (table.insertToBucket(curIndex, curTag) || table.insertToBucket(altIndex, curTag)) { count.incrementAndGet(); return true; } } finally { bucketLocker.unlockBucketsWrite(curIndex, altIndex); } // don't do insertion loop if victim slot is already filled long victimLockStamp = writeLockVictimIfClear(); if (victimLockStamp == 0L) // victim was set...can't insert return false; try { // fill victim slot and run fun insert method below victim.setTag(curTag); victim.setI1(curIndex); victim.setI2(altIndex); hasVictim = true; for (int i = 0; i <= INSERT_ATTEMPTS; i++) { if (trySwapVictimIntoEmptySpot()) break; } /* * count is incremented here because we should never increase count * when not locking buckets or victim. Reason is because otherwise * count may be inconsistent across threads when doing operations * that lock the whole table like hashcode() or equals() */ count.getAndIncrement(); } finally { victimLock.unlock(victimLockStamp); } // if we get here, we either managed to insert victim using retries or // it's in victim slot from another thread. Either way, it's in the // table. return true; } /** * if we kicked a tag we need to move it to alternate position, possibly * kicking another tag there, repeating the process until we succeed or run * out of chances * * The basic flow below is to insert our current tag into a position in an * already full bucket, then move the tag that we overwrote to it's * alternate index. We repeat this until we move a tag into a non-full * bucket or run out of attempts. This tag shuffling process is what gives * the Cuckoo filter such a high load factor. When we run out of attempts, * we leave the orphaned tag in the victim slot. * * We need to be extremely careful here to avoid deadlocks and thread stalls * during this process. The most nefarious deadlock is that two or more * threads run out of tries simultaneously and all need a place to store a * victim even though we only have one slot * */ private boolean trySwapVictimIntoEmptySpot() { long curIndex = victim.getI2(); // lock bucket. We always use I2 since victim tag is from bucket I1 bucketLocker.lockSingleBucketWrite(curIndex); long curTag = table.swapRandomTagInBucket(curIndex, victim.getTag()); bucketLocker.unlockSingleBucketWrite(curIndex); // new victim's I2 is different as long as tag isn't the same long altIndex = hasher.altIndex(curIndex, curTag); // try to insert the new victim tag in it's alternate bucket bucketLocker.lockSingleBucketWrite(altIndex); try { if (table.insertToBucket(altIndex, curTag)) { hasVictim = false; return true; } else { // still have a victim, but a different one... victim.setTag(curTag); // new victim always shares I1 with previous victims' I2 victim.setI1(curIndex); victim.setI2(altIndex); } } finally { bucketLocker.unlockSingleBucketWrite(altIndex); } return false; } /** * Attempts to insert the victim item if it exists. Remember that inserting * from the victim cache to the main table DOES NOT affect the count since * items in the victim cache are technically still in the table * */ private void insertIfVictim() { long victimLockstamp = writeLockVictimIfSet(); if (victimLockstamp == 0L) return; try { // when we get here we definitely have a victim and a write lock bucketLocker.lockBucketsWrite(victim.getI1(), victim.getI2()); try { if (table.insertToBucket(victim.getI1(), victim.getTag()) || table.insertToBucket(victim.getI2(), victim.getTag())) { // set this here because we already have lock hasVictim = false; } } finally { bucketLocker.unlockBucketsWrite(victim.getI1(), victim.getI2()); } } finally { victimLock.unlock(victimLockstamp); } } /*** * Checks if the victim is set using a read lock and upgrades to a write * lock if it is. Will either return a write lock stamp if victim is set, or * zero if no victim. * * @return a write lock stamp for the Victim or 0 if no victim */ private long writeLockVictimIfSet() { long victimLockstamp = victimLock.readLock(); if (hasVictim) { // try to upgrade our read lock to write exclusive if victim long writeLockStamp = victimLock.tryConvertToWriteLock(victimLockstamp); // could not get write lock if (writeLockStamp == 0L) { // so unlock the victim victimLock.unlock(victimLockstamp); // now just block until we have exclusive lock victimLockstamp = victimLock.writeLock(); // make sure victim is still set with our new write lock if (!hasVictim) { // victim has been cleared by another thread... so just give // up our lock victimLock.tryUnlockWrite(); return 0L; } else return victimLockstamp; } else { return writeLockStamp; } } else { victimLock.unlock(victimLockstamp); return 0L; } } /*** * Checks if the victim is clear using a read lock and upgrades to a write * lock if it is clear. Will either return a write lock stamp if victim is * clear, or zero if a victim is already set. * * @return a write lock stamp for the Victim or 0 if victim is set */ private long writeLockVictimIfClear() { long victimLockstamp = victimLock.readLock(); if (!hasVictim) { // try to upgrade our read lock to write exclusive if victim long writeLockStamp = victimLock.tryConvertToWriteLock(victimLockstamp); // could not get write lock if (writeLockStamp == 0L) { // so unlock the victim victimLock.unlock(victimLockstamp); // now just block until we have exclusive lock victimLockstamp = victimLock.writeLock(); // make sure victim is still clear with our new write lock if (!hasVictim) return victimLockstamp; else { // victim has been set by another thread... so just give up // our lock victimLock.tryUnlockWrite(); return 0L; } } else { return writeLockStamp; } } else { victimLock.unlock(victimLockstamp); return 0L; } } @VisibleForTesting /** * Checks if a given tag is the victim. * * @param tagToCheck * the tag to check * @return true if tag is stored in victim */ boolean checkIsVictim(BucketAndTag tagToCheck) { checkNotNull(tagToCheck); victimLock.readLock(); try { if (hasVictim) { if (victim.getTag() == tagToCheck.tag && (tagToCheck.index == victim.getI1() || tagToCheck.index == victim.getI2())) { return true; } } return false; } finally { victimLock.tryUnlockRead(); } } /** * Returns {@code true} if the element <i>might</i> have been put in this * Cuckoo filter, {@code false} if this is <i>definitely</i> not the case. * * @param item * to check * * @return true if the item might be in the filter */ public boolean mightContain(T item) { BucketAndTag pos = hasher.generate(item); long i1 = pos.index; long i2 = hasher.altIndex(pos.index, pos.tag); bucketLocker.lockBucketsRead(i1, i2); try { if (table.findTag(i1, i2, pos.tag)) { return true; } } finally { bucketLocker.unlockBucketsRead(i1, i2); } return checkIsVictim(pos); } /** * This method returns the approximate number of times an item was added to * the filter. This count is probabilistic like the rest of the filter, so * it may occasionally over-count. Since the filter has no false negatives, * <i>the approximate count will always be equal or greater than the actual * count(unless you've been deleting non-existent items)</i>. That is, this * method may return a higher count than the true value, but never lower. * The false inflation chance of the count depends on the filter's false * positive rate, but is generally low for sane configurations. * <p> * NOTE: Inserting the same key more than 7 times will cause a bucket * overflow, greatly decreasing the performance of the filter and making * early insertion failure (less than design load factor) very likely. For * this reason the filter should only be used to count small values. * * <p> * Also note that getting the count is generally about half as fast as * checking if a filter contains an item. * * @param item * item to check * @return Returns a positive integer representing the number of times an * item was probably added to the filter. Returns zero if the item * is not in the filter, behaving exactly like * {@code #mightContain(Object)} in this case. */ public int approximateCount(T item) { BucketAndTag pos = hasher.generate(item); long i1 = pos.index; long i2 = hasher.altIndex(pos.index, pos.tag); int tagCount = 0; bucketLocker.lockBucketsRead(i1, i2); try { tagCount = table.countTag(i1, i2, pos.tag); } finally { bucketLocker.unlockBucketsRead(i1, i2); } if (checkIsVictim(pos)) tagCount++; return tagCount; } /** * Deletes an element from this {@code CuckooFilter}. In most cases you * should only delete items that have been previously added to the filter. * Attempting to delete non-existent items may successfully delete the wrong * item in the filter, causing a false negative. False negatives are defined * as( {@code #mightContain(Object)} returning false for an item that * <i>has</i> been added to the filter. Deleting non-existent items doesn't * otherwise adversely affect the state of the filter, so attempting to * delete items that <i>may not</i> have been inserted is fine if false * negatives are acceptable. The false-delete rate is similar to the false * positive rate. False deletes can also cause the * {@code #approximateCount(Object)} to return both lower and higher than * the real count * * @return {@code true} if the cuckoo filter deleted this item successfully. * Returns {@code false} if the item was not found. * * @param item * the item to delete */ public boolean delete(T item) { BucketAndTag pos = hasher.generate(item); long i1 = pos.index; long i2 = hasher.altIndex(pos.index, pos.tag); bucketLocker.lockBucketsWrite(i1, i2); boolean deleteSuccess = false; try { if (table.deleteFromBucket(i1, pos.tag) || table.deleteFromBucket(i2, pos.tag)) deleteSuccess = true; } finally { bucketLocker.unlockBucketsWrite(i1, i2); } // try to insert the victim again if we were able to delete an item if (deleteSuccess) { count.decrementAndGet(); insertIfVictim();// might as well try to insert again return true; } // if delete failed but we have a victim, check if the item we're trying // to delete IS actually the victim long victimLockStamp = writeLockVictimIfSet(); if (victimLockStamp == 0L) return false; else { try { // check victim match if (victim.getTag() == pos.tag && (victim.getI1() == pos.index || victim.getI2() == pos.index)) { hasVictim = false; count.decrementAndGet(); return true; } else return false; } finally { victimLock.unlock(victimLockStamp); } } } private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException { // default deserialization ois.defaultReadObject(); // not serializable so we rebuild here bucketLocker = new SegmentedBucketLocker(expectedConcurrency); } @Override public boolean equals(@Nullable Object object) { if (object == this) { return true; } if (object instanceof CuckooFilter) { CuckooFilter<?> that = (CuckooFilter<?>) object; victimLock.readLock(); bucketLocker.lockAllBucketsRead(); try { if (hasVictim) { // only compare victim if set, victim is sometimes stale // since we use bool flag to determine if set or not return this.hasher.equals(that.hasher) && this.table.equals(that.table) && this.count.get() == that.count.get() && this.hasVictim == that.hasVictim && victim.equals(that.victim); } return this.hasher.equals(that.hasher) && this.table.equals(that.table) && this.count.get() == that.count.get() && this.hasVictim == that.hasVictim; } finally { bucketLocker.unlockAllBucketsRead(); victimLock.tryUnlockRead(); } } return false; } @Override public int hashCode() { victimLock.readLock(); bucketLocker.lockAllBucketsRead(); try { if (hasVictim) { return Objects.hash(hasher, table, count.get(), victim); } return Objects.hash(hasher, table, count.get()); } finally { bucketLocker.unlockAllBucketsRead(); victimLock.tryUnlockRead(); } } /** * Creates a new {@code CuckooFilter} that's a copy of this instance. The * new instance is equal to this instance but shares no mutable state. Note * that further {@code #put(Object)}} operations <i>may</i> cause a copy to * diverge even if the same operations are performed to both filters since * bucket swaps are essentially random. * * @return a copy of the filter */ public CuckooFilter<T> copy() { victimLock.readLock(); bucketLocker.lockAllBucketsRead(); try { return new CuckooFilter<>(hasher.copy(), table.copy(), count, hasVictim, victim.copy(), expectedConcurrency); } finally { bucketLocker.unlockAllBucketsRead(); victimLock.tryUnlockRead(); } } }
// messageLoop is the message read loop for this consumer // TODO (venkat): maintain a pre-allocated pool of Messages func (p *partitionConsumer) messageLoop(offsetRange *kafka.OffsetRange) { var drain bool if offsetRange != nil { drain = true } p.logger.Debug("partition consumer message loop started") for { select { case m, ok := <-p.pConsumer.Messages(): if !ok { p.logger.Debug("partition consumer message channel closed") p.Drain(p.options.MaxProcessingTime) return } if drain && m.Offset != offsetRange.LowOffset { p.logger.Debug("partition consumer drain message", zap.Object("offsetRange", offsetRange), zap.Int64("offset", m.Offset)) continue } if drain { p.logger.Debug("partition consumer drain message complete", zap.Object("offsetRange", offsetRange), zap.Int64("offset", m.Offset)) } drain = false p.delayMsg(m) lag := time.Now().Sub(m.Timestamp) p.tally.Gauge(metrics.KafkaPartitionTimeLag).Update(float64(lag)) p.tally.Gauge(metrics.KafkaPartitionReadOffset).Update(float64(m.Offset)) p.tally.Counter(metrics.KafkaPartitionMessagesIn).Inc(1) p.tally.Gauge(metrics.KafkaPartitionOffsetFreshnessLag).Update(float64(p.pConsumer.HighWaterMarkOffset() - 1 - m.Offset)) p.deliver(m) if offsetRange != nil && m.Offset >= offsetRange.HighOffset { p.logger.Info("partition consumer message loop reached range", zap.Int64("offset", m.Offset), zap.Object("offsetRange", offsetRange)) return } case <-p.stopC: p.logger.Debug("partition consumer message loop stopped") return } } }
<reponame>IMvision12/keras-io<gh_stars>0 """ Title: Text classification with Switch Transformer Author: [<NAME>](https://www.linkedin.com/in/khalid-salama-24403144/) Date created: 2020/05/10 Last modified: 2021/02/15 Description: Implement a Switch Transformer for text classification. """ """ ## Introduction This example demonstrates the implementation of the [Switch Transformer](https://arxiv.org/abs/2101.03961) model for text classification. The Switch Transformer replaces the feedforward network (FFN) layer in the standard Transformer with a Mixture of Expert (MoE) routing layer, where each expert operates independently on the tokens in the sequence. This allows increasing the model size without increasing the computation needed to process each example. Note that, for training the Switch Transformer efficiently, data and model parallelism need to be applied, so that expert modules can run simultaneously, each on its own accelerator. While the implementation described in the paper uses the [TensorFlow Mesh](https://github.com/tensorflow/mesh) framework for distributed training, this example presents a simple, non-distributed implementation of the Switch Transformer model for demonstration purposes. """ """ ## Setup """ import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers """ ## Download and prepare dataset """ vocab_size = 20000 # Only consider the top 20k words num_tokens_per_example = 200 # Only consider the first 200 words of each movie review (x_train, y_train), (x_val, y_val) = keras.datasets.imdb.load_data(num_words=vocab_size) print(len(x_train), "Training sequences") print(len(x_val), "Validation sequences") x_train = keras.preprocessing.sequence.pad_sequences( x_train, maxlen=num_tokens_per_example ) x_val = keras.preprocessing.sequence.pad_sequences(x_val, maxlen=num_tokens_per_example) """ ## Define hyperparameters """ embed_dim = 32 # Embedding size for each token. num_heads = 2 # Number of attention heads ff_dim = 32 # Hidden layer size in feedforward network. num_experts = 10 # Number of experts used in the Switch Transformer. batch_size = 50 # Batch size. learning_rate = 0.001 # Learning rate. dropout_rate = 0.25 # Dropout rate. num_epochs = 3 # Number of epochs. num_tokens_per_batch = ( batch_size * num_tokens_per_example ) # Total number of tokens per batch. print(f"Number of tokens per batch: {num_tokens_per_batch}") """ ## Implement token & position embedding layer It consists of two seperate embedding layers, one for tokens, one for token index (positions). """ class TokenAndPositionEmbedding(layers.Layer): def __init__(self, maxlen, vocab_size, embed_dim): super(TokenAndPositionEmbedding, self).__init__() self.token_emb = layers.Embedding(input_dim=vocab_size, output_dim=embed_dim) self.pos_emb = layers.Embedding(input_dim=maxlen, output_dim=embed_dim) def call(self, x): maxlen = tf.shape(x)[-1] positions = tf.range(start=0, limit=maxlen, delta=1) positions = self.pos_emb(positions) x = self.token_emb(x) return x + positions """ ## Implement the feedforward network This is used as the Mixture of Experts in the Switch Transformer. """ def create_feedforward_network(ff_dim, name=None): return keras.Sequential( [layers.Dense(ff_dim, activation="relu"), layers.Dense(ff_dim)], name=name ) """ ## Implement the load-balanced loss This is an auxiliary loss to encourage a balanced load across experts. """ def load_balanced_loss(router_probs, expert_mask): # router_probs [tokens_per_batch, num_experts] is the probability assigned for # each expert per token. expert_mask [tokens_per_batch, num_experts] contains # the expert with the highest router probability in one−hot format. num_experts = tf.shape(expert_mask)[-1] # Get the fraction of tokens routed to each expert. # density is a vector of length num experts that sums to 1. density = tf.reduce_mean(expert_mask, axis=0) # Get fraction of probability mass assigned to each expert from the router # across all tokens. density_proxy is a vector of length num experts that sums to 1. density_proxy = tf.reduce_mean(router_probs, axis=0) # Want both vectors to have uniform allocation (1/num experts) across all # num_expert elements. The two vectors will be pushed towards uniform allocation # when the dot product is minimized. loss = tf.reduce_mean(density_proxy * density) * tf.cast( (num_experts**2), tf.dtypes.float32 ) return loss """ ### Implement the router as a layer """ class Router(layers.Layer): def __init__(self, num_experts, expert_capacity): self.num_experts = num_experts self.route = layers.Dense(units=num_experts) self.expert_capacity = expert_capacity super(Router, self).__init__() def call(self, inputs, training=False): # inputs shape: [tokens_per_batch, embed_dim] # router_logits shape: [tokens_per_batch, num_experts] router_logits = self.route(inputs) if training: # Add noise for exploration across experts. router_logits += tf.random.uniform( shape=router_logits.shape, minval=0.9, maxval=1.1 ) # Probabilities for each token of what expert it should be sent to. router_probs = keras.activations.softmax(router_logits, axis=-1) # Get the top−1 expert for each token. expert_gate is the top−1 probability # from the router for each token. expert_index is what expert each token # is going to be routed to. expert_gate, expert_index = tf.math.top_k(router_probs, k=1) # expert_mask shape: [tokens_per_batch, num_experts] expert_mask = tf.one_hot(expert_index, depth=self.num_experts) # Compute load balancing loss. aux_loss = load_balanced_loss(router_probs, expert_mask) self.add_loss(aux_loss) # Experts have a fixed capacity, ensure we do not exceed it. Construct # the batch indices, to each expert, with position in expert make sure that # not more that expert capacity examples can be routed to each expert. position_in_expert = tf.cast( tf.math.cumsum(expert_mask, axis=0) * expert_mask, tf.dtypes.int32 ) # Keep only tokens that fit within expert capacity. expert_mask *= tf.cast( tf.math.less( tf.cast(position_in_expert, tf.dtypes.int32), self.expert_capacity ), tf.dtypes.float32, ) expert_mask_flat = tf.reduce_sum(expert_mask, axis=-1) # Mask out the experts that have overflowed the expert capacity. expert_gate *= expert_mask_flat # Combine expert outputs and scaling with router probability. # combine_tensor shape: [tokens_per_batch, num_experts, expert_capacity] combined_tensor = tf.expand_dims( expert_gate * expert_mask_flat * tf.squeeze(tf.one_hot(expert_index, depth=self.num_experts), 1), -1, ) * tf.squeeze(tf.one_hot(position_in_expert, depth=self.expert_capacity), 1) # Create binary dispatch_tensor [tokens_per_batch, num_experts, expert_capacity] # that is 1 if the token gets routed to the corresponding expert. dispatch_tensor = tf.cast(combined_tensor, tf.dtypes.float32) return dispatch_tensor, combined_tensor """ ### Implement a Switch layer """ class Switch(layers.Layer): def __init__(self, num_experts, embed_dim, num_tokens_per_batch, capacity_factor=1): self.num_experts = num_experts self.embed_dim = embed_dim self.experts = [ create_feedforward_network(embed_dim) for _ in range(num_experts) ] self.expert_capacity = num_tokens_per_batch // self.num_experts self.router = Router(self.num_experts, self.expert_capacity) super(Switch, self).__init__() def call(self, inputs): batch_size = tf.shape(inputs)[0] num_tokens_per_example = tf.shape(inputs)[1] # inputs shape: [num_tokens_per_batch, embed_dim] inputs = tf.reshape(inputs, [num_tokens_per_batch, self.embed_dim]) # dispatch_tensor shape: [expert_capacity, num_experts, tokens_per_batch] # combine_tensor shape: [tokens_per_batch, num_experts, expert_capacity] dispatch_tensor, combine_tensor = self.router(inputs) # expert_inputs shape: [num_experts, expert_capacity, embed_dim] expert_inputs = tf.einsum("ab,acd->cdb", inputs, dispatch_tensor) expert_inputs = tf.reshape( expert_inputs, [self.num_experts, self.expert_capacity, self.embed_dim] ) # Dispatch to experts expert_input_list = tf.unstack(expert_inputs, axis=0) expert_output_list = [ self.experts[idx](expert_input) for idx, expert_input in enumerate(expert_input_list) ] # expert_outputs shape: [expert_capacity, num_experts, embed_dim] expert_outputs = tf.stack(expert_output_list, axis=1) # expert_outputs_combined shape: [tokens_per_batch, embed_dim] expert_outputs_combined = tf.einsum( "abc,xba->xc", expert_outputs, combine_tensor ) # output shape: [batch_size, num_tokens_per_example, embed_dim] outputs = tf.reshape( expert_outputs_combined, [batch_size, num_tokens_per_example, self.embed_dim], ) return outputs """ ## Implement a Transformer block layer """ class TransformerBlock(layers.Layer): def __init__(self, embed_dim, num_heads, ffn, dropout_rate=0.1): super(TransformerBlock, self).__init__() self.att = layers.MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim) # The ffn can be either a standard feedforward network or a switch # layer with a Mixture of Experts. self.ffn = ffn self.layernorm1 = layers.LayerNormalization(epsilon=1e-6) self.layernorm2 = layers.LayerNormalization(epsilon=1e-6) self.dropout1 = layers.Dropout(dropout_rate) self.dropout2 = layers.Dropout(dropout_rate) def call(self, inputs, training): attn_output = self.att(inputs, inputs) attn_output = self.dropout1(attn_output, training=training) out1 = self.layernorm1(inputs + attn_output) ffn_output = self.ffn(out1) ffn_output = self.dropout2(ffn_output, training=training) return self.layernorm2(out1 + ffn_output) """ ## Implement the classifier The `TransformerBlock` layer outputs one vector for each time step of our input sequence. Here, we take the mean across all time steps and use a feedforward network on top of it to classify text. """ def create_classifier(): switch = Switch(num_experts, embed_dim, num_tokens_per_batch) transformer_block = TransformerBlock(ff_dim, num_heads, switch) inputs = layers.Input(shape=(num_tokens_per_example,)) embedding_layer = TokenAndPositionEmbedding( num_tokens_per_example, vocab_size, embed_dim ) x = embedding_layer(inputs) x = transformer_block(x) x = layers.GlobalAveragePooling1D()(x) x = layers.Dropout(dropout_rate)(x) x = layers.Dense(ff_dim, activation="relu")(x) x = layers.Dropout(dropout_rate)(x) outputs = layers.Dense(2, activation="softmax")(x) classifier = keras.Model(inputs=inputs, outputs=outputs) return classifier """ ## Train and evaluate the model """ def run_experiment(classifier): classifier.compile( optimizer=keras.optimizers.Adam(learning_rate), loss="sparse_categorical_crossentropy", metrics=["accuracy"], ) history = classifier.fit( x_train, y_train, batch_size=batch_size, epochs=num_epochs, validation_data=(x_val, y_val), ) return history classifier = create_classifier() run_experiment(classifier) """ ## Conclusion Compared to the standard Transformer architecture, the Switch Transformer can have a much larger number of parameters, leading to increased model capacity, while maintaining a reasonable computational cost. """
Deblurring by Example Using Dense Correspondence This paper presents a new method for deblurring photos using a sharp reference example that contains some shared content with the blurry photo. Most previous deblurring methods that exploit information from other photos require an accurately registered photo of the same static scene. In contrast, our method aims to exploit reference images where the shared content may have undergone substantial photometric and non-rigid geometric transformations, as these are the kind of reference images most likely to be found in personal photo albums. Our approach builds upon a recent method for example-based deblurring using non-rigid dense correspondence (NRDC) and extends it in two ways. First, we suggest exploiting information from the reference image not only for blur kernel estimation, but also as a powerful local prior for the non-blind deconvolution step. Second, we introduce a simple yet robust technique for spatially varying blur estimation, rather than assuming spatially uniform blur. Unlike the above previous method, which has proven successful only with simple deblurring scenarios, we demonstrate that our method succeeds on a variety of real-world examples. We provide quantitative and qualitative evaluation of our method and show that it outperforms the state-of-the-art.
/** * Container of result of an Ivy resolve and maybe retrieve. */ public class ResolveResult { private final boolean previousUsed; private final Set<ArtifactDownloadReport> artifactReports = new LinkedHashSet<>(); private Set<String> problemMessages = new HashSet<>(); private final ResolveReport report; private final Map<ModuleRevisionId, Artifact[]> artifactsByDependency = new HashMap<>(); /** * Mapping of resolved artifact to their retrieved path, <code>null</code> if there were no * retrieve * <p> * The paths may be relative It shouldn't be an issue has every relative path should be relative * to the eclipse project FIXME: not sure why the Ivy API is returning a set of paths... */ private Map<ArtifactDownloadReport, Set<String>> retrievedArtifacts; /** * Constructor to be used when the resolve have been refreshed. */ ResolveResult() { report = null; previousUsed = true; } /** * Constructor to be used based on the fresh resolve report. * * @param report ResolveReport */ ResolveResult(ResolveReport report) { this.report = report; previousUsed = false; problemMessages = new HashSet<>(report.getAllProblemMessages()); } /** * @return <code>true</code> if the refresh has been successful */ public boolean isPreviousUsed() { return previousUsed; } /** * @return the report from the resolve, <code>null</code> if there was a successful refresh */ public ResolveReport getReport() { return report; } /** * Get the list of errors of the resolve. They will be used to build a * {@link org.eclipse.core.runtime.MultiStatus}. * * @return the list of error message */ public Set<String> getProblemMessages() { return problemMessages; } void addArtifactReports(ArtifactDownloadReport[] reports) { artifactReports.addAll(Arrays.asList(reports)); } void addArtifactReport(ArtifactDownloadReport report) { artifactReports.add(report); } void putArtifactsForDep(ModuleRevisionId resolvedId, Artifact[] allArtifacts) { artifactsByDependency.put(resolvedId, allArtifacts); } /** * @return the reports of the artifacts resolved */ public Set<ArtifactDownloadReport> getArtifactReports() { return artifactReports; } /** * @return the reports of the artifacts by dependency */ public Map<ModuleRevisionId, Artifact[]> getArtifactsByDependency() { return artifactsByDependency; } void setRetrievedArtifacts(Map<ArtifactDownloadReport, Set<String>> retrievedArtifacts) { this.retrievedArtifacts = retrievedArtifacts; } /** * @return the path(s) of the retrieved artifacts */ public Map<ArtifactDownloadReport, Set<String>> getRetrievedArtifacts() { return retrievedArtifacts; } }
/* Remote utility routines for the remote server for GDB. Copyright (C) 1993-2017 Free Software Foundation, Inc. This file is part of GDB. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef REMOTE_UTILS_H #define REMOTE_UTILS_H extern int remote_debug; extern int noack_mode; extern int transport_is_reliable; int gdb_connected (void); #define STDIO_CONNECTION_NAME "stdio" int remote_connection_is_stdio (void); ptid_t read_ptid (char *buf, char **obuf); char *write_ptid (char *buf, ptid_t ptid); int putpkt (char *buf); int putpkt_binary (char *buf, int len); int putpkt_notif (char *buf); int getpkt (char *buf); void remote_prepare (const char *name); void remote_open (const char *name); void remote_close (void); void write_ok (char *buf); void write_enn (char *buf); void initialize_async_io (void); void enable_async_io (void); void disable_async_io (void); void check_remote_input_interrupt_request (void); void prepare_resume_reply (char *buf, ptid_t ptid, struct target_waitstatus *status); const char *decode_address_to_semicolon (CORE_ADDR *addrp, const char *start); void decode_address (CORE_ADDR *addrp, const char *start, int len); void decode_m_packet (char *from, CORE_ADDR * mem_addr_ptr, unsigned int *len_ptr); void decode_M_packet (char *from, CORE_ADDR * mem_addr_ptr, unsigned int *len_ptr, unsigned char **to_p); int decode_X_packet (char *from, int packet_len, CORE_ADDR * mem_addr_ptr, unsigned int *len_ptr, unsigned char **to_p); int decode_xfer_write (char *buf, int packet_len, CORE_ADDR *offset, unsigned int *len, unsigned char *data); int decode_search_memory_packet (const char *buf, int packet_len, CORE_ADDR *start_addrp, CORE_ADDR *search_space_lenp, gdb_byte *pattern, unsigned int *pattern_lenp); void clear_symbol_cache (struct sym_cache **symcache_p); int look_up_one_symbol (const char *name, CORE_ADDR *addrp, int may_ask_gdb); int relocate_instruction (CORE_ADDR *to, CORE_ADDR oldloc); void monitor_output (const char *msg); #endif /* REMOTE_UTILS_H */
<gh_stars>1-10 /* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2002-2008, Open Source Geospatial Foundation (OSGeo) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.styling; import java.util.ArrayList; import java.util.List; import org.geotools.util.Utilities; import org.opengis.filter.expression.Function; import org.opengis.style.StyleVisitor; /** * A simple implementation of the color map interface. * * @author iant * @author aaime * * * @source $URL$ */ public class ColorMapImpl implements ColorMap { private final Function function; private List<ColorMapEntry> list = new ArrayList<ColorMapEntry>(); private int type = ColorMap.TYPE_RAMP; private boolean extendedColors; public ColorMapImpl(){ function = null; } public ColorMapImpl(Function function){ this.function = function; } public void addColorMapEntry(ColorMapEntry entry) { list.add(entry); } public ColorMapEntry[] getColorMapEntries() { return (ColorMapEntry[]) list.toArray(new ColorMapEntry[0]); } public ColorMapEntry getColorMapEntry(int index) { return (ColorMapEntry) list.get(index); } /** * @see ColorMap#getType() */ public int getType() { return type; } /** * @see ColorMap#setType(int) */ public void setType(int type) { if ((type < TYPE_RAMP) || (type > TYPE_VALUES)) { throw new IllegalArgumentException(); } this.type = type; } public Object accept(StyleVisitor visitor,Object data) { return visitor.visit(this,data); } public boolean getExtendedColors() { return extendedColors; } public void setExtendedColors(boolean extended) { extendedColors=extended; } public Function getFunction() { return function; } public void accept(org.geotools.styling.StyleVisitor visitor) { visitor.visit(this); } @Override public int hashCode() { final int PRIME = 1000003; int result = 0; if (function != null){ result = (PRIME * result) + function.hashCode(); } if (list != null) { result = (PRIME * result) + list.hashCode(); } result = (PRIME * result) + type; result = (PRIME * result) + (extendedColors ? 1 : 0); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof ColorMapImpl) { ColorMapImpl other = (ColorMapImpl) obj; return Utilities.equals(function, other.function) && Utilities.equals(list, other.list) && Utilities.equals(type, other.type) && Utilities.equals(extendedColors, other.extendedColors); } return false; } static ColorMapImpl cast(org.opengis.style.ColorMap colorMap) { if( colorMap == null ){ return null; } else if ( colorMap instanceof ColorMapImpl){ return (ColorMapImpl) colorMap; } else { return null; // unable to handle the translation at this time } } }
def find_lca(tnode1: TreeNode, tnode2: TreeNode) -> TreeNode: path1, path2 = map(reversed, (tnode1.path, tnode2.path)) path1, path2 = map(list, (path1, path2)) higher_depth = tnode1.depth if tnode1.depth < tnode2.depth else tnode2.depth path1 = path1[-higher_depth: ] path2 = path2[-higher_depth: ] for anc1, anc2 in zip(path1, path2): if anc1.name == anc2.name: lca = anc1 break return lca
<gh_stars>10-100 package ox.integration.actions.migrations; import ox.engine.exception.OxException; import ox.engine.internal.OxAction; import ox.engine.internal.OxEnvironment; import ox.engine.structure.Migration; public class V0001__remove_collection implements Migration { @Override public void up(OxEnvironment env) throws OxException { env.execute(OxAction.removeCollection("collection1")); } @Override public void down(OxEnvironment env) throws OxException { } }
<gh_stars>0 package service import ( "context" ) type Service interface { Run(ctx context.Context, ready func()) error Shutdown(ctx context.Context) error }
def _generate_filters(self, df, column_lst): filter_dict = dict() for column in column_lst: filter_dict[column] = list(set(df[column])) return cartesian_product(filter_dict)
def guess_nthreads(self,default): omp=int(os.environ.get('OMP_NUM_THREADS',None)) mkl=int(os.environ.get('MKL_NUM_THREADS',None)) if omp is None and mkl is None: return default omp = (1 if omp is None else omp) mkl = (1 if mkl is None else mkl) return omp*mkl
package infra import ( "context" "fmt" "strings" "time" "github.com/golang/glog" e2e "github.com/openshift/cluster-api-actuator-pkg/pkg/e2e/framework" mapiv1beta1 "github.com/openshift/cluster-api/pkg/apis/machine/v1beta1" controllernode "github.com/openshift/cluster-api/pkg/controller/node" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/uuid" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/discovery" "k8s.io/client-go/dynamic" "k8s.io/client-go/scale" "k8s.io/utils/pointer" runtimeclient "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/apiutil" ) const ( machineRoleLabel = "machine.openshift.io/cluster-api-machine-role" machineAPIGroup = "machine.openshift.io" ) func isOneMachinePerNode(client runtimeclient.Client) bool { machineList := mapiv1beta1.MachineList{} nodeList := corev1.NodeList{} if err := wait.PollImmediate(5*time.Second, e2e.WaitShort, func() (bool, error) { if err := client.List(context.TODO(), &machineList, runtimeclient.InNamespace(e2e.TestContext.MachineApiNamespace)); err != nil { glog.Errorf("Error querying api for machineList object: %v, retrying...", err) return false, nil } if err := client.List(context.TODO(), &nodeList, runtimeclient.InNamespace(e2e.TestContext.MachineApiNamespace)); err != nil { glog.Errorf("Error querying api for nodeList object: %v, retrying...", err) return false, nil } glog.Infof("Expecting the same number of machines and nodes, have %d nodes and %d machines", len(nodeList.Items), len(machineList.Items)) if len(machineList.Items) != len(nodeList.Items) { return false, nil } nodeNameToMachineAnnotation := make(map[string]string) for _, node := range nodeList.Items { if _, ok := node.Annotations[controllernode.MachineAnnotationKey]; !ok { glog.Errorf("Node %q does not have a MachineAnnotationKey %q, retrying...", node.Name, controllernode.MachineAnnotationKey) return false, nil } nodeNameToMachineAnnotation[node.Name] = node.Annotations[controllernode.MachineAnnotationKey] } for _, machine := range machineList.Items { if machine.Status.NodeRef == nil { glog.Errorf("Machine %q has no NodeRef, retrying...", machine.Name) return false, nil } nodeName := machine.Status.NodeRef.Name if nodeNameToMachineAnnotation[nodeName] != fmt.Sprintf("%s/%s", e2e.TestContext.MachineApiNamespace, machine.Name) { glog.Errorf("Node name %q does not match expected machine name %q, retrying...", nodeName, machine.Name) return false, nil } glog.Infof("Machine %q is linked to node %q", machine.Name, nodeName) } return true, nil }); err != nil { glog.Errorf("Error checking isOneMachinePerNode: %v", err) return false } return true } // getClusterSize returns the number of nodes of the cluster func getClusterSize(client runtimeclient.Client) (int, error) { nodes, err := e2e.GetNodes(client) if err != nil { return 0, fmt.Errorf("error getting nodes: %v", err) } glog.Infof("Cluster size is %d nodes", len(nodes)) return len(nodes), nil } // machineSetsSnapShotLogs logs the state of all the machineSets in the cluster func machineSetsSnapShotLogs(client runtimeclient.Client) error { machineSets, err := e2e.GetMachineSets(context.TODO(), client) if err != nil { return fmt.Errorf("error getting machines: %v", err) } for _, machineset := range machineSets { glog.Infof("MachineSet %q replicas %d. Ready: %d, available %d", machineset.Name, pointer.Int32PtrDerefOr(machineset.Spec.Replicas, e2e.DefaultMachineSetReplicas), machineset.Status.ReadyReplicas, machineset.Status.AvailableReplicas) } return nil } // getMachinesFromMachineSet returns an array of machines owned by a given machineSet func getMachinesFromMachineSet(client runtimeclient.Client, machineSet mapiv1beta1.MachineSet) ([]mapiv1beta1.Machine, error) { machines, err := e2e.GetMachines(context.TODO(), client) if err != nil { return nil, fmt.Errorf("error getting machines: %v", err) } var machinesForSet []mapiv1beta1.Machine for key := range machines { if metav1.IsControlledBy(&machines[key], &machineSet) { machinesForSet = append(machinesForSet, machines[key]) } } return machinesForSet, nil } // deleteMachine deletes a specific machine and returns an error otherwise func deleteMachine(client runtimeclient.Client, machine *mapiv1beta1.Machine) error { return wait.PollImmediate(1*time.Second, time.Minute, func() (bool, error) { if err := client.Delete(context.TODO(), machine); err != nil { glog.Errorf("Error querying api for machine object %q: %v, retrying...", machine.Name, err) return false, err } return true, nil }) } // getNodesFromMachineSet returns an array of nodes backed by machines owned by a given machineSet func getNodesFromMachineSet(client runtimeclient.Client, machineSet mapiv1beta1.MachineSet) ([]*corev1.Node, error) { machines, err := getMachinesFromMachineSet(client, machineSet) if err != nil { return nil, fmt.Errorf("error calling getMachinesFromMachineSet %v", err) } var nodes []*corev1.Node for key := range machines { node, err := getNodeFromMachine(client, &machines[key]) if err != nil { return nil, fmt.Errorf("error getting node from machine %q: %v", machines[key].Name, err) } nodes = append(nodes, node) } glog.Infof("MachineSet %q have %d nodes", machineSet.Name, len(nodes)) return nodes, nil } // getNodeFromMachine returns the node object referenced by machine.Status.NodeRef func getNodeFromMachine(client runtimeclient.Client, machine *mapiv1beta1.Machine) (*corev1.Node, error) { var node corev1.Node if machine.Status.NodeRef == nil { glog.Errorf("Machine %q has no NodeRef", machine.Name) return nil, fmt.Errorf("machine %q has no NodeRef", machine.Name) } key := runtimeclient.ObjectKey{Namespace: machine.Status.NodeRef.Namespace, Name: machine.Status.NodeRef.Name} if err := client.Get(context.Background(), key, &node); err != nil { return nil, fmt.Errorf("error getting node %q: %v", node.Name, err) } glog.Infof("Machine %q is backing node %q", machine.Name, node.Name) return &node, nil } // nodesAreReady returns true if an array of nodes are all ready func nodesAreReady(nodes []*corev1.Node) bool { // All nodes needs to be ready for key := range nodes { if !e2e.IsNodeReady(nodes[key]) { glog.Errorf("Node %q is not ready. Conditions are: %v", nodes[key].Name, nodes[key].Status.Conditions) return false } glog.Infof("Node %q is ready. Conditions are: %v", nodes[key].Name, nodes[key].Status.Conditions) } return true } // scaleMachineSet scales a machineSet with a given name to the given number of replicas func scaleMachineSet(name string, replicas int) error { scaleClient, err := getScaleClient() if err != nil { return fmt.Errorf("error calling getScaleClient %v", err) } scale, err := scaleClient.Scales(e2e.TestContext.MachineApiNamespace).Get(schema.GroupResource{Group: machineAPIGroup, Resource: "MachineSet"}, name) if err != nil { return fmt.Errorf("error calling scaleClient.Scales get: %v", err) } scaleUpdate := scale.DeepCopy() scaleUpdate.Spec.Replicas = int32(replicas) _, err = scaleClient.Scales(e2e.TestContext.MachineApiNamespace).Update(schema.GroupResource{Group: machineAPIGroup, Resource: "MachineSet"}, scaleUpdate) if err != nil { return fmt.Errorf("error calling scaleClient.Scales update: %v", err) } return nil } // getScaleClient returns a ScalesGetter object to manipulate scale subresources func getScaleClient() (scale.ScalesGetter, error) { cfg, err := e2e.LoadConfig() if err != nil { return nil, fmt.Errorf("error getting config %v", err) } mapper, err := apiutil.NewDiscoveryRESTMapper(cfg) if err != nil { return nil, fmt.Errorf("error calling NewDiscoveryRESTMapper %v", err) } discovery := discovery.NewDiscoveryClientForConfigOrDie(cfg) scaleKindResolver := scale.NewDiscoveryScaleKindResolver(discovery) scaleClient, err := scale.NewForConfig(cfg, mapper, dynamic.LegacyAPIPathResolverFunc, scaleKindResolver) if err != nil { return nil, fmt.Errorf("error calling building scale client %v", err) } return scaleClient, nil } // nodesSnapShotLogs logs the state of all the nodes in the cluster func nodesSnapShotLogs(client runtimeclient.Client) error { nodes, err := e2e.GetNodes(client) if err != nil { return fmt.Errorf("error getting nodes: %v", err) } for key, node := range nodes { glog.Infof("Node %q. Ready: %t. Unschedulable: %t", node.Name, e2e.IsNodeReady(&nodes[key]), node.Spec.Unschedulable) } return nil } func waitForClusterSizeToBeHealthy(client runtimeclient.Client, targetSize int) error { if err := wait.PollImmediate(5*time.Second, e2e.WaitLong, func() (bool, error) { glog.Infof("Cluster size expected to be %d nodes", targetSize) if err := machineSetsSnapShotLogs(client); err != nil { return false, err } if err := nodesSnapShotLogs(client); err != nil { return false, err } finalClusterSize, err := getClusterSize(client) if err != nil { return false, err } return finalClusterSize == targetSize, nil }); err != nil { return fmt.Errorf("Did not reach expected number of nodes: %v", err) } glog.Infof("waiting for all nodes to be ready") if err := e2e.WaitUntilAllNodesAreReady(client); err != nil { return err } glog.Infof("waiting for all nodes to be schedulable") if err := waitUntilAllNodesAreSchedulable(client); err != nil { return err } glog.Infof("waiting for each node to be backed by a machine") if !isOneMachinePerNode(client) { return fmt.Errorf("One machine per node condition violated") } return nil } // waitUntilAllNodesAreSchedulable waits for all cluster nodes to be schedulable and returns an error otherwise func waitUntilAllNodesAreSchedulable(client runtimeclient.Client) error { return wait.PollImmediate(1*time.Second, time.Minute, func() (bool, error) { nodeList := corev1.NodeList{} if err := client.List(context.TODO(), &nodeList); err != nil { glog.Errorf("error querying api for nodeList object: %v, retrying...", err) return false, nil } // All nodes needs to be schedulable for _, node := range nodeList.Items { if node.Spec.Unschedulable == true { glog.Errorf("Node %q is unschedulable", node.Name) return false, nil } glog.Infof("Node %q is schedulable", node.Name) } return true, nil }) } func machineFromMachineset(machineset *mapiv1beta1.MachineSet) *mapiv1beta1.Machine { randomUUID := string(uuid.NewUUID()) machine := &mapiv1beta1.Machine{ ObjectMeta: metav1.ObjectMeta{ Namespace: machineset.Namespace, Name: "machine-" + randomUUID[:6], Labels: machineset.Labels, }, Spec: machineset.Spec.Template.Spec, } if machine.Spec.ObjectMeta.Labels == nil { machine.Spec.ObjectMeta.Labels = map[string]string{} } for key := range nodeDrainLabels { if _, exists := machine.Spec.ObjectMeta.Labels[key]; exists { continue } machine.Spec.ObjectMeta.Labels[key] = nodeDrainLabels[key] } return machine } func waitUntilNodesAreReady(client runtimeclient.Client, listOptFncs []runtimeclient.ListOptionFunc, nodeCount int) error { return wait.PollImmediate(e2e.RetryMedium, e2e.WaitLong, func() (bool, error) { nodes := corev1.NodeList{} if err := client.List(context.TODO(), &nodes, listOptFncs...); err != nil { glog.Errorf("Error querying api for Node object: %v, retrying...", err) return false, nil } // expecting nodeGroupSize nodes readyNodes := 0 for _, node := range nodes.Items { if _, exists := node.Labels[e2e.WorkerNodeRoleLabel]; !exists { continue } if !e2e.IsNodeReady(&node) { continue } readyNodes++ } if readyNodes < nodeCount { glog.Errorf("Expecting %v nodes with %#v labels in Ready state, got %v", nodeCount, nodeDrainLabels, readyNodes) return false, nil } glog.Infof("Expected number (%v) of nodes with %v label in Ready state found", nodeCount, nodeDrainLabels) return true, nil }) } func waitUntilNodesAreDeleted(client runtimeclient.Client, listOptFncs []runtimeclient.ListOptionFunc) error { return wait.PollImmediate(e2e.RetryMedium, e2e.WaitLong, func() (bool, error) { nodes := corev1.NodeList{} if err := client.List(context.TODO(), &nodes, listOptFncs...); err != nil { glog.Errorf("Error querying api for Node object: %v, retrying...", err) return false, nil } // expecting nodeGroupSize nodes nodeCounter := 0 for _, node := range nodes.Items { if _, exists := node.Labels[e2e.WorkerNodeRoleLabel]; !exists { continue } if !e2e.IsNodeReady(&node) { continue } nodeCounter++ } if nodeCounter > 0 { glog.Errorf("Expecting to found 0 nodes with %#v labels , got %v", nodeDrainLabels, nodeCounter) return false, nil } glog.Infof("Found 0 number of nodes with %v label as expected", nodeDrainLabels) return true, nil }) } func waitUntilAllRCPodsAreReady(client runtimeclient.Client, rc *corev1.ReplicationController) error { return wait.PollImmediate(e2e.RetryMedium, e2e.WaitLong, func() (bool, error) { rcObj := corev1.ReplicationController{} key := types.NamespacedName{ Namespace: rc.Namespace, Name: rc.Name, } if err := client.Get(context.TODO(), key, &rcObj); err != nil { glog.Errorf("Error querying api RC %q object: %v, retrying...", rc.Name, err) return false, nil } if rcObj.Status.ReadyReplicas == 0 { glog.Infof("Waiting for at least one RC ready replica, ReadyReplicas: %v, Replicas: %v", rcObj.Status.ReadyReplicas, rcObj.Status.Replicas) return false, nil } glog.Infof("Waiting for RC ready replicas, ReadyReplicas: %v, Replicas: %v", rcObj.Status.ReadyReplicas, rcObj.Status.Replicas) return rcObj.Status.Replicas == rcObj.Status.ReadyReplicas, nil }) } func verifyNodeDraining(client runtimeclient.Client, targetMachine *mapiv1beta1.Machine, rc *corev1.ReplicationController) (string, error) { var drainedNodeName string err := wait.PollImmediate(e2e.RetryMedium, e2e.WaitLong, func() (bool, error) { machine := mapiv1beta1.Machine{} key := types.NamespacedName{ Namespace: targetMachine.Namespace, Name: targetMachine.Name, } if err := client.Get(context.TODO(), key, &machine); err != nil { glog.Errorf("Error querying api machine %q object: %v, retrying...", targetMachine.Name, err) return false, nil } if machine.Status.NodeRef == nil || machine.Status.NodeRef.Kind != "Node" { glog.Errorf("Machine %q not linked to a node", machine.Name) return false, nil } drainedNodeName = machine.Status.NodeRef.Name node := corev1.Node{} if err := client.Get(context.TODO(), types.NamespacedName{Name: drainedNodeName}, &node); err != nil { glog.Errorf("Error querying api node %q object: %v, retrying...", drainedNodeName, err) return false, nil } if !node.Spec.Unschedulable { glog.Errorf("Node %q is expected to be marked as unschedulable, it is not", node.Name) return false, nil } glog.Infof("Node %q is mark unschedulable as expected", node.Name) pods := corev1.PodList{} if err := client.List(context.TODO(), &pods, runtimeclient.MatchingLabels(rc.Spec.Selector)); err != nil { glog.Errorf("Error querying api for Pods object: %v, retrying...", err) return false, nil } podCounter := 0 for _, pod := range pods.Items { if pod.Spec.NodeName != machine.Status.NodeRef.Name { continue } if !pod.DeletionTimestamp.IsZero() { continue } podCounter++ } glog.Infof("Have %v pods scheduled to node %q", podCounter, machine.Status.NodeRef.Name) // Verify we have enough pods running as well rcObj := corev1.ReplicationController{} key = types.NamespacedName{ Namespace: rc.Namespace, Name: rc.Name, } if err := client.Get(context.TODO(), key, &rcObj); err != nil { glog.Errorf("Error querying api RC %q object: %v, retrying...", rc.Name, err) return false, nil } // The point of the test is to make sure majority of the pods are rescheduled // to other nodes. Pod disruption budget makes sure at most one pod // owned by the RC is not Ready. So no need to test it. Though, useful to have it printed. glog.Infof("RC ReadyReplicas: %v, Replicas: %v", rcObj.Status.ReadyReplicas, rcObj.Status.Replicas) // This makes sure at most one replica is not ready if rcObj.Status.Replicas-rcObj.Status.ReadyReplicas > 1 { return false, fmt.Errorf("pod disruption budget not respected, node was not properly drained") } // Depends on timing though a machine can be deleted even before there is only // one pod left on the node (that is being evicted). if podCounter > 2 { glog.Infof("Expecting at most 2 pods to be scheduled to drained node %q, got %v", machine.Status.NodeRef.Name, podCounter) return false, nil } glog.Info("Expected result: all pods from the RC up to last one or two got scheduled to a different node while respecting PDB") return true, nil }) return drainedNodeName, err } func waitUntilNodeDoesNotExists(client runtimeclient.Client, nodeName string) error { return wait.PollImmediate(e2e.RetryMedium, e2e.WaitLong, func() (bool, error) { node := corev1.Node{} key := types.NamespacedName{ Name: nodeName, } err := client.Get(context.TODO(), key, &node) if err == nil { glog.Errorf("Node %q not yet deleted", nodeName) return false, nil } if !strings.Contains(err.Error(), "not found") { glog.Errorf("Error querying api node %q object: %v, retrying...", nodeName, err) return false, nil } glog.Infof("Node %q successfully deleted", nodeName) return true, nil }) }
Theological Education between the University and the Church Abstract This article examines the new ‘Common Awards’ partnership between the Church of England and Durham University, and asks what the university and the church have to gain from one another in the area of theological education. I argue that the university can help extend the range of critical conversations in which the church engages, and help form some of the intellectual virtues required in those who pursue this reflection. In return, the church can help the university to recognize its nature as a school of intellectual virtue, its need for insistent and pervasive discussion of the good that it does in the world, and its need to resist the pressures that threaten to thin its life down to technocratic rationality. I also argue that, for both the church’s purposes and the university’s purposes, the learning pursued in this partnership needs to be understood as deeply engaged with the life and practice of the church-as taking off from attentive description of that practice, and as returning to the refinement, extension and transformation of that practice, however long might be the journeys of abstraction and reflection that take place in between.
// Copyright (c) 2021 The Orbit 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 "LibunwindstackMaps.h" namespace orbit_linux_tracing { namespace { class LibunwindstackMapsImpl : public LibunwindstackMaps { public: explicit LibunwindstackMapsImpl(std::unique_ptr<unwindstack::BufferMaps> maps) : maps_{std::move(maps)} {} unwindstack::MapInfo* Find(uint64_t pc) override { return maps_->Find(pc); } unwindstack::Maps* Get() override { return maps_.get(); } void AddAndSort(uint64_t start, uint64_t end, uint64_t offset, uint64_t flags, const std::string& name, uint64_t load_bias) override { maps_->Add(start, end, offset, flags, name, load_bias); maps_->Sort(); } private: std::unique_ptr<unwindstack::BufferMaps> maps_; }; } // namespace std::unique_ptr<LibunwindstackMaps> LibunwindstackMaps::ParseMaps(const std::string& maps_buffer) { auto maps = std::make_unique<unwindstack::BufferMaps>(maps_buffer.c_str()); if (!maps->Parse()) { return nullptr; } return std::make_unique<LibunwindstackMapsImpl>(std::move(maps)); } } // namespace orbit_linux_tracing
Automated Temporal Equilibrium Analysis: Verification and Synthesis of Multi-Player Games In the context of multi-agent systems, the rational verification problem is concerned with checking which temporal logic properties will hold in a system when its constituent agents are assumed to behave rationally and strategically in pursuit of individual objectives. Typically, those objectives are expressed as temporal logic formulae which the relevant agent desires to see satisfied. Unfortunately, rational verification is computationally complex, and requires specialised techniques in order to obtain practically useable implementations. In this paper, we present such a technique. This technique relies on a reduction of the rational verification problem to the solution of a collection of parity games. Our approach has been implemented in the Equilibrium Verification Environment (EVE) system. The EVE system takes as input a model of a concurrent/multi-agent system represented using the Simple Reactive Modules Language (SRML), where agent goals are represented as Linear Temporal Logic (LTL) formulae, together with a claim about the equilibrium behaviour of the system, also expressed as an LTL formula. EVE can then check whether the LTL claim holds on some (or every) computation of the system that could arise through agents choosing Nash equilibrium strategies; it can also check whether a system has a Nash equilibrium, and synthesise individual strategies for players in the multi-player game. After presenting our basic framework, we describe our new technique and prove its correctness. We then describe our implementation in the EVE system, and present experimental results which show that EVE performs favourably in comparison to other existing tools that support rational verification. Introduction e deployment of AI technologies in a wide range of application areas over the past decade has brought the problem of verifying such systems into sharp focus. Veri cation is the problem of ensuring that a particular system is correct with respect to some speci cation. e most successful approach to automated formal veri cation is that of model checking . With this approach, we rst derive a nite state abstract model of the system S being studied; a common approach involves representing the system as a directed graph in which vertices correspond to states of the system, and edges correspond to the execution of program instructions, or the performance of actions; branching in the graph represents either input from the environment, or choices available to components of the system. With this approach, the directed graph is typically referred to as a labelled transition system, or Kripke structure: each path through the transition system represents a possible execution or computation of the system S. Correctness properties of interest are expressed as formulae ϕ of propositional temporal logic-the most popular such logics for this purpose are Linear Temporal Logic (LTL) and the Computation Tree Logic (CTL). In the case of properties ϕ expressed as LTL formulae, we typically want to check whether ϕ is satis ed on some or all possible computations of S, that is, on some or all possible paths through the transition system/Kripke structure representing S. Great advances have been made in model checking since the approach was rst proposed in the early 1980s, and the technique is now widely used in industry. Nevertheless, the veri cation of practical so ware systems is by no means a solved problem, and remains the subject of intense ongoing research. e veri cation of AI systems, however, raises a distinctive new set of challenges. e present paper is concerned with the problem of verifying multi-agent systems, which are AI systems consisting of multiple interacting semi-autonomous so ware components known as agents . So ware agents were originally proposed in the late 1980s, but it is only over the past decade that the so ware agent paradigm has been widely adopted. At the time of writing, so ware agents are ubiquitous: we have so ware agents in our phone (e.g., Siri), processing requests online, automatically trading in global markets, controlling complex navigation systems (e.g., those in self-driving cars), and even carrying out tasks on our behalf in our homes (e.g., Alexa). Typically, these agents do not work in isolation: they may interact with humans or with other so ware agents. e eld of multi-agent systems is concerned with understanding and engineering systems that have these characteristics. We typically assume that agents are acting in pursuit of goals or preferences that are delegated to them by their users. However, whether an agent is able to achieve its goal, or the extent to which it can bring about its preferences, will be directly in uenced by the behaviour of other agents. us, to act optimally, an agent must reason strategically, taking into account the goals/preferences of other agents, and the fact that they too will be acting strategically in the pursuit of these, taking into account the goals/preferences of other agents and their own strategic behaviour. Game theory is the mathematical theory of strategic interaction, and as such, it provides a natural set of tools for reasoning about multi-agent systems . With respect to the problem of verifying multi-agent systems, the relevance of game theory is as follows. Suppose we are interested in whether a multi-agent system S, populated by self-interested agents, might exhibit some property represented by an LTL formula ϕ. We can, of course, directly apply standard model checking techniques, to determine whether ϕ holds on some or all computations of S. However, given that our agents are assumed to act rationally, whether ϕ holds on some or all computations is not relevant if the computations in question involve irrational choices on behalf of some agents in the system. A much more relevant question, therefore, is whether ϕ holds on some or all computations that could result from agents in the system making rational choices. is raises the question of what counts as a rational choice by the agents in the system, and for this game theory provides a number of answers, in the form of solution concepts such as Nash equilibrium . us, from the point of view of game theory, correct behaviour would correspond to rational behaviour according to some game theoretic solution concept, which is another way of saying that agents in the system will act optimally with respect to their preferences/goals, under the assumption that other agents do the same. is approach to reasoning about the behaviour of multi-agent AI systems establishes a natural connection between multi-agent systems and multi-player games: agents correspond to players, computations of the multi-agent system correspond to plays of the game, individual agent behaviours correspond to player strategies (which de ne how players make choices in the system over time), and correct behaviour would correspond to rational behaviour-in our case, player behaviour that is consistent with the set of Nash equilibria of the multi-player game, whenever such a set is non-empty. Our main interest in this paper is the development of the theory, algorithms, and tools for the automated game theoretic analysis of concurrent and multi-agent systems, and in particular, the analysis of temporal logic properties that will hold in a multi-agent system under the assumption that players choose strategies which form a Nash equilibrium 1 . e connection between AI systems (modelled as multi-agent systems) and multiplayer games is well-established, but one may still wonder why correct behaviour for the AI system should correspond to rational behaviour in the multi-player game. is is a legitimate question, especially, because game theory o ers very many di erent notions of rationality, and therefore of optimal behaviour in the system/game. For instance, solution concepts such as subgame-perfect Nash equilibrium (SPNE) and strong Nash equilibrium (SNE) are re nements of Nash equilibrium where the notion of rationality needs to satisfy stronger requirements. Consequently, there may be executions of a multi-agent system that would correspond to a Nash equilibrium of the associated multi-player game (thus, regarded as correct behaviours of the multi- 1 Although in this work we focus on Nash equilibrium, a similar methodology may be applied using re nements of Nash equilibrium and other solution concepts. agent system), but which do not correspond to a subgame-perfect Nash equilibrium or to a strong Nash equilibrium of the associated multi-player game. We do not argue that Nash equilibrium is the only solution concept of relevance in the game theoretic analysis of multi-agent systems, but we believe (as do many others ) that Nash equilibrium is a natural and appropriate starting point for such an analysis. Taking Nash equilibrium as our baseline notion of rationality in multi-player games, and therefore of correctness in multi-agent systems, we focus our study on two problems related to the temporal equilibrium analysis of multi-agent systems , as we now explain. Synthesis and Rational Veri cation. e two main problems of interest to us are the rational veri cation and automated synthesis problems for concurrent and multi-agent systems modelled as multi-player games. In the rational veri cation problem, we desire to check which temporal logic properties are satis ed by the system/game in equilibrium, that is, temporal logic properties satis ed by executions of the multiagent system generated by strategies that form a Nash equilibrium. A li le more formally, let P 1 , . . . , P n be the agents in our concurrent and multi-agent system, and let NE(P 1 , . . . , P n ) denote the set of all executions, herea er called runs, of the system that could be generated by agents selecting strategies that form a Nash equilibrium. Finally, let ϕ be an LTL formula. en, in the rational veri cation problem, we want to know whether for some/every run π ∈ NE(P 1 , . . . , P n ) we have π |= ϕ. In the automated synthesis problem, on the other hand, we additionally desire to construct a pro le of strategies for players so that the resulting pro le is an equilibrium of the multi-player game, and induces a run that satis es a given property of interest, again expressed as a temporal logic formula. at is, we are given the system P 1 , . . . , P n , and a temporal logic property ϕ, and we are asked to compute Nash equilibrium strategies σ = (σ 1 , . . . , σ n ), one for each player in the game, that would result in ϕ being satis ed in the run π( σ) that would be generated when these strategies are enacted. Our Approach. In this paper, we present a new approach to the rational veri cation and automated synthesis problems for concurrent and multi-agent systems. In particular, we develop a novel technique that can be used for both rational verication and automated synthesis using a reduction to the solution of a collection of parity games. e technique can be e ciently implemented making use of powerful techniques for parity games and temporal logic synthesis and veri cation, and has been deployed in the Equilibrium V eri cation Environment (EVE ), which supports high-level descriptions of systems/games using the Simple Reactive Modules Language (SRML ) and temporal logic speci cations given by Linear Temporal Logic formulae . e central decision problem that we consider is that of N E , the problem of checking if the set of Nash equilibria in a multi-player game is empty; as we will later show, rational veri cation and synthesis can be reduced to this problem. If we consider concurrent and multi-player games in which players have goals expressed as temporal logic formulae, this problem is known to be 2EXPTIME-complete for a wide range of system representations and temporal logic languages. For instance, for games with perfect information played on labelled graphs, the problem is 2EXPTIMEcomplete when goals are given as LTL formulae , and 2EXPTIME-hard when goals are given in CTL . e problem is 2EXPTIME-complete even if succinct representations or only two-player games are considered, and becomes undecidable if imperfect information and more than two players are allowed , showing the very high complexity of solving this problem, from both practical and theoretical viewpoints. A common feature of the results above mentioned is that-modulo minor variationstheir solutions are, in the end, reduced to the construction of an alternating parity automaton over in nite trees (APT ) which are then checked for non-emptiness. Here, we present a novel, simpler, and more direct technique for checking the existence of Nash equilibria in games where players have goals expressed in LTL. In particular, our technique does not rely on the solution of an APT. Instead, we reduce the problem to the solution of (a collection of) parity games , which are widely used for synthesis and veri cation problems. Formally, a parity game is a two-player zero-sum turn-based game given by a partitioned into Player 0 (V 0 ) and Player 1 (V 1 ) states, respectively, E ⊆ V × V is a set of edges/transitions, and α : V → N is a labelling priority function. Player 0 wins if the smallest priority that occurs in nitely o en in the in nite play is even. Otherwise, player 1 wins. It is known that solving a parity game (checking which player has a winning strategy) is in NP ∩ coNP , and can be solved in quasipolynomial time 2 . Our technique uses parity games in the following way. We take as input a game G (representing a concurrent and multi-agent system) and build a parity game H whose sets of states and transitions are doubly exponential in the size of the input but with priority function only exponential in the size of the input game. Using a deterministic Stree automaton on in nite words (DSW ), we then solve the parity game, leading to a decision procedure that is, overall, in 2EXPTIME, and, therefore, given the hardness results we mentioned above, essentially optimal. Context. Games have several dimensions: for example, they may be cooperative or non-cooperative; have perfect or imperfect information; have perfect or imperfect recall; be stochastic or not; amongst many other features. Each of these aspects will have a modelling and computational impact on the work to be developed, and so it is important to be precise about the nature of the games we are studying, and therefore the assumptions underpinning our approach. Our framework considers non-cooperative multi-player general-sum games with perfect information, with Nash equilibrium as the main game-theoretic solution con- of the features of our framework -chie y, the fact that players have LTL goals and games are played on nite structures -considering deterministic strategies modelled as nite-state machines does not represent a restriction: in our framework, anything that a player can achieve with a perfect-recall strategy can also be achieved with a nite-state machine strategy (see, e.g., for the formal results). Finally, we note that our games have equilibria that are bisimulation invariant: that is, bisimilar structures have the same set of Nash equilibria. is is a highly desirable property, and to the best of our knowledge, in this respect our work is unique in the computer science and multi-agent systems literatures. e EVE System. e technique outlined above and described in detail in this paper has been successfully implemented in the Equilibrium V eri cation Environment (EVE) system . EVE takes as input a model of a concurrent and multi-agent system, in which agents are speci ed using the Simple Reactive Modules Language (SRML) , and preferences for agents are de ned by associating with each agent a goal, represented as a formula of LTL . Note that we believe our choice of the Reactive Modules language is a very natural one : e language is both widely used in practical model checking systems, such as MOCHA and PRISM , and close to real-world (declarative) programming models and speci cation languages. Now, given a speci cation of a multi-agent system and player preferences, the EVE system can: (i) check for the existence of a Nash equilibrium in a multi-player game; (ii) check whether a given LTL formula is satis ed on some or every Nash equilibrium of the system; and (iii) synthesise individual player strategies in the game. As we will show in the paper, EVE performs favourably compared with other existing tools that support rational veri cation. Moreover, EVE is the rst and only tool for automated temporal equilibrium analysis for a model of multi-player games where Nash equilibria are preserved under bisimilarity 3 . Note that our approach may be used to model a wide range of multi-agent systems. 3 Other tools to compute Nash equilibria exist, but they do not use our model of strategies. A comparison with those other techniques for equilibrium analysis are discussed later. For example, as shown in , it is easy to capture multi-agent STRIPS systems . Structure of the paper. e remainder of this article is structured as follows. • Section 2 presents the relevant background on games, logic, and automata. • In Section 3, we formalise the main problem of interest and give a high-level description of the core decision procedure for temporal equilibrium analysis developed in this paper. • In Sections 4, 5, and 6, we describe in detail our main decision procedure for temporal equilibrium analysis, prove its correctness, and show that it is essentially optimal with respect to computational complexity. • In Section 7, we show how to use our main decision procedure to do rational veri cation and automated synthesis of logic-based multi-player games. • In Section 8, we describe the EVE system, and give detailed experimental results which demonstrate that EVE performs favourably in comparison with other tools that support rational veri cation. • In Section 9, we conclude, discuss relevant related work, and propose some avenues for future work. e source code for EVE is available online 4 , and the system can also be accessed via the web 5 . Preliminaries Games. A concurrent (multi-player) game structure (CGS) is a tuple can perform when in state s. We refer to a pro le of actions a = (a 1 , . . . , a n ) ∈ Ac = Ac 1 × · · · × Ac n as a direction. A direction a is available in state s if for all i we have a i ∈ Ac i (s). Write Ac(s) for the set of available directions in state s. For a given set of players A ⊆ N and an action pro le a, we let a A and a −A be two tuples of actions, respectively, one for each player in A and one for each player in N \ A. We also write a i for a {i} and a −i for a N\{i} . Furthermore, for two directions a and a , we write Whenever there is a such that tr(s, a) = s , we say that s is accessible from s. A path π = s 0 , s 1 , . . . ∈ St ω is an in nite sequence of states such that, for every k ∈ N, s k+1 is accessible from s k . By π k we refer to the (k + 1)-th state in π and by π ≤k to the ( nite) pre x of π up to the (k + 1)-th element. An action pro le run is an in nite sequence η = a 0 , a 1 , . . . of action pro les. Note that, since M is deterministic (i.e., the transition function tr is deterministic), for a given state s 0 , an action pro le run uniquely determines the path π in which, for every k ∈ N, π k+1 = tr(π k , a k ). A CGS is a type of concurrent system. As such, behaviourally equivalent CGSs should give rise to strategically equivalent games. However, that is not always the case. A comprehensive study of this issue can be found in where the strategic power of games is compared using one of the most important behavioural (also called observational) equivalences in concurrency, namely bisimilarity, which is usually de ned over Kripke structures or labelled transition systems (see, e.g., ). However, the equivalence can be uniformly de ned for general CGSs, where direc- t, t ∈ St , and a ∈ Ac: • s R t implies λ(s) = λ (t), • s R t and tr(s, a) = s implies tr(t, a) = t for some t ∈ St with s R t , • s R t and tr(t, a) = t implies tr(s, a) = s for some s ∈ St with s R t . en, if there is a bisimulation between two states s * and t * , we say that they are bisimilar and write s * ∼ t * in such a case. We also say that CGSs M and M are bisimilar (in symbols M ∼ M ) if s 0 ∼ s 0 . Bisimilar structures satisfy the same set of temporal logic properties, a desirable property that will be relevant later. A CGS de nes the dynamic structure of a game, but lacks a central aspect of games in the sense of game theory: preferences, which give games their strategic structure. A multi-player game is obtained from a structure M by associating each player with a goal. In this paper, we consider multi-player games with parity and Linear Temporal Logic (LTL) goals. LTL extends classical propositional logic with two operators, X ("next") and U ("until"), that can be used to express properties of paths. e syntax of LTL is de ned with respect to a set AP of propositional variables as follows: where p ∈ AP. e remaining classical logical connectives are de ned in terms of ¬ and ∨ in the usual way. Two key derived LTL operators are F ("eventually") and G ("always"), which are de ned in terms of U as follows: Fϕ = U ϕ and Gϕ = ¬F¬ϕ. We interpret formulae of LTL with respect to tuples (π, t, λ), where π is a path over some multi-player game, t ∈ N is a temporal index into π, and λ : St → 2 AP is a labelling function, that indicates which propositional variables are true in every state. Formally, the semantics of LTL is given by the following rules: for all t ≤ t < t : (π, t , λ) |= ϕ . De nition 1. A (concurrent multi-player) LTL game is a tuple where λ : St → 2 AP is a labelling function on the set of states St of M, and each γ i is the goal of player i, given as an LTL formula over AP. To de ne multi-player games with parity goals we consider priority functions. Observe that parity conditions are pre x-independent, that is, for every path π and a nite sequence h ∈ St * , it holds that h · π |= α if and only if π |= α. De nition 2. A (concurrent multi-player) Parity game is a tuple where α i : St → N is the goal of player i, given as a priority function over St. Herea er, for statements regarding either LTL or Parity games 6 , we will simply denote the underlying structure as G. Games are played by each player i selecting a strategy σ i that will de ne how to make choices over time. Formally, for a given game G, a strategy σ i = (S i , s 0 i , δ i , τ i ) for player i is a nite state machine with output (a transducer), where S i is a nite and non-empty set of internal states, s 0 i is the initial state, δ i : S i × Ac → S i is a deterministic internal transition function, and τ i : S i → Ac i an action function. Note that strategies are required to output actions that are available to the agent in the current state. To enforce this, we assume that the current state s ∈ St in the arena is encoded in the internal state s i in S i of agent i and that the action τ i (s i ) taken by the action function belongs to Ac i (s). Let Σ i be the set of strategies for player i. A strategy is memoryless in G from s if S i = St, s 0 i = s, and δ i = tr. Once every player i has selected a strategy σ i , a strategy pro le σ = (σ 1 , . . . , σ n ) results and the game has an outcome, a path in M, which we will denote by π( σ). Because strategies are deterministic, π( σ) is the unique path induced by σ, that is, the in nite sequence s 0 , s 1 , s 2 , . . . such that • s k+1 = tr(s k , (τ 1 (s k 1 ), · · · , τ n (s k n ))), and , · · · , τ n (s k n ))), for all k ≥ 0. Note that the path induced by the strategy pro le σ(σ 1 , . . . , σ n ) from state s 0 corresponds to the one generated by the nite transducer T σ obtained from the composition of the strategies σ i 's in σ, with input set St and output set Ac, where the initial input is s 0 . Since such transducer is nite, the generated path π is ultimately periodic, that is, there exists p, r ∈ N such that π k = π k+r for every p ≤ k. is means that, a er the pre x π ≤p , the path loops inde nitely over the sequence π p+1 . . . π p+r . Nash equilibrium. Since the outcome of a game determines if a player goal is satis ed, we can de ne a preference relation i over outcomes for each player i. Let w i be γ i if G is an LTL game, and be α i if G is a Parity game. en, for two strategy pro les σ and σ in G, we have π( σ) i π( σ ) if and only if π( σ ) |= w i implies π( σ) |= w i . On this basis, we can de ne the concept of Nash equilibrium for a multi-player game with LTL or parity goals: given a game G, a strategy pro le σ is a Nash equilib-rium of G if, for every player i and strategy σ i ∈ Σ i , we have . . , σ n ), the strategy pro le where the strategy of player i in σ is replaced by σ i . Let NE(G) denote the set of Nash equilibria of G. In we showed that, using the model of strategies de ned above, the existence of Nash equilibria is preserved across bisimilar systems. is is in contrast to other models of strategies considered in the concurrent games literature, which do not preserve Nash equilibria. Because of this, herea er, we say that {Σ i } i∈N is a set of bisimulation-invariant strategies and that NE(G) is the set of bisimulationinvariant Nash equilibrium pro les of G. Automata. A deterministic automaton on in nite words is a tuple where Q is a nite set of states, ρ : Q × AP → Q is a transition function, q 0 is an initial state, and F is an acceptance condition. We mainly use parity and Stree acceptance conditions. A parity condition F is a partition {F 1 , . . . , F n } of Q, where n is the index of the parity condition and any k is a priority. We use a priority function α : Q → N that maps states to priorities such that α(q) = k if and only if q ∈ F k . For a run π = q 0 , q 1 , q 2 . . . , let inf (π) denote the set of states occurring in nitely o en in the run: inf (π) = {q ∈ Q | q = q i for in nitely many i's} A run π is accepted by a deterministic parity word (DPW) automaton with condition F if the minimum priority that occurs in nitely o en is even, i.e., if the following condition is satis ed: A run π is accepted by a deterministic Stree word (DSW) automaton S with condition F if π either visits E k nitely many times or visits C k in nitely o en, i.e., if for every k either inf (π) ∩ E k = ∅ or inf (π) ∩ C k = ∅. Example. In order to illustrate the usage of our framework, consider the following example. Suppose we have two robots/agents inhabiting a grid world (an abstraction of some environment, e.g., a warehouse) with dimensions n × n. Initially, the agents are located at some corners of the grid; e agents are each able to move around the grid in directions north, south, east, and west. e goal of each agent is to reach the opposite corner. For instance, if agent i's initial position is (0, 0), then the goal is to reach position (n − 1, n − 1). A number of obstacles may also appear on the grid. e agents are not allowed to move into a coordinate occupied by an obstacle or outside the grid world. To make it clearer, consider the con guration shown in Figure 1; a (grey) lled square depicts an obstacle. Agent 1, depicted by , can only move west to (2, 3), whereas agent 2, depicted by , can only move east to (1, 0). In this example we make the following assumptions: (1) at each timestep, each agent has to make a move, that is, it cannot stay at the same position for two consecutive timesteps, and it can only move at most one step; (2) the goal of each agent is, as stated previously, to eventually reach the opposite corner of her initial position. From system design point of view, the question that may be asked is: can we synthesise a strategy pro le such that it induces a stable (Nash equilibrium) run and at the same time ensures that the agents never crash into each other? Checking the existence of such strategy pro le is not trivial. For instance, the con guration in Figure 1 does not admit any safe Nash equilibrium runs, that is, where all agents get their goals achieved without crashing into each other. Player can and (1, 0), and (0, 3) and (1, 3), respectively. Clearly, such a reasoning is not always straightforward, especially when the se ing is more complex, and therefore, having a tool to verify and synthesise such scenario is desirable. Later in Section 8.5 we will discuss how to encode and check such systems using our tool. A Decision Procedure using Parity Games We are now in a position to formally state the N E problem: estion: Is it the case that NE(G LTL ) = ∅? As indicated before, we solve both veri cation and synthesis through a reduction to the above problem. e technique we develop consists of three steps. First, we build a Parity game G PAR from an input LTL game G LTL . en-using a characterisation of Nash equilibrium (presented later) that separates players in the game into those that achieve their goals in a Nash equilibrium (the "winners", W ) and those that do not achieve their goals (the "losers", L)-for each set of players in the game, we eliminate nodes and paths in G PAR which cannot be a part of a Nash equilibrium, thus producing a modi ed Parity game, G −L PAR . Finally, in the third step, we use Stree automata on in nite words to check if the obtained Parity game witnesses the existence of a Nash equilibrium. e overall algorithm is presented in Algorithm 1 which also includes some comments pointing to the relevant Sections/ eorems. e rst step is contained in line 3, while the third step is in lines 12-14. e rest of the algorithm is concerned with the second step. In the sections that follow, we will describe each step of the algorithm and, in particular, what are and how to compute Pun j (G PAR ) and G −L PAR , two key constructions used in our decision procedure. Algorithm 1: Nash equilibrium via Parity games Compute Pun j (G PAR ) ; /* from Section 5 (Theorem 2) */ Complexity. e procedure presented above runs in doubly exponential time, matching the optimal upper bound of the problem. In the rst step we obtain a doubly exponential blowup. e underlying structure M of the obtained Parity game G PAR is doubly exponential in the size of the goals of the input LTL game G LTL , but the priority functions set (α i ) i∈N is only (singly) exponential. en, in the second step, reasoning takes only polynomial time in the size of the underlying concurrent game structure of G PAR , but exponential time in both the number of players and the size of the priority functions set. Finally, the third step takes only polynomial time, leading to an overall 2EXPTIME complexity. From LTL to Parity We now describe how to realise line 3 of Algorithm 1, and in doing so we prove a strong correspondence between the set of Nash equilibria of the input LTL game G LTL and the set of Nash equilibria of its associated Parity game G PAR . is result allows us to shi reasoning on the set of Nash equilibria of G LTL into reasoning on the set of Nash equilibria of G PAR . e basic idea behind this step of the decision procedure is to transform all LTL goals (γ i ) i∈N in G LTL into a collection of DPWs, denoted by (A γi ) i∈N , that will be used to build the underlying CGS of G PAR . We construct G PAR as follows. In general, using the results in , from any LTL formula ϕ over AP one can build a DPW A ϕ = 2 AP , Q, q 0 , ρ, α such that, L(A ϕ ) = {π ∈ (2 AP ) ω : π |= ϕ}, that is, the language accepted by A ϕ is exactly the set of words over 2 AP that are models of ϕ. e size of Q is doubly exponential in |ϕ| and the size of the range of α is singly exponential in |ϕ|. Using this construction we can de ne, for each LTL Intuitively, the game G PAR is the product of the LTL game G LTL and the collection of parity (word) automata A γi that recognise the models of each player's goal. Observe that in the translation from G LTL to its associated G PAR the set of actions for each player is unchanged. is, in turn, means that the set of strategies in both G LTL and G PAR is the same, since for every state s ∈ St and action pro le a, it follows that a is available in s if and only if it is available in (s, q 1 , . . . , q n ) ∈ St , for all (q 1 , . . . , q n ) ∈ × i∈N Q i . Using this correspondence between strategies in G LTL and strategies in G PAR , we can prove the following Lemma, which states an invariance result between G LTL and G PAR with respect to the satisfaction of players' goals. Lemma 1 (Goals satisfaction invariance). Let G LTL be an LTL game and G PAR its associated Parity game. en, for every strategy pro le σ and player i, it is the case that Proof. We prove the statement by double implication. To show the le to right implication, assume that π( σ) |= γ i in G LTL , for any player i ∈ N, and let π denote the in nite path generated by σ in G LTL ; thus, we have that λ(π) |= γ i . On the other hand, let π denote the in nite path generated in G PAR by the same strategy pro le σ. Observe that the rst component of π is exactly π. Moreover, consider the (i + 1)-th component ρ i of π . By the de nition of G PAR , it holds that ρ i is the run executed by the automaton A γi when the word λ(π) is read. By the de nition of the labelling function of G PAR , it holds that the parity of π according to α i corresponds to the one recognised by A γi in ρ i . us, since we know that λ(π) |= γ i , it follows that ρ i is accepting in A γi and therefore π |= α i , which implies that π( σ) |= α i in G PAR . For the other direction, observe that all implications used above are equivalences. Using those equivalences one can reason backwards to prove the statement. Using Lemma 1 we can then show that the set of Nash Equilibria for any LTL game exactly corresponds to the set of Nash equilibria of its associated Parity game. Formally, we have the following invariance result between games. eorem 1 (Nash equilibrium invariance). Let G LTL be an LTL game and G PAR its associated Parity game. en, NE(G LTL ) = NE(G PAR ). Proof. e proof proceeds by double inclusion. First, assume that a strategy prole σ ∈ NE(G LTL ) is a Nash Equilibrium in G LTL and, by contradiction, it is not a Nash Equilibrium in G PAR . Observe that, due to Lemma 1, we known that the set of players that get their goals satis ed by π( σ) in G LTL (the "winners", W ) is the same set of players that get their goals satis ed by π( σ) in G PAR . en, there is player j ∈ L = N\W and a strategy σ j such that π(( σ −j , σ j )) |= α j in G PAR . en, due to Lemma 1, we have that π(( σ −j , σ j )) |= γ j in G LTL and so σ j would be a bene cial deviation for player j in G LTL too-a contradiction. On the other hand, for every σ ∈ NE(G PAR ), we can reason in a symmetric way and conclude that σ ∈ NE(G LTL ). Characterising Nash Equilibria anks to eorem 1, we can focus our a ention on Parity games, since a technique for solving such games will also provide a technique for solving their associated LTL games. To do this we characterise the set of Nash equilibria in the Parity game construction G PAR in our algorithm. e existence of Nash Equilibria in LTL games can be characterised in terms of punishment strategies and memoryful reasoning . We will show that a similar characterisation holds here in a parity games framework, where only memoryless reasoning is required. To do this, we rst introduce the notion of punishment strategies and regions formally, as well as some useful de nitions and notations. In what follows, given a (memoryless) strategy pro le σ = (σ 1 , . . . , σ n ) de ned on a state s ∈ St of a Parity game G PAR , that is, such that s 0 i = s for every Moreover, if s = s 0 is the initial state of the game, we omit it and simply write G PAR , σ |= α i in such a case. De nition 4 (Punishment strategies and regions). For a Parity game G PAR and a player i ∈ N, we say that σ −i is a punishment (partial) strategy pro le against i in a state s if, for all strategies s is punishing for i if there exists a punishment (partial) strategy pro le against i in s. By Pun i (G PAR ) we denote the set of punishing states, the punishment region, for i in To understand the meaning of a punishment (partial) strategy pro le, it is useful to think of a modi cation of the game G PAR , in which player i still has its goal α i , while the rest of the players are collectively playing in an adversarial mode, i.e., trying to make sure that i does not achieve α i . is scenario is represented by a twoplayer zero-sum game in which the winning strategies of the (coalition) player, denoted by −i, correspond (one-to-one) to the punishment strategies in the original game G PAR . As described in , knowing the set of punishment (partial) strategy pro les in a given game is important to compute its set of Nash Equilibria. For this reason, it is useful to compute the set Pun i (G PAR ), that is, the set of states in the game from which a given player i can be punished. (e.g., to deter undesirable unilateral player deviations). To do this, we reduce the problem to computing a winning strategy in a turn-based two-player zero-sum parity game, whose de nition is as follows. De nition 5. For a (concurrent multi-player) Parity game and player j ∈ N, the sequentialisation of G PAR with respect to player j is the (turn- ∃a j ∈ Ac j . s = tr(s, ( a −j ), a j )}; e formal connection between the notion of punishment in G PAR and the set of winning strategies in G j PAR is established in the following theorem, where by Win  (G j PAR ) we denote the winning region of Player 0 in G j PAR , that is, the states from which Player 0, representing the set of players −j = N \ {j} (the coalition of players not including j), has a memoryless winning strategy against player j in the two-player zero-sum parity game G j PAR . Proof. e proof goes by double inclusion. From le to right, assume s ∈ Pun j (G PAR ) and let σ −j be a punishment strategy pro le against player j in s, i.e., such that G PAR , ( σ −j , σ j ), s |= α j , for every strategy σ j ∈ Σ j of player j. We now de ne a strategy σ 0 for player 0 in G j PAR that is winning in s. In order to do this, rst observe that, for every nite path π ≤k ∈ V * · V 0 in G j PAR starting from s, there is a unique nite sequence of action pro les a 0 −j , . . . , a k −j and a sequence π ≤k = s 0 , . . . , s k+1 of states in St * such that Now, for every path π ≤k of this form that is consistent with σ −j , i.e., the sequence , where a k+1 −j is the action pro le selected by σ −j . To prove that σ 0 is winning, consider a strategy σ 1 for Player 1 and the in nite path π = π((σ 0 , σ 1 )) generated by (σ 0 , σ 1 ). It is not hard to see that the sequence π odd of odd positions in π belongs to a path π in G PAR and it is consistent with σ −j . From right to le , let s ∈ St ∩ Win  (G j PAR ) and let σ 0 be a winning strategy for Player 0 in G j PAR , and assume σ 0 is memoryless. Now, for every player i, with i = j, de ne the memoryless strategy σ i in G PAR such that, for every s ∈ St, i.e., the action that player i takes in σ 0 at s . Now, consider the (memoryless) strategy pro le σ −j given by the composition of all strategies σ i , and consider a play π in G PAR , starting from s, that is consistent with σ −j . us, there exists a play π in G i PAR , consistent with σ 0 , such that π = π odd . Moreover, since π odd = π even , we have that Inf(λ (π )) = Inf(λ (π odd )) ∪ Inf(λ (π even )) = Inf(λ(π)) − 1. Since π is winning for Player 0, we know that π |= α j and so σ −j is a punishment strategy against Player j in s. De nition 5 and eorem 2 not only make a bridge from the notion of punishment strategy to the notion of winning strategy for two-player zero-sum games, but also provide a way to understand how to compute punishment regions as well as how to synthesise an actual punishment strategy in Parity games. In this way, by computing winning regions and winning strategies in these games we can solve the synthesis problem for individual players in the original game with LTL goals, one of the problems we are interested in. us, from De nition 5 and eorem 2, we have the following corollary. to the size of the underlying graph of the game G PAR and exponential in the size of the priority function α i , that is, to the size of the range of α i . Moreover, there is a memoryless strategy σ i that is a punishment against player i in every state s ∈ Pun i (G PAR ). 7 By an abuse of notation, we let σ i (s ) be the value of τ i (s ). As described in , in any (in nite) run sustained by a Nash equilibrium σ in deterministic and pure strategies, that is, in π( σ), it is the case that all players that do not get their goals achieved in π( σ) can deviate from such a (Nash equilibrium) run only to states where they can be punished by the coalition consisting of all other players in the game. To formalise this idea in the present se ing, we need one more concept about punishments, de ned next. De nition 6. An action pro le run η = a 0 , a 1 , . . . ∈ Ac ω is punishing-secure in s for player j if, for all k ∈ N and a j , we have tr(π j , (( a k ) −j , a j )) ∈ Pun j (G PAR ), where π is the only play in G PAR starting from s and generated by η. Using the above de nition, we can characterise the set of Nash equilibria of a given game. Recall that strategies are formalised as transducers, i.e., as nite state machines with output, so such Nash equilibria strategy pro les produce runs which are ultimately periodic. Moreover, since in every run π there are players who get their goals achieved in π (and therefore do not have an incentive to deviate from π) and players who do not get their goals achieve in π (and therefore may have an incentive to deviate from π), we will also want to explicitly refer to such players. To do that, the following notation will be useful: Let W (G PAR , σ) = {i ∈ N : G PAR , σ |= α i } denote the set of player that get their goals achieved in π( σ). We also write W (G PAR , π) = {i ∈ N : G PAR , π |= α i }. eorem 3 (Nash equilibrium characterisation). For a Parity game G PAR , there is a Nash Equilibrium strategy pro le σ ∈ NE(G PAR ) if and only if there is an ultimately periodic action pro le run η such that, for every player j ∈ L = N \ W (G PAR , π), the run η is punishing-secure for j in state s 0 , where π is the unique path generated by η from s 0 . Proof. e proof is by double implication. From le to right, for σ ∈ NE(G PAR ), let η be the ultimately periodic sequence of action pro les generated by σ. Moreover, assume for a contradiction that η is not punishing-secure for some j ∈ L. By the de nition of punishment-secure, there is k ∈ N and action a j ∈ Ac j for player j such that s = tr(π k , (( a k ) −j , a j ) / ∈ Pun j (G PAR ). Now, consider the strategy σ j that follows η up to the (k −1)-th step, executes action a j on step k to get into state s , and applies a strategy that achieves α j from that point onwards. Note that such a strategy is guaranteed to exist since s / ∈ Pun j (G PAR ). erefore, G PAR , ( σ −j , σ j ) |= α j and so σ j is a bene cial deviation for player j, a contradiction to σ being a Nash equilibrium. From right to le , we need to de ne a Nash equilibrium σ assuming only the existence of η. First, recall that η can be generated by a nite transducer T η = (Q η , q 0 η , δ η , τ η ) where δ η : Q η → Q η and τ η : Q η → Ac. Moreover, for every player i and deviating player j, with i = j, there is a (memoryless) strategy σ punj i to punish player j in every state in Pun j (G PAR ). By suitably combining the transducer with the punishment strategies, we de ne the following strategy (tr(s, a), δ η (q), j), a −j = (τ η (q)) −j and a j = (τ η (q)) j ⊥, otherwise 8 • τ i : Q i → Ac i is such that 8 For completeness, the function δ i is assumed to take an available action. However, this is not important, as it is clear from the proof we never use this case. τ i (s, q, ) = (τ η (q)) i , and To understand how strategy σ i works, observe that its set of internal states is given , the resulting path will not satisfy the parity condition α j . Now, de ne σ to be the collection of all σ i . It remains to prove that σ is a Nash Equilibrium. First, observe that since σ produces exactly η, we have W (G PAR , σ) = W (G PAR , η), that is, the players that get their goals achieved in π( σ) and η are the same. us, only players in L could have a bene cial deviation. Now, consider a player j ∈ L and a strategy σ j and let k ∈ N be the minimum ( rst) step where σ j produces an outcome that di ers from σ j when executed along with σ −j . We write π for π(( σ −j , σ j )). us, we have π h = π h for all h ≤ k and π k+1 = π k+1 . Hence π k+1 = tr(π k , (η k ) −j , a j ) = tr(π k , (η k ) −j , a j ) ∈ Pun j (G PAR ) and G PAR , ( σ −j , σ j ) |= α j , since σ −j is a punishment strategy from π k+1 . us, there is no bene cial deviation for j and σ is a Nash equilibrium. 6. Computing Nash Equilibria eorem 3 allows us to reduce the problem of nding a Nash equilibrium to nding a path in the game satisfying certain properties, which we will show how to check using DPW and DSW automata. To do this, let us x a given set W ⊆ N of players in a given game G PAR , which are assumed to get their goals achieved. Now, due to eorem 3, we have that an action pro le run η corresponds to a Nash equilibrium with W being the set of "winners" in the game if, and only if, the following two properties are satis ed: • η is punishment-secure for j in s 0 , for all j ∈ L = N \ W ; where π is, as usual, the path generated by η from s 0 . To check the existence of such η, we have to check these two properties. First, note that, for η to be punishment-secure for every losing player j ∈ L, the game has to remain in the punishment region of each j. is means that an acceptable action pro le run needs to generate a path that is, at every step, contained in the intersection j∈L Pun j (G PAR ). us, to nd a Nash equilibrium, we can remove all states not in such an intersection. We also need to remove some edges from the game. Indeed, consider a state s and a partial action pro le a −j . It might be the case that tr(s, ( a −j , a j )) / ∈ Pun j (G PAR ), for some a j ∈ Ac j . erefore, an action pro le run that executes the partial pro le a −j over s cannot be punishment-secure, and so all outgoing edges from (s, a −j ), can also be removed. A er doing this for every j ∈ L, we obtain G −L PAR , the game resulting from G PAR a er the removal of the states and edges just described. As a consequence, G −L PAR has all and only the paths that can be generated by an action pro le run that is punishment-secure for every j ∈ L. e only thing that remains to be done is to check whether there exists a path in G −L PAR that satis es all players in W . To do this, we use DPW and DSW automata. Since players goals are parity conditions, a path satisfying player i is an accepting run of the DPW A i where the set of states and transitions are exactly those of G −L PAR and the acceptance condition is given by α i . en, in order to nd a path satisfying the goals of all players in W , we can solve the emptiness problem of the automaton intersection × i∈W A i . However, observe that each A i di ers from each other only in its acceptance condition α i . Moreover, each parity condition α = (F 1 , . . . , F n ) can be regarded as a Street condition of the form ((E 1 , C 1 ), . . . , (E m , C m )) with m = n 2 and (E i , C i ) = (F 2i+1 , j≤i F 2j ), for every 0 ≤ i < m. erefore, the intersection language of × i∈W A i can be recognized by a Street automaton over the same set of states and transitions and the concatenation of all the Stree conditions determined by the parity conditions of the players in W . e overall translation is a DSW automaton with a number of Stree pairs being logarithmic in the number of its states, whose emptiness can be solved in polynomial time . Finally, as we xed W at the beginning, all we need to do is to use the procedure just described for each W ⊆ N, if needed (see Algorithm 1). 9 Concerning the complexity analysis, consider again Algorithm 1 and denote by n the number of agents and |St LTL | the number of states. Observe that Line 3 of the algorithm builds a Parity game G PAR by making the product construction between G LTL and all the DPW automata A γi , whose state space is 2 2 |γ i | , and the number of priorities is 2 |γi| . us, the number of states of G PAR is |St PAR | = |St LTL | · 2 2 |γ 1 | · . . . · 2 2 |γn| . Now, on the one hand, Line 6 requires to solve a parity game on the state-graph of G PAR with 2 γi priorities. is is solved by applying Zielonka's algorithm , that e second is on all the possible agents, and thus of length n. is sums up to an overall complexity for Algorithm 1 of: Recall that |St PAR | is linear in the set of states of the G LTL and doubly exponential 9 Some previous techniques, e.g. , to the computation of pure Nash equilibria are not optimal as they have exponential space complexity in the number of players |N|. in every objective γ i 's of the agents. us, the procedure is polynomial in |St LTL |, exponential in N , and doubly exponential in the size of the formulas |γ 1 |, . . . , |γ N |. Synthesis and Veri cation We now show how to solve the synthesis and veri cation problems using N E . For synthesis, the solution is already contained in the proof of eorem 3, so we only need to sketch out the approach here. Note that, in the computation of punishing regions, the algorithm builds, for every player i and potential deviator j, a (memoryless) strategy that player i can play in the collective strategy pro le σ − j in order to punish player j, should player j wishes to deviate. If a Nash equilibrium exists, the algorithm also computes a (ultimately periodic) witness of it, that is, a computation π in G, that, in particular, satis es the goals of players in W . At this point, using this information, we are able to de ne a strategy σ i for each player i ∈ N in the game (i.e., including those not in W ), as follows: while no deviation occurs, play the action that contributes to generate π, and if a deviation of player j occurs, then play the (memoryless) strategy σ punj i that is de ned in the game to punish player j in case j were to deviate. Notice, in addition, that because of Lemma 1 and eorem 1, every strategy for player i in the game with parity goals is also a valid strategy for player i in the game with LTL goals, and that such a strategy, being bisimulationinvariant, is also a strategy for every possible bisimilar representation of player i. In this way, our technique can also solve the synthesis problem for every player, that is, can compute individual bisimulation-invariant strategies for every player (system component) in the original multi-player game (concurrent system). For veri cation, one can use a reduction of the following two problems, called E N and A N in , to N E . We write (G LTL , ϕ) ∈ E N to denote that (G LTL , ϕ) is an instance of E N , i.e., given a game G LTL and a LTL formula ϕ, the answer to E N problem is a "yes"; and, similarly for A N . Because we are working on a bisimulation-invariant se ing, we can ensure something even stronger: that for any two games G LTL and G LTL , whose underlying CGSs are M and M , respectively, we know that if M is bisimilar to M , then (G LTL , ϕ) ∈ E N if and only if (G LTL , ϕ) ∈ E N , for all LTL formulae ϕ; and, similarly for A N , as desired. In order to solve E N and A N via N E , one could use the following result, whose proof is a simple adaptation of the same result for iterated Boolean games and for multi-player games with LTL goals modelled using SRML , which was rst presented in . S ϕ is the DSW automaton representing ϕ. All complexities remain the same; the modi ed algorithm for E N is denoted as Algorithm 1'. We can then use Algorithm 1' to solve A N , also as described in : essentially, we can check whether Algorithm 1'(G LTL , ¬ϕ) returns "No" in line 16. If it does, then no Nash equilibrium of G LTL satis es ¬ϕ, either because no Nash equilibrium exists at all (thus, A N is vacuously true) or because all Nash equilibria of G LTL satisfy ϕ, then solving A N positively. Note that in this case, since A N is solved positively when the algorithm returns "No" in line 16, then no speci c Nash equilibrium strategy pro le is synthesised, as expected. However, if the algorithm returns "Yes", that is, the case when the answer to A N problem with (G LTL , ϕ) instance is negative, then a strategy pro le is synthesised from Algorithm 1' which corresponds to a counter-example for (G LTL , ϕ) ∈ A N . It should be easy to see that implementing E N and A N is straightforward from Algorithm 1. Also, as already known, it is also easy to see that Algorithm 1' solves N E if and only if (G LTL , ) ∈ E N . Implementation We have implemented the decision procedures presented in this paper. Our implementation uses SRML as a modelling language. SRML is based on the Reactive Modules language which is used in a number of veri cation tools, including PRISM and MOCHA . e tool that implements our algorithms is called EVE (for Equilibrium V eri cation Environment) . EVE is the rst and only tool able to analyse the linear temporal logic properties that hold in equilibrium in a concurrent, reactive, and multi-agent system within a bisimulation-invariant framework. It is also the only tool that supports all of the following combined features: a high-level description language using SRML, general-sum multi-player games with LTL goals, bisimulation-invariant strategies, and perfect recall. It is also the only tool for Nash equilibrium analysis that relies on a procedure based on the solution of parity games, which has allowed us to solve the (rational) synthesis problem for individual players in the system using very powerful techniques originally developed to solve the synthesis problem from (linear-time) temporal logic speci cations. To the best of our knowledge, there are only two other tools that can be used to reason about temporal logic equilibrium properties of concurrent/multi-agent systems: PRALINE and MCMAS . PRALINE allows one to compute a Nash equilibrium in a game played in a concurrent game structure . e underlying technique uses alternating Büchi automata and relies on the solution of a two-player zero-sum game called the 'suspect game' . PRALINE can be used to analyse games with di erent kinds of players goals (e.g., reachability, safety, and others), but does not permit LTL goals, and does not compute bisimulation-invariant strategies. MCMAS is a model checking tool for multi-agent systems . A guarded command has two parts: a "condition" part (the "guard") and an "action" part. e "guard" determines whether a guarded command can be executed or not given the current state, while the "action" part de nes how to update the value of (some of) the variables controlled by a corresponding module. Intuitively, ϕ ; α can be read as "if the condition ϕ is satis ed, then one of the choices available to the module is to execute α". Note that the value of ϕ being true does not guarantee the execution of α, but only that it is enabled for execution, and thus may be chosen. If no guarded command of a module is enabled in some state, then that module has no choice and the values of the variables controlled by it remain unchanged in the next state. Formally, an SRML module m i is de ned as a triple :: x ; x := ⊥; then in the next time-step, variable p will be assigned true and variable q will be assigned false. Figure 5 shows a module named toggle that controls a Boolean variable named x. ere are two init guarded commands and two update guarded commands. e init guarded commands de ne two choices for the initialisation of variable x: true or false. e rst update guarded command says that if x has the value of true, then the corresponding choice is to assign it to false, while the second command says that if x has the value of false, then it can be assigned to true. Intuitively, the module would choose (in a non-deterministic manner) an initial value for x, and then on subsequent rounds toggles this value. In this particular example, the init commands are nondeterministic, while the update commands are deterministic. We refer to for further details on the semantics of SRML. In particular, in Figure 12 of , we detail how to build a Kripke structure that models the behaviour of an SRML system. In addition, we associate each module with a goal, which is speci ed as an LTL formula. At this point, readers might notice that the way SRML modules are de ned leads to the possibility of having multiple initial states -which appears to contradict the G LTL Kripke structure Figure 6: High-level work ow of EVE. de nition of CMGS. However, this is not a problem, since we can always add an extra "pre"-initial state whose outgoing edges are labelled according to init guarded commands, and use it as the "real" initial state. Automated Temporal Equilibrium Analysis. Once a multi-agent system is modelled in SRML, it can be seen as a multi-player game in which players (the modules) use strategies to resolve the non-deterministic choices in the system. EVE uses Algorithm 1 to solve N E . e main idea behind this algorithm is illustrated in Figure 6. e general ow of the implementation is as follows. Let G LTL be a game, modelled using SRML, with a set of players/modules N = {1, . . . , n} and LTL goals Γ = {γ 1 , . . . , γ n }, one for each player. Using G LTL we construct an associated concurrent game with parity goals G PAR in order to shi reasoning on the set of Nash equilibria of G LTL into the set of Nash equilibria of G PAR . e basic idea of this construction is, rstly, to transform all LTL goals in G LTL into deterministic parity word (DPW) automata. To do this, we use LTL2BA tool to transform the formulae into nondeterministic Büchi word (NBW) automata. From NBWs, we construct the associated deterministic parity word (DPW) automata via construction described in . Secondly, to perform a product construction of the Kripke structure that represents G LTL with the collection of DPWs in which the set of Nash equilibria of the input game is preserved. With G PAR in our hands, we can then reason about Nash equilibria by solving a collection of parity games. To solve these parity games, we use PGSolver tool . EVE then iterates through all possible set of "winners" W ⊆ N (Algorithm 1 line 4) and computes a punishment region Pun j (G PAR ) for each j ∈ L = N\W , with which a reduced parity game G −L PAR = j∈L Pun j (G PAR ) is built. Notice that for each player j, Pun j (G PAR ) need only computed once and can be stored, thus resulting in a more e cient running time. Lastly, EVE checks whether there exists a path ρ in G −L PAR that satis es the goals of each i ∈ W . To do this, we translate G −L PAR into a deterministic Stree automata, whose language is empty if and only if so is the set of Nash equilibria of G PAR . For E N problem, we simply need to nd a run in the witness returned when we check for N E ; this can be done via automata intersection 11 . EVE was developed in Python and available online from . EVE takes as input a concurrent and multi-agent system described in SRML code, with player goals and a property ϕ to be checked speci ed in LTL. For N E , EVE returns "YES" (along with a set of winning players W ) if the set of Nash equilibria in the system is not empty, and returns "NO" otherwise. For E N (A N ), EVE returns "YES" if ϕ holds on some (every) Nash equilibrium of the system, and "NO" otherwise. In the next subsection, we present some case studies to evaluate the performance of EVE. e case studies are based on distributed and concurrent systems that can naturally be modelled as multi-agent systems. We note, however, that such case studies bear no special relevance to multi-agent systems research. Instead, our only purpose is to use such case studies and multi-agent systems to evaluate EVE's performance, rather than to solve problems of particular relevance in the AI or multi-agent systems literatures. Nevertheless, one could easily see that the case studies are based on systems that one can imagine to be found in many AI systems nowadays. Case Studies In module RM1 controls s1 init :: true ∼> s1':=true; update :: s1 ∼> s1':=false; :: s1 ∼> s1':=true; :: !s1 and (!s2 or ... or !sn) ∼> s1':=true; goal :: G F (!s1); rst one is played in an arena implicitly given by the speci cation of the players in the game (as done in ), the second one is played on a graph, e.g., as done in with the use of concurrent game structures. Both of these models of games (modelling approaches) can be used within our tool. We will also use these two examples to which exchange "gossip" messages periodically in order to keep the data updated. e architecture of such an approach is shown in Figure 7. We can model each RM as a module in SRML as follows: (1) When in servicing mode, an RM can choose either to keep in servicing mode or to switch to gossiping mode; (2) If it is in gossiping mode and there is at least another RM also in gossiping mode 12 , since the information during gossip exchange is of (small) bounded size, it goes back to servicing mode in the subsequent step. We then set the goal of each RM to be able to gossip in nitely o en. As shown in Figure 8, the module RM1 controls a variable: s1. Its value being true signi es that RM1 is in servicing mode; otherwise, it is in gossiping mode. Behaviour (1) is re ected in the rst and second update commands, while behaviour (2) is re ected in the third update command. e goal of RM1 is speci ed with the LTL formula GF ¬ s1, which expresses that RM1's goal is to gossip in nitely o en: "always" (G) "eventually" (F) gossip (¬s1). Observe that with all RMs rationally pursuing their goals, they will adopt any Replica Control Protocol. Consensus is a key issue in distributed computing and multiagent systems. An important application domain is in maintaining data consistency. Gi ord proposed a quorum-based voting protocol to ensure data consistency by not allowing more than one processes to read/write a data item concurrently. To do this, each copy of a replicated item is assigned a vote. by the sequence of states q 1 , . . . , q n , where q i means that player i is requesting to read/write the data item. At state q i , other players in N\{i} then can vote whether to allow player i to read/write. If the majority of players in N vote "yes", then the transition goes to q 0 , i.e., player i is allowed to read/write, and otherwise it goes to q i+1 13 . e voting process then restarts from q 1 . e protocol's structure is shown in Figure 9. Notice that at the last state, q n , there is only one outgoing arrow to q 0 . As in the previous example, the goal of each player i is to visit q 0 right a er q i in nitely o en, so that the desired behaviour of the system is sustained on all Nash equilibria of the system: a data item is not concurrently accessed by two di erent processes and the data is updated in every round. e associated temporal properties are automatically veri ed in the experiments in Section 8.3. Speci cally, the temporal properties we check are as follows. With E N : there is no Nash equlibrium in which the data is never updated; and, with A N : on all Nash equilibria, for each player, its request will be granted in nitely o en. Also, in this example, we de ne a module, called "Environment", which is used to represent the underlying concurrent game structure, shown in Figure 9, where the game is played. Experiment I In order to evaluate the practical performance of our tool and approach (against MCMAS and PRALINE), we present results on the temporal equilibrium analysis for the examples in Section 8.2. We ran the tools on the two examples with di erent 13 We assume arithmetic modulo (|N| + 1) in this example. E ("ν"), E N (" "), and A N ("α"). For the last two problems, since there is no direct support in PRALINE and MCMAS, we used the reduction of E/A N to N E presented in . Intuitively, the reduction is as follows: given a game G and formula ϕ, we construct a new game H with two additional agents, say n + 1 and n + 2, with goals γ n+1 = ϕ ∨ (p ↔ q) and γ n+2 = ϕ ∨ ¬(p ↔ q), where Φ n+1 = {p} and Φ n+2 = {q}, p and q are fresh Boolean variables. is means that it is the case NE(H) = ∅ if and only if there exists a Nash equilibrium run in G satisfying ϕ. From the experiment results shown in Table 1 and 2, we observe that, in general, EVE has the best performance, followed by PRALINE and MCMAS. Although PRA-LINE performed be er than MCMAS, both struggled (timed-out 15 ) with inputs with more than 100 edges, while EVE could handle up to 6000 edges (for N E ). Experiment II is experiment is taken from the motivating examples in . Suppose the systems shown in Figure 10 and 11 represents a 3-player game, where each transition is labelled by the actions x, y, z of player 1, 2, and 3, respectively, an asterisk * being a wildcard. e goals of the players can be represented by the LTL formulae γ 1 = Fp, γ 2 = Fq, and γ 3 = G¬(p ∨ q). e system in Figure 10 has a Nash equilibrium, whereas no (non-bisimulation-invariant strategies) Nash equilibria exists in the (bisimilar) system in Figure 11. In this experiment, we extended the number of states by adding more layers to and (ii) whether the tools nd any Nash equilibria ("NE"). 15 Time-out was xed to be 7200 seconds. 16 Similarly to Experiment I (Section 8.3), we added to PRALINE's running time the time needed to convert LTL games into its input to carry out a fairer comparison. Table 3 shows the results of the experiments on the example in which the model of strategies that depends only on the run (sequence of states) of the game (run-based strategies ) cannot sustain any Nash equilibria, a model of strategies that is not invariant under bisimilarity. Indeed, since MCMAS and PRALINE use this model of strategies, both did not nd any Nash equilibria in the game, as shown in Table 3. EVE, which uses a model of strategies that not only depends on the run of the game but also on the actions of players (computation-based ), found a Nash equilibrium in the game. We can also see that EVE outperformed MCMAS on games with 14 or more states. In fact, MCMAS timed-out 17 on games with 17 states or more, while EVE kept working e ciently for games of bigger size. We can also observe that PRALINE performed almost as e ciently as EVE in this experiment, although EVE performed be er in both small and large instances of these games. 17 We xed the time-out value to be 3600 seconds (1 hour). In Table 4, we used the example in which Nash equilibria is sustained in runbased strategies. As shown in the table, MCMAS found Nash equilibria in games with 6 and 9 states. However, since MCMAS uses imperfect recall, when the third layer was added (case with 12 states in Table 4) to the game, it could not nd any Nash equilibria. Regarding running times, EVE outperformed MCMAS from the game with 12 states and beyond, where MCMAS timed-out on games with 15 or more states. As for PRALINE, it performed comparably to EVE in this experiment, but again, EVE performed be er in all instances. Experiment III is experiment is based on the example previously presented in Section 2. For this particular experiment, we assume that initially the agents are located at opposing corners of the grid; speci cally, agent 1 is located at the top-le corner (coordinate (0, 0)) and agent 2 at the bo om-right corner (n−1, n−1). A number of obstacles are also placed (uniformly) randomly on the grid. We use a binary encoding to represent A safety speci cation (no more than one agent occupying the same position at the same time) can be expressed by the following LTL formula: e experiment was obtained on a PC with Intel i5-4690S CPU 3.20 GHz machine with 8 GB of RAM running Linux kernel version 4.12.14-300.fc26.x86 64. We varied the size of the grid world ("size") from 3 × 3 to 10 × 10, each with a xed number of obstacles ("# Obs"), randomly distributed on the grid. We report the number of Kripke states ("KS"), Kripke edges ("KE"), G PAR states ("GS"), G PAR edges ("GE"), N E execution time ("ν"), and E N execution time (" "). We ran the experiment for ve replications, and report the average (ave), minimum (min), and From the experiments shown in this section it is also clear that the bo leneck in the performance is the translation of LTL goals and the high-level description of the game into the underlying parity game. Once an explicit parity game is constructed, then the performance improves radically. is result is perfectly consistent with what the theoretical complexity of the decision procedure predicts: our algorithm works in doubly-exponential time in the size of the goals of the players, while it is only singly-exponential in the size of the SRML speci cation. ese two exponential-time reductions are in fact optimal, so there is no hope that they can be improved, at least in theory. On the other hand, the actual subroutine that nds a Nash equilibrium and computes players' strategies from the parity games representation of the problem is rather e cient in theory -but still not known to be in polynomial time using the best algorithms to solve parity games. en, it is clear that a natural way to make rational veri cation a feasible problem, in theory, is to look at cases where goals and/or game representations are simpler. Such study is conducted in , where several positive results on the complexity of solving the rational veri cation problem are obtained. Concluding Remarks and Related Work is paper contains a complete study, from theory to implementation, of the temporal equilibrium analysis of multi-agent AI systems formally modelled as multiplayer games. e two main contributions of the paper are: (1) a novel and optimal decision procedure, based on the solution of parity games, that can be used to solve both the rational veri cation and the automated synthesis problems for multi-player games; and (2) a complete implementation of the general game-theoretic modelling and reasoning framework -with full support of goals expressed as LTL formulae and 18 Since the grid coordinate index starts at 0, the "actual" transitions are 3 to 4 and 7 to 8. high-level game descriptions in SRML -which is available online. Our work builds on several previous results in the computer science (synthesis and veri cation) and AI literatures (multi-agent systems). Relevant related literature will be discussed next. Equilibrium Analysis in Multi-Agent Systems. Rational veri cation was proposed as an complementary veri cation methodology to conventional methods, such as model checking. A legitimate question is, then, when is rational veri cation an appropriate veri cation approach? A possible answer is given next. e veri cation problem , as conventionally formulated, is concerned with checking that some property, usually de ned using a modal or a temporal logic , holds on some or on every computation run of a system. In a game-theoretic se ing, this can be a very strong requirement -and in some cases even inappropriate -since only some computations of the system will arise (be sustained) as the result of agents in the system choosing strategies in equilibrium, that is, due to strategic and rational play. It was precisely this concern that motivated the rational veri cation approach . In rational veri cation, we ask if a given temporal property holds on some or every computation run that can be sustained by agents choosing Nash equilibrium strategies. Rational veri cation can be reduced to the N E problem, as stated in this paper; cf., . As a consequence, along with the polynomial transformations in , our results provide a complete framework (theory, algorithms, and implementation) for automated temporal equilibrium analysis, speci cally, to do rational synthesis and formal veri cation of logic-based multi-agent systems. e framework, in particular, provides a concrete and algorithmic solution to the rational synthesis problem as studied in , where the Boolean case (iterated games where players control Boolean variables, whose valuations de ne sequences of states in the game, i.e., the plays in the game) was given an interesting automata-theoretic solution via (an extension of) Strategy Logic . Automata and logic. In computer science, a common technique to reason about Nash equilibria in multi-player games is using alternating parity automata on innite trees (APTs ). is approach is used to do rational synthesis ; equilibrium checking and rational veri cation ; and model checking of logics for strategic reasoning capable to specify the existence of a Nash equilibrium in concurrent game structures , both in two-player games and in multi-player games . In cases where players' goals are simpler than general LTL formulae, e.g., for reachability or safety goals, alternating Büchi automata can be used instead . Our technique is di erent from all these automata-based approaches, and in some cases more general, as it can be used to handle either a more complex model of strategies or a more complex type of goals, and delivers an immediate procedure to synthesise individual strategies for players in the game, while being amenable to implementation. Tools and algorithms. In theory, the kind of equilibrium analysis that can be done using MCMAS and PRALINE rely on the automata-based approach. However, the algorithms that are actually implemented have a di erent avour. MC-MAS uses a procedure for SL which works as a labelling algorithm since it only considers memoryless strategies . On the other hand, PRALINE, which works for Büchi de nable objectives, uses a procedure based on the "suspect game" . Despite some similarities between our construction and the suspect game, introduced in , the two procedures are substantially di erent. Unlike our procedure, the suspect game is a standard two-player zero-sum turn-based game H(G, π), constructed from a game G and a possible path π, in which one of the players ("Eve") has a winning strategy if, and only if, π can be sustained by a Nash equilibrium in G. e overall procedure in relies on the construction of such a game, whose size (space complexity) is exponential in the number of agents . Instead, our procedure solves, independently, a collection of parity games that avoids an exponential use of space but may require to be executed exponentially many times. Key to the correctness of our approach is that we deal with parity conditions, which are pre x-independent, ensuring that punishment strategies do not depend on the history of the game. Regarding similarities, our procedure also checks for the existence of a path sustained by a Nash Equilibrium, but our algorithm does this for every subset W ⊆ N of agents, if needed. Doing this (i.e., trading exponential space for exponential time), at every call of this subroutine, our algorithm avoids building an exponentially sized game, like H. On the other hand, from a practical point of view, avoiding the construction of such an exponential sized game leads to be er performance (running times), even in cases where no Nash equilibrium exists, when our subroutine is necessarily called exponentially many times. In addition to all of the above, neither the algorithm used for MCMAS nor the one used for PRALINE computes pure Nash equilibria in a bisimulation-invariant framework, as our procedure does. While MCMAS and PRALINE are the two closest tools to EVE, they are not the only available options to reason about games. For instance, PRISM-games , EAGLE , and UPPAAL are other interesting tools to reason about games. PRISM-games allows one to do strategy synthesis for turnbased stochastic games as well as model checking for long-run, average, and ratio rewards properties. Only until very recently, PRISM-games had no support of equilibrium reasoning, but see . EAGLE is a tool speci cally designed to reason about pure Nash equilibria in multi-player games. EAGLE considers games where goals are given as CTL formulae and allows one to check if a given strategy pro le is a Nash equilibrium of a given multi-agent system. is decision problem, called M within the rational veri cation framework , is, theoretically, simpler than N E : while the former can be solved in EXPTIME (for branching-time goals expressed using CTL formulae ), the la er is 2EXPTIME-complete for LTL goals, and even 2EXPTIME-hard for CTL goals and nondeterministic strategies . UPPAAL is another tool that can be used to analyse equilibrium behaviour in a system . However, UPPAAL di ers from EVE in various critical ways: e.g., it works in a quantitative se ing, uses statistical model checking, and most importantly, computes approximate Nash equilibria of a game. e Role of Bisimilarity. One crucial aspect of our approach to rational veri cation and synthesis is the role of bisimilarity . Bisimulation is the most important type of behavioural equivalence relation considered in computer science, and in particular two bisimilar systems will satisfy the same temporal logic properties. In our se ing, it is highly desirable that properties which hold in equilibrium are sustained across all bisimilar systems to P 1 , . . . , P n . at is, that for every (temporal logic) property ϕ and every system component P i modelled as an agent in a multi-player game, if P i is bisimilar to P i ∈ {P 1 , . . . , P n }, then ϕ is satis ed in equilibrium -that is, on a run induced by some Nash equilibrium of the game -by P 1 , . . . , P i , . . . P n if and only if is also satis ed in equilibrium by P 1 , . . . , P i , . . . , P n , the system in which P i is replaced by P i , that is, across all bisimilar systems to P 1 , . . . , P n . is property is called invariance under bisimilarity. Unfortunately, as shown in , the satisfaction of temporal logic properties in equilibrium is not invariant under bisimilarity, thus posing a challenge for the modular and compositional reasoning of concurrent systems, since individual system components in a concurrent system cannot be replaced by (behaviourally equivalent) bisimilar ones, while preserving the temporal logic properties that the overall multi-agent system satis es in equilibrium. is is also a problem from a synthesis point of view. Indeed, a strategy for a system component P i may not be a valid strategy for a bisimilar system component P i . As a consequence, the problem of building strategies for individual processes in the concurrent system P 1 , . . . , P i , . . . P n may not, in general, be the same as building strategies for a bisimilar system P 1 , . . . , P i , . . . P n , again, deterring any hope of being able to do modular reasoning on concurrent and multi-agent systems. ese problems were rst identi ed in and further studied in . However, no algorithmic solutions to these two problems were presented in either or . Speci cally, in this paper, bisimilarity was exploited in two ways. Firstly, our construction of punishment strategies (used in the characterisation of Nash equilibrium given by eorem 3) assumes that players have access to the history of choices that other players in the game have made. As shown in , with a model of strategies where this is not the case, the preservation of Nash equilibria in the game, as well as of temporal logic properties in equilibrium, may not be guaranteed. Secondly, our implementation in EVE guarantees that any two games whose underlying CGSs are bisimilar, and therefore should be regarded as observationally equivalent from a concurrency point of view, will produce the same answers to the rational veri cation and automated synthesis problems. It is also worth noting that even though bisimilarity is probably the most widely used behavioural equivalence in concurrency, in the context of multiagent systems other relations may be preferred, for instance, equivalence relations that take a detailed account of the independent interactions and behaviour of indi-vidual components in a multi-agent system. In such a se ing, "alternating" relations with natural ATL * characterisations have been studied . Alternating bisimulation is very similar to bisimilarity on labelled transition systems , only that when de ned on CGSs, instead of action pro les (directions) taken as possible transitions, one allows individual player's actions, which must be matched in the bisimulation game. Because of this, it immediately follows that any alternating bisimulation as de ned in is also a bisimilarity as de ned here. Despite having a di erent formal de nition, a simple observation can be made: Nash equilibria are not preserved by the alternating (bisimulation) equivalence relations in either, which discourages the use of these even stronger equivalence relations for multi-agent systems. In fact, as discussed in , the "right" notion of equivalence for games (which can be indirectly used as an observationally equivalence between multi-agent systems) and their game theoretic solution concepts is, undoubtedly, an important and interesting topic of debate, which deserves to be investigated further. Some features of our framework. Unlike other approaches to rational synthesis and temporal equilibrium analysis, e.g. , we employ parity games , which are an intuitively simple veri cation model with an abundant associated set of algorithmic solutions . In particular, strategies in our framework, as in , can depend on players' actions, leading to a much richer game-theoretic se ing where Nash equilibrium is invariant under bisimilarity , a desirable property for concurrent and reactive systems . Our reasoning and veri cation approach applies to multi-player games that are concurrent and synchronous, with perfect recall and perfect information, and which can be represented in a high-level, succinct manner using SRML . In addition, the technique developed in this paper, and its associated implementation, considers games with LTL goals, deterministic and pure strategies, and dichotomous preferences. In particular, strategies in these games are assumed to be able to see all past players' actions. We do not consider mixed or nondeterministic strategies, or goals given by branching-time formulae. We also do not allow for quantitative or probabilistic systems, e.g., such as stochastic games or similar game models. We note, however, that some of these aspects of our reasoning frame-work have been placed to avoid undesirable computational properties. For instance, it is known that checking for the existence of a Nash equilibrium in multi-player games like the ones we consider is an undecidable problem if either imperfect information or (various kinds of) quantitative/probabilistic information is allowed . Future Work. is paper gives a solution to the temporal equilibrium problem (both automated synthesis and formal veri cation) in a noncooperative se ing. In future work, we plan to investigate the cooperative games se ing . e paper also solves the problem in practice for perfect information games. We also plan to investigate if our main algorithms can be extended to decidable classes of imperfect information games, for instance, as those studied to model the behaviour of multi-agent systems in . Whenever possible, such studies will be complemented with practical implementations in EVE. Finally, extensions to epistemic systems and quantitative information in the context of multi-agent systems may be another avenue for further applications , as well as se ings with more complex preference relations , which would provide a strictly stronger modelling power.
<reponame>HighOakRobotics/16457FreightFrenzy<gh_stars>0 package org.firstinspires.ftc.teamcode.opmodes.tuning; import com.ftc11392.sequoia.SequoiaOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import org.firstinspires.ftc.teamcode.subsystems.arm.Arm; @TeleOp public class ArmEncoderTool extends SequoiaOpMode { Arm arm = new Arm(); @Override public void initTriggers() { } @Override public void runTriggers() { arm.setArmState(Arm.ArmState.IDLE); } }
Chief Keef is currently serving a two month sentence in juvenile detention for violating his parole. Since taken into custody, he has seen even more legal trouble, including a lawsuit for a missed concert appearance, as well as a claim of unpaid child support from a middle school student. New reports indicate that Keef may be planning to turn his life around, as reverend Corey Brooks explains that he will baptize the teenage rapper upon his release. Brooks, who's known as Chicago's "Rooftop Pastor" says Keef “is not a bad kid”, and believes his troubles are simply a result of his young age and misperception of things. ”I think people forget he is 17 years old,” said Brooks, adding, “He is an entertainer, that is how he sees himself. But at the same time, he has a God-consciousness. He is not some terror who is wreaking havoc.” The baptism will reportedly take place at Rev. Brooks’ New Beginnings Church in Chicago’s Woodlawn neighborhood after Keef is through serving his time. [Via]
<gh_stars>1-10 #include <stdio.h> char* matchGivenWord( char* word ,char queriedLetter ); int findNumberOfChars( char* word ); void getWord(); void reset(); int main( void ) { int numOfChars = 0; int missMatch = 0; char word[8] = NULL; char typedWord[8] = {'_' , '_' , '_', '_','_' ,'_','_','_'}; char pressedLetter = '\0'; int start = 0; int i = 0; while ( !start ) { reset(); getWord(); } /* it will be sended to 7-Segment-Display */ numOfChars = findNumberOfChars( word ); while ( findNumberOfChars( typedWord ) != numOfChars && missMatch != 10 ) { scanf("%c",&pressedLetter); char* takenWord = matchGivenWord(word , pressedLetter); for( int i = 0 ; i < 8 ; ++i ) { if( takenWord[i] != '\0' ) { typedWord[i] = takenWord[i]; } } if( findNumberOfChars(takenWord) == 0 ) { ++missMatch; } printWordtoScreen(); } if( missMatch < 10 ) { printf("Win"); } else { printf("Lose"); } return 0; } void printWordtoScreen(){ /*Print the word to */} void getWord(){ /* Get input with shifting */}; void reset(){ /* Reset all the input that's given by the player */}; int findNumberOfChars( char* word ) { int numOfChars = 0; for( int i = 0 ; i < 8 ; ++i ) { if( word[i] != '\0' ) { ++numOfChars; } } return numOfChars; } char* matchGivenWord( char* word ,char queriedLetter ) { char* matchedWord = (char*) malloc( sizeof(char) * 8); for( int i = 0 ; i < 8 ; ++i ) { matchedWord[i] = '\0'; } for( int i = 0 ; i < 8 ; ++i ) { if( word[i] == queriedLetter ) { matchedWord[i] = queriedLetter; } } return matchedWord; }