text
stringlengths
1
1.05M
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common' import { TypeOrmModule } from '@nestjs/typeorm' import { JourneyService } from './journey.service' import { JourneyResolver } from './journey.resolver' import { JourneyEntity } from './journey.entity' @Module({ imports: [TypeOrmModule.forFeature([JourneyEntity])], providers: [JourneyService, JourneyResolver], controllers: [], }) export class JourneyModule implements NestModule { configure(consumer: MiddlewareConsumer): void {} }
#!/bin/bash # Copyright 2016 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -ex cd $(dirname $0)/../.. tools/buildgen/generate_projects.sh tools/distrib/clang_format_code.sh tools/distrib/check_copyright.py tools/distrib/check_trailing_newlines.sh
<filename>app/Database/ci4_wpu.sql -- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Aug 13, 2020 at 06:04 AM -- Server version: 10.4.11-MariaDB -- PHP Version: 7.4.6 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `ci4_wpu` -- -- -------------------------------------------------------- -- -- Table structure for table `komik` -- CREATE TABLE `komik` ( `id` int(11) NOT NULL, `judul` varchar(255) NOT NULL, `slug` varchar(255) NOT NULL, `penulis` varchar(255) NOT NULL, `penerbit` varchar(255) NOT NULL, `sampul` varchar(255) NOT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `komik` -- INSERT INTO `komik` (`id`, `judul`, `slug`, `penulis`, `penerbit`, `sampul`, `created_at`, `updated_at`) VALUES (1, '<NAME>', 'naruto-uzumaki', '<NAME>', 'Shonen Jump', '1594815552_e5e795cb4d5d76018716.jpeg', NULL, '2020-07-15 07:19:12'), (2, 'Bleach', 'bleach', 'Tite Kubo', 'Shonen Jump', 'bleach.jpg', NULL, NULL), (12, 'Eye Shield 21', 'eye-shield-21', 'artau', 'yfuofyuo', 'default.jpg', '2020-07-15 06:57:11', '2020-07-15 06:57:11'); -- -------------------------------------------------------- -- -- Table structure for table `migrations` -- CREATE TABLE `migrations` ( `id` bigint(20) UNSIGNED NOT NULL, `version` varchar(255) NOT NULL, `class` text NOT NULL, `group` varchar(255) NOT NULL, `namespace` varchar(255) NOT NULL, `time` int(11) NOT NULL, `batch` int(11) UNSIGNED NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `migrations` -- INSERT INTO `migrations` (`id`, `version`, `class`, `group`, `namespace`, `time`, `batch`) VALUES (1, '2020-07-15-122850', 'App\\Database\\Migrations\\Orang', 'default', 'App', 1594823659, 1); -- -------------------------------------------------------- -- -- Table structure for table `orang` -- CREATE TABLE `orang` ( `id` int(11) UNSIGNED NOT NULL, `nama` varchar(255) NOT NULL, `alamat` varchar(255) NOT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `orang` -- INSERT INTO `orang` (`id`, `nama`, `alamat`, `created_at`, `updated_at`) VALUES (1, '<NAME>', 'Gg. Rajawali Timur No. 20, Samarinda 99382, KepR', '2016-06-30 14:32:46', '2020-07-15 10:17:17'), (2, '<NAME>', 'Jr. Ki Hajar Dewantara No. 500, Sawahlunto 57319, PapBar', '2019-06-02 06:51:55', '2020-07-15 10:17:17'), (3, '<NAME>', 'Dk. K.<NAME> (Kopo) No. 301, Pematangsiantar 64808, KepR', '1977-07-05 01:02:57', '2020-07-15 10:17:17'), (4, '<NAME>', 'Ki. Bakau No. 95, Mataram 62861, SumBar', '1995-02-01 08:05:04', '2020-07-15 10:17:17'), (5, '<NAME>', 'Ki. Bayan No. 194, Pekanbaru 16588, JaBar', '1989-09-15 14:59:30', '2020-07-15 10:17:17'), (6, '<NAME>', 'Jr. Katamso No. 64, Ambon 63367, Lampung', '2015-03-22 02:21:49', '2020-07-15 10:17:17'), (7, '<NAME>', 'Ds. Gedebage Selatan No. 87, Payakumbuh 54647, KalBar', '2012-03-17 15:27:38', '2020-07-15 10:17:17'), (8, '<NAME>', 'Kpg. Qrisdoren No. 787, Tomohon 43511, KalUt', '2001-04-29 00:58:37', '2020-07-15 10:17:17'), (9, '<NAME>', 'Jln. Yogyakarta No. 214, Pekalongan 25790, KalBar', '1980-05-21 07:59:53', '2020-07-15 10:17:17'), (10, '<NAME> S.Pt', 'Dk. HOS. Cjokroaminoto (Pasirkaliki) No. 216, Padangsidempuan 97549, Jambi', '2019-02-26 06:11:00', '2020-07-15 10:17:17'), (11, '<NAME> M.Pd', 'Jln. Urip Sumoharjo No. 238, Bima 15419, Gorontalo', '2018-08-15 23:16:11', '2020-07-15 10:17:17'), (12, '<NAME>', 'Kpg. Cikapayang No. 956, Prabumulih 12873, JaTim', '1979-02-22 13:11:22', '2020-07-15 10:17:17'), (13, '<NAME> S.Gz', 'Psr. Umalas No. 353, Metro 54672, SumSel', '2013-07-28 11:49:48', '2020-07-15 10:17:17'), (14, '<NAME>', 'Dk. Barat No. 833, Lhokseumawe 72221, SulTra', '1970-05-15 18:42:22', '2020-07-15 10:17:17'), (15, '<NAME>', 'Psr. Sugiono No. 933, Ambon 58282, SulTra', '1986-08-20 02:33:38', '2020-07-15 10:17:17'), (16, '<NAME>', 'Jr. Gardujati No. 324, Tanjung Pinang 13211, DKI', '2012-01-10 12:57:29', '2020-07-15 10:17:17'), (17, '<NAME>', 'Jln. Monginsidi No. 200, Prabumulih 24967, KalTim', '2003-08-12 22:02:30', '2020-07-15 10:17:17'), (18, '<NAME> M.Kom.', 'Dk. Sunaryo No. 896, Pangkal Pinang 26334, DIY', '1998-05-29 17:12:23', '2020-07-15 10:17:17'), (19, '<NAME>', 'Ki. Casablanca No. 283, Pekanbaru 40274, SulUt', '2015-09-30 13:09:58', '2020-07-15 10:17:17'), (20, '<NAME>', 'Kpg. Daan No. 765, Batu 76410, NTB', '1978-10-27 22:12:43', '2020-07-15 10:17:17'), (21, '<NAME> S.Pd', 'Jln. Cikutra Timur No. 192, Pariaman 51189, Aceh', '2018-05-12 03:31:20', '2020-07-15 10:17:17'), (22, '<NAME>', 'Jr. Qrisdoren No. 835, Palopo 77052, MalUt', '1988-06-22 13:39:43', '2020-07-15 10:17:17'), (23, '<NAME>', 'Jln. Veteran No. 701, Pematangsiantar 53258, JaTim', '1973-11-19 06:24:25', '2020-07-15 10:17:17'), (24, '<NAME>', 'Gg. Bakti No. 159, Palembang 87065, Jambi', '1975-03-09 05:05:32', '2020-07-15 10:17:17'), (25, '<NAME>', 'Kpg. Ahmad Dahlan No. 173, Sungai Penuh 87511, KalSel', '1992-06-05 10:28:52', '2020-07-15 10:17:17'), (26, '<NAME>', 'Kpg. Abdul Rahmat No. 221, Cimahi 17236, NTB', '2000-11-03 02:03:11', '2020-07-15 10:17:17'), (27, '<NAME>', 'Gg. Zamrud No. 625, Cimahi 67665, Gorontalo', '1985-08-08 14:11:16', '2020-07-15 10:17:17'), (28, '<NAME>', 'Dk. Kusmanto No. 372, Bitung 60635, SumBar', '2013-12-20 03:15:07', '2020-07-15 10:17:17'), (29, '<NAME>', 'Jln. Uluwatu No. 21, Serang 70475, KalTeng', '2019-03-15 20:06:10', '2020-07-15 10:17:17'), (30, '<NAME>', 'Kpg. Gremet No. 335, Tomohon 90821, Bali', '2012-08-07 08:57:10', '2020-07-15 10:17:17'), (31, '<NAME>', 'Psr. Baja No. 341, Cirebon 13091, SumUt', '2012-12-14 03:33:49', '2020-07-15 10:17:17'), (32, 'Emong Saefullah M.TI.', 'Ki. Siliwangi No. 46, Administrasi Jakarta Barat 31054, Gorontalo', '2006-09-16 09:45:22', '2020-07-15 10:17:17'), (33, '<NAME>', 'Kpg. Surapati No. 293, Administrasi Jakarta Barat 94832, Banten', '1990-12-10 12:24:17', '2020-07-15 10:17:17'), (34, '<NAME>', 'Psr. Bakti No. 60, Blitar 42177, SulTra', '2002-05-05 04:22:11', '2020-07-15 10:17:17'), (35, '<NAME>', 'Dk. Diponegoro No. 414, Solok 71357, SulSel', '1996-05-09 17:08:58', '2020-07-15 10:17:17'), (36, '<NAME> S.I.Kom', 'Jr. Astana Anyar No. 798, Blitar 80975, SumBar', '1988-08-09 01:01:56', '2020-07-15 10:17:17'), (37, '<NAME>', 'Jr. Bara Tambar No. 968, Bandar Lampung 31573, Jambi', '2012-03-04 09:54:03', '2020-07-15 10:17:17'), (38, '<NAME> S.E.', 'Jln. Ters. Kiaracondong No. 366, Cilegon 21174, KepR', '1998-05-26 20:22:33', '2020-07-15 10:17:17'), (39, '<NAME>', 'Gg. Dipatiukur No. 31, Dumai 83908, SulBar', '1995-02-20 15:38:48', '2020-07-15 10:17:17'), (40, '<NAME> S.H.', 'Jln. Reksoninten No. 331, Medan 88678, NTT', '1990-07-19 06:29:17', '2020-07-15 10:17:17'), (41, '<NAME>', 'Psr. Bakau No. 801, Padang 52527, SulBar', '2013-05-06 12:17:38', '2020-07-15 10:17:17'), (42, '<NAME>', 'Ds. Yos No. 851, Cirebon 27158, NTB', '1972-06-20 08:30:30', '2020-07-15 10:17:17'), (43, '<NAME>', 'Ki. Baladewa No. 574, Magelang 28736, SumSel', '1973-12-07 01:44:44', '2020-07-15 10:17:17'), (44, '<NAME> S.Gz', 'Jr. <NAME> No. 850, Subulussalam 44201, SumBar', '2004-03-04 16:19:05', '2020-07-15 10:17:17'), (45, 'Eja Arta Utama S.Farm', 'Ds. Wahid No. 103, Bontang 52001, KalSel', '2016-11-02 04:35:46', '2020-07-15 10:17:17'), (46, '<NAME>', 'Dk. Reksoninten No. 900, Tangerang Selatan 11421, KalTeng', '1997-10-06 10:55:11', '2020-07-15 10:17:17'), (47, '<NAME>', 'Psr. Kalimantan No. 749, Palu 54795, DKI', '2013-06-03 16:58:39', '2020-07-15 10:17:17'), (48, '<NAME>', 'Jr. <NAME>ati No. 563, Pontianak 76090, Aceh', '1981-03-01 07:18:34', '2020-07-15 10:17:17'), (49, '<NAME> S.Pt', 'Dk. Madrasah No. 688, Tebing Tinggi 27469, DIY', '1975-08-14 13:00:29', '2020-07-15 10:17:17'), (50, '<NAME>', 'Ds. Babadak No. 275, Pontianak 78087, KalTeng', '1973-06-26 19:27:45', '2020-07-15 10:17:17'); -- -- Indexes for dumped tables -- -- -- Indexes for table `komik` -- ALTER TABLE `komik` ADD PRIMARY KEY (`id`); -- -- Indexes for table `migrations` -- ALTER TABLE `migrations` ADD PRIMARY KEY (`id`); -- -- Indexes for table `orang` -- ALTER TABLE `orang` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `komik` -- ALTER TABLE `komik` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- AUTO_INCREMENT for table `migrations` -- ALTER TABLE `migrations` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `orang` -- ALTER TABLE `orang` MODIFY `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=51; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<reponame>xfyre/tapestry-5 // 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.apache.tapestry5.func; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; /** * Functional operations on collections with generics support. The core interface is {@link Flow} to * which operations * and transformations * (in terms of {@link Predicate}s, {@link Mapper}s and {@link Reducer}s) to create new Flows. Flows * are initially * created * using {@link #flow(Collection)} and {@link #flow(Object...)}. * * F will be used a bit, thus it has a short name (for those who don't like static imports). It provides a base set of * Predicate, Mapper and Reducer factories. A good development pattern for applications is to provide a similar, * application-specific, set of such factories. * * @since 5.2.0 */ @SuppressWarnings("all") public class F { final static Flow<?> EMPTY_FLOW = new EmptyFlow(); @SuppressWarnings("unchecked") static <T> Flow<T> emptyFlow() { return (Flow<T>) EMPTY_FLOW; } /** * A Predicate factory for equality of an element from a flow against a specified * value. */ public static <T> Predicate<T> eql(final T value) { return new Predicate<T>() { @Override public boolean accept(T element) { return element.equals(value); } }; } /** * Predicate that returns true if the provided string is blank (null or all whitespace). */ public static Predicate<String> IS_BLANK = new Predicate<String>() { @Override public boolean accept(String element) { return element == null || element.trim().length() == 0; } }; /** * A Predicate factory for comparison of a Comparable element from a flow against a fixed value. */ public static <T extends Comparable<T>> Predicate<T> eq(final T value) { return new Predicate<T>() { @Override public boolean accept(T element) { return element.compareTo(value) == 0; } }; } /** * A Predicate factory for comparison of a Comparable element against a fixed value. */ public static <T extends Comparable<T>> Predicate<T> neq(final T value) { return new Predicate<T>() { @Override public boolean accept(T object) { return object.compareTo(value) != 0; } }; } /** * A Predicate factory for comparison of a Comparable against a fixed value; true * if the flow element is greater than the provided value. */ public static <T extends Comparable<T>> Predicate<T> gt(final T value) { return new Predicate<T>() { @Override public boolean accept(T element) { return element.compareTo(value) > 0; } }; } /** * A Predicate factory for comparison of a Comparable against a fixed value; true * if the flow element is greater than or equal to the value. */ public static <T extends Comparable<T>> Predicate<T> gteq(final T value) { return new Predicate<T>() { @Override public boolean accept(T element) { return element.compareTo(value) >= 0; } }; } /** * A Predicate factory for comparison of a Comparable against a fixed value; true * if the element is less than the value. */ public static <T extends Comparable<T>> Predicate<T> lt(T value) { return not(gteq(value)); } /** * A Predicate factory for comparison of a Comprable element against a fixed value; true * if the element is less than or equal to the value. */ public static <T extends Comparable<T>> Predicate<T> lteq(T value) { return not(gt(value)); } /** * A Predicate factory; returns true if the value from the Flow is null. */ public static <T> Predicate<T> isNull() { return new Predicate<T>() { @Override public boolean accept(T element) { return element == null; } }; } /** * A Predicate factory; returns true if the value from the Flow is not null. */ public static <T> Predicate<T> notNull() { return not(isNull()); } /** * A Mapper factory that gets the string value of the flow value using {@link String#valueOf(Object)}. */ public static <T> Mapper<T, String> stringValueOf() { return new Mapper<T, String>() { @Override public String map(T value) { return String.valueOf(value); } }; } /** * A Mapper factory; the returned Mapper ignores its input value and always returns a * predetermined result. */ public static <S, T> Mapper<S, T> always(final T fixedResult) { return new Mapper<S, T>() { @Override public T map(S input) { return fixedResult; } }; } /** * A Mapper factory that combines a Predicate with two {@link Mapper}s; evaluating the predicate * selects one of the two mappers. * * @param predicate * evaluated to selected a coercion * @param ifAccepted * used when predicate evaluates to true * @param ifRejected * used when predicate evaluates to false */ public static <S, T> Mapper<S, T> select(final Predicate<? super S> predicate, final Mapper<S, T> ifAccepted, final Mapper<S, T> ifRejected) { assert predicate != null; assert ifAccepted != null; assert ifRejected != null; return new Mapper<S, T>() { @Override public T map(S input) { Mapper<S, T> active = predicate.accept(input) ? ifAccepted : ifRejected; return active.map(input); } }; } /** * Override of {@link #select(Predicate, Mapper, Mapper)} where rejected values are replaced * with null. */ public static <S, T> Mapper<S, T> select(Predicate<? super S> predicate, Mapper<S, T> ifAccepted) { return select(predicate, ifAccepted, (T) null); } /** * Override of {@link #select(Predicate, Mapper)} where rejected values are replaced with a * fixed value. */ public static <S, T> Mapper<S, T> select(Predicate<? super S> predicate, Mapper<S, T> ifAccepted, T ifRejectedValue) { Mapper<S, T> rejectedMapper = always(ifRejectedValue); return select(predicate, ifAccepted, rejectedMapper); } /** * A Mapper factory; the Mapper returns the the flow value unchanged. */ public static <S> Mapper<S, S> identity() { return new Mapper<S, S>() { @Override public S map(S input) { return input; } }; } /** * Allows a Mapper that maps to boolean to be used as a Predicate. */ public static <S> Predicate<S> toPredicate(final Mapper<S, Boolean> mapper) { assert mapper != null; return new Predicate<S>() { @Override public boolean accept(S object) { return mapper.map(object); } }; } /** * A Reducer that operates on a Flow of Integers and is used to sum the values. */ public static Reducer<Integer, Integer> SUM_INTS = new Reducer<Integer, Integer>() { @Override public Integer reduce(Integer accumulator, Integer value) { return accumulator + value; } }; /** * A two-input Mapper used to add the values from two Flows of Integers into a Flow of Integer * sums. */ public static Mapper2<Integer, Integer, Integer> ADD_INTS = new Mapper2<Integer, Integer, Integer>() { @Override public Integer map(Integer first, Integer second) { return first + second; } }; /** * Extracts the values from the collection to form a {@link Flow}. The Collection * may change after the Flow is created without affecting the Flow. */ public static <T> Flow<T> flow(Collection<T> values) { assert values != null; if (values.isEmpty()) return emptyFlow(); return new ArrayFlow<T>(values); } /** * Creates a new Flow from the values. You should not change the values array * after invoking this method (i.e., no defensive copy of the values is made). */ public static <T> Flow<T> flow(T... values) { if (values.length == 0) return emptyFlow(); return new ArrayFlow<T>(values); } /** * Creates a lazy Flow from the {@link Iterator} obtained from the iterable. The Flow * will be threadsafe as long as the iterable yields a new Iterator on each invocation <em>and</em> the underlying * iterable object is not modified while the Flow is evaluating. * In other words, not extremely threadsafe. */ public static <T> Flow<T> flow(Iterable<T> iterable) { assert iterable != null; return flow(iterable.iterator()); } /** * Creates a lazy Flow from the {@link Iterator}. The Flow will be threadsafe as long as the underlying iterable * object is not modified while the Flow is evaluating. In other words, not extremely threadsafe. * * @since 5.3 */ public static <T> Flow<T> flow(Iterator<T> iterator) { return lazy(new LazyIterator<T>(iterator)); } /** * Creates a ZippedFlow from the provided map; the order of the tuples in the ZippedFlow is defined * by the iteration order of the map entries. * * @param <A> * type of key and first tuple value * @param <B> * type of value and second tuple value * @param map * source of tuples * @return zipped flow created from map * @since 5.3 */ public static <A, B> ZippedFlow<A, B> zippedFlow(Map<A, B> map) { assert map != null; Flow<Tuple<A, B>> tuples = F.flow(map.entrySet()).map(new Mapper<Map.Entry<A, B>, Tuple<A, B>>() { @Override public Tuple<A, B> map(Entry<A, B> element) { return Tuple.create(element.getKey(), element.getValue()); } }); return ZippedFlowImpl.create(tuples); } /** * Creates a lazy Flow that returns integers in the given range. The range starts * with the lower value and counts by 1 up to the upper range (which is not part of * the Flow). If lower equals upper, the Flow is empty. If upper is less than lower, * the Flow counts down instead. * * @param lower * start of range (inclusive) * @param upper * end of range (exclusive) */ public static Flow<Integer> range(int lower, int upper) { if (lower == upper) return F.emptyFlow(); if (lower < upper) return lazy(new LazyRange(lower, upper, 1)); return lazy(new LazyRange(lower, upper, -1)); } /** * Creates a {@link Flow} from a {@linkplain LazyFunction lazy function}. */ public static <T> Flow<T> lazy(LazyFunction<T> function) { assert function != null; return new LazyFlow<T>(function); } private static <T> LazyFunction<T> toLazyFunction(final T currentValue, final Mapper<T, T> function) { return new LazyFunction<T>() { @Override public LazyContinuation<T> next() { final T nextValue = function.map(currentValue); return new LazyContinuation<T>(nextValue, toLazyFunction(nextValue, function)); } }; } /** * Creates an infinite lazy flow from an initial value and a function to map from the current value to the * next value. * * @param initial * initial value in flow * @param function * maps from current value in flow to next value in flow * @return lazy flow */ public static <T> Flow<T> iterate(final T initial, final Mapper<T, T> function) { LazyFunction<T> head = new LazyFunction<T>() { @Override public LazyContinuation<T> next() { return new LazyContinuation<T>(initial, toLazyFunction(initial, function)); } }; return lazy(head); } /** * Creates an <em>infinite</em> series of numbers. * * Attempting to get the {@linkplain Flow#count()} of the series will form an infinite loop. */ public static Flow<Integer> series(int start, final int delta) { return iterate(start, new Mapper<Integer, Integer>() { @Override public Integer map(Integer element) { return element + delta; } }); } /** * A Worker factory; the returnedWorker adds the values to a provided collection. */ public static <T> Worker<T> addToCollection(final Collection<T> coll) { return new Worker<T>() { @Override public void work(T value) { coll.add(value); } }; } /** * A Predicate factory for matching String elements with a given prefix. * * @since 5.3 */ public static Predicate<String> startsWith(String prefix) { return startsWith(prefix, false); } /** * As {@link #startsWith(String)}, but ignores case. * * @since 5.3 */ public static Predicate<String> startsWithIgnoringCase(String prefix) { return startsWith(prefix, true); } /** * @since 5.3 */ private static Predicate<String> startsWith(final String prefix, final boolean ignoreCase) { return new Predicate<String>() { @Override public boolean accept(String element) { return element.regionMatches(ignoreCase, 0, prefix, 0, prefix.length()); } }; } /** * A Predicate factory for matching String elements with a given suffix. * * @since 5.3 */ public static Predicate<String> endsWith(String suffix) { return endsWith(suffix, false); } /** * As with {@link #endsWith(String)} but ignores case. * * @since 5.3 */ public static Predicate<String> endsWithIgnoringCase(String suffix) { return endsWith(suffix, true); } /** * @since 5.3 */ private static Predicate<String> endsWith(final String suffix, final boolean ignoreCase) { return new Predicate<String>() { @Override public boolean accept(String element) { return element .regionMatches(ignoreCase, element.length() - suffix.length(), suffix, 0, suffix.length()); } }; } /** * Creates a Comparator for the Tuples of a {@link ZippedFlow} that sorts the Tuple elements based on the first * value in the Tuple. * * @since 5.3 */ public static <A extends Comparable<A>, B> Comparator<Tuple<A, B>> orderByFirst() { return new Comparator<Tuple<A, B>>() { @Override public int compare(Tuple<A, B> o1, Tuple<A, B> o2) { return o1.first.compareTo(o2.first); } }; } /** * Creates a Comparator for the Tuples of a {@link ZippedFlow} that sorts the Tuple elements based on the first * value in the Tuple. * * @since 5.3 */ public static <A, B extends Comparable<B>> Comparator<Tuple<A, B>> orderBySecond() { return new Comparator<Tuple<A, B>>() { @Override public int compare(Tuple<A, B> o1, Tuple<A, B> o2) { return o1.second.compareTo(o2.second); } }; } /** * Inverts a predicate. * * @param delegate * the predicate to invert * @return a new predicate that is inverse to the existing predicate * @since 5.3 */ public static <T> Predicate<T> not(final Predicate<? super T> delegate) { assert delegate != null; return new Predicate<T>() { @Override public boolean accept(T element) { return !delegate.accept(element); } }; } /** * Combines two mappers into a composite mapping from type A to type C via type B. * * @param abMapper * maps from A to B * @param bcMapper * maps from B to C * @return mapper from A to C */ public static <A, B, C> Mapper<A, C> combine(final Mapper<A, B> abMapper, final Mapper<B, C> bcMapper) { assert abMapper != null; assert bcMapper != null; return new Mapper<A, C>() { @Override public C map(A aElement) { B bElement = abMapper.map(aElement); return bcMapper.map(bElement); } }; } /** * Combines any number of delegates as a logical and operation. Evaluation terminates * with the first delegate predicate that returns false. * * @param delegates * to evaluate * @return combined delegate * @since 5.3 */ public static <T> Predicate<T> and(final Predicate<? super T>... delegates) { return new Predicate<T>() { @Override public boolean accept(T element) { for (Predicate<? super T> delegate : delegates) { if (!delegate.accept(element)) return false; } return true; } }; } /** * Combines any number of delegates as a logical or operation. Evaluation terminates * with the first delegate predicate that returns true. * * @param delegates * to evaluate * @return combined delegate * @since 5.3 */ public static <T> Predicate<T> or(final Predicate<? super T>... delegates) { return new Predicate<T>() { @Override public boolean accept(T element) { for (Predicate<? super T> delegate : delegates) { if (delegate.accept(element)) return true; } return false; } }; } /** * Combines several compatible workers together into a composite. * * @since 5.3 */ public static <T> Worker<T> combine(final Worker<? super T>... delegates) { assert delegates.length > 0; return new Worker<T>() { @Override public void work(T value) { for (Worker<? super T> delegate : delegates) { delegate.work(value); } } }; } }
/* eslint-disable react-hooks/exhaustive-deps */ import { useState, useEffect } from 'react' import axios from 'axios' const useUrlLoader = (url: string, deps: any[] = []) => { const [data, setData] = useState<any>(null) const [loading, setLoading] = useState(false) useEffect(() => { setLoading(true) axios.get(url).then(res => { setLoading(false) setData(res.data) }) }, deps) return [data, loading] } export default useUrlLoader
var fs = require("fs"); function hex2num(hex) { return parseInt(hex); } function createByte(code) { var high = Math.floor(code / 0x100), low = code % 0x100; return String.fromCharCode(high, low); } fs.readFile("src/uao250-u2b.txt", "utf-8", function(err, data) { if (err) { throw err; } var i = 0, j, line, table = {}; while (i < data.length) { j = data.indexOf("\n", i); if (j < 0) { j = data.length; } if (data[i] != "#") { // extract line line = data.substring(i, j).trim(); if (line) { var t = line.split(" ").map(hex2num); var big5 = createByte(t[0]), unicode = String.fromCharCode(t[1]); if (t[0] != 65533) { // skip replacement character table[unicode] = big5; } } } i = j + 1; } fs.writeFile("table/u2b.json", JSON.stringify(table), "utf-8"); }); fs.readFile("src/uao250-b2u.txt", "utf-8", function(err, data) { if (err) { throw err; } var i = 0, j, line, table = {}; while (i < data.length) { j = data.indexOf("\n", i); if (j < 0) { j = data.length; } if (data[i] != "#") { // extract line line = data.substring(i, j).trim(); if (line) { var t = line.split(" ").map(hex2num); var big5 = createByte(t[0]), unicode = String.fromCharCode(t[1]); table[big5] = unicode; } } i = j + 1; } fs.writeFile("table/b2u.json", JSON.stringify(table), "utf-8"); });
# awscli s3 ls peco function peco-s3arch() { if [[ $LBUFFER =~ "aws s3 ls" ]]; then local filepath="$(${=BUFFER} | awk '{print $NF}' | peco)" BUFFER=$LBUFFER$filepath CURSOR=$#BUFFER zle redisplay fi } zle -N peco-s3arch bindkey '^j' peco-s3arch
from flask import Flask, jsonify from pymongo import MongoClient app = Flask(__name__) client = MongoClient('localhost', 27017) @app.route('/create', methods=['GET']) def create_record(): db = client.test db.records.insert_one({'name':'John'}) return jsonify({'message': 'Success'}) @app.route('/get', methods=['GET']) def get_record(): db = client.test records= db.records.find() out = [] for record in records: out.append({'name':record['name']}) return jsonify(out) if __name__ == '__main__': app.run(debug=True)
const TextStyleMixin = { styles: { heading: { fontSize: '24px', fontWeight: 'bold', color: 'black', }, subheading: { fontSize: '18px', fontWeight: 'normal', color: 'gray', }, link: { fontSize: '16px', fontWeight: 'bold', color: 'blue', textDecoration: 'underline', }, }, applyStyle(element, styleName) { const style = this.styles[styleName]; if (style) { Object.keys(style).forEach(property => { element.style[property] = style[property]; }); } else { console.error(`Style '${styleName}' is not defined.`); } }, }; export default TextStyleMixin;
<reponame>lerages/anarchy-source<filename>src/main/java/org/rs2server/rs2/model/combat/npcs/Vespula.java package org.rs2server.rs2.model.combat.npcs; public class Vespula { }
<filename>presentation/src/main/java/com/gw/presentation/mapper/TransactionItemModelMapper.java<gh_stars>1-10 package com.gw.presentation.mapper; import com.gw.data.entity.TransactionItemEntity; import com.gw.domain.model.TransactionItem; import com.gw.presentation.internal.di.PerActivity; import com.gw.presentation.model.TransactionItemModel; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.inject.Inject; @PerActivity public class TransactionItemModelMapper { @Inject public TransactionItemModelMapper() { } /** * Transform a {@link TransactionItemEntity} into an {@link TransactionItem}. * * @param item Object to be transformed. * @return {@link TransactionItem} if valid {@link TransactionItemEntity} otherwise null. */ public TransactionItemModel transform(TransactionItem item) { TransactionItemModel itemModel = null; if (item != null) { itemModel = new TransactionItemModel(item.getDate(), item.getAmount()); itemModel.setBalance(item.getBalance()); itemModel.setDescription(item.getDescription()); itemModel.setCurrency(item.getCurrency()); } return itemModel; } /** * Transform a List of {@link TransactionItemEntity} into a Collection of {@link TransactionItem}. * * @param itemCollection Object Collection to be transformed. * @return {@link TransactionItem} if valid {@link TransactionItemEntity} otherwise null. */ public List<TransactionItemModel> transform(Collection<TransactionItem> itemCollection) { final List<TransactionItemModel> itemModels = new ArrayList<>(); for (TransactionItem item : itemCollection) { final TransactionItemModel itemModel = transform(item); if (itemModel != null) { itemModels.add(itemModel); } } return itemModels; } }
# Upload the config.json aws s3 cp config.json s3://emmaa/models/covid19/config.json # Upload the raw statement pickle file python ../../scripts/emmaa_model_from_stmts.py -m covid19 -s ../../../covid-19/stmts/cord19_combined_stmts.pkl -c config.json
#!/bin/bash NODE_QT_MOD=../../node_modules/qt-darwin/Frameworks QMAKE=`which qmake` if [ "$QMAKE" == "" ]; then QT_LIBS_PATH=$NODE_QT_MOD else QT_LIBS_PATH=`qmake -query QT_INSTALL_LIBS` fi QTVERSION=`qmake -query QT_VERSION` if [ "$1" == "--include-dirs" ]; then shift 1 for i in $@; do INCPATH=$QT_LIBS_PATH/${i}.framework/Versions/Current/Headers if [ -d "$INCPATH" ]; then echo $INCPATH fi PRIINCPATH=$QT_LIBS_PATH/${i}.framework/Versions/Current/Headers/$QTVERSION if [ -d "$PRIINCPATH" ]; then echo $PRIINCPATH fi done elif [ "$1" == "--cflags" ]; then if [ -d "$NODE_QT_MOD" ]; then QT_LIBS_PATH=$NODE_QT_MOD fi echo -F$QT_LIBS_PATH elif [ "$1" == "--libs" ]; then shift 1 if [ -d "$NODE_QT_MOD" ]; then QT_LIBS_PATH=$NODE_QT_MOD fi echo -F$QT_LIBS_PATH for i in $@; do echo $QT_LIBS_PATH/${i}.framework done elif [ "$1" == '--internal' ]; then OUT=build/src FILES=" $QT_LIBS_PATH/QtGui.framework/Versions/Current/Headers/$QTVERSION/QtGui/qpa/qwindowsysteminterface.h $QT_LIBS_PATH/QtCore.framework/Versions/Current/Headers/$QTVERSION/QtCore/private/qmetaobjectbuilder_p.h " mkdir -p $OUT/internal for file in $FILES; do if [ -e "$file" ]; then basepath=$(basename $file) out=$OUT/internal/"$basepath" cp -a "$file" $out echo "$out" fi done fi
<gh_stars>0 import { useState } from "react"; import { ChromePicker } from "react-color"; import { StyledBox } from "./Styled"; export default function Box({ data, pickColor, index }) { const [show, setShow] = useState(false); return ( <StyledBox bgColor={data?.color || "orange"} onClick={() => setShow(true)}> {show && ( <ChromePicker color={data?.color || "orange"} onChange={(color) => pickColor(color, index)} onChangeComplete={() => setShow(false)} /> )} </StyledBox> ); }
class InternalTransferLogsController < ApiController def index internal_transfer_logs = InternalTransferLog.for_user(current_user) json_response internal_transfer_logs end def show internal_transfer_log = InternalTransferLog.for_user(current_user).find(params[:id]) json_response internal_transfer_log end end
#!/bin/bash #borrowed form Jeff Helt BRIDGE_NAME=br0 CLIENT_SIDE_IP=192.1.1.1 SERVER_SIDE_IP=10.1.1.1 OVS_PORT=6677 DOCKER_PORT=4243 update() { echo "Updating apt-get..." sudo apt-get update -qq sudo apt-get install -yqq openjdk-11-jre openjdk-11-jdk maven jq echo "Update complete" } install_docker() { echo "Installing Docker..." sudo apt-get update -qq sudo apt-get install -yqq docker-compose sudo apt-get install -yqq apt-transport-https ca-certificates \ curl software-properties-common curl -fsSL https://download.docker.com/linux/ubuntu/gpg \ | sudo apt-key add - sudo apt-key fingerprint 0EBFCD88 sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" sudo apt-get update -qq sudo apt-get install -yqq docker-ce sudo systemctl start docker sudo systemctl enable docker echo "Docker Install Complete" } build_docker_containers(){ echo "Building Snort ICMP Packet Warning Container" sudo docker build -t="snort_demoa" docker_containers/demo_conts/snort_demoA sudo docker build -t="snort_demob" docker_containers/demo_conts/snort_demoB sudo docker build -t="snort_base" docker_containers/demo_conts/snort_base sudo docker build -t="nmap_base" docker_containers/demo_conts/nmap_base echo "Docker containers built" } install_ovs_fromGit() { #Install Build Dependencies sudo apt-get update -qq sudo apt-get install -yqq make gcc \ libcap-ng0 libcap-ng-dev python python-pip autoconf \ libtool wget netcat curl clang sparse flake8 \ graphviz automake python-dev python3-pip \ graphviz build-essential pkg-config \ libssl-dev gdb linux-headers-`uname -r` sudo pip3 -qq install --upgrade pip pip -qq install --user six pyftpdlib tftpy flake8 sparse #Clone repository, build, and install cd ~ git clone https://github.com/slab14/ovs.git cd ovs git checkout feature-kernsign ./boot.sh ./configure --prefix=/usr --localstatedir=/var --sysconfdir=/etc --with-linux=/lib/modules/$(uname -r)/build make sudo make install sudo rmmod openvswitch sudo rm /lib/modules/$(uname -r)/extra/openvswitch.ko sudo make modules_install sudo modprobe -v openvswitch cd ~ # Install ovs-docker-remote dependencies sudo apt-get install -yqq jq curl uuid-runtime # Start OVS Deamons sudo /usr/share/openvswitch/scripts/ovs-ctl start --system-id } setup_maven() { export JAVA_HOME=`type -p javac|xargs readlink -f|xargs dirname|xargs dirname|sed '/s/8/11'` export PATH=$PATH:$JAVA_HOME/bin/ mkdir -p ~/.m2 cp /usr/share/maven/conf/settings.xml ~/.m2/settings.xml cp -n ~/.m2/settings.xml{,.orig} wget -q -O - https://raw.githubusercontent.com/opendaylight/odlparent/6.0.x/settings.xml > ~/.m2/settings.xml export M2_HOME=/usr/share/maven/ export M2=$M2_HOME export MAVEN_OPTS='-Xmx1048m -XX:MaxPermSize=512m -Xms256m' export PATH=$M2:$PATH } find_interface_for_ip() { local ip="$1" local interface=$(ip -o addr | grep "inet $ip" | awk -F ' ' '{ print $2 }') if [[ -z $interface ]]; then return 1 else echo $interface return 0 fi } setup_remote_ovsdb_server() { sudo ovs-appctl -t ovsdb-server ovsdb-server/add-remote ptcp:$OVS_PORT } setup_remote_docker() { sudo sed -i 's/fd\:\/\// fd\:\/\/ \-H tcp\:\/\/127\.0\.0\.1\:'"$DOCKER_PORT"'/g' /lib/systemd/system/docker.service sudo systemctl daemon-reload sudo service docker restart } disable_gro() { local client_side_if=$(find_interface_for_ip $CLIENT_SIDE_IP) local server_side_if=$(find_interface_for_ip $SERVER_SIDE_IP) sudo ethtool -K $client_side_if gro off sudo ethtool -K $server_side_if gro off } setup_bridge() { echo "Setting up basic Bridge..." sudo ovs-vsctl --may-exist add-br $BRIDGE_NAME sudo ip link set $BRIDGE_NAME up local client_side_if=$(find_interface_for_ip $CLIENT_SIDE_IP) local server_side_if=$(find_interface_for_ip $SERVER_SIDE_IP) sudo ovs-vsctl --may-exist add-port $BRIDGE_NAME $client_side_if \ -- set Interface $client_side_if ofport_request=1 sudo ovs-ofctl mod-port $BRIDGE_NAME $client_side_if up sudo ovs-vsctl --may-exist add-port $BRIDGE_NAME $server_side_if \ -- set Interface $server_side_if ofport_request=2 sudo ovs-ofctl mod-port $BRIDGE_NAME $server_side_if up echo "Bridge Setup Complete" } configure_ovs_switch() { sudo ovs-vsctl set-controller $BRIDGE_NAME tcp:127.0.0.1:6633 ptcp:6634 sudo ovs-vsctl set-fail-mode $BRIDGE_NAME secure } get_controller() { cd ~ sudo mkdir -p /etc/sec_gate/policies sudo cp IoT_Sec_Gateway/policies/cloudlab-NewPolicy20.json /etc/sec_gate/policies/cloudlab-NewPolicy20.json sudo mkdir -p /etc/sec_gate/testNode0 sudo cp IoT_Sec_Gateway/docker_containers/demo_conts/snort_base/rules_* /etc/sec_gate/testNode0/ git clone https://github.com/slab14/l2switch.git cd l2switch/ git checkout slab-update ./build.sh cd ~ } load_policies(){ cd ~ sudo mkdir -p /etc/sec_gate/policy sudo mkdir -p /etc/sec_gate/testNode0 sudo chown $USER: /etc/sec_gate cp IoT_Sec_Gateway/policies/baseline /etc/sec_gate/policy/. cp IoT_Sec_Gateway/policies/nmap /etc/sec_gate/policy/. cp IoT_Sec_Gateway/policies/radio /etc/sec_gate/policy/. } # Install packages echo "Beginning Dataplane Setup..." update install_docker build_docker_containers build_docker_containers install_ovs_fromGit install_python_packages setup_maven setup_remote_ovsdb_server setup_remote_docker get_controller # Setup #disable_gro #setup_bridge #configure_ovs_switch echo "Dataplane Ready"
<reponame>nascu/dht-tracker<gh_stars>1-10 from __future__ import absolute_import import tornado.ioloop from ._basehandle import BaseHandle from ._counthandle import CountHandle from ._taskhandle import TaskHandle from ..config import WEBPORT approte = [(r"/count.*",CountHandle),(r"/task",TaskHandle),] application = tornado.web.Application(approte ) #---------------------------------------------------------------------- def web_start(port = WEBPORT): """""" application.listen(port) tornado.ioloop.IOLoop.instance().start()
<reponame>xblia/Upgrade-service-for-java-application /* * Copyright 2015 lixiaobo * * VersionUpgrade project 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 com.cats.ui.cursor; import java.awt.Cursor; import java.awt.Point; import java.awt.Toolkit; import javax.swing.ImageIcon; /** * @author xiaobolx * 2015年11月18日 */ public class BeautifulCursor { private static Cursor customeCursor; private static String gameCursorIcon = "/com/cats/ui/cursor/icon_cursor_hand.png"; public static Cursor getCursor() { if (null == customeCursor) { customeCursor = Toolkit .getDefaultToolkit() .createCustomCursor( new ImageIcon( BeautifulCursor.class .getResource(gameCursorIcon)) .getImage(), new Point(10, 10), "custome"); } return customeCursor; } }
<gh_stars>0 package de.morphyum.speedruncomapiwrapper.entity; public class Moderator { private String id; private String role; }
mylist = [x**2 for x in range(0, 10) if x % 2 == 0]
<reponame>kazukiigeta/go-myjvn // Copyright 2020 go-myjvn authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package myjvn_test import ( "context" "fmt" "github.com/kazukiigeta/go-myjvn" ) func ExampleClient_GetAlertList() { c := myjvn.NewClient(nil) alertList, err := c.GetAlertList(context.Background(), nil) if err != nil { fmt.Println(err) } fmt.Println(alertList.Title) } func ExampleClient_GetVendorList() { c := myjvn.NewClient(nil) vendorList, err := c.GetVendorList(context.Background()) if err != nil { fmt.Println(err) } for _, v := range vendorList.VendorInfo.Vendors { fmt.Println(*v) } } func ExampleClient_GetProductList() { c := myjvn.NewClient(nil) productList, err := c.GetProductList(context.Background()) if err != nil { fmt.Println(err) } for _, product := range productList.VendorInfo.Vendors[100].Products { fmt.Println(*product) } } func ExampleClient_GetVulnOverviewList() { c := myjvn.NewClient(nil) vulnOverviewList, err := c.GetVulnOverviewList(context.Background()) if err != nil { fmt.Println(err) } fmt.Println(vulnOverviewList.Items[0].Title) } func ExampleClient_GetVulnDetailInfo() { c := myjvn.NewClient(nil) vulnDetailInfo, err := c.GetVulnDetailInfo(context.Background(), myjvn.SetVulnID("JVNDB-2020-006469")) if err != nil { fmt.Println(err) } fmt.Println(vulnDetailInfo.VulInfo.VulInfoID) } func ExampleClient_GetStatistics() { c := myjvn.NewClient(nil) statisticsHND, err := c.GetStatistics(context.Background(), myjvn.SetFeed("hnd"), myjvn.SetTheme("sumCvss"), myjvn.SetCWEID("CWE-20"), myjvn.SetDatePublicStartY(2015), ) if err != nil { fmt.Println(err) } statisticsITM, err := c.GetStatistics(context.Background(), myjvn.SetFeed("itm"), myjvn.SetTheme("sumCvss"), myjvn.SetCWEID("CWE-20"), myjvn.SetDatePublicStartY(2015), ) if err != nil { fmt.Println(err) } fmt.Println(statisticsHND.SumCVSS.Titles) fmt.Println(statisticsITM.SumCVSS.Titles) }
package com.telenav.osv.recorder.camera.focus; import java.util.ArrayList; import java.util.List; import android.graphics.Point; import android.hardware.Camera; import android.os.Handler; import com.google.common.base.Optional; import com.telenav.osv.recorder.camera.util.CameraHelper; import com.telenav.osv.utils.Log; import com.telenav.osv.utils.Size; /** * The implementation of the {@code Focus} operations using Camera V1. */ //TODO: This class contains the legacy code and should be refactored properly. @SuppressWarnings("deprecation") public class Camera1FocusManager implements Focus, Camera.AutoFocusCallback { private static final String TAG = Camera1FocusManager.class.getSimpleName(); /** * Milliseconds during which we assume the focus is good */ private static final int FOCUS_KEEP_TIME = 30000; private static final int STATE_FOCUSING = 0; private static final int STATE_FOCUSED = 1; private static final int STATE_NOT_FOCUSED = 2; private static final int STATE_FOCUS_LOCKED = 3; private static final int STATE_FOCUS_UNLOCKED = 4; private static final int STATE_TAP_TO_FOCUS = 5; private static final int FOCUS_WEIGHT = 1000; /** * The maximum number for retrying to focus. */ private static final int MAX_FOCUS_RETRIES = 3; private Camera.Parameters cameraParameters; private Camera camera; private Handler backgroundHandler; private int focusState; private int focusRetryCounter; private long mLastFocusTimestamp = 0; public Camera1FocusManager(Camera.Parameters cameraParameters, Optional<Camera> camera) { if (camera.isPresent()) { this.camera = camera.get(); } this.cameraParameters = cameraParameters; } @Override public void focusOnArea(Point screenPoint, Size previewSize) { Log.d(TAG, "focusOnArea"); if (cameraParameters == null || camera == null) { return; } focusState = STATE_TAP_TO_FOCUS; cancelAutoFocus(); List<Camera.Area> focusList = new ArrayList<>(); Camera.Area focusArea = new Camera.Area(CameraHelper.calculateCameraFocusRect(screenPoint.x, screenPoint.y), FOCUS_WEIGHT); focusList.add(focusArea); if (cameraParameters.getMaxNumFocusAreas() > 0) { cameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); try { if (cameraParameters.getFocusAreas() != null) { cameraParameters.getFocusAreas().clear(); } } catch (NumberFormatException e) { Log.d(TAG, "focusOnArea. Status: error. Message: " + e.getLocalizedMessage()); } cameraParameters.setFocusAreas(focusList); } setParameters(); enableAutoFocus(); } @Override public void lockFocus() { Log.d(TAG, "lockFocus"); focusState = STATE_FOCUS_LOCKED; enableAutoFocus(); } @Override public void unlockFocus() { Log.d(TAG, "unlockFocus"); if (cameraParameters == null || camera == null) { return; } focusState = STATE_FOCUS_UNLOCKED; boolean mContinuousSupported = cameraParameters.getSupportedFocusModes() .contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); if (mContinuousSupported) { cameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); } else { if (cameraParameters.getSupportedFocusModes().contains(Camera.Parameters.FOCUS_MODE_AUTO)) { cameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); } } setParameters(); } @Override public void setBackgroundThread(Handler backgroundHandler) { this.backgroundHandler = backgroundHandler; } @Override public void onAutoFocus(boolean success, Camera camera) { mLastFocusTimestamp = System.currentTimeMillis(); if (!success) { if (focusRetryCounter < MAX_FOCUS_RETRIES) { enableAutoFocus(); focusRetryCounter++; Log.d(TAG, "onAutoFocus. Status: retry. Message: Retry auto focus counter - " + focusRetryCounter); } else { // if the focus is not true after 3 tries cancel the focus and switch to continuous focus focusRetryCounter = 0; unlockFocus(); focusState = STATE_NOT_FOCUSED; } } else { if (focusState == STATE_TAP_TO_FOCUS) { unlockFocus(); } else { focusState = STATE_FOCUSED; } } } @Override public void setCamera(Camera camera) { try { if (camera != null) { cameraParameters = camera.getParameters(); } this.camera = camera; } catch (RuntimeException e) { Log.d(TAG, "setCamera. Status: error. Message: " + e.getMessage()); this.camera = null; this.cameraParameters = null; } } /** * Cancel camera auto focus. */ private void cancelAutoFocus() { if (camera != null) { try { // cancel af camera.cancelAutoFocus(); } catch (Exception e) { Log.w(TAG, "cancelAutoFocus: " + Log.getStackTraceString(e)); } } } /** * Enables the auto focus mode. * @return {@code true} if the auto focus mode is enabled, {@code false} otherwise. */ private boolean enableAutoFocus() { if (camera != null) { try { camera.cancelAutoFocus(); backgroundHandler.post(() -> { try { camera.autoFocus(this); } catch (Exception e) { Log.d(TAG, "enableAutoFocus. Status: error. Message: Unable to focus. " + e.getMessage()); } }); } catch (Exception e) { Log.d(TAG, "enableAutoFocus. Status: error. Message: Unable to cancel auto focus. " + e.getMessage()); return false; } return true; } else { return false; } } /** * Set the camera parameters to the camera device. */ private void setParameters() { try { if (camera != null && cameraParameters != null) { camera.setParameters(cameraParameters); } } catch (Exception e) { Log.d(TAG, "setParameters. Status: error. Message: Unable to set the parameters. " + e.getMessage()); } } /** * Check if manual focus is enabled otherwise enable the auto focus mode. */ private void checkFocusManual() { long time = System.currentTimeMillis(); if ((time - mLastFocusTimestamp > FOCUS_KEEP_TIME) || focusState == STATE_NOT_FOCUSED) { if (enableAutoFocus()) { focusState = STATE_FOCUSING; } } } }
<reponame>retrofuturejosh/typescript-kafka-consumer export interface IKafkaConfig { bootstrap: { servers: string } sasl: { username: string password: string mechanisms: string } security: { protocol: 'plaintext' | 'ssl' | 'sasl_plaintext' | 'sasl_ssl' } dr_msg_cb: boolean topic: string group: { id: string } auto: { offset: { reset: 'smallest' | 'earliest' | 'beginning' | 'largest' | 'latest' | 'end' | 'error' } } }
<gh_stars>1-10 import Vue from 'vue' import Vuex from 'vuex' import common from "../utils/common"; Vue.use(Vuex) export default new Vuex.Store({ state: { menuBG:sessionStorage.getItem("menuBG") || 'no',//导航栏背景是否展示 CurrenciesInfo:{ btc:sessionStorage.getItem("btcprice") || 0, hc:sessionStorage.getItem("hcprice") || 0 },//各种币的价格 imgUrl:process.env.NODE_ENV === 'production'?'//cdn.hashland.com/images/':'//cdn.hashland.com/testimgs/',//图片前缀 userCardInfo:sessionStorage.getItem('setCardInfo') || [],//用户卡牌信息 rewardsInfo:{ proupTitle:'',//标题 minserDis:false, boxarr:[] },//中奖信息 account:sessionStorage.getItem("setAccount") || '',// 账号 chain:sessionStorage.getItem("setChain") || '',//链 HashMenuActive: sessionStorage.getItem('HashMenu') || -1, // 导航栏菜单索引 }, getters: { // 是否是移动端 getIsMobile(){ return document.body.clientWidth > 980 }, // 获取导航栏背景状态 getMenuBG(state){ return state.menuBG; }, // 获取币的价格 getCoinPrice(state){ return state.CurrenciesInfo; }, getrewardsInfo(state){ return state.rewardsInfo; }, // 获取导航栏状态 getMenuIndex(state) { return state.HashMenuActive; }, // 获取完整账号 getAccount(state) { return state.account }, // 截取过后的账号 getSubtringAccount(state) { return common.getSubStr(state.account,4) }, // 获取链接的链 getChain(state) { return state.chain }, // 获取是否已连接且网络状态正确 getIstrue(state) { if(state.chain && state.account && state.account !='no'){ return true }else{ return false } }, // 获取用户卡牌信息 getUserCardInfo(state) { return state.userCardInfo }, // 获取各种币的价格 getCurrenciesPrice(state) { return state.CurrenciesInfo }, }, mutations: { // 设置导航栏背景是否显示 menuBG(state, isMenu) { state.menuBG = isMenu; }, // 设置导航栏状态 HashMenu(state, isMenu) { state.HashMenuActive = isMenu; }, // 接收sdk返回的账号 setAccount(state, data) { state.account = data; }, // 接收sdk返回的链 setChain(state, data) { state.chain = data; }, // 设置中奖信息 setrewardsInfo(state,data) { state.rewardsInfo = data; }, // 设置用户卡牌信息 setCardInfo(state,data) { state.userCardInfo = data; }, // 各种币的价格 setCurrenciesPrice(state,data){ state.CurrenciesInfo = data; } } })
#!/usr/bin/env bash set -e REPO_ROOT="$(dirname "$0")"/.. USE_DEBUGGER=0 DEBUGGER="gdb --args" BOOST_OPTIONS= SOLTEST_OPTIONS= SOLIDITY_BUILD_DIR=${SOLIDITY_BUILD_DIR:-${REPO_ROOT}/build} usage() { echo 2>&1 " Usage: $0 [options] [soltest-options] Runs BOOST C++ unit test program, soltest. Options: --debug soltest invocation prefaced with: \"$DEBUGGER\" --debugger *dbg-cmd* soltest prefaced with your own debugger command. --run_test | -t *name* filters test unit(s) to include or exclude from test. This option can be given several times. --boost-options *x* Set BOOST option *x*. --show-progress | -p Set BOOST option --show-progress. Important environment variables: SOLIDITY_BUILD_DIR: Sets directory where test/soltest should be found. The default is \"${SOLIDITY_BUILD_DIR}\". " } while [ $# -gt 0 ] do case "$1" in --debugger) shift DEBUGGER="$1" USE_DEBUGGER=1 ;; --debug) USE_DEBUGGER=1 ;; --boost-options) shift BOOST_OPTIONS="${BOOST_OPTIONS} $1" ;; --help) usage exit 0 ;; --run_test | -t ) shift BOOST_OPTIONS="${BOOST_OPTIONS} -t $1" ;; --show-progress | -p) BOOST_OPTIONS="${BOOST_OPTIONS} $1" ;; *) SOLTEST_OPTIONS="${SOLTEST_OPTIONS} $1" ;; esac shift done if [ "$USE_DEBUGGER" -ne "0" ]; then DEBUG_PREFIX=${DEBUGGER} fi exec ${DEBUG_PREFIX} ${SOLIDITY_BUILD_DIR}/test/soltest ${BOOST_OPTIONS} -- --testpath ${REPO_ROOT}/test ${SOLTEST_OPTIONS}
<reponame>zhaozw/servicecomb-java-chassis<filename>demo/demo-zeroconfig-schemadiscovery-registry/demo-zeroconfig-schemadiscovery-registry-client/src/main/java/org/apache/servicecomb/demo/zeroconfig/client/ClientServerEndpoint.java /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.servicecomb.demo.zeroconfig.client; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.ws.rs.core.MediaType; import org.apache.servicecomb.provider.pojo.RpcReference; import org.apache.servicecomb.provider.rest.common.RestSchema; import org.apache.servicecomb.registry.DiscoveryManager; import org.apache.servicecomb.registry.api.registry.Microservice; import org.apache.servicecomb.swagger.extend.annotations.RawJsonRequestBody; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import io.vertx.core.json.JsonObject; @RestSchema(schemaId = "ClientServerEndpoint") @RequestMapping(path = "/register/url/prefix", produces = MediaType.APPLICATION_JSON) public class ClientServerEndpoint { private static final Logger LOGGER = LoggerFactory.getLogger(ClientServerEndpoint.class); @RpcReference(microserviceName = "demo-zeroconfig-schemadiscovery-registry-server", schemaId = "ServerEndpoint") private IServerEndpoint serverEndpoint; @RpcReference(microserviceName = "demo-zeroconfig-schemadiscovery-registry-server", schemaId = "RpcEndpoint") private IRpcEndpoint rpcEndpoint; @GetMapping(path = "/getName") public String getName(@RequestParam(name = "name") String name) { return serverEndpoint.getName(name); } @GetMapping(path = "/getRegisteredMicroservice") public Set<String> getRegisteredMicroservice() { List<Microservice> microserviceList = DiscoveryManager.INSTANCE.getAllMicroservices(); Set<String> names = new HashSet<>(); for (Microservice m : microserviceList) { if (m.getServiceName().equals("demo-zeroconfig-schemadiscovery-registry-client") || m.getServiceName().equals("demo-zeroconfig-schemadiscovery-registry-server")) { names.add(m.getServiceName()); } } return names; } @PostMapping(path = "/jsonObject") public JsonObject jsonObject(@RequestBody JsonObject jsonObject) { JsonObject param = new JsonObject(); param.put("map", jsonObject); JsonObject message = rpcEndpoint.getJsonObject(param); JsonObject inner = new JsonObject(); inner.put("map", message); return inner; } @PostMapping(path = "/getString") public String getString(@RawJsonRequestBody String jsonString) { return jsonString; } }
export function repeater(str: string, n: number): string { let repeatedStr: string = ""; for (let i = 0; i < n; i++) repeatedStr += str; return repeatedStr; } // Write a function named repeater() that takes two arguments (a string and a number), // and returns a new string where the input string is repeated that many times. // Example: // Repeater.repeat("a", 5) // should return // "aaaaa"
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/512+0+512-FW/13-model --tokenizer_name model-configs/1024-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/512+0+512-FW/13-512+0+512-N-VB-FILL-first-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function remove_all_but_nouns_and_verbs_fill_first_half_quarter --eval_function penultimate_quarter_eval
#!/bin/sh set -e echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" install_framework() { if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then local source="${BUILT_PRODUCTS_DIR}/$1" elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" elif [ -r "$1" ]; then local source="$1" fi local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" if [ -L "${source}" ]; then echo "Symlinked..." source="$(readlink "${source}")" fi # use filter instead of exclude so missing patterns dont' throw errors echo "rsync -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" rsync -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" local basename basename="$(basename -s .framework "$1")" binary="${destination}/${basename}.framework/${basename}" if ! [ -r "$binary" ]; then binary="${destination}/${basename}" fi # Strip invalid architectures so "fat" simulator / device frameworks work on device if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then strip_invalid_archs "$binary" fi # Resign the code if required by the build settings to avoid unstable apps code_sign_if_enabled "${destination}/$(basename "$1")" # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then local swift_runtime_libs swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]}) for lib in $swift_runtime_libs; do echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" code_sign_if_enabled "${destination}/${lib}" done fi } # Signs a framework with the provided identity code_sign_if_enabled() { if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then # Use the current code_sign_identitiy echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements '$1'" if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then code_sign_cmd="$code_sign_cmd &" fi echo "$code_sign_cmd" eval "$code_sign_cmd" fi } # Strip invalid architectures strip_invalid_archs() { binary="$1" # Get architectures for current file archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)" stripped="" for arch in $archs; do if ! [[ "${VALID_ARCHS}" == *"$arch"* ]]; then # Strip non-valid architectures in-place lipo -remove "$arch" -output "$binary" "$binary" || exit 1 stripped="$stripped $arch" fi done if [[ "$stripped" ]]; then echo "Stripped $binary of architectures:$stripped" fi } if [[ "$CONFIGURATION" == "Debug" ]]; then install_framework "$BUILT_PRODUCTS_DIR/AFNetworking/AFNetworking.framework" install_framework "$BUILT_PRODUCTS_DIR/HATHandyKit/HATHandyKit.framework" install_framework "$BUILT_PRODUCTS_DIR/MBProgressHUD/MBProgressHUD.framework" install_framework "$BUILT_PRODUCTS_DIR/MJRefresh/MJRefresh.framework" install_framework "$BUILT_PRODUCTS_DIR/Masonry/Masonry.framework" install_framework "$BUILT_PRODUCTS_DIR/SDWebImage/SDWebImage.framework" install_framework "$BUILT_PRODUCTS_DIR/YTKNetwork/YTKNetwork.framework" fi if [[ "$CONFIGURATION" == "Release" ]]; then install_framework "$BUILT_PRODUCTS_DIR/AFNetworking/AFNetworking.framework" install_framework "$BUILT_PRODUCTS_DIR/HATHandyKit/HATHandyKit.framework" install_framework "$BUILT_PRODUCTS_DIR/MBProgressHUD/MBProgressHUD.framework" install_framework "$BUILT_PRODUCTS_DIR/MJRefresh/MJRefresh.framework" install_framework "$BUILT_PRODUCTS_DIR/Masonry/Masonry.framework" install_framework "$BUILT_PRODUCTS_DIR/SDWebImage/SDWebImage.framework" install_framework "$BUILT_PRODUCTS_DIR/YTKNetwork/YTKNetwork.framework" fi if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then wait fi
import { RefObject } from "react"; export interface UseOutsideClickProps { /** * Whether the hook is enabled */ enabled?: boolean; /** * The reference to a DOM element. */ ref: RefObject<HTMLElement>; /** * Function invoked when a click is triggered outside the referenced element. */ handler?: (e: Event) => void; } /** * Example, used in components like Dialogs and Popovers so they can close * when a user clicks outside them. */ export declare function useOutsideClick(props: UseOutsideClickProps): void; //# sourceMappingURL=use-outside-click.d.ts.map
<gh_stars>100-1000 require "forwardable" require "agent/queue/buffered" require "agent/queue/unbuffered" require "agent/errors" module Agent class Queue extend Forwardable attr_reader :type, :operations # protected attributes attr_reader :mutex, :queue, :pops, :pushes protected :mutex, :queue, :pops, :pushes # size is the queue size def_delegators :@queue, :size def initialize(type) @type = type raise Errors::Untyped unless @type raise Errors::InvalidType unless @type.is_a?(Module) @closed = false @queue = [] @operations = [] @pushes = [] @pops = [] @mutex = Mutex.new reset_custom_state end def buffered? # implement in subclass raise Errors::NotImplementedError end def unbuffered? # implement in subclass raise Errors::NotImplementedError end def pop? # implement in subclass raise Errors::NotImplementedError end def push? # implement in subclass raise Errors::NotImplementedError end def close mutex.synchronize do raise Errors::ChannelClosed if @closed @operations.each{|o| o.close } @closed = true reset_custom_state end end def closed?; @closed; end def open?; !@closed; end def push(object, options={}) raise Errors::InvalidType unless object.is_a?(@type) push = Push.new(object, options) mutex.synchronize do raise Errors::ChannelClosed if @closed operations << push pushes << push process end return push if options[:deferred] push.wait end def pop(options={}) pop = Pop.new(options) mutex.synchronize do pop.close if @closed and queue.size == 0 operations << pop pops << pop process end return pop if options[:deferred] ok = pop.wait [pop.object, ok] end def remove_operations(ops) mutex.synchronize do return if @closed ops.each do |operation| operations.delete(operation) end pushes.clear pops.clear operations.each do |operation| if operation.is_a?(Push) pushes << operation else pops << operation end end reset_custom_state end end protected def reset_custom_state # implement in subclass...or not... end def process # implement in subclass raise Errors::NotImplementedError end end end
g++ -std=c++11 -g -o Test test.cpp -I ./ -ltcmalloc #g++ -std=c++11 -g -o Test test.cpp -I ./
import operator import re def get_keywords(sentence): # Store list of words in a set words = set(re.split(r"\W+", sentence)) # Count occurances of each word in the set count_dict = {} for word in words: count_dict[word] = sentence.count(word) # Sort the words according to their occurences sorted_words = sorted(count_dict.items(), key = operator.itemgetter(1), reverse = True) # Return the three most frequently used words keywords = [word[0] for word in sorted_words[:3]] return keywords
// <NAME> Copyright (c) 2019 // New Beginnings 2018 - Capstone Project // filename: f_printUserList.c #include "headers.h" int userListPrint(struct userList* L) { printf("printing user linked list\n"); if (L->head == NULL) { printf("no head, returning to main\n"); return 0; } struct userData* current = L->head; int tempCount = 0; while (current != NULL) { tempCount++; printf("#%d = location: %s\tlat,lng: %lf, %lf\n", tempCount,current->userLocation, current->u_lat, current->u_long); current = current->next; } printf("done printing linked list\n"); return 0; }
func distinctElements(input: [Int]) -> [Int] { // Create a set with the elements in the input array var distinctSet = Set(input) // Create an array from the set let distinctArray = Array(distinctSet) return distinctArray } // Test cases print(distinctElements(input: [1,2,1,3,4,4,4])) // Output: [1,2,3,4]
<filename>src/ProgressChart/consts.js export const TYPES_LAYOUT = ['vertical', 'horizontal']; export const TYPES_LABEL_POSITION = ['left', 'right', 'inline', 'above', 'below'];
package com.github.chen0040.leetcode.day21.medium; import java.util.ArrayList; import java.util.List; /** * Created by xschen on 16/8/2017. * * link: https://leetcode.com/problems/permutation-sequence/description/ */ public class PermutationSequence { public class Solution { String target; int count; public String getPermutation(int n, int k) { int[] factorial = new int[n]; factorial[0] = 1; for(int i = 1; i < n; ++i) { factorial[i] = factorial[i-1] * i; } k--; List<Integer> nums = new ArrayList<Integer>(); for(int i=0; i < n; ++i) { nums.add(i+1); } StringBuilder sb = new StringBuilder(); for(int i=1; i <= n; ++i) { int index = k / factorial[n-i]; sb.append(nums.get(index)); nums.remove(nums.get(index)); k -= index * factorial[n-i]; } return sb.toString(); } } }
/* eslint-disable */ /* ESLint didn't like some expects */ import { expect } from 'chai' import { shallowMount } from 'corteza-webapp-messaging/tests/lib/helpers' import Threads from 'corteza-webapp-messaging/src/views/Threads' import Messages from 'corteza-webapp-messaging/src/components/Messages' import fp from 'flush-promises' import sinon from 'sinon' describe('corteza-webapp-messaging/src/views/Threads.vue', () => { afterEach(() => { sinon.restore() }) let propsData, $MessagingAPI, $SystemAPI, $auth beforeEach(() => { propsData = { channel: { channelID: 'ch.0001', members: [], }, } $MessagingAPI = { statusList: sinon.stub().resolves([]), searchMessages: sinon.stub().resolves({}), searchThreads: sinon.stub().resolves({}), messagePinRemove: sinon.stub().resolves({}), messagePinCreate: sinon.stub().resolves({}), messageBookmarkRemove: sinon.stub().resolves({}), messageBookmarkCreate: sinon.stub().resolves({}), messageReactionRemove: sinon.stub().resolves({}), messageReactionCreate: sinon.stub().resolves({}), messageDelete: sinon.stub().resolves({}), } $SystemAPI = { userList: sinon.stub().resolves({}), } $auth = { user: { userID: 'u.0001' }, } }) const mountCmp = (opt) => { return shallowMount(Threads, { mocks: { $MessagingAPI, $SystemAPI, $auth }, propsData, ...opt, }) } describe('state', () => { it('should fetch threads on load', async () => { $MessagingAPI.searchThreads = sinon.stub().resolves([ { messageID: '0001', message: 'content1', replies: 2 }, { messageID: '0002', message: 'content1', replies: 1 }, { messageID: '0003', message: 'content1', replies: 0 }, { messageID: '0004', message: 'content1', replyTo: '0001' }, ]) const wrap = mountCmp() await fp() expect(wrap.findAll(Messages)).to.have.length(2) }) it('should group messages under topics', async () => { $MessagingAPI.searchThreads = sinon.stub().resolves([ { messageID: '0001', message: 'content1', replies: 3 }, { messageID: '0002', message: 'content1', replyTo: '0001' }, { messageID: '0003', message: 'content1', replyTo: '0001' }, { messageID: '0004', message: 'content1', replyTo: '0001' }, ]) const wrap = mountCmp() await fp() expect(wrap.findAll(Messages)).to.have.length(1) const m = wrap.find(Messages) const { messages } = m.props() expect(messages).to.have.length(4) }) }) })
#!/bin/sh "${SRCROOT}/Pods/Target Support Files/Pods-ClubMessenger/Pods-ClubMessenger-frameworks.sh"
#include <stddef.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include <stdlib.h> #include <lib/formats/gltf.h> int main(int argc, char** argv) { struct Gltf gltf; if (argc < 2) { printf("usage: %s filename\n", argv[0]); return -1; } gltf_ctor(&gltf, argv[1]); for (int i = 0; i < gltf.n_scenes; i++) { printf("Scene name: '%s'\n", gltf.scenes[i].name); for (int j = 0; j < gltf.scenes[i].n_nodes; j++) { printf("Node: %d\n", gltf.scenes[i].nodes[j]); } for (int j = 0; j < gltf.n_buffers; j++) { printf("Buffer: %d %p %ld\n", j, gltf.buffers[j].data, (long)gltf.buffers[j].size); } for (int j = 0; j < gltf.n_views; j++) { printf("View: %d %d %p %ld\n", j, gltf.views[j].buffer, gltf.views[j].data, (long)gltf.views[j].size); } for (int j = 0; j < gltf.n_nodes; j++) { printf("Node: %d '%s'\n", j, gltf.nodes[j].name); } for (int j = 0; j < gltf.n_accessors; j++) { printf("Accessor: %d %d %d\n", j, gltf.accessors[j].view, gltf.accessors[j].count); } } printf("Meshes: %d\n", gltf.n_meshes); gltf_dtor(&gltf); return 0; }
/** * Implementation of the * {@link com.google.android.stardroid.source.AstronomicalSource} interface * from objects serialized as protocol buffers. * * @author <NAME> */ function ProtobufAstronomicalSource(proto, resources) { AbstractAstronomicalSource.call(this); var shapeMap = {}; shapeMap[0] = PointSource.Shape.CIRCLE; shapeMap[1] = PointSource.Shape.CIRCLE; shapeMap[2] = PointSource.Shape.ELLIPTICAL_GALAXY; shapeMap[3] = PointSource.Shape.SPIRAL_GALAXY; shapeMap[4] = PointSource.Shape.IRREGULAR_GALAXY; shapeMap[5] = PointSource.Shape.LENTICULAR_GALAXY; shapeMap[6] = PointSource.Shape.GLOBULAR_CLUSTER; shapeMap[7] = PointSource.Shape.OPEN_CLUSTER; shapeMap[8] = PointSource.Shape.NEBULA; shapeMap[9] = PointSource.Shape.HUBBLE_DEEP_FIELD; // Lazily construct the names. var names = null; this.getNames = function () { if (names == null) { names = []; if (proto.names_ids) { proto.name_ids.forEach(function (id) { names.push(resources.getString(id)); }); } } return names; }; function getCoords(proto) { return GeocentricCoordinates.getInstance(proto.right_ascension, proto.declination); }; this.getSearchLocation = function () { return getCoords(proto.search_location); } this.getPoints = function () { if (!proto.point || proto.point.length == 0) { return []; } var points = []; proto.point.forEach(function (element) { points.push(new PointSourceImpl(getCoords(element.location), element.color, element.size, shapeMap[element.shape])); }); return points; }; this.getLabels = function () { if (!proto.label || proto.label.length == 0) { return []; } var points = []; proto.label.forEach(function (element) { points.push(new TextSourceImpl(getCoords(element.location), resources.getString(element.string_index), element.color, element.offset, element.font_size)); }); return points; }; this.getLines = function () { if (!proto.line || proto.line.length == 0) { return []; } var points = []; proto.line.forEach(function (element) { var vertices = []; element.vertex.forEach(function (elementVertex) { vertices.push(getCoords(elementVertex)); }); var line_width = element.line_width || 1.5; points.push(new LineSourceImpl(element.color, vertices, line_width)); }); return points; }; }
/** Name: <NAME> Course: BTP305 **/ #ifndef _I_PRODUCT_H_ #define _I_PRODUCT_H_ #include <iostream> #include <fstream> namespace w7 { class iProduct { public: virtual double getCharge() const = 0; virtual void display(std::ostream&) const = 0; virtual ~iProduct(){}; }; std::ostream& operator<<(std::ostream&, const iProduct&); iProduct* readProduct(std::ifstream&); } #endif
<gh_stars>0 package services import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "os" ) func GetAwsSession() *session.Session { return session.Must(session.NewSession( &aws.Config{ Endpoint: aws.String(os.Getenv("AWS_ENDPOINT")), Region: aws.String(os.Getenv("AWS_REGION")), }, )) }
package com.codecool.quest; import com.codecool.quest.inventoryui.*; import com.codecool.quest.logic.*; import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.input.KeyEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.paint.Color; import javafx.stage.Stage; public class Main extends Application { GameMap map = MapLoader.loadMap(); Canvas canvas = new Canvas( map.getWidth() * Tiles.TILE_WIDTH, map.getHeight() * Tiles.TILE_WIDTH); GraphicsContext context = canvas.getGraphicsContext2D(); Label healthLabel = new Label(); Label inventoryLabel = new Label(); // Label wonLabel = new Label(); // Label loseLabel = new Label(); static Button button = new Button("Pick up"); public static Inventory inventory = new Inventory(); private InventoryUI inventoryui = new InventoryUI(); public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { GridPane rightPanel = new GridPane(); GridPane inventoryPanel = new GridPane(); rightPanel.setPrefWidth(200); rightPanel.setPadding(new Insets(10)); Label label = new Label(); GridPane.setConstraints(label, 10, 20); inventoryui.setInventoryUI(inventoryPanel); inventory.setUI(inventoryui); rightPanel.add(inventoryPanel, 0, 6); rightPanel.add(new Label("Health: "), 0, 0); rightPanel.add(healthLabel, 1, 0); // rightPanel.add(new Label("You Won!"), 0, 12); // rightPanel.add(wonLabel, 5, 0); // rightPanel.add(new Label("You Lose!"), 0, 11); // rightPanel.add(loseLabel, 5, 0); rightPanel.add(new Label("Inventory: "), 0, 1); rightPanel.add(inventoryLabel, 1, 0); Canvas inventoryCanvas = new Canvas( Tiles.TILE_WIDTH, Tiles.TILE_WIDTH); rightPanel.add(inventoryCanvas, 0, 0); rightPanel.add(button, 6, 10); // loseLabel.setVisible(true); // wonLabel.setVisible(true); button.setVisible(false); BorderPane borderPane = new BorderPane(); borderPane.setCenter(canvas); borderPane.setRight(rightPanel); Scene scene = new Scene(borderPane); primaryStage.setScene(scene); refresh(); button.setOnAction(actionEvent -> { inventory.addItem(map.getPlayer().getCell().getItem().getTileName()); map.getPlayer().getCell().setItem(null); hidePickUpButton(); borderPane.requestFocus(); }); scene.setOnKeyPressed(this::onKeyPressed); primaryStage.setTitle("Codecool Quest"); primaryStage.show(); borderPane.requestFocus(); } private void onKeyPressed(KeyEvent keyEvent) { if (map.getPlayer().getHealth() != 0 && !inventory.getInventoryList().contains("crown")) { switch (keyEvent.getCode()) { case UP: map.getPlayer().move(0, -1); refresh(); break; case DOWN: map.getPlayer().move(0, 1); refresh(); break; case LEFT: map.getPlayer().move(-1, 0); refresh(); break; case RIGHT: map.getPlayer().move(1, 0); refresh(); break; } } } public static void showPickUpButton() { button.setVisible(true); } public static void hidePickUpButton() { button.setVisible(false); } private void refresh() { context.setFill(Color.BLACK); context.fillRect(0, 0, canvas.getWidth(), canvas.getHeight()); for (int x = 0; x < map.getWidth(); x++) { for (int y = 0; y < map.getHeight(); y++) { Cell cell = map.getCell(x, y); if (cell.getActor() != null) { Tiles.drawTile(context, cell.getActor(), x, y); } else if (cell.getItem() != null) { Tiles.drawTile(context, cell.getItem(), x, y); } else { Tiles.drawTile(context, cell, x, y); } } } healthLabel.setText("" + map.getPlayer().getHealth()); } }
<gh_stars>1-10 import { useEffect, useState } from 'react'; import useRouter from './useRouter'; function useSearch<T>(arr: T[], textFields: (keyof T)[], priceFields: (keyof T)[]) { const [dataToReturn, setDataToReturn] = useState<T[]>([]); const { query } = useRouter(); const { search = '', minMax = '' } = query; useEffect(() => { setDataToReturn(arr); }, []); useEffect(() => { const searchName = arr.filter((item) => { const dataToSearch = textFields .map((field) => item[field]) .join(' ') .toLowerCase(); const searchToString = search.toLowerCase(); return dataToSearch.includes(searchToString); }); const searchPrice = searchName.filter((item) => { const [min, max] = minMax.split('-'); if (!min && !max) return item; const price = Number(item[priceFields[0]] ? item[priceFields[0]] : item[priceFields[1]]); if (min && !max) return price >= Number(min); if (!min && max) return price <= Number(max); return price >= Number(min) && price <= Number(max); }); setDataToReturn(searchPrice); }, [arr, minMax, search]); return dataToReturn; } export default useSearch;
<filename>docs/.vuepress/routes/2019.js<gh_stars>100-1000 const genSidebarConfig = require('./getSidebarConfig') module.exports = [ { title: '2019十二月(December)', collapsable: true, children: genSidebarConfig('english/2019/2019-December', false) }, { title: '2019十一月(November)', collapsable: true, children: genSidebarConfig('english/2019/2019-November', false) }, { title: '2019十月(October)', collapsable: true, children: genSidebarConfig('english/2019/2019-October', false) }, { title: '2019九月(September)', collapsable: true, children: genSidebarConfig('english/2019/2019-September', false) }, { title: '2019八月(August)', collapsable: true, children: genSidebarConfig('english/2019/2019-August', false) }, { title: '2019七月(July)', collapsable: true, children: genSidebarConfig('english/2019/2019-July', false) }, { title: '2019六月(June)', collapsable: true, children: genSidebarConfig('english/2019/2019-June', false) }, { title: '2019年五月(May)', collapsable: true, children: genSidebarConfig('english/2019/2019-May', false) }, { title: '2019年四月(April)', collapsable: true, children: genSidebarConfig('english/2019/2019-April', false) }, { title: '2019年三月(March)', collapsable: true, children: genSidebarConfig('english/2019/2019-March', false) }, { title: '2019年二月(February)', collapsable: true, children: genSidebarConfig('english/2019/2019-February', false) }, { title: '2019年一月(January)', collapsable: true, children: genSidebarConfig('english/2019/2019-January', false) }, ]
const cheerio = require('cheerio'); const fs = require('fs'); const path = require('path'); const glob = require('glob'); const cleanCSS = require('clean-css'); var appRoot = require('app-root-path'); var dummyFn = function (html) { return html; } module.exports = function (options) { if (!(options && options.coverageDir)) throw new Error('coverageDir param is required'); const defaultOpts = { coverageDir: './', pattern: '/**/*.html', fileEncoding: 'utf8', extraCss: '', minifyOptions: { }, preProcessFn: dummyFn, postProcessFn: dummyFn } let appRootPath = appRoot.path; let opts = Object.assign(defaultOpts, options); let root = path.resolve(appRootPath, opts.coverageDir); let globPattern = root + opts.pattern; // console.log(globPattern); glob(globPattern, (err, files) => { if (err) { throw new Error(err); } let fileCache = {}; if (opts.extraCss) { opts.extraCss = new cleanCSS(opts.minifyOptions).minify(opts.extraCss).styles; } files.forEach((file) => { fs.readFile(file, opts.fileEncoding, (fileErr, data) => { data = opts.preProcessFn(data); const $ = cheerio.load(data); $('link[rel="stylesheet"]').each(function (idx, elem) { let jElem = $(elem); let href = jElem.attr('href'); var resolvedHref = path.resolve(path.dirname(file), href); if (!fileCache[resolvedHref]) { let cssContent = fs.readFileSync(resolvedHref, opts.fileEncoding); fileCache[resolvedHref] = new cleanCSS(opts.minifyOptions).minify(cssContent).styles; } $('<style/>').html(fileCache[resolvedHref]).insertAfter(jElem); jElem.remove(); }); if (opts.extraCss) { var customCssObj = $('<style/>').html(opts.extraCss); $('head').append(customCssObj); } let processedHTML = opts.postProcessFn($.html()); fs.writeFile(file, processedHTML, () => { // console.log(file + ' written'); }); }); }); }); }
<filename>core/src/main/java/org/hisp/dhis/android/core/arch/repositories/filters/internal/PeriodFilterConnector.java /* * Copyright (c) 2004-2021, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.arch.repositories.filters.internal; import androidx.annotation.NonNull; import org.hisp.dhis.android.core.arch.repositories.collection.BaseRepository; import org.hisp.dhis.android.core.common.DateFilterPeriod; import org.hisp.dhis.android.core.common.DatePeriodType; import org.hisp.dhis.android.core.common.RelativePeriod; import org.hisp.dhis.android.core.period.DatePeriod; import org.hisp.dhis.android.core.period.Period; import java.util.Date; public final class PeriodFilterConnector<R extends BaseRepository> { private final ScopedRepositoryFilterFactory<R, DateFilterPeriod> repositoryFactory; PeriodFilterConnector(ScopedRepositoryFilterFactory<R, DateFilterPeriod> repositoryFactory) { this.repositoryFactory = repositoryFactory; } /** * Returns a new repository whose scope is the one of the current repository plus the new filter being applied. * The before filter checks if the given field has a date value which is before or equal to the one provided. * @param value value to compare with the target field * @return the new repository */ public R beforeOrEqual(Date value) { DateFilterPeriod filter = DateFilterPeriod.builder().endDate(value).type(DatePeriodType.ABSOLUTE).build(); return repositoryFactory.updated(filter); } /** * Returns a new repository whose scope is the one of the current repository plus the new filter being applied. * The after filter checks if the given field has a date value which is after or equal to the one provided. * @param value value to compare with the target field * @return the new repository */ public R afterOrEqual(Date value) { DateFilterPeriod filter = DateFilterPeriod.builder().startDate(value).type(DatePeriodType.ABSOLUTE).build(); return repositoryFactory.updated(filter); } /** * Returns a new repository whose scope is the one of the current repository plus the new filter being applied. * The inDatePeriod filter checks if the given field has a date value which is within the provided DatePeriod. * @param datePeriod date period to compare with the target field * @return the new repository */ public R inDatePeriod(@NonNull DatePeriod datePeriod) { return inPeriod(datePeriod.startDate(), datePeriod.endDate()); } /** * Returns a new repository whose scope is the one of the current repository plus the new filter being applied. * The inPeriod filter checks if the given field has a date value which is within the provided Period. * @param period period to compare with the target field * @return the new repository */ public R inPeriod(@NonNull Period period) { return inPeriod(period.startDate(), period.endDate()); } private R inPeriod(@NonNull Date startDate, @NonNull Date endDate) { DateFilterPeriod filter = DateFilterPeriod.builder() .startDate(startDate).endDate(endDate).type(DatePeriodType.ABSOLUTE).build(); return repositoryFactory.updated(filter); } /** * Returns a new repository whose scope is the one of the current repository plus the new filter being applied. * The inRelativePeriod filter checks if the given field has a date value which is within the provided * RelativePeriod. * @param relativePeriod relative period to compare with the target field * @return the new repository */ public R inPeriod(@NonNull RelativePeriod relativePeriod) { DateFilterPeriod filter = DateFilterPeriod.builder() .period(relativePeriod).type(DatePeriodType.RELATIVE).build(); return repositoryFactory.updated(filter); } }
const memUsage = handler.getMemoryUsage(); let output = ''; for (let key in memUsage) { output += `${key} ${Math.round(memUsage[key] / 1024 / 1024 * 100) / 100} MB\n`; } output += `Total Loaded Game Objects: ${objectManager.objectStore.getLoadedObjectCount()}\n`; user.send(output);
import React, {useState, useRef} from 'react'; const child = { padding: '25px', margin: '25px', border: '2px solid blue' }; const Counter = (prop) => { console.log("fuction called...."); let counter = useRef(0); let [myState, setMyState] = useState("A"); let updateState = () => { counter.current++; setMyState(myState + "-u-"); console.log("counter: "+ counter.current); } return ( <div style={child}> <div> <div>MyState : {myState}</div> <input type="button" onClick = {() => updateState()} value="Update State"></input> </div> </div> ); } export default Counter;
#!/bin/bash source ~/.bash_profile sed -i "s/mysql_url/${mysql_url}/g" application.conf sed -i "s/mysql_port/${mysql_port}/g" application.conf sed -i "s/redis_url/${redis_url}/g" application.conf sed -i "s/redis_port/${redis_port}/g" application.conf
package com.quantconnect.lean; /// Live server types available through the web IDE. / QC deployment. public enum ServerType { /// Additional server Server512, /// Upgraded server Server1024, /// Server with 2048 MB Ram. Server2048 }
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include "functions.h" #include "main-screen.h" #include "models/profile.h" int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); app.setApplicationName("Grabber"); app.setApplicationVersion(VERSION); app.setOrganizationName("Bionus"); app.setOrganizationDomain("bionus.fr.cr"); const QUrl url(QStringLiteral("qrc:/main-screen.qml")); QQmlApplicationEngine engine; QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) { if (!obj && url == objUrl) { QCoreApplication::exit(-1); } }, Qt::QueuedConnection); Profile profile(savePath()); MainScreen mainScreen(&profile); engine.rootContext()->setContextProperty("backend", &mainScreen); engine.load(url); return app.exec(); }
#!/bin/bash ############################################################################# # Engine tests ############################################################################# CURRUSER=`whoami` TESTPREFIX="" SLEEPCMD="" HAS_XSERVER="0" if [ "$CURRUSER" == "buildbot" ] || [ "$CURRUSER" == "abuild" ]; then if [[ "$OSTYPE" == "linux-gnu"* ]]; then if [ `which xvfb-run` == "" ]; then echo "xvfb-run not found in this system. Please install with: sudo apt-get install xvfb" exit fi TESTPREFIX="xvfb-run" HAS_XSERVER="1" # if we're running as build slave, set a sleep time to start/stop xvfb between tests SLEEPCMD="sleep 1" elif [[ "$OSTYPE" == "darwin"* ]]; then echo "We're on OSX. Any prefix needed ?" fi else if [[ "$OSTYPE" == "linux-gnu"* ]]; then XPID=`pidof X` if [ ! ${#XPID} -gt 0 ]; then XPID=`pidof Xorg` fi if [ ${#XPID} -gt 0 ]; then HAS_XSERVER="1" fi # no X server ? Let's look for xvfb. This is how Travis is setup if [ -n "$TRAVIS" ]; then HAS_XSERVER="1" fi fi fi TESTDIR=engine/test TESTS=`find ${TESTDIR} -maxdepth 1 -mindepth 1 -type d` for test in ${TESTS} do # Ignore .git if [ `echo ${test} | grep ".git"` ]; then continue fi # Isolate just the test name test=`echo ${test} | sed 's/engine\/test\///'` $SLEEPCMD # Execute the test pushd . cd ${TESTDIR}/${test} $TESTPREFIX ./test.sh RESULT=${?} popd if [ ${RESULT} != 0 ]; then echo "${RESULT} Engine unit tests failed. Please fix before commit." exit ${RESULT} fi done ############################################################################# # UI tests ############################################################################# if [ "$HAS_XSERVER" -eq "1" ]; then TESTDIR=ui/test TESTS=`find ${TESTDIR} -maxdepth 1 -mindepth 1 -type d` for test in ${TESTS} do # Ignore .git if [ `echo ${test} | grep ".git"` ]; then continue fi # Isolate just the test name test=`echo ${test} | sed 's/ui\/test\///'` $SLEEPCMD # Execute the test pushd . cd ${TESTDIR}/${test} DYLD_FALLBACK_LIBRARY_PATH=$DYLD_FALLBACK_LIBRARY_PATH:../../../engine/src:../../src \ LD_LIBRARY_PATH=$LD_LIBRARY_PATH:../../../engine/src:../../src $TESTPREFIX ./${test}_test RESULT=${?} popd if [ ${RESULT} != 0 ]; then echo "${RESULT} UI unit tests failed. Please fix before commit." exit ${RESULT} fi done fi ############################################################################# # Enttec wing tests ############################################################################# $SLEEPCMD pushd . cd plugins/enttecwing/test $TESTPREFIX ./test.sh RESULT=$? if [ $RESULT != 0 ]; then echo "${RESULT} Enttec wing unit tests failed. Please fix before commit." exit $RESULT fi popd ############################################################################# # Velleman test ############################################################################# if [[ "$OSTYPE" == "darwin"* ]]; then echo "Skip Velleman test (not supported on OSX)" else $SLEEPCMD pushd . cd plugins/velleman/test $TESTPREFIX ./test.sh RESULT=$? if [ $RESULT != 0 ]; then echo "Velleman unit test failed ($RESULT). Please fix before commit." exit $RESULT fi popd fi ############################################################################# # MIDI tests ############################################################################# #pushd . #cd plugins/midi/common/test #DYLD_FALLBACK_LIBRARY_PATH=$DYLD_FALLBACK_LIBRARY_PATH:../src \ # LD_LIBRARY_PATH=$LD_LIBRARY_PATH:../src ./common_test #RESULT=$? #if [ $RESULT != 0 ]; then # echo "MIDI Input common unit test failed ($RESULT). Please fix before commit." # exit $RESULT #fi #popd ############################################################################# # ArtNet tests ############################################################################# $SLEEPCMD pushd . cd plugins/artnet/test $TESTPREFIX ./test.sh RESULT=$? if [ $RESULT != 0 ]; then echo "${RESULT} ArtNet unit tests failed. Please fix before commit." exit $RESULT fi popd ############################################################################# # Final judgment ############################################################################# echo "Unit tests passed."
#Calculate the sum of all elements in a given dataframe df$sum <- rowSums(df) #Print the results print(df$sum)
<reponame>DNAbro/Java-Game-Project-3<filename>src/models/Item/Armors/HeadArmor.java package models.Item.Armors; import models.Entity.Entity; import models.Inventory.Inventory; import models.Equipment.Equipment; import utilities.Location.Location; import views.Assets; import java.awt.image.BufferedImage; /** * Implemented by <NAME> */ public class HeadArmor extends Armor{ /*Constructors*/ public HeadArmor(){ super(Assets.headArmor,1,"Head Armor",2,1); } public HeadArmor(int id, String name, double rating){ super(Assets.headArmor, id, name ,rating); } public HeadArmor(int id, String name, double rating , int requiredLevel){ super(Assets.headArmor, id, name ,rating , requiredLevel); } /* Methods */ public void equip(Entity entity, Equipment equipment , Inventory inventory) { /* if(equipment.hasHead()){ equipment.getHead().unequip(equipment , inventory); //NOT OOP. Should probably do this within models.Equipment State } */ equipment.addHead(this); inventory.removeItem(id); this.applyRating(entity); } public void unequip(Entity entity, Equipment equipment, Inventory inventory) { inventory.addItem(this); equipment.removeHead(); this.unapplyRating(entity); } }
package fwcd.fructose.ml.math; import java.io.Serializable; import java.util.Arrays; import java.util.Iterator; import java.util.concurrent.ThreadLocalRandom; import fwcd.fructose.ArrayIterator; import fwcd.fructose.exception.SizeMismatchException; import fwcd.fructose.function.FloatSupplier; import fwcd.fructose.function.FloatUnaryOperator; import fwcd.fructose.geometry.Vector2D; /** * A mutable float matrix specifically designed * for neural networks with performance in mind. * * @author Fredrik * */ public class NNMatrix implements Iterable<float[]>, Serializable { private static final long serialVersionUID = -6602539081610190469L; private final float[][] data; public NNMatrix(int width, int height) { data = new float[height][width]; } public NNMatrix(float[][] data) { this.data = data; } public void fill(FloatSupplier generator) { for (int y=0; y<height(); y++) { for (int x=0; x<width(); x++) { data[y][x] = generator.getAsFloat(); } } } public NNMatrix transpose() { int width = width(); int height = height(); NNMatrix result = new NNMatrix(height, width); for (int y=0; y<result.height(); y++) { for (int x=0; x<result.width(); x++) { result.data[y][x] = data[x][y]; } } return result; } public NNVector hadamardProduct(NNVector other) { if (width() != 1 || height() != other.size()) { throw new SizeMismatchException("matrix size", getSize(), "vector size", other.size()); } NNVector result = new NNVector(other.size()); for (int i=0; i<result.size(); i++) { result.set(i, data[i][0] * other.get(i)); } return result; } public NNMatrix hadamardProduct(NNMatrix other) { int width = width(); int height = height(); if (width != other.width() || height != other.height()) { throw new SizeMismatchException("first matrix size", getSize(), "second matrix size", other.getSize()); } NNMatrix result = new NNMatrix(width, height); for (int x=0; x<width; x++) { for (int y=0; y<height; y++) { result.data[y][x] = data[y][x] * other.data[y][x]; } } return result; } public void fillRandomly() { ThreadLocalRandom rand = ThreadLocalRandom.current(); for (int y=0; y<height(); y++) { for (int x=0; x<width(); x++) { data[y][x] = rand.nextFloat(); } } } public int width() { return data[0].length; } public int height() { return data.length; } public void addAllInPlace(Iterable<NNMatrix> deltas) { for (NNMatrix delta : deltas) { addInPlace(delta); } } public void addInPlace(NNMatrix delta) { if (delta.width() != width() || delta.height() != height()) { throw new SizeMismatchException("delta matrix size", delta.getSize(), "matrix size", getSize()); } for (int y=0; y<height(); y++) { for (int x=0; x<width(); x++) { data[y][x] += delta.data[y][x]; } } } public void mapInPlace(FloatUnaryOperator func) { for (int y=0; y<height(); y++) { for (int x=0; x<width(); x++) { data[y][x] = func.applyAsFloat(data[y][x]); } } } public NNMatrix multiply(float scalar) { int width = width(); int height = height(); NNMatrix result = new NNMatrix(width, height); for (int y=0; y<height; y++) { for (int x=0; x<width; x++) { result.data[y][x] = data[y][x] * scalar; } } return result; } public NNVector multiply(NNVector vec) { if (vec.size() != width()) { throw new SizeMismatchException("vector size", vec.size(), "matrix width", width()); } NNVector result = new NNVector(height()); for (int y=0; y<height(); y++) { for (int x=0; x<width(); x++) { result.addInPlace(y, data[y][x] * vec.get(x)); } } return result; } public NNMatrix multiply(NNMatrix right) { int width = width(); if (right.height() != width) { throw new SizeMismatchException("left matrix width", width, "right matrix height", right.height()); } NNMatrix result = new NNMatrix(right.width(), height()); for (int y=0; y<result.height(); y++) { for (int x=0; x<result.width(); x++) { float dot = 0; for (int i=0; i<width; i++) { dot += get(i, y) * right.get(x, i); } result.set(x, y, dot); } } return result; } public void addInPlace(int x, int y, float value) { data[y][x] += value; } public Vector2D getSize() { return new Vector2D(width(), height()); } public NNVector asVector() { if (width() == 1) { int height = height(); NNVector result = new NNVector(height); for (int i=0; i<height; i++) { result.set(i, data[i][0]); } return result; } else { throw new SizeMismatchException("matrix width", width(), "required vector width", 1); } } public void set(int x, int y, float value) { data[y][x] = value; } public float get(int x, int y) { return data[y][x]; } public float[] getRow(int y) { float[] row = data[y]; return Arrays.copyOf(row, row.length); } public float[] getCol(int x) { float[] col = new float[height()]; for (int y=0; y<height(); y++) { col[y] = data[y][x]; } return col; } @Override public Iterator<float[]> iterator() { return new ArrayIterator<>(data); } @Override public String toString() { StringBuilder b = new StringBuilder(); for (int y=0; y<height(); y++) { b.append(Arrays.toString(data[y])); b.append("\n"); } return b.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.deepHashCode(data); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } NNMatrix other = (NNMatrix) obj; if (!Arrays.deepEquals(data, other.data)) { return false; } return true; } }
<reponame>Igfernandes/modaousada function hoverImg(z, l){ val = z.childNodes; if(l == 'off'){ y = z.childElementCount x = 2; wait = setInterval(() =>{ if(x <= y){ if(x > 1){ val[x - 1].classList.remove('on') val[x - 1].classList.add('off') val[x].classList.remove('off') val[x].classList.add('on') }else{ val[x].classList.add('on') } x++ }else{ clearInterval(wait); } }, 2500); } else{ val[1].classList.add('on') for(x = 2; x <= z.childElementCount; x++ ){ val[x].classList.remove('on') val[x].classList.add('off') } } }
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by <NAME>, <EMAIL>, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program 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, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Fasttree(Package): """FastTree infers approximately-maximum-likelihood phylogenetic trees from alignments of nucleotide or protein sequences. FastTree can handle alignments with up to a million of sequences in a reasonable amount of time and memory.""" homepage = "http://www.microbesonline.org/fasttree" url = "http://www.microbesonline.org/fasttree/FastTree-2.1.10.c" version('2.1.10', '1c2c6425a638ec0c61ef064cda687987', expand=False, url='http://www.microbesonline.org/fasttree/FastTree-2.1.10.c') phases = ['build', 'install'] def build(self, spec, prefix): cc = Executable(spack_cc) cc('-O3', self.compiler.openmp_flag, '-DOPENMP', '-finline-functions', '-funroll-loops', '-Wall', '-oFastTreeMP', 'FastTree-' + format(spec.version.dotted) + '.c', '-lm') def install(self, spec, prefix): mkdir(prefix.bin) install('FastTreeMP', prefix.bin)
// Exercício 09 - Crie um programa por meio do qual o usuário irá digitar a operação desejada e // dois valores, ao final deverá ser exibido o resultado da operação. // Opções disponíveis: 1 – Divisão; 2 – resto da divisão; 3 – adição; 4 – multiplicação. #include <stdio.h> int main(void) { int escolha; int n1, n2, resultado; do { printf("Escolha a operação desejada: \n[ 1 ] - Divisão \n[ 2 ] - Resto da Divisão \n[ 3 ] - Adição \n[ 4 ] - Multiplicação \n"); scanf("%d", &escolha); } while (escolha > 5 || escolha < 0); printf("Digite o 1° número: "); scanf("%d", &n1); printf("Digite o 2° número: "); scanf("%d", &n2); switch (escolha) { case 1 : resultado = n1 / n2; break; case 2 : resultado = n1 % n2; break; case 3 : resultado = n1 + n2; break; case 4 : resultado = n1 * n2; break; } printf("Resultado = %d \n", resultado); return 0; }
#!/bin/sh echo [$(date)] "Download success." echo "Group Id: $1" echo "File Num: $2" echo "File Path: $3"
<filename>src/views/systemManagement/role/api copy.js import request from '@/utils/request' const BASE_API_7 = process.env.VUE_APP_BASE_API_7 //shuiku //查看图片接口 export function getReservoirImage(params) { return request({ url: '/web/point/getReservoirImage', baseURL: BASE_API_7, method: 'GET', params: params }) } //水库基本信息列表 export function getReservoirListByPage(params) { return request({ url: '/web/rsvr/getReservoirListByPage', baseURL: BASE_API_7, method: 'GET', params: params }) } //添加水库 export function addReservoirBaseInfo(params) { return request({ url: '/web/rsvr/addReservoirBaseInfo', baseURL: BASE_API_7, method: 'POST', data: params }) } //修改水库基本信息 export function updateReservoirBaseInfo(params) { return request({ url: '/web/rsvr/updateReservoirBaseInfo', baseURL: BASE_API_7, method: 'POST', data: params }) } //水库详情 export function getBaseInfoById(params) { return request({ url: '/web/rsvr/getBaseInfoById', baseURL: BASE_API_7, method: 'GET', params: params }) } //userPatrolTJ export function userPatrolTJ(params) { return request({ url: '/map/userPatrolTJ', baseURL: BASE_API_7, method: 'post', data: params }) } //根据水库编码查询库容曲线 export function getCapacityCurveByReservoirCode(params) { return request({ url: '/web/rsvr/getCapacityCurveByReservoirCode', baseURL: BASE_API_7, method: 'GET', params: params }) } //新增水库管理人员 export function addReservoirInscptor(params) { return request({ url: '/web/inscptor/addReservoirInscptor', baseURL: BASE_API_7, method: 'POST', data: params }) } //修改水库人员 export function updateUserDetailInfo(params) { return request({ url: '/web/inscptor/updateUserDetailInfo', baseURL: BASE_API_7, method: 'POST', data: params }) } //根据水库人员ID查询用户详细信息 export function getUserDetailInfoById(params) { return request({ url: '/web/inscptor/getUserDetailInfoById', baseURL: BASE_API_7, method: 'GET', params: params }) } //配置水库人员 export function configReservoirInscptor(params) { return request({ url: '/web/inscptor/configReservoirInscptor', baseURL: BASE_API_7, method: 'GET', params: params }) } //根据人员ID删除人员与水库关系 export function deleteByInscptorId(params) { return request({ url: '/web/inscptor/deleteByInscptorId', baseURL: BASE_API_7, method: 'GET', params: params }) } //根据水库ID数组和角色ID数组查询人员列表 export function getInscptorByReservoirIdAndRoleId(params) { return request({ url: '/web/inscptor/getInscptorByReservoirIdAndRoleId', baseURL: BASE_API_7, method: 'POST', data: params }) } //分页查询水库人员列表 export function getReservoirInspctorByPage(params) { return request({ url: '/web/inscptor/getReservoirInspctorByPage', baseURL: BASE_API_7, method: 'GET', params: params }) } //查询所有点位列表 export function getAllPointLocationList(params) { return request({ url: '/web/point/getAllPointLocationList', baseURL: BASE_API_7, method: 'GET', params: params }) } //查询可配置项 export function getReservoirNotExistPointByReservoirId(params) { return request({ url: '/web/point/getReservoirNotExistPointByReservoirId', baseURL: BASE_API_7, method: 'GET', params: params }) } //根据已配置项 export function getReservoirPointByReservoirId(params) { return request({ url: '/web/point/getReservoirPointByReservoirId', baseURL: BASE_API_7, method: 'GET', params: params }) } //移除水库点位 export function removeAllotPointBatch(params) { return request({ url: '/web/point/removeAllotPointBatch', baseURL: BASE_API_7, method: 'GET', params: params }) } //添加水库点位 export function reservoirAllotPoint(params) { return request({ url: '/web/point/reservoirAllotPoint', baseURL: BASE_API_7, method: 'GET', params: params }) } //批量删除水库 export function deleteBatchReservoirInscptor(params) { return request({ url: '/web/inscptor/deleteBatchReservoirInscptor', baseURL: BASE_API_7, method: 'GET', params: params }) } //根据点位ID查询点位信息 export function getPointLocationById(params) { return request({ url: '/web/point/getPointLocationById', baseURL: BASE_API_7, method: 'GET', params: params }) } //分页查询水库点位信息列表 export function getPointLocationListByPage(params) { return request({ url: '/web/point/getPointLocationListByPage', baseURL: BASE_API_7, method: 'GET', params: params }) } //根据角色ID和用户ID分页查询水库人员列表明细 export function findByInscptorPage(params) { return request({ url: '/web/inscptor/findByInscptorPage', baseURL: BASE_API_7, method: 'GET', params: params }) } //根据用户ID和角色ID批量删除水库关系人 export function deleteTotalBetch(params) { return request({ url: '/web/inscptor/deleteTotalBetch', baseURL: BASE_API_7, method: 'GET', params: params }) } //添加点位 export function addPointLocation(params) { return request({ url: '/web/point/addPointLocation', baseURL: BASE_API_7, method: 'POST', data: params }) } //修改点位 export function updatePointLocation(params) { return request({ url: '/web/point/updatePointLocation', baseURL: BASE_API_7, method: 'POST', data: params }) } //删除点位信息 export function deletePointLocationById(params) { return request({ url: '/web/point/deletePointLocationById', baseURL: BASE_API_7, method: 'GET', params: params }) } //获得所有用户 export function getAllUserList(params) { return request({ url: '/user/getAllUserList', baseURL: BASE_API_7, method: 'GET', params: params }) } //获得所有角色 // export function getAllRoles(params) { // return request({ // url: "/role/getAllRoles", // baseURL: BASE_API_7, // method: "GET", // params: params // }); // } //获得所有角色role/getAllRoles export function getAllRoles(params) { return request({ url: '/sys/getAllRoles', baseURL: BASE_API_7, method: 'GET', params: params }) } //获得当前用户的所有角色 export function getCurrentUserAllRoles(params) { return request({ url: '/sys/getRolesFromUsers ', baseURL: BASE_API_7, method: 'GET', params: params }) } //导入excel水库李彪接口 export function imporData(params) { return request({ url: '/web/rsvr/imporData', baseURL: BASE_API_7, method: 'GET', params: params }) } //下载链接 export function model(params) { return request({ url: '/web/rsvr/downloadTemplate', baseURL: BASE_API_7, method: 'GET', params: params }) } //用户列表+角色类型 export function getUserRoleByUserId(params) { return request({ url: '/web/inscptor/getUserRoleByUserId', baseURL: BASE_API_7, method: 'GET', params: params }) } // 月报自定义下载 /download/skPatrolRecordFile4ZipByMonth export function skPatrolRecordFile4ZipByMonth(params) { return request({ url: '/download/skPatrolRecordFile4ZipByMonth', baseURL: BASE_API_7, method: 'POST', data: params }) }
<reponame>darshanpatil/SampleSpringBootApp package com.demoapp; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoSpringBootAppApplication { private static final Logger LOGGER = LogManager.getLogger(DemoSpringBootAppApplication.class); public static void main(String[] args) { LOGGER.debug("Debug level"); LOGGER.error("Error level"); LOGGER.info("Info level"); LOGGER.warn("Warn level"); LOGGER.trace("Trace level"); System.out.println("isDebugEnabled: " + LOGGER.isDebugEnabled()); System.out.println("isErrorEnabled: " + LOGGER.isErrorEnabled()); System.out.println("isWarnEnabled: " + LOGGER.isWarnEnabled()); System.out.println("isInfoEnabled: " + LOGGER.isInfoEnabled()); System.out.println("isTraceEnabled: " + LOGGER.isTraceEnabled()); SpringApplication.run(DemoSpringBootAppApplication.class, args); } }
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm"; import { ItemPedido } from "src/item-pedido/itemPedido.entity"; @Entity() export class Produto{ @PrimaryGeneratedColumn() id: number; @Column({type: "varchar" }) nome: String; @Column({type: "varchar" }) descrição: String; @Column({name: 'preço', type: "money" }) preco: number; @Column({type: "int" }) estoque: number @Column({name: 'data-de-validade', type: "date" }) dataValidade: Date; @Column({name: 'unidade-de-medida', type: "varchar" }) unidadeMedida: String; @OneToMany(() => ItemPedido, item => item.produto_id) itensPedidos: ItemPedido[]; }
#!/bin/bash set -ex LOCAL_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) ROOT_DIR=$(dirname "$LOCAL_DIR") # Run build script from scripts if applicable if [[ "${BUILD_ENVIRONMENT}" == *android ]]; then export ANDROID_NDK=/opt/ndk ./scripts/build_android.sh "$@" exit 0 fi # Run cmake from ./build directory mkdir -p build cd build CMAKE_ARGS=("-DCMAKE_INSTALL_PREFIX=/usr/local/caffe2") case "${BUILD_ENVIRONMENT}" in *-mkl) CMAKE_ARGS+=("-DBLAS=MKL") ;; *-cuda*) CMAKE_ARGS+=("-DUSE_CUDA=ON") CMAKE_ARGS+=("-DCUDA_ARCH_NAME=Maxwell") CMAKE_ARGS+=("-DUSE_NNPACK=OFF") # Explicitly set path to NVCC such that the symlink to ccache is used CMAKE_ARGS+=("-DCUDA_NVCC_EXECUTABLE=/usr/local/bin/nvcc") # The CMake code that finds the CUDA distribution looks for nvcc in $PATH. # This doesn't work here, as that would yield /usr/local/bin, which doesn't # contain a CUDA distribution. We need it to resolve to /usr/local/cuda/bin, # so we add it to $PATH here. We can make CMake still use ccache by # specifying CUDA_NVCC_EXECUTABLE above. export PATH=/usr/local/cuda/bin:$PATH ;; esac # Configure cmake .. ${CMAKE_ARGS[*]} "$@" # Build if [ "$(uname)" == "Linux" ]; then make "-j$(nproc)" install else echo "Don't know how to build on $(uname)" exit 1 fi
<filename>spacegraphcats/catlas/test_components.py #! /usr/bin/env python3 import unittest from .graph import Graph from .components import components, num_components class ComponentsTest(unittest.TestCase): def test_components(self): g = Graph(num_nodes=12) g.add_arc(1, 2) g.add_arc(3, 4) g.add_arc(5, 6).add_arc(6, 7).add_arc(7, 5) g.add_arc(8, 9).add_arc(8, 10).add_arc(8, 11) self.assertEqual(num_components(g), 5) comps = components(g) self.assertEqual(len(comps), 5) union = set() for c in comps: union |= set(c) self.assertEqual(len(union), len(g)) if __name__ == '__main__': unittest.main()
const express = require('express') const _ = require('lodash') const bodyParser = require('../../services/body-parser') const helper = require('../../helper') //const log = require('hw-logger').log module.exports = (config, store) => { const router = express.Router() router.post('/', helper.checkAuth(config, true), bodyParser, (req, res, next) => { store.saveQuiz(req.body && Object.assign( helper.clone(req.body), { created: new Date(), } ) ) .then(data => { res.status(201).renderData(data) }) .catch(next) }) router.get('/', (req, res, next) => { store.getQuizzes() .then(data => { res.renderData(data) }) .catch(next) }) router.get('/:id', (req, res, next) => { const authorized = helper.checkAuth(config)(req, res) store.getQuiz(req.params.id) .then(data => { if (!authorized) { data.questions.forEach(question => { question.choices = question.choices.map(choice => _.omit(choice, 'score')) }) } res.renderData(data) }) .catch(next) }) return router }
var assert = require('assert'); var helpers = require('we-test-tools').helpers; var path = require('path'); var utils, we; describe('lib/utils', function () { before(function (done) { utils = require('../../../src/utils'); we = helpers.getWe(); done(); }); describe('listFilesRecursive', function() { it('should list files in we-plugin-post dir', function (done) { var folder = path.resolve(process.cwd(), 'node_modules', 'we-plugin-post'); utils.listFilesRecursive(folder, function(err, files){ if (err) return done(err); assert.equal(files.length, 12); assert(files.indexOf(folder+'/package.json') > -1); assert(files.indexOf(folder+'/plugin.js') > -1); assert(files.indexOf(folder+'/server/controllers/post.js') > -1); assert(files.indexOf(folder+'/server/models/hero.json') > -1); assert(files.indexOf(folder+'/server/models/post.js') > -1); assert(files.indexOf(folder+'/server/models/user.js') > -1); done(); }); }); it('should return a empty list if the dir not is found', function (done) { var folder = path.resolve(process.cwd(), 'asadasdas'); utils.listFilesRecursive(folder, function(err, files){ if (err) return done(err); assert.equal(files.length, 0); done(); }); }); it('should a empty list if the dir is one file', function (done) { var folder = path.resolve(process.cwd(), 'plugin.js'); utils.listFilesRecursive(folder, function(err, files) { assert(!files); assert.equal(err.code, 'ENOTDIR'); done(); }); }); }); describe('isNNAssoc', function() { it ('should return true if are a belongsTo assoc', function(done) { assert(utils.isNNAssoc({ associationType: 'belongsTo' })); done(); }); it ('should return false if are a hasMany assoc', function(done) { assert(!utils.isNNAssoc({ associationType: 'hasMany' })); done(); }); }); describe('getRedirectUrl', function() { it ('should return a valid url from body', function(done) { var req = { we: we, body: { redirectTo: '/test' } }; var url = utils.getRedirectUrl(req); assert.equal(url, '/test'); done(); }); it ('should return null to invalid url from body', function(done) { var req = { we: we, body: { redirectTo: 'http://google.com' } }; var url = utils.getRedirectUrl(req); assert.equal(url, null); done(); }); it ('should return url from service', function(done) { we.config.services.dance = { url: '/dancee' }; var req = { we: we, query: { service: 'dance' } }; var url = utils.getRedirectUrl(req); assert.equal(url, '/dancee'); delete we.config.services.dance; done(); }); it ('should return url from query.redirectTo', function(done) { var req = { we: we, query: { redirectTo: '/iooo' } }; var url = utils.getRedirectUrl(req); assert.equal(url, '/iooo'); done(); }); }); describe('parseAttributes', function(){ it ('should return false if are a hasMany assoc', function (done) { var str = utils.helper.parseAttributes({ hash: { class: 'btn btn-default' } }); assert(str.indexOf('class="btn btn-default"') > -1); done(); }); }) });
import React, { PureComponent } from 'react'; const Greeter = () => { return ( <h1> Hello World!</h1> ); } export default Greeter ;
<gh_stars>0 package personalfinance.gui.panel; import personalfinance.gui.MainButton; import personalfinance.gui.MainFrame; import personalfinance.settings.HandlerCode; import personalfinance.settings.Text; public final class StatisticsTypePanel extends AbstractPanel { private final String title; public StatisticsTypePanel(MainFrame frame, String title) { super(frame); this.title = Text.get(title); init(); } @Override protected void init() { MainButton type = new MainButton(title, null, HandlerCode.TYPE); add(type); } }
#! /bin/bash scp -P 2022 farm:charcoal/output.ibd2/just_taxonomy.combined_summary.csv . scp -P 2022 farm:charcoal/output.ibd2/SRS104400_110.fna.gz.report.txt .
<filename>thread/src/main/java/com/java/study/chapter14/ConditionBoundBuffer.java<gh_stars>1-10 package com.java.study.chapter14; import org.apache.http.annotation.GuardedBy; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ConditionBoundBuffer<T> { protected final Lock lock = new ReentrantLock(); private final Condition notFull = lock.newCondition(); @GuardedBy("lock") private final Condition notEmpty = lock.newCondition(); @GuardedBy("lock") private final T[] items = (T[]) new Object[10]; @GuardedBy("lock") private int tail, head, count; public void put(T x) throws InterruptedException { lock.lock(); try { while (count == items.length) { System.out.println(Thread.currentThread().getName() + "开始等待"); notFull.await(); } items[tail] = x; if (++tail == items.length) { tail = 0; } ++count; notEmpty.signal(); } finally { lock.unlock(); } } public T take() throws InterruptedException { lock.lock(); try { while (count == 0) { System.out.println(Thread.currentThread().getName() + "开始等待"); notEmpty.await(); } T x = items[head]; items[head] = null; if (++head == items.length) { head = 0; } --count; notFull.signal(); return x; } finally { lock.unlock(); } } }
<gh_stars>1-10 /* * */ package net.community.chest.jfree.jfreechart.plot.category; import java.util.List; import net.community.chest.convert.ValueStringInstantiator; import net.community.chest.dom.DOMUtils; import net.community.chest.jfree.jfreechart.chart.renderer.BaseGeneratorConverter; import net.community.chest.lang.StringUtil; import org.jfree.chart.urls.StandardCategoryURLGenerator; import org.w3c.dom.Element; /** * <P>Copyright GPLv2</P> * * @author <NAME>. * @since Jun 8, 2009 12:53:04 PM */ public class StandardCategoryURLGeneratorConverter extends BaseGeneratorConverter<StandardCategoryURLGenerator> implements ValueStringInstantiator<StandardCategoryURLGenerator> { public StandardCategoryURLGeneratorConverter () { super(StandardCategoryURLGenerator.class); } /* * @see net.community.chest.dom.transform.XmlValueInstantiator#fromXml(org.w3c.dom.Element) */ @Override public StandardCategoryURLGenerator fromXml (Element elem) throws Exception { final String prfx=elem.getAttribute("prefix"), sn=elem.getAttribute("series"), cn=elem.getAttribute("category"); if ((null == prfx) || (prfx.length() <= 0)) { if (((sn != null) && (sn.length() > 0)) || ((cn != null) && (cn.length() > 0))) throw new IllegalArgumentException("fromXml(" + DOMUtils.toString(elem) + ") superfluous arguments"); return new StandardCategoryURLGenerator(); } if (((sn == null) || (sn.length() <= 0)) && ((cn == null) ||(cn.length() <= 0))) return new StandardCategoryURLGenerator(prfx); if ((sn != null) && (sn.length() > 0) && (cn != null) && (cn.length() > 0)) return new StandardCategoryURLGenerator(prfx, sn, cn); throw new IllegalStateException("fromXml(" + DOMUtils.toString(elem) + ") missing data"); } /* * @see net.community.chest.convert.ValueStringInstantiator#convertInstance(java.lang.Object) */ @Override public String convertInstance (StandardCategoryURLGenerator inst) throws Exception { throw new UnsupportedOperationException("convertInstance(" + inst + ") N/A"); } public static final StandardCategoryURLGenerator fromString (final String s) throws IllegalArgumentException { final List<String> args=StringUtil.splitString(s, ','); final int numArgs=(null == args) ? 0 : Math.max(0, args.size()); switch(numArgs) { case 0 : return new StandardCategoryURLGenerator(); case 1 : return new StandardCategoryURLGenerator(args.get(0)); case 3 : return new StandardCategoryURLGenerator(args.get(0), args.get(1), args.get(2)); default : throw new IllegalArgumentException("fromString(" + s + ") unexpected number of arguments"); } } /* * @see net.community.chest.convert.ValueStringInstantiator#newInstance(java.lang.String) */ @Override public StandardCategoryURLGenerator newInstance (String s) throws Exception { return fromString(StringUtil.getCleanStringValue(s)); } public static final StandardCategoryURLGeneratorConverter DEFAULT=new StandardCategoryURLGeneratorConverter(); }
package com.lsngo.myapplication.ui.activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import com.lsngo.myapplication.ui.adapter.mPagerAdapter; import com.lsngo.myapplication.R; /** * Created by Administrator on 2017/3/29. */ public class GuideActivity extends AppCompatActivity { private ViewPager viewPager; private int[] pics; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.guide_activity); viewPager = (ViewPager) findViewById(R.id.guide_activity_vp); initData(); mPagerAdapter mPagerAdapter = new mPagerAdapter(this,pics); viewPager.setAdapter(mPagerAdapter); viewPager.setOnPageChangeListener(mPagerListener); } private void initData() { pics = new int[]{ R.drawable.guide32, R.drawable.guide33, R.drawable.guide34 }; } Handler handler = new Handler(); private ViewPager.OnPageChangeListener mPagerListener = new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(final int position) { handler.postDelayed(new Runnable() { @Override public void run() { if (position == viewPager.getAdapter().getCount() - 1) // Toast.makeText(GuideActivity.this, "last image", Toast.LENGTH_SHORT).show(); finish(); startActivity(new Intent(GuideActivity.this, MainActivity.class)); } }, 2000); } @Override public void onPageScrollStateChanged(int state) { } }; }
package com.rahul.uberapi.android.demo; import android.app.Activity; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Bundle; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.HashMap; public class Constants { private static HashMap<String, String> authParameters = new HashMap<String, String>(); public static final String AUTHORIZE_URL = "https://login.uber.com/oauth/authorize"; public static final String BASE_URL = "https://login.uber.com/"; public static final String SCOPES = "profile history_lite history"; public static final String BASE_UBER_URL_V1 = "https://api.uber.com/v1/"; public static final String BASE_UBER_URL_V1_1 = "https://api.uber.com/v1.1/"; public static final double START_LATITUDE = 37.781955; public static final double START_LONGITUDE = -122.402367; public static final double END_LATITUDE = 37.744352; public static final double END_LONGITUDE = -122.416743; public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); public static String getUberClientId(Activity activity) { return getManifestData(activity, "com.rahul.uberapi.android.demo.UBER_CLIENT_ID"); } public static String getUberClientSecret(Activity activity) { return getManifestData(activity, "com.rahul.uberapi.android.demo.UBER_CLIENT_SECRET"); } public static String getUberRedirectUrl(Activity activity) { return getManifestData(activity, "com.rahul.uberapi.android.demo.UBER_REDIRECT_URL"); } public static String getManifestData(Activity activity, String name) { String data = authParameters.get(name); if (data != null) { return data; } try { ApplicationInfo ai = activity.getPackageManager().getApplicationInfo(activity.getPackageName(), PackageManager.GET_META_DATA); Bundle bundle = ai.metaData; data = bundle.getString(name); authParameters.put(name, data); } catch (Exception e) { e.printStackTrace(); } return data; } }
class MyClass: def __init__(self, name, age): self.name = name self.age = age def test_repr(self): return f'MyClass("{self.name}", {self.age})' # Example usage obj = MyClass("Alice", 25) print(obj.test_repr()) # Output: 'MyClass("Alice", 25)'
<gh_stars>1-10 'use strict'; const client = require('../client'); // CARD WITH WISHLIST TAG CALL FROM DATABASE function getCardWishlist(request, response) { let sql = `SELECT * FROM cardtable WHERE tag = 'wish-list' ORDER BY id DESC;`; client.query(sql) .then(results => { response.render('pages/wish-list', { wishlistArray: results.rows }); }) .catch(error => { console.log(`card wish-list error: ${error}`); response.render('pages/error', { error: error }); }); } module.exports = getCardWishlist;
package com.lepao.ydcgkf.mvp.presenter; import android.util.Log; import com.lepao.ydcgkf.api.ApiService; import com.lepao.ydcgkf.base.BasePresenter; import com.lepao.ydcgkf.mvp.model.CommonModel; import com.lepao.ydcgkf.mvp.model.FingerModel; import com.lepao.ydcgkf.mvp.view.FingerView; import java.util.Map; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import okhttp3.RequestBody; /** * created by zwj on 2018/9/10 0010 */ public class FingerPresenter extends BasePresenter<FingerView> { public void matchFP(RequestBody body) { Disposable disposable = ApiService.getFingerApi().matchFinger(body) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<FingerModel>() { @Override public void accept(FingerModel bean) throws Exception { baseview.matchFpResult(bean); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { baseview.requestError(throwable.getMessage()); } }); addSubscription(disposable); } public void getFingerInfo(Map<String,String> map) { Disposable disposable = ApiService.getFingerApi().getFingerInfo(map) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<CommonModel>() { @Override public void accept(CommonModel bean) throws Exception { baseview.fingerInfoResult(bean); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { baseview.requestError(throwable.getMessage()); } }); addSubscription(disposable); } public void saveFPByCardNO(Map<String,String> map) { Disposable disposable = ApiService.getFingerApi().saveFPByCardNO(map) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<CommonModel>() { @Override public void accept(CommonModel bean) throws Exception { baseview.fingerInfoResult(bean); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { baseview.requestError(throwable.getMessage()); } }); addSubscription(disposable); } public void entence(String sid,String code) { Disposable disposable = ApiService.getFingerApi().postScanResult(sid,code) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<CommonModel>() { @Override public void accept(CommonModel bean) throws Exception { baseview.entranceResult(bean); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { baseview.requestError(throwable.getMessage() +" "); } }); addSubscription(disposable); } public void walkedOut(String sid,String code) { Disposable disposable = ApiService.getFingerApi().postWalkedOut(sid,code) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<CommonModel>() { @Override public void accept(CommonModel bean) throws Exception { baseview.walkedOutResult(bean); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { baseview.requestError(throwable.getMessage() +" "); } }); addSubscription(disposable); } }
#!/bin/bash SCRIPTDIR=$(dirname $(readlink -f "$0")) export FLUENTDCONFIGDIR="$SCRIPTDIR/realtimeapp_fluentd/config" export LOGDIR="$SCRIPTDIR/logs" docker-compose -f monitoring.yml "$@"
#!/bin/bash if [ ! -d ./builds ] ; then mkdir builds fi; SRC="spatial.c tools.c" FLAGS="-lgsl -std=c99 -DLOG -qopenmp -Wall -fast" echo Building: $1-saved rm -f ./builds/$1-saved icc $SRC -o builds/$1-saved $FLAGS strip ./builds/$1-saved echo Building: $1-gen rm -rf ./buids/$1-gen icc $SRC -o builds/$1-gen -D_BUILD_GENERATOR $FLAGS strip ./builds/$1-gen echo Building: $1-auto rm -rf ./builds/$1-auto icc $SRC -o builds/$1-auto -D_BUILD_AUTO_ALG $FLAGS strip ./builds/$1-auto echo Building: $1-rand rm -rf ./builds/$1-rand icc $SRC -o builds/$1-rand -D_BUILD_RANDOM $FLAGS strip ./builds/$1-rand
import React, { useEffect, useState } from 'react'; import { BrowserRouter as Router, useLocation, Link, useParams, useHistory } from "react-router-dom"; import { HttpClient } from '../shared/http-client'; import { MeetingAttendeeListProperties, MeetingAttendeesList } from './meeting-attendees-list'; interface MeetingDetails { id: string, meetingGroupId: string, title: string, termStartDate: Date, termEndDate: Date, description: string, locationName: string, locationAddress: string, locationPostalCode: string, locationCity: string, attendeesLimit?: number, guestsLimit: number, rsvpTermStartDate?: string, rsvpTermEndDate?: string, eventFeeValue?: string, eventFeeCurrency: string } interface MeetingDetailsUrlParams { meetingId: string; } export function MeetingDetails() { const { meetingId } = useParams<MeetingDetailsUrlParams>(); const [meetingDetails, setMeetingDetails] = useState<MeetingDetails | null>(null); useEffect(() => { loadDetails(); }, []); let history = useHistory(); function loadDetails() { HttpClient.get<MeetingDetails>(`api/meetings/meetings/${meetingId}`) .then(response => setMeetingDetails(response)); } function getMeetingAttendeesListProperties() : MeetingAttendeeListProperties { return { meetingId: meetingId } } return ( <div> {meetingDetails !== null && <div> <div>ID: {meetingDetails.id} </div> <div>Title: {meetingDetails.title} </div> <div>Date: {meetingDetails.termStartDate} - {meetingDetails.termEndDate} </div> <div>Description: {meetingDetails.description} </div> <div>Location name: {meetingDetails.locationName} </div> <div>Location address: {meetingDetails.locationAddress} </div> <div>Postal code: {meetingDetails.locationPostalCode} </div> <div>City: {meetingDetails.locationCity} </div> <div>Attendees limit: {meetingDetails.attendeesLimit} </div> <div>Guests limit: {meetingDetails.guestsLimit} </div> <div>RSVP start date: {meetingDetails.rsvpTermStartDate} - {meetingDetails.rsvpTermEndDate} </div> <div>Fee: {meetingDetails.eventFeeValue} {meetingDetails.eventFeeCurrency} </div> </div> } <MeetingAttendeesList {...getMeetingAttendeesListProperties()}></MeetingAttendeesList> </div> ) }
def add_10_elements(old_array): new_array = [] for i in range(len(old_array)): new_array.append(old_array[i] + 10) return new_array # Driver code old_array = [1, 2, 3, 4, 5] print(add_10_elements(old_array))
#include <queue> #include <memory> #include <iostream> // Event structure representing an event with a unique identifier and a timestamp struct Event { int id; long long timestamp; // Other event properties and methods // ... void Delete() { // Implementation to delete the event std::cout << "Event " << id << " deleted." << std::endl; } }; // Custom comparator for priority_queue to compare events based on their timestamps struct EventComparator { bool operator()(const Event& e1, const Event& e2) const { return e1.timestamp > e2.timestamp; // Min heap based on timestamp } }; class EventQueue { private: std::priority_queue<Event, std::vector<Event>, EventComparator> events; public: // Method to enqueue an event into the queue void Enqueue(const Event& event) { events.push(event); } // Method to dequeue an event from the queue and return it to the caller Event Dequeue() { Event dequeuedEvent = events.top(); events.pop(); return dequeuedEvent; } // Method to remove the event from the top of the queue and return it to the caller Event RemoveFromTop() { Event topEvent = events.top(); events.pop(); return topEvent; } }; int main() { Event e1{1, 100}; // Sample events with unique identifiers and timestamps Event e2{2, 50}; Event e3{3, 200}; EventQueue eventQueue; eventQueue.Enqueue(e1); eventQueue.Enqueue(e2); eventQueue.Enqueue(e3); Event removedEvent = eventQueue.RemoveFromTop(); removedEvent.Delete(); // Caller takes ownership and calls Delete on the removed event return 0; }
model = Sequential() model.add(Dense(50, input_dim=X_train.shape[1], activation='relu')) model.add(Dense(50, activation='relu')) model.add(Dense(1, activation='sigmoid'))
<reponame>kxepal/couchdb-fauxton // 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. define([ 'app', 'api', 'addons/documents/changes/actiontypes', 'addons/documents/changes/stores', 'addons/documents/helpers' ], function (app, FauxtonAPI, ActionTypes, Stores, Helpers) { var changesStore = Stores.changesStore; var pollingTimeout = 60000; var currentRequest; return { toggleTabVisibility: function () { FauxtonAPI.dispatch({ type: ActionTypes.TOGGLE_CHANGES_TAB_VISIBILITY }); }, addFilter: function (filter) { FauxtonAPI.dispatch({ type: ActionTypes.ADD_CHANGES_FILTER_ITEM, filter: filter }); }, removeFilter: function (filter) { FauxtonAPI.dispatch({ type: ActionTypes.REMOVE_CHANGES_FILTER_ITEM, filter: filter }); }, initChanges: function (options) { FauxtonAPI.dispatch({ type: ActionTypes.INIT_CHANGES, options: options }); currentRequest = null; this.getLatestChanges(); }, getLatestChanges: function () { var params = { limit: 100 }; // after the first request for the changes list has been made, switch to longpoll if (currentRequest) { params.since = changesStore.getLastSeqNum(); params.timeout = pollingTimeout; params.feed = 'longpoll'; } var query = $.param(params); var db = app.utils.safeURLName(changesStore.getDatabaseName()); var endpoint = FauxtonAPI.urls('changes', 'server', db, ''); currentRequest = $.getJSON(endpoint); currentRequest.then(_.bind(this.updateChanges, this)); }, updateChanges: function (json) { // only bother updating the list of changes if the seq num has changed var latestSeqNum = Helpers.getSeqNum(json.last_seq); if (latestSeqNum !== changesStore.getLastSeqNum()) { FauxtonAPI.dispatch({ type: ActionTypes.UPDATE_CHANGES, changes: json.results, seqNum: latestSeqNum }); } if (changesStore.pollingEnabled()) { this.getLatestChanges(); } }, togglePolling: function () { FauxtonAPI.dispatch({ type: ActionTypes.TOGGLE_CHANGES_POLLING }); // the user just enabled polling. Start 'er up if (changesStore.pollingEnabled()) { this.getLatestChanges(); } else { currentRequest.abort(); } } }; });
import { ALERT_SUCCESS, ALERT_ERROR, ALERT_INFO, ALERT_WARNING, ALERT_CLEAR } from 'ActionTypes'; const initialState = { visible:true }; export default function productReducer(state = initialState, action) { switch (action.type) { case ALERT_SUCCESS: // All done: set loading "false". // Also, replace the items with the ones from the server return { ...state, text: action.text, type: 'success', visible:true }; case ALERT_ERROR: // All done: set loading "false". // Also, replace the items with the ones from the server return { ...state, text: action.text, type: 'error', visible:true }; case ALERT_INFO: // All done: set loading "false". // Also, replace the items with the ones from the server return { ...state, text: action.text, type: 'info', visible:true }; case ALERT_WARNING: // All done: set loading "false". // Also, replace the items with the ones from the server return { ...state, text: action.text, type: 'warning', visible:true }; case ALERT_CLEAR: // Mark the state as "loading" so we can show a spinner or something // Also, reset any errors. We're starting fresh. return { visible:false }; default: // ALWAYS have a default case in a reducer return state; } }
#!/usr/bin/env bash # Copyright AppsCode Inc. and Contributors. # # 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. set -eou pipefail if [ -z "${OS:-}" ]; then echo "OS must be set" exit 1 fi if [ -z "${ARCH:-}" ]; then echo "ARCH must be set" exit 1 fi if [ -z "${VERSION:-}" ]; then echo "VERSION must be set" exit 1 fi export CGO_ENABLED=0 export GOARCH="${ARCH}" export GOOS="${OS}" export GO111MODULE=on export GOFLAGS="-mod=vendor" ENFORCE_LICENSE=${ENFORCE_LICENSE:-} if [ ! -z "${git_tag:-}" ]; then ENFORCE_LICENSE=true fi if [ "$ENFORCE_LICENSE" != "true" ]; then ENFORCE_LICENSE=false fi # ref: https://medium.com/golangspec/blocks-in-go-2f68768868f6 # ref: https://dave.cheney.net/2020/05/02/mid-stack-inlining-in-go # -gcflags="all=-N -l" \ go install \ -installsuffix "static" \ -ldflags " \ -X main.Version=${VERSION} \ -X main.VersionStrategy=${version_strategy:-} \ -X main.GitTag=${git_tag:-} \ -X main.GitBranch=${git_branch:-} \ -X main.CommitHash=${commit_hash:-} \ -X main.CommitTimestamp=${commit_timestamp:-} \ -X main.GoVersion=$(go version | cut -d " " -f 3) \ -X main.Compiler=$(go env CC) \ -X main.Platform=${OS}/${ARCH} \ -X 'go.bytebuilders.dev/license-verifier/info.EnforceLicense=${ENFORCE_LICENSE}' \ -X 'go.bytebuilders.dev/license-verifier/info.LicenseCA=$(curl -fsSL https://licenses.appscode.com/certificates/ca.crt)' \ -X 'go.bytebuilders.dev/license-verifier/info.ProductOwnerName=${PRODUCT_OWNER_NAME}' \ -X 'go.bytebuilders.dev/license-verifier/info.ProductName=${PRODUCT_NAME}' \ " \ ./...
<reponame>ctuning/ck-spack ############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by <NAME>, <EMAIL>, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program 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, February 1999. # # 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 terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Orthofinder(Package): """OrthoFinder is a fast, accurate and comprehensive analysis tool for comparative genomics. It finds orthologues and orthogroups infers rooted gene trees for all orthogroups and infers a rooted species tree for the species being analysed. OrthoFinder also provides comprehensive statistics for comparative genomic analyses. OrthoFinder is simple to use and all you need to run it is a set of protein sequence files (one per species) in FASTA format.""" homepage = "https://github.com/davidemms/OrthoFinder" url = "https://github.com/davidemms/OrthoFinder/releases/download/2.2.0/OrthoFinder-2.2.0.tar.gz" version('2.2.0', '<KEY>') depends_on('blast-plus', type='run') depends_on('mcl', type='run') depends_on('fastme', type='run') depends_on('py-dlcpar', type='run') def install(self, spec, prefix): install_tree('.', prefix.bin) chmod = which('chmod') chmod('+x', join_path(prefix.bin, 'orthofinder'))
""" CPSC 231 Group Project - Apocalypse 095 Play the game of Apocalypse! A simultaneous game based upon the principles of chess. The rules can be found here: https://en.wikipedia.org/wiki/Apocalypse_(chess_variant) The program functions are neatly divided into different sections to define different areas of the program. There are classes for the board drawing, AI, and buttons Created by: <NAME>, <NAME>, <NAME>, <NAME> Features: - Fully interactive GUI to play Apocalypse - Dark Theme Interface - Main Menu Screen - Saving and Loading game states - Variable levels of AI difficulty (Can you beat it on hard?) - Advanced MiniMax AI w/ Alpha Beta Pruning (that handles the simultaneous nature of Apocalypse) - Uses Recursion for the MiniMax AI - Uses sorting heuristics to speed up the alpha beta constraints and AI move generation - Sounds that work on most platforms (Windows, Linux, Mac OSX) - Classes for the buttons and AI to simplify code structure For sounds, since we can't use external libraries, we used this solution for Linux and Windows: http://stackoverflow.com/a/311634 """ import turtle import platform # used to know what the general display scaling should be import copy # for deep copies (for the minimax ai) import os # libraries used for sounds for various platforms if platform.system() == "Windows": import winsound elif platform.system() == "Linux": from wave import open as waveOpen from ossaudiodev import open as ossOpen # if one pawn left, value it much higher # algorithm that values the pieces dynamically # declare all of the global variables board = [["K", "P", "P", "P", "K"], ["P", "W", "W", "W", "P"], ["W", "W", "W", "W", "W"], ["p", "W", "W", "W", "p"], ["k", "p", "p", "p", "k"]] # penalty points for each player (player, ai) penalty_points = [0, 0] # default amount of moves the AI thinks forward (computation gets exponential). # Anything over 7 will take a very long time.... depth_amt = 6 # store the state of the highlighting of boxes highlight_params = [0, 0, 0, False, 0] box_selected = 0 # stores objects of created buttons buttons = [] # Stores the object of BoardDraw after the main function is executed DrawingBoard = False """ Board Drawing Class """ class BoardDraw: """ This class contains the necessary variables and functions for drawing things onto the screen """ # X, Y coords for each board box (to make our lives easier for onclick events) box_locations = [[[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]] # store individual turtle objects for each position on the board (makes editing easier) board_turtles = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] screen = turtle.Screen() # for proper scaling with many dimensions, if the width is substantially more, go by the height of the screen BOARD_DIMENSION = screen.window_width()*0.75 # dictionary that converts location num to a symbol SYMBOL_DICT = {"K": "♞", "P": "♟", "k": "♘", "p": "♙", "W": ""} # stores text height for the queue messages TEXT_HEIGHT = int(BOARD_DIMENSION/7.5) # stores text height for strings related to the penalty score board PENALTY_TEXT_HEIGHT = int(BOARD_DIMENSION/50) # creates the move offset that is needed to increment by everytime a new message is printed (creates extra var to save it) moveOffset = BOARD_DIMENSION/2 - (TEXT_HEIGHT/0.7) - (PENALTY_TEXT_HEIGHT * 1.5) SAVED_OFFSET = moveOffset # define dynamic scaling variable that stores whether to scale by height or width scaling_value = screen.window_width() def __init__(self): # Initiate the screen with bgcolor self.screen.bgcolor("#4A4A4A") self.screen.title("Apocalypse") # Initialize Turtles for the right message queue and penalties self.PenaltyTurtle = turtle.Turtle() self.PenaltyTurtle.hideturtle() self.MessagesTurtle = turtle.Turtle() self.MessagesTurtle.hideturtle() # for proper scaling for relative values, if the height is less than the width, go based off of that if self.screen.window_height() < self.screen.window_width(): self.scaling_value = self.screen.window_height() # If there is a high ratio of width to height, make the board dimensions based upon the height if self.screen.window_width()/self.screen.window_height() > 1.20: # width of the board is equal to 95% of the screen height self.BOARD_DIMENSION = self.screen.window_height()*0.95 def draw_main_screen(self): """ Draws the main menu screen with created turtles and creates the main screen buttons :return: """ delete_buttons() self.screen.clear() self.screen.onclick(None) self.screen.onclick(button_event) self.screen.bgcolor("#4A4A4A") self.screen.title("Apocalypse") # draw the checkered background self.draw_main_bg() # Initialize a turtle to draw the main screen text main_menu_turtle = create_default_turtle() main_menu_turtle.sety(self.screen.window_height()/5) main_menu_turtle.write("Apocalypse", True, align="center", font=("Ariel", int(self.scaling_value/8))) main_menu_turtle.home() main_menu_turtle.write("♘ ♙ ♞ ♟", True, align="center", font=("Ariel", int(self.scaling_value/10))) main_menu_turtle.setposition((self.screen.window_width() / 2), -((self.screen.window_height() / 2) - 10)) # Create the main screen buttons Button(0, -(self.screen.window_height()/20), "New Game", 'DrawingBoard.choose_difficulty()', self.screen.window_width()/3) Button(0, -(self.screen.window_height()/7), "Load Game", 'load_state()', self.screen.window_width()/3) def draw_main_bg(self): """ Draws the checkerboard pattern onto the screen as a background for the main menu :return: """ # create the turtle that draws the checkerboard bg pattern and configure its settings bg_turtle = create_default_turtle("#5E5E5E") # define the size of each box box_height = self.screen.window_height() / 5 box_width = self.screen.window_width() / 5 # set the turtle to the top left corner of the screen bg_turtle.setpos(-(self.screen.window_width()/2), (self.screen.window_height()/2)) # iterate and draw out the checkerboard pattern for row in range(0, 5): for column in range(0, 5): if row % 2 == 0: # even case if column % 2 != 0: # print out a block bg_turtle.begin_fill() for i in range(4): if i % 2 == 0: bg_turtle.forward(box_width) else: bg_turtle.forward(box_height) bg_turtle.right(90) bg_turtle.end_fill() else: if column % 2 == 0: bg_turtle.begin_fill() for i in range(4): if i % 2 == 0: bg_turtle.forward(box_width) else: bg_turtle.forward(box_height) bg_turtle.right(90) bg_turtle.end_fill() bg_turtle.setx(bg_turtle.xcor() + box_width) # reset position each time a row is done bg_turtle.setpos(-(self.screen.window_width()/2), (bg_turtle.ycor() - box_height)) def draw_board(self): """ This function will draw the game board onto the screen based upon the constants BOARD_DIMENSION and SYMBOL_DICT :return: """ delete_buttons() X_COR = 0 Y_COR = 1 self.moveOffset = self.BOARD_DIMENSION/2 - (self.TEXT_HEIGHT/0.7) - (self.PENALTY_TEXT_HEIGHT * 1.5) self.SAVED_OFFSET = self.moveOffset # Initiate turtle that will draw the board main_board = create_default_turtle("#5E5E5E") # Make the board 80% width and 10% to the left main_board.goto(-(self.BOARD_DIMENSION/2) - (self.screen.window_width()*0.1), self.BOARD_DIMENSION/2) # create outer rectangle main_board.down() main_board.pendown() for i in range(4): main_board.forward(self.BOARD_DIMENSION) main_board.right(90) main_board.penup() # move turtle back to top left of the board main_board.goto(-(self.BOARD_DIMENSION/2) - (self.screen.window_width()*0.1), self.BOARD_DIMENSION/2) # iterate through each box and draw it for row in range(0, 5): for column in range(0, 5): # store the top left of every box in the chess table for future reference and click events self.box_locations[row][column][X_COR] = main_board.xcor() self.box_locations[row][column][Y_COR] = main_board.ycor() # create checkerboard pattern # check if the row is 0, 2, 4 if row % 2 == 0: # Check whether there is an even column if column % 2 == 0: # print out a block main_board.begin_fill() for i in range(4): main_board.forward(self.BOARD_DIMENSION/5) main_board.right(90) main_board.end_fill() else: # row is 1, 3 # Check whether it is an odd column if column % 2 != 0: main_board.begin_fill() for i in range(4): main_board.forward(self.BOARD_DIMENSION/5) main_board.right(90) main_board.end_fill() # write out the characters (board pieces) # create new turtle just for the character, and store it in the array board_turtles char_turtle = create_default_turtle() char_turtle.setx(main_board.xcor() + (self.BOARD_DIMENSION/10)) # get symbol from dict text_to_write = self.SYMBOL_DICT[get_piece(row, column)] # mac osx and windows have different symbol designs, with diff height/width # haven't tested on a Unix system other than Mac OSX, Linux may have a different character set if platform.system() == "Windows": # adjust scaling of the y coord based upon the os char_turtle.sety(main_board.ycor() - (self.BOARD_DIMENSION/4.10)) char_turtle.write(text_to_write, False, align="center", font=("Ariel", int(self.BOARD_DIMENSION/5.4))) else: # haven't tested on a Unix system other than Mac OSX, Linux may have a different character set char_turtle.sety(main_board.ycor() - (self.BOARD_DIMENSION/5)) char_turtle.write(text_to_write, False, align="center", font=("Ariel", int(self.BOARD_DIMENSION/5))) # add turtle to the board so that the memory location is stored self.board_turtles[row][column] = char_turtle # move the turtle to the right for the distance of one block main_board.setx(main_board.xcor() + (self.BOARD_DIMENSION/5)) # reset x position each time a row is done (to the very left), move the turtle down one block main_board.setpos(-(self.BOARD_DIMENSION/2) - (self.screen.window_width()*0.1), (main_board.ycor() - (self.BOARD_DIMENSION/5))) # create buttons on the main board to perform various actions, the offsets were calculated by eye and are relative Button(self.BOARD_DIMENSION/2 + (self.BOARD_DIMENSION/2 * 0.03), -self.BOARD_DIMENSION/2.13, "Load Game", 'load_state()', self.screen.window_width()*0.20, self.scaling_value/36) Button(self.BOARD_DIMENSION/2 + (self.BOARD_DIMENSION/2 * 0.03), -self.BOARD_DIMENSION/2.50, "Save Game", 'save_state()', self.screen.window_width()*0.20, self.scaling_value/36) Button(self.BOARD_DIMENSION/2 + (self.BOARD_DIMENSION/2 * 0.03), -self.BOARD_DIMENSION/3.02, "Main Menu", 'DrawingBoard.draw_main_screen()', self.screen.window_width()*0.20, self.scaling_value/36) def penalty_count(self): """ Draws out the penalty points display on the right of the board :return: """ # height of the text PenaltyTurtle = self.PenaltyTurtle PENALTY_TEXT_HEIGHT = self.PENALTY_TEXT_HEIGHT BOARD_DIMENSION = self.BOARD_DIMENSION TEXT_HEIGHT = self.TEXT_HEIGHT screen = self.screen PenaltyTurtle.up() PenaltyTurtle.clear() PenaltyTurtle.color("grey") # Font sizes differ on Windows and Unix Platforms, use different scaling for both to position the turtle if platform.system() == "Windows": PenaltyTurtle.setpos(BOARD_DIMENSION/2 - screen.window_width() * 0.08, BOARD_DIMENSION/2 - (PENALTY_TEXT_HEIGHT/0.8)) else: PenaltyTurtle.setpos(BOARD_DIMENSION/2 - screen.window_width() * 0.08, BOARD_DIMENSION/2 - (PENALTY_TEXT_HEIGHT/1)) PenaltyTurtle.write("Penalty Points:", False, align="left", font=("Ariel", PENALTY_TEXT_HEIGHT)) # Font sizes differ on Windows and Unix Platforms, use different scaling for both to position the turtle if platform.system() == "Windows": PenaltyTurtle.setpos(BOARD_DIMENSION/2 - screen.window_width() * 0.08, BOARD_DIMENSION/2 - (TEXT_HEIGHT/0.8)) else: PenaltyTurtle.setpos(BOARD_DIMENSION/2 - screen.window_width() * 0.08, BOARD_DIMENSION/2 - (TEXT_HEIGHT/1)) PenaltyTurtle.sety(PenaltyTurtle.ycor() - (PENALTY_TEXT_HEIGHT * 1.5)) PenaltyTurtle.color("grey") PenaltyTurtle._tracer(False) # save coords to write out the numbers along with centered strings that define AI or Player # write out the player penalty amount and string saved_y = PenaltyTurtle.ycor() PenaltyTurtle.setx(BOARD_DIMENSION/2 - screen.window_width() * 0.08) text_width = PenaltyTurtle.xcor() PenaltyTurtle.write(penalty_points[0], move=True, align="left", font=("Ariel", TEXT_HEIGHT)) # Set the coords of the turtle to write the centered "Player" text below the penalty score text_width = PenaltyTurtle.xcor() - text_width saved_x = PenaltyTurtle.xcor() PenaltyTurtle.setx(saved_x - text_width/2) PenaltyTurtle.write("Player", False, align="center", font=("Ariel", PENALTY_TEXT_HEIGHT)) # Reset the coord position to the saved position PenaltyTurtle.setpos(saved_x, saved_y) # Set the x coord of the penalty turtle to the location for the AI, using relative offsets PenaltyTurtle.setx(PenaltyTurtle.xcor() + screen.window_width() * 0.03) text_width = PenaltyTurtle.xcor() PenaltyTurtle.write(penalty_points[1], move=True, align="left", font=("Ariel", TEXT_HEIGHT)) # Set the coords of the turtle to write the centered "AI" text below the penalty score text_width = PenaltyTurtle.xcor() - text_width saved_x = PenaltyTurtle.xcor() PenaltyTurtle.setx(saved_x - text_width/2) PenaltyTurtle.write("AI", move=False, align="center", font=("Ariel", PENALTY_TEXT_HEIGHT)) def display_move(self, x, y, new_x, new_y, player): """ Displays a given move in the queue messages :param x: **int** x coord of old piece position :param y: **int** y coord of old piece position :param new_x: **int** x coord of the new piece position :param new_y: **int** y coord of the new piece position :return: """ to_write = player + ": " + str(y+1) + ", " + str(x+1) + " to " + str(new_y+1) + ", " + str(new_x+1) self.message_queue(to_write) def message_queue(self, to_write): """ Writes any defined string to the message queue on the right of the board :param to_write: **string** Message to write in the queue :return: """ self.MessagesTurtle.up() # reset the messages if it goes beyond the space height if self.moveOffset < -(self.BOARD_DIMENSION/4.5): self.moveOffset = self.SAVED_OFFSET self.MessagesTurtle.clear() # position the height to be lower for the new text self.moveOffset -= int(self.BOARD_DIMENSION/40) * 1.25 self.MessagesTurtle._tracer(False) self.MessagesTurtle.color("grey") # go to the position to write out the text and write it self.MessagesTurtle.goto(self.BOARD_DIMENSION/2 - self.screen.window_width() * 0.08, self.moveOffset) self.MessagesTurtle.write(to_write, move=True, align="left", font=("Ariel", int(self.BOARD_DIMENSION/45))) # overwrite the moveOffset with the new location self.moveOffset = self.MessagesTurtle.ycor() def game_end_screen(self, winner): """ Clears the screen and draws out the end game screen as to who won :param winner: **numeric** integer that defines who won (0 for AI, 1 for Player, 3 for Stalemate) :return: """ self.screen.clear() # clear any other buttons and rebind the handler delete_buttons() self.screen.onclick(button_event) self.screen.bgcolor("#4A4A4A") if winner == 1: text_write = "AI Won!" elif winner == 0: text_write = "You Won!" elif winner == 2: text_write = "Stalemate!" # configure a turtle and write out who won end_screen_turtle = create_default_turtle() # the font size is just a relative static value to make sure it is proportionate to the screen dimensions end_screen_turtle.write(text_write, move=False, align="center", font=("Arial", int(self.BOARD_DIMENSION/8))) # draw out the main menu button Button(0, -(self.screen.window_height()/20), "Main Menu", 'DrawingBoard.draw_main_screen()', self.scaling_value/3) def choose_difficulty(self): """ Clears and draws the difficulty screen :return: """ delete_buttons() self.screen.clear() self.screen.onclick(button_event) self.screen.bgcolor("#4A4A4A") # setup the turtle difficulty_turtle = create_default_turtle() difficulty_turtle.setpos(0, self.screen.window_height()/20) difficulty_turtle.write("Difficulty", True, align="center", font=("Ariel", int(self.screen.window_width()/12))) Button(0, -(self.screen.window_height()/20), "Easy", 'modify_difficulty(1); DrawingBoard.new_game()', self.screen.window_width()/3) Button(0, -(self.screen.window_height()/7), "Medium", 'modify_difficulty(4); DrawingBoard.new_game()', self.screen.window_width()/3) Button(0, -(self.screen.window_height()/4.2), "Hard", 'modify_difficulty(7); DrawingBoard.new_game()', self.screen.window_width()/3) def new_game(self): """ Starts a new game, draws the board, and binds event handlers :return: """ delete_buttons() self.screen.clear() self.screen.bgcolor("#4A4A4A") # reset the game state and draw it out reset_game_state() reset_highlight_params() self.draw_board() self.penalty_count() # bind the event handler self.screen.onclick(onclick_board_handler) self.screen.onkeyrelease(save_state, "s") self.screen.onkeyrelease(load_state, "l") self.screen.listen() def select_tile(self, New_Highlight_Turtle, current_box, column, row): global box_selected, highlight_params LAST_CLICK_COLUMN = 1 LAST_CLICK_ROW = 2 X_COORD = 0 Y_COORD = 1 # only let the user select tiles it owns New_Highlight_Turtle.up() New_Highlight_Turtle.goto(current_box[X_COORD], current_box[Y_COORD]) New_Highlight_Turtle.down() for i2 in range(4): New_Highlight_Turtle.forward(self.BOARD_DIMENSION/5) New_Highlight_Turtle.right(90) New_Highlight_Turtle.up() box_selected = 1 # save x y coords from the turtle for future reference highlight_params[LAST_CLICK_COLUMN] = column highlight_params[LAST_CLICK_ROW] = row """ Button Class and Delete Function """ class Button: def __init__(self, x, y, text, code_exec, width=0, font_size=BoardDraw.scaling_value/25): """ Draws a button centered at the specified x, y point with the text passed in as a parameter and also handles configuring the click events for it :param x: **numeric** x coord of the center of the button :param y: **numeric** y coord of the center of the button :param text: **string** desired button text :param code_exec: **string** function or code to execute when the button is clicked :param width: optional **numeric** overwrites the default padding width with a specified width of the button :return: """ self.font_size = int(font_size) self.function = code_exec self.x = x self.y = y self.width = width self.text = text text_width = self.text_width() if width == 0: self.width = text_width + text_width * 0.15 self.height = font_size + (font_size * 0.6) print("Drawing button with text " + text) self.draw_button() self.top_left = (x - self.width/2) self.bottom = (y + self.height/2) # append the object of the button to the list "buttons" for the event handler buttons.append(self) def text_width(self): """ Determines the text width of the specified text of the button :return: """ width_turtle = create_default_turtle() init_x = width_turtle.xcor() width_turtle.write(self.text, move=True, align="left", font=("Ariel", self.font_size)) width_turtle.clear() self.text_width = width_turtle.xcor() - init_x return self.text_width def draw_button(self): """ Draws the button given the already set state :return: """ # draw out the background white box around the text self.button_turtle = create_default_turtle() self.button_turtle.setpos(self.x - (self.width/2), self.y + (self.height/2)) self.button_turtle.down() self.button_turtle.begin_fill() for i in range(4): if i % 2 == 0: # even num self.button_turtle.forward(self.width) else: self.button_turtle.forward(self.height) self.button_turtle.right(90) self.button_turtle.end_fill() self.button_turtle.up() self.button_turtle.color("black") # Windows and Unix based systems have different font heights and scaling if platform.system() == "Windows": self.button_turtle.setpos(self.x, self.y - (self.font_size/1.4)) else: self.button_turtle.setpos(self.x, self.y - (self.font_size/1.65)) # write out the text in the center of the button self.button_turtle.write(self.text, align="center", font=("Ariel", self.font_size)) def check_clicked(self, x, y): """ Given the x and y of a user's click, return a Bool as to whether the user clicked this button :param x: **numeric** The x coordinate of a user's click :param y: **numeric** The y coordinate of a user's click :return: **bool** True if the user clicked the button, False if not """ if (self.top_left + self.width) > x > self.top_left and self.bottom > y > (self.bottom - self.height): return True else: return False def execute_function(self): """ Execute the function this button holds when clicked """ exec(self.function) def delete_buttons(): """ Deletes all of the onclick data for all current buttons """ global buttons del buttons[:] """ AI Class """ class AIMove: # set the score weighting for pawns and knights (for the AI) KNIGHT_WEIGHTING = 1 PAWN_WEIGHTING = 1 def __init__(self, board_copy): """ Sets initial parameters for the AI :param board_copy: **multi-dimensional list** Board State :return: """ self.board = board_copy def findmove(self, depth): """ Starts the minimax recursion sequence with the given depth and board state :param depth: **int** Depth of moves to think ahead :return: **multi-dimensional list** Defines the best possible move using minimax w/ alpha beta pruning """ return self.minimax_alphabeta(self.board, depth, True, float("-infinity"), float("infinity"), 0, True) def minimax_alphabeta(self, board_state, depth, MaxPlayer, alpha, beta, prev_move=0, top_tree=False): """ Implements the Minimax algorithm with alpha beta pruning for calculating AI decisions This function is recursively called and tries to mimic simultaneous movements :param board_state: **multi-dimensional list** Board state :param depth: **int** Current depth of the recursive call :param MaxPlayer: **bool** Defines whether to minimize or maximize in the current recursive call :param alpha: **float** Current alpha value for pruning purposes :param beta: **float** Current beta value for pruning purposes :param prev_move: **multi-dimensional list** **optional** List defining the previous move (set if the last call was maximizing :param top_tree: **bool** **optional** True if the current node is at the top of the tree :return: If its the terminal node, returns the score of the node """ board_copy = copy.deepcopy(board_state) # This mimics simultaneous movements when checking a leaf node that doesn't involve the minimizing player if prev_move != 0: board_copy = self.combine_single_move(board_copy, prev_move[0], prev_move[1], prev_move[2], prev_move[3]) current_score = self.ai_score(board_copy) if depth == 0 or current_score == float("-infinity") or current_score == float("infinity") \ or current_score == 255: # this is a leaf node, return the score return self.ai_score(board_copy) # Revert any changes that were done to calculate the AI score board_copy = copy.deepcopy(board_state) if MaxPlayer: best_val = float("-infinity") moves = self.possible_moves(board_copy, 0) # Heuristic: Sort moves by ones that kill pieces first to reduce alpha beta constraints faster moves = sorted(moves, key=lambda x: x[1], reverse=True) if top_tree: best_move = [] old_piece = [] for move in moves: clean_move = move[0] #print("Max Depth " + str(depth) + " Board: " + str(board_copy)) val = self.minimax_alphabeta(copy.deepcopy(board_copy), depth - 1, False, alpha, beta, clean_move) #print("Score of " + str(val)) if val > best_val: best_move = clean_move if len(move) == 3: # this contains values about the piece that died in this process old_piece = move[2] best_val = max(best_val, val) alpha = max(best_val, alpha) if beta <= alpha: # cut off break # This might be the top of the tree, if so, return the best move along with the value if top_tree: return [[best_move, old_piece], best_val] else: return best_val else: # min player best_val = float("infinity") moves = self.possible_moves(board_copy, 1) # Heuristic: Sort moves by ones that kill pieces first to reduce alpha beta constraints faster moves = sorted(moves, key=lambda x: x[1], reverse=True) for move in moves: move = move[0] move_board = copy.deepcopy(board_copy) # The minimizing player always combines moves simultaneously move_board = self.combine_moves(move_board, move[0], move[1], move[2], move[3], prev_move[0], prev_move[1], prev_move[2], prev_move[3]) val = self.minimax_alphabeta(move_board, depth - 1, True, alpha, beta) best_val = min(best_val, val) beta = min(best_val, beta) if beta <= alpha: # cutoff break return best_val def possible_moves(self, board_state, player_type): """ Generates possible moves for player_type on the given board_state :param board_state: **multi-dimensional list** Represents the current board state :param player_type: **int** 0 if AI, 1 if Player :return: **multi-dimensional list** List that defines the possible moves that can be made by that player """ # list to store the possible moves possible_moves = [] # Possible knight move offsets knight_moves = [[1, 2], [2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1], [-2, 1], [-1, 2]] for x in range(5): for y in range(5): piece_type = board_state[x][y] # check whether the AI owns this piece if (piece_type == "K" and player_type == 0) or (piece_type == "k" and player_type == 1): for move in knight_moves: if 0 <= (x + move[0]) < 5 and 0 <= (y + move[1]) < 5: # it is inside the board if player_type == 0: if board_state[x+move[0]][y+move[1]] != "P" and board_state[x+move[0]][y+move[1]] != "K": # valid AI move for the knight, return it if board_state[x+move[0]][y+move[1]] == "W": possible_moves.append([[x, y, (x+move[0]), (y+move[1])], 0]) elif board_state[x+move[0]][y+move[1]] == "p": # give more points if it kills a pawn possible_moves.append([[x, y, (x+move[0]), (y+move[1])], 2]) else: possible_moves.append([[x, y, (x+move[0]), (y+move[1])], 1]) else: if board_state[x+move[0]][y+move[1]] != "p" and board_state[x+move[0]][y+move[1]] != "k": # valid AI move for the knight, return it if board_state[x+move[0]][y+move[1]] == "W": possible_moves.append([[x, y, (x+move[0]), (y+move[1])], 0]) elif board_state[x+move[0]][y+move[1]] == "P": # give more points if it kills a pawn, that matters much much more possible_moves.append([[x, y, (x+move[0]), (y+move[1])], 2]) else: possible_moves.append([[x, y, (x+move[0]), (y+move[1])], 1]) elif (piece_type == "P" and player_type == 0) or (piece_type == "p" and player_type == 1): # offset of rows is down for the AI if piece_type == "P": offset_val = x + 1 else: offset_val = x - 1 # boolean defining whether the pawn is redeploying or not movement_upgrade = ((player_type == 0 and offset_val != 4) or (player_type == 1 and offset_val != 0)) or ((knight_amount(board_state, player_type) < 2) and ((player_type == 0 and offset_val == 4) or (player_type == 1 and offset_val == 0))) valid_move_val = False move_vals = [] # check going diagonally right if 0 <= offset_val < 5 and 0 <= (y + 1) < 5: # it is within the constraints of the board, check whether there is an enemy there if player_type == 0: if board_state[offset_val][(y + 1)] == "k" or board_state[offset_val][(y + 1)] == "p": if movement_upgrade: if board_state[offset_val][(y + 1)] == "p": possible_moves.append([[x, y, offset_val, (y + 1)], 2]) else: possible_moves.append([[x, y, offset_val, (y + 1)], 1]) else: valid_move_val = True move_vals.append([x, y, offset_val, (y + 1)]) else: if board_state[offset_val][(y + 1)] == "K" or board_state[offset_val][(y + 1)] == "P": if movement_upgrade: if board_state[offset_val][(y + 1)] == "p": possible_moves.append([[x, y, offset_val, (y + 1)], 2]) else: possible_moves.append([[x, y, offset_val, (y + 1)], 1]) else: valid_move_val = True move_vals.append([x, y, offset_val, (y + 1)]) if 0 <= offset_val < 5 and 0 <= (y - 1) < 5: # it is within the constraints of the board, check whether there is an enemy there if player_type == 0: if board_state[offset_val][(y - 1)] == "k" or board_state[offset_val][(y - 1)] == "p": if movement_upgrade: if board_state[offset_val][(y - 1)] == "p": possible_moves.append([[x, y, offset_val, (y - 1)], 2]) else: possible_moves.append([[x, y, offset_val, (y - 1)], 1]) else: valid_move_val = True move_vals.append([x, y, offset_val, (y - 1)]) else: if board_state[offset_val][(y - 1)] == "K" or board_state[offset_val][(y - 1)] == "P": if movement_upgrade: if board_state[offset_val][(y - 1)] == "P": possible_moves.append([[x, y, offset_val, (y - 1)], 2]) else: possible_moves.append([[x, y, offset_val, (y - 1)], 1]) else: valid_move_val = True move_vals.append([x, y, offset_val, (y - 1)]) if 0 <= offset_val < 5: # check whether it is going forward # check whether forward is whitespace or not if board_state[offset_val][y] == "W": if movement_upgrade: possible_moves.append([[x, y, offset_val, y], 0]) else: valid_move_val = True move_vals.append([x, y, offset_val, y]) if not movement_upgrade and valid_move_val is True: # pawn reached last rank and they have 2 knights already # allow them to redeploy, generate possible moves for move_output in move_vals: for tempx in range(5): for tempy in range(5): temp_piece_type = board_state[tempx][tempy] if temp_piece_type == "W": # this is a possibility possible_moves.append([[x, y, tempx, tempy], 0, move_output]) return possible_moves def ai_score(self, board_state): """ Computes the score of the board for the AI using a weighted score heuristic :param board_state: **multi-dimensional list** defining the board state :return: **numerical** returns score of the current board for the AI """ # Calculate the current AI score and pawn amount ai_score_val = 0 ai_pawns = 0 for row in range(5): for column in range(5): if board_state[row][column] == "K": ai_score_val += self.KNIGHT_WEIGHTING elif board_state[row][column] == "P": ai_score_val += self.PAWN_WEIGHTING ai_pawns += 1 # Calculate the current player score and pawn amount player_score = 0 player_pawns = 0 for row in range(5): for column in range(5): if board_state[row][column] == "k": player_score += self.KNIGHT_WEIGHTING elif board_state[row][column] == "p": player_score += self.PAWN_WEIGHTING player_pawns += 1 # Set value to store the return value return_val = 0 # Calculate general score of the board for the AI if len(self.possible_moves(board_state, 0)) == 0: return_val = float("-infinity") elif ai_pawns == 0 and player_pawns == 0: # stalemate, return a high value less than a win # The number is not generally achievable with pawn wighting and thus works for terminal nodes return_val = 255 elif ai_pawns == 0: # the player won return_val = float("-infinity") elif player_pawns == 0: # the ai won return_val = float("infinity") else: return_val = ai_score_val-player_score return return_val def combine_moves(self, board_state_val, x, y, new_x, new_y, x2, y2, new_x2, new_y2): """ Combines two move onto a given board state without any drawing functionality Uses the rules of simultaneous movement in Apocalypse when combining the moves :param board_state_val: **multi-dimensional list** Board state :param x: **int** current x coord of the first piece to move :param y: **int** current y coord of the first piece to move :param new_x: **int** new x coord of the first piece to move :param new_y: **int** new y coord of the first piece to move :param x2: **int** current x coord of the second piece to move :param y2: **int** current y coord of the second piece to move :param new_x2: **int** new y coord of the second piece to move :param new_y2: **int** new y coord of the second piece to move :return: **multi-dimensional list** Board state with the moves combined """ # Create deep copy of the board to configure board_state = copy.deepcopy(board_state_val) # store the values of each moving board piece player_val = board_state[x][y] ai_val = board_state[x2][y2] if new_x == new_x2 and new_y == new_y2: piece_type1 = board_state[x][y] piece_type2 = board_state[x2][y2] if piece_type1 == "p" and piece_type2 == "P": # both pawns, delete both board_state[x][y] = "W" board_state[x2][y2] = "W" elif piece_type1 == "k" and piece_type2 == "K": board_state[y][x] = "W" board_state[x2][y2] = "W" elif piece_type1 == "p" and piece_type2 == "K": board_state[x][y] = "W" # execute move for AI board_state[new_x2][new_y2] = board_state[y2][x2] board_state[x2][y2] = "W" elif piece_type1 == "k" and piece_type2 == "P": board_state[x2][y2] = "W" # execute move for player board_state[new_x][new_y] = board_state[y][x] board_state[x][y] = "W" else: # the pieces are moving to different locations, simultaneous movement does not matter board_state[new_x][new_y] = player_val board_state[x][y] = "W" board_state[new_x2][new_y2] = ai_val board_state[x2][y2] = "W" # check whether an AI pawn reached the last rank if ai_val == "P" and new_x2 == 4: # reached last rank, process it board_state[new_x2][new_y2] = "K" # check whether a player pawn reached the last rank if player_val == "p" and new_x == 0: # reached last rank, process it board_state[new_x][new_y] = "k" return board_state def combine_single_move(self, board_state_val, x, y, new_x, new_y): """ Combines a single move onto a given board state without any drawing functionality **Does not take simultaneous action into account** :param board_state_val: **multi-dimensional list** Board state :param x: **int** current x coord of the piece to move :param y: **int** current y coord of the piece to move :param new_x: **int** new x coord of the piece to move :param new_y: **int** new y coord of the piece to move :return: **multi-dimensional list** Board state with the move combined """ board_state = copy.deepcopy(board_state_val) player_val = copy.copy(board_state[x][y]) board_state[new_x][new_y] = player_val board_state[x][y] = "W" # check whether we need to upgrade pawns to knights if new_x == 4 and player_val == "P": board_state[new_x][new_y] = "K" elif new_x == 0 and player_val == "p": board_state[new_x][new_y] = "k" return board_state """ Board Drawing Related Functions """ def create_default_turtle(colour="white"): """ Creates a default turtle with standard settings that are used in many places throughout the program :param colour: **string** **optional** Colour of the turtle to set :return: **object** Configured turtle """ temp_turtle = turtle.Turtle() temp_turtle.hideturtle() temp_turtle.color(colour) temp_turtle._tracer(False) temp_turtle.up() return temp_turtle """ Piece Handler and Game Logic Functions """ def move_piece(x, y, new_x, new_y, x2, y2, new_x2, new_y2): """ Combines two move onto a given board state WITH drawing functionality Uses the rules of simultaneous movement in Apocalypse when combining the moves :param board_state_val: **multi-dimensional list** Board state :param x: **int** current x coord of the first piece to move :param y: **int** current y coord of the first piece to move :param new_x: **int** new x coord of the first piece to move :param new_y: **int** new y coord of the first piece to move :param x2: **int** current x coord of the second piece to move :param y2: **int** current y coord of the second piece to move :param new_x2: **int** new y coord of the second piece to move :param new_y2: **int** new y coord of the second piece to move :return: **multi-dimensional list** Board state with the moves combined """ global board # check whether the destination is the same for both if new_x == new_x2 and new_y == new_y2: print("Both pieces going to the same location") piece_type1 = get_piece(y, x) piece_type2 = get_piece(y2, x2) if piece_type1 == "p" and piece_type2 == "P": # both pawns, delete both print("Both are pawns, detroying both") delete_piece(x, y) delete_piece(x2, y2) elif piece_type1 == "k" and piece_type2 == "K": print("Both are knights, detroying both") delete_piece(x, y) delete_piece(x2, y2) elif piece_type1 == "p" and piece_type2 == "K": delete_piece(x, y) # execute move for AI execute_move(x2, y2, new_x2, new_y2, SYMBOL_DICT[get_piece(y2, x2)]) elif piece_type1 == "k" and piece_type2 == "P": delete_piece(x2, y2) # execute move for AI execute_move(x, y, new_x, new_y, SYMBOL_DICT[get_piece(y, x)]) else: # the pieces are moving to different locations, simultaneous movement does not matter # we need to save the pawn type for each value if x != -1: player_pawn = DrawingBoard.SYMBOL_DICT[get_piece(y, x)] player_code = get_piece(y, x) if x2 != -1: ai_pawn = DrawingBoard.SYMBOL_DICT[get_piece(y2, x2)] ai_code = get_piece(y2, x2) if (x != -1): execute_move(x, y, new_x, new_y, player_pawn, player_code) if (x2 != -1): # since this is the second move, execute_move(x2, y2, new_x2, new_y2, ai_pawn, ai_code) def execute_move(x, y, new_x, new_y, symbol, piece_code=-1, force_delete=3): """ Executes a given move on the board (modifying values and drawing the board) :param x: **int** current piece x coord :param y: **int** current piece y coord :param new_x: **int** new piece x coord :param new_y: **int** new piece y coord :param symbol: **string** Symbol of the piece you're moving :param piece_code: **int** Piece value (on the board) to use (optional) :param force_delete: **int** Force delete the previous piece on the board (optional) :return: """ global highlight_params, box_selected, board print("Moving The Piece At: Column:", x, "and Row:", y, "\n\t\t\t To: Column:", new_x, "and Row:", new_y) # replace piece on the board if piece_code == -1: piece_code = get_piece(y, x) set_piece(new_y, new_x, piece_code) # check the saved symbol is the same as the current piece on the board at that location, make sure we don't delete it test_symbol = DrawingBoard.SYMBOL_DICT[get_piece(y, x)] if test_symbol == symbol and force_delete == 3: # the other player did not move into our old location, we can delete whatever is there delete_piece(x, y) if force_delete == True: print("Force deleting the piece") delete_piece(x, y) # Get the turtle stored for the new block new_turtle = DrawingBoard.board_turtles[new_y][new_x] # clear the turtle (in case there is a written piece there) at the desired position new_turtle.clear() # write out the piece symbol centered in the block in ariel font with a size of the block height/width if platform.system() == "Windows": # adjust scaling of the y coord based upon the os new_turtle.write(symbol, False, align="center", font=("Ariel", int(DrawingBoard.BOARD_DIMENSION/5.5))) else: # haven't tested on a Unix system other than Mac OSX, Linux may have a different character set new_turtle.write(symbol, False, align="center", font=("Ariel", int(DrawingBoard.BOARD_DIMENSION/5))) # display the move on the right display if piece_code.isupper(): # AI Move DrawingBoard.display_move(x, y, new_x, new_y, "A") else: # Player Move DrawingBoard.display_move(x, y, new_x, new_y, "P") def valid_move(x, y, newx, newy, playername): """ Checks whether a given move is valid or not for playername :param x: **int** current piece x coord :param y: **int** current piece y coord :param newx: **int** new piece x coord :param newy: **int** new piece y coord :param playername: **string** playername is 'p' or 'a' depending on player or ai :return: **bool** True if it is a valid move, False if not """ # x, y is current piece that wants to move to newx, newy # playername is p or a depending on player or ai Bool_Return = False knight_moves = [[1, 2], [2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1], [-2, 1], [-1, 2]] if (0 <= x <= 4 and 0 <= y <= 4 and 0 <= newx <= 4 and 0 <= newy <= 4): piece_type = get_piece(x, y) new_piece_type = get_piece(newx, newy) if piece_type.lower() == "k": if ((piece_type == "k" and playername == "p") or (piece_type == "K" and playername == "a")): # make sure they own that piece # see whether it is a valid knight move in the grid for move in knight_moves: if (x + move[0]) == newx and (y + move[1] == newy): if (playername == "p"): if (new_piece_type != "p" and new_piece_type != "k"): # valid knight move, continue on Bool_Return = True break elif (playername == "a"): if (new_piece_type != "P" and new_piece_type != "K"): # valid knight move, continue on Bool_Return = True break elif piece_type.lower() == "p": if ((piece_type == "p" and playername == "p") or (piece_type == "P" and playername == "a")): # they own the pawn piece # check whether it is going diagonal print("Owns piece") print(x, y, newx, newy) # whether the pawn is moving upwards or downwards, depending on whether it is the AI or Player if playername == "p": offset_val = x - 1 else: offset_val = x + 1 if (newx == offset_val and newy == (y + 1)) or (newx == offset_val and newy == (y - 1)): # check whether there is an enemy there print("Checking diagonal") print("New Piece is " + new_piece_type) print("Board State: " + str(board)) if playername == "p": if new_piece_type == "K" or new_piece_type == "P": Bool_Return = True elif playername == "a": if new_piece_type == "k" or new_piece_type == "p": Bool_Return = True elif (newx == offset_val and newy == y): # check whether it is going forward # check whether forward is whitespace or not print("Checking whitespace") if (new_piece_type == "W"): Bool_Return = True return Bool_Return def delete_piece(x, y): """ This function will remove a board piece, and do the proper logic to remove the current location of it. It also clears the piece visually on the board. :param x: **int** x coord of the piece to delete :param y: **int** y coord of the piece to delete :return: """ # get the turtle at x, y cur_turtle = DrawingBoard.board_turtles[y][x] # set the state of the board at that location to W set_piece(y, x, "W") # clear any symbols in that location cur_turtle.clear() def get_piece(x, y): """ Returns the piece from the board at the specified coord :param x: **int** x coord of the piece to delete :param y: **int** y coord of the piece to delete :return: """ return board[x][y] def set_piece(x, y, new_val): """ Sets a given piece to a new value on the current global game state :param x: **int** x coord of the piece to set :param y: **int** y coord of the piece to set :param new_val: **string** value of the piece (ex. K, k, W, P, p) :return: """ # Want to edit the global copy global board board[x][y] = new_val def game_over(): """ Checks the global game state as to whether the game is over or not and returns a value defining the state :return: **int** returns a value based upon the current state (0 = player won, 1 = ai won, 2 = stalemate, 3 = not game over) """ print("Checking whether it is game over or not") # Set constants for readability AI = 1 PLAYER = 0 AI_WON = 1 PLAYER_WON = 0 STALEMATE = 2 NOT_OVER = 3 # check whether one of the players has made two illegal moves return_val = -1 if penalty_points[AI] == 2 and penalty_points[PLAYER] == 2: return_val = STALEMATE elif penalty_points[PLAYER] == 2: return_val = AI_WON elif penalty_points[AI] == 2: return_val = PLAYER_WON if return_val == -1: # now check whether one of the players has no pawns left # loop over each pawn ai_pieces = 0 player_pieces = 0 # Check how many pawns each has, if they are all gone, they lose for row in board: for column in row: if column == "P": ai_pieces += 1 elif column == "p": player_pieces += 1 if ai_pieces == 0 and player_pieces == 0: # no pawns on both sides return_val = STALEMATE elif ai_pieces == 0: return_val = PLAYER_WON elif player_pieces == 0: return_val = AI_WON else: return_val = NOT_OVER return return_val else: # we've already come to the game over condition, return it return return_val def penalty_add(player): """ Adds a penalty point to the player specified :param player: **string** letter defining the user (p for player, a for ai) :return: """ if player == "p": penalty_index = 0 else: penalty_index = 1 # add one to the penalty, and return the new board cur_val = int(penalty_points[penalty_index]) cur_val += 1 penalty_points[penalty_index] = cur_val DrawingBoard.penalty_count() return board def knight_amount(board, player): """ Returns the amount knights a player has :param board_state: multidimensional list defining the game state :param player: **numeric** integer defining player :return: **numeric** how many knights the player owns on that game state """ knight_amt = 0 for row in board: for column in row: if player == 1 and column == "k": knight_amt += 1 elif player == 0 and column == "K": knight_amt += 1 return knight_amt """ Saving and Loading Functions """ def load_state(): """ Loads a saved game state and overwrites the global variables defining it. Then it draws out the new game state to allow the player to continue playing :return: """ try: global penalty_points, board, moveOffset, depth_amt file_obj = open("saved_board.apoc", "r") penalty_line = file_obj.readline().split(" ") penalty_points = [int(penalty_line[0]), int(penalty_line[1])] depth_amt = int(file_obj.readline()) board_new_data = [] for line in file_obj: split_data = line.replace("\n", "").split(" ") board_new_data.append(split_data) board = board_new_data # now we need to clear the screen and set the colour of it DrawingBoard.screen.clear() DrawingBoard.screen.bgcolor("#4A4A4A") # draw out the board and penalty system DrawingBoard.draw_board() DrawingBoard.penalty_count() # bind the event handlers again DrawingBoard.screen.onclick(onclick_board_handler) DrawingBoard.screen.onkeyrelease(save_state, "s") DrawingBoard.screen.onkeyrelease(load_state, "l") DrawingBoard.screen.listen() # reset messages offset location moveOffset = (DrawingBoard.BOARD_DIMENSION/2) - (DrawingBoard.TEXT_HEIGHT/0.7) - (DrawingBoard.PENALTY_TEXT_HEIGHT * 1.5) DrawingBoard.message_queue("Loaded Board") file_obj.close() except: print("There was an error loading the board") DrawingBoard.message_queue("Error Loading") def save_state(): """ Saves the global game state of the board and penalty points to a file :return: """ # we don't want to let them save while a pawn is redeploying (can cause game mechanics issues) if highlight_params[3] is False: try: file_obj = open("saved_board.apoc", "w") # the file is just a single line defining the state line_to_write = str(penalty_points[0]) + " " + str(penalty_points[1]) + "\n" #store the depth amt (difficulty) line_to_write += str(depth_amt) for line in board: line_to_write += "\n" + " ".join(line) file_obj.write(line_to_write) DrawingBoard.message_queue("Saved Board") file_obj.close() except: print("There was an error saving the board") message_queue("Error Saving") """ Click Handler Functions """ def onclick_board_handler(x, y): """ Handles click events on the board and figures out how to deal with the game state :param x: **numeric** x coord of the screen click :param y: **numeric** y coord of the sreen click :return: """ global board TOP_LEFT_X = DrawingBoard.box_locations[0][0][0] BOTTOM_LEFT_X = DrawingBoard.box_locations[4][4][0] BOX_WIDTH = DrawingBoard.BOARD_DIMENSION/5 TOP_LEFT_Y = DrawingBoard.box_locations[0][0][1] BOTTOM_RIGHT_Y = DrawingBoard.box_locations[4][4][1] HIGHLIGHT_TURTLE = 0 LAST_CLICK_COLUMN = 1 LAST_CLICK_ROW = 2 REDEPLOYING_PAWN = 3 X_COORD = 0 Y_COORD = 1 # check whether they clicked inside the board if TOP_LEFT_X < x < (BOTTOM_LEFT_X + BOX_WIDTH) and (BOTTOM_RIGHT_Y - BOX_WIDTH) < y < TOP_LEFT_Y: # Want to edit the global copies of these vars global highlight_params, box_selected, board # Check whether a box is already highlighted, if so, clear that turtle if highlight_params[HIGHLIGHT_TURTLE] != 0: # already selected highlight_params[HIGHLIGHT_TURTLE].clear() # create new turtle for highlighting squares New_Highlight_Turtle = create_default_turtle("#007AFF") highlight_params[HIGHLIGHT_TURTLE] = New_Highlight_Turtle row = 0 column = 0 for current_row in DrawingBoard.box_locations: row += 1 for current_box in current_row: column += 1 if (current_box[X_COORD] + BOX_WIDTH) > x > current_box[X_COORD] and current_box[Y_COORD] > y > (current_box[Y_COORD] - BOX_WIDTH): # They clicked in this box if column != highlight_params[LAST_CLICK_COLUMN] or row != highlight_params[LAST_CLICK_ROW]: # They clicked on a different square than last time if box_selected == 1 and not highlight_params[REDEPLOYING_PAWN]: # move the piece, a move was made process_turn(row, column, current_box) # Check whether it is game over game_state = game_over() if game_state != 3: DrawingBoard.game_end_screen(game_state) print_board() elif highlight_params[REDEPLOYING_PAWN] is True and get_piece(row - 1, column - 1) == "W": print("The user wants to redeploy the pawn, making the move") redeploy_pawn(column, row) elif (get_piece(row - 1, column - 1) == "k" or get_piece(row - 1, column - 1) == "p") and highlight_params[REDEPLOYING_PAWN] is False: # only let the user select tiles it owns play_sound("mouseDeselect.wav") DrawingBoard.select_tile(New_Highlight_Turtle, current_box, column, row) else: if highlight_params[REDEPLOYING_PAWN] is False: play_sound("mouseDeselect.wav") print("deselected same box") reset_highlight_params() else: print("You must redeploy to whitespace") column = 0 else: # They didn't click on the board, check whether they clicked on a button for button in buttons: if button.check_clicked(x, y): button.execute_function() def redeploy_pawn(column, row): """ Redeploys the users given pawn to the row and column :param column: **int** column to move the pawn to :param row: **int** row to move the pawn to :return: """ global highlight_params LAST_CLICK_COLUMN = 1 LAST_CLICK_ROW = 2 REDEPLOY_TURTLE = 4 execute_move((highlight_params[LAST_CLICK_COLUMN] - 1), (highlight_params[LAST_CLICK_ROW] - 1), (column - 1), (row - 1), "♙", "p", True) highlight_params[REDEPLOY_TURTLE].clear() reset_highlight_params() # rebind the saving and loading DrawingBoard.screen.onkeyrelease(save_state, "s") DrawingBoard.screen.onkeyrelease(load_state, "l") def process_turn(row, column, current_box): """ Processes a given valid turn for the player and ai, also calls the AI to generate its move here :param row: **int** Row the user wants the piece to move to :param column: **int** Column the user wants the piece to move to :param current_box: **list** Defines the [x, y] coords of the box :return: """ # process turn global board HIGHLIGHT_TURTLE = 0 LAST_CLICK_COLUMN = 1 LAST_CLICK_ROW = 2 REDEPLOYING_PAWN = 3 REDEPLOY_TURTLE = 4 X_COORD = 0 Y_COORD = 1 AI = 0 PLAYER = 1 screen = DrawingBoard.screen # we don't want to let them click again while the AI move is being generated screen.onclick(None) # generate the AI move DrawingBoard.message_queue("Generating AI Move") print("GENERATING MINIMAX AI MOVE") # Generate the AI move using the global depth level AI_obj = AIMove(board) generated_ai = AI_obj.findmove(depth_amt) # The AI didn't find a move that it determined it would win from, we lower its depth level until one is found if generated_ai[1] == float("-infinity"): # it didn't find a move that seemed promising at this depth level, lets try to use lower depth levels for depth in range(depth_amt-1, 0, -1): print("Generating at a depth level of " + str(depth)) generated_ai = AI_obj.findmove(depth) if generated_ai[1] != float("-infinity"): # we found a move that could work, break out of the loop break if generated_ai[1] == float("-infinity"): # just add a penalty point, we've found absolutely no valid moves, oh well :( # forcing a penalty generated_ai[0] = False print(generated_ai) # Set the AI move to the actual move and not the score value ai_val = generated_ai[0] print("AI MOVE: " + str(ai_val)) if ai_val is not False: ai_val = ai_val[0] ai_type_val = get_piece(ai_val[0], ai_val[1]) else: ai_type_val = "W" print("DONE GENERATING MINIMAX AI MOVE") # Values are minus 1 since the board is from 0-4, not 1-5 player_validity = valid_move((highlight_params[LAST_CLICK_ROW] - 1), (highlight_params[LAST_CLICK_COLUMN] - 1), (row - 1), (column - 1), "p") player_type_val = get_piece((highlight_params[LAST_CLICK_ROW] - 1), (highlight_params[LAST_CLICK_COLUMN] - 1)) # check whether to upgrade the pawn to knight for the AI if ai_val is not False and ai_type_val == "P" and ai_val[2] == 4 and knight_amount(board, AI) < 2: print("Upgraded AI pawn to knight") board[ai_val[0]][ai_val[1]] = "K" process_movements(ai_val, player_validity, row, column) # rebind the onscreenclick since the user cannot click fast enough now to influence the game screen.onclick(onclick_board_handler) # check whether the player has moved to the end row with a pawn if player_type_val == "p" and (row - 1) == 0 and player_validity is True: print("Player pawn got to the last rank, checking how many knights they have") if knight_amount(board, PLAYER) >= 2: redeploy_player_pawn(current_box, row, column) else: print("Changing piece to a knight") execute_move((highlight_params[LAST_CLICK_COLUMN] - 1), (highlight_params[LAST_CLICK_ROW] - 1), column - 1, row - 1, "♘", "k", False) reset_highlight_params() else: reset_highlight_params() # check whether the AI deleted a piece when redeploying if ai_val is not False and len(generated_ai[0][1]) > 0: print(generated_ai[0][1]) redeploy_location = generated_ai[0][1] delete_piece(redeploy_location[3], redeploy_location[2]) def process_movements(ai_val, player_validity, row, column): global board LAST_CLICK_COLUMN = 1 LAST_CLICK_ROW = 2 if ai_val is not False and player_validity is True: # both made valid moves, we'll process them move_piece((highlight_params[LAST_CLICK_COLUMN] - 1), (highlight_params[LAST_CLICK_ROW] - 1), (column - 1), (row - 1), ai_val[1], ai_val[0], ai_val[3], ai_val[2]) elif ai_val is False and player_validity is False: print("AI and Player Penalty") DrawingBoard.message_queue("Player Penalty") DrawingBoard.message_queue("AI Penalty") board = penalty_add("a") board = penalty_add("p") elif ai_val is False: # give the ai a penalty, and process the move print("AI Penalty") DrawingBoard.message_queue("AI Penalty") board = penalty_add("a") move_piece((highlight_params[LAST_CLICK_COLUMN] - 1), (highlight_params[LAST_CLICK_ROW] - 1), (column - 1), (row - 1), -1, 0, 0, 0) elif player_validity is False: print("Player Penalty") DrawingBoard.message_queue("Player Penalty") board = penalty_add("p") move_piece(-1, 0, 0, 0, ai_val[1], ai_val[0], ai_val[3], ai_val[2]) def redeploy_player_pawn(current_box, row, column): global highlight_params, box_selected HIGHLIGHT_TURTLE = 0 LAST_CLICK_COLUMN = 1 LAST_CLICK_ROW = 2 REDEPLOYING_PAWN = 3 REDEPLOY_TURTLE = 4 print("Allowing them to redeploy pawn, disabling saving") DrawingBoard.screen.onkeyrelease(None, "s") DrawingBoard.screen.onkeyrelease(None, "l") highlight_params[REDEPLOYING_PAWN] = True highlight_params[LAST_CLICK_COLUMN] = column highlight_params[LAST_CLICK_ROW] = row box_selected = 0 new_redeploy_turtle = turtle.Turtle() highlight_params[REDEPLOY_TURTLE] = new_redeploy_turtle new_redeploy_turtle._tracer(False) new_redeploy_turtle.hideturtle() new_redeploy_turtle.color("#FF9500") new_redeploy_turtle.up() new_redeploy_turtle.goto(current_box[0], current_box[1]) new_redeploy_turtle.down() for i2 in range(4): new_redeploy_turtle.forward(DrawingBoard.BOARD_DIMENSION/5) new_redeploy_turtle.right(90) new_redeploy_turtle.up() DrawingBoard.message_queue("Redeploy Pawn to") DrawingBoard.message_queue("a Vacant Square") def reset_highlight_params(): """ Reset the values of highlight_params and box_selected :return: """ global highlight_params, box_selected highlight_params[0] = 0 highlight_params[1] = 0 highlight_params[2] = 0 highlight_params[3] = False box_selected = 0 def button_event(x, y): """ Handles user click events on screens that have buttons :param x: **numeric** The x coordinate of a user's click :param y: **numeric** The y coordinate of a user's click :return: """ for button in buttons: if button.check_clicked(x, y): button.execute_function() """ Game State Functions """ def reset_game_state(): """ Resets the game state for a new game, rewrites variables :return: """ global board, penalty_points board = [["K", "P", "P", "P", "K"], ["P", "W", "W", "W", "P"], ["W", "W", "W", "W", "W"], ["p", "W", "W", "W", "p"], ["k", "p", "p", "p", "k"]] penalty_points = [0, 0] def modify_difficulty(level): """ Modifies a global to change the ai difficulty for future move calculations :param level: **numeric** Specifies the difficulty level (ai move depth) :return: """ global depth_amt depth_amt = level """ Miscellaneous Functions """ def main_menu(): """ Main function call, immediately draws the main menu screen and sets the proper scaling values of the screen :return: """ # print out the "Apocalypse" text into the console (not needed, but a nice commemoration of our roots) print(""" ( ( )\ ) )\( ( ((((_)( ` ) ( ( ( /(((_)\ ) ` ) ( ))\\ )\ _ )\ /(/( )\ )\ )(_) )_(()/( /(/( )\ /((_) (_)_\(_|(_)_\((_) ((_| (_)_| |(_)|(_)_\((__|__)) / _ \ | '_ \) _ \/ _|/ _` | | || | '_ \|_-< -_) /_/ \_\| .__/\___/\__|\__,_|_|\_, | .__//__|___| |_| |__/|_| """) global DrawingBoard DrawingBoard = BoardDraw() DrawingBoard.draw_main_screen() turtle.done() def play_sound(sound_file): """ Plays a given sound on most platforms :param sound_file: **string** name of the sound to play :return: """ # Since we can't use external libraries, this solution works: http://stackoverflow.com/a/311634 if platform.system() == "Windows": winsound.PlaySound(sound_file, winsound.SND_FILENAME) elif platform.system() == "Darwin": os.system("afplay " + sound_file + "&") elif platform.system() == "Linux": s = waveOpen(sound_file,'rb') (nc,sw,fr,nf,comptype, compname) = s.getparams( ) dsp = ossOpen('/dev/dsp','w') try: from ossaudiodev import AFMT_S16_NE except ImportError: if byteorder == "little": AFMT_S16_NE = ossaudiodev.AFMT_S16_LE else: AFMT_S16_NE = ossaudiodev.AFMT_S16_BE dsp.setparameters(AFMT_S16_NE, nc, fr) data = s.readframes(nf) s.close() dsp.write(data) dsp.close() else: print("Sounds not supported") def print_board(): print("Board:") for row in range(5): print(board[row]) """ Main Function Call """ if __name__ == '__main__': main_menu()
<filename>src/features/userActivityMonitoring/redux/actions/communication.ts<gh_stars>1-10 import { makeCommunicationActionCreators } from 'shared/helpers/redux/index'; import * as NS from '../../namespace'; /* tslint:disable:max-line-length */ export const { execute: setLastActivity, completed: setLastActivityCompleted, failed: setLastActivityFailed } = makeCommunicationActionCreators<NS.ISetLastActivity, NS.ISetLastActivityCompleted, NS.ISetLastActivityFailed>( 'USER_ACTIVITY_MONITORING:SET_LAST_ACTIVITY', 'USER_ACTIVITY_MONITORING:SET_LAST_ACTIVITY_COMPLETED', 'USER_ACTIVITY_MONITORING:SET_LAST_ACTIVITY_FAILED', );
// Copyright <NAME> 2006. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/parameter/config.hpp> #if (BOOST_PARAMETER_MAX_ARITY < 4) #error Define BOOST_PARAMETER_MAX_ARITY as 4 or greater. #endif namespace test { struct X { }; struct Y : X { }; } // namespace test #if defined(BOOST_PARAMETER_CAN_USE_MP11) #include <type_traits> #else #include <boost/mpl/bool.hpp> #include <boost/mpl/if.hpp> #include <boost/type_traits/is_base_of.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/type_traits/remove_reference.hpp> #endif namespace test { struct Z { template <typename T, typename Args> #if defined(BOOST_PARAMETER_CAN_USE_MP11) using fn = std::is_base_of< X , typename std::remove_const< typename std::remove_reference<T>::type >::type >; #else struct apply : boost::mpl::if_< boost::is_base_of< X , typename boost::remove_const< typename boost::remove_reference<T>::type >::type > , boost::mpl::true_ , boost::mpl::false_ >::type { }; #endif // BOOST_PARAMETER_CAN_USE_MP11 }; } // namespace test #include <boost/parameter/template_keyword.hpp> namespace test { template <typename T = int> struct a0_is : boost::parameter::template_keyword<test::a0_is<>,T> { }; template <typename T = int> struct a1_is : boost::parameter::template_keyword<test::a1_is<>,T> { }; template <typename T = int> struct a2_is : boost::parameter::template_keyword<test::a2_is<>,T> { }; template <typename T = int> struct a3_is : boost::parameter::template_keyword<test::a3_is<>,T> { }; } // namespace test #include <boost/parameter/parameters.hpp> #include <boost/parameter/optional.hpp> #include <boost/parameter/deduced.hpp> #include <boost/parameter/binding.hpp> namespace test { template < typename A0 = boost::parameter::void_ , typename A1 = boost::parameter::void_ , typename A2 = boost::parameter::void_ , typename A3 = boost::parameter::void_ > struct with_ntp { typedef typename boost::parameter::parameters< test::a0_is<> , test::a1_is<> , test::a2_is<> , boost::parameter::optional< boost::parameter::deduced<test::a3_is<> > , Z > >::BOOST_NESTED_TEMPLATE bind< A0 , A1 , A2 , A3 #if BOOST_WORKAROUND(BOOST_BORLANDC, BOOST_TESTED_AT(0x564)) , boost::parameter::void_ #endif >::type args; typedef typename boost::parameter::binding< args , test::a0_is<> , void* >::type a0; typedef typename boost::parameter::binding< args , test::a1_is<> , void* >::type a1; typedef typename boost::parameter::binding< args , test::a2_is<> , void* >::type a2; typedef typename boost::parameter::binding< args , test::a3_is<> , void* >::type a3; typedef void(*type)(a0, a1, a2, a3); }; } // namespace test #include <boost/mpl/aux_/test.hpp> #if !defined(BOOST_PARAMETER_CAN_USE_MP11) #include <boost/mpl/assert.hpp> #include <boost/type_traits/is_same.hpp> #endif MPL_TEST_CASE() { #if defined(BOOST_PARAMETER_CAN_USE_MP11) static_assert( std::is_same< test::with_ntp<>::type , void(*)(void*, void*, void*, void*) >::value , "type must be void(*)(void*, void*, void*, void*)" ); static_assert( std::is_same< test::with_ntp<test::a2_is<int> >::type , void(*)(void*, void*, int, void*) >::value , "type must be void(*)(void*, void*, int, void*)" ); static_assert( std::is_same< test::with_ntp<test::a1_is<int> >::type , void(*)(void*, int, void*, void*) >::value , "type must be void(*)(void*, int, void*, void*)" ); static_assert( std::is_same< test::with_ntp<test::a2_is<int const>,test::a1_is<float> >::type , void(*)(void*, float, int const, void*) >::value , "type must be void(*)(void*, float, int const, void*)" ); static_assert( std::is_same< test::with_ntp<int const>::type , void(*)(int const, void*, void*, void*) >::value , "type must be void(*)(int const, void*, void*, void*)" ); static_assert( std::is_same< test::with_ntp<int,float>::type , void(*)(int, float, void*, void*) >::value , "type must be void(*)(int, float, void*, void*)" ); static_assert( std::is_same< test::with_ntp<int,float,char>::type , void(*)(int, float, char, void*) >::value , "type must be void(*)(int, float, char, void*)" ); static_assert( std::is_same< test::with_ntp<test::a0_is<int>,test::Y>::type , void(*)(int, void*, void*, test::Y) >::value , "type must be must be void(*)(int, void*, void*, test::Y)" ); static_assert( std::is_same< test::with_ntp<int&,test::a2_is<char>,test::Y>::type , void(*)(int&, void*, char, test::Y) >::value , "type must be void(*)(int&, void*, char, test::Y)" ); #else // !defined(BOOST_PARAMETER_CAN_USE_MP11) BOOST_MPL_ASSERT(( boost::mpl::if_< boost::is_same< test::with_ntp<>::type , void(*)(void*, void*, void*, void*) > , boost::mpl::true_ , boost::mpl::false_ >::type )); BOOST_MPL_ASSERT(( boost::mpl::if_< boost::is_same< test::with_ntp<test::a2_is<int> >::type , void(*)(void*, void*, int, void*) > , boost::mpl::true_ , boost::mpl::false_ >::type )); BOOST_MPL_ASSERT(( boost::mpl::if_< boost::is_same< test::with_ntp<test::a1_is<int> >::type , void(*)(void*, int, void*, void*) > , boost::mpl::true_ , boost::mpl::false_ >::type )); BOOST_MPL_ASSERT(( boost::mpl::if_< boost::is_same< test::with_ntp< test::a2_is<int const> , test::a1_is<float> >::type , void(*)(void*, float, int const, void*) > , boost::mpl::true_ , boost::mpl::false_ >::type )); BOOST_MPL_ASSERT(( boost::mpl::if_< boost::is_same< test::with_ntp<int const>::type , void(*)(int const, void*, void*, void*) > , boost::mpl::true_ , boost::mpl::false_ >::type )); BOOST_MPL_ASSERT(( boost::mpl::if_< boost::is_same< test::with_ntp<int,float>::type , void(*)(int, float, void*, void*) > , boost::mpl::true_ , boost::mpl::false_ >::type )); BOOST_MPL_ASSERT(( boost::mpl::if_< boost::is_same< test::with_ntp<int,float,char>::type , void(*)(int, float, char, void*) > , boost::mpl::true_ , boost::mpl::false_ >::type )); BOOST_MPL_ASSERT(( boost::mpl::if_< boost::is_same< test::with_ntp<test::a0_is<int>,test::Y>::type , void(*)(int, void*, void*, test::Y) > , boost::mpl::true_ , boost::mpl::false_ >::type )); BOOST_MPL_ASSERT(( boost::mpl::if_< boost::is_same< test::with_ntp<int&,test::a2_is<char>,test::Y>::type , void(*)(int&, void*, char, test::Y) > , boost::mpl::true_ , boost::mpl::false_ >::type )); #endif // BOOST_PARAMETER_CAN_USE_MP11 typedef int test_array[1]; typedef void(*test_function)(); #if defined(BOOST_PARAMETER_CAN_USE_MP11) static_assert( std::is_same< test::with_ntp<test_array,test_function>::type , void(*)(test_array&, test_function, void*, void*) >::value , "type must be void(*)(test_array&, test_function, void*, void*)" ); #else BOOST_MPL_ASSERT(( boost::mpl::if_< boost::is_same< test::with_ntp<test_array,test_function>::type , void(*)(test_array&, test_function, void*, void*) > , boost::mpl::true_ , boost::mpl::false_ >::type )); #endif }
<reponame>Azeirah/note-taking-experimentation<filename>lib/disableContextMenu.js function disableContextMenu(element) { element.addEventListener("contextmenu", function (event) { event.preventDefault(); return false; }); }
import { WizardContext } from 'react-albus'; import WelcomeAnimation from 'scenes/WelcomeAnimation/WelcomeAnimation'; function Welcome({ next }: WizardContext) { return <WelcomeAnimation next={next} />; } export default Welcome;
mkdir target # Execute static code analysis with swiftlint swiftlint > target/swiftlint-result.xml
#!/bin/bash set -e -x -o pipefail DUB_FLAGS=${DUB_FLAGS:-} # Check for trailing whitespace" grep -nrI --include='*.d' '\s$' . && (echo "Trailing whitespace found"; exit 1) # test for successful release build dub build -b release --compiler=$DC -c $CONFIG $DUB_FLAGS # test for successful 32-bit build if [ "$DC" == "dmd" ]; then dub build --arch=x86 -c $CONFIG $DUB_FLAGS fi dub test --compiler=$DC -c $CONFIG $DUB_FLAGS if [ ${BUILD_EXAMPLE=1} -eq 1 ]; then for ex in $(\ls -1 examples/); do echo "[INFO] Building example $ex" (cd examples/$ex && dub build --compiler=$DC --override-config vibe-core/$CONFIG && dub clean) done fi if [ ${RUN_TEST=1} -eq 1 ]; then for ex in `\ls -1 tests/*.d`; do script="${ex%.d}.sh" if [ -e "$script" ]; then echo "[INFO] Running test scipt $script" (cd tests && "./${script:6}") else echo "[INFO] Running test $ex" dub --temp-build --compiler=$DC --single $ex --override-config vibe-core/$CONFIG fi done fi
#!/bin/bash fw_depends zeromq RETCODE=$(fw_exists ${IROOT}/mongrel2.installed) [ ! "$RETCODE" == 0 ] || { \ source $IROOT/mongrel2.installed return 0; } MONGREL2=$IROOT/mongrel2 # TODO: Get away from apt-get # Dependencies sudo apt-get install -y sqlite3 libsqlite3-dev uuid uuid-runtime uuid-dev # Update linker cache sudo ldconfig -v fw_get -o mongrel2.tar.gz https://github.com/zedshaw/mongrel2/tarball/v1.8.1 fw_untar mongrel2.tar.gz # mongrel2 untars into this folder mv zedshaw-mongrel2-aa2ecf8 mongrel2-install # for zmq4, we update the following file manually (not in v1.8.1) fw_get -O https://raw.github.com/zedshaw/mongrel2/9b565eeea003783c47502c2d350b99c9684ce97c/src/zmq_compat.h mv -f zmq_compat.h mongrel2-install/src/ cd mongrel2-install # Do this in a subshell to avoid leaking env variables ( export PREFIX=${IROOT}/mongrel2 export OPTFLAGS="-I$IROOT/zeromq-4.0.3/include" export OPTLIBS="-Wl,-rpath,$IROOT/zeromq-4.0.3/lib -L$IROOT/zeromq-4.0.3/lib" make clean all make install ) echo "export MONGREL2_HOME=${MONGREL2}" > $IROOT/mongrel2.installed echo -e "export PATH=\$MONGREL2/bin:\$PATH" >> $IROOT/mongrel2.installed source $IROOT/mongrel2.installed
#!/bin/sh . /usr/share/openclash/ruby.sh LOG_FILE="/tmp/openclash.log" LOGTIME=$(echo $(date "+%Y-%m-%d %H:%M:%S")) dns_advanced_setting=$(uci -q get openclash.config.dns_advanced_setting) if [ "${14}" != "1" ]; then controller_address="0.0.0.0" bind_address="*" else controller_address=${11} bind_address=${11} fi if [ -n "$(ruby_read "$7" "['tun']")" ]; then if [ -n "$(ruby_read "$7" "['tun']['device-url']")" ]; then if [ "${15}" -eq 1 ] || [ "${15}" -eq 3 ]; then uci set openclash.config.config_reload=0 fi else uci set openclash.config.config_reload=0 fi else if [ -n "${15}" ]; then uci set openclash.config.config_reload=0 fi fi if [ -z "${15}" ]; then en_mode_tun=0 else en_mode_tun=${15} fi if [ -z "${16}" ]; then stack_type=system else stack_type=${16} fi if [ "$(ruby_read "$7" "['external-controller']")" != "$controller_address:$5" ]; then uci set openclash.config.config_reload=0 fi if [ "$(ruby_read "$7" "['secret']")" != "$4" ]; then uci set openclash.config.config_reload=0 fi uci commit openclash ruby -ryaml -E UTF-8 -e " begin Value = YAML.load_file('$7'); rescue Exception => e puts '${LOGTIME} Error: Load File Error,【' + e.message + '】' end begin Value['redir-port']=$6; Value['tproxy-port']=${20}; Value['port']=$9; Value['socks-port']=${10}; Value['mixed-port']=${19}; Value['mode']='${13}'; Value['log-level']='${12}'; Value['allow-lan']=true; Value['external-controller']='$controller_address:$5'; Value['secret']='$4'; Value['bind-address']='$bind_address'; Value['external-ui']='/usr/share/openclash/dashboard'; if not Value.key?('dns') then Value_1={'dns'=>{'enable'=>true}} Value['dns']=Value_1['dns'] else Value['dns']['enable']=true end; if $8 == 1 then Value['ipv6']=true else Value['ipv6']=false end; if ${21} == 1 then Value['dns']['ipv6']=true else Value['dns']['ipv6']=false end; Value['dns']['enhanced-mode']='$2'; if '$2' == 'fake-ip' then Value['dns']['fake-ip-range']='198.18.0.1/16' else Value['dns'].delete('fake-ip-range') end; if ${21} != 1 then Value['dns']['listen']='127.0.0.1:${17}' else Value['dns']['listen']='0.0.0.0:${17}' end; Value_2={'tun'=>{'enable'=>true}}; if $en_mode_tun == 1 or $en_mode_tun == 3 then Value['tun']=Value_2['tun'] Value['tun']['stack']='$stack_type' Value_2={'dns-hijack'=>['tcp://8.8.8.8:53','tcp://8.8.4.4:53']} Value['tun'].merge!(Value_2) elsif $en_mode_tun == 2 Value['tun']=Value_2['tun'] Value['tun']['device-url']='dev://utun' Value['tun']['dns-listen']='0.0.0.0:53' elsif $en_mode_tun == 0 if Value.key?('tun') then Value.delete('tun') end end; if not Value.key?('profile') then Value_3={'profile'=>{'store-selected'=>true}} Value['profile']=Value_3['profile'] else Value['profile']['store-selected']=true end; if ${22} != 1 then Value['profile']['store-fakeip']=false else Value['profile']['store-fakeip']=true end; rescue Exception => e puts '${LOGTIME} Error: Set General Error,【' + e.message + '】' end begin #添加自定义Hosts设置 if '$2' == 'redir-host' then if File::exist?('/etc/openclash/custom/openclash_custom_hosts.list') then Value_3 = YAML.load_file('/etc/openclash/custom/openclash_custom_hosts.list') if Value_3 != false then Value['dns']['use-hosts']=true if Value.has_key?('hosts') and not Value['hosts'].to_a.empty? then Value['hosts'].merge!(Value_3) Value['hosts'].uniq else Value['hosts']=Value_3 end end end end; rescue Exception => e puts '${LOGTIME} Error: Set Hosts Rules Error,【' + e.message + '】' end begin #fake-ip-filter if '$2' == 'fake-ip' then if File::exist?('/tmp/openclash_fake_filter.list') then Value_4 = YAML.load_file('/tmp/openclash_fake_filter.list') if Value_4 != false then if Value['dns'].has_key?('fake-ip-filter') and not Value['dns']['fake-ip-filter'].to_a.empty? then Value_5 = Value_4['fake-ip-filter'].reverse! Value_5.each{|x| Value['dns']['fake-ip-filter'].insert(-1,x)} else Value['dns']['fake-ip-filter']=Value_4['fake-ip-filter'] end Value['dns']['fake-ip-filter']=Value['dns']['fake-ip-filter'].uniq end end if ${23} == 1 then if Value['dns'].has_key?('fake-ip-filter') and not Value['dns']['fake-ip-filter'].to_a.empty? then Value['dns']['fake-ip-filter'].insert(-1,'+.nflxvideo.net') Value['dns']['fake-ip-filter']=Value['dns']['fake-ip-filter'].uniq else Value['dns'].merge!({'fake-ip-filter'=>['+.nflxvideo.net']}) end end end; rescue Exception => e puts '${LOGTIME} Error: Set Fake-IP-Filter Error,【' + e.message + '】' end begin #nameserver-policy if '$dns_advanced_setting' == '1' then if File::exist?('/etc/openclash/custom/openclash_custom_domain_dns_policy.list') then Value_6 = YAML.load_file('/etc/openclash/custom/openclash_custom_domain_dns_policy.list') if Value_6 != false then if Value['dns'].has_key?('nameserver-policy') and not Value['dns']['nameserver-policy'].to_a.empty? then Value['dns']['nameserver-policy'].merge!(Value_6) Value['dns']['nameserver-policy'].uniq else Value['dns']['nameserver-policy']=Value_6 end end end end; rescue Exception => e puts '${LOGTIME} Error: Set Nameserver-Policy Error,【' + e.message + '】' ensure File.open('$7','w') {|f| YAML.dump(Value, f)} end" 2>/dev/null >> $LOG_FILE
<reponame>captainwong/Tools #pragma once // CalcDlg dialog class CalcDlg : public CDialogEx { DECLARE_DYNAMIC(CalcDlg) public: CalcDlg(CWnd* pParent = nullptr); // standard constructor virtual ~CalcDlg(); // Dialog Data #ifdef AFX_DESIGN_TIME enum { IDD = IDD_DIALOG_CALC }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() CDateTimeCtrl m_date; CDateTimeCtrl m_time; CComboBox m_op; CEdit m_number; CComboBox m_unit; afx_msg void OnBnClickedButton1(); afx_msg void OnDtnDatetimechangeDatetimepickerDate(NMHDR* pNMHDR, LRESULT* pResult); afx_msg void OnDtnDatetimechangeDatetimepickerTime(NMHDR* pNMHDR, LRESULT* pResult); void calc(); public: CDateTimeCtrl m_date2; CDateTimeCtrl m_time2; afx_msg void OnCbnSelchangeComboOp(); afx_msg void OnEnChangeEditNumber(); afx_msg void OnCbnSelchangeComboUnit(); virtual BOOL OnInitDialog(); CEdit m_asms; };
<reponame>pkubiak/mdoc import unittest, sys, os sys.path.append(os.path.dirname(os.path.realpath(__file__)) + '/..') from parameterized import parameterized from mdoc.parser import tokenize class TokenizeTestCase(unittest.TestCase): @parameterized.expand([ ### COMMENTS ### # Leading and trailing whitespaces are removed from block comment ('comments/block_comment_trim', [('BLOCK_COMMENT', 'Line1\nLine2')]), # Block comments are parser eager way, from """ to next """ ('comments/block_comment_eager', SyntaxError), # Leading and trailing whitespaces are removed from inline comment ('comments/inline_comment_trim', [('INLINE_COMMENT', 'Line1')]), # Inline comment can be place next to other tokens, then their token precede them ('comments/inline_comment_order', [('INLINE_COMMENT', 'comment next to heading'), ('HEADING', 1, 'heading'), ('INLINE_COMMENT', 'guard')]), ### HEADINGS ### # Empty line is required after heading ('headings/heading_no_empty_line', SyntaxError), # Number of oppening '#' must match number of closing '#' ('headings/heading_unbalanced', SyntaxError), # Three levels of heading are supported ('headings/heading_levels', [('HEADING', 1, 'heading1'), ('HEADING', 2, 'heading2'), ('HEADING', 3, 'heading3'), ('INLINE_COMMENT', 'guard')]), ('headings/heading_level_4', SyntaxError), # Heading text must be surounded with whitespace ('headings/heading_not_surrounded', SyntaxError), # Whitespace are trimmed from heading text ('headings/heading_trim_whitespace', [('HEADING', 1, 'heading1'), ('INLINE_COMMENT', 'guard')]), ### VARIABLES ### ('variables/correct', [ ('VARIABLE', 'pi', ('FLOAT', 3.14)), ('VARIABLE', 'negative-pi', ('FLOAT', -3.141592)), ('VARIABLE', 'integer', ('INTEGER', 42)), ('VARIABLE', 'negative-int', ('INTEGER', -42)), ('VARIABLE', 'string', ('STRING', 'Hello World')), ('VARIABLE', 'bool-true', ('BOOLEAN', True)), ('VARIABLE', 'bool-false', ('BOOLEAN', False)), ('VARIABLE', 'name', ('IDENTIFIER', 'pi')), ]), # dot is decimal separator for floats ('variables/float_with_comma', SyntaxError), # leading zeros are not allowed ('variables/integer_leading_zeros', SyntaxError), ('variables/float_leading_zeros', SyntaxError), # String must be surrounded with double quotes ('variables/string_single_quote', SyntaxError), # Variables names can contain a-z, 0-9 and - ('variables/names', [ ('VARIABLE', 'x', ('INTEGER', 1)), ('VARIABLE', 'xx', ('INTEGER', 2)), ('VARIABLE', 'abc', ('INTEGER', 3)), ('VARIABLE', 'abc1', ('INTEGER', 4)), ('VARIABLE', 'a-b-c', ('INTEGER', 5)), ('VARIABLE', '007', ('INTEGER', 6)), ('VARIABLE', '42x', ('INTEGER', 7)), ]), ('variables/name_uppercase', SyntaxError), ('variables/name_underscore', SyntaxError), # Variable name can't starts or ends with '-' ('variables/name_leading_minus', SyntaxError), ('variables/name_trailing_minus', SyntaxError), # Malformed definition ('variables/malformed_space_after_dolar', SyntaxError), ('variables/malformed_space_before_colon', SyntaxError), ### WIDGETS ### # Widget require to proceded by double new line ('widgets/no_new_line', SyntaxError), # When there is no params or body, brackets can be ommited but it is not required ('widgets/no_params_no_body_01', [('WIDGET', 'widget', {}, None), ('INLINE_COMMENT', 'guard')]), ('widgets/no_params_no_body_02', [('WIDGET', 'widget', {}, None), ('INLINE_COMMENT', 'guard')]), ('widgets/no_params_no_body_03', [('WIDGET', 'widget', {}, None), ('INLINE_COMMENT', 'guard')]), ('widgets/no_params_empty_body_01', [('WIDGET', 'widget', {}, ''), ('INLINE_COMMENT', 'guard')]), ('widgets/no_params_empty_body_02', SyntaxError), ('widgets/no_params_empty_body_01', [('WIDGET', 'widget', {}, ''), ('INLINE_COMMENT', 'guard')]), # Widget with params ('widgets/inline_params', [('WIDGET', 'image', {'src': ('STRING', 'img.jpg'), 'margin': ('INTEGER', 5), 'border': ('BOOLEAN', True), 'pi': ('FLOAT', 3.14), 'parent': ('IDENTIFIER', 'root')}, None)]), ('widgets/multiline_params', [('WIDGET', 'image', {'src': ('STRING', 'img.jpg'), 'margin': ('INTEGER', 5), 'border': ('BOOLEAN', True), 'pi': ('FLOAT', 3.14), 'parent': ('IDENTIFIER', 'root')}, None)]), # Whitespaces doesn't metter ('widgets/params_whitespaces', [('WIDGET', 'image', {'src': ('STRING', 'img.jpg')}, None)]), # Widget can't contain duplicated parameters ('widgets/params_duplicated', SyntaxError), ### PARAGRAPHS ### #### Strong **xx** #### #### Italic //xx// #### #### Underline __xx__ #### #### Strikeout --xx-- #### #### Links #### #### References #### #### inline code #### #### automatic links #### #### variable interpolation #### #### char escaping #### #### sub / sup ^{} / _{} #### #### mark ==xx== #### #### smartarrows #### #### emoji #### #### LATEX $$xxx$$ #### ### ANCHORS ### ### FOOTNOTES ### ### BLOCKQUOTES ### ### LISTS ### ### OTHERS ### # Empty lines are ignored ('empty_lines', [('INLINE_COMMENT', 'guard')]), ]) def test_tokenize(self, name, output): """ Check result of tokenization on given test file. """ with open(os.path.join(os.path.dirname(__file__), 'test_cases', name + '.mdoc')) as input: text = input.read() if isinstance(output, type): with self.assertRaises(output): tokenize(text) else: self.assertEqual(tokenize(text), output) if __name__ == '__main__': unittest.main()
#!/usr/bin/env bash # Copyright 2021 The Knative Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -e set -o errexit set -o nounset set -o pipefail CLUSTER_SUFFIX=${CLUSTER_SUFFIX:-"cluster.local"} NODE_VERSION=${NODE_VERSION:-"v1.20.0"} NODE_SHA=${NODE_SHA:-"sha256:b40ecf8bcb188f6a0d0f5d406089c48588b75edc112c6f635d26be5de1c89040"} cat <<EOF | kind create cluster --config=- apiVersion: kind.x-k8s.io/v1alpha4 kind: Cluster # This is needed in order to support projected volumes with service account tokens. # See: https://kubernetes.slack.com/archives/CEKK1KTN2/p1600268272383600 kubeadmConfigPatches: - | apiVersion: kubeadm.k8s.io/v1beta2 kind: ClusterConfiguration metadata: name: config apiServer: extraArgs: "service-account-issuer": "kubernetes.default.svc" "service-account-signing-key-file": "/etc/kubernetes/pki/sa.key" networking: dnsDomain: "${CLUSTER_SUFFIX}" nodes: - role: control-plane image: kindest/node:${NODE_VERSION}@${NODE_SHA} - role: worker image: kindest/node:${NODE_VERSION}@${NODE_SHA} EOF