code
stringlengths
4
991k
repo_name
stringlengths
6
116
path
stringlengths
4
249
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
4
991k
input_ids
listlengths
502
502
token_type_ids
listlengths
502
502
attention_mask
listlengths
502
502
labels
listlengths
502
502
import { expect } from 'chai'; import { NorthwindContext } from 'common/northwind-sqlite'; import { seedNorthwindDatabase } from './helper'; describe('entitype-integration-tests > query > websql > blob', async () => { beforeEach(async function () { this.timeout(10000); await seedNorthwindDatabase(); }); it('should return Uint8Array for blob type', async () => { let ctx = new NorthwindContext(); let photo = await ctx.employees.select(x => x.photo).first(); expect(photo).to.be.instanceof(Buffer); }); });
KurtGokhan/entitype
packages/entitype-integration-tests/test/websql/blob.spec.ts
TypeScript
mit
558
[ 30522, 12324, 1063, 5987, 1065, 2013, 1005, 15775, 2072, 1005, 1025, 12324, 1063, 2167, 11101, 8663, 18209, 1065, 2013, 1005, 2691, 1013, 2167, 11101, 1011, 29296, 4221, 1005, 1025, 12324, 1063, 6534, 12131, 2705, 11101, 30524, 2013, 1005, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!doctype html> <html> <title>npm-rm</title> <meta http-equiv="content-type" value="text/html;utf-8"> <link rel="stylesheet" type="text/css" href="../../static/style.css"> <link rel="canonical" href="https://www.npmjs.org/doc/cli/npm-rm.html"> <script async=true src="../../static/toc.js"></script> <body> <div id="wrapper"> <h1><a href="../cli/npm-rm.html">npm-rm</a></h1> <p>Remove a package</p> <h2 id="synopsis">SYNOPSIS</h2> <pre><code>npm rm &lt;name&gt; npm r &lt;name&gt; npm uninstall &lt;name&gt; npm un &lt;name&gt; </code></pre><h2 id="description">DESCRIPTION</h2> <p>This uninstalls a package, completely removing everything npm installed on its behalf.</p> <h2 id="see-also">SEE ALSO</h2> <ul> <li><a href="../cli/npm-prune.html">npm-prune(1)</a></li> <li><a href="../cli/npm-install.html">npm-install(1)</a></li> <li><a href="../files/npm-folders.html">npm-folders(5)</a></li> <li><a href="../cli/npm-config.html">npm-config(1)</a></li> <li><a href="../misc/npm-config.html">npm-config(7)</a></li> <li><a href="../files/npmrc.html">npmrc(5)</a></li> </ul> </div> <table border=0 cellspacing=0 cellpadding=0 id=npmlogo> <tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18>&nbsp;</td></tr> <tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td><td style="width:40px;height:10px;background:#fff" colspan=4>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4>&nbsp;</td><td style="width:40px;height:10px;background:#fff" colspan=4>&nbsp;</td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td><td colspan=6 style="width:60px;height:10px;background:#fff">&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4>&nbsp;</td></tr> <tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2>&nbsp;</td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:#fff" rowspan=3>&nbsp;</td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3>&nbsp;</td></tr> <tr><td style="width:10px;height:10px;background:#fff" rowspan=2>&nbsp;</td></tr> <tr><td style="width:10px;height:10px;background:#fff">&nbsp;</td></tr> <tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6>&nbsp;</td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)">&nbsp;</td></tr> <tr><td colspan=5 style="width:50px;height:10px;background:#fff">&nbsp;</td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4>&nbsp;</td><td style="width:90px;height:10px;background:#fff" colspan=9>&nbsp;</td></tr> </table> <p id="footer">npm-rm &mdash; npm@2.14.18</p>
justathoughtor2/atomicApe
cygwin/bin/node_modules/phonegap/node_modules/cordova/node_modules/cordova-lib/node_modules/npm/html/doc/cli/npm-rm.html
HTML
gpl-3.0
3,248
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 1028, 1026, 2516, 1028, 27937, 2213, 1011, 28549, 1026, 1013, 2516, 1028, 1026, 18804, 8299, 1011, 1041, 15549, 2615, 1027, 1000, 4180, 1011, 2828, 1000, 3643, 1027, 1000, 3793, 1013,...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* @(#) src/java/javax/sip/header/TimeStampHeader.java <p> Copyright &copy; 2008-2015 Monavacon Limited <a href="http://www.monavacon.com/">&lt;http://www.monavacon.com/&gt;</a>. <br> Copyright &copy; 2001-2008 OpenSS7 Corporation <a href="http://www.openss7.com/">&lt;http://www.openss7.com/&gt;</a>. <br> Copyright &copy; 1997-2001 Brian F. G. Bidulock <a href="mailto:bidulock@openss7.org">&lt;bidulock@openss7.org&gt;</a>. <p> All Rights Reserved. <p> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, version 3 of the license. <p> This program is distributed in the hope that it will be useful, but <b>WITHOUT ANY WARRANTY</b>; without even the implied warranty of <b>MERCHANTABILITY</b> or <b>FITNESS FOR A PARTICULAR PURPOSE</b>. See the GNU Affero General Public License for more details. <p> You should have received a copy of the GNU Affero General Public License along with this program. If not, see <a href="http://www.gnu.org/licenses/">&lt;http://www.gnu.org/licenses/&gt</a>, or write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. <p> <em>U.S. GOVERNMENT RESTRICTED RIGHTS</em>. If you are licensing this Software on behalf of the U.S. Government ("Government"), the following provisions apply to you. If the Software is supplied by the Department of Defense ("DoD"), it is classified as "Commercial Computer Software" under paragraph 252.227-7014 of the DoD Supplement to the Federal Acquisition Regulations ("DFARS") (or any successor regulations) and the Government is acquiring only the license rights granted herein (the license rights customarily provided to non-Government users). If the Software is supplied to any unit or agency of the Government other than DoD, it is classified as "Restricted Computer Software" and the Government's rights in the Software are defined in paragraph 52.227-19 of the Federal Acquisition Regulations ("FAR") (or any successor regulations) or, in the cases of NASA, in paragraph 18.52.227-86 of the NASA Supplement to the FAR (or any successor regulations). <p> Commercial licensing and support of this software is available from OpenSS7 Corporation at a fee. See <a href="http://www.openss7.com/">http://www.openss7.com/</a> */ package javax.sip.header; import javax.sip.*; /** The Timestamp header field describes when the UAC sent the request to the UAS. When a 100 (Trying) response is generated, any Timestamp header field present in the request MUST be copied into this 100 (Trying) response. If there is a delay in generating the response, the UAS SHOULD add a delay value into the Timestamp value in the response. This value MUST contain the difference between the time of sending of the response and receipt of the request, measured in seconds. Although there is no normative behavior defined here that makes use of the header, it allows for extensions or SIP applications to obtain RTT estimates, that may be used to adjust the timeout value for retransmissions. <p> For Example: <br> <code> Timestamp: 54 </code> @version 1.2.2 @author Monavacon Limited */ public interface TimeStampHeader extends Header { /** Name of TimeStampHeader. */ static final java.lang.String NAME = "Timestamp"; /** @deprecated This method is replaced with setTimeStamp(float). Sets the timestamp value of this TimeStampHeader to the new timestamp value passed to this method. @param timeStamp The new float timestamp value. @exception InvalidArgumentException Thrown when the timestamp value argument is a negative value. */ void setTimeStamp(float timeStamp) throws InvalidArgumentException; /** @deprecated This method is replaced with getTime(). Gets the timestamp value of this TimeStampHeader. @return The timestamp value of this TimeStampHeader. */ float getTimeStamp(); /** Gets the timestamp value of this TimeStampHeader. @return The timestamp value of this TimeStampHeader. @since v1.2 */ long getTime(); /** Sets the timestamp value of this TimeStampHeader to the new timestamp value passed to this method. This method allows applications to conveniantly use System.currentTimeMillis to set the timeStamp value. @param timeStamp The new long timestamp value. @exception InvalidArgumentException Thrown when the timestamp value argument is a negative value. @since v1.2 */ void setTime(long timeStamp) throws InvalidArgumentException; /** @deprecated This method is replaced with getTimeDelay(). Gets delay of TimeStampHeader. This method returns -1 if the delay parameter is not set. @return The delay value of this TimeStampHeader */ float getDelay(); /** @deprecated This method is replaced with setTimeDelay(int). Sets the new delay value of the TimestampHeader to the delay parameter passed to this method @param delay The new float delay value. @exception InvalidArgumentException Thrown when the delay value argumenmt is a negative value other than the default value -1. */ void setDelay(float delay) throws InvalidArgumentException; /** Gets delay of TimeStampHeader. This method returns -1 if the delay parameter is not set. @return The delay value of this TimeStampHeader as an integer. @since v1.2 */ int getTimeDelay(); /** Sets the new delay value of the TimestampHeader to the delay parameter passed to this method @param delay The new int delay value. @exception InvalidArgumentException Thrown when the delay value argumenmt is a negative value other than the default value -1. @since v1.2 */ void setTimeDelay(int delay) throws InvalidArgumentException; } // vim: sw=4 et tw=72 com=srO\:/**,mb\:*,ex\:*/,srO\:/*,mb\:*,ex\:*/,b\:TRANS,\://,b\:#,\:%,\:XCOMM,n\:>,fb\:-
kerr-huang/openss7
src/java/javax/sip/header/TimeStampHeader.java
Java
agpl-3.0
6,210
[ 30522, 1013, 1008, 1030, 1006, 1001, 1007, 5034, 2278, 1013, 9262, 1013, 9262, 2595, 1013, 10668, 1013, 20346, 1013, 2335, 15464, 8458, 13775, 2121, 1012, 9262, 1026, 1052, 1028, 9385, 1004, 6100, 1025, 2263, 1011, 2325, 13813, 24887, 2239,...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * 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.ignite.internal.marshaller.optimized; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamField; import java.io.Serializable; import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller; import org.apache.ignite.marshaller.GridMarshallerAbstractTest; import org.apache.ignite.marshaller.Marshaller; import org.junit.Test; /** * Test that Optimized Marshaller works with classes with serialPersistentFields. */ public class OptimizedMarshallerSerialPersistentFieldsSelfTest extends GridMarshallerAbstractTest { /** {@inheritDoc} */ @Override protected Marshaller marshaller() { return new OptimizedMarshaller(false); } /** * @throws Exception If failed. */ @Test public void testOptimizedMarshaller() throws Exception { unmarshal(marshal(new TestClass())); TestClass2 val = unmarshal(marshal(new TestClass2())); assertNull(val.field3); } /** * Test class with serialPersistentFields fields. */ private static class TestClass implements Serializable { private static final long serialVersionUID = 0L; /** For serialization compatibility. */ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField("field1", Integer.TYPE), new ObjectStreamField("field2", Integer.TYPE) }; /** * @param s Object output stream. */ private void writeObject(ObjectOutputStream s) throws IOException { s.putFields().put("field1", 1); s.putFields().put("field2", 2); s.writeFields(); s.writeObject(null); } /** * @param s Object input stream. */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); s.readObject(); } } /** * Test class with serialPersistentFields fields. */ private static class TestClass2 implements Serializable { private static final long serialVersionUID = 0L; private Integer field3 = 1; /** For serialization compatibility. */ private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField("field1", Integer.TYPE), new ObjectStreamField("field2", Integer.TYPE) }; /** * @param s Object output stream. */ private void writeObject(ObjectOutputStream s) throws IOException { s.putFields().put("field1", 1); s.putFields().put("field2", 2); s.writeFields(); s.writeObject(null); } /** * @param s Object input stream. */ private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); s.readObject(); } } }
ptupitsyn/ignite
modules/core/src/test/java/org/apache/ignite/internal/marshaller/optimized/OptimizedMarshallerSerialPersistentFieldsSelfTest.java
Java
apache-2.0
3,845
[ 30522, 1013, 1008, 1008, 7000, 2000, 1996, 15895, 4007, 3192, 1006, 2004, 2546, 1007, 2104, 2028, 2030, 2062, 1008, 12130, 6105, 10540, 1012, 2156, 1996, 5060, 5371, 5500, 2007, 1008, 2023, 2147, 2005, 3176, 2592, 4953, 9385, 6095, 1012, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
{-# LANGUAGE TupleSections #-} module Y2016.M09.D09.Solution where import Control.Arrow (first) import Control.Monad (guard, (>=>)) import Data.Function (on) import Data.List (sortBy) import Data.Map (Map) import qualified Data.Map as Map -- below import available from 1HaskellADay git repository import Control.List (takeout) {-- Now for something completely different ... So some related cryptoarithmetic: --} sums :: [(String, String, Int)] sums = [("FAT", "CAT", 904), ("STORE","CAKE",60836), ("EACH", "ROSE", 7839)] -- solve these sums -- Okay, first we need to assign a letter to a value assign :: Map Char Int -> Char -> [Int] -> [((Char, Int), [Int])] assign ctx ch domain = maybe (fmap (first (ch,)) (takeout domain)) (pure . (,domain) . (ch,)) (Map.lookup ch ctx) -- we do that for each of the letters. assigns :: Map Char Int -> String -> [Int] -> [([(Char, Int)], [Int])] assigns _ [] = pure . ([],) assigns ctx (ch:s) = assign ctx ch >=> \(a,b) -> assigns ctx s b >>= return . first (a:) {-- *Y2016.M09.D09.Solution> let ans = assigns Map.empty "FAT" [0..9] *Y2016.M09.D09.Solution> head ans ~> ([('F',0),('A',1),('T',2)],[3,4,5,6,7,8,9]) *Y2016.M09.D09.Solution> last ans ~> ([('F',9),('A',8),('T',7)],[0,1,2,3,4,5,6]) *Y2016.M09.D09.Solution> length ans ~> 720 --} -- Okay, we have that, so let's convert that to a map. With arrows, this is -- easy, right: map (first Map.fromList) -- Now we convert a word into a number: numfrom :: Map Char Int -> String -> Int numfrom ctx = foldl (\tots -> (10 * tots +) . (ctx Map.!)) 0 {-- *Y2016.M09.D09.Solution> let fats = map (first (flip numfrom "FAT" . Map.fromList)) ans *Y2016.M09.D09.Solution> head fats ~> (210,[3,4,5,6,7,8,9]) *Y2016.M09.D09.Solution> last fats ~> (789,[0,1,2,3,4,5,6]) --} solver :: (String, String, Int) -> Map Char Int -> [Int] -> [(Map Char Int, [Int])] solver (a,b,c) ctx domain = assigns ctx a domain >>= \(asol, rest) -> let amap = merge ctx asol na = numfrom amap a in guard (na < c) >> assigns amap b rest >>= \(bsol, subdom) -> let newmap = merge amap bsol in guard (na + numfrom newmap b == c) >> return (newmap, subdom) merge :: Ord a => Map a b -> [(a,b)] -> Map a b merge m = Map.union m . Map.fromList -- solving all three will map the letter to the digits [0..9] {-- *Y2016.M09.D09.Solution> let solves = solver Map.empty [0..9] (head sums) *Y2016.M09.D09.Solution> length solves ~> 10 *Y2016.M09.D09.Solution> head solves (fromList [('A',5),('C',8),('F',0),('T',2)],[1,3,4,6,7,9]) so: --} solveAll :: [(String, String, Int)] -> Map Char Int -> [Int] -> [Map Char Int] solveAll [] ctx = const (pure ctx) solveAll (e:qs) ctx = solver e ctx >=> uncurry (solveAll qs) . first (Map.union ctx) {-- *Y2016.M09.D09.Solution> solveAll sums Map.empty [0..9] ~> {[('A',0),('C',8),('E',3),('F',1),('H',6),('K',9),('O',7),('R',4),('S',5),('T',2)]} --} -- arrange the character in their digit-value order. What word do you get? arrange :: Map Char Int -> String arrange = map fst . sortBy (compare `on` snd) . Map.toList -- *Y2016.M09.D09.Solution> arrange (head it) ~> "AFTERSHOCK"
geophf/1HaskellADay
exercises/HAD/Y2016/M09/D09/Solution.hs
Haskell
mit
3,206
[ 30522, 1063, 1011, 1001, 2653, 10722, 21112, 18491, 2015, 1001, 1011, 1065, 11336, 1061, 11387, 16048, 1012, 1049, 2692, 2683, 1012, 1040, 2692, 2683, 1012, 5576, 2073, 12324, 2491, 1012, 8612, 1006, 2034, 1007, 12324, 2491, 1012, 13813, 20...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
--- title: getMutation description: getMutation API reference for redux-requests - declarative AJAX requests and automatic network state management for single-page applications --- Almost the same as `getQuery`, it is just used for mutations: ```js import { getMutation } from '@redux-requests/core'; const deleteBookMutation = getMutation(state, { type: 'DELETE_BOOK' }); /* for example { loading: false, error: null, pending: 0 // number of pending requests downloadProgress: null, // only when requestAction.meta.measureDownloadProgress is true uploadProgress: null, // only when requestAction.meta.measureUploadProgress is true } */ ``` It accept `type` and optionally `requestKey` props, which work like for queries.
klis87/redux-saga-requests
docusaurus/docs/api-reference/get-mutation.md
Markdown
mit
736
[ 30522, 1011, 1011, 1011, 2516, 1024, 2131, 28120, 3370, 6412, 1024, 2131, 28120, 3370, 17928, 4431, 2005, 2417, 5602, 1011, 11186, 1011, 11703, 8017, 8082, 18176, 11186, 1998, 6882, 2897, 2110, 2968, 2005, 2309, 1011, 3931, 5097, 1011, 1011...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
//: net/mindview/util/Print.java // Print methods that can be used without // qualifiers, using Java SE5 static imports: package tsj.example.java.project.tsj.net.mindview.util; import java.io.*; public class Print { // Print with a newline: public static void print(Object obj) { System.out.println(obj); } // Print a newline by itself: public static void print() { System.out.println(); } // Print with no line break: public static void printnb(Object obj) { System.out.print(obj); } // The new Java SE5 printf() (from C): public static PrintStream printf(String format, Object... args) { return System.out.printf(format, args); } } ///:~
taoshujian/exampleJava
src/main/java/tsj/example/java/project/tsj/net/mindview/util/Print.java
Java
apache-2.0
683
[ 30522, 1013, 1013, 1024, 5658, 1013, 2568, 8584, 1013, 21183, 4014, 1013, 6140, 1012, 9262, 1013, 1013, 6140, 4725, 2008, 2064, 2022, 2109, 2302, 1013, 1013, 18956, 1010, 2478, 9262, 7367, 2629, 10763, 17589, 1024, 7427, 24529, 3501, 1012, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package com.rootulp.rootulpjsona; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; import java.io.InputStream; public class picPage extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pic_page); Intent local = getIntent(); Bundle localBundle = local.getExtras(); artist selected = (artist) localBundle.getSerializable("selected"); String imageURL = selected.getImageURL(); new DownloadImageTask((ImageView) findViewById(R.id.painting)).execute(imageURL); } private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { ImageView bmImage; public DownloadImageTask(ImageView bmImage) { this.bmImage = bmImage; } protected Bitmap doInBackground(String... urls) { String urldisplay = urls[0]; Bitmap mIcon11 = null; try { InputStream in = new java.net.URL(urldisplay).openStream(); mIcon11 = BitmapFactory.decodeStream(in); } catch (Exception e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return mIcon11; } protected void onPostExecute(Bitmap result) { bmImage.setImageBitmap(result); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_pic_page, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
rootulp/school
mobile_apps/assignment6_rootulp/RootulpJsonA/app/src/main/java/com/rootulp/rootulpjsona/picPage.java
Java
mit
2,172
[ 30522, 7427, 4012, 1012, 7117, 5313, 2361, 1012, 7117, 5313, 2361, 22578, 7856, 1025, 12324, 11924, 1012, 4180, 1012, 7848, 1025, 12324, 11924, 1012, 8389, 1012, 2978, 2863, 2361, 1025, 12324, 11924, 1012, 8389, 1012, 2978, 2863, 14376, 189...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<html> <head> <title>libvorbis - function - vorbis_comment_query_count</title> <link rel=stylesheet href="style.css" type="text/css"> </head> <body bgcolor=white text=black link="#5555ff" alink="#5555ff" vlink="#5555ff"> <table border=0 width=100%> <tr> <td><p class=tiny>libvorbis documentation</p></td> <td align=right><p class=tiny>libvorbis version 1.3.2 - 20101101</p></td> </tr> </table> <h1>vorbis_comment_query_count</h1> <p><i>declared in "vorbis/codec.h";</i></p> <p>This function determines the number of comments with a given tag that are present in a <a href="vorbis_comment.html">vorbis_comment</a> structure.</p> <table border=0 color=black cellspacing=0 cellpadding=7> <tr bgcolor=#cccccc> <td> <pre><b> extern int vorbis_comment_query_count(vorbis_comment *vc, const char *tag); </b></pre> </td> </tr> </table> <h3>Parameters</h3> <dl> <dt><i>vc</i></dt> <dd>Pointer to the vorbis_comment structure.</dd> <dt><i>tag</i></dt> <dd>Pointer to a null-terminated string of the comment tag to look for. Tags are compared case-insensitively.</dd> </dl> <h3>Return Values</h3> <blockquote> <li>The number of comments present with the given tag.</li> <li>0 if no such comments are present.</li> </blockquote> <p> <br><br> <hr noshade> <table border=0 width=100%> <tr valign=top> <td><p class=tiny>copyright &copy; 2010 Xiph.Org</p></td> <td align=right><p class=tiny><a href="https://xiph.org/vorbis/">Ogg Vorbis</a></p></td> </tr><tr> <td><p class=tiny>libvorbis documentation</p></td> <td align=right><p class=tiny>libvorbis version 1.3.2 - 20101101</p></td> </tr> </table> </body> </html>
Jean-LouisH/LaniaEngine
thirdparty/libvorbis-1.3.7/doc/libvorbis/vorbis_comment_query_count.html
HTML
mit
1,620
[ 30522, 1026, 16129, 1028, 1026, 2132, 1028, 1026, 2516, 1028, 5622, 2497, 14550, 18477, 1011, 3853, 1011, 29536, 15185, 2483, 1035, 7615, 1035, 23032, 1035, 4175, 1026, 1013, 2516, 1028, 1026, 4957, 2128, 2140, 1027, 6782, 21030, 2102, 1785...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#include <stdio.h> #include "aeb.h" #include <string.h> #include <math.h> int main() { Aeb * raiz, *esq, * dir; Aeb * arvore; double r; char s[127]; /*arvore = criaRaiz('*'); esq = criaFolha(10.0); dir = criaFolha(7.0); conectaNodos(arvore, esq, dir); raiz = criaRaiz('+'); dir = criaFolha(8.0); conectaNodos(raiz, arvore, dir); printf("Resultado: %g\n", resolveExpressao(raiz));*/ printf("\nExpressão: "); scanf("%s",s); arvore = criaArvore(s); printf("Expressão após conversão: "); mostraArvore(arvore); puts(""); r=resolveExpressao(arvore); printf("\nO resultado é= %g\n",r); }
EltonBroering/Programacao_C
Projeto7/teste.c
C
gpl-3.0
636
[ 30522, 1001, 2421, 1026, 2358, 20617, 1012, 1044, 1028, 1001, 2421, 1000, 29347, 2497, 1012, 1044, 1000, 1001, 2421, 1026, 5164, 1012, 1044, 1028, 1001, 2421, 1026, 8785, 1012, 1044, 1028, 20014, 2364, 1006, 1007, 1063, 29347, 2497, 1008, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// // SettingViewController.h // CoreDataCache-Demo // // Created by Jakey on 15/1/30. // Copyright (c) 2015年 www.skyfox.org. All rights reserved. // #import "BaseViewController.h" @interface SettingViewController : BaseViewController @end
shaojiankui/CoreDataCache-Demo
CoreDataCache-Demo/Controller/Setting/SettingViewController.h
C
mit
249
[ 30522, 1013, 1013, 1013, 1013, 4292, 8584, 8663, 13181, 10820, 1012, 1044, 1013, 1013, 4563, 2850, 2696, 3540, 5403, 1011, 9703, 1013, 1013, 1013, 1013, 2580, 2011, 5180, 2100, 2006, 2321, 1013, 1015, 1013, 2382, 1012, 1013, 1013, 9385, 1...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
class CreateTeachers < ActiveRecord::Migration def change create_table :teachers do |t| t.string :name, null: false t.integer :grade t.integer :college_id t.integer :user_id t.string :address t.string :phone t.string :email t.timestamps null: false end end end
vjudge1/score
db/migrate/20150908120446_create_teachers.rb
Ruby
gpl-2.0
322
[ 30522, 2465, 3443, 24741, 2015, 1026, 3161, 2890, 27108, 2094, 1024, 1024, 9230, 13366, 2689, 3443, 1035, 2795, 1024, 5089, 2079, 1064, 1056, 1064, 1056, 1012, 5164, 1024, 2171, 1010, 19701, 1024, 6270, 1056, 1012, 16109, 1024, 3694, 1056, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* global $:true */ + function($) { var defaults; var Photos = function(config) { this.initConfig(config); this.index = 0; } Photos.prototype = { initConfig: function (config) { this.config = $.extend({}, defaults, config); this.activeIndex = this.lastActiveIndex = this.config.initIndex; this.config.items = this.config.items.map(function(d, i) { if(typeof d === typeof 'a') { return { image: d, caption: '' } } return d; }); this.tpl = $.t7.compile(this.config.tpl); if(this.config.autoOpen) this.open(); }, open: function (index) { if (this._open) return false; if (!this.modal) { this.modal = $(this.tpl(this.config)).appendTo(document.body); this.container = this.modal.find('.swiper-container'); this.wrapper = this.modal.find('.swiper-wrapper'); var hammer = new Hammer(this.container[0]); hammer.get('pinch').set({ enable: true }); hammer.on('pinchstart', $.proxy(this.onGestureStart, this)); hammer.on('pinchmove', $.proxy(this.onGestureChange, this)); hammer.on('pinchend', $.proxy(this.onGestureEnd, this)); this.modal.on($.touchEvents.start, $.proxy(this.onTouchStart, this)); this.modal.on($.touchEvents.move, $.proxy(this.onTouchMove, this)); this.modal.on($.touchEvents.end, $.proxy(this.onTouchEnd, this)); //init index this.wrapper.transition(0); this.wrapper.transform('translate3d(-' + $(window).width()*this.config.initIndex + 'px,0,0)'); this.container.find('.caption-item').eq(this.config.initIndex).addClass('active'); this.container.find('.swiper-pagination-bullet').eq(this.config.initIndex).addClass('swiper-pagination-bullet-active'); } var self = this; this.modal.show().height(); this.modal.addClass('weui-photo-browser-modal-visible'); this.container.addClass('swiper-container-visible').transitionEnd(function() { self.initParams(); if(index !== undefined) { self.slideTo(index); } if(self.config.onOpen) { self.config.onOpen.call(self); } }); this._open = true; }, close: function() { this.container.transitionEnd($.proxy(function() { this.modal.hide(); this._open = false; if(this.config.onClose) this.config.onClose.call(this); }, this)); this.container.removeClass('swiper-container-visible'); this.modal.removeClass('weui-photo-browser-modal-visible'); }, initParams: function () { if(this.containerHeight) return false; this.windowWidth = $(window).width(); this.containerHeight = this.container.height(); this.containerWidth = this.container.width(); this.touchStart = {}; this.wrapperTransform = 0; this.wrapperLastTransform = - $(window).width()*this.config.initIndex; this.wrapperDiff = 0; this.lastScale = 1; this.currentScale = 1; this.imageLastTransform = { x: 0, y: 0 }; this.imageTransform = { x: 0, y: 0 }; this.imageDiff = { x: 0, y: 0 }; this.imageLastDiff = { x: 0, y: 0 }; }, onTouchStart: function (e) { if(this.scaling) return false; this.touching = true; this.touchStart = $.getTouchPosition(e); this.touchMove = null; this.touchStartTime = + new Date; this.wrapperDiff = 0; this.breakpointPosition = null; }, onTouchMove: function (e) { if(!this.touching || this.scaling) return false; e.preventDefault(); if(this.gestureImage) { var rect = this.gestureImage[0].getBoundingClientRect(); if (rect.left >= 0 || rect.right <= this.windowWidth) { this.overflow = true; } else { this.overflow = false; } } else { this.oveflow = false; } var p = this.touchMove = $.getTouchPosition(e); if(this.currentScale === 1 || this.overflow) { if(this.breakpointPosition) { this.wrapperDiff = p.x - this.breakpointPosition.x; } else { this.wrapperDiff = p.x - this.touchStart.x; } if(this.activeIndex === 0 && this.wrapperDiff > 0) this.wrapperDiff = Math.pow(this.wrapperDiff, .8); if(this.activeIndex === this.config.items.length - 1 && this.wrapperDiff < 0) this.wrapperDiff = - Math.pow(-this.wrapperDiff, .8); this.wrapperTransform = this.wrapperLastTransform + this.wrapperDiff; this.doWrapperTransform(); } else { var img = this.gestureImage; this.imageDiff = { x: p.x - this.touchStart.x, y: p.y - this.touchStart.y } this.imageTransform = { x: this.imageDiff.x + this.imageLastTransform.x, y: this.imageDiff.y + this.imageLastTransform.y }; this.doImageTransform(); this.breakpointPosition = p; this.imageLastDiff = this.imageDiff; } }, onTouchEnd: function (e) { if(!this.touching) return false; this.touching = false; if(this.scaling) return false; var duration = (+ new Date) - this.touchStartTime; if(duration < 200 && (!this.touchMove || Math.abs(this.touchStart.x - this.touchMove.x) <= 2 && Math.abs(this.touchStart.y - this.touchMove.y) <= 2)) { this.onClick(); return; } if(this.wrapperDiff > 0) { if(this.wrapperDiff > this.containerWidth/2 || (this.wrapperDiff > 20 && duration < 300)) { this.slidePrev(); } else { this.slideTo(this.activeIndex, 200); } } else { if(- this.wrapperDiff > this.containerWidth/2 || (-this.wrapperDiff > 20 && duration < 300)) { this.slideNext(); } else { this.slideTo(this.activeIndex, 200); } } this.imageLastTransform = this.imageTransform; this.adjust(); }, onClick: function () { var self = this; if (this._lastClickTime && ( + new Date - this._lastClickTime < 300)) { this.onDoubleClick(); clearTimeout(this._clickTimeout); } else { this._clickTimeout = setTimeout(function () { self.close(); }, 300); } this._lastClickTime = + new Date; }, onDoubleClick: function () { this.gestureImage = this.container.find('.swiper-slide').eq(this.activeIndex).find('img'); this.currentScale = this.currentScale > 1 ? 1 : 2; this.doImageTransform(200); this.adjust(); }, onGestureStart: function (e) { this.scaling = true; this.gestureImage = this.container.find('.swiper-slide').eq(this.activeIndex).find('img'); }, onGestureChange: function (e) { var s = this.lastScale * e.scale; if (s > this.config.maxScale) { s = this.config.maxScale + Math.pow((s - this.config.maxScale), 0.5); } else if (s < 1) { s = Math.pow(s, .5); } this.currentScale = s; this.doImageTransform(); }, onGestureEnd: function (e) { if (this.currentScale > this.config.maxScale) { this.currentScale = this.config.maxScale; this.doImageTransform(200); } else if (this.currentScale < 1) { this.currentScale = 1; this.doImageTransform(200); } this.lastScale = this.currentScale; this.scaling = false; this.adjust(); }, doWrapperTransform: function(duration, callback) { if (duration === 0) { var origin = this.wrapper.css('transition-property') this.wrapper.css('transition-property', 'none').transform('translate3d(' + this.wrapperTransform + 'px, 0, 0)'); this.wrapper.css('transition-property', origin); callback() } else { this.wrapper.transitionEnd(function() { callback && callback(); }); this.wrapper.transition(duration || defaults.duration).transform('translate3d(' + this.wrapperTransform + 'px, 0, 0)'); } }, doImageTransform: function(duration, callback) { if(!this.gestureImage) return; this.gestureImage.transition(duration || 0).transform('translate3d(' + this.imageTransform.x + 'px,' + this.imageTransform.y + 'px, 0) scale(' + this.currentScale + ')'); this._needAdjust = true; }, adjust: function() { if(!this._needAdjust) return false; var img = this.gestureImage; if(!img) return false; if(this.currentScale === 1) { this.imageTransform = this.imageLastDiff = {x:0,y:0}; this.doImageTransform(200); return; } var rect = img[0].getBoundingClientRect(); //调整上下 if(rect.height < this.containerHeight) { // 如果高度没容器高,则自动居中 this.imageTransform.y = this.imageLastTransform.y = 0; } else { //如果比容器高,那么要保证上下不能有空隙 if(rect.top > 0) this.imageTransform.y = this.imageTransform.y - rect.top; else if(rect.bottom < this.containerHeight) this.imageTransform.y = this.imageTransform.y + this.containerHeight - rect.bottom; } this.doImageTransform(200); this._needAdjust = false; // must at last line, because doImageTransform will set this._needAdjust true }, slideTo: function(index, duration) { if(index < 0) index = 0; if(index > this.config.items.length-1) index = this.config.items.length - 1; this.lastActiveIndex = this.activeIndex; this.activeIndex = index; this.wrapperTransform = - (index * this.containerWidth); this.wrapperLastTransform = this.wrapperTransform; this.doWrapperTransform(duration, $.proxy(function() { if(this.lastActiveIndex === this.activeIndex) return false; // active index not change this.container.find('.caption-item.active').removeClass('active'); this.container.find('.swiper-slide-active').removeClass('swiper-slide-active'); this.container.find('.swiper-pagination-bullet-active').removeClass('swiper-pagination-bullet-active'); this.container.find('.caption-item').eq(this.activeIndex).addClass('active'); this.container.find('.swiper-slide').eq(this.activeIndex).addClass('swiper-slide-active'); this.container.find('.swiper-pagination-bullet').eq(this.activeIndex).addClass('swiper-pagination-bullet-active'); //reset image transform this.container.find('.swiper-slide img[style]').transition(0).transform('translate3d(0,0,0) scale(1)'); this.lastScale = 1; this.currentScale = 1; this.imageLastTransform = { x: 0, y: 0 }; this.imageTransform = { x: 0, y: 0 }; this.imageDiff = { x: 0, y: 0 }; this.imageLastDiff = { x: 0, y: 0 }; if(this.config.onSlideChange) { this.config.onSlideChange.call(this, this.activeIndex); } }, this)); }, slideNext: function() { return this.slideTo(this.activeIndex+1, 200); }, slidePrev: function() { return this.slideTo(this.activeIndex-1, 200); } } defaults = Photos.prototype.defaults = { items: [], autoOpen: false, //初始化完成之后立刻打开 onOpen: undefined, onClose: undefined, initIndex: 0, //打开时默认显示第几张 maxScale: 3, onSlideChange: undefined, duration: 200, // 默认动画时间,如果没有在调用函数的时候指定,则使用这个值 tpl: '<div class="weui-photo-browser-modal">\ <div class="swiper-container">\ <div class="swiper-wrapper">\ {{#items}}\ <div class="swiper-slide">\ <div class="photo-container">\ <img src="{{image}}" />\ </div>\ </div>\ {{/items}}\ </div>\ <div class="caption">\ {{#items}}\ <div class="caption-item caption-item-{{@index}}">{{caption}}</div>\ {{/items}}\ </div>\ <div class="swiper-pagination swiper-pagination-bullets">\ {{#items}}\ <span class="swiper-pagination-bullet"></span>\ {{/items}}\ </div>\ </div>\ </div>' } $.photoBrowser = function(params) { return new Photos(params); } }($);
lihongxun945/jquery-weui
src/js/photos.js
JavaScript
mit
12,514
[ 30522, 1013, 1008, 3795, 1002, 1024, 2995, 1008, 1013, 1009, 3853, 1006, 1002, 1007, 1063, 13075, 12398, 2015, 1025, 13075, 7760, 1027, 3853, 1006, 9530, 8873, 2290, 1007, 1063, 2023, 1012, 1999, 4183, 8663, 8873, 2290, 30524, 1025, 1065, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
//// [topLevelLambda.ts] module M { var f = () => {this.window;} } //// [topLevelLambda.js] var M; (function (M) { var _this = this; var f = function () { _this.window; }; })(M || (M = {}));
RReverser/TSX
tests/baselines/reference/topLevelLambda.js
JavaScript
apache-2.0
225
[ 30522, 1013, 1013, 1013, 1013, 1031, 2327, 20414, 8411, 14905, 2850, 1012, 24529, 1033, 11336, 1049, 1063, 13075, 1042, 1027, 1006, 1007, 1027, 1028, 1063, 2023, 1012, 3332, 1025, 1065, 1065, 1013, 1013, 1013, 1013, 1031, 2327, 20414, 8411,...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
use std::os; use std::rand; use std::rand::Rng; use std::io::Timer; use std::time::Duration; use std::clone::Clone; #[deriving(Clone)] struct Field { x: uint, y: uint, active: bool } fn next_round(field: &mut Vec<Vec<Field>>) { let old_field = field.clone(); for row in field.iter_mut() { for c in row.iter_mut() { c.active = next_vitality(&old_field, c.x, c.y); } } } fn next_vitality(old_field: &Vec<Vec<Field>>, x: uint, y: uint) -> bool { let height = old_field.len(); let width = old_field[0].len(); let mut allowed_x: Vec<uint> = vec![x]; let mut allowed_y: Vec<uint> = vec![y]; if x > 0 { allowed_x.push(x-1); } if x < width-1 { allowed_x.push(x+1); } if y > 0 { allowed_y.push(y-1); } if y < height-1 { allowed_y.push(y+1); } let mut total: int = 0; for i in allowed_x.iter() { for j in allowed_y.iter() { if *i == x && *j == y { continue; } if old_field[*j][*i].active == true { total += 1; } } } match total { 2 => old_field[y][x].active, 3 => true, _ => false } } fn print_field(field: &Vec<Vec<Field>>) { for row in field.iter() { for c in row.iter() { print!("{}", match c.active {false => " ", true => "#"}); } print!("\n"); } print!("\n"); } fn generate_first_round() -> Vec<Vec<Field>> { let mut field: Vec<Vec<Field>> = Vec::new(); let args = os::args(); let mut width: uint = 50; let mut height: uint = 50; if args.len() > 1 { match from_str::<uint>(args[1].as_slice()){ Some(x) => width = x, None => fail!("Argument supplied is not a positive number") }; } else { print!("Use default value 50 as width") } if args.len() > 2 { match from_str::<uint>(args[2].as_slice()){ Some(x) => height = x, None => fail!("Argument supplied is not a positive number") }; } else { print!("Use default value 50 as height") } for y in range(0u, height) { let mut row: Vec<Field> = Vec::new(); for x in range(0u, width) { let mut v = false; let mut rng = rand::task_rng(); if rng.gen::<u8>() < 32 { v = true; } else { v = false; } row.push(Field{x:x, y:y, active:v}); } field.push(row); } return field; } fn main() { let mut field = generate_first_round(); let mut timer = Timer::new().unwrap(); loop { timer.sleep(Duration::milliseconds(150)); print_field(&field); next_round(&mut field); } }
SimonWaldherr/cgol.rs
cgol.rs
Rust
mit
2,851
[ 30522, 2224, 2358, 2094, 1024, 1024, 9808, 1025, 2224, 2358, 2094, 1024, 1024, 14566, 1025, 2224, 2358, 2094, 1024, 1024, 14566, 1024, 1024, 29300, 2290, 1025, 2224, 2358, 2094, 1024, 1024, 22834, 1024, 1024, 25309, 1025, 2224, 2358, 2094, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package generated.glib20.glib; import org.bridj.BridJ; import org.bridj.Pointer; import org.bridj.StructObject; import org.bridj.ann.Library; import org.bridj.ann.Ptr; @Library("glib-2.0") public class GAsyncQueue extends StructObject { static { BridJ.register(); } public GAsyncQueue() { super(); } public GAsyncQueue(Pointer pointer) { super(pointer); } protected native int g_async_queue_length( @Ptr long queue); public int length() { return this.g_async_queue_length(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } protected native int g_async_queue_length_unlocked( @Ptr long queue); public int length_unlocked() { return this.g_async_queue_length_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } protected native void g_async_queue_lock( @Ptr long queue); public void lock() { this.g_async_queue_lock(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } @Ptr protected native long g_async_queue_pop( @Ptr long queue); public Pointer pop() { return Pointer.pointerToAddress(this.g_async_queue_pop(Pointer.pointerTo(this, GAsyncQueue.class).getPeer())); } @Ptr protected native long g_async_queue_pop_unlocked( @Ptr long queue); public Pointer pop_unlocked() { return Pointer.pointerToAddress(this.g_async_queue_pop_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer())); } protected native void g_async_queue_push( @Ptr long queue, @Ptr long data); public void push(Pointer data) { this.g_async_queue_push(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(data)); } protected native void g_async_queue_push_unlocked( @Ptr long queue, @Ptr long data); public void push_unlocked(Pointer data) { this.g_async_queue_push_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(data)); } @Ptr protected native long g_async_queue_ref( @Ptr long queue); public Pointer ref() { return Pointer.pointerToAddress(this.g_async_queue_ref(Pointer.pointerTo(this, GAsyncQueue.class).getPeer())); } protected native void g_async_queue_ref_unlocked( @Ptr long queue); public void ref_unlocked() { this.g_async_queue_ref_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } @Ptr protected native long g_async_queue_timed_pop( @Ptr long queue, @Ptr long end_time); public Pointer timed_pop(Pointer end_time) { return Pointer.pointerToAddress(this.g_async_queue_timed_pop(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(end_time))); } @Ptr protected native long g_async_queue_timed_pop_unlocked( @Ptr long queue, @Ptr long end_time); public Pointer timed_pop_unlocked(Pointer end_time) { return Pointer.pointerToAddress(this.g_async_queue_timed_pop_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(end_time))); } @Ptr protected native long g_async_queue_timeout_pop( @Ptr long queue, long timeout); public Pointer timeout_pop(long timeout) { return Pointer.pointerToAddress(this.g_async_queue_timeout_pop(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), timeout)); } @Ptr protected native long g_async_queue_timeout_pop_unlocked( @Ptr long queue, long timeout); public Pointer timeout_pop_unlocked(long timeout) { return Pointer.pointerToAddress(this.g_async_queue_timeout_pop_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), timeout)); } @Ptr protected native long g_async_queue_try_pop( @Ptr long queue); public Pointer try_pop() { return Pointer.pointerToAddress(this.g_async_queue_try_pop(Pointer.pointerTo(this, GAsyncQueue.class).getPeer())); } @Ptr protected native long g_async_queue_try_pop_unlocked( @Ptr long queue); public Pointer try_pop_unlocked() { return Pointer.pointerToAddress(this.g_async_queue_try_pop_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer())); } protected native void g_async_queue_unlock( @Ptr long queue); public void unlock() { this.g_async_queue_unlock(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } protected native void g_async_queue_unref( @Ptr long queue); public void unref() { this.g_async_queue_unref(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } protected native void g_async_queue_unref_and_unlock( @Ptr long queue); public void unref_and_unlock() { this.g_async_queue_unref_and_unlock(Pointer.pointerTo(this, GAsyncQueue.class).getPeer()); } @Ptr protected static native long g_async_queue_new(); public static Pointer _new() { return Pointer.pointerToAddress(GAsyncQueue.g_async_queue_new()); } @Ptr protected static native long g_async_queue_new_full( @Ptr long item_free_func); public static Pointer<GAsyncQueue> new_full(Pointer item_free_func) { return Pointer.pointerToAddress(GAsyncQueue.g_async_queue_new_full(Pointer.getPeer(item_free_func)), GAsyncQueue.class); } protected native void g_async_queue_push_sorted( @Ptr long queue, @Ptr long data, @Ptr long func, @Ptr long user_data); public void push_sorted(Pointer data, Pointer func, Pointer user_data) { this.g_async_queue_push_sorted(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(data), Pointer.getPeer(func), Pointer.getPeer(user_data)); } protected native void g_async_queue_push_sorted_unlocked( @Ptr long queue, @Ptr long data, @Ptr long func, @Ptr long user_data); public void push_sorted_unlocked(Pointer data, Pointer func, Pointer user_data) { this.g_async_queue_push_sorted_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(data), Pointer.getPeer(func), Pointer.getPeer(user_data)); } protected native void g_async_queue_sort_unlocked( @Ptr long queue, @Ptr long func, @Ptr long user_data); public void sort_unlocked(Pointer func, Pointer user_data) { this.g_async_queue_sort_unlocked(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(func), Pointer.getPeer(user_data)); } protected native void g_async_queue_sort( @Ptr long queue, @Ptr long func, @Ptr long user_data); public void sort(Pointer func, Pointer user_data) { this.g_async_queue_sort(Pointer.pointerTo(this, GAsyncQueue.class).getPeer(), Pointer.getPeer(func), Pointer.getPeer(user_data)); } }
gstreamer-java/gir2java
generated-src/generated/glib20/glib/GAsyncQueue.java
Java
gpl-3.0
7,257
[ 30522, 7427, 7013, 1012, 1043, 29521, 11387, 1012, 1043, 29521, 1025, 12324, 8917, 1012, 7987, 3593, 3501, 1012, 7987, 3593, 3501, 1025, 12324, 8917, 1012, 7987, 3593, 3501, 1012, 20884, 1025, 12324, 8917, 1012, 7987, 3593, 3501, 1012, 2358...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
import re import quantities as pq from numbers import NumberService class ConversionService(object): __exponents__ = { 'square': 2, 'squared': 2, 'cubed': 3 } def _preprocess(self, input): def handleExponents(input): m = re.search(r'\bsquare (\w+)', input) if m and self.isValidUnit(m.group(1)): input = re.sub(r'\bsquare (\w+)', r'\g<1>^2', input) m = re.search(r'\bsquared (\w+)', input) if m and self.isValidUnit(m.group(1)): input = re.sub(r'\bsquared (\w+)', r'\g<1>^2', input) m = re.search(r'\b(\w+) squared', input) if m and self.isValidUnit(m.group(1)): input = re.sub(r'\b(\w+) squared', r'\g<1>^2', input) m = re.search(r'\bsq (\w+)', input) if m and self.isValidUnit(m.group(1)): input = re.sub(r'\bsq (\w+)', r'\g<1>^2', input) m = re.search(r'\b(\w+) cubed', input) if m and self.isValidUnit(m.group(1)): input = re.sub(r'\b(\w+) cubed', r'\g<1>^3', input) m = re.search(r'\bcubic (\w+)', input) if m and self.isValidUnit(m.group(1)): input = re.sub(r'\bcubic (\w+)', r'\g<1>^3', input) service = NumberService() m = re.search(r'\b(\w+) to the (\w+)( power)?', input) if m and self.isValidUnit(m.group(1)): if m.group(2) in service.__ordinals__: exp = service.parseMagnitude(m.group(2)) input = re.sub(r'\b(\w+) to the (\w+)( power)?', r'\g<1>^' + str(exp), input) return input input = re.sub(r'\sper\s', r' / ', input) input = handleExponents(input) return input def parseUnits(self, input): """Carries out a conversion (represented as a string) and returns the result as a human-readable string. Args: input (str): Text representing a unit conversion, which should include a magnitude, a description of the initial units, and a description of the target units to which the quantity should be converted. Returns: A quantities object representing the converted quantity and its new units. """ quantity = self.convert(input) units = ' '.join(str(quantity.units).split(' ')[1:]) return NumberService.parseMagnitude(quantity.item()) + " " + units def isValidUnit(self, w): """Checks if a string represents a valid quantities unit. Args: w (str): A string to be tested against the set of valid quantities units. Returns: True if the string can be used as a unit in the quantities module. """ bad = set(['point', 'a']) if w in bad: return False try: pq.Quantity(0.0, w) return True except: return w == '/' def extractUnits(self, input): """Collects all the valid units from an input string. Works by appending consecutive words from the string and cross-referncing them with a set of valid units. Args: input (str): Some text which hopefully contains descriptions of different units. Returns: A list of strings, each entry in which is a valid quantities unit. """ input = self._preprocess(input) units = [] description = "" for w in input.split(' '): if self.isValidUnit(w) or w == '/': if description: description += " " description += w else: if description: units.append(description) description = "" if description: units.append(description) return units def convert(self, input): """Converts a string representation of some quantity of units into a quantities object. Args: input (str): A textual representation of some quantity of units, e.g., "fifty kilograms". Returns: A quantities object representing the described quantity and its units. """ input = self._preprocess(input) n = NumberService().longestNumber(input) units = self.extractUnits(input) # Convert to quantity object, attempt conversion quantity = pq.Quantity(float(n), units[0]) quantity.units = units[1] return quantity
jobdash/semantic
semantic/units.py
Python
mit
4,744
[ 30522, 12324, 2128, 12324, 12450, 2004, 1052, 4160, 2013, 3616, 12324, 3616, 2121, 7903, 2063, 2465, 25834, 2121, 7903, 2063, 1006, 4874, 1007, 1024, 1035, 1035, 16258, 21576, 2015, 1035, 1035, 1027, 1063, 1005, 2675, 1005, 1024, 1016, 1010...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# What is Plone? [Plone](https://plone.org) is a free and open source content management system built on top of the Zope application server. %%LOGO%% ## Features - Images for Plone 5 and Plone 4 - Enable add-ons via environment variables ## Usage ### Start a single Plone instance This will download and start the latest Plone 5 container, based on [Debian](https://www.debian.org/). ```console $ docker run -p 8080:8080 plone ``` This image includes `EXPOSE 8080` (the Plone port), so standard container linking will make it automatically available to the linked containers. Now you can add a Plone Site at http://localhost:8080 - default Zope user and password are `admin/admin`. ### Start Plone within a ZEO cluster Start ZEO server ```console $ docker run --name=zeo plone zeoserver ``` Start 2 Plone clients ```console $ docker run --link=zeo -e ZEO_ADDRESS=zeo:8100 -p 8081:8080 plone $ docker run --link=zeo -e ZEO_ADDRESS=zeo:8100 -p 8082:8080 plone ``` ### Start Plone in debug mode You can also start Plone in debug mode (`fg`) by running ```console $ docker run -p 8080:8080 plone fg ``` ### Add-ons You can enable Plone add-ons via the `PLONE_ADDONS` environment variable ```console $ docker run -p 8080:8080 -e PLONE_ADDONS="eea.facetednavigation Products.PloneFormGen" plone ``` For more information on how to extend this image with your own custom settings, adding more add-ons, building it or mounting volumes, please refer to our [documentation](https://github.com/plone/plone.docker/blob/master/docs/usage.rst). ### Supported Environment Variables The Plone image uses several environment variable that allow to specify a more specific setup. - `PLONE_ADDONS`, `ADDONS` - Customize Plone via Plone add-ons using this environment variable - `PLONE_ZCML`, `ZCML` - Include custom Plone add-ons ZCML files - `PLONE_DEVELOP`, `DEVELOP` - Develop new or existing Plone add-ons - `ZEO_ADDRESS` - This environment variable allows you to run Plone image as a ZEO client. - `ZEO_READ_ONLY` - Run Plone as a read-only ZEO client. Defaults to `off`. - `ZEO_CLIENT_READ_ONLY_FALLBACK` - A flag indicating whether a read-only remote storage should be acceptable as a fallback when no writable storages are available. Defaults to `false`. - `ZEO_SHARED_BLOB_DIR` - Set this to on if the ZEO server and the instance have access to the same directory. Defaults to `off`. - `ZEO_STORAGE` - Set the storage number of the ZEO storage. Defaults to `1`. - `ZEO_CLIENT_CACHE_SIZE` - Set the size of the ZEO client cache. Defaults to `128MB`. - `ZEO_PACK_KEEP_OLD` - Can be set to false to disable the creation of `*.fs.old` files before the pack is run. Defaults to true. - `HEALTH_CHECK_TIMEOUT` - Time in seconds to wait until health check starts. Defaults to `1` second. - `HEALTH_CHECK_INTERVAL` - Interval in seconds to check that the Zope application is still healthy. Defaults to `1` second. ## Documentation Full documentation for end users can be found in the ["docs"](https://github.com/plone/plone.docker/tree/master/docs) folder. It is also available online at http://docs.plone.org/ ## Credits This docker image was originally financed by the [European Environment Agency](http://eea.europa.eu), an agency of the European Union. Thanks to [Antonio De Marinis](https://github.com/demarant), [Sven Strack](https://github.com/svx) and [Alin Voinea](https://github.com/avoinea) for their preliminary work.
pydio/docs
plone/content.md
Markdown
mit
3,440
[ 30522, 1001, 2054, 2003, 20228, 5643, 1029, 1031, 20228, 5643, 1033, 1006, 16770, 1024, 1013, 1013, 20228, 5643, 1012, 8917, 1007, 2003, 1037, 2489, 1998, 2330, 3120, 4180, 2968, 2291, 2328, 2006, 2327, 1997, 1996, 1062, 17635, 4646, 8241, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Created by Ron 'Maxwolf' McDowell (ron.mcdowell@gmail.com) // Timestamp 01/03/2016@1:50 AM using System.Diagnostics.CodeAnalysis; using OregonTrailDotNet.Event.Prefab; using OregonTrailDotNet.Module.Director; namespace OregonTrailDotNet.Event.Person { /// <summary> /// Rocky Mountain spotted fever (RMSF), also known as blue disease, is the most lethal and most frequently reported /// rickettsial illness in the United States. /// </summary> [DirectorEvent(EventCategory.Person)] [SuppressMessage("ReSharper", "UnusedMember.Global")] public sealed class MountainFever : PersonInfect { /// <summary>Fired after the event has executed and the infection flag set on the person.</summary> /// <param name="person">Person whom is now infected by whatever you say they are here.</param> /// <returns>Name or type of infection the person is currently affected with.</returns> protected override string OnPostInfection(Entity.Person.Person person) { return $"{person.Name} has mountain fever."; } } }
Maxwolf/OregonTrail
src/Event/Person/MountainFever.cs
C#
mit
1,107
[ 30522, 1013, 1013, 2580, 2011, 6902, 1005, 4098, 12155, 10270, 1005, 25005, 1006, 6902, 1012, 25005, 1030, 20917, 4014, 1012, 4012, 1007, 1013, 1013, 2335, 15464, 2361, 5890, 1013, 6021, 1013, 2355, 1030, 1015, 1024, 2753, 2572, 2478, 2291,...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Cheiridopsis curta L.Bolus SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Aizoaceae/Cheiridopsis/Cheiridopsis curta/README.md
Markdown
apache-2.0
176
[ 30522, 1001, 18178, 15735, 3527, 18409, 20099, 2050, 1048, 1012, 8945, 7393, 2427, 1001, 1001, 1001, 1001, 3570, 3970, 1001, 1001, 1001, 1001, 2429, 2000, 2248, 3269, 3415, 5950, 1001, 1001, 1001, 1001, 2405, 1999, 19701, 1001, 1001, 1001, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * This file is part of Bisq. * * Bisq is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at * your option) any later version. * * Bisq is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Bisq. If not, see <http://www.gnu.org/licenses/>. */ package bisq.core.offer; import bisq.core.offer.bisq_v1.OfferPayload; import bisq.common.app.Capabilities; import bisq.common.app.Capability; import bisq.common.config.Config; import bisq.common.util.Utilities; import org.bitcoinj.core.Coin; import java.util.Date; import java.util.GregorianCalendar; import java.util.Map; public class OfferRestrictions { // The date when traders who have not upgraded to a Tor v3 Node Address cannot take offers and their offers become // invisible. private static final Date REQUIRE_TOR_NODE_ADDRESS_V3_DATE = Utilities.getUTCDate(2021, GregorianCalendar.AUGUST, 15); public static boolean requiresNodeAddressUpdate() { return new Date().after(REQUIRE_TOR_NODE_ADDRESS_V3_DATE) && !Config.baseCurrencyNetwork().isRegtest(); } public static Coin TOLERATED_SMALL_TRADE_AMOUNT = Coin.parseCoin("0.01"); static boolean hasOfferMandatoryCapability(Offer offer, Capability mandatoryCapability) { Map<String, String> extraDataMap = offer.getExtraDataMap(); if (extraDataMap != null && extraDataMap.containsKey(OfferPayload.CAPABILITIES)) { String commaSeparatedOrdinals = extraDataMap.get(OfferPayload.CAPABILITIES); Capabilities capabilities = Capabilities.fromStringList(commaSeparatedOrdinals); return Capabilities.hasMandatoryCapability(capabilities, mandatoryCapability); } return false; } }
bitsquare/bitsquare
core/src/main/java/bisq/core/offer/OfferRestrictions.java
Java
agpl-3.0
2,124
[ 30522, 1013, 1008, 1008, 2023, 5371, 2003, 2112, 1997, 20377, 4160, 1012, 1008, 1008, 20377, 4160, 2003, 2489, 4007, 1024, 2017, 2064, 2417, 2923, 3089, 8569, 2618, 2009, 1998, 1013, 2030, 19933, 2009, 1008, 2104, 1996, 3408, 1997, 1996, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#region Dapplo 2017 - GNU Lesser General Public License // Dapplo - building blocks for .NET applications // Copyright (C) 2017 Dapplo // // For more information see: http://dapplo.net/ // Dapplo repositories are hosted on GitHub: https://github.com/dapplo // // This file is part of Dapplo.Jira // // Dapplo.Jira 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, either version 3 of the License, or // (at your option) any later version. // // Dapplo.Jira is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have a copy of the GNU Lesser General Public License // along with Dapplo.Jira. If not, see <http://www.gnu.org/licenses/lgpl.txt>. #endregion namespace Dapplo.Jira.Domains { /// <summary> /// The marker interface of the user domain /// </summary> public interface IUserDomain : IJiraDomain { } }
alfadormx/Dapplo.Jira
src/Dapplo.Jira/Domains/IUserDomain.cs
C#
lgpl-3.0
1,161
[ 30522, 1001, 2555, 4830, 9397, 4135, 2418, 1011, 27004, 8276, 2236, 2270, 6105, 1013, 1013, 4830, 9397, 4135, 1011, 2311, 5991, 2005, 1012, 5658, 5097, 1013, 1013, 9385, 1006, 1039, 1007, 2418, 4830, 9397, 4135, 1013, 1013, 1013, 1013, 20...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: mheule@google.com (Markus Heule) // // Google C++ Testing Framework (Google Test) // // Sometimes it's desirable to build Google Test by compiling a single file. // This file serves this purpose. // This line ensures that gtest.h can be compiled on its own, even // when it's fused. #include "gtest.h" // The following lines pull in the real gtest *.cc files. // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // // The Google C++ Testing Framework (Google Test) // Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // // Utilities for testing Google Test itself and code that uses Google Test // (e.g. frameworks built on top of Google Test). #ifndef GTEST_INCLUDE_GTEST_GTEST_SPI_H_ #define GTEST_INCLUDE_GTEST_GTEST_SPI_H_ namespace testing { // This helper class can be used to mock out Google Test failure reporting // so that we can test Google Test or code that builds on Google Test. // // An object of this class appends a TestPartResult object to the // TestPartResultArray object given in the constructor whenever a Google Test // failure is reported. It can either intercept only failures that are // generated in the same thread that created this object or it can intercept // all generated failures. The scope of this mock object can be controlled with // the second argument to the two arguments constructor. class GTEST_API_ ScopedFakeTestPartResultReporter : public TestPartResultReporterInterface { public: // The two possible mocking modes of this object. enum InterceptMode { INTERCEPT_ONLY_CURRENT_THREAD, // Intercepts only thread local failures. INTERCEPT_ALL_THREADS // Intercepts all failures. }; // The c'tor sets this object as the test part result reporter used // by Google Test. The 'result' parameter specifies where to report the // results. This reporter will only catch failures generated in the current // thread. DEPRECATED explicit ScopedFakeTestPartResultReporter(TestPartResultArray* result); // Same as above, but you can choose the interception scope of this object. ScopedFakeTestPartResultReporter(InterceptMode intercept_mode, TestPartResultArray* result); // The d'tor restores the previous test part result reporter. virtual ~ScopedFakeTestPartResultReporter(); // Appends the TestPartResult object to the TestPartResultArray // received in the constructor. // // This method is from the TestPartResultReporterInterface // interface. virtual void ReportTestPartResult(const TestPartResult& result); private: void Init(); const InterceptMode intercept_mode_; TestPartResultReporterInterface* old_reporter_; TestPartResultArray* const result_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedFakeTestPartResultReporter); }; namespace internal { // A helper class for implementing EXPECT_FATAL_FAILURE() and // EXPECT_NONFATAL_FAILURE(). Its destructor verifies that the given // TestPartResultArray contains exactly one failure that has the given // type and contains the given substring. If that's not the case, a // non-fatal failure will be generated. class GTEST_API_ SingleFailureChecker { public: // The constructor remembers the arguments. SingleFailureChecker(const TestPartResultArray* results, TestPartResult::Type type, const string& substr); ~SingleFailureChecker(); private: const TestPartResultArray* const results_; const TestPartResult::Type type_; const string substr_; GTEST_DISALLOW_COPY_AND_ASSIGN_(SingleFailureChecker); }; } // namespace internal } // namespace testing // A set of macros for testing Google Test assertions or code that's expected // to generate Google Test fatal failures. It verifies that the given // statement will cause exactly one fatal Google Test failure with 'substr' // being part of the failure message. // // There are two different versions of this macro. EXPECT_FATAL_FAILURE only // affects and considers failures generated in the current thread and // EXPECT_FATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. // // The verification of the assertion is done correctly even when the statement // throws an exception or aborts the current function. // // Known restrictions: // - 'statement' cannot reference local non-static variables or // non-static members of the current object. // - 'statement' cannot return a value. // - You cannot stream a failure message to this macro. // // Note that even though the implementations of the following two // macros are much alike, we cannot refactor them to use a common // helper macro, due to some peculiarity in how the preprocessor // works. The AcceptsMacroThatExpandsToUnprotectedComma test in // gtest_unittest.cc will fail to compile if we do that. #define EXPECT_FATAL_FAILURE(statement, substr) \ do { \ class GTestExpectFatalFailureHelper {\ public:\ static void Execute() { statement; }\ };\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter:: \ INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\ GTestExpectFatalFailureHelper::Execute();\ }\ } while (::testing::internal::AlwaysFalse()) #define EXPECT_FATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ do { \ class GTestExpectFatalFailureHelper {\ public:\ static void Execute() { statement; }\ };\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ &gtest_failures, ::testing::TestPartResult::kFatalFailure, (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter:: \ INTERCEPT_ALL_THREADS, &gtest_failures);\ GTestExpectFatalFailureHelper::Execute();\ }\ } while (::testing::internal::AlwaysFalse()) // A macro for testing Google Test assertions or code that's expected to // generate Google Test non-fatal failures. It asserts that the given // statement will cause exactly one non-fatal Google Test failure with 'substr' // being part of the failure message. // // There are two different versions of this macro. EXPECT_NONFATAL_FAILURE only // affects and considers failures generated in the current thread and // EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS does the same but for all threads. // // 'statement' is allowed to reference local variables and members of // the current object. // // The verification of the assertion is done correctly even when the statement // throws an exception or aborts the current function. // // Known restrictions: // - You cannot stream a failure message to this macro. // // Note that even though the implementations of the following two // macros are much alike, we cannot refactor them to use a common // helper macro, due to some peculiarity in how the preprocessor // works. If we do that, the code won't compile when the user gives // EXPECT_NONFATAL_FAILURE() a statement that contains a macro that // expands to code containing an unprotected comma. The // AcceptsMacroThatExpandsToUnprotectedComma test in gtest_unittest.cc // catches that. // // For the same reason, we have to write // if (::testing::internal::AlwaysTrue()) { statement; } // instead of // GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_(statement) // to avoid an MSVC warning on unreachable code. #define EXPECT_NONFATAL_FAILURE(statement, substr) \ do {\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \ (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter:: \ INTERCEPT_ONLY_CURRENT_THREAD, &gtest_failures);\ if (::testing::internal::AlwaysTrue()) { statement; }\ }\ } while (::testing::internal::AlwaysFalse()) #define EXPECT_NONFATAL_FAILURE_ON_ALL_THREADS(statement, substr) \ do {\ ::testing::TestPartResultArray gtest_failures;\ ::testing::internal::SingleFailureChecker gtest_checker(\ &gtest_failures, ::testing::TestPartResult::kNonFatalFailure, \ (substr));\ {\ ::testing::ScopedFakeTestPartResultReporter gtest_reporter(\ ::testing::ScopedFakeTestPartResultReporter::INTERCEPT_ALL_THREADS, \ &gtest_failures);\ if (::testing::internal::AlwaysTrue()) { statement; }\ }\ } while (::testing::internal::AlwaysFalse()) #endif // GTEST_INCLUDE_GTEST_GTEST_SPI_H_ #include <ctype.h> #include <math.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <wchar.h> #include <wctype.h> #include <algorithm> #include <iomanip> #include <limits> #include <list> #include <map> #include <ostream> // NOLINT #include <sstream> #include <vector> #if GTEST_OS_LINUX // TODO(kenton@google.com): Use autoconf to detect availability of // gettimeofday(). # define GTEST_HAS_GETTIMEOFDAY_ 1 # include <fcntl.h> // NOLINT # include <limits.h> // NOLINT # include <sched.h> // NOLINT // Declares vsnprintf(). This header is not available on Windows. # include <strings.h> // NOLINT # include <sys/mman.h> // NOLINT # include <sys/time.h> // NOLINT # include <unistd.h> // NOLINT # include <string> #elif GTEST_OS_SYMBIAN # define GTEST_HAS_GETTIMEOFDAY_ 1 # include <sys/time.h> // NOLINT #elif GTEST_OS_ZOS # define GTEST_HAS_GETTIMEOFDAY_ 1 # include <sys/time.h> // NOLINT // On z/OS we additionally need strings.h for strcasecmp. # include <strings.h> // NOLINT #elif GTEST_OS_WINDOWS_MOBILE // We are on Windows CE. # include <windows.h> // NOLINT # undef min #elif GTEST_OS_WINDOWS // We are on Windows proper. # include <io.h> // NOLINT # include <sys/timeb.h> // NOLINT # include <sys/types.h> // NOLINT # include <sys/stat.h> // NOLINT # if GTEST_OS_WINDOWS_MINGW // MinGW has gettimeofday() but not _ftime64(). // TODO(kenton@google.com): Use autoconf to detect availability of // gettimeofday(). // TODO(kenton@google.com): There are other ways to get the time on // Windows, like GetTickCount() or GetSystemTimeAsFileTime(). MinGW // supports these. consider using them instead. # define GTEST_HAS_GETTIMEOFDAY_ 1 # include <sys/time.h> // NOLINT # endif // GTEST_OS_WINDOWS_MINGW // cpplint thinks that the header is already included, so we want to // silence it. # include <windows.h> // NOLINT # undef min #else // Assume other platforms have gettimeofday(). // TODO(kenton@google.com): Use autoconf to detect availability of // gettimeofday(). # define GTEST_HAS_GETTIMEOFDAY_ 1 // cpplint thinks that the header is already included, so we want to // silence it. # include <sys/time.h> // NOLINT # include <unistd.h> // NOLINT #endif // GTEST_OS_LINUX #if GTEST_HAS_EXCEPTIONS # include <stdexcept> #endif #if GTEST_CAN_STREAM_RESULTS_ # include <arpa/inet.h> // NOLINT # include <netdb.h> // NOLINT # include <sys/socket.h> // NOLINT # include <sys/types.h> // NOLINT #endif // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick is to // prevent a user from accidentally including gtest-internal-inl.h in // his code. #define GTEST_IMPLEMENTATION_ 1 // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Utility functions and classes used by the Google C++ testing framework. // // Author: wan@google.com (Zhanyong Wan) // // This file contains purely Google Test's internal implementation. Please // DO NOT #INCLUDE IT IN A USER PROGRAM. #ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_ #define GTEST_SRC_GTEST_INTERNAL_INL_H_ // GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is // part of Google Test's implementation; otherwise it's undefined. #if !GTEST_IMPLEMENTATION_ // If this file is included from the user's code, just say no. # error "gtest-internal-inl.h is part of Google Test's internal implementation." # error "It must not be included except by Google Test itself." #endif // GTEST_IMPLEMENTATION_ #ifndef _WIN32_WCE # include <errno.h> #endif // !_WIN32_WCE #include <stddef.h> #include <stdlib.h> // For strtoll/_strtoul64/malloc/free. #include <string.h> // For memmove. #include <algorithm> #include <string> #include <vector> #if GTEST_CAN_STREAM_RESULTS_ # include <arpa/inet.h> // NOLINT # include <netdb.h> // NOLINT #endif #if GTEST_OS_WINDOWS # include <windows.h> // NOLINT #endif // GTEST_OS_WINDOWS namespace testing { // Declares the flags. // // We don't want the users to modify this flag in the code, but want // Google Test's own unit tests to be able to access it. Therefore we // declare it here as opposed to in gtest.h. GTEST_DECLARE_bool_(death_test_use_fork); namespace internal { // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). GTEST_API_ extern const TypeId kTestTypeIdInGoogleTest; // Names of the flags (needed for parsing Google Test flags). const char kAlsoRunDisabledTestsFlag[] = "also_run_disabled_tests"; const char kBreakOnFailureFlag[] = "break_on_failure"; const char kCatchExceptionsFlag[] = "catch_exceptions"; const char kColorFlag[] = "color"; const char kFilterFlag[] = "filter"; const char kListTestsFlag[] = "list_tests"; const char kOutputFlag[] = "output"; const char kPrintTimeFlag[] = "print_time"; const char kRandomSeedFlag[] = "random_seed"; const char kRepeatFlag[] = "repeat"; const char kShuffleFlag[] = "shuffle"; const char kStackTraceDepthFlag[] = "stack_trace_depth"; const char kStreamResultToFlag[] = "stream_result_to"; const char kThrowOnFailureFlag[] = "throw_on_failure"; const char kFlagfileFlag[] = "flagfile"; // A valid random seed must be in [1, kMaxRandomSeed]. const int kMaxRandomSeed = 99999; // g_help_flag is true iff the --help flag or an equivalent form is // specified on the command line. GTEST_API_ extern bool g_help_flag; // Returns the current time in milliseconds. GTEST_API_ TimeInMillis GetTimeInMillis(); // Returns true iff Google Test should use colors in the output. GTEST_API_ bool ShouldUseColor(bool stdout_is_tty); // Formats the given time in milliseconds as seconds. GTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms); // Converts the given time in milliseconds to a date string in the ISO 8601 // format, without the timezone information. N.B.: due to the use the // non-reentrant localtime() function, this function is not thread safe. Do // not use it in any code that can be called from multiple threads. GTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms); // Parses a string for an Int32 flag, in the form of "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. GTEST_API_ bool ParseInt32Flag( const char* str, const char* flag, Int32* value); // Returns a random seed in range [1, kMaxRandomSeed] based on the // given --gtest_random_seed flag value. inline int GetRandomSeedFromFlag(Int32 random_seed_flag) { const unsigned int raw_seed = (random_seed_flag == 0) ? static_cast<unsigned int>(GetTimeInMillis()) : static_cast<unsigned int>(random_seed_flag); // Normalizes the actual seed to range [1, kMaxRandomSeed] such that // it's easy to type. const int normalized_seed = static_cast<int>((raw_seed - 1U) % static_cast<unsigned int>(kMaxRandomSeed)) + 1; return normalized_seed; } // Returns the first valid random seed after 'seed'. The behavior is // undefined if 'seed' is invalid. The seed after kMaxRandomSeed is // considered to be 1. inline int GetNextRandomSeed(int seed) { GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed) << "Invalid random seed " << seed << " - must be in [1, " << kMaxRandomSeed << "]."; const int next_seed = seed + 1; return (next_seed > kMaxRandomSeed) ? 1 : next_seed; } // This class saves the values of all Google Test flags in its c'tor, and // restores them in its d'tor. class GTestFlagSaver { public: // The c'tor. GTestFlagSaver() { also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests); break_on_failure_ = GTEST_FLAG(break_on_failure); catch_exceptions_ = GTEST_FLAG(catch_exceptions); color_ = GTEST_FLAG(color); death_test_style_ = GTEST_FLAG(death_test_style); death_test_use_fork_ = GTEST_FLAG(death_test_use_fork); filter_ = GTEST_FLAG(filter); internal_run_death_test_ = GTEST_FLAG(internal_run_death_test); list_tests_ = GTEST_FLAG(list_tests); output_ = GTEST_FLAG(output); print_time_ = GTEST_FLAG(print_time); random_seed_ = GTEST_FLAG(random_seed); repeat_ = GTEST_FLAG(repeat); shuffle_ = GTEST_FLAG(shuffle); stack_trace_depth_ = GTEST_FLAG(stack_trace_depth); stream_result_to_ = GTEST_FLAG(stream_result_to); throw_on_failure_ = GTEST_FLAG(throw_on_failure); } // The d'tor is not virtual. DO NOT INHERIT FROM THIS CLASS. ~GTestFlagSaver() { GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_; GTEST_FLAG(break_on_failure) = break_on_failure_; GTEST_FLAG(catch_exceptions) = catch_exceptions_; GTEST_FLAG(color) = color_; GTEST_FLAG(death_test_style) = death_test_style_; GTEST_FLAG(death_test_use_fork) = death_test_use_fork_; GTEST_FLAG(filter) = filter_; GTEST_FLAG(internal_run_death_test) = internal_run_death_test_; GTEST_FLAG(list_tests) = list_tests_; GTEST_FLAG(output) = output_; GTEST_FLAG(print_time) = print_time_; GTEST_FLAG(random_seed) = random_seed_; GTEST_FLAG(repeat) = repeat_; GTEST_FLAG(shuffle) = shuffle_; GTEST_FLAG(stack_trace_depth) = stack_trace_depth_; GTEST_FLAG(stream_result_to) = stream_result_to_; GTEST_FLAG(throw_on_failure) = throw_on_failure_; } private: // Fields for saving the original values of flags. bool also_run_disabled_tests_; bool break_on_failure_; bool catch_exceptions_; std::string color_; std::string death_test_style_; bool death_test_use_fork_; std::string filter_; std::string internal_run_death_test_; bool list_tests_; std::string output_; bool print_time_; internal::Int32 random_seed_; internal::Int32 repeat_; bool shuffle_; internal::Int32 stack_trace_depth_; std::string stream_result_to_; bool throw_on_failure_; } GTEST_ATTRIBUTE_UNUSED_; // Converts a Unicode code point to a narrow string in UTF-8 encoding. // code_point parameter is of type UInt32 because wchar_t may not be // wide enough to contain a code point. // If the code_point is not a valid Unicode code point // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted // to "(Invalid Unicode 0xXXXXXXXX)". GTEST_API_ std::string CodePointToUtf8(UInt32 code_point); // Converts a wide string to a narrow string in UTF-8 encoding. // The wide string is assumed to have the following encoding: // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) // UTF-32 if sizeof(wchar_t) == 4 (on Linux) // Parameter str points to a null-terminated wide string. // Parameter num_chars may additionally limit the number // of wchar_t characters processed. -1 is used when the entire string // should be processed. // If the string contains code points that are not valid Unicode code points // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. GTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars); // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file // if the variable is present. If a file already exists at this location, this // function will write over it. If the variable is present, but the file cannot // be created, prints an error and exits. void WriteToShardStatusFileIfNeeded(); // Checks whether sharding is enabled by examining the relevant // environment variable values. If the variables are present, // but inconsistent (e.g., shard_index >= total_shards), prints // an error and exits. If in_subprocess_for_death_test, sharding is // disabled because it must only be applied to the original test // process. Otherwise, we could filter out death tests we intended to execute. GTEST_API_ bool ShouldShard(const char* total_shards_str, const char* shard_index_str, bool in_subprocess_for_death_test); // Parses the environment variable var as an Int32. If it is unset, // returns default_val. If it is not an Int32, prints an error and // and aborts. GTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val); // Given the total number of shards, the shard index, and the test id, // returns true iff the test should be run on this shard. The test id is // some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. GTEST_API_ bool ShouldRunTestOnShard( int total_shards, int shard_index, int test_id); // STL container utilities. // Returns the number of elements in the given container that satisfy // the given predicate. template <class Container, typename Predicate> inline int CountIf(const Container& c, Predicate predicate) { // Implemented as an explicit loop since std::count_if() in libCstd on // Solaris has a non-standard signature. int count = 0; for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) { if (predicate(*it)) ++count; } return count; } // Applies a function/functor to each element in the container. template <class Container, typename Functor> void ForEach(const Container& c, Functor functor) { std::for_each(c.begin(), c.end(), functor); } // Returns the i-th element of the vector, or default_value if i is not // in range [0, v.size()). template <typename E> inline E GetElementOr(const std::vector<E>& v, int i, E default_value) { return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i]; } // Performs an in-place shuffle of a range of the vector's elements. // 'begin' and 'end' are element indices as an STL-style range; // i.e. [begin, end) are shuffled, where 'end' == size() means to // shuffle to the end of the vector. template <typename E> void ShuffleRange(internal::Random* random, int begin, int end, std::vector<E>* v) { const int size = static_cast<int>(v->size()); GTEST_CHECK_(0 <= begin && begin <= size) << "Invalid shuffle range start " << begin << ": must be in range [0, " << size << "]."; GTEST_CHECK_(begin <= end && end <= size) << "Invalid shuffle range finish " << end << ": must be in range [" << begin << ", " << size << "]."; // Fisher-Yates shuffle, from // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle for (int range_width = end - begin; range_width >= 2; range_width--) { const int last_in_range = begin + range_width - 1; const int selected = begin + random->Generate(range_width); std::swap((*v)[selected], (*v)[last_in_range]); } } // Performs an in-place shuffle of the vector's elements. template <typename E> inline void Shuffle(internal::Random* random, std::vector<E>* v) { ShuffleRange(random, 0, static_cast<int>(v->size()), v); } // A function for deleting an object. Handy for being used as a // functor. template <typename T> static void Delete(T* x) { delete x; } // A predicate that checks the key of a TestProperty against a known key. // // TestPropertyKeyIs is copyable. class TestPropertyKeyIs { public: // Constructor. // // TestPropertyKeyIs has NO default constructor. explicit TestPropertyKeyIs(const std::string& key) : key_(key) {} // Returns true iff the test name of test property matches on key_. bool operator()(const TestProperty& test_property) const { return test_property.key() == key_; } private: std::string key_; }; // Class UnitTestOptions. // // This class contains functions for processing options the user // specifies when running the tests. It has only static members. // // In most cases, the user can specify an option using either an // environment variable or a command line flag. E.g. you can set the // test filter using either GTEST_FILTER or --gtest_filter. If both // the variable and the flag are present, the latter overrides the // former. class GTEST_API_ UnitTestOptions { public: // Functions for processing the gtest_output flag. // Returns the output format, or "" for normal printed output. static std::string GetOutputFormat(); // Returns the absolute path of the requested output file, or the // default (test_detail.xml in the original working directory) if // none was explicitly specified. static std::string GetAbsolutePathToOutputFile(); // Functions for processing the gtest_filter flag. // Returns true iff the wildcard pattern matches the string. The // first ':' or '\0' character in pattern marks the end of it. // // This recursive algorithm isn't very efficient, but is clear and // works well enough for matching test names, which are short. static bool PatternMatchesString(const char *pattern, const char *str); // Returns true iff the user-specified filter matches the test case // name and the test name. static bool FilterMatchesTest(const std::string &test_case_name, const std::string &test_name); #if GTEST_OS_WINDOWS // Function for supporting the gtest_catch_exception flag. // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. // This function is useful as an __except condition. static int GTestShouldProcessSEH(DWORD exception_code); #endif // GTEST_OS_WINDOWS // Returns true if "name" matches the ':' separated list of glob-style // filters in "filter". static bool MatchesFilter(const std::string& name, const char* filter); }; // Returns the current application's name, removing directory path if that // is present. Used by UnitTestOptions::GetOutputFile. GTEST_API_ FilePath GetCurrentExecutableName(); // The role interface for getting the OS stack trace as a string. class OsStackTraceGetterInterface { public: OsStackTraceGetterInterface() {} virtual ~OsStackTraceGetterInterface() {} // Returns the current OS stack trace as an std::string. Parameters: // // max_depth - the maximum number of stack frames to be included // in the trace. // skip_count - the number of top frames to be skipped; doesn't count // against max_depth. virtual string CurrentStackTrace(int max_depth, int skip_count) = 0; // UponLeavingGTest() should be called immediately before Google Test calls // user code. It saves some information about the current stack that // CurrentStackTrace() will use to find and hide Google Test stack frames. virtual void UponLeavingGTest() = 0; // This string is inserted in place of stack frames that are part of // Google Test's implementation. static const char* const kElidedFramesMarker; private: GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface); }; // A working implementation of the OsStackTraceGetterInterface interface. class OsStackTraceGetter : public OsStackTraceGetterInterface { public: OsStackTraceGetter() {} virtual string CurrentStackTrace(int max_depth, int skip_count); virtual void UponLeavingGTest(); private: GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter); }; // Information about a Google Test trace point. struct TraceInfo { const char* file; int line; std::string message; }; // This is the default global test part result reporter used in UnitTestImpl. // This class should only be used by UnitTestImpl. class DefaultGlobalTestPartResultReporter : public TestPartResultReporterInterface { public: explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. Reports the test part // result in the current test. virtual void ReportTestPartResult(const TestPartResult& result); private: UnitTestImpl* const unit_test_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter); }; // This is the default per thread test part result reporter used in // UnitTestImpl. This class should only be used by UnitTestImpl. class DefaultPerThreadTestPartResultReporter : public TestPartResultReporterInterface { public: explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test); // Implements the TestPartResultReporterInterface. The implementation just // delegates to the current global test part result reporter of *unit_test_. virtual void ReportTestPartResult(const TestPartResult& result); private: UnitTestImpl* const unit_test_; GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter); }; // The private implementation of the UnitTest class. We don't protect // the methods under a mutex, as this class is not accessible by a // user and the UnitTest class that delegates work to this class does // proper locking. class GTEST_API_ UnitTestImpl { public: explicit UnitTestImpl(UnitTest* parent); virtual ~UnitTestImpl(); // There are two different ways to register your own TestPartResultReporter. // You can register your own repoter to listen either only for test results // from the current thread or for results from all threads. // By default, each per-thread test result repoter just passes a new // TestPartResult to the global test result reporter, which registers the // test part result for the currently running test. // Returns the global test part result reporter. TestPartResultReporterInterface* GetGlobalTestPartResultReporter(); // Sets the global test part result reporter. void SetGlobalTestPartResultReporter( TestPartResultReporterInterface* reporter); // Returns the test part result reporter for the current thread. TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread(); // Sets the test part result reporter for the current thread. void SetTestPartResultReporterForCurrentThread( TestPartResultReporterInterface* reporter); // Gets the number of successful test cases. int successful_test_case_count() const; // Gets the number of failed test cases. int failed_test_case_count() const; // Gets the number of all test cases. int total_test_case_count() const; // Gets the number of all test cases that contain at least one test // that should run. int test_case_to_run_count() const; // Gets the number of successful tests. int successful_test_count() const; // Gets the number of failed tests. int failed_test_count() const; // Gets the number of disabled tests that will be reported in the XML report. int reportable_disabled_test_count() const; // Gets the number of disabled tests. int disabled_test_count() const; // Gets the number of tests to be printed in the XML report. int reportable_test_count() const; // Gets the number of all tests. int total_test_count() const; // Gets the number of tests that should run. int test_to_run_count() const; // Gets the time of the test program start, in ms from the start of the // UNIX epoch. TimeInMillis start_timestamp() const { return start_timestamp_; } // Gets the elapsed time, in milliseconds. TimeInMillis elapsed_time() const { return elapsed_time_; } // Returns true iff the unit test passed (i.e. all test cases passed). bool Passed() const { return !Failed(); } // Returns true iff the unit test failed (i.e. some test case failed // or something outside of all tests failed). bool Failed() const { return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed(); } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. const TestCase* GetTestCase(int i) const { const int index = GetElementOr(test_case_indices_, i, -1); return index < 0 ? NULL : test_cases_[i]; } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. TestCase* GetMutableTestCase(int i) { const int index = GetElementOr(test_case_indices_, i, -1); return index < 0 ? NULL : test_cases_[index]; } // Provides access to the event listener list. TestEventListeners* listeners() { return &listeners_; } // Returns the TestResult for the test that's currently running, or // the TestResult for the ad hoc test if no test is running. TestResult* current_test_result(); // Returns the TestResult for the ad hoc test. const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; } // Sets the OS stack trace getter. // // Does nothing if the input and the current OS stack trace getter // are the same; otherwise, deletes the old getter and makes the // input the current getter. void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter); // Returns the current OS stack trace getter if it is not NULL; // otherwise, creates an OsStackTraceGetter, makes it the current // getter, and returns it. OsStackTraceGetterInterface* os_stack_trace_getter(); // Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // CurrentOsStackTraceExceptTop(1), Foo() will be included in the // trace but Bar() and CurrentOsStackTraceExceptTop() won't. std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_; // Finds and returns a TestCase with the given name. If one doesn't // exist, creates one and returns it. // // Arguments: // // test_case_name: name of the test case // type_param: the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case TestCase* GetTestCase(const char* test_case_name, const char* type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc); // Adds a TestInfo to the unit test. // // Arguments: // // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case // test_info: the TestInfo object void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc, TestInfo* test_info) { // In order to support thread-safe death tests, we need to // remember the original working directory when the test program // was first invoked. We cannot do this in RUN_ALL_TESTS(), as // the user may have changed the current directory before calling // RUN_ALL_TESTS(). Therefore we capture the current directory in // AddTestInfo(), which is called to register a TEST or TEST_F // before main() is reached. if (original_working_dir_.IsEmpty()) { original_working_dir_.Set(FilePath::GetCurrentDir()); GTEST_CHECK_(!original_working_dir_.IsEmpty()) << "Failed to get the current working directory."; } GetTestCase(test_info->test_case_name(), test_info->type_param(), set_up_tc, tear_down_tc)->AddTestInfo(test_info); } #if GTEST_HAS_PARAM_TEST // Returns ParameterizedTestCaseRegistry object used to keep track of // value-parameterized tests and instantiate and register them. internal::ParameterizedTestCaseRegistry& parameterized_test_registry() { return parameterized_test_registry_; } #endif // GTEST_HAS_PARAM_TEST // Sets the TestCase object for the test that's currently running. void set_current_test_case(TestCase* a_current_test_case) { current_test_case_ = a_current_test_case; } // Sets the TestInfo object for the test that's currently running. If // current_test_info is NULL, the assertion results will be stored in // ad_hoc_test_result_. void set_current_test_info(TestInfo* a_current_test_info) { current_test_info_ = a_current_test_info; } // Registers all parameterized tests defined using TEST_P and // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter // combination. This method can be called more then once; it has guards // protecting from registering the tests more then once. If // value-parameterized tests are disabled, RegisterParameterizedTests is // present but does nothing. void RegisterParameterizedTests(); // Runs all tests in this UnitTest object, prints the result, and // returns true if all tests are successful. If any exception is // thrown during a test, this test is considered to be failed, but // the rest of the tests will still be run. bool RunAllTests(); // Clears the results of all tests, except the ad hoc tests. void ClearNonAdHocTestResult() { ForEach(test_cases_, TestCase::ClearTestCaseResult); } // Clears the results of ad-hoc test assertions. void ClearAdHocTestResult() { ad_hoc_test_result_.Clear(); } // Adds a TestProperty to the current TestResult object when invoked in a // context of a test or a test case, or to the global property set. If the // result already contains a property with the same key, the value will be // updated. void RecordProperty(const TestProperty& test_property); enum ReactionToSharding { HONOR_SHARDING_PROTOCOL, IGNORE_SHARDING_PROTOCOL }; // Matches the full name of each test against the user-specified // filter to decide whether the test should run, then records the // result in each TestCase and TestInfo object. // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests // based on sharding variables in the environment. // Returns the number of tests that should run. int FilterTests(ReactionToSharding shard_tests); // Prints the names of the tests matching the user-specified filter flag. void ListTestsMatchingFilter(); const TestCase* current_test_case() const { return current_test_case_; } TestInfo* current_test_info() { return current_test_info_; } const TestInfo* current_test_info() const { return current_test_info_; } // Returns the vector of environments that need to be set-up/torn-down // before/after the tests are run. std::vector<Environment*>& environments() { return environments_; } // Getters for the per-thread Google Test trace stack. std::vector<TraceInfo>& gtest_trace_stack() { return *(gtest_trace_stack_.pointer()); } const std::vector<TraceInfo>& gtest_trace_stack() const { return gtest_trace_stack_.get(); } #if GTEST_HAS_DEATH_TEST void InitDeathTestSubprocessControlInfo() { internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag()); } // Returns a pointer to the parsed --gtest_internal_run_death_test // flag, or NULL if that flag was not specified. // This information is useful only in a death test child process. // Must not be called before a call to InitGoogleTest. const InternalRunDeathTestFlag* internal_run_death_test_flag() const { return internal_run_death_test_flag_.get(); } // Returns a pointer to the current death test factory. internal::DeathTestFactory* death_test_factory() { return death_test_factory_.get(); } void SuppressTestEventsIfInSubprocess(); friend class ReplaceDeathTestFactory; #endif // GTEST_HAS_DEATH_TEST // Initializes the event listener performing XML output as specified by // UnitTestOptions. Must not be called before InitGoogleTest. void ConfigureXmlOutput(); #if GTEST_CAN_STREAM_RESULTS_ // Initializes the event listener for streaming test results to a socket. // Must not be called before InitGoogleTest. void ConfigureStreamingOutput(); #endif // Performs initialization dependent upon flag values obtained in // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest // this function is also called from RunAllTests. Since this function can be // called more than once, it has to be idempotent. void PostFlagParsingInit(); // Gets the random seed used at the start of the current test iteration. int random_seed() const { return random_seed_; } // Gets the random number generator. internal::Random* random() { return &random_; } // Shuffles all test cases, and the tests within each test case, // making sure that death tests are still run first. void ShuffleTests(); // Restores the test cases and tests to their order before the first shuffle. void UnshuffleTests(); // Returns the value of GTEST_FLAG(catch_exceptions) at the moment // UnitTest::Run() starts. bool catch_exceptions() const { return catch_exceptions_; } private: friend class ::testing::UnitTest; // Used by UnitTest::Run() to capture the state of // GTEST_FLAG(catch_exceptions) at the moment it starts. void set_catch_exceptions(bool value) { catch_exceptions_ = value; } // The UnitTest object that owns this implementation object. UnitTest* const parent_; // The working directory when the first TEST() or TEST_F() was // executed. internal::FilePath original_working_dir_; // The default test part result reporters. DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_; DefaultPerThreadTestPartResultReporter default_per_thread_test_part_result_reporter_; // Points to (but doesn't own) the global test part result reporter. TestPartResultReporterInterface* global_test_part_result_repoter_; // Protects read and write access to global_test_part_result_reporter_. internal::Mutex global_test_part_result_reporter_mutex_; // Points to (but doesn't own) the per-thread test part result reporter. internal::ThreadLocal<TestPartResultReporterInterface*> per_thread_test_part_result_reporter_; // The vector of environments that need to be set-up/torn-down // before/after the tests are run. std::vector<Environment*> environments_; // The vector of TestCases in their original order. It owns the // elements in the vector. std::vector<TestCase*> test_cases_; // Provides a level of indirection for the test case list to allow // easy shuffling and restoring the test case order. The i-th // element of this vector is the index of the i-th test case in the // shuffled order. std::vector<int> test_case_indices_; #if GTEST_HAS_PARAM_TEST // ParameterizedTestRegistry object used to register value-parameterized // tests. internal::ParameterizedTestCaseRegistry parameterized_test_registry_; // Indicates whether RegisterParameterizedTests() has been called already. bool parameterized_tests_registered_; #endif // GTEST_HAS_PARAM_TEST // Index of the last death test case registered. Initially -1. int last_death_test_case_; // This points to the TestCase for the currently running test. It // changes as Google Test goes through one test case after another. // When no test is running, this is set to NULL and Google Test // stores assertion results in ad_hoc_test_result_. Initially NULL. TestCase* current_test_case_; // This points to the TestInfo for the currently running test. It // changes as Google Test goes through one test after another. When // no test is running, this is set to NULL and Google Test stores // assertion results in ad_hoc_test_result_. Initially NULL. TestInfo* current_test_info_; // Normally, a user only writes assertions inside a TEST or TEST_F, // or inside a function called by a TEST or TEST_F. Since Google // Test keeps track of which test is current running, it can // associate such an assertion with the test it belongs to. // // If an assertion is encountered when no TEST or TEST_F is running, // Google Test attributes the assertion result to an imaginary "ad hoc" // test, and records the result in ad_hoc_test_result_. TestResult ad_hoc_test_result_; // The list of event listeners that can be used to track events inside // Google Test. TestEventListeners listeners_; // The OS stack trace getter. Will be deleted when the UnitTest // object is destructed. By default, an OsStackTraceGetter is used, // but the user can set this field to use a custom getter if that is // desired. OsStackTraceGetterInterface* os_stack_trace_getter_; // True iff PostFlagParsingInit() has been called. bool post_flag_parse_init_performed_; // The random number seed used at the beginning of the test run. int random_seed_; // Our random number generator. internal::Random random_; // The time of the test program start, in ms from the start of the // UNIX epoch. TimeInMillis start_timestamp_; // How long the test took to run, in milliseconds. TimeInMillis elapsed_time_; #if GTEST_HAS_DEATH_TEST // The decomposed components of the gtest_internal_run_death_test flag, // parsed when RUN_ALL_TESTS is called. internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_; internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_; #endif // GTEST_HAS_DEATH_TEST // A per-thread stack of traces created by the SCOPED_TRACE() macro. internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_; // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests() // starts. bool catch_exceptions_; GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl); }; // class UnitTestImpl // Convenience function for accessing the global UnitTest // implementation object. inline UnitTestImpl* GetUnitTestImpl() { return UnitTest::GetInstance()->impl(); } #if GTEST_USES_SIMPLE_RE // Internal helper functions for implementing the simple regular // expression matcher. GTEST_API_ bool IsInSet(char ch, const char* str); GTEST_API_ bool IsAsciiDigit(char ch); GTEST_API_ bool IsAsciiPunct(char ch); GTEST_API_ bool IsRepeat(char ch); GTEST_API_ bool IsAsciiWhiteSpace(char ch); GTEST_API_ bool IsAsciiWordChar(char ch); GTEST_API_ bool IsValidEscape(char ch); GTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch); GTEST_API_ bool ValidateRegex(const char* regex); GTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str); GTEST_API_ bool MatchRepetitionAndRegexAtHead( bool escaped, char ch, char repeat, const char* regex, const char* str); GTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str); #endif // GTEST_USES_SIMPLE_RE // Parses the command line for Google Test flags, without initializing // other parts of Google Test. GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv); GTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv); #if GTEST_HAS_DEATH_TEST // Returns the message describing the last system error, regardless of the // platform. GTEST_API_ std::string GetLastErrnoDescription(); // Attempts to parse a string into a positive integer pointed to by the // number parameter. Returns true if that is possible. // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use // it here. template <typename Integer> bool ParseNaturalNumber(const ::std::string& str, Integer* number) { // Fail fast if the given string does not begin with a digit; // this bypasses strtoXXX's "optional leading whitespace and plus // or minus sign" semantics, which are undesirable here. if (str.empty() || !IsDigit(str[0])) { return false; } errno = 0; char* end; // BiggestConvertible is the largest integer type that system-provided // string-to-number conversion routines can return. # if GTEST_OS_WINDOWS && !defined(__GNUC__) // MSVC and C++ Builder define __int64 instead of the standard long long. typedef unsigned __int64 BiggestConvertible; const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10); # else typedef unsigned long long BiggestConvertible; // NOLINT const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10); # endif // GTEST_OS_WINDOWS && !defined(__GNUC__) const bool parse_success = *end == '\0' && errno == 0; // TODO(vladl@google.com): Convert this to compile time assertion when it is // available. GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed)); const Integer result = static_cast<Integer>(parsed); if (parse_success && static_cast<BiggestConvertible>(result) == parsed) { *number = result; return true; } return false; } #endif // GTEST_HAS_DEATH_TEST // TestResult contains some private methods that should be hidden from // Google Test user but are required for testing. This class allow our tests // to access them. // // This class is supplied only for the purpose of testing Google Test's own // constructs. Do not use it in user tests, either directly or indirectly. class TestResultAccessor { public: static void RecordProperty(TestResult* test_result, const std::string& xml_element, const TestProperty& property) { test_result->RecordProperty(xml_element, property); } static void ClearTestPartResults(TestResult* test_result) { test_result->ClearTestPartResults(); } static const std::vector<testing::TestPartResult>& test_part_results( const TestResult& test_result) { return test_result.test_part_results(); } }; #if GTEST_CAN_STREAM_RESULTS_ // Streams test results to the given port on the given host machine. class GTEST_API_ StreamingListener : public EmptyTestEventListener { public: // Abstract base class for writing strings to a socket. class AbstractSocketWriter { public: virtual ~AbstractSocketWriter() {} // Sends a string to the socket. virtual void Send(const string& message) = 0; // Closes the socket. virtual void CloseConnection() {} // Sends a string and a newline to the socket. void SendLn(const string& message) { Send(message + "\n"); } }; // Concrete class for actually writing strings to a socket. class SocketWriter : public AbstractSocketWriter { public: SocketWriter(const string& host, const string& port) : sockfd_(-1), host_name_(host), port_num_(port) { MakeConnection(); } virtual ~SocketWriter() { if (sockfd_ != -1) CloseConnection(); } // Sends a string to the socket. virtual void Send(const string& message) { GTEST_CHECK_(sockfd_ != -1) << "Send() can be called only when there is a connection."; const int len = static_cast<int>(message.length()); if (write(sockfd_, message.c_str(), len) != len) { GTEST_LOG_(WARNING) << "stream_result_to: failed to stream to " << host_name_ << ":" << port_num_; } } private: // Creates a client socket and connects to the server. void MakeConnection(); // Closes the socket. void CloseConnection() { GTEST_CHECK_(sockfd_ != -1) << "CloseConnection() can be called only when there is a connection."; close(sockfd_); sockfd_ = -1; } int sockfd_; // socket file descriptor const string host_name_; const string port_num_; GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter); }; // class SocketWriter // Escapes '=', '&', '%', and '\n' characters in str as "%xx". static string UrlEncode(const char* str); StreamingListener(const string& host, const string& port) : socket_writer_(new SocketWriter(host, port)) { Start(); } explicit StreamingListener(AbstractSocketWriter* socket_writer) : socket_writer_(socket_writer) { Start(); } void OnTestProgramStart(const UnitTest& /* unit_test */) { SendLn("event=TestProgramStart"); } void OnTestProgramEnd(const UnitTest& unit_test) { // Note that Google Test current only report elapsed time for each // test iteration, not for the entire test program. SendLn("event=TestProgramEnd&passed=" + FormatBool(unit_test.Passed())); // Notify the streaming server to stop. socket_writer_->CloseConnection(); } void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) { SendLn("event=TestIterationStart&iteration=" + StreamableToString(iteration)); } void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) { SendLn("event=TestIterationEnd&passed=" + FormatBool(unit_test.Passed()) + "&elapsed_time=" + StreamableToString(unit_test.elapsed_time()) + "ms"); } void OnTestCaseStart(const TestCase& test_case) { SendLn(std::string("event=TestCaseStart&name=") + test_case.name()); } void OnTestCaseEnd(const TestCase& test_case) { SendLn("event=TestCaseEnd&passed=" + FormatBool(test_case.Passed()) + "&elapsed_time=" + StreamableToString(test_case.elapsed_time()) + "ms"); } void OnTestStart(const TestInfo& test_info) { SendLn(std::string("event=TestStart&name=") + test_info.name()); } void OnTestEnd(const TestInfo& test_info) { SendLn("event=TestEnd&passed=" + FormatBool((test_info.result())->Passed()) + "&elapsed_time=" + StreamableToString((test_info.result())->elapsed_time()) + "ms"); } void OnTestPartResult(const TestPartResult& test_part_result) { const char* file_name = test_part_result.file_name(); if (file_name == NULL) file_name = ""; SendLn("event=TestPartResult&file=" + UrlEncode(file_name) + "&line=" + StreamableToString(test_part_result.line_number()) + "&message=" + UrlEncode(test_part_result.message())); } private: // Sends the given message and a newline to the socket. void SendLn(const string& message) { socket_writer_->SendLn(message); } // Called at the start of streaming to notify the receiver what // protocol we are using. void Start() { SendLn("gtest_streaming_protocol_version=1.0"); } string FormatBool(bool value) { return value ? "1" : "0"; } const scoped_ptr<AbstractSocketWriter> socket_writer_; GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener); }; // class StreamingListener #endif // GTEST_CAN_STREAM_RESULTS_ } // namespace internal } // namespace testing #endif // GTEST_SRC_GTEST_INTERNAL_INL_H_ #undef GTEST_IMPLEMENTATION_ #if GTEST_OS_WINDOWS # define vsnprintf _vsnprintf #endif // GTEST_OS_WINDOWS namespace testing { using internal::CountIf; using internal::ForEach; using internal::GetElementOr; using internal::Shuffle; // Constants. // A test whose test case name or test name matches this filter is // disabled and not run. static const char kDisableTestFilter[] = "DISABLED_*:*/DISABLED_*"; // A test case whose name matches this filter is considered a death // test case and will be run before test cases whose name doesn't // match this filter. static const char kDeathTestCaseFilter[] = "*DeathTest:*DeathTest/*"; // A test filter that matches everything. static const char kUniversalFilter[] = "*"; // The default output file for XML output. static const char kDefaultOutputFile[] = "test_detail.xml"; // The environment variable name for the test shard index. static const char kTestShardIndex[] = "GTEST_SHARD_INDEX"; // The environment variable name for the total number of test shards. static const char kTestTotalShards[] = "GTEST_TOTAL_SHARDS"; // The environment variable name for the test shard status file. static const char kTestShardStatusFile[] = "GTEST_SHARD_STATUS_FILE"; namespace internal { // The text used in failure messages to indicate the start of the // stack trace. const char kStackTraceMarker[] = "\nStack trace:\n"; // g_help_flag is true iff the --help flag or an equivalent form is // specified on the command line. bool g_help_flag = false; } // namespace internal static const char* GetDefaultFilter() { #ifdef GTEST_TEST_FILTER_ENV_VAR_ const char* const testbridge_test_only = getenv(GTEST_TEST_FILTER_ENV_VAR_); if (testbridge_test_only != NULL) { return testbridge_test_only; } #endif // GTEST_TEST_FILTER_ENV_VAR_ return kUniversalFilter; } GTEST_DEFINE_bool_( also_run_disabled_tests, internal::BoolFromGTestEnv("also_run_disabled_tests", false), "Run disabled tests too, in addition to the tests normally being run."); GTEST_DEFINE_bool_( break_on_failure, internal::BoolFromGTestEnv("break_on_failure", false), "True iff a failed assertion should be a debugger break-point."); GTEST_DEFINE_bool_( catch_exceptions, internal::BoolFromGTestEnv("catch_exceptions", true), "True iff " GTEST_NAME_ " should catch exceptions and treat them as test failures."); GTEST_DEFINE_string_( color, internal::StringFromGTestEnv("color", "auto"), "Whether to use colors in the output. Valid values: yes, no, " "and auto. 'auto' means to use colors if the output is " "being sent to a terminal and the TERM environment variable " "is set to a terminal type that supports colors."); GTEST_DEFINE_string_( filter, internal::StringFromGTestEnv("filter", GetDefaultFilter()), "A colon-separated list of glob (not regex) patterns " "for filtering the tests to run, optionally followed by a " "'-' and a : separated list of negative patterns (tests to " "exclude). A test is run if it matches one of the positive " "patterns and does not match any of the negative patterns."); GTEST_DEFINE_bool_(list_tests, false, "List all tests without running them."); GTEST_DEFINE_string_( output, internal::StringFromGTestEnv("output", ""), "A format (currently must be \"xml\"), optionally followed " "by a colon and an output file name or directory. A directory " "is indicated by a trailing pathname separator. " "Examples: \"xml:filename.xml\", \"xml::directoryname/\". " "If a directory is specified, output files will be created " "within that directory, with file-names based on the test " "executable's name and, if necessary, made unique by adding " "digits."); GTEST_DEFINE_bool_( print_time, internal::BoolFromGTestEnv("print_time", true), "True iff " GTEST_NAME_ " should display elapsed time in text output."); GTEST_DEFINE_int32_( random_seed, internal::Int32FromGTestEnv("random_seed", 0), "Random number seed to use when shuffling test orders. Must be in range " "[1, 99999], or 0 to use a seed based on the current time."); GTEST_DEFINE_int32_( repeat, internal::Int32FromGTestEnv("repeat", 1), "How many times to repeat each test. Specify a negative number " "for repeating forever. Useful for shaking out flaky tests."); GTEST_DEFINE_bool_( show_internal_stack_frames, false, "True iff " GTEST_NAME_ " should include internal stack frames when " "printing test failure stack traces."); GTEST_DEFINE_bool_( shuffle, internal::BoolFromGTestEnv("shuffle", false), "True iff " GTEST_NAME_ " should randomize tests' order on every run."); GTEST_DEFINE_int32_( stack_trace_depth, internal::Int32FromGTestEnv("stack_trace_depth", kMaxStackTraceDepth), "The maximum number of stack frames to print when an " "assertion fails. The valid range is 0 through 100, inclusive."); GTEST_DEFINE_string_( stream_result_to, internal::StringFromGTestEnv("stream_result_to", ""), "This flag specifies the host name and the port number on which to stream " "test results. Example: \"localhost:555\". The flag is effective only on " "Linux."); GTEST_DEFINE_bool_( throw_on_failure, internal::BoolFromGTestEnv("throw_on_failure", false), "When this flag is specified, a failed assertion will throw an exception " "if exceptions are enabled or exit the program with a non-zero code " "otherwise."); #if GTEST_USE_OWN_FLAGFILE_FLAG_ GTEST_DEFINE_string_( flagfile, internal::StringFromGTestEnv("flagfile", ""), "This flag specifies the flagfile to read command-line flags from."); #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ namespace internal { // Generates a random number from [0, range), using a Linear // Congruential Generator (LCG). Crashes if 'range' is 0 or greater // than kMaxRange. UInt32 Random::Generate(UInt32 range) { // These constants are the same as are used in glibc's rand(3). state_ = (1103515245U*state_ + 12345U) % kMaxRange; GTEST_CHECK_(range > 0) << "Cannot generate a number in the range [0, 0)."; GTEST_CHECK_(range <= kMaxRange) << "Generation of a number in [0, " << range << ") was requested, " << "but this can only generate numbers in [0, " << kMaxRange << ")."; // Converting via modulus introduces a bit of downward bias, but // it's simple, and a linear congruential generator isn't too good // to begin with. return state_ % range; } // GTestIsInitialized() returns true iff the user has initialized // Google Test. Useful for catching the user mistake of not initializing // Google Test before calling RUN_ALL_TESTS(). static bool GTestIsInitialized() { return GetArgvs().size() > 0; } // Iterates over a vector of TestCases, keeping a running sum of the // results of calling a given int-returning method on each. // Returns the sum. static int SumOverTestCaseList(const std::vector<TestCase*>& case_list, int (TestCase::*method)() const) { int sum = 0; for (size_t i = 0; i < case_list.size(); i++) { sum += (case_list[i]->*method)(); } return sum; } // Returns true iff the test case passed. static bool TestCasePassed(const TestCase* test_case) { return test_case->should_run() && test_case->Passed(); } // Returns true iff the test case failed. static bool TestCaseFailed(const TestCase* test_case) { return test_case->should_run() && test_case->Failed(); } // Returns true iff test_case contains at least one test that should // run. static bool ShouldRunTestCase(const TestCase* test_case) { return test_case->should_run(); } // AssertHelper constructor. AssertHelper::AssertHelper(TestPartResult::Type type, const char* file, int line, const char* message) : data_(new AssertHelperData(type, file, line, message)) { } AssertHelper::~AssertHelper() { delete data_; } // Message assignment, for assertion streaming support. void AssertHelper::operator=(const Message& message) const { UnitTest::GetInstance()-> AddTestPartResult(data_->type, data_->file, data_->line, AppendUserMessage(data_->message, message), UnitTest::GetInstance()->impl() ->CurrentOsStackTraceExceptTop(1) // Skips the stack frame for this function itself. ); // NOLINT } // Mutex for linked pointers. GTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex); // A copy of all command line arguments. Set by InitGoogleTest(). ::std::vector<testing::internal::string> g_argvs; const ::std::vector<testing::internal::string>& GetArgvs() { #if defined(GTEST_CUSTOM_GET_ARGVS_) return GTEST_CUSTOM_GET_ARGVS_(); #else // defined(GTEST_CUSTOM_GET_ARGVS_) return g_argvs; #endif // defined(GTEST_CUSTOM_GET_ARGVS_) } // Returns the current application's name, removing directory path if that // is present. FilePath GetCurrentExecutableName() { FilePath result; #if GTEST_OS_WINDOWS result.Set(FilePath(GetArgvs()[0]).RemoveExtension("exe")); #else result.Set(FilePath(GetArgvs()[0])); #endif // GTEST_OS_WINDOWS return result.RemoveDirectoryName(); } // Functions for processing the gtest_output flag. // Returns the output format, or "" for normal printed output. std::string UnitTestOptions::GetOutputFormat() { const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); if (gtest_output_flag == NULL) return std::string(""); const char* const colon = strchr(gtest_output_flag, ':'); return (colon == NULL) ? std::string(gtest_output_flag) : std::string(gtest_output_flag, colon - gtest_output_flag); } // Returns the name of the requested output file, or the default if none // was explicitly specified. std::string UnitTestOptions::GetAbsolutePathToOutputFile() { const char* const gtest_output_flag = GTEST_FLAG(output).c_str(); if (gtest_output_flag == NULL) return ""; const char* const colon = strchr(gtest_output_flag, ':'); if (colon == NULL) return internal::FilePath::ConcatPaths( internal::FilePath( UnitTest::GetInstance()->original_working_dir()), internal::FilePath(kDefaultOutputFile)).string(); internal::FilePath output_name(colon + 1); if (!output_name.IsAbsolutePath()) // TODO(wan@google.com): on Windows \some\path is not an absolute // path (as its meaning depends on the current drive), yet the // following logic for turning it into an absolute path is wrong. // Fix it. output_name = internal::FilePath::ConcatPaths( internal::FilePath(UnitTest::GetInstance()->original_working_dir()), internal::FilePath(colon + 1)); if (!output_name.IsDirectory()) return output_name.string(); internal::FilePath result(internal::FilePath::GenerateUniqueFileName( output_name, internal::GetCurrentExecutableName(), GetOutputFormat().c_str())); return result.string(); } // Returns true iff the wildcard pattern matches the string. The // first ':' or '\0' character in pattern marks the end of it. // // This recursive algorithm isn't very efficient, but is clear and // works well enough for matching test names, which are short. bool UnitTestOptions::PatternMatchesString(const char *pattern, const char *str) { switch (*pattern) { case '\0': case ':': // Either ':' or '\0' marks the end of the pattern. return *str == '\0'; case '?': // Matches any single character. return *str != '\0' && PatternMatchesString(pattern + 1, str + 1); case '*': // Matches any string (possibly empty) of characters. return (*str != '\0' && PatternMatchesString(pattern, str + 1)) || PatternMatchesString(pattern + 1, str); default: // Non-special character. Matches itself. return *pattern == *str && PatternMatchesString(pattern + 1, str + 1); } } bool UnitTestOptions::MatchesFilter( const std::string& name, const char* filter) { const char *cur_pattern = filter; for (;;) { if (PatternMatchesString(cur_pattern, name.c_str())) { return true; } // Finds the next pattern in the filter. cur_pattern = strchr(cur_pattern, ':'); // Returns if no more pattern can be found. if (cur_pattern == NULL) { return false; } // Skips the pattern separater (the ':' character). cur_pattern++; } } // Returns true iff the user-specified filter matches the test case // name and the test name. bool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name, const std::string &test_name) { const std::string& full_name = test_case_name + "." + test_name.c_str(); // Split --gtest_filter at '-', if there is one, to separate into // positive filter and negative filter portions const char* const p = GTEST_FLAG(filter).c_str(); const char* const dash = strchr(p, '-'); std::string positive; std::string negative; if (dash == NULL) { positive = GTEST_FLAG(filter).c_str(); // Whole string is a positive filter negative = ""; } else { positive = std::string(p, dash); // Everything up to the dash negative = std::string(dash + 1); // Everything after the dash if (positive.empty()) { // Treat '-test1' as the same as '*-test1' positive = kUniversalFilter; } } // A filter is a colon-separated list of patterns. It matches a // test if any pattern in it matches the test. return (MatchesFilter(full_name, positive.c_str()) && !MatchesFilter(full_name, negative.c_str())); } #if GTEST_HAS_SEH // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise. // This function is useful as an __except condition. int UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) { // Google Test should handle a SEH exception if: // 1. the user wants it to, AND // 2. this is not a breakpoint exception, AND // 3. this is not a C++ exception (VC++ implements them via SEH, // apparently). // // SEH exception code for C++ exceptions. // (see http://support.microsoft.com/kb/185294 for more information). const DWORD kCxxExceptionCode = 0xe06d7363; bool should_handle = true; if (!GTEST_FLAG(catch_exceptions)) should_handle = false; else if (exception_code == EXCEPTION_BREAKPOINT) should_handle = false; else if (exception_code == kCxxExceptionCode) should_handle = false; return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH; } #endif // GTEST_HAS_SEH } // namespace internal // The c'tor sets this object as the test part result reporter used by // Google Test. The 'result' parameter specifies where to report the // results. Intercepts only failures from the current thread. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( TestPartResultArray* result) : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD), result_(result) { Init(); } // The c'tor sets this object as the test part result reporter used by // Google Test. The 'result' parameter specifies where to report the // results. ScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter( InterceptMode intercept_mode, TestPartResultArray* result) : intercept_mode_(intercept_mode), result_(result) { Init(); } void ScopedFakeTestPartResultReporter::Init() { internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); if (intercept_mode_ == INTERCEPT_ALL_THREADS) { old_reporter_ = impl->GetGlobalTestPartResultReporter(); impl->SetGlobalTestPartResultReporter(this); } else { old_reporter_ = impl->GetTestPartResultReporterForCurrentThread(); impl->SetTestPartResultReporterForCurrentThread(this); } } // The d'tor restores the test part result reporter used by Google Test // before. ScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() { internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); if (intercept_mode_ == INTERCEPT_ALL_THREADS) { impl->SetGlobalTestPartResultReporter(old_reporter_); } else { impl->SetTestPartResultReporterForCurrentThread(old_reporter_); } } // Increments the test part result count and remembers the result. // This method is from the TestPartResultReporterInterface interface. void ScopedFakeTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { result_->Append(result); } namespace internal { // Returns the type ID of ::testing::Test. We should always call this // instead of GetTypeId< ::testing::Test>() to get the type ID of // testing::Test. This is to work around a suspected linker bug when // using Google Test as a framework on Mac OS X. The bug causes // GetTypeId< ::testing::Test>() to return different values depending // on whether the call is from the Google Test framework itself or // from user test code. GetTestTypeId() is guaranteed to always // return the same value, as it always calls GetTypeId<>() from the // gtest.cc, which is within the Google Test framework. TypeId GetTestTypeId() { return GetTypeId<Test>(); } // The value of GetTestTypeId() as seen from within the Google Test // library. This is solely for testing GetTestTypeId(). extern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId(); // This predicate-formatter checks that 'results' contains a test part // failure of the given type and that the failure message contains the // given substring. AssertionResult HasOneFailure(const char* /* results_expr */, const char* /* type_expr */, const char* /* substr_expr */, const TestPartResultArray& results, TestPartResult::Type type, const string& substr) { const std::string expected(type == TestPartResult::kFatalFailure ? "1 fatal failure" : "1 non-fatal failure"); Message msg; if (results.size() != 1) { msg << "Expected: " << expected << "\n" << " Actual: " << results.size() << " failures"; for (int i = 0; i < results.size(); i++) { msg << "\n" << results.GetTestPartResult(i); } return AssertionFailure() << msg; } const TestPartResult& r = results.GetTestPartResult(0); if (r.type() != type) { return AssertionFailure() << "Expected: " << expected << "\n" << " Actual:\n" << r; } if (strstr(r.message(), substr.c_str()) == NULL) { return AssertionFailure() << "Expected: " << expected << " containing \"" << substr << "\"\n" << " Actual:\n" << r; } return AssertionSuccess(); } // The constructor of SingleFailureChecker remembers where to look up // test part results, what type of failure we expect, and what // substring the failure message should contain. SingleFailureChecker:: SingleFailureChecker( const TestPartResultArray* results, TestPartResult::Type type, const string& substr) : results_(results), type_(type), substr_(substr) {} // The destructor of SingleFailureChecker verifies that the given // TestPartResultArray contains exactly one failure that has the given // type and contains the given substring. If that's not the case, a // non-fatal failure will be generated. SingleFailureChecker::~SingleFailureChecker() { EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_); } DefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter( UnitTestImpl* unit_test) : unit_test_(unit_test) {} void DefaultGlobalTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { unit_test_->current_test_result()->AddTestPartResult(result); unit_test_->listeners()->repeater()->OnTestPartResult(result); } DefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter( UnitTestImpl* unit_test) : unit_test_(unit_test) {} void DefaultPerThreadTestPartResultReporter::ReportTestPartResult( const TestPartResult& result) { unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result); } // Returns the global test part result reporter. TestPartResultReporterInterface* UnitTestImpl::GetGlobalTestPartResultReporter() { internal::MutexLock lock(&global_test_part_result_reporter_mutex_); return global_test_part_result_repoter_; } // Sets the global test part result reporter. void UnitTestImpl::SetGlobalTestPartResultReporter( TestPartResultReporterInterface* reporter) { internal::MutexLock lock(&global_test_part_result_reporter_mutex_); global_test_part_result_repoter_ = reporter; } // Returns the test part result reporter for the current thread. TestPartResultReporterInterface* UnitTestImpl::GetTestPartResultReporterForCurrentThread() { return per_thread_test_part_result_reporter_.get(); } // Sets the test part result reporter for the current thread. void UnitTestImpl::SetTestPartResultReporterForCurrentThread( TestPartResultReporterInterface* reporter) { per_thread_test_part_result_reporter_.set(reporter); } // Gets the number of successful test cases. int UnitTestImpl::successful_test_case_count() const { return CountIf(test_cases_, TestCasePassed); } // Gets the number of failed test cases. int UnitTestImpl::failed_test_case_count() const { return CountIf(test_cases_, TestCaseFailed); } // Gets the number of all test cases. int UnitTestImpl::total_test_case_count() const { return static_cast<int>(test_cases_.size()); } // Gets the number of all test cases that contain at least one test // that should run. int UnitTestImpl::test_case_to_run_count() const { return CountIf(test_cases_, ShouldRunTestCase); } // Gets the number of successful tests. int UnitTestImpl::successful_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count); } // Gets the number of failed tests. int UnitTestImpl::failed_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count); } // Gets the number of disabled tests that will be reported in the XML report. int UnitTestImpl::reportable_disabled_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::reportable_disabled_test_count); } // Gets the number of disabled tests. int UnitTestImpl::disabled_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count); } // Gets the number of tests to be printed in the XML report. int UnitTestImpl::reportable_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count); } // Gets the number of all tests. int UnitTestImpl::total_test_count() const { return SumOverTestCaseList(test_cases_, &TestCase::total_test_count); } // Gets the number of tests that should run. int UnitTestImpl::test_to_run_count() const { return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count); } // Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // CurrentOsStackTraceExceptTop(1), Foo() will be included in the // trace but Bar() and CurrentOsStackTraceExceptTop() won't. std::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) { return os_stack_trace_getter()->CurrentStackTrace( static_cast<int>(GTEST_FLAG(stack_trace_depth)), skip_count + 1 // Skips the user-specified number of frames plus this function // itself. ); // NOLINT } // Returns the current time in milliseconds. TimeInMillis GetTimeInMillis() { #if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__) // Difference between 1970-01-01 and 1601-01-01 in milliseconds. // http://analogous.blogspot.com/2005/04/epoch.html const TimeInMillis kJavaEpochToWinFileTimeDelta = static_cast<TimeInMillis>(116444736UL) * 100000UL; const DWORD kTenthMicrosInMilliSecond = 10000; SYSTEMTIME now_systime; FILETIME now_filetime; ULARGE_INTEGER now_int64; // TODO(kenton@google.com): Shouldn't this just use // GetSystemTimeAsFileTime()? GetSystemTime(&now_systime); if (SystemTimeToFileTime(&now_systime, &now_filetime)) { now_int64.LowPart = now_filetime.dwLowDateTime; now_int64.HighPart = now_filetime.dwHighDateTime; now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) - kJavaEpochToWinFileTimeDelta; return now_int64.QuadPart; } return 0; #elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_ __timeb64 now; // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996 // (deprecated function) there. // TODO(kenton@google.com): Use GetTickCount()? Or use // SystemTimeToFileTime() GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) _ftime64(&now); GTEST_DISABLE_MSC_WARNINGS_POP_() return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm; #elif GTEST_HAS_GETTIMEOFDAY_ struct timeval now; gettimeofday(&now, NULL); return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000; #else # error "Don't know how to get the current time on your system." #endif } // Utilities // class String. #if GTEST_OS_WINDOWS_MOBILE // Creates a UTF-16 wide string from the given ANSI string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the wide string, or NULL if the // input is NULL. LPCWSTR String::AnsiToUtf16(const char* ansi) { if (!ansi) return NULL; const int length = strlen(ansi); const int unicode_length = MultiByteToWideChar(CP_ACP, 0, ansi, length, NULL, 0); WCHAR* unicode = new WCHAR[unicode_length + 1]; MultiByteToWideChar(CP_ACP, 0, ansi, length, unicode, unicode_length); unicode[unicode_length] = 0; return unicode; } // Creates an ANSI string from the given wide string, allocating // memory using new. The caller is responsible for deleting the return // value using delete[]. Returns the ANSI string, or NULL if the // input is NULL. const char* String::Utf16ToAnsi(LPCWSTR utf16_str) { if (!utf16_str) return NULL; const int ansi_length = WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, NULL, 0, NULL, NULL); char* ansi = new char[ansi_length + 1]; WideCharToMultiByte(CP_ACP, 0, utf16_str, -1, ansi, ansi_length, NULL, NULL); ansi[ansi_length] = 0; return ansi; } #endif // GTEST_OS_WINDOWS_MOBILE // Compares two C strings. Returns true iff they have the same content. // // Unlike strcmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. bool String::CStringEquals(const char * lhs, const char * rhs) { if ( lhs == NULL ) return rhs == NULL; if ( rhs == NULL ) return false; return strcmp(lhs, rhs) == 0; } #if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING // Converts an array of wide chars to a narrow string using the UTF-8 // encoding, and streams the result to the given Message object. static void StreamWideCharsToMessage(const wchar_t* wstr, size_t length, Message* msg) { for (size_t i = 0; i != length; ) { // NOLINT if (wstr[i] != L'\0') { *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i)); while (i != length && wstr[i] != L'\0') i++; } else { *msg << '\0'; i++; } } } #endif // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING void SplitString(const ::std::string& str, char delimiter, ::std::vector< ::std::string>* dest) { ::std::vector< ::std::string> parsed; ::std::string::size_type pos = 0; while (::testing::internal::AlwaysTrue()) { const ::std::string::size_type colon = str.find(delimiter, pos); if (colon == ::std::string::npos) { parsed.push_back(str.substr(pos)); break; } else { parsed.push_back(str.substr(pos, colon - pos)); pos = colon + 1; } } dest->swap(parsed); } } // namespace internal // Constructs an empty Message. // We allocate the stringstream separately because otherwise each use of // ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's // stack frame leading to huge stack frames in some cases; gcc does not reuse // the stack space. Message::Message() : ss_(new ::std::stringstream) { // By default, we want there to be enough precision when printing // a double to a Message. *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2); } // These two overloads allow streaming a wide C string to a Message // using the UTF-8 encoding. Message& Message::operator <<(const wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } Message& Message::operator <<(wchar_t* wide_c_str) { return *this << internal::String::ShowWideCString(wide_c_str); } #if GTEST_HAS_STD_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. Message& Message::operator <<(const ::std::wstring& wstr) { internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); return *this; } #endif // GTEST_HAS_STD_WSTRING #if GTEST_HAS_GLOBAL_WSTRING // Converts the given wide string to a narrow string using the UTF-8 // encoding, and streams the result to this Message object. Message& Message::operator <<(const ::wstring& wstr) { internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this); return *this; } #endif // GTEST_HAS_GLOBAL_WSTRING // Gets the text streamed to this object so far as an std::string. // Each '\0' character in the buffer is replaced with "\\0". std::string Message::GetString() const { return internal::StringStreamToString(ss_.get()); } // AssertionResult constructors. // Used in EXPECT_TRUE/FALSE(assertion_result). AssertionResult::AssertionResult(const AssertionResult& other) : success_(other.success_), message_(other.message_.get() != NULL ? new ::std::string(*other.message_) : static_cast< ::std::string*>(NULL)) { } // Swaps two AssertionResults. void AssertionResult::swap(AssertionResult& other) { using std::swap; swap(success_, other.success_); swap(message_, other.message_); } // Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE. AssertionResult AssertionResult::operator!() const { AssertionResult negation(!success_); if (message_.get() != NULL) negation << *message_; return negation; } // Makes a successful assertion result. AssertionResult AssertionSuccess() { return AssertionResult(true); } // Makes a failed assertion result. AssertionResult AssertionFailure() { return AssertionResult(false); } // Makes a failed assertion result with the given failure message. // Deprecated; use AssertionFailure() << message. AssertionResult AssertionFailure(const Message& message) { return AssertionFailure() << message; } namespace internal { namespace edit_distance { std::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left, const std::vector<size_t>& right) { std::vector<std::vector<double> > costs( left.size() + 1, std::vector<double>(right.size() + 1)); std::vector<std::vector<EditType> > best_move( left.size() + 1, std::vector<EditType>(right.size() + 1)); // Populate for empty right. for (size_t l_i = 0; l_i < costs.size(); ++l_i) { costs[l_i][0] = static_cast<double>(l_i); best_move[l_i][0] = kRemove; } // Populate for empty left. for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) { costs[0][r_i] = static_cast<double>(r_i); best_move[0][r_i] = kAdd; } for (size_t l_i = 0; l_i < left.size(); ++l_i) { for (size_t r_i = 0; r_i < right.size(); ++r_i) { if (left[l_i] == right[r_i]) { // Found a match. Consume it. costs[l_i + 1][r_i + 1] = costs[l_i][r_i]; best_move[l_i + 1][r_i + 1] = kMatch; continue; } const double add = costs[l_i + 1][r_i]; const double remove = costs[l_i][r_i + 1]; const double replace = costs[l_i][r_i]; if (add < remove && add < replace) { costs[l_i + 1][r_i + 1] = add + 1; best_move[l_i + 1][r_i + 1] = kAdd; } else if (remove < add && remove < replace) { costs[l_i + 1][r_i + 1] = remove + 1; best_move[l_i + 1][r_i + 1] = kRemove; } else { // We make replace a little more expensive than add/remove to lower // their priority. costs[l_i + 1][r_i + 1] = replace + 1.00001; best_move[l_i + 1][r_i + 1] = kReplace; } } } // Reconstruct the best path. We do it in reverse order. std::vector<EditType> best_path; for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) { EditType move = best_move[l_i][r_i]; best_path.push_back(move); l_i -= move != kAdd; r_i -= move != kRemove; } std::reverse(best_path.begin(), best_path.end()); return best_path; } namespace { // Helper class to convert string into ids with deduplication. class InternalStrings { public: size_t GetId(const std::string& str) { IdMap::iterator it = ids_.find(str); if (it != ids_.end()) return it->second; size_t id = ids_.size(); return ids_[str] = id; } private: typedef std::map<std::string, size_t> IdMap; IdMap ids_; }; } // namespace std::vector<EditType> CalculateOptimalEdits( const std::vector<std::string>& left, const std::vector<std::string>& right) { std::vector<size_t> left_ids, right_ids; { InternalStrings intern_table; for (size_t i = 0; i < left.size(); ++i) { left_ids.push_back(intern_table.GetId(left[i])); } for (size_t i = 0; i < right.size(); ++i) { right_ids.push_back(intern_table.GetId(right[i])); } } return CalculateOptimalEdits(left_ids, right_ids); } namespace { // Helper class that holds the state for one hunk and prints it out to the // stream. // It reorders adds/removes when possible to group all removes before all // adds. It also adds the hunk header before printint into the stream. class Hunk { public: Hunk(size_t left_start, size_t right_start) : left_start_(left_start), right_start_(right_start), adds_(), removes_(), common_() {} void PushLine(char edit, const char* line) { switch (edit) { case ' ': ++common_; FlushEdits(); hunk_.push_back(std::make_pair(' ', line)); break; case '-': ++removes_; hunk_removes_.push_back(std::make_pair('-', line)); break; case '+': ++adds_; hunk_adds_.push_back(std::make_pair('+', line)); break; } } void PrintTo(std::ostream* os) { PrintHeader(os); FlushEdits(); for (std::list<std::pair<char, const char*> >::const_iterator it = hunk_.begin(); it != hunk_.end(); ++it) { *os << it->first << it->second << "\n"; } } bool has_edits() const { return adds_ || removes_; } private: void FlushEdits() { hunk_.splice(hunk_.end(), hunk_removes_); hunk_.splice(hunk_.end(), hunk_adds_); } // Print a unified diff header for one hunk. // The format is // "@@ -<left_start>,<left_length> +<right_start>,<right_length> @@" // where the left/right parts are ommitted if unnecessary. void PrintHeader(std::ostream* ss) const { *ss << "@@ "; if (removes_) { *ss << "-" << left_start_ << "," << (removes_ + common_); } if (removes_ && adds_) { *ss << " "; } if (adds_) { *ss << "+" << right_start_ << "," << (adds_ + common_); } *ss << " @@\n"; } size_t left_start_, right_start_; size_t adds_, removes_, common_; std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_; }; } // namespace // Create a list of diff hunks in Unified diff format. // Each hunk has a header generated by PrintHeader above plus a body with // lines prefixed with ' ' for no change, '-' for deletion and '+' for // addition. // 'context' represents the desired unchanged prefix/suffix around the diff. // If two hunks are close enough that their contexts overlap, then they are // joined into one hunk. std::string CreateUnifiedDiff(const std::vector<std::string>& left, const std::vector<std::string>& right, size_t context) { const std::vector<EditType> edits = CalculateOptimalEdits(left, right); size_t l_i = 0, r_i = 0, edit_i = 0; std::stringstream ss; while (edit_i < edits.size()) { // Find first edit. while (edit_i < edits.size() && edits[edit_i] == kMatch) { ++l_i; ++r_i; ++edit_i; } // Find the first line to include in the hunk. const size_t prefix_context = std::min(l_i, context); Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1); for (size_t i = prefix_context; i > 0; --i) { hunk.PushLine(' ', left[l_i - i].c_str()); } // Iterate the edits until we found enough suffix for the hunk or the input // is over. size_t n_suffix = 0; for (; edit_i < edits.size(); ++edit_i) { if (n_suffix >= context) { // Continue only if the next hunk is very close. std::vector<EditType>::const_iterator it = edits.begin() + edit_i; while (it != edits.end() && *it == kMatch) ++it; if (it == edits.end() || (it - edits.begin()) - edit_i >= context) { // There is no next edit or it is too far away. break; } } EditType edit = edits[edit_i]; // Reset count when a non match is found. n_suffix = edit == kMatch ? n_suffix + 1 : 0; if (edit == kMatch || edit == kRemove || edit == kReplace) { hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str()); } if (edit == kAdd || edit == kReplace) { hunk.PushLine('+', right[r_i].c_str()); } // Advance indices, depending on edit type. l_i += edit != kAdd; r_i += edit != kRemove; } if (!hunk.has_edits()) { // We are done. We don't want this hunk. break; } hunk.PrintTo(&ss); } return ss.str(); } } // namespace edit_distance namespace { // The string representation of the values received in EqFailure() are already // escaped. Split them on escaped '\n' boundaries. Leave all other escaped // characters the same. std::vector<std::string> SplitEscapedString(const std::string& str) { std::vector<std::string> lines; size_t start = 0, end = str.size(); if (end > 2 && str[0] == '"' && str[end - 1] == '"') { ++start; --end; } bool escaped = false; for (size_t i = start; i + 1 < end; ++i) { if (escaped) { escaped = false; if (str[i] == 'n') { lines.push_back(str.substr(start, i - start - 1)); start = i + 1; } } else { escaped = str[i] == '\\'; } } lines.push_back(str.substr(start, end - start)); return lines; } } // namespace // Constructs and returns the message for an equality assertion // (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure. // // The first four parameters are the expressions used in the assertion // and their values, as strings. For example, for ASSERT_EQ(foo, bar) // where foo is 5 and bar is 6, we have: // // lhs_expression: "foo" // rhs_expression: "bar" // lhs_value: "5" // rhs_value: "6" // // The ignoring_case parameter is true iff the assertion is a // *_STRCASEEQ*. When it's true, the string "Ignoring case" will // be inserted into the message. AssertionResult EqFailure(const char* lhs_expression, const char* rhs_expression, const std::string& lhs_value, const std::string& rhs_value, bool ignoring_case) { Message msg; msg << " Expected: " << lhs_expression; if (lhs_value != lhs_expression) { msg << "\n Which is: " << lhs_value; } msg << "\nTo be equal to: " << rhs_expression; if (rhs_value != rhs_expression) { msg << "\n Which is: " << rhs_value; } if (ignoring_case) { msg << "\nIgnoring case"; } if (!lhs_value.empty() && !rhs_value.empty()) { const std::vector<std::string> lhs_lines = SplitEscapedString(lhs_value); const std::vector<std::string> rhs_lines = SplitEscapedString(rhs_value); if (lhs_lines.size() > 1 || rhs_lines.size() > 1) { msg << "\nWith diff:\n" << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines); } } return AssertionFailure() << msg; } // Constructs a failure message for Boolean assertions such as EXPECT_TRUE. std::string GetBoolAssertionFailureMessage( const AssertionResult& assertion_result, const char* expression_text, const char* actual_predicate_value, const char* expected_predicate_value) { const char* actual_message = assertion_result.message(); Message msg; msg << "Value of: " << expression_text << "\n Actual: " << actual_predicate_value; if (actual_message[0] != '\0') msg << " (" << actual_message << ")"; msg << "\nExpected: " << expected_predicate_value; return msg.GetString(); } // Helper function for implementing ASSERT_NEAR. AssertionResult DoubleNearPredFormat(const char* expr1, const char* expr2, const char* abs_error_expr, double val1, double val2, double abs_error) { const double diff = fabs(val1 - val2); if (diff <= abs_error) return AssertionSuccess(); // TODO(wan): do not print the value of an expression if it's // already a literal. return AssertionFailure() << "The difference between " << expr1 << " and " << expr2 << " is " << diff << ", which exceeds " << abs_error_expr << ", where\n" << expr1 << " evaluates to " << val1 << ",\n" << expr2 << " evaluates to " << val2 << ", and\n" << abs_error_expr << " evaluates to " << abs_error << "."; } // Helper template for implementing FloatLE() and DoubleLE(). template <typename RawType> AssertionResult FloatingPointLE(const char* expr1, const char* expr2, RawType val1, RawType val2) { // Returns success if val1 is less than val2, if (val1 < val2) { return AssertionSuccess(); } // or if val1 is almost equal to val2. const FloatingPoint<RawType> lhs(val1), rhs(val2); if (lhs.AlmostEquals(rhs)) { return AssertionSuccess(); } // Note that the above two checks will both fail if either val1 or // val2 is NaN, as the IEEE floating-point standard requires that // any predicate involving a NaN must return false. ::std::stringstream val1_ss; val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << val1; ::std::stringstream val2_ss; val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2) << val2; return AssertionFailure() << "Expected: (" << expr1 << ") <= (" << expr2 << ")\n" << " Actual: " << StringStreamToString(&val1_ss) << " vs " << StringStreamToString(&val2_ss); } } // namespace internal // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. AssertionResult FloatLE(const char* expr1, const char* expr2, float val1, float val2) { return internal::FloatingPointLE<float>(expr1, expr2, val1, val2); } // Asserts that val1 is less than, or almost equal to, val2. Fails // otherwise. In particular, it fails if either val1 or val2 is NaN. AssertionResult DoubleLE(const char* expr1, const char* expr2, double val1, double val2) { return internal::FloatingPointLE<double>(expr1, expr2, val1, val2); } namespace internal { // The helper function for {ASSERT|EXPECT}_EQ with int or enum // arguments. AssertionResult CmpHelperEQ(const char* lhs_expression, const char* rhs_expression, BiggestInt lhs, BiggestInt rhs) { if (lhs == rhs) { return AssertionSuccess(); } return EqFailure(lhs_expression, rhs_expression, FormatForComparisonFailureMessage(lhs, rhs), FormatForComparisonFailureMessage(rhs, lhs), false); } // A macro for implementing the helper functions needed to implement // ASSERT_?? and EXPECT_?? with integer or enum arguments. It is here // just to avoid copy-and-paste of similar code. #define GTEST_IMPL_CMP_HELPER_(op_name, op)\ AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \ BiggestInt val1, BiggestInt val2) {\ if (val1 op val2) {\ return AssertionSuccess();\ } else {\ return AssertionFailure() \ << "Expected: (" << expr1 << ") " #op " (" << expr2\ << "), actual: " << FormatForComparisonFailureMessage(val1, val2)\ << " vs " << FormatForComparisonFailureMessage(val2, val1);\ }\ } // Implements the helper function for {ASSERT|EXPECT}_NE with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(NE, !=) // Implements the helper function for {ASSERT|EXPECT}_LE with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(LE, <=) // Implements the helper function for {ASSERT|EXPECT}_LT with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(LT, < ) // Implements the helper function for {ASSERT|EXPECT}_GE with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(GE, >=) // Implements the helper function for {ASSERT|EXPECT}_GT with int or // enum arguments. GTEST_IMPL_CMP_HELPER_(GT, > ) #undef GTEST_IMPL_CMP_HELPER_ // The helper function for {ASSERT|EXPECT}_STREQ. AssertionResult CmpHelperSTREQ(const char* lhs_expression, const char* rhs_expression, const char* lhs, const char* rhs) { if (String::CStringEquals(lhs, rhs)) { return AssertionSuccess(); } return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), PrintToString(rhs), false); } // The helper function for {ASSERT|EXPECT}_STRCASEEQ. AssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression, const char* rhs_expression, const char* lhs, const char* rhs) { if (String::CaseInsensitiveCStringEquals(lhs, rhs)) { return AssertionSuccess(); } return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), PrintToString(rhs), true); } // The helper function for {ASSERT|EXPECT}_STRNE. AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2) { if (!String::CStringEquals(s1, s2)) { return AssertionSuccess(); } else { return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << "), actual: \"" << s1 << "\" vs \"" << s2 << "\""; } } // The helper function for {ASSERT|EXPECT}_STRCASENE. AssertionResult CmpHelperSTRCASENE(const char* s1_expression, const char* s2_expression, const char* s1, const char* s2) { if (!String::CaseInsensitiveCStringEquals(s1, s2)) { return AssertionSuccess(); } else { return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << ") (ignoring case), actual: \"" << s1 << "\" vs \"" << s2 << "\""; } } } // namespace internal namespace { // Helper functions for implementing IsSubString() and IsNotSubstring(). // This group of overloaded functions return true iff needle is a // substring of haystack. NULL is considered a substring of itself // only. bool IsSubstringPred(const char* needle, const char* haystack) { if (needle == NULL || haystack == NULL) return needle == haystack; return strstr(haystack, needle) != NULL; } bool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) { if (needle == NULL || haystack == NULL) return needle == haystack; return wcsstr(haystack, needle) != NULL; } // StringType here can be either ::std::string or ::std::wstring. template <typename StringType> bool IsSubstringPred(const StringType& needle, const StringType& haystack) { return haystack.find(needle) != StringType::npos; } // This function implements either IsSubstring() or IsNotSubstring(), // depending on the value of the expected_to_be_substring parameter. // StringType here can be const char*, const wchar_t*, ::std::string, // or ::std::wstring. template <typename StringType> AssertionResult IsSubstringImpl( bool expected_to_be_substring, const char* needle_expr, const char* haystack_expr, const StringType& needle, const StringType& haystack) { if (IsSubstringPred(needle, haystack) == expected_to_be_substring) return AssertionSuccess(); const bool is_wide_string = sizeof(needle[0]) > 1; const char* const begin_string_quote = is_wide_string ? "L\"" : "\""; return AssertionFailure() << "Value of: " << needle_expr << "\n" << " Actual: " << begin_string_quote << needle << "\"\n" << "Expected: " << (expected_to_be_substring ? "" : "not ") << "a substring of " << haystack_expr << "\n" << "Which is: " << begin_string_quote << haystack << "\""; } } // namespace // IsSubstring() and IsNotSubstring() check whether needle is a // substring of haystack (NULL is considered a substring of itself // only), and return an appropriate error message when they fail. AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const char* needle, const char* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const wchar_t* needle, const wchar_t* haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::string& needle, const ::std::string& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #if GTEST_HAS_STD_WSTRING AssertionResult IsSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack) { return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack); } AssertionResult IsNotSubstring( const char* needle_expr, const char* haystack_expr, const ::std::wstring& needle, const ::std::wstring& haystack) { return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack); } #endif // GTEST_HAS_STD_WSTRING namespace internal { #if GTEST_OS_WINDOWS namespace { // Helper function for IsHRESULT{SuccessFailure} predicates AssertionResult HRESULTFailureHelper(const char* expr, const char* expected, long hr) { // NOLINT # if GTEST_OS_WINDOWS_MOBILE // Windows CE doesn't support FormatMessage. const char error_text[] = ""; # else // Looks up the human-readable system message for the HRESULT code // and since we're not passing any params to FormatMessage, we don't // want inserts expanded. const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; const DWORD kBufSize = 4096; // Gets the system's human readable message string for this HRESULT. char error_text[kBufSize] = { '\0' }; DWORD message_length = ::FormatMessageA(kFlags, 0, // no source, we're asking system hr, // the error 0, // no line width restrictions error_text, // output buffer kBufSize, // buf size NULL); // no arguments for inserts // Trims tailing white space (FormatMessage leaves a trailing CR-LF) for (; message_length && IsSpace(error_text[message_length - 1]); --message_length) { error_text[message_length - 1] = '\0'; } # endif // GTEST_OS_WINDOWS_MOBILE const std::string error_hex("0x" + String::FormatHexInt(hr)); return ::testing::AssertionFailure() << "Expected: " << expr << " " << expected << ".\n" << " Actual: " << error_hex << " " << error_text << "\n"; } } // namespace AssertionResult IsHRESULTSuccess(const char* expr, long hr) { // NOLINT if (SUCCEEDED(hr)) { return AssertionSuccess(); } return HRESULTFailureHelper(expr, "succeeds", hr); } AssertionResult IsHRESULTFailure(const char* expr, long hr) { // NOLINT if (FAILED(hr)) { return AssertionSuccess(); } return HRESULTFailureHelper(expr, "fails", hr); } #endif // GTEST_OS_WINDOWS // Utility functions for encoding Unicode text (wide strings) in // UTF-8. // A Unicode code-point can have upto 21 bits, and is encoded in UTF-8 // like this: // // Code-point length Encoding // 0 - 7 bits 0xxxxxxx // 8 - 11 bits 110xxxxx 10xxxxxx // 12 - 16 bits 1110xxxx 10xxxxxx 10xxxxxx // 17 - 21 bits 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx // The maximum code-point a one-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) << 7) - 1; // The maximum code-point a two-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1; // The maximum code-point a three-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1; // The maximum code-point a four-byte UTF-8 sequence can represent. const UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1; // Chops off the n lowest bits from a bit pattern. Returns the n // lowest bits. As a side effect, the original bit pattern will be // shifted to the right by n bits. inline UInt32 ChopLowBits(UInt32* bits, int n) { const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1); *bits >>= n; return low_bits; } // Converts a Unicode code point to a narrow string in UTF-8 encoding. // code_point parameter is of type UInt32 because wchar_t may not be // wide enough to contain a code point. // If the code_point is not a valid Unicode code point // (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted // to "(Invalid Unicode 0xXXXXXXXX)". std::string CodePointToUtf8(UInt32 code_point) { if (code_point > kMaxCodePoint4) { return "(Invalid Unicode 0x" + String::FormatHexInt(code_point) + ")"; } char str[5]; // Big enough for the largest valid code point. if (code_point <= kMaxCodePoint1) { str[1] = '\0'; str[0] = static_cast<char>(code_point); // 0xxxxxxx } else if (code_point <= kMaxCodePoint2) { str[2] = '\0'; str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[0] = static_cast<char>(0xC0 | code_point); // 110xxxxx } else if (code_point <= kMaxCodePoint3) { str[3] = '\0'; str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[0] = static_cast<char>(0xE0 | code_point); // 1110xxxx } else { // code_point <= kMaxCodePoint4 str[4] = '\0'; str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6)); // 10xxxxxx str[0] = static_cast<char>(0xF0 | code_point); // 11110xxx } return str; } // The following two functions only make sense if the the system // uses UTF-16 for wide string encoding. All supported systems // with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16. // Determines if the arguments constitute UTF-16 surrogate pair // and thus should be combined into a single Unicode code point // using CreateCodePointFromUtf16SurrogatePair. inline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) { return sizeof(wchar_t) == 2 && (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00; } // Creates a Unicode code point from UTF16 surrogate pair. inline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first, wchar_t second) { const UInt32 mask = (1 << 10) - 1; return (sizeof(wchar_t) == 2) ? (((first & mask) << 10) | (second & mask)) + 0x10000 : // This function should not be called when the condition is // false, but we provide a sensible default in case it is. static_cast<UInt32>(first); } // Converts a wide string to a narrow string in UTF-8 encoding. // The wide string is assumed to have the following encoding: // UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS) // UTF-32 if sizeof(wchar_t) == 4 (on Linux) // Parameter str points to a null-terminated wide string. // Parameter num_chars may additionally limit the number // of wchar_t characters processed. -1 is used when the entire string // should be processed. // If the string contains code points that are not valid Unicode code points // (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output // as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding // and contains invalid UTF-16 surrogate pairs, values in those pairs // will be encoded as individual Unicode characters from Basic Normal Plane. std::string WideStringToUtf8(const wchar_t* str, int num_chars) { if (num_chars == -1) num_chars = static_cast<int>(wcslen(str)); ::std::stringstream stream; for (int i = 0; i < num_chars; ++i) { UInt32 unicode_code_point; if (str[i] == L'\0') { break; } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) { unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i], str[i + 1]); i++; } else { unicode_code_point = static_cast<UInt32>(str[i]); } stream << CodePointToUtf8(unicode_code_point); } return StringStreamToString(&stream); } // Converts a wide C string to an std::string using the UTF-8 encoding. // NULL will be converted to "(null)". std::string String::ShowWideCString(const wchar_t * wide_c_str) { if (wide_c_str == NULL) return "(null)"; return internal::WideStringToUtf8(wide_c_str, -1); } // Compares two wide C strings. Returns true iff they have the same // content. // // Unlike wcscmp(), this function can handle NULL argument(s). A NULL // C string is considered different to any non-NULL C string, // including the empty string. bool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) { if (lhs == NULL) return rhs == NULL; if (rhs == NULL) return false; return wcscmp(lhs, rhs) == 0; } // Helper function for *_STREQ on wide strings. AssertionResult CmpHelperSTREQ(const char* lhs_expression, const char* rhs_expression, const wchar_t* lhs, const wchar_t* rhs) { if (String::WideCStringEquals(lhs, rhs)) { return AssertionSuccess(); } return EqFailure(lhs_expression, rhs_expression, PrintToString(lhs), PrintToString(rhs), false); } // Helper function for *_STRNE on wide strings. AssertionResult CmpHelperSTRNE(const char* s1_expression, const char* s2_expression, const wchar_t* s1, const wchar_t* s2) { if (!String::WideCStringEquals(s1, s2)) { return AssertionSuccess(); } return AssertionFailure() << "Expected: (" << s1_expression << ") != (" << s2_expression << "), actual: " << PrintToString(s1) << " vs " << PrintToString(s2); } // Compares two C strings, ignoring case. Returns true iff they have // the same content. // // Unlike strcasecmp(), this function can handle NULL argument(s). A // NULL C string is considered different to any non-NULL C string, // including the empty string. bool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) { if (lhs == NULL) return rhs == NULL; if (rhs == NULL) return false; return posix::StrCaseCmp(lhs, rhs) == 0; } // Compares two wide C strings, ignoring case. Returns true iff they // have the same content. // // Unlike wcscasecmp(), this function can handle NULL argument(s). // A NULL C string is considered different to any non-NULL wide C string, // including the empty string. // NB: The implementations on different platforms slightly differ. // On windows, this method uses _wcsicmp which compares according to LC_CTYPE // environment variable. On GNU platform this method uses wcscasecmp // which compares according to LC_CTYPE category of the current locale. // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the // current locale. bool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs, const wchar_t* rhs) { if (lhs == NULL) return rhs == NULL; if (rhs == NULL) return false; #if GTEST_OS_WINDOWS return _wcsicmp(lhs, rhs) == 0; #elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID return wcscasecmp(lhs, rhs) == 0; #else // Android, Mac OS X and Cygwin don't define wcscasecmp. // Other unknown OSes may not define it either. wint_t left, right; do { left = towlower(*lhs++); right = towlower(*rhs++); } while (left && left == right); return left == right; #endif // OS selector } // Returns true iff str ends with the given suffix, ignoring case. // Any string is considered to end with an empty suffix. bool String::EndsWithCaseInsensitive( const std::string& str, const std::string& suffix) { const size_t str_len = str.length(); const size_t suffix_len = suffix.length(); return (str_len >= suffix_len) && CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len, suffix.c_str()); } // Formats an int value as "%02d". std::string String::FormatIntWidth2(int value) { std::stringstream ss; ss << std::setfill('0') << std::setw(2) << value; return ss.str(); } // Formats an int value as "%X". std::string String::FormatHexInt(int value) { std::stringstream ss; ss << std::hex << std::uppercase << value; return ss.str(); } // Formats a byte as "%02X". std::string String::FormatByte(unsigned char value) { std::stringstream ss; ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase << static_cast<unsigned int>(value); return ss.str(); } // Converts the buffer in a stringstream to an std::string, converting NUL // bytes to "\\0" along the way. std::string StringStreamToString(::std::stringstream* ss) { const ::std::string& str = ss->str(); const char* const start = str.c_str(); const char* const end = start + str.length(); std::string result; result.reserve(2 * (end - start)); for (const char* ch = start; ch != end; ++ch) { if (*ch == '\0') { result += "\\0"; // Replaces NUL with "\\0"; } else { result += *ch; } } return result; } // Appends the user-supplied message to the Google-Test-generated message. std::string AppendUserMessage(const std::string& gtest_msg, const Message& user_msg) { // Appends the user message if it's non-empty. const std::string user_msg_string = user_msg.GetString(); if (user_msg_string.empty()) { return gtest_msg; } return gtest_msg + "\n" + user_msg_string; } } // namespace internal // class TestResult // Creates an empty TestResult. TestResult::TestResult() : death_test_count_(0), elapsed_time_(0) { } // D'tor. TestResult::~TestResult() { } // Returns the i-th test part result among all the results. i can // range from 0 to total_part_count() - 1. If i is not in that range, // aborts the program. const TestPartResult& TestResult::GetTestPartResult(int i) const { if (i < 0 || i >= total_part_count()) internal::posix::Abort(); return test_part_results_.at(i); } // Returns the i-th test property. i can range from 0 to // test_property_count() - 1. If i is not in that range, aborts the // program. const TestProperty& TestResult::GetTestProperty(int i) const { if (i < 0 || i >= test_property_count()) internal::posix::Abort(); return test_properties_.at(i); } // Clears the test part results. void TestResult::ClearTestPartResults() { test_part_results_.clear(); } // Adds a test part result to the list. void TestResult::AddTestPartResult(const TestPartResult& test_part_result) { test_part_results_.push_back(test_part_result); } // Adds a test property to the list. If a property with the same key as the // supplied property is already represented, the value of this test_property // replaces the old value for that key. void TestResult::RecordProperty(const std::string& xml_element, const TestProperty& test_property) { if (!ValidateTestProperty(xml_element, test_property)) { return; } internal::MutexLock lock(&test_properites_mutex_); const std::vector<TestProperty>::iterator property_with_matching_key = std::find_if(test_properties_.begin(), test_properties_.end(), internal::TestPropertyKeyIs(test_property.key())); if (property_with_matching_key == test_properties_.end()) { test_properties_.push_back(test_property); return; } property_with_matching_key->SetValue(test_property.value()); } // The list of reserved attributes used in the <testsuites> element of XML // output. static const char* const kReservedTestSuitesAttributes[] = { "disabled", "errors", "failures", "name", "random_seed", "tests", "time", "timestamp" }; // The list of reserved attributes used in the <testsuite> element of XML // output. static const char* const kReservedTestSuiteAttributes[] = { "disabled", "errors", "failures", "name", "tests", "time" }; // The list of reserved attributes used in the <testcase> element of XML output. static const char* const kReservedTestCaseAttributes[] = { "classname", "name", "status", "time", "type_param", "value_param" }; template <int kSize> std::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) { return std::vector<std::string>(array, array + kSize); } static std::vector<std::string> GetReservedAttributesForElement( const std::string& xml_element) { if (xml_element == "testsuites") { return ArrayAsVector(kReservedTestSuitesAttributes); } else if (xml_element == "testsuite") { return ArrayAsVector(kReservedTestSuiteAttributes); } else if (xml_element == "testcase") { return ArrayAsVector(kReservedTestCaseAttributes); } else { GTEST_CHECK_(false) << "Unrecognized xml_element provided: " << xml_element; } // This code is unreachable but some compilers may not realizes that. return std::vector<std::string>(); } static std::string FormatWordList(const std::vector<std::string>& words) { Message word_list; for (size_t i = 0; i < words.size(); ++i) { if (i > 0 && words.size() > 2) { word_list << ", "; } if (i == words.size() - 1) { word_list << "and "; } word_list << "'" << words[i] << "'"; } return word_list.GetString(); } bool ValidateTestPropertyName(const std::string& property_name, const std::vector<std::string>& reserved_names) { if (std::find(reserved_names.begin(), reserved_names.end(), property_name) != reserved_names.end()) { ADD_FAILURE() << "Reserved key used in RecordProperty(): " << property_name << " (" << FormatWordList(reserved_names) << " are reserved by " << GTEST_NAME_ << ")"; return false; } return true; } // Adds a failure if the key is a reserved attribute of the element named // xml_element. Returns true if the property is valid. bool TestResult::ValidateTestProperty(const std::string& xml_element, const TestProperty& test_property) { return ValidateTestPropertyName(test_property.key(), GetReservedAttributesForElement(xml_element)); } // Clears the object. void TestResult::Clear() { test_part_results_.clear(); test_properties_.clear(); death_test_count_ = 0; elapsed_time_ = 0; } // Returns true iff the test failed. bool TestResult::Failed() const { for (int i = 0; i < total_part_count(); ++i) { if (GetTestPartResult(i).failed()) return true; } return false; } // Returns true iff the test part fatally failed. static bool TestPartFatallyFailed(const TestPartResult& result) { return result.fatally_failed(); } // Returns true iff the test fatally failed. bool TestResult::HasFatalFailure() const { return CountIf(test_part_results_, TestPartFatallyFailed) > 0; } // Returns true iff the test part non-fatally failed. static bool TestPartNonfatallyFailed(const TestPartResult& result) { return result.nonfatally_failed(); } // Returns true iff the test has a non-fatal failure. bool TestResult::HasNonfatalFailure() const { return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0; } // Gets the number of all test parts. This is the sum of the number // of successful test parts and the number of failed test parts. int TestResult::total_part_count() const { return static_cast<int>(test_part_results_.size()); } // Returns the number of the test properties. int TestResult::test_property_count() const { return static_cast<int>(test_properties_.size()); } // class Test // Creates a Test object. // The c'tor saves the states of all flags. Test::Test() : gtest_flag_saver_(new GTEST_FLAG_SAVER_) { } // The d'tor restores the states of all flags. The actual work is // done by the d'tor of the gtest_flag_saver_ field, and thus not // visible here. Test::~Test() { } // Sets up the test fixture. // // A sub-class may override this. void Test::SetUp() { } // Tears down the test fixture. // // A sub-class may override this. void Test::TearDown() { } // Allows user supplied key value pairs to be recorded for later output. void Test::RecordProperty(const std::string& key, const std::string& value) { UnitTest::GetInstance()->RecordProperty(key, value); } // Allows user supplied key value pairs to be recorded for later output. void Test::RecordProperty(const std::string& key, int value) { Message value_message; value_message << value; RecordProperty(key, value_message.GetString().c_str()); } namespace internal { void ReportFailureInUnknownLocation(TestPartResult::Type result_type, const std::string& message) { // This function is a friend of UnitTest and as such has access to // AddTestPartResult. UnitTest::GetInstance()->AddTestPartResult( result_type, NULL, // No info about the source file where the exception occurred. -1, // We have no info on which line caused the exception. message, ""); // No stack trace, either. } } // namespace internal // Google Test requires all tests in the same test case to use the same test // fixture class. This function checks if the current test has the // same fixture class as the first test in the current test case. If // yes, it returns true; otherwise it generates a Google Test failure and // returns false. bool Test::HasSameFixtureClass() { internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); const TestCase* const test_case = impl->current_test_case(); // Info about the first test in the current test case. const TestInfo* const first_test_info = test_case->test_info_list()[0]; const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_; const char* const first_test_name = first_test_info->name(); // Info about the current test. const TestInfo* const this_test_info = impl->current_test_info(); const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_; const char* const this_test_name = this_test_info->name(); if (this_fixture_id != first_fixture_id) { // Is the first test defined using TEST? const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId(); // Is this test defined using TEST? const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId(); if (first_is_TEST || this_is_TEST) { // Both TEST and TEST_F appear in same test case, which is incorrect. // Tell the user how to fix this. // Gets the name of the TEST and the name of the TEST_F. Note // that first_is_TEST and this_is_TEST cannot both be true, as // the fixture IDs are different for the two tests. const char* const TEST_name = first_is_TEST ? first_test_name : this_test_name; const char* const TEST_F_name = first_is_TEST ? this_test_name : first_test_name; ADD_FAILURE() << "All tests in the same test case must use the same test fixture\n" << "class, so mixing TEST_F and TEST in the same test case is\n" << "illegal. In test case " << this_test_info->test_case_name() << ",\n" << "test " << TEST_F_name << " is defined using TEST_F but\n" << "test " << TEST_name << " is defined using TEST. You probably\n" << "want to change the TEST to TEST_F or move it to another test\n" << "case."; } else { // Two fixture classes with the same name appear in two different // namespaces, which is not allowed. Tell the user how to fix this. ADD_FAILURE() << "All tests in the same test case must use the same test fixture\n" << "class. However, in test case " << this_test_info->test_case_name() << ",\n" << "you defined test " << first_test_name << " and test " << this_test_name << "\n" << "using two different test fixture classes. This can happen if\n" << "the two classes are from different namespaces or translation\n" << "units and have the same name. You should probably rename one\n" << "of the classes to put the tests into different test cases."; } return false; } return true; } #if GTEST_HAS_SEH // Adds an "exception thrown" fatal failure to the current test. This // function returns its result via an output parameter pointer because VC++ // prohibits creation of objects with destructors on stack in functions // using __try (see error C2712). static std::string* FormatSehExceptionMessage(DWORD exception_code, const char* location) { Message message; message << "SEH exception with code 0x" << std::setbase(16) << exception_code << std::setbase(10) << " thrown in " << location << "."; return new std::string(message.GetString()); } #endif // GTEST_HAS_SEH namespace internal { #if GTEST_HAS_EXCEPTIONS // Adds an "exception thrown" fatal failure to the current test. static std::string FormatCxxExceptionMessage(const char* description, const char* location) { Message message; if (description != NULL) { message << "C++ exception with description \"" << description << "\""; } else { message << "Unknown C++ exception"; } message << " thrown in " << location << "."; return message.GetString(); } static std::string PrintTestPartResultToString( const TestPartResult& test_part_result); GoogleTestFailureException::GoogleTestFailureException( const TestPartResult& failure) : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {} #endif // GTEST_HAS_EXCEPTIONS // We put these helper functions in the internal namespace as IBM's xlC // compiler rejects the code if they were declared static. // Runs the given method and handles SEH exceptions it throws, when // SEH is supported; returns the 0-value for type Result in case of an // SEH exception. (Microsoft compilers cannot handle SEH and C++ // exceptions in the same function. Therefore, we provide a separate // wrapper function for handling SEH exceptions.) template <class T, typename Result> Result HandleSehExceptionsInMethodIfSupported( T* object, Result (T::*method)(), const char* location) { #if GTEST_HAS_SEH __try { return (object->*method)(); } __except (internal::UnitTestOptions::GTestShouldProcessSEH( // NOLINT GetExceptionCode())) { // We create the exception message on the heap because VC++ prohibits // creation of objects with destructors on stack in functions using __try // (see error C2712). std::string* exception_message = FormatSehExceptionMessage( GetExceptionCode(), location); internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure, *exception_message); delete exception_message; return static_cast<Result>(0); } #else (void)location; return (object->*method)(); #endif // GTEST_HAS_SEH } // Runs the given method and catches and reports C++ and/or SEH-style // exceptions, if they are supported; returns the 0-value for type // Result in case of an SEH exception. template <class T, typename Result> Result HandleExceptionsInMethodIfSupported( T* object, Result (T::*method)(), const char* location) { // NOTE: The user code can affect the way in which Google Test handles // exceptions by setting GTEST_FLAG(catch_exceptions), but only before // RUN_ALL_TESTS() starts. It is technically possible to check the flag // after the exception is caught and either report or re-throw the // exception based on the flag's value: // // try { // // Perform the test method. // } catch (...) { // if (GTEST_FLAG(catch_exceptions)) // // Report the exception as failure. // else // throw; // Re-throws the original exception. // } // // However, the purpose of this flag is to allow the program to drop into // the debugger when the exception is thrown. On most platforms, once the // control enters the catch block, the exception origin information is // lost and the debugger will stop the program at the point of the // re-throw in this function -- instead of at the point of the original // throw statement in the code under test. For this reason, we perform // the check early, sacrificing the ability to affect Google Test's // exception handling in the method where the exception is thrown. if (internal::GetUnitTestImpl()->catch_exceptions()) { #if GTEST_HAS_EXCEPTIONS try { return HandleSehExceptionsInMethodIfSupported(object, method, location); } catch (const internal::GoogleTestFailureException&) { // NOLINT // This exception type can only be thrown by a failed Google // Test assertion with the intention of letting another testing // framework catch it. Therefore we just re-throw it. throw; } catch (const std::exception& e) { // NOLINT internal::ReportFailureInUnknownLocation( TestPartResult::kFatalFailure, FormatCxxExceptionMessage(e.what(), location)); } catch (...) { // NOLINT internal::ReportFailureInUnknownLocation( TestPartResult::kFatalFailure, FormatCxxExceptionMessage(NULL, location)); } return static_cast<Result>(0); #else return HandleSehExceptionsInMethodIfSupported(object, method, location); #endif // GTEST_HAS_EXCEPTIONS } else { return (object->*method)(); } } } // namespace internal // Runs the test and updates the test result. void Test::Run() { if (!HasSameFixtureClass()) return; internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, "SetUp()"); // We will run the test only if SetUp() was successful. if (!HasFatalFailure()) { impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &Test::TestBody, "the test body"); } // However, we want to clean up as much as possible. Hence we will // always call TearDown(), even if SetUp() or the test body has // failed. impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &Test::TearDown, "TearDown()"); } // Returns true iff the current test has a fatal failure. bool Test::HasFatalFailure() { return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure(); } // Returns true iff the current test has a non-fatal failure. bool Test::HasNonfatalFailure() { return internal::GetUnitTestImpl()->current_test_result()-> HasNonfatalFailure(); } // class TestInfo // Constructs a TestInfo object. It assumes ownership of the test factory // object. TestInfo::TestInfo(const std::string& a_test_case_name, const std::string& a_name, const char* a_type_param, const char* a_value_param, internal::CodeLocation a_code_location, internal::TypeId fixture_class_id, internal::TestFactoryBase* factory) : test_case_name_(a_test_case_name), name_(a_name), type_param_(a_type_param ? new std::string(a_type_param) : NULL), value_param_(a_value_param ? new std::string(a_value_param) : NULL), location_(a_code_location), fixture_class_id_(fixture_class_id), should_run_(false), is_disabled_(false), matches_filter_(false), factory_(factory), result_() {} // Destructs a TestInfo object. TestInfo::~TestInfo() { delete factory_; } namespace internal { // Creates a new TestInfo object and registers it with Google Test; // returns the created object. // // Arguments: // // test_case_name: name of the test case // name: name of the test // type_param: the name of the test's type parameter, or NULL if // this is not a typed or a type-parameterized test. // value_param: text representation of the test's value parameter, // or NULL if this is not a value-parameterized test. // code_location: code location where the test is defined // fixture_class_id: ID of the test fixture class // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case // factory: pointer to the factory that creates a test object. // The newly created TestInfo instance will assume // ownership of the factory object. TestInfo* MakeAndRegisterTestInfo( const char* test_case_name, const char* name, const char* type_param, const char* value_param, CodeLocation code_location, TypeId fixture_class_id, SetUpTestCaseFunc set_up_tc, TearDownTestCaseFunc tear_down_tc, TestFactoryBase* factory) { TestInfo* const test_info = new TestInfo(test_case_name, name, type_param, value_param, code_location, fixture_class_id, factory); GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info); return test_info; } #if GTEST_HAS_PARAM_TEST void ReportInvalidTestCaseType(const char* test_case_name, CodeLocation code_location) { Message errors; errors << "Attempted redefinition of test case " << test_case_name << ".\n" << "All tests in the same test case must use the same test fixture\n" << "class. However, in test case " << test_case_name << ", you tried\n" << "to define a test using a fixture class different from the one\n" << "used earlier. This can happen if the two fixture classes are\n" << "from different namespaces and have the same name. You should\n" << "probably rename one of the classes to put the tests into different\n" << "test cases."; fprintf(stderr, "%s %s", FormatFileLocation(code_location.file.c_str(), code_location.line).c_str(), errors.GetString().c_str()); } #endif // GTEST_HAS_PARAM_TEST } // namespace internal namespace { // A predicate that checks the test name of a TestInfo against a known // value. // // This is used for implementation of the TestCase class only. We put // it in the anonymous namespace to prevent polluting the outer // namespace. // // TestNameIs is copyable. class TestNameIs { public: // Constructor. // // TestNameIs has NO default constructor. explicit TestNameIs(const char* name) : name_(name) {} // Returns true iff the test name of test_info matches name_. bool operator()(const TestInfo * test_info) const { return test_info && test_info->name() == name_; } private: std::string name_; }; } // namespace namespace internal { // This method expands all parameterized tests registered with macros TEST_P // and INSTANTIATE_TEST_CASE_P into regular tests and registers those. // This will be done just once during the program runtime. void UnitTestImpl::RegisterParameterizedTests() { #if GTEST_HAS_PARAM_TEST if (!parameterized_tests_registered_) { parameterized_test_registry_.RegisterTests(); parameterized_tests_registered_ = true; } #endif } } // namespace internal // Creates the test object, runs it, records its result, and then // deletes it. void TestInfo::Run() { if (!should_run_) return; // Tells UnitTest where to store test result. internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); impl->set_current_test_info(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); // Notifies the unit test event listeners that a test is about to start. repeater->OnTestStart(*this); const TimeInMillis start = internal::GetTimeInMillis(); impl->os_stack_trace_getter()->UponLeavingGTest(); // Creates the test object. Test* const test = internal::HandleExceptionsInMethodIfSupported( factory_, &internal::TestFactoryBase::CreateTest, "the test fixture's constructor"); // Runs the test only if the test object was created and its // constructor didn't generate a fatal failure. if ((test != NULL) && !Test::HasFatalFailure()) { // This doesn't throw as all user code that can throw are wrapped into // exception handling code. test->Run(); } // Deletes the test object. impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( test, &Test::DeleteSelf_, "the test fixture's destructor"); result_.set_elapsed_time(internal::GetTimeInMillis() - start); // Notifies the unit test event listener that a test has just finished. repeater->OnTestEnd(*this); // Tells UnitTest to stop associating assertion results to this // test. impl->set_current_test_info(NULL); } // class TestCase // Gets the number of successful tests in this test case. int TestCase::successful_test_count() const { return CountIf(test_info_list_, TestPassed); } // Gets the number of failed tests in this test case. int TestCase::failed_test_count() const { return CountIf(test_info_list_, TestFailed); } // Gets the number of disabled tests that will be reported in the XML report. int TestCase::reportable_disabled_test_count() const { return CountIf(test_info_list_, TestReportableDisabled); } // Gets the number of disabled tests in this test case. int TestCase::disabled_test_count() const { return CountIf(test_info_list_, TestDisabled); } // Gets the number of tests to be printed in the XML report. int TestCase::reportable_test_count() const { return CountIf(test_info_list_, TestReportable); } // Get the number of tests in this test case that should run. int TestCase::test_to_run_count() const { return CountIf(test_info_list_, ShouldRunTest); } // Gets the number of all tests. int TestCase::total_test_count() const { return static_cast<int>(test_info_list_.size()); } // Creates a TestCase with the given name. // // Arguments: // // name: name of the test case // a_type_param: the name of the test case's type parameter, or NULL if // this is not a typed or a type-parameterized test case. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case TestCase::TestCase(const char* a_name, const char* a_type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc) : name_(a_name), type_param_(a_type_param ? new std::string(a_type_param) : NULL), set_up_tc_(set_up_tc), tear_down_tc_(tear_down_tc), should_run_(false), elapsed_time_(0) { } // Destructor of TestCase. TestCase::~TestCase() { // Deletes every Test in the collection. ForEach(test_info_list_, internal::Delete<TestInfo>); } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. const TestInfo* TestCase::GetTestInfo(int i) const { const int index = GetElementOr(test_indices_, i, -1); return index < 0 ? NULL : test_info_list_[index]; } // Returns the i-th test among all the tests. i can range from 0 to // total_test_count() - 1. If i is not in that range, returns NULL. TestInfo* TestCase::GetMutableTestInfo(int i) { const int index = GetElementOr(test_indices_, i, -1); return index < 0 ? NULL : test_info_list_[index]; } // Adds a test to this test case. Will delete the test upon // destruction of the TestCase object. void TestCase::AddTestInfo(TestInfo * test_info) { test_info_list_.push_back(test_info); test_indices_.push_back(static_cast<int>(test_indices_.size())); } // Runs every test in this TestCase. void TestCase::Run() { if (!should_run_) return; internal::UnitTestImpl* const impl = internal::GetUnitTestImpl(); impl->set_current_test_case(this); TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater(); repeater->OnTestCaseStart(*this); impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &TestCase::RunSetUpTestCase, "SetUpTestCase()"); const internal::TimeInMillis start = internal::GetTimeInMillis(); for (int i = 0; i < total_test_count(); i++) { GetMutableTestInfo(i)->Run(); } elapsed_time_ = internal::GetTimeInMillis() - start; impl->os_stack_trace_getter()->UponLeavingGTest(); internal::HandleExceptionsInMethodIfSupported( this, &TestCase::RunTearDownTestCase, "TearDownTestCase()"); repeater->OnTestCaseEnd(*this); impl->set_current_test_case(NULL); } // Clears the results of all tests in this test case. void TestCase::ClearResult() { ad_hoc_test_result_.Clear(); ForEach(test_info_list_, TestInfo::ClearTestResult); } // Shuffles the tests in this test case. void TestCase::ShuffleTests(internal::Random* random) { Shuffle(random, &test_indices_); } // Restores the test order to before the first shuffle. void TestCase::UnshuffleTests() { for (size_t i = 0; i < test_indices_.size(); i++) { test_indices_[i] = static_cast<int>(i); } } // Formats a countable noun. Depending on its quantity, either the // singular form or the plural form is used. e.g. // // FormatCountableNoun(1, "formula", "formuli") returns "1 formula". // FormatCountableNoun(5, "book", "books") returns "5 books". static std::string FormatCountableNoun(int count, const char * singular_form, const char * plural_form) { return internal::StreamableToString(count) + " " + (count == 1 ? singular_form : plural_form); } // Formats the count of tests. static std::string FormatTestCount(int test_count) { return FormatCountableNoun(test_count, "test", "tests"); } // Formats the count of test cases. static std::string FormatTestCaseCount(int test_case_count) { return FormatCountableNoun(test_case_count, "test case", "test cases"); } // Converts a TestPartResult::Type enum to human-friendly string // representation. Both kNonFatalFailure and kFatalFailure are translated // to "Failure", as the user usually doesn't care about the difference // between the two when viewing the test result. static const char * TestPartResultTypeToString(TestPartResult::Type type) { switch (type) { case TestPartResult::kSuccess: return "Success"; case TestPartResult::kNonFatalFailure: case TestPartResult::kFatalFailure: #ifdef _MSC_VER return "error: "; #else return "Failure\n"; #endif default: return "Unknown result type"; } } namespace internal { // Prints a TestPartResult to an std::string. static std::string PrintTestPartResultToString( const TestPartResult& test_part_result) { return (Message() << internal::FormatFileLocation(test_part_result.file_name(), test_part_result.line_number()) << " " << TestPartResultTypeToString(test_part_result.type()) << test_part_result.message()).GetString(); } // Prints a TestPartResult. static void PrintTestPartResult(const TestPartResult& test_part_result) { const std::string& result = PrintTestPartResultToString(test_part_result); printf("%s\n", result.c_str()); fflush(stdout); // If the test program runs in Visual Studio or a debugger, the // following statements add the test part result message to the Output // window such that the user can double-click on it to jump to the // corresponding source code location; otherwise they do nothing. #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE // We don't call OutputDebugString*() on Windows Mobile, as printing // to stdout is done by OutputDebugString() there already - we don't // want the same message printed twice. ::OutputDebugStringA(result.c_str()); ::OutputDebugStringA("\n"); #endif } // class PrettyUnitTestResultPrinter enum GTestColor { COLOR_DEFAULT, COLOR_RED, COLOR_GREEN, COLOR_YELLOW }; #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Returns the character attribute for the given color. WORD GetColorAttribute(GTestColor color) { switch (color) { case COLOR_RED: return FOREGROUND_RED; case COLOR_GREEN: return FOREGROUND_GREEN; case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN; default: return 0; } } #else // Returns the ANSI color code for the given color. COLOR_DEFAULT is // an invalid input. const char* GetAnsiColorCode(GTestColor color) { switch (color) { case COLOR_RED: return "1"; case COLOR_GREEN: return "2"; case COLOR_YELLOW: return "3"; default: return NULL; }; } #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE // Returns true iff Google Test should use colors in the output. bool ShouldUseColor(bool stdout_is_tty) { const char* const gtest_color = GTEST_FLAG(color).c_str(); if (String::CaseInsensitiveCStringEquals(gtest_color, "auto")) { #if GTEST_OS_WINDOWS // On Windows the TERM variable is usually not set, but the // console there does support colors. return stdout_is_tty; #else // On non-Windows platforms, we rely on the TERM variable. const char* const term = posix::GetEnv("TERM"); const bool term_supports_color = String::CStringEquals(term, "xterm") || String::CStringEquals(term, "xterm-color") || String::CStringEquals(term, "xterm-256color") || String::CStringEquals(term, "screen") || String::CStringEquals(term, "screen-256color") || String::CStringEquals(term, "tmux") || String::CStringEquals(term, "tmux-256color") || String::CStringEquals(term, "rxvt-unicode") || String::CStringEquals(term, "rxvt-unicode-256color") || String::CStringEquals(term, "linux") || String::CStringEquals(term, "cygwin"); return stdout_is_tty && term_supports_color; #endif // GTEST_OS_WINDOWS } return String::CaseInsensitiveCStringEquals(gtest_color, "yes") || String::CaseInsensitiveCStringEquals(gtest_color, "true") || String::CaseInsensitiveCStringEquals(gtest_color, "t") || String::CStringEquals(gtest_color, "1"); // We take "yes", "true", "t", and "1" as meaning "yes". If the // value is neither one of these nor "auto", we treat it as "no" to // be conservative. } // Helpers for printing colored strings to stdout. Note that on Windows, we // cannot simply emit special characters and have the terminal change colors. // This routine must actually emit the characters rather than return a string // that would be colored when printed, as can be done on Linux. void ColoredPrintf(GTestColor color, const char* fmt, ...) { va_list args; va_start(args, fmt); #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \ GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT const bool use_color = AlwaysFalse(); #else static const bool in_color_mode = ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0); const bool use_color = in_color_mode && (color != COLOR_DEFAULT); #endif // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS // The '!= 0' comparison is necessary to satisfy MSVC 7.1. if (!use_color) { vprintf(fmt, args); va_end(args); return; } #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \ !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE); // Gets the current text color. CONSOLE_SCREEN_BUFFER_INFO buffer_info; GetConsoleScreenBufferInfo(stdout_handle, &buffer_info); const WORD old_color_attrs = buffer_info.wAttributes; // We need to flush the stream buffers into the console before each // SetConsoleTextAttribute call lest it affect the text that is already // printed but has not yet reached the console. fflush(stdout); SetConsoleTextAttribute(stdout_handle, GetColorAttribute(color) | FOREGROUND_INTENSITY); vprintf(fmt, args); fflush(stdout); // Restores the text color. SetConsoleTextAttribute(stdout_handle, old_color_attrs); #else printf("\033[0;3%sm", GetAnsiColorCode(color)); vprintf(fmt, args); printf("\033[m"); // Resets the terminal to default. #endif // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE va_end(args); } // Text printed in Google Test's text output and --gunit_list_tests // output to label the type parameter and value parameter for a test. static const char kTypeParamLabel[] = "TypeParam"; static const char kValueParamLabel[] = "GetParam()"; void PrintFullTestCommentIfPresent(const TestInfo& test_info) { const char* const type_param = test_info.type_param(); const char* const value_param = test_info.value_param(); if (type_param != NULL || value_param != NULL) { printf(", where "); if (type_param != NULL) { printf("%s = %s", kTypeParamLabel, type_param); if (value_param != NULL) printf(" and "); } if (value_param != NULL) { printf("%s = %s", kValueParamLabel, value_param); } } } // This class implements the TestEventListener interface. // // Class PrettyUnitTestResultPrinter is copyable. class PrettyUnitTestResultPrinter : public TestEventListener { public: PrettyUnitTestResultPrinter() {} static void PrintTestName(const char * test_case, const char * test) { printf("%s.%s", test_case, test); } // The following methods override what's in the TestEventListener class. virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {} virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {} virtual void OnTestCaseStart(const TestCase& test_case); virtual void OnTestStart(const TestInfo& test_info); virtual void OnTestPartResult(const TestPartResult& result); virtual void OnTestEnd(const TestInfo& test_info); virtual void OnTestCaseEnd(const TestCase& test_case); virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {} virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {} private: static void PrintFailedTests(const UnitTest& unit_test); }; // Fired before each iteration of tests starts. void PrettyUnitTestResultPrinter::OnTestIterationStart( const UnitTest& unit_test, int iteration) { if (GTEST_FLAG(repeat) != 1) printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration + 1); const char* const filter = GTEST_FLAG(filter).c_str(); // Prints the filter if it's not *. This reminds the user that some // tests may be skipped. if (!String::CStringEquals(filter, kUniversalFilter)) { ColoredPrintf(COLOR_YELLOW, "Note: %s filter = %s\n", GTEST_NAME_, filter); } if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) { const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1); ColoredPrintf(COLOR_YELLOW, "Note: This is test shard %d of %s.\n", static_cast<int>(shard_index) + 1, internal::posix::GetEnv(kTestTotalShards)); } if (GTEST_FLAG(shuffle)) { ColoredPrintf(COLOR_YELLOW, "Note: Randomizing tests' orders with a seed of %d .\n", unit_test.random_seed()); } ColoredPrintf(COLOR_GREEN, "[==========] "); printf("Running %s from %s.\n", FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); fflush(stdout); } void PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart( const UnitTest& /*unit_test*/) { ColoredPrintf(COLOR_GREEN, "[----------] "); printf("Global test environment set-up.\n"); fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) { const std::string counts = FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); ColoredPrintf(COLOR_GREEN, "[----------] "); printf("%s from %s", counts.c_str(), test_case.name()); if (test_case.type_param() == NULL) { printf("\n"); } else { printf(", where %s = %s\n", kTypeParamLabel, test_case.type_param()); } fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) { ColoredPrintf(COLOR_GREEN, "[ RUN ] "); PrintTestName(test_info.test_case_name(), test_info.name()); printf("\n"); fflush(stdout); } // Called after an assertion failure. void PrettyUnitTestResultPrinter::OnTestPartResult( const TestPartResult& result) { // If the test part succeeded, we don't need to do anything. if (result.type() == TestPartResult::kSuccess) return; // Print failure message from the assertion (e.g. expected this and got that). PrintTestPartResult(result); fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) { if (test_info.result()->Passed()) { ColoredPrintf(COLOR_GREEN, "[ OK ] "); } else { ColoredPrintf(COLOR_RED, "[ FAILED ] "); } PrintTestName(test_info.test_case_name(), test_info.name()); if (test_info.result()->Failed()) PrintFullTestCommentIfPresent(test_info); if (GTEST_FLAG(print_time)) { printf(" (%s ms)\n", internal::StreamableToString( test_info.result()->elapsed_time()).c_str()); } else { printf("\n"); } fflush(stdout); } void PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) { if (!GTEST_FLAG(print_time)) return; const std::string counts = FormatCountableNoun(test_case.test_to_run_count(), "test", "tests"); ColoredPrintf(COLOR_GREEN, "[----------] "); printf("%s from %s (%s ms total)\n\n", counts.c_str(), test_case.name(), internal::StreamableToString(test_case.elapsed_time()).c_str()); fflush(stdout); } void PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart( const UnitTest& /*unit_test*/) { ColoredPrintf(COLOR_GREEN, "[----------] "); printf("Global test environment tear-down\n"); fflush(stdout); } // Internal helper for printing the list of failed tests. void PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) { const int failed_test_count = unit_test.failed_test_count(); if (failed_test_count == 0) { return; } for (int i = 0; i < unit_test.total_test_case_count(); ++i) { const TestCase& test_case = *unit_test.GetTestCase(i); if (!test_case.should_run() || (test_case.failed_test_count() == 0)) { continue; } for (int j = 0; j < test_case.total_test_count(); ++j) { const TestInfo& test_info = *test_case.GetTestInfo(j); if (!test_info.should_run() || test_info.result()->Passed()) { continue; } ColoredPrintf(COLOR_RED, "[ FAILED ] "); printf("%s.%s", test_case.name(), test_info.name()); PrintFullTestCommentIfPresent(test_info); printf("\n"); } } } void PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int /*iteration*/) { ColoredPrintf(COLOR_GREEN, "[==========] "); printf("%s from %s ran.", FormatTestCount(unit_test.test_to_run_count()).c_str(), FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str()); if (GTEST_FLAG(print_time)) { printf(" (%s ms total)", internal::StreamableToString(unit_test.elapsed_time()).c_str()); } printf("\n"); ColoredPrintf(COLOR_GREEN, "[ PASSED ] "); printf("%s.\n", FormatTestCount(unit_test.successful_test_count()).c_str()); int num_failures = unit_test.failed_test_count(); if (!unit_test.Passed()) { const int failed_test_count = unit_test.failed_test_count(); ColoredPrintf(COLOR_RED, "[ FAILED ] "); printf("%s, listed below:\n", FormatTestCount(failed_test_count).c_str()); PrintFailedTests(unit_test); printf("\n%2d FAILED %s\n", num_failures, num_failures == 1 ? "TEST" : "TESTS"); } int num_disabled = unit_test.reportable_disabled_test_count(); if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) { if (!num_failures) { printf("\n"); // Add a spacer if no FAILURE banner is displayed. } ColoredPrintf(COLOR_YELLOW, " YOU HAVE %d DISABLED %s\n\n", num_disabled, num_disabled == 1 ? "TEST" : "TESTS"); } // Ensure that Google Test output is printed before, e.g., heapchecker output. fflush(stdout); } // End PrettyUnitTestResultPrinter // class TestEventRepeater // // This class forwards events to other event listeners. class TestEventRepeater : public TestEventListener { public: TestEventRepeater() : forwarding_enabled_(true) {} virtual ~TestEventRepeater(); void Append(TestEventListener *listener); TestEventListener* Release(TestEventListener* listener); // Controls whether events will be forwarded to listeners_. Set to false // in death test child processes. bool forwarding_enabled() const { return forwarding_enabled_; } void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; } virtual void OnTestProgramStart(const UnitTest& unit_test); virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration); virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test); virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test); virtual void OnTestCaseStart(const TestCase& test_case); virtual void OnTestStart(const TestInfo& test_info); virtual void OnTestPartResult(const TestPartResult& result); virtual void OnTestEnd(const TestInfo& test_info); virtual void OnTestCaseEnd(const TestCase& test_case); virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test); virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test); virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); virtual void OnTestProgramEnd(const UnitTest& unit_test); private: // Controls whether events will be forwarded to listeners_. Set to false // in death test child processes. bool forwarding_enabled_; // The list of listeners that receive events. std::vector<TestEventListener*> listeners_; GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater); }; TestEventRepeater::~TestEventRepeater() { ForEach(listeners_, Delete<TestEventListener>); } void TestEventRepeater::Append(TestEventListener *listener) { listeners_.push_back(listener); } // TODO(vladl@google.com): Factor the search functionality into Vector::Find. TestEventListener* TestEventRepeater::Release(TestEventListener *listener) { for (size_t i = 0; i < listeners_.size(); ++i) { if (listeners_[i] == listener) { listeners_.erase(listeners_.begin() + i); return listener; } } return NULL; } // Since most methods are very similar, use macros to reduce boilerplate. // This defines a member that forwards the call to all listeners. #define GTEST_REPEATER_METHOD_(Name, Type) \ void TestEventRepeater::Name(const Type& parameter) { \ if (forwarding_enabled_) { \ for (size_t i = 0; i < listeners_.size(); i++) { \ listeners_[i]->Name(parameter); \ } \ } \ } // This defines a member that forwards the call to all listeners in reverse // order. #define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \ void TestEventRepeater::Name(const Type& parameter) { \ if (forwarding_enabled_) { \ for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \ listeners_[i]->Name(parameter); \ } \ } \ } GTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest) GTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest) GTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase) GTEST_REPEATER_METHOD_(OnTestStart, TestInfo) GTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult) GTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest) GTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo) GTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase) GTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest) #undef GTEST_REPEATER_METHOD_ #undef GTEST_REVERSE_REPEATER_METHOD_ void TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test, int iteration) { if (forwarding_enabled_) { for (size_t i = 0; i < listeners_.size(); i++) { listeners_[i]->OnTestIterationStart(unit_test, iteration); } } } void TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test, int iteration) { if (forwarding_enabled_) { for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { listeners_[i]->OnTestIterationEnd(unit_test, iteration); } } } // End TestEventRepeater // This class generates an XML output file. class XmlUnitTestResultPrinter : public EmptyTestEventListener { public: explicit XmlUnitTestResultPrinter(const char* output_file); virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration); private: // Is c a whitespace character that is normalized to a space character // when it appears in an XML attribute value? static bool IsNormalizableWhitespace(char c) { return c == 0x9 || c == 0xA || c == 0xD; } // May c appear in a well-formed XML document? static bool IsValidXmlCharacter(char c) { return IsNormalizableWhitespace(c) || c >= 0x20; } // Returns an XML-escaped copy of the input string str. If // is_attribute is true, the text is meant to appear as an attribute // value, and normalizable whitespace is preserved by replacing it // with character references. static std::string EscapeXml(const std::string& str, bool is_attribute); // Returns the given string with all characters invalid in XML removed. static std::string RemoveInvalidXmlCharacters(const std::string& str); // Convenience wrapper around EscapeXml when str is an attribute value. static std::string EscapeXmlAttribute(const std::string& str) { return EscapeXml(str, true); } // Convenience wrapper around EscapeXml when str is not an attribute value. static std::string EscapeXmlText(const char* str) { return EscapeXml(str, false); } // Verifies that the given attribute belongs to the given element and // streams the attribute as XML. static void OutputXmlAttribute(std::ostream* stream, const std::string& element_name, const std::string& name, const std::string& value); // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. static void OutputXmlCDataSection(::std::ostream* stream, const char* data); // Streams an XML representation of a TestInfo object. static void OutputXmlTestInfo(::std::ostream* stream, const char* test_case_name, const TestInfo& test_info); // Prints an XML representation of a TestCase object static void PrintXmlTestCase(::std::ostream* stream, const TestCase& test_case); // Prints an XML summary of unit_test to output stream out. static void PrintXmlUnitTest(::std::ostream* stream, const UnitTest& unit_test); // Produces a string representing the test properties in a result as space // delimited XML attributes based on the property key="value" pairs. // When the std::string is not empty, it includes a space at the beginning, // to delimit this attribute from prior attributes. static std::string TestPropertiesAsXmlAttributes(const TestResult& result); // The output file. const std::string output_file_; GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter); }; // Creates a new XmlUnitTestResultPrinter. XmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file) : output_file_(output_file) { if (output_file_.c_str() == NULL || output_file_.empty()) { fprintf(stderr, "XML output file may not be null\n"); fflush(stderr); exit(EXIT_FAILURE); } } // Called after the unit test ends. void XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test, int /*iteration*/) { FILE* xmlout = NULL; FilePath output_file(output_file_); FilePath output_dir(output_file.RemoveFileName()); if (output_dir.CreateDirectoriesRecursively()) { xmlout = posix::FOpen(output_file_.c_str(), "w"); } if (xmlout == NULL) { // TODO(wan): report the reason of the failure. // // We don't do it for now as: // // 1. There is no urgent need for it. // 2. It's a bit involved to make the errno variable thread-safe on // all three operating systems (Linux, Windows, and Mac OS). // 3. To interpret the meaning of errno in a thread-safe way, // we need the strerror_r() function, which is not available on // Windows. fprintf(stderr, "Unable to open file \"%s\"\n", output_file_.c_str()); fflush(stderr); exit(EXIT_FAILURE); } std::stringstream stream; PrintXmlUnitTest(&stream, unit_test); fprintf(xmlout, "%s", StringStreamToString(&stream).c_str()); fclose(xmlout); } // Returns an XML-escaped copy of the input string str. If is_attribute // is true, the text is meant to appear as an attribute value, and // normalizable whitespace is preserved by replacing it with character // references. // // Invalid XML characters in str, if any, are stripped from the output. // It is expected that most, if not all, of the text processed by this // module will consist of ordinary English text. // If this module is ever modified to produce version 1.1 XML output, // most invalid characters can be retained using character references. // TODO(wan): It might be nice to have a minimally invasive, human-readable // escaping scheme for invalid characters, rather than dropping them. std::string XmlUnitTestResultPrinter::EscapeXml( const std::string& str, bool is_attribute) { Message m; for (size_t i = 0; i < str.size(); ++i) { const char ch = str[i]; switch (ch) { case '<': m << "&lt;"; break; case '>': m << "&gt;"; break; case '&': m << "&amp;"; break; case '\'': if (is_attribute) m << "&apos;"; else m << '\''; break; case '"': if (is_attribute) m << "&quot;"; else m << '"'; break; default: if (IsValidXmlCharacter(ch)) { if (is_attribute && IsNormalizableWhitespace(ch)) m << "&#x" << String::FormatByte(static_cast<unsigned char>(ch)) << ";"; else m << ch; } break; } } return m.GetString(); } // Returns the given string with all characters invalid in XML removed. // Currently invalid characters are dropped from the string. An // alternative is to replace them with certain characters such as . or ?. std::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters( const std::string& str) { std::string output; output.reserve(str.size()); for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) if (IsValidXmlCharacter(*it)) output.push_back(*it); return output; } // The following routines generate an XML representation of a UnitTest // object. // // This is how Google Test concepts map to the DTD: // // <testsuites name="AllTests"> <-- corresponds to a UnitTest object // <testsuite name="testcase-name"> <-- corresponds to a TestCase object // <testcase name="test-name"> <-- corresponds to a TestInfo object // <failure message="...">...</failure> // <failure message="...">...</failure> // <failure message="...">...</failure> // <-- individual assertion failures // </testcase> // </testsuite> // </testsuites> // Formats the given time in milliseconds as seconds. std::string FormatTimeInMillisAsSeconds(TimeInMillis ms) { ::std::stringstream ss; ss << (static_cast<double>(ms) * 1e-3); return ss.str(); } static bool PortableLocaltime(time_t seconds, struct tm* out) { #if defined(_MSC_VER) return localtime_s(out, &seconds) == 0; #elif defined(__MINGW32__) || defined(__MINGW64__) // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses // Windows' localtime(), which has a thread-local tm buffer. struct tm* tm_ptr = localtime(&seconds); // NOLINT if (tm_ptr == NULL) return false; *out = *tm_ptr; return true; #else return localtime_r(&seconds, out) != NULL; #endif } // Converts the given epoch time in milliseconds to a date string in the ISO // 8601 format, without the timezone information. std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) { struct tm time_struct; if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct)) return ""; // YYYY-MM-DDThh:mm:ss return StreamableToString(time_struct.tm_year + 1900) + "-" + String::FormatIntWidth2(time_struct.tm_mon + 1) + "-" + String::FormatIntWidth2(time_struct.tm_mday) + "T" + String::FormatIntWidth2(time_struct.tm_hour) + ":" + String::FormatIntWidth2(time_struct.tm_min) + ":" + String::FormatIntWidth2(time_struct.tm_sec); } // Streams an XML CDATA section, escaping invalid CDATA sequences as needed. void XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream, const char* data) { const char* segment = data; *stream << "<![CDATA["; for (;;) { const char* const next_segment = strstr(segment, "]]>"); if (next_segment != NULL) { stream->write( segment, static_cast<std::streamsize>(next_segment - segment)); *stream << "]]>]]&gt;<![CDATA["; segment = next_segment + strlen("]]>"); } else { *stream << segment; break; } } *stream << "]]>"; } void XmlUnitTestResultPrinter::OutputXmlAttribute( std::ostream* stream, const std::string& element_name, const std::string& name, const std::string& value) { const std::vector<std::string>& allowed_names = GetReservedAttributesForElement(element_name); GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) != allowed_names.end()) << "Attribute " << name << " is not allowed for element <" << element_name << ">."; *stream << " " << name << "=\"" << EscapeXmlAttribute(value) << "\""; } // Prints an XML representation of a TestInfo object. // TODO(wan): There is also value in printing properties with the plain printer. void XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream, const char* test_case_name, const TestInfo& test_info) { const TestResult& result = *test_info.result(); const std::string kTestcase = "testcase"; *stream << " <testcase"; OutputXmlAttribute(stream, kTestcase, "name", test_info.name()); if (test_info.value_param() != NULL) { OutputXmlAttribute(stream, kTestcase, "value_param", test_info.value_param()); } if (test_info.type_param() != NULL) { OutputXmlAttribute(stream, kTestcase, "type_param", test_info.type_param()); } OutputXmlAttribute(stream, kTestcase, "status", test_info.should_run() ? "run" : "notrun"); OutputXmlAttribute(stream, kTestcase, "time", FormatTimeInMillisAsSeconds(result.elapsed_time())); OutputXmlAttribute(stream, kTestcase, "classname", test_case_name); *stream << TestPropertiesAsXmlAttributes(result); int failures = 0; for (int i = 0; i < result.total_part_count(); ++i) { const TestPartResult& part = result.GetTestPartResult(i); if (part.failed()) { if (++failures == 1) { *stream << ">\n"; } const string location = internal::FormatCompilerIndependentFileLocation( part.file_name(), part.line_number()); const string summary = location + "\n" + part.summary(); *stream << " <failure message=\"" << EscapeXmlAttribute(summary.c_str()) << "\" type=\"\">"; const string detail = location + "\n" + part.message(); OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str()); *stream << "</failure>\n"; } } if (failures == 0) *stream << " />\n"; else *stream << " </testcase>\n"; } // Prints an XML representation of a TestCase object void XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream, const TestCase& test_case) { const std::string kTestsuite = "testsuite"; *stream << " <" << kTestsuite; OutputXmlAttribute(stream, kTestsuite, "name", test_case.name()); OutputXmlAttribute(stream, kTestsuite, "tests", StreamableToString(test_case.reportable_test_count())); OutputXmlAttribute(stream, kTestsuite, "failures", StreamableToString(test_case.failed_test_count())); OutputXmlAttribute( stream, kTestsuite, "disabled", StreamableToString(test_case.reportable_disabled_test_count())); OutputXmlAttribute(stream, kTestsuite, "errors", "0"); OutputXmlAttribute(stream, kTestsuite, "time", FormatTimeInMillisAsSeconds(test_case.elapsed_time())); *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result()) << ">\n"; for (int i = 0; i < test_case.total_test_count(); ++i) { if (test_case.GetTestInfo(i)->is_reportable()) OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i)); } *stream << " </" << kTestsuite << ">\n"; } // Prints an XML summary of unit_test to output stream out. void XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream, const UnitTest& unit_test) { const std::string kTestsuites = "testsuites"; *stream << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; *stream << "<" << kTestsuites; OutputXmlAttribute(stream, kTestsuites, "tests", StreamableToString(unit_test.reportable_test_count())); OutputXmlAttribute(stream, kTestsuites, "failures", StreamableToString(unit_test.failed_test_count())); OutputXmlAttribute( stream, kTestsuites, "disabled", StreamableToString(unit_test.reportable_disabled_test_count())); OutputXmlAttribute(stream, kTestsuites, "errors", "0"); OutputXmlAttribute( stream, kTestsuites, "timestamp", FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp())); OutputXmlAttribute(stream, kTestsuites, "time", FormatTimeInMillisAsSeconds(unit_test.elapsed_time())); if (GTEST_FLAG(shuffle)) { OutputXmlAttribute(stream, kTestsuites, "random_seed", StreamableToString(unit_test.random_seed())); } *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result()); OutputXmlAttribute(stream, kTestsuites, "name", "AllTests"); *stream << ">\n"; for (int i = 0; i < unit_test.total_test_case_count(); ++i) { if (unit_test.GetTestCase(i)->reportable_test_count() > 0) PrintXmlTestCase(stream, *unit_test.GetTestCase(i)); } *stream << "</" << kTestsuites << ">\n"; } // Produces a string representing the test properties in a result as space // delimited XML attributes based on the property key="value" pairs. std::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes( const TestResult& result) { Message attributes; for (int i = 0; i < result.test_property_count(); ++i) { const TestProperty& property = result.GetTestProperty(i); attributes << " " << property.key() << "=" << "\"" << EscapeXmlAttribute(property.value()) << "\""; } return attributes.GetString(); } // End XmlUnitTestResultPrinter #if GTEST_CAN_STREAM_RESULTS_ // Checks if str contains '=', '&', '%' or '\n' characters. If yes, // replaces them by "%xx" where xx is their hexadecimal value. For // example, replaces "=" with "%3D". This algorithm is O(strlen(str)) // in both time and space -- important as the input str may contain an // arbitrarily long test failure message and stack trace. string StreamingListener::UrlEncode(const char* str) { string result; result.reserve(strlen(str) + 1); for (char ch = *str; ch != '\0'; ch = *++str) { switch (ch) { case '%': case '=': case '&': case '\n': result.append("%" + String::FormatByte(static_cast<unsigned char>(ch))); break; default: result.push_back(ch); break; } } return result; } void StreamingListener::SocketWriter::MakeConnection() { GTEST_CHECK_(sockfd_ == -1) << "MakeConnection() can't be called when there is already a connection."; addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; // To allow both IPv4 and IPv6 addresses. hints.ai_socktype = SOCK_STREAM; addrinfo* servinfo = NULL; // Use the getaddrinfo() to get a linked list of IP addresses for // the given host name. const int error_num = getaddrinfo( host_name_.c_str(), port_num_.c_str(), &hints, &servinfo); if (error_num != 0) { GTEST_LOG_(WARNING) << "stream_result_to: getaddrinfo() failed: " << gai_strerror(error_num); } // Loop through all the results and connect to the first we can. for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL; cur_addr = cur_addr->ai_next) { sockfd_ = socket( cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol); if (sockfd_ != -1) { // Connect the client socket to the server socket. if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) { close(sockfd_); sockfd_ = -1; } } } freeaddrinfo(servinfo); // all done with this structure if (sockfd_ == -1) { GTEST_LOG_(WARNING) << "stream_result_to: failed to connect to " << host_name_ << ":" << port_num_; } } // End of class Streaming Listener #endif // GTEST_CAN_STREAM_RESULTS__ // Class ScopedTrace // Pushes the given source file location and message onto a per-thread // trace stack maintained by Google Test. ScopedTrace::ScopedTrace(const char* file, int line, const Message& message) GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { TraceInfo trace; trace.file = file; trace.line = line; trace.message = message.GetString(); UnitTest::GetInstance()->PushGTestTrace(trace); } // Pops the info pushed by the c'tor. ScopedTrace::~ScopedTrace() GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) { UnitTest::GetInstance()->PopGTestTrace(); } // class OsStackTraceGetter const char* const OsStackTraceGetterInterface::kElidedFramesMarker = "... " GTEST_NAME_ " internal frames ..."; string OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/, int /*skip_count*/) { return ""; } void OsStackTraceGetter::UponLeavingGTest() {} // A helper class that creates the premature-exit file in its // constructor and deletes the file in its destructor. class ScopedPrematureExitFile { public: explicit ScopedPrematureExitFile(const char* premature_exit_filepath) : premature_exit_filepath_(premature_exit_filepath) { // If a path to the premature-exit file is specified... if (premature_exit_filepath != NULL && *premature_exit_filepath != '\0') { // create the file with a single "0" character in it. I/O // errors are ignored as there's nothing better we can do and we // don't want to fail the test because of this. FILE* pfile = posix::FOpen(premature_exit_filepath, "w"); fwrite("0", 1, 1, pfile); fclose(pfile); } } ~ScopedPrematureExitFile() { if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\0') { remove(premature_exit_filepath_); } } private: const char* const premature_exit_filepath_; GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile); }; } // namespace internal // class TestEventListeners TestEventListeners::TestEventListeners() : repeater_(new internal::TestEventRepeater()), default_result_printer_(NULL), default_xml_generator_(NULL) { } TestEventListeners::~TestEventListeners() { delete repeater_; } // Returns the standard listener responsible for the default console // output. Can be removed from the listeners list to shut down default // console output. Note that removing this object from the listener list // with Release transfers its ownership to the user. void TestEventListeners::Append(TestEventListener* listener) { repeater_->Append(listener); } // Removes the given event listener from the list and returns it. It then // becomes the caller's responsibility to delete the listener. Returns // NULL if the listener is not found in the list. TestEventListener* TestEventListeners::Release(TestEventListener* listener) { if (listener == default_result_printer_) default_result_printer_ = NULL; else if (listener == default_xml_generator_) default_xml_generator_ = NULL; return repeater_->Release(listener); } // Returns repeater that broadcasts the TestEventListener events to all // subscribers. TestEventListener* TestEventListeners::repeater() { return repeater_; } // Sets the default_result_printer attribute to the provided listener. // The listener is also added to the listener list and previous // default_result_printer is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) { if (default_result_printer_ != listener) { // It is an error to pass this method a listener that is already in the // list. delete Release(default_result_printer_); default_result_printer_ = listener; if (listener != NULL) Append(listener); } } // Sets the default_xml_generator attribute to the provided listener. The // listener is also added to the listener list and previous // default_xml_generator is removed from it and deleted. The listener can // also be NULL in which case it will not be added to the list. Does // nothing if the previous and the current listener objects are the same. void TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) { if (default_xml_generator_ != listener) { // It is an error to pass this method a listener that is already in the // list. delete Release(default_xml_generator_); default_xml_generator_ = listener; if (listener != NULL) Append(listener); } } // Controls whether events will be forwarded by the repeater to the // listeners in the list. bool TestEventListeners::EventForwardingEnabled() const { return repeater_->forwarding_enabled(); } void TestEventListeners::SuppressEventForwarding() { repeater_->set_forwarding_enabled(false); } // class UnitTest // Gets the singleton UnitTest object. The first time this method is // called, a UnitTest object is constructed and returned. Consecutive // calls will return the same object. // // We don't protect this under mutex_ as a user is not supposed to // call this before main() starts, from which point on the return // value will never change. UnitTest* UnitTest::GetInstance() { // When compiled with MSVC 7.1 in optimized mode, destroying the // UnitTest object upon exiting the program messes up the exit code, // causing successful tests to appear failed. We have to use a // different implementation in this case to bypass the compiler bug. // This implementation makes the compiler happy, at the cost of // leaking the UnitTest object. // CodeGear C++Builder insists on a public destructor for the // default implementation. Use this implementation to keep good OO // design with private destructor. #if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) static UnitTest* const instance = new UnitTest; return instance; #else static UnitTest instance; return &instance; #endif // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__) } // Gets the number of successful test cases. int UnitTest::successful_test_case_count() const { return impl()->successful_test_case_count(); } // Gets the number of failed test cases. int UnitTest::failed_test_case_count() const { return impl()->failed_test_case_count(); } // Gets the number of all test cases. int UnitTest::total_test_case_count() const { return impl()->total_test_case_count(); } // Gets the number of all test cases that contain at least one test // that should run. int UnitTest::test_case_to_run_count() const { return impl()->test_case_to_run_count(); } // Gets the number of successful tests. int UnitTest::successful_test_count() const { return impl()->successful_test_count(); } // Gets the number of failed tests. int UnitTest::failed_test_count() const { return impl()->failed_test_count(); } // Gets the number of disabled tests that will be reported in the XML report. int UnitTest::reportable_disabled_test_count() const { return impl()->reportable_disabled_test_count(); } // Gets the number of disabled tests. int UnitTest::disabled_test_count() const { return impl()->disabled_test_count(); } // Gets the number of tests to be printed in the XML report. int UnitTest::reportable_test_count() const { return impl()->reportable_test_count(); } // Gets the number of all tests. int UnitTest::total_test_count() const { return impl()->total_test_count(); } // Gets the number of tests that should run. int UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); } // Gets the time of the test program start, in ms from the start of the // UNIX epoch. internal::TimeInMillis UnitTest::start_timestamp() const { return impl()->start_timestamp(); } // Gets the elapsed time, in milliseconds. internal::TimeInMillis UnitTest::elapsed_time() const { return impl()->elapsed_time(); } // Returns true iff the unit test passed (i.e. all test cases passed). bool UnitTest::Passed() const { return impl()->Passed(); } // Returns true iff the unit test failed (i.e. some test case failed // or something outside of all tests failed). bool UnitTest::Failed() const { return impl()->Failed(); } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. const TestCase* UnitTest::GetTestCase(int i) const { return impl()->GetTestCase(i); } // Returns the TestResult containing information on test failures and // properties logged outside of individual test cases. const TestResult& UnitTest::ad_hoc_test_result() const { return *impl()->ad_hoc_test_result(); } // Gets the i-th test case among all the test cases. i can range from 0 to // total_test_case_count() - 1. If i is not in that range, returns NULL. TestCase* UnitTest::GetMutableTestCase(int i) { return impl()->GetMutableTestCase(i); } // Returns the list of event listeners that can be used to track events // inside Google Test. TestEventListeners& UnitTest::listeners() { return *impl()->listeners(); } // Registers and returns a global test environment. When a test // program is run, all global test environments will be set-up in the // order they were registered. After all tests in the program have // finished, all global test environments will be torn-down in the // *reverse* order they were registered. // // The UnitTest object takes ownership of the given environment. // // We don't protect this under mutex_, as we only support calling it // from the main thread. Environment* UnitTest::AddEnvironment(Environment* env) { if (env == NULL) { return NULL; } impl_->environments().push_back(env); return env; } // Adds a TestPartResult to the current TestResult object. All Google Test // assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call // this to report their results. The user code should use the // assertion macros instead of calling this directly. void UnitTest::AddTestPartResult( TestPartResult::Type result_type, const char* file_name, int line_number, const std::string& message, const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) { Message msg; msg << message; internal::MutexLock lock(&mutex_); if (impl_->gtest_trace_stack().size() > 0) { msg << "\n" << GTEST_NAME_ << " trace:"; for (int i = static_cast<int>(impl_->gtest_trace_stack().size()); i > 0; --i) { const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1]; msg << "\n" << internal::FormatFileLocation(trace.file, trace.line) << " " << trace.message; } } if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) { msg << internal::kStackTraceMarker << os_stack_trace; } const TestPartResult result = TestPartResult(result_type, file_name, line_number, msg.GetString().c_str()); impl_->GetTestPartResultReporterForCurrentThread()-> ReportTestPartResult(result); if (result_type != TestPartResult::kSuccess) { // gtest_break_on_failure takes precedence over // gtest_throw_on_failure. This allows a user to set the latter // in the code (perhaps in order to use Google Test assertions // with another testing framework) and specify the former on the // command line for debugging. if (GTEST_FLAG(break_on_failure)) { #if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // Using DebugBreak on Windows allows gtest to still break into a debugger // when a failure happens and both the --gtest_break_on_failure and // the --gtest_catch_exceptions flags are specified. DebugBreak(); #else // Dereference NULL through a volatile pointer to prevent the compiler // from removing. We use this rather than abort() or __builtin_trap() for // portability: Symbian doesn't implement abort() well, and some debuggers // don't correctly trap abort(). *static_cast<volatile int*>(NULL) = 1; #endif // GTEST_OS_WINDOWS } else if (GTEST_FLAG(throw_on_failure)) { #if GTEST_HAS_EXCEPTIONS throw internal::GoogleTestFailureException(result); #else // We cannot call abort() as it generates a pop-up in debug mode // that cannot be suppressed in VC 7.1 or below. exit(1); #endif } } } // Adds a TestProperty to the current TestResult object when invoked from // inside a test, to current TestCase's ad_hoc_test_result_ when invoked // from SetUpTestCase or TearDownTestCase, or to the global property set // when invoked elsewhere. If the result already contains a property with // the same key, the value will be updated. void UnitTest::RecordProperty(const std::string& key, const std::string& value) { impl_->RecordProperty(TestProperty(key, value)); } // Runs all tests in this UnitTest object and prints the result. // Returns 0 if successful, or 1 otherwise. // // We don't protect this under mutex_, as we only support calling it // from the main thread. int UnitTest::Run() { const bool in_death_test_child_process = internal::GTEST_FLAG(internal_run_death_test).length() > 0; // Google Test implements this protocol for catching that a test // program exits before returning control to Google Test: // // 1. Upon start, Google Test creates a file whose absolute path // is specified by the environment variable // TEST_PREMATURE_EXIT_FILE. // 2. When Google Test has finished its work, it deletes the file. // // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before // running a Google-Test-based test program and check the existence // of the file at the end of the test execution to see if it has // exited prematurely. // If we are in the child process of a death test, don't // create/delete the premature exit file, as doing so is unnecessary // and will confuse the parent process. Otherwise, create/delete // the file upon entering/leaving this function. If the program // somehow exits before this function has a chance to return, the // premature-exit file will be left undeleted, causing a test runner // that understands the premature-exit-file protocol to report the // test as having failed. const internal::ScopedPrematureExitFile premature_exit_file( in_death_test_child_process ? NULL : internal::posix::GetEnv("TEST_PREMATURE_EXIT_FILE")); // Captures the value of GTEST_FLAG(catch_exceptions). This value will be // used for the duration of the program. impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions)); #if GTEST_HAS_SEH // Either the user wants Google Test to catch exceptions thrown by the // tests or this is executing in the context of death test child // process. In either case the user does not want to see pop-up dialogs // about crashes - they are expected. if (impl()->catch_exceptions() || in_death_test_child_process) { # if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT // SetErrorMode doesn't exist on CE. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); # endif // !GTEST_OS_WINDOWS_MOBILE # if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE // Death test children can be terminated with _abort(). On Windows, // _abort() can show a dialog with a warning message. This forces the // abort message to go to stderr instead. _set_error_mode(_OUT_TO_STDERR); # endif # if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE // In the debug version, Visual Studio pops up a separate dialog // offering a choice to debug the aborted program. We need to suppress // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement // executed. Google Test will notify the user of any unexpected // failure via stderr. // // VC++ doesn't define _set_abort_behavior() prior to the version 8.0. // Users of prior VC versions shall suffer the agony and pain of // clicking through the countless debug dialogs. // TODO(vladl@google.com): find a way to suppress the abort dialog() in the // debug mode when compiled with VC 7.1 or lower. if (!GTEST_FLAG(break_on_failure)) _set_abort_behavior( 0x0, // Clear the following flags: _WRITE_ABORT_MSG | _CALL_REPORTFAULT); // pop-up window, core dump. # endif } #endif // GTEST_HAS_SEH return internal::HandleExceptionsInMethodIfSupported( impl(), &internal::UnitTestImpl::RunAllTests, "auxiliary test code (environments or event listeners)") ? 0 : 1; } // Returns the working directory when the first TEST() or TEST_F() was // executed. const char* UnitTest::original_working_dir() const { return impl_->original_working_dir_.c_str(); } // Returns the TestCase object for the test that's currently running, // or NULL if no test is running. const TestCase* UnitTest::current_test_case() const GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); return impl_->current_test_case(); } // Returns the TestInfo object for the test that's currently running, // or NULL if no test is running. const TestInfo* UnitTest::current_test_info() const GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); return impl_->current_test_info(); } // Returns the random seed used at the start of the current test run. int UnitTest::random_seed() const { return impl_->random_seed(); } #if GTEST_HAS_PARAM_TEST // Returns ParameterizedTestCaseRegistry object used to keep track of // value-parameterized tests and instantiate and register them. internal::ParameterizedTestCaseRegistry& UnitTest::parameterized_test_registry() GTEST_LOCK_EXCLUDED_(mutex_) { return impl_->parameterized_test_registry(); } #endif // GTEST_HAS_PARAM_TEST // Creates an empty UnitTest. UnitTest::UnitTest() { impl_ = new internal::UnitTestImpl(this); } // Destructor of UnitTest. UnitTest::~UnitTest() { delete impl_; } // Pushes a trace defined by SCOPED_TRACE() on to the per-thread // Google Test trace stack. void UnitTest::PushGTestTrace(const internal::TraceInfo& trace) GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); impl_->gtest_trace_stack().push_back(trace); } // Pops a trace from the per-thread Google Test trace stack. void UnitTest::PopGTestTrace() GTEST_LOCK_EXCLUDED_(mutex_) { internal::MutexLock lock(&mutex_); impl_->gtest_trace_stack().pop_back(); } namespace internal { UnitTestImpl::UnitTestImpl(UnitTest* parent) : parent_(parent), GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */) default_global_test_part_result_reporter_(this), default_per_thread_test_part_result_reporter_(this), GTEST_DISABLE_MSC_WARNINGS_POP_() global_test_part_result_repoter_( &default_global_test_part_result_reporter_), per_thread_test_part_result_reporter_( &default_per_thread_test_part_result_reporter_), #if GTEST_HAS_PARAM_TEST parameterized_test_registry_(), parameterized_tests_registered_(false), #endif // GTEST_HAS_PARAM_TEST last_death_test_case_(-1), current_test_case_(NULL), current_test_info_(NULL), ad_hoc_test_result_(), os_stack_trace_getter_(NULL), post_flag_parse_init_performed_(false), random_seed_(0), // Will be overridden by the flag before first use. random_(0), // Will be reseeded before first use. start_timestamp_(0), elapsed_time_(0), #if GTEST_HAS_DEATH_TEST death_test_factory_(new DefaultDeathTestFactory), #endif // Will be overridden by the flag before first use. catch_exceptions_(false) { listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter); } UnitTestImpl::~UnitTestImpl() { // Deletes every TestCase. ForEach(test_cases_, internal::Delete<TestCase>); // Deletes every Environment. ForEach(environments_, internal::Delete<Environment>); delete os_stack_trace_getter_; } // Adds a TestProperty to the current TestResult object when invoked in a // context of a test, to current test case's ad_hoc_test_result when invoke // from SetUpTestCase/TearDownTestCase, or to the global property set // otherwise. If the result already contains a property with the same key, // the value will be updated. void UnitTestImpl::RecordProperty(const TestProperty& test_property) { std::string xml_element; TestResult* test_result; // TestResult appropriate for property recording. if (current_test_info_ != NULL) { xml_element = "testcase"; test_result = &(current_test_info_->result_); } else if (current_test_case_ != NULL) { xml_element = "testsuite"; test_result = &(current_test_case_->ad_hoc_test_result_); } else { xml_element = "testsuites"; test_result = &ad_hoc_test_result_; } test_result->RecordProperty(xml_element, test_property); } #if GTEST_HAS_DEATH_TEST // Disables event forwarding if the control is currently in a death test // subprocess. Must not be called before InitGoogleTest. void UnitTestImpl::SuppressTestEventsIfInSubprocess() { if (internal_run_death_test_flag_.get() != NULL) listeners()->SuppressEventForwarding(); } #endif // GTEST_HAS_DEATH_TEST // Initializes event listeners performing XML output as specified by // UnitTestOptions. Must not be called before InitGoogleTest. void UnitTestImpl::ConfigureXmlOutput() { const std::string& output_format = UnitTestOptions::GetOutputFormat(); if (output_format == "xml") { listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter( UnitTestOptions::GetAbsolutePathToOutputFile().c_str())); } else if (output_format != "") { printf("WARNING: unrecognized output format \"%s\" ignored.\n", output_format.c_str()); fflush(stdout); } } #if GTEST_CAN_STREAM_RESULTS_ // Initializes event listeners for streaming test results in string form. // Must not be called before InitGoogleTest. void UnitTestImpl::ConfigureStreamingOutput() { const std::string& target = GTEST_FLAG(stream_result_to); if (!target.empty()) { const size_t pos = target.find(':'); if (pos != std::string::npos) { listeners()->Append(new StreamingListener(target.substr(0, pos), target.substr(pos+1))); } else { printf("WARNING: unrecognized streaming target \"%s\" ignored.\n", target.c_str()); fflush(stdout); } } } #endif // GTEST_CAN_STREAM_RESULTS_ // Performs initialization dependent upon flag values obtained in // ParseGoogleTestFlagsOnly. Is called from InitGoogleTest after the call to // ParseGoogleTestFlagsOnly. In case a user neglects to call InitGoogleTest // this function is also called from RunAllTests. Since this function can be // called more than once, it has to be idempotent. void UnitTestImpl::PostFlagParsingInit() { // Ensures that this function does not execute more than once. if (!post_flag_parse_init_performed_) { post_flag_parse_init_performed_ = true; #if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) // Register to send notifications about key process state changes. listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_()); #endif // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_) #if GTEST_HAS_DEATH_TEST InitDeathTestSubprocessControlInfo(); SuppressTestEventsIfInSubprocess(); #endif // GTEST_HAS_DEATH_TEST // Registers parameterized tests. This makes parameterized tests // available to the UnitTest reflection API without running // RUN_ALL_TESTS. RegisterParameterizedTests(); // Configures listeners for XML output. This makes it possible for users // to shut down the default XML output before invoking RUN_ALL_TESTS. ConfigureXmlOutput(); #if GTEST_CAN_STREAM_RESULTS_ // Configures listeners for streaming test results to the specified server. ConfigureStreamingOutput(); #endif // GTEST_CAN_STREAM_RESULTS_ } } // A predicate that checks the name of a TestCase against a known // value. // // This is used for implementation of the UnitTest class only. We put // it in the anonymous namespace to prevent polluting the outer // namespace. // // TestCaseNameIs is copyable. class TestCaseNameIs { public: // Constructor. explicit TestCaseNameIs(const std::string& name) : name_(name) {} // Returns true iff the name of test_case matches name_. bool operator()(const TestCase* test_case) const { return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0; } private: std::string name_; }; // Finds and returns a TestCase with the given name. If one doesn't // exist, creates one and returns it. It's the CALLER'S // RESPONSIBILITY to ensure that this function is only called WHEN THE // TESTS ARE NOT SHUFFLED. // // Arguments: // // test_case_name: name of the test case // type_param: the name of the test case's type parameter, or NULL if // this is not a typed or a type-parameterized test case. // set_up_tc: pointer to the function that sets up the test case // tear_down_tc: pointer to the function that tears down the test case TestCase* UnitTestImpl::GetTestCase(const char* test_case_name, const char* type_param, Test::SetUpTestCaseFunc set_up_tc, Test::TearDownTestCaseFunc tear_down_tc) { // Can we find a TestCase with the given name? const std::vector<TestCase*>::const_iterator test_case = std::find_if(test_cases_.begin(), test_cases_.end(), TestCaseNameIs(test_case_name)); if (test_case != test_cases_.end()) return *test_case; // No. Let's create one. TestCase* const new_test_case = new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc); // Is this a death test case? if (internal::UnitTestOptions::MatchesFilter(test_case_name, kDeathTestCaseFilter)) { // Yes. Inserts the test case after the last death test case // defined so far. This only works when the test cases haven't // been shuffled. Otherwise we may end up running a death test // after a non-death test. ++last_death_test_case_; test_cases_.insert(test_cases_.begin() + last_death_test_case_, new_test_case); } else { // No. Appends to the end of the list. test_cases_.push_back(new_test_case); } test_case_indices_.push_back(static_cast<int>(test_case_indices_.size())); return new_test_case; } // Helpers for setting up / tearing down the given environment. They // are for use in the ForEach() function. static void SetUpEnvironment(Environment* env) { env->SetUp(); } static void TearDownEnvironment(Environment* env) { env->TearDown(); } // Runs all tests in this UnitTest object, prints the result, and // returns true if all tests are successful. If any exception is // thrown during a test, the test is considered to be failed, but the // rest of the tests will still be run. // // When parameterized tests are enabled, it expands and registers // parameterized tests first in RegisterParameterizedTests(). // All other functions called from RunAllTests() may safely assume that // parameterized tests are ready to be counted and run. bool UnitTestImpl::RunAllTests() { // Makes sure InitGoogleTest() was called. if (!GTestIsInitialized()) { printf("%s", "\nThis test program did NOT call ::testing::InitGoogleTest " "before calling RUN_ALL_TESTS(). Please fix it.\n"); return false; } // Do not run any test if the --help flag was specified. if (g_help_flag) return true; // Repeats the call to the post-flag parsing initialization in case the // user didn't call InitGoogleTest. PostFlagParsingInit(); // Even if sharding is not on, test runners may want to use the // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding // protocol. internal::WriteToShardStatusFileIfNeeded(); // True iff we are in a subprocess for running a thread-safe-style // death test. bool in_subprocess_for_death_test = false; #if GTEST_HAS_DEATH_TEST in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL); # if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) if (in_subprocess_for_death_test) { GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_(); } # endif // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_) #endif // GTEST_HAS_DEATH_TEST const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex, in_subprocess_for_death_test); // Compares the full test names with the filter to decide which // tests to run. const bool has_tests_to_run = FilterTests(should_shard ? HONOR_SHARDING_PROTOCOL : IGNORE_SHARDING_PROTOCOL) > 0; // Lists the tests and exits if the --gtest_list_tests flag was specified. if (GTEST_FLAG(list_tests)) { // This must be called *after* FilterTests() has been called. ListTestsMatchingFilter(); return true; } random_seed_ = GTEST_FLAG(shuffle) ? GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0; // True iff at least one test has failed. bool failed = false; TestEventListener* repeater = listeners()->repeater(); start_timestamp_ = GetTimeInMillis(); repeater->OnTestProgramStart(*parent_); // How many times to repeat the tests? We don't want to repeat them // when we are inside the subprocess of a death test. const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat); // Repeats forever if the repeat count is negative. const bool forever = repeat < 0; for (int i = 0; forever || i != repeat; i++) { // We want to preserve failures generated by ad-hoc test // assertions executed before RUN_ALL_TESTS(). ClearNonAdHocTestResult(); const TimeInMillis start = GetTimeInMillis(); // Shuffles test cases and tests if requested. if (has_tests_to_run && GTEST_FLAG(shuffle)) { random()->Reseed(random_seed_); // This should be done before calling OnTestIterationStart(), // such that a test event listener can see the actual test order // in the event. ShuffleTests(); } // Tells the unit test event listeners that the tests are about to start. repeater->OnTestIterationStart(*parent_, i); // Runs each test case if there is at least one test to run. if (has_tests_to_run) { // Sets up all environments beforehand. repeater->OnEnvironmentsSetUpStart(*parent_); ForEach(environments_, SetUpEnvironment); repeater->OnEnvironmentsSetUpEnd(*parent_); // Runs the tests only if there was no fatal failure during global // set-up. if (!Test::HasFatalFailure()) { for (int test_index = 0; test_index < total_test_case_count(); test_index++) { GetMutableTestCase(test_index)->Run(); } } // Tears down all environments in reverse order afterwards. repeater->OnEnvironmentsTearDownStart(*parent_); std::for_each(environments_.rbegin(), environments_.rend(), TearDownEnvironment); repeater->OnEnvironmentsTearDownEnd(*parent_); } elapsed_time_ = GetTimeInMillis() - start; // Tells the unit test event listener that the tests have just finished. repeater->OnTestIterationEnd(*parent_, i); // Gets the result and clears it. if (!Passed()) { failed = true; } // Restores the original test order after the iteration. This // allows the user to quickly repro a failure that happens in the // N-th iteration without repeating the first (N - 1) iterations. // This is not enclosed in "if (GTEST_FLAG(shuffle)) { ... }", in // case the user somehow changes the value of the flag somewhere // (it's always safe to unshuffle the tests). UnshuffleTests(); if (GTEST_FLAG(shuffle)) { // Picks a new random seed for each iteration. random_seed_ = GetNextRandomSeed(random_seed_); } } repeater->OnTestProgramEnd(*parent_); return !failed; } // Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file // if the variable is present. If a file already exists at this location, this // function will write over it. If the variable is present, but the file cannot // be created, prints an error and exits. void WriteToShardStatusFileIfNeeded() { const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile); if (test_shard_file != NULL) { FILE* const file = posix::FOpen(test_shard_file, "w"); if (file == NULL) { ColoredPrintf(COLOR_RED, "Could not write to the test shard status file \"%s\" " "specified by the %s environment variable.\n", test_shard_file, kTestShardStatusFile); fflush(stdout); exit(EXIT_FAILURE); } fclose(file); } } // Checks whether sharding is enabled by examining the relevant // environment variable values. If the variables are present, // but inconsistent (i.e., shard_index >= total_shards), prints // an error and exits. If in_subprocess_for_death_test, sharding is // disabled because it must only be applied to the original test // process. Otherwise, we could filter out death tests we intended to execute. bool ShouldShard(const char* total_shards_env, const char* shard_index_env, bool in_subprocess_for_death_test) { if (in_subprocess_for_death_test) { return false; } const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1); const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1); if (total_shards == -1 && shard_index == -1) { return false; } else if (total_shards == -1 && shard_index != -1) { const Message msg = Message() << "Invalid environment variables: you have " << kTestShardIndex << " = " << shard_index << ", but have left " << kTestTotalShards << " unset.\n"; ColoredPrintf(COLOR_RED, msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (total_shards != -1 && shard_index == -1) { const Message msg = Message() << "Invalid environment variables: you have " << kTestTotalShards << " = " << total_shards << ", but have left " << kTestShardIndex << " unset.\n"; ColoredPrintf(COLOR_RED, msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } else if (shard_index < 0 || shard_index >= total_shards) { const Message msg = Message() << "Invalid environment variables: we require 0 <= " << kTestShardIndex << " < " << kTestTotalShards << ", but you have " << kTestShardIndex << "=" << shard_index << ", " << kTestTotalShards << "=" << total_shards << ".\n"; ColoredPrintf(COLOR_RED, msg.GetString().c_str()); fflush(stdout); exit(EXIT_FAILURE); } return total_shards > 1; } // Parses the environment variable var as an Int32. If it is unset, // returns default_val. If it is not an Int32, prints an error // and aborts. Int32 Int32FromEnvOrDie(const char* var, Int32 default_val) { const char* str_val = posix::GetEnv(var); if (str_val == NULL) { return default_val; } Int32 result; if (!ParseInt32(Message() << "The value of environment variable " << var, str_val, &result)) { exit(EXIT_FAILURE); } return result; } // Given the total number of shards, the shard index, and the test id, // returns true iff the test should be run on this shard. The test id is // some arbitrary but unique non-negative integer assigned to each test // method. Assumes that 0 <= shard_index < total_shards. bool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) { return (test_id % total_shards) == shard_index; } // Compares the name of each test with the user-specified filter to // decide whether the test should be run, then records the result in // each TestCase and TestInfo object. // If shard_tests == true, further filters tests based on sharding // variables in the environment - see // http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide. // Returns the number of tests that should run. int UnitTestImpl::FilterTests(ReactionToSharding shard_tests) { const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ? Int32FromEnvOrDie(kTestTotalShards, -1) : -1; const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ? Int32FromEnvOrDie(kTestShardIndex, -1) : -1; // num_runnable_tests are the number of tests that will // run across all shards (i.e., match filter and are not disabled). // num_selected_tests are the number of tests to be run on // this shard. int num_runnable_tests = 0; int num_selected_tests = 0; for (size_t i = 0; i < test_cases_.size(); i++) { TestCase* const test_case = test_cases_[i]; const std::string &test_case_name = test_case->name(); test_case->set_should_run(false); for (size_t j = 0; j < test_case->test_info_list().size(); j++) { TestInfo* const test_info = test_case->test_info_list()[j]; const std::string test_name(test_info->name()); // A test is disabled if test case name or test name matches // kDisableTestFilter. const bool is_disabled = internal::UnitTestOptions::MatchesFilter(test_case_name, kDisableTestFilter) || internal::UnitTestOptions::MatchesFilter(test_name, kDisableTestFilter); test_info->is_disabled_ = is_disabled; const bool matches_filter = internal::UnitTestOptions::FilterMatchesTest(test_case_name, test_name); test_info->matches_filter_ = matches_filter; const bool is_runnable = (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) && matches_filter; const bool is_selected = is_runnable && (shard_tests == IGNORE_SHARDING_PROTOCOL || ShouldRunTestOnShard(total_shards, shard_index, num_runnable_tests)); num_runnable_tests += is_runnable; num_selected_tests += is_selected; test_info->should_run_ = is_selected; test_case->set_should_run(test_case->should_run() || is_selected); } } return num_selected_tests; } // Prints the given C-string on a single line by replacing all '\n' // characters with string "\\n". If the output takes more than // max_length characters, only prints the first max_length characters // and "...". static void PrintOnOneLine(const char* str, int max_length) { if (str != NULL) { for (int i = 0; *str != '\0'; ++str) { if (i >= max_length) { printf("..."); break; } if (*str == '\n') { printf("\\n"); i += 2; } else { printf("%c", *str); ++i; } } } } // Prints the names of the tests matching the user-specified filter flag. void UnitTestImpl::ListTestsMatchingFilter() { // Print at most this many characters for each type/value parameter. const int kMaxParamLength = 250; for (size_t i = 0; i < test_cases_.size(); i++) { const TestCase* const test_case = test_cases_[i]; bool printed_test_case_name = false; for (size_t j = 0; j < test_case->test_info_list().size(); j++) { const TestInfo* const test_info = test_case->test_info_list()[j]; if (test_info->matches_filter_) { if (!printed_test_case_name) { printed_test_case_name = true; printf("%s.", test_case->name()); if (test_case->type_param() != NULL) { printf(" # %s = ", kTypeParamLabel); // We print the type parameter on a single line to make // the output easy to parse by a program. PrintOnOneLine(test_case->type_param(), kMaxParamLength); } printf("\n"); } printf(" %s", test_info->name()); if (test_info->value_param() != NULL) { printf(" # %s = ", kValueParamLabel); // We print the value parameter on a single line to make the // output easy to parse by a program. PrintOnOneLine(test_info->value_param(), kMaxParamLength); } printf("\n"); } } } fflush(stdout); } // Sets the OS stack trace getter. // // Does nothing if the input and the current OS stack trace getter are // the same; otherwise, deletes the old getter and makes the input the // current getter. void UnitTestImpl::set_os_stack_trace_getter( OsStackTraceGetterInterface* getter) { if (os_stack_trace_getter_ != getter) { delete os_stack_trace_getter_; os_stack_trace_getter_ = getter; } } // Returns the current OS stack trace getter if it is not NULL; // otherwise, creates an OsStackTraceGetter, makes it the current // getter, and returns it. OsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() { if (os_stack_trace_getter_ == NULL) { #ifdef GTEST_OS_STACK_TRACE_GETTER_ os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_; #else os_stack_trace_getter_ = new OsStackTraceGetter; #endif // GTEST_OS_STACK_TRACE_GETTER_ } return os_stack_trace_getter_; } // Returns the TestResult for the test that's currently running, or // the TestResult for the ad hoc test if no test is running. TestResult* UnitTestImpl::current_test_result() { return current_test_info_ ? &(current_test_info_->result_) : &ad_hoc_test_result_; } // Shuffles all test cases, and the tests within each test case, // making sure that death tests are still run first. void UnitTestImpl::ShuffleTests() { // Shuffles the death test cases. ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_); // Shuffles the non-death test cases. ShuffleRange(random(), last_death_test_case_ + 1, static_cast<int>(test_cases_.size()), &test_case_indices_); // Shuffles the tests inside each test case. for (size_t i = 0; i < test_cases_.size(); i++) { test_cases_[i]->ShuffleTests(random()); } } // Restores the test cases and tests to their order before the first shuffle. void UnitTestImpl::UnshuffleTests() { for (size_t i = 0; i < test_cases_.size(); i++) { // Unshuffles the tests in each test case. test_cases_[i]->UnshuffleTests(); // Resets the index of each test case. test_case_indices_[i] = static_cast<int>(i); } } // Returns the current OS stack trace as an std::string. // // The maximum number of stack frames to be included is specified by // the gtest_stack_trace_depth flag. The skip_count parameter // specifies the number of top frames to be skipped, which doesn't // count against the number of frames to be included. // // For example, if Foo() calls Bar(), which in turn calls // GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in // the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't. std::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/, int skip_count) { // We pass skip_count + 1 to skip this wrapper function in addition // to what the user really wants to skip. return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1); } // Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to // suppress unreachable code warnings. namespace { class ClassUniqueToAlwaysTrue {}; } bool IsTrue(bool condition) { return condition; } bool AlwaysTrue() { #if GTEST_HAS_EXCEPTIONS // This condition is always false so AlwaysTrue() never actually throws, // but it makes the compiler think that it may throw. if (IsTrue(false)) throw ClassUniqueToAlwaysTrue(); #endif // GTEST_HAS_EXCEPTIONS return true; } // If *pstr starts with the given prefix, modifies *pstr to be right // past the prefix and returns true; otherwise leaves *pstr unchanged // and returns false. None of pstr, *pstr, and prefix can be NULL. bool SkipPrefix(const char* prefix, const char** pstr) { const size_t prefix_len = strlen(prefix); if (strncmp(*pstr, prefix, prefix_len) == 0) { *pstr += prefix_len; return true; } return false; } // Parses a string as a command line flag. The string should have // the format "--flag=value". When def_optional is true, the "=value" // part can be omitted. // // Returns the value of the flag, or NULL if the parsing failed. const char* ParseFlagValue(const char* str, const char* flag, bool def_optional) { // str and flag must not be NULL. if (str == NULL || flag == NULL) return NULL; // The flag must start with "--" followed by GTEST_FLAG_PREFIX_. const std::string flag_str = std::string("--") + GTEST_FLAG_PREFIX_ + flag; const size_t flag_len = flag_str.length(); if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL; // Skips the flag name. const char* flag_end = str + flag_len; // When def_optional is true, it's OK to not have a "=value" part. if (def_optional && (flag_end[0] == '\0')) { return flag_end; } // If def_optional is true and there are more characters after the // flag name, or if def_optional is false, there must be a '=' after // the flag name. if (flag_end[0] != '=') return NULL; // Returns the string after "=". return flag_end + 1; } // Parses a string for a bool flag, in the form of either // "--flag=value" or "--flag". // // In the former case, the value is taken as true as long as it does // not start with '0', 'f', or 'F'. // // In the latter case, the value is taken as true. // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. bool ParseBoolFlag(const char* str, const char* flag, bool* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, true); // Aborts if the parsing failed. if (value_str == NULL) return false; // Converts the string value to a bool. *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F'); return true; } // Parses a string for an Int32 flag, in the form of // "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. bool ParseInt32Flag(const char* str, const char* flag, Int32* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, false); // Aborts if the parsing failed. if (value_str == NULL) return false; // Sets *value to the value of the flag. return ParseInt32(Message() << "The value of flag --" << flag, value_str, value); } // Parses a string for a string flag, in the form of // "--flag=value". // // On success, stores the value of the flag in *value, and returns // true. On failure, returns false without changing *value. bool ParseStringFlag(const char* str, const char* flag, std::string* value) { // Gets the value of the flag as a string. const char* const value_str = ParseFlagValue(str, flag, false); // Aborts if the parsing failed. if (value_str == NULL) return false; // Sets *value to the value of the flag. *value = value_str; return true; } // Determines whether a string has a prefix that Google Test uses for its // flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_. // If Google Test detects that a command line flag has its prefix but is not // recognized, it will print its help message. Flags starting with // GTEST_INTERNAL_PREFIX_ followed by "internal_" are considered Google Test // internal flags and do not trigger the help message. static bool HasGoogleTestFlagPrefix(const char* str) { return (SkipPrefix("--", &str) || SkipPrefix("-", &str) || SkipPrefix("/", &str)) && !SkipPrefix(GTEST_FLAG_PREFIX_ "internal_", &str) && (SkipPrefix(GTEST_FLAG_PREFIX_, &str) || SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str)); } // Prints a string containing code-encoded text. The following escape // sequences can be used in the string to control the text color: // // @@ prints a single '@' character. // @R changes the color to red. // @G changes the color to green. // @Y changes the color to yellow. // @D changes to the default terminal text color. // // TODO(wan@google.com): Write tests for this once we add stdout // capturing to Google Test. static void PrintColorEncoded(const char* str) { GTestColor color = COLOR_DEFAULT; // The current color. // Conceptually, we split the string into segments divided by escape // sequences. Then we print one segment at a time. At the end of // each iteration, the str pointer advances to the beginning of the // next segment. for (;;) { const char* p = strchr(str, '@'); if (p == NULL) { ColoredPrintf(color, "%s", str); return; } ColoredPrintf(color, "%s", std::string(str, p).c_str()); const char ch = p[1]; str = p + 2; if (ch == '@') { ColoredPrintf(color, "@"); } else if (ch == 'D') { color = COLOR_DEFAULT; } else if (ch == 'R') { color = COLOR_RED; } else if (ch == 'G') { color = COLOR_GREEN; } else if (ch == 'Y') { color = COLOR_YELLOW; } else { --str; } } } static const char kColorEncodedHelpMessage[] = "This program contains tests written using " GTEST_NAME_ ". You can use the\n" "following command line flags to control its behavior:\n" "\n" "Test Selection:\n" " @G--" GTEST_FLAG_PREFIX_ "list_tests@D\n" " List the names of all tests instead of running them. The name of\n" " TEST(Foo, Bar) is \"Foo.Bar\".\n" " @G--" GTEST_FLAG_PREFIX_ "filter=@YPOSTIVE_PATTERNS" "[@G-@YNEGATIVE_PATTERNS]@D\n" " Run only the tests whose name matches one of the positive patterns but\n" " none of the negative patterns. '?' matches any single character; '*'\n" " matches any substring; ':' separates two patterns.\n" " @G--" GTEST_FLAG_PREFIX_ "also_run_disabled_tests@D\n" " Run all disabled tests too.\n" "\n" "Test Execution:\n" " @G--" GTEST_FLAG_PREFIX_ "repeat=@Y[COUNT]@D\n" " Run the tests repeatedly; use a negative count to repeat forever.\n" " @G--" GTEST_FLAG_PREFIX_ "shuffle@D\n" " Randomize tests' orders on every iteration.\n" " @G--" GTEST_FLAG_PREFIX_ "random_seed=@Y[NUMBER]@D\n" " Random number seed to use for shuffling test orders (between 1 and\n" " 99999, or 0 to use a seed based on the current time).\n" "\n" "Test Output:\n" " @G--" GTEST_FLAG_PREFIX_ "color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\n" " Enable/disable colored output. The default is @Gauto@D.\n" " -@G-" GTEST_FLAG_PREFIX_ "print_time=0@D\n" " Don't print the elapsed time of each test.\n" " @G--" GTEST_FLAG_PREFIX_ "output=xml@Y[@G:@YDIRECTORY_PATH@G" GTEST_PATH_SEP_ "@Y|@G:@YFILE_PATH]@D\n" " Generate an XML report in the given directory or with the given file\n" " name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\n" #if GTEST_CAN_STREAM_RESULTS_ " @G--" GTEST_FLAG_PREFIX_ "stream_result_to=@YHOST@G:@YPORT@D\n" " Stream test results to the given server.\n" #endif // GTEST_CAN_STREAM_RESULTS_ "\n" "Assertion Behavior:\n" #if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS " @G--" GTEST_FLAG_PREFIX_ "death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\n" " Set the default death test style.\n" #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS " @G--" GTEST_FLAG_PREFIX_ "break_on_failure@D\n" " Turn assertion failures into debugger break-points.\n" " @G--" GTEST_FLAG_PREFIX_ "throw_on_failure@D\n" " Turn assertion failures into C++ exceptions.\n" " @G--" GTEST_FLAG_PREFIX_ "catch_exceptions=0@D\n" " Do not report exceptions as test failures. Instead, allow them\n" " to crash the program or throw a pop-up (on Windows).\n" "\n" "Except for @G--" GTEST_FLAG_PREFIX_ "list_tests@D, you can alternatively set " "the corresponding\n" "environment variable of a flag (all letters in upper-case). For example, to\n" "disable colored text output, you can either specify @G--" GTEST_FLAG_PREFIX_ "color=no@D or set\n" "the @G" GTEST_FLAG_PREFIX_UPPER_ "COLOR@D environment variable to @Gno@D.\n" "\n" "For more information, please read the " GTEST_NAME_ " documentation at\n" "@G" GTEST_PROJECT_URL_ "@D. If you find a bug in " GTEST_NAME_ "\n" "(not one in your own code or tests), please report it to\n" "@G<" GTEST_DEV_EMAIL_ ">@D.\n"; bool ParseGoogleTestFlag(const char* const arg) { return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag, &GTEST_FLAG(also_run_disabled_tests)) || ParseBoolFlag(arg, kBreakOnFailureFlag, &GTEST_FLAG(break_on_failure)) || ParseBoolFlag(arg, kCatchExceptionsFlag, &GTEST_FLAG(catch_exceptions)) || ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) || ParseStringFlag(arg, kDeathTestStyleFlag, &GTEST_FLAG(death_test_style)) || ParseBoolFlag(arg, kDeathTestUseFork, &GTEST_FLAG(death_test_use_fork)) || ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) || ParseStringFlag(arg, kInternalRunDeathTestFlag, &GTEST_FLAG(internal_run_death_test)) || ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) || ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) || ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) || ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) || ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) || ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) || ParseInt32Flag(arg, kStackTraceDepthFlag, &GTEST_FLAG(stack_trace_depth)) || ParseStringFlag(arg, kStreamResultToFlag, &GTEST_FLAG(stream_result_to)) || ParseBoolFlag(arg, kThrowOnFailureFlag, &GTEST_FLAG(throw_on_failure)); } #if GTEST_USE_OWN_FLAGFILE_FLAG_ void LoadFlagsFromFile(const std::string& path) { FILE* flagfile = posix::FOpen(path.c_str(), "r"); if (!flagfile) { fprintf(stderr, "Unable to open file \"%s\"\n", GTEST_FLAG(flagfile).c_str()); fflush(stderr); exit(EXIT_FAILURE); } std::string contents(ReadEntireFile(flagfile)); posix::FClose(flagfile); std::vector<std::string> lines; SplitString(contents, '\n', &lines); for (size_t i = 0; i < lines.size(); ++i) { if (lines[i].empty()) continue; if (!ParseGoogleTestFlag(lines[i].c_str())) g_help_flag = true; } } #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ // Parses the command line for Google Test flags, without initializing // other parts of Google Test. The type parameter CharType can be // instantiated to either char or wchar_t. template <typename CharType> void ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) { for (int i = 1; i < *argc; i++) { const std::string arg_string = StreamableToString(argv[i]); const char* const arg = arg_string.c_str(); using internal::ParseBoolFlag; using internal::ParseInt32Flag; using internal::ParseStringFlag; bool remove_flag = false; if (ParseGoogleTestFlag(arg)) { remove_flag = true; #if GTEST_USE_OWN_FLAGFILE_FLAG_ } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) { LoadFlagsFromFile(GTEST_FLAG(flagfile)); remove_flag = true; #endif // GTEST_USE_OWN_FLAGFILE_FLAG_ } else if (arg_string == "--help" || arg_string == "-h" || arg_string == "-?" || arg_string == "/?" || HasGoogleTestFlagPrefix(arg)) { // Both help flag and unrecognized Google Test flags (excluding // internal ones) trigger help display. g_help_flag = true; } if (remove_flag) { // Shift the remainder of the argv list left by one. Note // that argv has (*argc + 1) elements, the last one always being // NULL. The following loop moves the trailing NULL element as // well. for (int j = i; j != *argc; j++) { argv[j] = argv[j + 1]; } // Decrements the argument count. (*argc)--; // We also need to decrement the iterator as we just removed // an element. i--; } } if (g_help_flag) { // We print the help here instead of in RUN_ALL_TESTS(), as the // latter may not be called at all if the user is using Google // Test with another testing framework. PrintColorEncoded(kColorEncodedHelpMessage); } } // Parses the command line for Google Test flags, without initializing // other parts of Google Test. void ParseGoogleTestFlagsOnly(int* argc, char** argv) { ParseGoogleTestFlagsOnlyImpl(argc, argv); } void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) { ParseGoogleTestFlagsOnlyImpl(argc, argv); } // The internal implementation of InitGoogleTest(). // // The type parameter CharType can be instantiated to either char or // wchar_t. template <typename CharType> void InitGoogleTestImpl(int* argc, CharType** argv) { // We don't want to run the initialization code twice. if (GTestIsInitialized()) return; if (*argc <= 0) return; g_argvs.clear(); for (int i = 0; i != *argc; i++) { g_argvs.push_back(StreamableToString(argv[i])); } ParseGoogleTestFlagsOnly(argc, argv); GetUnitTestImpl()->PostFlagParsingInit(); } } // namespace internal // Initializes Google Test. This must be called before calling // RUN_ALL_TESTS(). In particular, it parses a command line for the // flags that Google Test recognizes. Whenever a Google Test flag is // seen, it is removed from argv, and *argc is decremented. // // No value is returned. Instead, the Google Test flag variables are // updated. // // Calling the function for the second time has no user-visible effect. void InitGoogleTest(int* argc, char** argv) { #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) internal::InitGoogleTestImpl(argc, argv); #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) } // This overloaded version can be used in Windows programs compiled in // UNICODE mode. void InitGoogleTest(int* argc, wchar_t** argv) { #if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv); #else // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) internal::InitGoogleTestImpl(argc, argv); #endif // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_) } } // namespace testing // Copyright 2005, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev) // // This file implements death tests. #if GTEST_HAS_DEATH_TEST # if GTEST_OS_MAC # include <crt_externs.h> # endif // GTEST_OS_MAC # include <errno.h> # include <fcntl.h> # include <limits.h> # if GTEST_OS_LINUX # include <signal.h> # endif // GTEST_OS_LINUX # include <stdarg.h> # if GTEST_OS_WINDOWS # include <windows.h> # else # include <sys/mman.h> # include <sys/wait.h> # endif // GTEST_OS_WINDOWS # if GTEST_OS_QNX # include <spawn.h> # endif // GTEST_OS_QNX #endif // GTEST_HAS_DEATH_TEST // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick exists to // prevent the accidental inclusion of gtest-internal-inl.h in the // user's code. #define GTEST_IMPLEMENTATION_ 1 #undef GTEST_IMPLEMENTATION_ namespace testing { // Constants. // The default death test style. static const char kDefaultDeathTestStyle[] = "fast"; GTEST_DEFINE_string_( death_test_style, internal::StringFromGTestEnv("death_test_style", kDefaultDeathTestStyle), "Indicates how to run a death test in a forked child process: " "\"threadsafe\" (child process re-executes the test binary " "from the beginning, running only the specific death test) or " "\"fast\" (child process runs the death test immediately " "after forking)."); GTEST_DEFINE_bool_( death_test_use_fork, internal::BoolFromGTestEnv("death_test_use_fork", false), "Instructs to use fork()/_exit() instead of clone() in death tests. " "Ignored and always uses fork() on POSIX systems where clone() is not " "implemented. Useful when running under valgrind or similar tools if " "those do not support clone(). Valgrind 3.3.1 will just fail if " "it sees an unsupported combination of clone() flags. " "It is not recommended to use this flag w/o valgrind though it will " "work in 99% of the cases. Once valgrind is fixed, this flag will " "most likely be removed."); namespace internal { GTEST_DEFINE_string_( internal_run_death_test, "", "Indicates the file, line number, temporal index of " "the single death test to run, and a file descriptor to " "which a success code may be sent, all separated by " "the '|' characters. This flag is specified if and only if the current " "process is a sub-process launched for running a thread-safe " "death test. FOR INTERNAL USE ONLY."); } // namespace internal #if GTEST_HAS_DEATH_TEST namespace internal { // Valid only for fast death tests. Indicates the code is running in the // child process of a fast style death test. # if !GTEST_OS_WINDOWS static bool g_in_fast_death_test_child = false; # endif // Returns a Boolean value indicating whether the caller is currently // executing in the context of the death test child process. Tools such as // Valgrind heap checkers may need this to modify their behavior in death // tests. IMPORTANT: This is an internal utility. Using it may break the // implementation of death tests. User code MUST NOT use it. bool InDeathTestChild() { # if GTEST_OS_WINDOWS // On Windows, death tests are thread-safe regardless of the value of the // death_test_style flag. return !GTEST_FLAG(internal_run_death_test).empty(); # else if (GTEST_FLAG(death_test_style) == "threadsafe") return !GTEST_FLAG(internal_run_death_test).empty(); else return g_in_fast_death_test_child; #endif } } // namespace internal // ExitedWithCode constructor. ExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) { } // ExitedWithCode function-call operator. bool ExitedWithCode::operator()(int exit_status) const { # if GTEST_OS_WINDOWS return exit_status == exit_code_; # else return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_; # endif // GTEST_OS_WINDOWS } # if !GTEST_OS_WINDOWS // KilledBySignal constructor. KilledBySignal::KilledBySignal(int signum) : signum_(signum) { } // KilledBySignal function-call operator. bool KilledBySignal::operator()(int exit_status) const { # if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) { bool result; if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) { return result; } } # endif // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_) return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_; } # endif // !GTEST_OS_WINDOWS namespace internal { // Utilities needed for death tests. // Generates a textual description of a given exit code, in the format // specified by wait(2). static std::string ExitSummary(int exit_code) { Message m; # if GTEST_OS_WINDOWS m << "Exited with exit status " << exit_code; # else if (WIFEXITED(exit_code)) { m << "Exited with exit status " << WEXITSTATUS(exit_code); } else if (WIFSIGNALED(exit_code)) { m << "Terminated by signal " << WTERMSIG(exit_code); } # ifdef WCOREDUMP if (WCOREDUMP(exit_code)) { m << " (core dumped)"; } # endif # endif // GTEST_OS_WINDOWS return m.GetString(); } // Returns true if exit_status describes a process that was terminated // by a signal, or exited normally with a nonzero exit code. bool ExitedUnsuccessfully(int exit_status) { return !ExitedWithCode(0)(exit_status); } # if !GTEST_OS_WINDOWS // Generates a textual failure message when a death test finds more than // one thread running, or cannot determine the number of threads, prior // to executing the given statement. It is the responsibility of the // caller not to pass a thread_count of 1. static std::string DeathTestThreadWarning(size_t thread_count) { Message msg; msg << "Death tests use fork(), which is unsafe particularly" << " in a threaded context. For this test, " << GTEST_NAME_ << " "; if (thread_count == 0) msg << "couldn't detect the number of threads."; else msg << "detected " << thread_count << " threads."; return msg.GetString(); } # endif // !GTEST_OS_WINDOWS // Flag characters for reporting a death test that did not die. static const char kDeathTestLived = 'L'; static const char kDeathTestReturned = 'R'; static const char kDeathTestThrew = 'T'; static const char kDeathTestInternalError = 'I'; // An enumeration describing all of the possible ways that a death test can // conclude. DIED means that the process died while executing the test // code; LIVED means that process lived beyond the end of the test code; // RETURNED means that the test statement attempted to execute a return // statement, which is not allowed; THREW means that the test statement // returned control by throwing an exception. IN_PROGRESS means the test // has not yet concluded. // TODO(vladl@google.com): Unify names and possibly values for // AbortReason, DeathTestOutcome, and flag characters above. enum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW }; // Routine for aborting the program which is safe to call from an // exec-style death test child process, in which case the error // message is propagated back to the parent process. Otherwise, the // message is simply printed to stderr. In either case, the program // then exits with status 1. void DeathTestAbort(const std::string& message) { // On a POSIX system, this function may be called from a threadsafe-style // death test child process, which operates on a very small stack. Use // the heap for any additional non-minuscule memory requirements. const InternalRunDeathTestFlag* const flag = GetUnitTestImpl()->internal_run_death_test_flag(); if (flag != NULL) { FILE* parent = posix::FDOpen(flag->write_fd(), "w"); fputc(kDeathTestInternalError, parent); fprintf(parent, "%s", message.c_str()); fflush(parent); _exit(1); } else { fprintf(stderr, "%s", message.c_str()); fflush(stderr); posix::Abort(); } } // A replacement for CHECK that calls DeathTestAbort if the assertion // fails. # define GTEST_DEATH_TEST_CHECK_(expression) \ do { \ if (!::testing::internal::IsTrue(expression)) { \ DeathTestAbort( \ ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ + ::testing::internal::StreamableToString(__LINE__) + ": " \ + #expression); \ } \ } while (::testing::internal::AlwaysFalse()) // This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for // evaluating any system call that fulfills two conditions: it must return // -1 on failure, and set errno to EINTR when it is interrupted and // should be tried again. The macro expands to a loop that repeatedly // evaluates the expression as long as it evaluates to -1 and sets // errno to EINTR. If the expression evaluates to -1 but errno is // something other than EINTR, DeathTestAbort is called. # define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \ do { \ int gtest_retval; \ do { \ gtest_retval = (expression); \ } while (gtest_retval == -1 && errno == EINTR); \ if (gtest_retval == -1) { \ DeathTestAbort( \ ::std::string("CHECK failed: File ") + __FILE__ + ", line " \ + ::testing::internal::StreamableToString(__LINE__) + ": " \ + #expression + " != -1"); \ } \ } while (::testing::internal::AlwaysFalse()) // Returns the message describing the last system error in errno. std::string GetLastErrnoDescription() { return errno == 0 ? "" : posix::StrError(errno); } // This is called from a death test parent process to read a failure // message from the death test child process and log it with the FATAL // severity. On Windows, the message is read from a pipe handle. On other // platforms, it is read from a file descriptor. static void FailFromInternalError(int fd) { Message error; char buffer[256]; int num_read; do { while ((num_read = posix::Read(fd, buffer, 255)) > 0) { buffer[num_read] = '\0'; error << buffer; } } while (num_read == -1 && errno == EINTR); if (num_read == 0) { GTEST_LOG_(FATAL) << error.GetString(); } else { const int last_error = errno; GTEST_LOG_(FATAL) << "Error while reading death test internal: " << GetLastErrnoDescription() << " [" << last_error << "]"; } } // Death test constructor. Increments the running death test count // for the current test. DeathTest::DeathTest() { TestInfo* const info = GetUnitTestImpl()->current_test_info(); if (info == NULL) { DeathTestAbort("Cannot run a death test outside of a TEST or " "TEST_F construct"); } } // Creates and returns a death test by dispatching to the current // death test factory. bool DeathTest::Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test) { return GetUnitTestImpl()->death_test_factory()->Create( statement, regex, file, line, test); } const char* DeathTest::LastMessage() { return last_death_test_message_.c_str(); } void DeathTest::set_last_death_test_message(const std::string& message) { last_death_test_message_ = message; } std::string DeathTest::last_death_test_message_; // Provides cross platform implementation for some death functionality. class DeathTestImpl : public DeathTest { protected: DeathTestImpl(const char* a_statement, const RE* a_regex) : statement_(a_statement), regex_(a_regex), spawned_(false), status_(-1), outcome_(IN_PROGRESS), read_fd_(-1), write_fd_(-1) {} // read_fd_ is expected to be closed and cleared by a derived class. ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); } void Abort(AbortReason reason); virtual bool Passed(bool status_ok); const char* statement() const { return statement_; } const RE* regex() const { return regex_; } bool spawned() const { return spawned_; } void set_spawned(bool is_spawned) { spawned_ = is_spawned; } int status() const { return status_; } void set_status(int a_status) { status_ = a_status; } DeathTestOutcome outcome() const { return outcome_; } void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; } int read_fd() const { return read_fd_; } void set_read_fd(int fd) { read_fd_ = fd; } int write_fd() const { return write_fd_; } void set_write_fd(int fd) { write_fd_ = fd; } // Called in the parent process only. Reads the result code of the death // test child process via a pipe, interprets it to set the outcome_ // member, and closes read_fd_. Outputs diagnostics and terminates in // case of unexpected codes. void ReadAndInterpretStatusByte(); private: // The textual content of the code this object is testing. This class // doesn't own this string and should not attempt to delete it. const char* const statement_; // The regular expression which test output must match. DeathTestImpl // doesn't own this object and should not attempt to delete it. const RE* const regex_; // True if the death test child process has been successfully spawned. bool spawned_; // The exit status of the child process. int status_; // How the death test concluded. DeathTestOutcome outcome_; // Descriptor to the read end of the pipe to the child process. It is // always -1 in the child process. The child keeps its write end of the // pipe in write_fd_. int read_fd_; // Descriptor to the child's write end of the pipe to the parent process. // It is always -1 in the parent process. The parent keeps its end of the // pipe in read_fd_. int write_fd_; }; // Called in the parent process only. Reads the result code of the death // test child process via a pipe, interprets it to set the outcome_ // member, and closes read_fd_. Outputs diagnostics and terminates in // case of unexpected codes. void DeathTestImpl::ReadAndInterpretStatusByte() { char flag; int bytes_read; // The read() here blocks until data is available (signifying the // failure of the death test) or until the pipe is closed (signifying // its success), so it's okay to call this in the parent before // the child process has exited. do { bytes_read = posix::Read(read_fd(), &flag, 1); } while (bytes_read == -1 && errno == EINTR); if (bytes_read == 0) { set_outcome(DIED); } else if (bytes_read == 1) { switch (flag) { case kDeathTestReturned: set_outcome(RETURNED); break; case kDeathTestThrew: set_outcome(THREW); break; case kDeathTestLived: set_outcome(LIVED); break; case kDeathTestInternalError: FailFromInternalError(read_fd()); // Does not return. break; default: GTEST_LOG_(FATAL) << "Death test child process reported " << "unexpected status byte (" << static_cast<unsigned int>(flag) << ")"; } } else { GTEST_LOG_(FATAL) << "Read from death test child process failed: " << GetLastErrnoDescription(); } GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd())); set_read_fd(-1); } // Signals that the death test code which should have exited, didn't. // Should be called only in a death test child process. // Writes a status byte to the child's status file descriptor, then // calls _exit(1). void DeathTestImpl::Abort(AbortReason reason) { // The parent process considers the death test to be a failure if // it finds any data in our pipe. So, here we write a single flag byte // to the pipe, then exit. const char status_ch = reason == TEST_DID_NOT_DIE ? kDeathTestLived : reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned; GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1)); // We are leaking the descriptor here because on some platforms (i.e., // when built as Windows DLL), destructors of global objects will still // run after calling _exit(). On such systems, write_fd_ will be // indirectly closed from the destructor of UnitTestImpl, causing double // close if it is also closed here. On debug configurations, double close // may assert. As there are no in-process buffers to flush here, we are // relying on the OS to close the descriptor after the process terminates // when the destructors are not run. _exit(1); // Exits w/o any normal exit hooks (we were supposed to crash) } // Returns an indented copy of stderr output for a death test. // This makes distinguishing death test output lines from regular log lines // much easier. static ::std::string FormatDeathTestOutput(const ::std::string& output) { ::std::string ret; for (size_t at = 0; ; ) { const size_t line_end = output.find('\n', at); ret += "[ DEATH ] "; if (line_end == ::std::string::npos) { ret += output.substr(at); break; } ret += output.substr(at, line_end + 1 - at); at = line_end + 1; } return ret; } // Assesses the success or failure of a death test, using both private // members which have previously been set, and one argument: // // Private data members: // outcome: An enumeration describing how the death test // concluded: DIED, LIVED, THREW, or RETURNED. The death test // fails in the latter three cases. // status: The exit status of the child process. On *nix, it is in the // in the format specified by wait(2). On Windows, this is the // value supplied to the ExitProcess() API or a numeric code // of the exception that terminated the program. // regex: A regular expression object to be applied to // the test's captured standard error output; the death test // fails if it does not match. // // Argument: // status_ok: true if exit_status is acceptable in the context of // this particular death test, which fails if it is false // // Returns true iff all of the above conditions are met. Otherwise, the // first failing condition, in the order given above, is the one that is // reported. Also sets the last death test message string. bool DeathTestImpl::Passed(bool status_ok) { if (!spawned()) return false; const std::string error_message = GetCapturedStderr(); bool success = false; Message buffer; buffer << "Death test: " << statement() << "\n"; switch (outcome()) { case LIVED: buffer << " Result: failed to die.\n" << " Error msg:\n" << FormatDeathTestOutput(error_message); break; case THREW: buffer << " Result: threw an exception.\n" << " Error msg:\n" << FormatDeathTestOutput(error_message); break; case RETURNED: buffer << " Result: illegal return in test statement.\n" << " Error msg:\n" << FormatDeathTestOutput(error_message); break; case DIED: if (status_ok) { const bool matched = RE::PartialMatch(error_message.c_str(), *regex()); if (matched) { success = true; } else { buffer << " Result: died but not with expected error.\n" << " Expected: " << regex()->pattern() << "\n" << "Actual msg:\n" << FormatDeathTestOutput(error_message); } } else { buffer << " Result: died but not with expected exit code:\n" << " " << ExitSummary(status()) << "\n" << "Actual msg:\n" << FormatDeathTestOutput(error_message); } break; case IN_PROGRESS: default: GTEST_LOG_(FATAL) << "DeathTest::Passed somehow called before conclusion of test"; } DeathTest::set_last_death_test_message(buffer.GetString()); return success; } # if GTEST_OS_WINDOWS // WindowsDeathTest implements death tests on Windows. Due to the // specifics of starting new processes on Windows, death tests there are // always threadsafe, and Google Test considers the // --gtest_death_test_style=fast setting to be equivalent to // --gtest_death_test_style=threadsafe there. // // A few implementation notes: Like the Linux version, the Windows // implementation uses pipes for child-to-parent communication. But due to // the specifics of pipes on Windows, some extra steps are required: // // 1. The parent creates a communication pipe and stores handles to both // ends of it. // 2. The parent starts the child and provides it with the information // necessary to acquire the handle to the write end of the pipe. // 3. The child acquires the write end of the pipe and signals the parent // using a Windows event. // 4. Now the parent can release the write end of the pipe on its side. If // this is done before step 3, the object's reference count goes down to // 0 and it is destroyed, preventing the child from acquiring it. The // parent now has to release it, or read operations on the read end of // the pipe will not return when the child terminates. // 5. The parent reads child's output through the pipe (outcome code and // any possible error messages) from the pipe, and its stderr and then // determines whether to fail the test. // // Note: to distinguish Win32 API calls from the local method and function // calls, the former are explicitly resolved in the global namespace. // class WindowsDeathTest : public DeathTestImpl { public: WindowsDeathTest(const char* a_statement, const RE* a_regex, const char* file, int line) : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {} // All of these virtual functions are inherited from DeathTest. virtual int Wait(); virtual TestRole AssumeRole(); private: // The name of the file in which the death test is located. const char* const file_; // The line number on which the death test is located. const int line_; // Handle to the write end of the pipe to the child process. AutoHandle write_handle_; // Child process handle. AutoHandle child_handle_; // Event the child process uses to signal the parent that it has // acquired the handle to the write end of the pipe. After seeing this // event the parent can release its own handles to make sure its // ReadFile() calls return when the child terminates. AutoHandle event_handle_; }; // Waits for the child in a death test to exit, returning its exit // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. int WindowsDeathTest::Wait() { if (!spawned()) return 0; // Wait until the child either signals that it has acquired the write end // of the pipe or it dies. const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() }; switch (::WaitForMultipleObjects(2, wait_handles, FALSE, // Waits for any of the handles. INFINITE)) { case WAIT_OBJECT_0: case WAIT_OBJECT_0 + 1: break; default: GTEST_DEATH_TEST_CHECK_(false); // Should not get here. } // The child has acquired the write end of the pipe or exited. // We release the handle on our side and continue. write_handle_.Reset(); event_handle_.Reset(); ReadAndInterpretStatusByte(); // Waits for the child process to exit if it haven't already. This // returns immediately if the child has already exited, regardless of // whether previous calls to WaitForMultipleObjects synchronized on this // handle or not. GTEST_DEATH_TEST_CHECK_( WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(), INFINITE)); DWORD status_code; GTEST_DEATH_TEST_CHECK_( ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE); child_handle_.Reset(); set_status(static_cast<int>(status_code)); return status(); } // The AssumeRole process for a Windows death test. It creates a child // process with the same executable as the current process to run the // death test. The child process is given the --gtest_filter and // --gtest_internal_run_death_test flags such that it knows to run the // current death test only. DeathTest::TestRole WindowsDeathTest::AssumeRole() { const UnitTestImpl* const impl = GetUnitTestImpl(); const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); const TestInfo* const info = impl->current_test_info(); const int death_test_index = info->result()->death_test_count(); if (flag != NULL) { // ParseInternalRunDeathTestFlag() has performed all the necessary // processing. set_write_fd(flag->write_fd()); return EXECUTE_TEST; } // WindowsDeathTest uses an anonymous pipe to communicate results of // a death test. SECURITY_ATTRIBUTES handles_are_inheritable = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; HANDLE read_handle, write_handle; GTEST_DEATH_TEST_CHECK_( ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable, 0) // Default buffer size. != FALSE); set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle), O_RDONLY)); write_handle_.Reset(write_handle); event_handle_.Reset(::CreateEvent( &handles_are_inheritable, TRUE, // The event will automatically reset to non-signaled state. FALSE, // The initial state is non-signalled. NULL)); // The even is unnamed. GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL); const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + info->test_case_name() + "." + info->name(); const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + file_ + "|" + StreamableToString(line_) + "|" + StreamableToString(death_test_index) + "|" + StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) + // size_t has the same width as pointers on both 32-bit and 64-bit // Windows platforms. // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx. "|" + StreamableToString(reinterpret_cast<size_t>(write_handle)) + "|" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get())); char executable_path[_MAX_PATH + 1]; // NOLINT GTEST_DEATH_TEST_CHECK_( _MAX_PATH + 1 != ::GetModuleFileNameA(NULL, executable_path, _MAX_PATH)); std::string command_line = std::string(::GetCommandLineA()) + " " + filter_flag + " \"" + internal_flag + "\""; DeathTest::set_last_death_test_message(""); CaptureStderr(); // Flush the log buffers since the log streams are shared with the child. FlushInfoLog(); // The child process will share the standard handles with the parent. STARTUPINFOA startup_info; memset(&startup_info, 0, sizeof(STARTUPINFO)); startup_info.dwFlags = STARTF_USESTDHANDLES; startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE); startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE); startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE); PROCESS_INFORMATION process_info; GTEST_DEATH_TEST_CHECK_(::CreateProcessA( executable_path, const_cast<char*>(command_line.c_str()), NULL, // Retuned process handle is not inheritable. NULL, // Retuned thread handle is not inheritable. TRUE, // Child inherits all inheritable handles (for write_handle_). 0x0, // Default creation flags. NULL, // Inherit the parent's environment. UnitTest::GetInstance()->original_working_dir(), &startup_info, &process_info) != FALSE); child_handle_.Reset(process_info.hProcess); ::CloseHandle(process_info.hThread); set_spawned(true); return OVERSEE_TEST; } # else // We are not on Windows. // ForkingDeathTest provides implementations for most of the abstract // methods of the DeathTest interface. Only the AssumeRole method is // left undefined. class ForkingDeathTest : public DeathTestImpl { public: ForkingDeathTest(const char* statement, const RE* regex); // All of these virtual functions are inherited from DeathTest. virtual int Wait(); protected: void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; } private: // PID of child process during death test; 0 in the child process itself. pid_t child_pid_; }; // Constructs a ForkingDeathTest. ForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex) : DeathTestImpl(a_statement, a_regex), child_pid_(-1) {} // Waits for the child in a death test to exit, returning its exit // status, or 0 if no child process exists. As a side effect, sets the // outcome data member. int ForkingDeathTest::Wait() { if (!spawned()) return 0; ReadAndInterpretStatusByte(); int status_value; GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0)); set_status(status_value); return status_value; } // A concrete death test class that forks, then immediately runs the test // in the child process. class NoExecDeathTest : public ForkingDeathTest { public: NoExecDeathTest(const char* a_statement, const RE* a_regex) : ForkingDeathTest(a_statement, a_regex) { } virtual TestRole AssumeRole(); }; // The AssumeRole process for a fork-and-run death test. It implements a // straightforward fork, with a simple pipe to transmit the status byte. DeathTest::TestRole NoExecDeathTest::AssumeRole() { const size_t thread_count = GetThreadCount(); if (thread_count != 1) { GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count); } int pipe_fd[2]; GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); DeathTest::set_last_death_test_message(""); CaptureStderr(); // When we fork the process below, the log file buffers are copied, but the // file descriptors are shared. We flush all log files here so that closing // the file descriptors in the child process doesn't throw off the // synchronization between descriptors and buffers in the parent process. // This is as close to the fork as possible to avoid a race condition in case // there are multiple threads running before the death test, and another // thread writes to the log file. FlushInfoLog(); const pid_t child_pid = fork(); GTEST_DEATH_TEST_CHECK_(child_pid != -1); set_child_pid(child_pid); if (child_pid == 0) { GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0])); set_write_fd(pipe_fd[1]); // Redirects all logging to stderr in the child process to prevent // concurrent writes to the log files. We capture stderr in the parent // process and append the child process' output to a log. LogToStderr(); // Event forwarding to the listeners of event listener API mush be shut // down in death test subprocesses. GetUnitTestImpl()->listeners()->SuppressEventForwarding(); g_in_fast_death_test_child = true; return EXECUTE_TEST; } else { GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); set_read_fd(pipe_fd[0]); set_spawned(true); return OVERSEE_TEST; } } // A concrete death test class that forks and re-executes the main // program from the beginning, with command-line flags set that cause // only this specific death test to be run. class ExecDeathTest : public ForkingDeathTest { public: ExecDeathTest(const char* a_statement, const RE* a_regex, const char* file, int line) : ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { } virtual TestRole AssumeRole(); private: static ::std::vector<testing::internal::string> GetArgvsForDeathTestChildProcess() { ::std::vector<testing::internal::string> args = GetInjectableArgvs(); # if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) ::std::vector<testing::internal::string> extra_args = GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_(); args.insert(args.end(), extra_args.begin(), extra_args.end()); # endif // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_) return args; } // The name of the file in which the death test is located. const char* const file_; // The line number on which the death test is located. const int line_; }; // Utility class for accumulating command-line arguments. class Arguments { public: Arguments() { args_.push_back(NULL); } ~Arguments() { for (std::vector<char*>::iterator i = args_.begin(); i != args_.end(); ++i) { free(*i); } } void AddArgument(const char* argument) { args_.insert(args_.end() - 1, posix::StrDup(argument)); } template <typename Str> void AddArguments(const ::std::vector<Str>& arguments) { for (typename ::std::vector<Str>::const_iterator i = arguments.begin(); i != arguments.end(); ++i) { args_.insert(args_.end() - 1, posix::StrDup(i->c_str())); } } char* const* Argv() { return &args_[0]; } private: std::vector<char*> args_; }; // A struct that encompasses the arguments to the child process of a // threadsafe-style death test process. struct ExecDeathTestArgs { char* const* argv; // Command-line arguments for the child's call to exec int close_fd; // File descriptor to close; the read end of a pipe }; # if GTEST_OS_MAC inline char** GetEnviron() { // When Google Test is built as a framework on MacOS X, the environ variable // is unavailable. Apple's documentation (man environ) recommends using // _NSGetEnviron() instead. return *_NSGetEnviron(); } # else // Some POSIX platforms expect you to declare environ. extern "C" makes // it reside in the global namespace. extern "C" char** environ; inline char** GetEnviron() { return environ; } # endif // GTEST_OS_MAC # if !GTEST_OS_QNX // The main function for a threadsafe-style death test child process. // This function is called in a clone()-ed process and thus must avoid // any potentially unsafe operations like malloc or libc functions. static int ExecDeathTestChildMain(void* child_arg) { ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd)); // We need to execute the test program in the same environment where // it was originally invoked. Therefore we change to the original // working directory first. const char* const original_dir = UnitTest::GetInstance()->original_working_dir(); // We can safely call chdir() as it's a direct system call. if (chdir(original_dir) != 0) { DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } // We can safely call execve() as it's a direct system call. We // cannot use execvp() as it's a libc function and thus potentially // unsafe. Since execve() doesn't search the PATH, the user must // invoke the test program via a valid path that contains at least // one path separator. execve(args->argv[0], args->argv, GetEnviron()); DeathTestAbort(std::string("execve(") + args->argv[0] + ", ...) in " + original_dir + " failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } # endif // !GTEST_OS_QNX // Two utility routines that together determine the direction the stack // grows. // This could be accomplished more elegantly by a single recursive // function, but we want to guard against the unlikely possibility of // a smart compiler optimizing the recursion away. // // GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining // StackLowerThanAddress into StackGrowsDown, which then doesn't give // correct answer. void StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_; void StackLowerThanAddress(const void* ptr, bool* result) { int dummy; *result = (&dummy < ptr); } // Make sure AddressSanitizer does not tamper with the stack here. GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ bool StackGrowsDown() { int dummy; bool result; StackLowerThanAddress(&dummy, &result); return result; } // Spawns a child process with the same executable as the current process in // a thread-safe manner and instructs it to run the death test. The // implementation uses fork(2) + exec. On systems where clone(2) is // available, it is used instead, being slightly more thread-safe. On QNX, // fork supports only single-threaded environments, so this function uses // spawn(2) there instead. The function dies with an error message if // anything goes wrong. static pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) { ExecDeathTestArgs args = { argv, close_fd }; pid_t child_pid = -1; # if GTEST_OS_QNX // Obtains the current directory and sets it to be closed in the child // process. const int cwd_fd = open(".", O_RDONLY); GTEST_DEATH_TEST_CHECK_(cwd_fd != -1); GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC)); // We need to execute the test program in the same environment where // it was originally invoked. Therefore we change to the original // working directory first. const char* const original_dir = UnitTest::GetInstance()->original_working_dir(); // We can safely call chdir() as it's a direct system call. if (chdir(original_dir) != 0) { DeathTestAbort(std::string("chdir(\"") + original_dir + "\") failed: " + GetLastErrnoDescription()); return EXIT_FAILURE; } int fd_flags; // Set close_fd to be closed after spawn. GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD)); GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD, fd_flags | FD_CLOEXEC)); struct inheritance inherit = {0}; // spawn is a system call. child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron()); // Restores the current working directory. GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd)); # else // GTEST_OS_QNX # if GTEST_OS_LINUX // When a SIGPROF signal is received while fork() or clone() are executing, // the process may hang. To avoid this, we ignore SIGPROF here and re-enable // it after the call to fork()/clone() is complete. struct sigaction saved_sigprof_action; struct sigaction ignore_sigprof_action; memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action)); sigemptyset(&ignore_sigprof_action.sa_mask); ignore_sigprof_action.sa_handler = SIG_IGN; GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction( SIGPROF, &ignore_sigprof_action, &saved_sigprof_action)); # endif // GTEST_OS_LINUX # if GTEST_HAS_CLONE const bool use_fork = GTEST_FLAG(death_test_use_fork); if (!use_fork) { static const bool stack_grows_down = StackGrowsDown(); const size_t stack_size = getpagesize(); // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead. void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED); // Maximum stack alignment in bytes: For a downward-growing stack, this // amount is subtracted from size of the stack space to get an address // that is within the stack space and is aligned on all systems we care // about. As far as I know there is no ABI with stack alignment greater // than 64. We assume stack and stack_size already have alignment of // kMaxStackAlignment. const size_t kMaxStackAlignment = 64; void* const stack_top = static_cast<char*>(stack) + (stack_grows_down ? stack_size - kMaxStackAlignment : 0); GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment && reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0); child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args); GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1); } # else const bool use_fork = true; # endif // GTEST_HAS_CLONE if (use_fork && (child_pid = fork()) == 0) { ExecDeathTestChildMain(&args); _exit(0); } # endif // GTEST_OS_QNX # if GTEST_OS_LINUX GTEST_DEATH_TEST_CHECK_SYSCALL_( sigaction(SIGPROF, &saved_sigprof_action, NULL)); # endif // GTEST_OS_LINUX GTEST_DEATH_TEST_CHECK_(child_pid != -1); return child_pid; } // The AssumeRole process for a fork-and-exec death test. It re-executes the // main program from the beginning, setting the --gtest_filter // and --gtest_internal_run_death_test flags to cause only the current // death test to be re-run. DeathTest::TestRole ExecDeathTest::AssumeRole() { const UnitTestImpl* const impl = GetUnitTestImpl(); const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); const TestInfo* const info = impl->current_test_info(); const int death_test_index = info->result()->death_test_count(); if (flag != NULL) { set_write_fd(flag->write_fd()); return EXECUTE_TEST; } int pipe_fd[2]; GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1); // Clear the close-on-exec flag on the write end of the pipe, lest // it be closed when the child process does an exec: GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1); const std::string filter_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kFilterFlag + "=" + info->test_case_name() + "." + info->name(); const std::string internal_flag = std::string("--") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + "=" + file_ + "|" + StreamableToString(line_) + "|" + StreamableToString(death_test_index) + "|" + StreamableToString(pipe_fd[1]); Arguments args; args.AddArguments(GetArgvsForDeathTestChildProcess()); args.AddArgument(filter_flag.c_str()); args.AddArgument(internal_flag.c_str()); DeathTest::set_last_death_test_message(""); CaptureStderr(); // See the comment in NoExecDeathTest::AssumeRole for why the next line // is necessary. FlushInfoLog(); const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]); GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1])); set_child_pid(child_pid); set_read_fd(pipe_fd[0]); set_spawned(true); return OVERSEE_TEST; } # endif // !GTEST_OS_WINDOWS // Creates a concrete DeathTest-derived class that depends on the // --gtest_death_test_style flag, and sets the pointer pointed to // by the "test" argument to its address. If the test should be // skipped, sets that pointer to NULL. Returns true, unless the // flag is set to an invalid value. bool DefaultDeathTestFactory::Create(const char* statement, const RE* regex, const char* file, int line, DeathTest** test) { UnitTestImpl* const impl = GetUnitTestImpl(); const InternalRunDeathTestFlag* const flag = impl->internal_run_death_test_flag(); const int death_test_index = impl->current_test_info() ->increment_death_test_count(); if (flag != NULL) { if (death_test_index > flag->index()) { DeathTest::set_last_death_test_message( "Death test count (" + StreamableToString(death_test_index) + ") somehow exceeded expected maximum (" + StreamableToString(flag->index()) + ")"); return false; } if (!(flag->file() == file && flag->line() == line && flag->index() == death_test_index)) { *test = NULL; return true; } } # if GTEST_OS_WINDOWS if (GTEST_FLAG(death_test_style) == "threadsafe" || GTEST_FLAG(death_test_style) == "fast") { *test = new WindowsDeathTest(statement, regex, file, line); } # else if (GTEST_FLAG(death_test_style) == "threadsafe") { *test = new ExecDeathTest(statement, regex, file, line); } else if (GTEST_FLAG(death_test_style) == "fast") { *test = new NoExecDeathTest(statement, regex); } # endif // GTEST_OS_WINDOWS else { // NOLINT - this is more readable than unbalanced brackets inside #if. DeathTest::set_last_death_test_message( "Unknown death test style \"" + GTEST_FLAG(death_test_style) + "\" encountered"); return false; } return true; } # if GTEST_OS_WINDOWS // Recreates the pipe and event handles from the provided parameters, // signals the event, and returns a file descriptor wrapped around the pipe // handle. This function is called in the child process only. int GetStatusFileDescriptor(unsigned int parent_process_id, size_t write_handle_as_size_t, size_t event_handle_as_size_t) { AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE, FALSE, // Non-inheritable. parent_process_id)); if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) { DeathTestAbort("Unable to open parent process " + StreamableToString(parent_process_id)); } // TODO(vladl@google.com): Replace the following check with a // compile-time assertion when available. GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t)); const HANDLE write_handle = reinterpret_cast<HANDLE>(write_handle_as_size_t); HANDLE dup_write_handle; // The newly initialized handle is accessible only in in the parent // process. To obtain one accessible within the child, we need to use // DuplicateHandle. if (!::DuplicateHandle(parent_process_handle.Get(), write_handle, ::GetCurrentProcess(), &dup_write_handle, 0x0, // Requested privileges ignored since // DUPLICATE_SAME_ACCESS is used. FALSE, // Request non-inheritable handler. DUPLICATE_SAME_ACCESS)) { DeathTestAbort("Unable to duplicate the pipe handle " + StreamableToString(write_handle_as_size_t) + " from the parent process " + StreamableToString(parent_process_id)); } const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t); HANDLE dup_event_handle; if (!::DuplicateHandle(parent_process_handle.Get(), event_handle, ::GetCurrentProcess(), &dup_event_handle, 0x0, FALSE, DUPLICATE_SAME_ACCESS)) { DeathTestAbort("Unable to duplicate the event handle " + StreamableToString(event_handle_as_size_t) + " from the parent process " + StreamableToString(parent_process_id)); } const int write_fd = ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND); if (write_fd == -1) { DeathTestAbort("Unable to convert pipe handle " + StreamableToString(write_handle_as_size_t) + " to a file descriptor"); } // Signals the parent that the write end of the pipe has been acquired // so the parent can release its own write end. ::SetEvent(dup_event_handle); return write_fd; } # endif // GTEST_OS_WINDOWS // Returns a newly created InternalRunDeathTestFlag object with fields // initialized from the GTEST_FLAG(internal_run_death_test) flag if // the flag is specified; otherwise returns NULL. InternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() { if (GTEST_FLAG(internal_run_death_test) == "") return NULL; // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we // can use it here. int line = -1; int index = -1; ::std::vector< ::std::string> fields; SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields); int write_fd = -1; # if GTEST_OS_WINDOWS unsigned int parent_process_id = 0; size_t write_handle_as_size_t = 0; size_t event_handle_as_size_t = 0; if (fields.size() != 6 || !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[2], &index) || !ParseNaturalNumber(fields[3], &parent_process_id) || !ParseNaturalNumber(fields[4], &write_handle_as_size_t) || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) { DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + GTEST_FLAG(internal_run_death_test)); } write_fd = GetStatusFileDescriptor(parent_process_id, write_handle_as_size_t, event_handle_as_size_t); # else if (fields.size() != 4 || !ParseNaturalNumber(fields[1], &line) || !ParseNaturalNumber(fields[2], &index) || !ParseNaturalNumber(fields[3], &write_fd)) { DeathTestAbort("Bad --gtest_internal_run_death_test flag: " + GTEST_FLAG(internal_run_death_test)); } # endif // GTEST_OS_WINDOWS return new InternalRunDeathTestFlag(fields[0], line, index, write_fd); } } // namespace internal #endif // GTEST_HAS_DEATH_TEST } // namespace testing // Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Authors: keith.ray@gmail.com (Keith Ray) #include <stdlib.h> #if GTEST_OS_WINDOWS_MOBILE # include <windows.h> #elif GTEST_OS_WINDOWS # include <direct.h> # include <io.h> #elif GTEST_OS_SYMBIAN // Symbian OpenC has PATH_MAX in sys/syslimits.h # include <sys/syslimits.h> #else # include <limits.h> # include <climits> // Some Linux distributions define PATH_MAX here. #endif // GTEST_OS_WINDOWS_MOBILE #if GTEST_OS_WINDOWS # define GTEST_PATH_MAX_ _MAX_PATH #elif defined(PATH_MAX) # define GTEST_PATH_MAX_ PATH_MAX #elif defined(_XOPEN_PATH_MAX) # define GTEST_PATH_MAX_ _XOPEN_PATH_MAX #else # define GTEST_PATH_MAX_ _POSIX_PATH_MAX #endif // GTEST_OS_WINDOWS namespace testing { namespace internal { #if GTEST_OS_WINDOWS // On Windows, '\\' is the standard path separator, but many tools and the // Windows API also accept '/' as an alternate path separator. Unless otherwise // noted, a file path can contain either kind of path separators, or a mixture // of them. const char kPathSeparator = '\\'; const char kAlternatePathSeparator = '/'; const char kAlternatePathSeparatorString[] = "/"; # if GTEST_OS_WINDOWS_MOBILE // Windows CE doesn't have a current directory. You should not use // the current directory in tests on Windows CE, but this at least // provides a reasonable fallback. const char kCurrentDirectoryString[] = "\\"; // Windows CE doesn't define INVALID_FILE_ATTRIBUTES const DWORD kInvalidFileAttributes = 0xffffffff; # else const char kCurrentDirectoryString[] = ".\\"; # endif // GTEST_OS_WINDOWS_MOBILE #else const char kPathSeparator = '/'; const char kCurrentDirectoryString[] = "./"; #endif // GTEST_OS_WINDOWS // Returns whether the given character is a valid path separator. static bool IsPathSeparator(char c) { #if GTEST_HAS_ALT_PATH_SEP_ return (c == kPathSeparator) || (c == kAlternatePathSeparator); #else return c == kPathSeparator; #endif } // Returns the current working directory, or "" if unsuccessful. FilePath FilePath::GetCurrentDir() { #if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT // Windows CE doesn't have a current directory, so we just return // something reasonable. return FilePath(kCurrentDirectoryString); #elif GTEST_OS_WINDOWS char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? "" : cwd); #else char cwd[GTEST_PATH_MAX_ + 1] = { '\0' }; char* result = getcwd(cwd, sizeof(cwd)); # if GTEST_OS_NACL // getcwd will likely fail in NaCl due to the sandbox, so return something // reasonable. The user may have provided a shim implementation for getcwd, // however, so fallback only when failure is detected. return FilePath(result == NULL ? kCurrentDirectoryString : cwd); # endif // GTEST_OS_NACL return FilePath(result == NULL ? "" : cwd); #endif // GTEST_OS_WINDOWS_MOBILE } // Returns a copy of the FilePath with the case-insensitive extension removed. // Example: FilePath("dir/file.exe").RemoveExtension("EXE") returns // FilePath("dir/file"). If a case-insensitive extension is not // found, returns a copy of the original FilePath. FilePath FilePath::RemoveExtension(const char* extension) const { const std::string dot_extension = std::string(".") + extension; if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) { return FilePath(pathname_.substr( 0, pathname_.length() - dot_extension.length())); } return *this; } // Returns a pointer to the last occurence of a valid path separator in // the FilePath. On Windows, for example, both '/' and '\' are valid path // separators. Returns NULL if no path separator was found. const char* FilePath::FindLastPathSeparator() const { const char* const last_sep = strrchr(c_str(), kPathSeparator); #if GTEST_HAS_ALT_PATH_SEP_ const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator); // Comparing two pointers of which only one is NULL is undefined. if (last_alt_sep != NULL && (last_sep == NULL || last_alt_sep > last_sep)) { return last_alt_sep; } #endif return last_sep; } // Returns a copy of the FilePath with the directory part removed. // Example: FilePath("path/to/file").RemoveDirectoryName() returns // FilePath("file"). If there is no directory part ("just_a_file"), it returns // the FilePath unmodified. If there is no file part ("just_a_dir/") it // returns an empty FilePath (""). // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath FilePath::RemoveDirectoryName() const { const char* const last_sep = FindLastPathSeparator(); return last_sep ? FilePath(last_sep + 1) : *this; } // RemoveFileName returns the directory path with the filename removed. // Example: FilePath("path/to/file").RemoveFileName() returns "path/to/". // If the FilePath is "a_file" or "/a_file", RemoveFileName returns // FilePath("./") or, on Windows, FilePath(".\\"). If the filepath does // not have a file, like "just/a/dir/", it returns the FilePath unmodified. // On Windows platform, '\' is the path separator, otherwise it is '/'. FilePath FilePath::RemoveFileName() const { const char* const last_sep = FindLastPathSeparator(); std::string dir; if (last_sep) { dir = std::string(c_str(), last_sep + 1 - c_str()); } else { dir = kCurrentDirectoryString; } return FilePath(dir); } // Helper functions for naming files in a directory for xml output. // Given directory = "dir", base_name = "test", number = 0, // extension = "xml", returns "dir/test.xml". If number is greater // than zero (e.g., 12), returns "dir/test_12.xml". // On Windows platform, uses \ as the separator rather than /. FilePath FilePath::MakeFileName(const FilePath& directory, const FilePath& base_name, int number, const char* extension) { std::string file; if (number == 0) { file = base_name.string() + "." + extension; } else { file = base_name.string() + "_" + StreamableToString(number) + "." + extension; } return ConcatPaths(directory, FilePath(file)); } // Given directory = "dir", relative_path = "test.xml", returns "dir/test.xml". // On Windows, uses \ as the separator rather than /. FilePath FilePath::ConcatPaths(const FilePath& directory, const FilePath& relative_path) { if (directory.IsEmpty()) return relative_path; const FilePath dir(directory.RemoveTrailingPathSeparator()); return FilePath(dir.string() + kPathSeparator + relative_path.string()); } // Returns true if pathname describes something findable in the file-system, // either a file, directory, or whatever. bool FilePath::FileOrDirectoryExists() const { #if GTEST_OS_WINDOWS_MOBILE LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str()); const DWORD attributes = GetFileAttributes(unicode); delete [] unicode; return attributes != kInvalidFileAttributes; #else posix::StatStruct file_stat; return posix::Stat(pathname_.c_str(), &file_stat) == 0; #endif // GTEST_OS_WINDOWS_MOBILE } // Returns true if pathname describes a directory in the file-system // that exists. bool FilePath::DirectoryExists() const { bool result = false; #if GTEST_OS_WINDOWS // Don't strip off trailing separator if path is a root directory on // Windows (like "C:\\"). const FilePath& path(IsRootDirectory() ? *this : RemoveTrailingPathSeparator()); #else const FilePath& path(*this); #endif #if GTEST_OS_WINDOWS_MOBILE LPCWSTR unicode = String::AnsiToUtf16(path.c_str()); const DWORD attributes = GetFileAttributes(unicode); delete [] unicode; if ((attributes != kInvalidFileAttributes) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) { result = true; } #else posix::StatStruct file_stat; result = posix::Stat(path.c_str(), &file_stat) == 0 && posix::IsDir(file_stat); #endif // GTEST_OS_WINDOWS_MOBILE return result; } // Returns true if pathname describes a root directory. (Windows has one // root directory per disk drive.) bool FilePath::IsRootDirectory() const { #if GTEST_OS_WINDOWS // TODO(wan@google.com): on Windows a network share like // \\server\share can be a root directory, although it cannot be the // current directory. Handle this properly. return pathname_.length() == 3 && IsAbsolutePath(); #else return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]); #endif } // Returns true if pathname describes an absolute path. bool FilePath::IsAbsolutePath() const { const char* const name = pathname_.c_str(); #if GTEST_OS_WINDOWS return pathname_.length() >= 3 && ((name[0] >= 'a' && name[0] <= 'z') || (name[0] >= 'A' && name[0] <= 'Z')) && name[1] == ':' && IsPathSeparator(name[2]); #else return IsPathSeparator(name[0]); #endif } // Returns a pathname for a file that does not currently exist. The pathname // will be directory/base_name.extension or // directory/base_name_<number>.extension if directory/base_name.extension // already exists. The number will be incremented until a pathname is found // that does not already exist. // Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'. // There could be a race condition if two or more processes are calling this // function at the same time -- they could both pick the same filename. FilePath FilePath::GenerateUniqueFileName(const FilePath& directory, const FilePath& base_name, const char* extension) { FilePath full_pathname; int number = 0; do { full_pathname.Set(MakeFileName(directory, base_name, number++, extension)); } while (full_pathname.FileOrDirectoryExists()); return full_pathname; } // Returns true if FilePath ends with a path separator, which indicates that // it is intended to represent a directory. Returns false otherwise. // This does NOT check that a directory (or file) actually exists. bool FilePath::IsDirectory() const { return !pathname_.empty() && IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]); } // Create directories so that path exists. Returns true if successful or if // the directories already exist; returns false if unable to create directories // for any reason. bool FilePath::CreateDirectoriesRecursively() const { if (!this->IsDirectory()) { return false; } if (pathname_.length() == 0 || this->DirectoryExists()) { return true; } const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName()); return parent.CreateDirectoriesRecursively() && this->CreateFolder(); } // Create the directory so that path exists. Returns true if successful or // if the directory already exists; returns false if unable to create the // directory for any reason, including if the parent directory does not // exist. Not named "CreateDirectory" because that's a macro on Windows. bool FilePath::CreateFolder() const { #if GTEST_OS_WINDOWS_MOBILE FilePath removed_sep(this->RemoveTrailingPathSeparator()); LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str()); int result = CreateDirectory(unicode, NULL) ? 0 : -1; delete [] unicode; #elif GTEST_OS_WINDOWS int result = _mkdir(pathname_.c_str()); #else int result = mkdir(pathname_.c_str(), 0777); #endif // GTEST_OS_WINDOWS_MOBILE if (result == -1) { return this->DirectoryExists(); // An error is OK if the directory exists. } return true; // No error. } // If input name has a trailing separator character, remove it and return the // name, otherwise return the name string unmodified. // On Windows platform, uses \ as the separator, other platforms use /. FilePath FilePath::RemoveTrailingPathSeparator() const { return IsDirectory() ? FilePath(pathname_.substr(0, pathname_.length() - 1)) : *this; } // Removes any redundant separators that might be in the pathname. // For example, "bar///foo" becomes "bar/foo". Does not eliminate other // redundancies that might be in a pathname involving "." or "..". // TODO(wan@google.com): handle Windows network shares (e.g. \\server\share). void FilePath::Normalize() { if (pathname_.c_str() == NULL) { pathname_ = ""; return; } const char* src = pathname_.c_str(); char* const dest = new char[pathname_.length() + 1]; char* dest_ptr = dest; memset(dest_ptr, 0, pathname_.length() + 1); while (*src != '\0') { *dest_ptr = *src; if (!IsPathSeparator(*src)) { src++; } else { #if GTEST_HAS_ALT_PATH_SEP_ if (*dest_ptr == kAlternatePathSeparator) { *dest_ptr = kPathSeparator; } #endif while (IsPathSeparator(*src)) src++; } dest_ptr++; } *dest_ptr = '\0'; pathname_ = dest; delete[] dest; } } // namespace internal } // namespace testing // Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) #include <limits.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fstream> #if GTEST_OS_WINDOWS # include <windows.h> # include <io.h> # include <sys/stat.h> # include <map> // Used in ThreadLocal. #else # include <unistd.h> #endif // GTEST_OS_WINDOWS #if GTEST_OS_MAC # include <mach/mach_init.h> # include <mach/task.h> # include <mach/vm_map.h> #endif // GTEST_OS_MAC #if GTEST_OS_QNX # include <devctl.h> # include <fcntl.h> # include <sys/procfs.h> #endif // GTEST_OS_QNX #if GTEST_OS_AIX # include <procinfo.h> # include <sys/types.h> #endif // GTEST_OS_AIX // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick exists to // prevent the accidental inclusion of gtest-internal-inl.h in the // user's code. #define GTEST_IMPLEMENTATION_ 1 #undef GTEST_IMPLEMENTATION_ namespace testing { namespace internal { #if defined(_MSC_VER) || defined(__BORLANDC__) // MSVC and C++Builder do not provide a definition of STDERR_FILENO. const int kStdOutFileno = 1; const int kStdErrFileno = 2; #else const int kStdOutFileno = STDOUT_FILENO; const int kStdErrFileno = STDERR_FILENO; #endif // _MSC_VER #if GTEST_OS_LINUX namespace { template <typename T> T ReadProcFileField(const string& filename, int field) { std::string dummy; std::ifstream file(filename.c_str()); while (field-- > 0) { file >> dummy; } T output = 0; file >> output; return output; } } // namespace // Returns the number of active threads, or 0 when there is an error. size_t GetThreadCount() { const string filename = (Message() << "/proc/" << getpid() << "/stat").GetString(); return ReadProcFileField<int>(filename, 19); } #elif GTEST_OS_MAC size_t GetThreadCount() { const task_t task = mach_task_self(); mach_msg_type_number_t thread_count; thread_act_array_t thread_list; const kern_return_t status = task_threads(task, &thread_list, &thread_count); if (status == KERN_SUCCESS) { // task_threads allocates resources in thread_list and we need to free them // to avoid leaks. vm_deallocate(task, reinterpret_cast<vm_address_t>(thread_list), sizeof(thread_t) * thread_count); return static_cast<size_t>(thread_count); } else { return 0; } } #elif GTEST_OS_QNX // Returns the number of threads running in the process, or 0 to indicate that // we cannot detect it. size_t GetThreadCount() { const int fd = open("/proc/self/as", O_RDONLY); if (fd < 0) { return 0; } procfs_info process_info; const int status = devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL); close(fd); if (status == EOK) { return static_cast<size_t>(process_info.num_threads); } else { return 0; } } #elif GTEST_OS_AIX size_t GetThreadCount() { struct procentry64 entry; pid_t pid = getpid(); int status = getprocs64(&entry, sizeof(entry), NULL, 0, &pid, 1); if (status == 1) { return entry.pi_thcount; } else { return 0; } } #else size_t GetThreadCount() { // There's no portable way to detect the number of threads, so we just // return 0 to indicate that we cannot detect it. return 0; } #endif // GTEST_OS_LINUX #if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS void SleepMilliseconds(int n) { ::Sleep(n); } AutoHandle::AutoHandle() : handle_(INVALID_HANDLE_VALUE) {} AutoHandle::AutoHandle(Handle handle) : handle_(handle) {} AutoHandle::~AutoHandle() { Reset(); } AutoHandle::Handle AutoHandle::Get() const { return handle_; } void AutoHandle::Reset() { Reset(INVALID_HANDLE_VALUE); } void AutoHandle::Reset(HANDLE handle) { // Resetting with the same handle we already own is invalid. if (handle_ != handle) { if (IsCloseable()) { ::CloseHandle(handle_); } handle_ = handle; } else { GTEST_CHECK_(!IsCloseable()) << "Resetting a valid handle to itself is likely a programmer error " "and thus not allowed."; } } bool AutoHandle::IsCloseable() const { // Different Windows APIs may use either of these values to represent an // invalid handle. return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE; } Notification::Notification() : event_(::CreateEvent(NULL, // Default security attributes. TRUE, // Do not reset automatically. FALSE, // Initially unset. NULL)) { // Anonymous event. GTEST_CHECK_(event_.Get() != NULL); } void Notification::Notify() { GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE); } void Notification::WaitForNotification() { GTEST_CHECK_( ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0); } Mutex::Mutex() : owner_thread_id_(0), type_(kDynamic), critical_section_init_phase_(0), critical_section_(new CRITICAL_SECTION) { ::InitializeCriticalSection(critical_section_); } Mutex::~Mutex() { // Static mutexes are leaked intentionally. It is not thread-safe to try // to clean them up. // TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires // nothing to clean it up but is available only on Vista and later. // http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937.aspx if (type_ == kDynamic) { ::DeleteCriticalSection(critical_section_); delete critical_section_; critical_section_ = NULL; } } void Mutex::Lock() { ThreadSafeLazyInit(); ::EnterCriticalSection(critical_section_); owner_thread_id_ = ::GetCurrentThreadId(); } void Mutex::Unlock() { ThreadSafeLazyInit(); // We don't protect writing to owner_thread_id_ here, as it's the // caller's responsibility to ensure that the current thread holds the // mutex when this is called. owner_thread_id_ = 0; ::LeaveCriticalSection(critical_section_); } // Does nothing if the current thread holds the mutex. Otherwise, crashes // with high probability. void Mutex::AssertHeld() { ThreadSafeLazyInit(); GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId()) << "The current thread is not holding the mutex @" << this; } // Initializes owner_thread_id_ and critical_section_ in static mutexes. void Mutex::ThreadSafeLazyInit() { // Dynamic mutexes are initialized in the constructor. if (type_ == kStatic) { switch ( ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) { case 0: // If critical_section_init_phase_ was 0 before the exchange, we // are the first to test it and need to perform the initialization. owner_thread_id_ = 0; critical_section_ = new CRITICAL_SECTION; ::InitializeCriticalSection(critical_section_); // Updates the critical_section_init_phase_ to 2 to signal // initialization complete. GTEST_CHECK_(::InterlockedCompareExchange( &critical_section_init_phase_, 2L, 1L) == 1L); break; case 1: // Somebody else is already initializing the mutex; spin until they // are done. while (::InterlockedCompareExchange(&critical_section_init_phase_, 2L, 2L) != 2L) { // Possibly yields the rest of the thread's time slice to other // threads. ::Sleep(0); } break; case 2: break; // The mutex is already initialized and ready for use. default: GTEST_CHECK_(false) << "Unexpected value of critical_section_init_phase_ " << "while initializing a static mutex."; } } } namespace { class ThreadWithParamSupport : public ThreadWithParamBase { public: static HANDLE CreateThread(Runnable* runnable, Notification* thread_can_start) { ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start); DWORD thread_id; // TODO(yukawa): Consider to use _beginthreadex instead. HANDLE thread_handle = ::CreateThread( NULL, // Default security. 0, // Default stack size. &ThreadWithParamSupport::ThreadMain, param, // Parameter to ThreadMainStatic 0x0, // Default creation flags. &thread_id); // Need a valid pointer for the call to work under Win98. GTEST_CHECK_(thread_handle != NULL) << "CreateThread failed with error " << ::GetLastError() << "."; if (thread_handle == NULL) { delete param; } return thread_handle; } private: struct ThreadMainParam { ThreadMainParam(Runnable* runnable, Notification* thread_can_start) : runnable_(runnable), thread_can_start_(thread_can_start) { } scoped_ptr<Runnable> runnable_; // Does not own. Notification* thread_can_start_; }; static DWORD WINAPI ThreadMain(void* ptr) { // Transfers ownership. scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr)); if (param->thread_can_start_ != NULL) param->thread_can_start_->WaitForNotification(); param->runnable_->Run(); return 0; } // Prohibit instantiation. ThreadWithParamSupport(); GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport); }; } // namespace ThreadWithParamBase::ThreadWithParamBase(Runnable *runnable, Notification* thread_can_start) : thread_(ThreadWithParamSupport::CreateThread(runnable, thread_can_start)) { } ThreadWithParamBase::~ThreadWithParamBase() { Join(); } void ThreadWithParamBase::Join() { GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0) << "Failed to join the thread with error " << ::GetLastError() << "."; } // Maps a thread to a set of ThreadIdToThreadLocals that have values // instantiated on that thread and notifies them when the thread exits. A // ThreadLocal instance is expected to persist until all threads it has // values on have terminated. class ThreadLocalRegistryImpl { public: // Registers thread_local_instance as having value on the current thread. // Returns a value that can be used to identify the thread from other threads. static ThreadLocalValueHolderBase* GetValueOnCurrentThread( const ThreadLocalBase* thread_local_instance) { DWORD current_thread = ::GetCurrentThreadId(); MutexLock lock(&mutex_); ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); ThreadIdToThreadLocals::iterator thread_local_pos = thread_to_thread_locals->find(current_thread); if (thread_local_pos == thread_to_thread_locals->end()) { thread_local_pos = thread_to_thread_locals->insert( std::make_pair(current_thread, ThreadLocalValues())).first; StartWatcherThreadFor(current_thread); } ThreadLocalValues& thread_local_values = thread_local_pos->second; ThreadLocalValues::iterator value_pos = thread_local_values.find(thread_local_instance); if (value_pos == thread_local_values.end()) { value_pos = thread_local_values .insert(std::make_pair( thread_local_instance, linked_ptr<ThreadLocalValueHolderBase>( thread_local_instance->NewValueForCurrentThread()))) .first; } return value_pos->second.get(); } static void OnThreadLocalDestroyed( const ThreadLocalBase* thread_local_instance) { std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders; // Clean up the ThreadLocalValues data structure while holding the lock, but // defer the destruction of the ThreadLocalValueHolderBases. { MutexLock lock(&mutex_); ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); for (ThreadIdToThreadLocals::iterator it = thread_to_thread_locals->begin(); it != thread_to_thread_locals->end(); ++it) { ThreadLocalValues& thread_local_values = it->second; ThreadLocalValues::iterator value_pos = thread_local_values.find(thread_local_instance); if (value_pos != thread_local_values.end()) { value_holders.push_back(value_pos->second); thread_local_values.erase(value_pos); // This 'if' can only be successful at most once, so theoretically we // could break out of the loop here, but we don't bother doing so. } } } // Outside the lock, let the destructor for 'value_holders' deallocate the // ThreadLocalValueHolderBases. } static void OnThreadExit(DWORD thread_id) { GTEST_CHECK_(thread_id != 0) << ::GetLastError(); std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders; // Clean up the ThreadIdToThreadLocals data structure while holding the // lock, but defer the destruction of the ThreadLocalValueHolderBases. { MutexLock lock(&mutex_); ThreadIdToThreadLocals* const thread_to_thread_locals = GetThreadLocalsMapLocked(); ThreadIdToThreadLocals::iterator thread_local_pos = thread_to_thread_locals->find(thread_id); if (thread_local_pos != thread_to_thread_locals->end()) { ThreadLocalValues& thread_local_values = thread_local_pos->second; for (ThreadLocalValues::iterator value_pos = thread_local_values.begin(); value_pos != thread_local_values.end(); ++value_pos) { value_holders.push_back(value_pos->second); } thread_to_thread_locals->erase(thread_local_pos); } } // Outside the lock, let the destructor for 'value_holders' deallocate the // ThreadLocalValueHolderBases. } private: // In a particular thread, maps a ThreadLocal object to its value. typedef std::map<const ThreadLocalBase*, linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues; // Stores all ThreadIdToThreadLocals having values in a thread, indexed by // thread's ID. typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals; // Holds the thread id and thread handle that we pass from // StartWatcherThreadFor to WatcherThreadFunc. typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle; static void StartWatcherThreadFor(DWORD thread_id) { // The returned handle will be kept in thread_map and closed by // watcher_thread in WatcherThreadFunc. HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION, FALSE, thread_id); GTEST_CHECK_(thread != NULL); // We need to to pass a valid thread ID pointer into CreateThread for it // to work correctly under Win98. DWORD watcher_thread_id; HANDLE watcher_thread = ::CreateThread( NULL, // Default security. 0, // Default stack size &ThreadLocalRegistryImpl::WatcherThreadFunc, reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)), CREATE_SUSPENDED, &watcher_thread_id); GTEST_CHECK_(watcher_thread != NULL); // Give the watcher thread the same priority as ours to avoid being // blocked by it. ::SetThreadPriority(watcher_thread, ::GetThreadPriority(::GetCurrentThread())); ::ResumeThread(watcher_thread); ::CloseHandle(watcher_thread); } // Monitors exit from a given thread and notifies those // ThreadIdToThreadLocals about thread termination. static DWORD WINAPI WatcherThreadFunc(LPVOID param) { const ThreadIdAndHandle* tah = reinterpret_cast<const ThreadIdAndHandle*>(param); GTEST_CHECK_( ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0); OnThreadExit(tah->first); ::CloseHandle(tah->second); delete tah; return 0; } // Returns map of thread local instances. static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() { mutex_.AssertHeld(); static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals; return map; } // Protects access to GetThreadLocalsMapLocked() and its return value. static Mutex mutex_; // Protects access to GetThreadMapLocked() and its return value. static Mutex thread_map_mutex_; }; Mutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex); Mutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex); ThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread( const ThreadLocalBase* thread_local_instance) { return ThreadLocalRegistryImpl::GetValueOnCurrentThread( thread_local_instance); } void ThreadLocalRegistry::OnThreadLocalDestroyed( const ThreadLocalBase* thread_local_instance) { ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance); } #endif // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS #if GTEST_USES_POSIX_RE // Implements RE. Currently only needed for death tests. RE::~RE() { if (is_valid_) { // regfree'ing an invalid regex might crash because the content // of the regex is undefined. Since the regex's are essentially // the same, one cannot be valid (or invalid) without the other // being so too. regfree(&partial_regex_); regfree(&full_regex_); } free(const_cast<char*>(pattern_)); } // Returns true iff regular expression re matches the entire str. bool RE::FullMatch(const char* str, const RE& re) { if (!re.is_valid_) return false; regmatch_t match; return regexec(&re.full_regex_, str, 1, &match, 0) == 0; } // Returns true iff regular expression re matches a substring of str // (including str itself). bool RE::PartialMatch(const char* str, const RE& re) { if (!re.is_valid_) return false; regmatch_t match; return regexec(&re.partial_regex_, str, 1, &match, 0) == 0; } // Initializes an RE from its string representation. void RE::Init(const char* regex) { pattern_ = posix::StrDup(regex); // Reserves enough bytes to hold the regular expression used for a // full match. const size_t full_regex_len = strlen(regex) + 10; char* const full_pattern = new char[full_regex_len]; snprintf(full_pattern, full_regex_len, "^(%s)$", regex); is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0; // We want to call regcomp(&partial_regex_, ...) even if the // previous expression returns false. Otherwise partial_regex_ may // not be properly initialized can may cause trouble when it's // freed. // // Some implementation of POSIX regex (e.g. on at least some // versions of Cygwin) doesn't accept the empty string as a valid // regex. We change it to an equivalent form "()" to be safe. if (is_valid_) { const char* const partial_regex = (*regex == '\0') ? "()" : regex; is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0; } EXPECT_TRUE(is_valid_) << "Regular expression \"" << regex << "\" is not a valid POSIX Extended regular expression."; delete[] full_pattern; } #elif GTEST_USES_SIMPLE_RE // Returns true iff ch appears anywhere in str (excluding the // terminating '\0' character). bool IsInSet(char ch, const char* str) { return ch != '\0' && strchr(str, ch) != NULL; } // Returns true iff ch belongs to the given classification. Unlike // similar functions in <ctype.h>, these aren't affected by the // current locale. bool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; } bool IsAsciiPunct(char ch) { return IsInSet(ch, "^-!\"#$%&'()*+,./:;<=>?@[\\]_`{|}~"); } bool IsRepeat(char ch) { return IsInSet(ch, "?*+"); } bool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, " \f\n\r\t\v"); } bool IsAsciiWordChar(char ch) { return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ('0' <= ch && ch <= '9') || ch == '_'; } // Returns true iff "\\c" is a supported escape sequence. bool IsValidEscape(char c) { return (IsAsciiPunct(c) || IsInSet(c, "dDfnrsStvwW")); } // Returns true iff the given atom (specified by escaped and pattern) // matches ch. The result is undefined if the atom is invalid. bool AtomMatchesChar(bool escaped, char pattern_char, char ch) { if (escaped) { // "\\p" where p is pattern_char. switch (pattern_char) { case 'd': return IsAsciiDigit(ch); case 'D': return !IsAsciiDigit(ch); case 'f': return ch == '\f'; case 'n': return ch == '\n'; case 'r': return ch == '\r'; case 's': return IsAsciiWhiteSpace(ch); case 'S': return !IsAsciiWhiteSpace(ch); case 't': return ch == '\t'; case 'v': return ch == '\v'; case 'w': return IsAsciiWordChar(ch); case 'W': return !IsAsciiWordChar(ch); } return IsAsciiPunct(pattern_char) && pattern_char == ch; } return (pattern_char == '.' && ch != '\n') || pattern_char == ch; } // Helper function used by ValidateRegex() to format error messages. std::string FormatRegexSyntaxError(const char* regex, int index) { return (Message() << "Syntax error at index " << index << " in simple regular expression \"" << regex << "\": ").GetString(); } // Generates non-fatal failures and returns false if regex is invalid; // otherwise returns true. bool ValidateRegex(const char* regex) { if (regex == NULL) { // TODO(wan@google.com): fix the source file location in the // assertion failures to match where the regex is used in user // code. ADD_FAILURE() << "NULL is not a valid simple regular expression."; return false; } bool is_valid = true; // True iff ?, *, or + can follow the previous atom. bool prev_repeatable = false; for (int i = 0; regex[i]; i++) { if (regex[i] == '\\') { // An escape sequence i++; if (regex[i] == '\0') { ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) << "'\\' cannot appear at the end."; return false; } if (!IsValidEscape(regex[i])) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1) << "invalid escape sequence \"\\" << regex[i] << "\"."; is_valid = false; } prev_repeatable = true; } else { // Not an escape sequence. const char ch = regex[i]; if (ch == '^' && i > 0) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'^' can only appear at the beginning."; is_valid = false; } else if (ch == '$' && regex[i + 1] != '\0') { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'$' can only appear at the end."; is_valid = false; } else if (IsInSet(ch, "()[]{}|")) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch << "' is unsupported."; is_valid = false; } else if (IsRepeat(ch) && !prev_repeatable) { ADD_FAILURE() << FormatRegexSyntaxError(regex, i) << "'" << ch << "' can only follow a repeatable token."; is_valid = false; } prev_repeatable = !IsInSet(ch, "^$?*+"); } } return is_valid; } // Matches a repeated regex atom followed by a valid simple regular // expression. The regex atom is defined as c if escaped is false, // or \c otherwise. repeat is the repetition meta character (?, *, // or +). The behavior is undefined if str contains too many // characters to be indexable by size_t, in which case the test will // probably time out anyway. We are fine with this limitation as // std::string has it too. bool MatchRepetitionAndRegexAtHead( bool escaped, char c, char repeat, const char* regex, const char* str) { const size_t min_count = (repeat == '+') ? 1 : 0; const size_t max_count = (repeat == '?') ? 1 : static_cast<size_t>(-1) - 1; // We cannot call numeric_limits::max() as it conflicts with the // max() macro on Windows. for (size_t i = 0; i <= max_count; ++i) { // We know that the atom matches each of the first i characters in str. if (i >= min_count && MatchRegexAtHead(regex, str + i)) { // We have enough matches at the head, and the tail matches too. // Since we only care about *whether* the pattern matches str // (as opposed to *how* it matches), there is no need to find a // greedy match. return true; } if (str[i] == '\0' || !AtomMatchesChar(escaped, c, str[i])) return false; } return false; } // Returns true iff regex matches a prefix of str. regex must be a // valid simple regular expression and not start with "^", or the // result is undefined. bool MatchRegexAtHead(const char* regex, const char* str) { if (*regex == '\0') // An empty regex matches a prefix of anything. return true; // "$" only matches the end of a string. Note that regex being // valid guarantees that there's nothing after "$" in it. if (*regex == '$') return *str == '\0'; // Is the first thing in regex an escape sequence? const bool escaped = *regex == '\\'; if (escaped) ++regex; if (IsRepeat(regex[1])) { // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so // here's an indirect recursion. It terminates as the regex gets // shorter in each recursion. return MatchRepetitionAndRegexAtHead( escaped, regex[0], regex[1], regex + 2, str); } else { // regex isn't empty, isn't "$", and doesn't start with a // repetition. We match the first atom of regex with the first // character of str and recurse. return (*str != '\0') && AtomMatchesChar(escaped, *regex, *str) && MatchRegexAtHead(regex + 1, str + 1); } } // Returns true iff regex matches any substring of str. regex must be // a valid simple regular expression, or the result is undefined. // // The algorithm is recursive, but the recursion depth doesn't exceed // the regex length, so we won't need to worry about running out of // stack space normally. In rare cases the time complexity can be // exponential with respect to the regex length + the string length, // but usually it's must faster (often close to linear). bool MatchRegexAnywhere(const char* regex, const char* str) { if (regex == NULL || str == NULL) return false; if (*regex == '^') return MatchRegexAtHead(regex + 1, str); // A successful match can be anywhere in str. do { if (MatchRegexAtHead(regex, str)) return true; } while (*str++ != '\0'); return false; } // Implements the RE class. RE::~RE() { free(const_cast<char*>(pattern_)); free(const_cast<char*>(full_pattern_)); } // Returns true iff regular expression re matches the entire str. bool RE::FullMatch(const char* str, const RE& re) { return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str); } // Returns true iff regular expression re matches a substring of str // (including str itself). bool RE::PartialMatch(const char* str, const RE& re) { return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str); } // Initializes an RE from its string representation. void RE::Init(const char* regex) { pattern_ = full_pattern_ = NULL; if (regex != NULL) { pattern_ = posix::StrDup(regex); } is_valid_ = ValidateRegex(regex); if (!is_valid_) { // No need to calculate the full pattern when the regex is invalid. return; } const size_t len = strlen(regex); // Reserves enough bytes to hold the regular expression used for a // full match: we need space to prepend a '^', append a '$', and // terminate the string with '\0'. char* buffer = static_cast<char*>(malloc(len + 3)); full_pattern_ = buffer; if (*regex != '^') *buffer++ = '^'; // Makes sure full_pattern_ starts with '^'. // We don't use snprintf or strncpy, as they trigger a warning when // compiled with VC++ 8.0. memcpy(buffer, regex, len); buffer += len; if (len == 0 || regex[len - 1] != '$') *buffer++ = '$'; // Makes sure full_pattern_ ends with '$'. *buffer = '\0'; } #endif // GTEST_USES_POSIX_RE const char kUnknownFile[] = "unknown file"; // Formats a source file path and a line number as they would appear // in an error message from the compiler used to compile this code. GTEST_API_ ::std::string FormatFileLocation(const char* file, int line) { const std::string file_name(file == NULL ? kUnknownFile : file); if (line < 0) { return file_name + ":"; } #ifdef _MSC_VER return file_name + "(" + StreamableToString(line) + "):"; #else return file_name + ":" + StreamableToString(line) + ":"; #endif // _MSC_VER } // Formats a file location for compiler-independent XML output. // Although this function is not platform dependent, we put it next to // FormatFileLocation in order to contrast the two functions. // Note that FormatCompilerIndependentFileLocation() does NOT append colon // to the file location it produces, unlike FormatFileLocation(). GTEST_API_ ::std::string FormatCompilerIndependentFileLocation( const char* file, int line) { const std::string file_name(file == NULL ? kUnknownFile : file); if (line < 0) return file_name; else return file_name + ":" + StreamableToString(line); } GTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line) : severity_(severity) { const char* const marker = severity == GTEST_INFO ? "[ INFO ]" : severity == GTEST_WARNING ? "[WARNING]" : severity == GTEST_ERROR ? "[ ERROR ]" : "[ FATAL ]"; GetStream() << ::std::endl << marker << " " << FormatFileLocation(file, line).c_str() << ": "; } // Flushes the buffers and, if severity is GTEST_FATAL, aborts the program. GTestLog::~GTestLog() { GetStream() << ::std::endl; if (severity_ == GTEST_FATAL) { fflush(stderr); posix::Abort(); } } // Disable Microsoft deprecation warnings for POSIX functions called from // this class (creat, dup, dup2, and close) GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996) #if GTEST_HAS_STREAM_REDIRECTION // Object that captures an output stream (stdout/stderr). class CapturedStream { public: // The ctor redirects the stream to a temporary file. explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) { # if GTEST_OS_WINDOWS char temp_dir_path[MAX_PATH + 1] = { '\0' }; // NOLINT char temp_file_path[MAX_PATH + 1] = { '\0' }; // NOLINT ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path); const UINT success = ::GetTempFileNameA(temp_dir_path, "gtest_redir", 0, // Generate unique file name. temp_file_path); GTEST_CHECK_(success != 0) << "Unable to create a temporary file in " << temp_dir_path; const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE); GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file " << temp_file_path; filename_ = temp_file_path; # else // There's no guarantee that a test has write access to the current // directory, so we create the temporary file in the /tmp directory // instead. We use /tmp on most systems, and /sdcard on Android. // That's because Android doesn't have /tmp. # if GTEST_OS_LINUX_ANDROID // Note: Android applications are expected to call the framework's // Context.getExternalStorageDirectory() method through JNI to get // the location of the world-writable SD Card directory. However, // this requires a Context handle, which cannot be retrieved // globally from native code. Doing so also precludes running the // code as part of a regular standalone executable, which doesn't // run in a Dalvik process (e.g. when running it through 'adb shell'). // // The location /sdcard is directly accessible from native code // and is the only location (unofficially) supported by the Android // team. It's generally a symlink to the real SD Card mount point // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or // other OEM-customized locations. Never rely on these, and always // use /sdcard. char name_template[] = "/sdcard/gtest_captured_stream.XXXXXX"; # else char name_template[] = "/tmp/captured_stream.XXXXXX"; # endif // GTEST_OS_LINUX_ANDROID const int captured_fd = mkstemp(name_template); filename_ = name_template; # endif // GTEST_OS_WINDOWS fflush(NULL); dup2(captured_fd, fd_); close(captured_fd); } ~CapturedStream() { remove(filename_.c_str()); } std::string GetCapturedString() { if (uncaptured_fd_ != -1) { // Restores the original stream. fflush(NULL); dup2(uncaptured_fd_, fd_); close(uncaptured_fd_); uncaptured_fd_ = -1; } FILE* const file = posix::FOpen(filename_.c_str(), "r"); const std::string content = ReadEntireFile(file); posix::FClose(file); return content; } private: const int fd_; // A stream to capture. int uncaptured_fd_; // Name of the temporary file holding the stderr output. ::std::string filename_; GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream); }; GTEST_DISABLE_MSC_WARNINGS_POP_() static CapturedStream* g_captured_stderr = NULL; static CapturedStream* g_captured_stdout = NULL; // Starts capturing an output stream (stdout/stderr). void CaptureStream(int fd, const char* stream_name, CapturedStream** stream) { if (*stream != NULL) { GTEST_LOG_(FATAL) << "Only one " << stream_name << " capturer can exist at a time."; } *stream = new CapturedStream(fd); } // Stops capturing the output stream and returns the captured string. std::string GetCapturedStream(CapturedStream** captured_stream) { const std::string content = (*captured_stream)->GetCapturedString(); delete *captured_stream; *captured_stream = NULL; return content; } // Starts capturing stdout. void CaptureStdout() { CaptureStream(kStdOutFileno, "stdout", &g_captured_stdout); } // Starts capturing stderr. void CaptureStderr() { CaptureStream(kStdErrFileno, "stderr", &g_captured_stderr); } // Stops capturing stdout and returns the captured string. std::string GetCapturedStdout() { return GetCapturedStream(&g_captured_stdout); } // Stops capturing stderr and returns the captured string. std::string GetCapturedStderr() { return GetCapturedStream(&g_captured_stderr); } #endif // GTEST_HAS_STREAM_REDIRECTION std::string TempDir() { #if GTEST_OS_WINDOWS_MOBILE return "\\temp\\"; #elif GTEST_OS_WINDOWS const char* temp_dir = posix::GetEnv("TEMP"); if (temp_dir == NULL || temp_dir[0] == '\0') return "\\temp\\"; else if (temp_dir[strlen(temp_dir) - 1] == '\\') return temp_dir; else return std::string(temp_dir) + "\\"; #elif GTEST_OS_LINUX_ANDROID return "/sdcard/"; #else return "/tmp/"; #endif // GTEST_OS_WINDOWS_MOBILE } size_t GetFileSize(FILE* file) { fseek(file, 0, SEEK_END); return static_cast<size_t>(ftell(file)); } std::string ReadEntireFile(FILE* file) { const size_t file_size = GetFileSize(file); char* const buffer = new char[file_size]; size_t bytes_last_read = 0; // # of bytes read in the last fread() size_t bytes_read = 0; // # of bytes read so far fseek(file, 0, SEEK_SET); // Keeps reading the file until we cannot read further or the // pre-determined file size is reached. do { bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file); bytes_read += bytes_last_read; } while (bytes_last_read > 0 && bytes_read < file_size); const std::string content(buffer, bytes_read); delete[] buffer; return content; } #if GTEST_HAS_DEATH_TEST static const ::std::vector<testing::internal::string>* g_injected_test_argvs = NULL; // Owned. void SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) { if (g_injected_test_argvs != argvs) delete g_injected_test_argvs; g_injected_test_argvs = argvs; } const ::std::vector<testing::internal::string>& GetInjectableArgvs() { if (g_injected_test_argvs != NULL) { return *g_injected_test_argvs; } return GetArgvs(); } #endif // GTEST_HAS_DEATH_TEST #if GTEST_OS_WINDOWS_MOBILE namespace posix { void Abort() { DebugBreak(); TerminateProcess(GetCurrentProcess(), 1); } } // namespace posix #endif // GTEST_OS_WINDOWS_MOBILE // Returns the name of the environment variable corresponding to the // given flag. For example, FlagToEnvVar("foo") will return // "GTEST_FOO" in the open-source version. static std::string FlagToEnvVar(const char* flag) { const std::string full_flag = (Message() << GTEST_FLAG_PREFIX_ << flag).GetString(); Message env_var; for (size_t i = 0; i != full_flag.length(); i++) { env_var << ToUpper(full_flag.c_str()[i]); } return env_var.GetString(); } // Parses 'str' for a 32-bit signed integer. If successful, writes // the result to *value and returns true; otherwise leaves *value // unchanged and returns false. bool ParseInt32(const Message& src_text, const char* str, Int32* value) { // Parses the environment variable as a decimal integer. char* end = NULL; const long long_value = strtol(str, &end, 10); // NOLINT // Has strtol() consumed all characters in the string? if (*end != '\0') { // No - an invalid character was encountered. Message msg; msg << "WARNING: " << src_text << " is expected to be a 32-bit integer, but actually" << " has value \"" << str << "\".\n"; printf("%s", msg.GetString().c_str()); fflush(stdout); return false; } // Is the parsed value in the range of an Int32? const Int32 result = static_cast<Int32>(long_value); if (long_value == LONG_MAX || long_value == LONG_MIN || // The parsed value overflows as a long. (strtol() returns // LONG_MAX or LONG_MIN when the input overflows.) result != long_value // The parsed value overflows as an Int32. ) { Message msg; msg << "WARNING: " << src_text << " is expected to be a 32-bit integer, but actually" << " has value " << str << ", which overflows.\n"; printf("%s", msg.GetString().c_str()); fflush(stdout); return false; } *value = result; return true; } // Reads and returns the Boolean environment variable corresponding to // the given flag; if it's not set, returns default_value. // // The value is considered true iff it's not "0". bool BoolFromGTestEnv(const char* flag, bool default_value) { #if defined(GTEST_GET_BOOL_FROM_ENV_) return GTEST_GET_BOOL_FROM_ENV_(flag, default_value); #endif // defined(GTEST_GET_BOOL_FROM_ENV_) const std::string env_var = FlagToEnvVar(flag); const char* const string_value = posix::GetEnv(env_var.c_str()); return string_value == NULL ? default_value : strcmp(string_value, "0") != 0; } // Reads and returns a 32-bit integer stored in the environment // variable corresponding to the given flag; if it isn't set or // doesn't represent a valid 32-bit integer, returns default_value. Int32 Int32FromGTestEnv(const char* flag, Int32 default_value) { #if defined(GTEST_GET_INT32_FROM_ENV_) return GTEST_GET_INT32_FROM_ENV_(flag, default_value); #endif // defined(GTEST_GET_INT32_FROM_ENV_) const std::string env_var = FlagToEnvVar(flag); const char* const string_value = posix::GetEnv(env_var.c_str()); if (string_value == NULL) { // The environment variable is not set. return default_value; } Int32 result = default_value; if (!ParseInt32(Message() << "Environment variable " << env_var, string_value, &result)) { printf("The default value %s is used.\n", (Message() << default_value).GetString().c_str()); fflush(stdout); return default_value; } return result; } // Reads and returns the string environment variable corresponding to // the given flag; if it's not set, returns default_value. std::string StringFromGTestEnv(const char* flag, const char* default_value) { #if defined(GTEST_GET_STRING_FROM_ENV_) return GTEST_GET_STRING_FROM_ENV_(flag, default_value); #endif // defined(GTEST_GET_STRING_FROM_ENV_) const std::string env_var = FlagToEnvVar(flag); const char* value = posix::GetEnv(env_var.c_str()); if (value != NULL) { return value; } // As a special case for the 'output' flag, if GTEST_OUTPUT is not // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build // system. The value of XML_OUTPUT_FILE is a filename without the // "xml:" prefix of GTEST_OUTPUT. // // The net priority order after flag processing is thus: // --gtest_output command line flag // GTEST_OUTPUT environment variable // XML_OUTPUT_FILE environment variable // 'default_value' if (strcmp(flag, "output") == 0) { value = posix::GetEnv("XML_OUTPUT_FILE"); if (value != NULL) { return std::string("xml:") + value; } } return default_value; } } // namespace internal } // namespace testing // Copyright 2007, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) // Google Test - The Google C++ Testing Framework // // This file implements a universal value printer that can print a // value of any type T: // // void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr); // // It uses the << operator when possible, and prints the bytes in the // object otherwise. A user can override its behavior for a class // type Foo by defining either operator<<(::std::ostream&, const Foo&) // or void PrintTo(const Foo&, ::std::ostream*) in the namespace that // defines Foo. #include <ctype.h> #include <stdio.h> #include <cwchar> #include <ostream> // NOLINT #include <string> namespace testing { namespace { using ::std::ostream; // Prints a segment of bytes in the given object. GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ void PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start, size_t count, ostream* os) { char text[5] = ""; for (size_t i = 0; i != count; i++) { const size_t j = start + i; if (i != 0) { // Organizes the bytes into groups of 2 for easy parsing by // human. if ((j % 2) == 0) *os << ' '; else *os << '-'; } GTEST_SNPRINTF_(text, sizeof(text), "%02X", obj_bytes[j]); *os << text; } } // Prints the bytes in the given value to the given ostream. void PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count, ostream* os) { // Tells the user how big the object is. *os << count << "-byte object <"; const size_t kThreshold = 132; const size_t kChunkSize = 64; // If the object size is bigger than kThreshold, we'll have to omit // some details by printing only the first and the last kChunkSize // bytes. // TODO(wan): let the user control the threshold using a flag. if (count < kThreshold) { PrintByteSegmentInObjectTo(obj_bytes, 0, count, os); } else { PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os); *os << " ... "; // Rounds up to 2-byte boundary. const size_t resume_pos = (count - kChunkSize + 1)/2*2; PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os); } *os << ">"; } } // namespace namespace internal2 { // Delegates to PrintBytesInObjectToImpl() to print the bytes in the // given object. The delegation simplifies the implementation, which // uses the << operator and thus is easier done outside of the // ::testing::internal namespace, which contains a << operator that // sometimes conflicts with the one in STL. void PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count, ostream* os) { PrintBytesInObjectToImpl(obj_bytes, count, os); } } // namespace internal2 namespace internal { // Depending on the value of a char (or wchar_t), we print it in one // of three formats: // - as is if it's a printable ASCII (e.g. 'a', '2', ' '), // - as a hexidecimal escape sequence (e.g. '\x7F'), or // - as a special escape sequence (e.g. '\r', '\n'). enum CharFormat { kAsIs, kHexEscape, kSpecialEscape }; // Returns true if c is a printable ASCII character. We test the // value of c directly instead of calling isprint(), which is buggy on // Windows Mobile. inline bool IsPrintableAscii(wchar_t c) { return 0x20 <= c && c <= 0x7E; } // Prints a wide or narrow char c as a character literal without the // quotes, escaping it when necessary; returns how c was formatted. // The template argument UnsignedChar is the unsigned version of Char, // which is the type of c. template <typename UnsignedChar, typename Char> static CharFormat PrintAsCharLiteralTo(Char c, ostream* os) { switch (static_cast<wchar_t>(c)) { case L'\0': *os << "\\0"; break; case L'\'': *os << "\\'"; break; case L'\\': *os << "\\\\"; break; case L'\a': *os << "\\a"; break; case L'\b': *os << "\\b"; break; case L'\f': *os << "\\f"; break; case L'\n': *os << "\\n"; break; case L'\r': *os << "\\r"; break; case L'\t': *os << "\\t"; break; case L'\v': *os << "\\v"; break; default: if (IsPrintableAscii(c)) { *os << static_cast<char>(c); return kAsIs; } else { *os << "\\x" + String::FormatHexInt(static_cast<UnsignedChar>(c)); return kHexEscape; } } return kSpecialEscape; } // Prints a wchar_t c as if it's part of a string literal, escaping it when // necessary; returns how c was formatted. static CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) { switch (c) { case L'\'': *os << "'"; return kAsIs; case L'"': *os << "\\\""; return kSpecialEscape; default: return PrintAsCharLiteralTo<wchar_t>(c, os); } } // Prints a char c as if it's part of a string literal, escaping it when // necessary; returns how c was formatted. static CharFormat PrintAsStringLiteralTo(char c, ostream* os) { return PrintAsStringLiteralTo( static_cast<wchar_t>(static_cast<unsigned char>(c)), os); } // Prints a wide or narrow character c and its code. '\0' is printed // as "'\\0'", other unprintable characters are also properly escaped // using the standard C++ escape sequence. The template argument // UnsignedChar is the unsigned version of Char, which is the type of c. template <typename UnsignedChar, typename Char> void PrintCharAndCodeTo(Char c, ostream* os) { // First, print c as a literal in the most readable form we can find. *os << ((sizeof(c) > 1) ? "L'" : "'"); const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os); *os << "'"; // To aid user debugging, we also print c's code in decimal, unless // it's 0 (in which case c was printed as '\\0', making the code // obvious). if (c == 0) return; *os << " (" << static_cast<int>(c); // For more convenience, we print c's code again in hexidecimal, // unless c was already printed in the form '\x##' or the code is in // [1, 9]. if (format == kHexEscape || (1 <= c && c <= 9)) { // Do nothing. } else { *os << ", 0x" << String::FormatHexInt(static_cast<UnsignedChar>(c)); } *os << ")"; } void PrintTo(unsigned char c, ::std::ostream* os) { PrintCharAndCodeTo<unsigned char>(c, os); } void PrintTo(signed char c, ::std::ostream* os) { PrintCharAndCodeTo<unsigned char>(c, os); } // Prints a wchar_t as a symbol if it is printable or as its internal // code otherwise and also as its code. L'\0' is printed as "L'\\0'". void PrintTo(wchar_t wc, ostream* os) { PrintCharAndCodeTo<wchar_t>(wc, os); } // Prints the given array of characters to the ostream. CharType must be either // char or wchar_t. // The array starts at begin, the length is len, it may include '\0' characters // and may not be NUL-terminated. template <typename CharType> GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static void PrintCharsAsStringTo( const CharType* begin, size_t len, ostream* os) { const char* const kQuoteBegin = sizeof(CharType) == 1 ? "\"" : "L\""; *os << kQuoteBegin; bool is_previous_hex = false; for (size_t index = 0; index < len; ++index) { const CharType cur = begin[index]; if (is_previous_hex && IsXDigit(cur)) { // Previous character is of '\x..' form and this character can be // interpreted as another hexadecimal digit in its number. Break string to // disambiguate. *os << "\" " << kQuoteBegin; } is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape; } *os << "\""; } // Prints a (const) char/wchar_t array of 'len' elements, starting at address // 'begin'. CharType must be either char or wchar_t. template <typename CharType> GTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_ GTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_ GTEST_ATTRIBUTE_NO_SANITIZE_THREAD_ static void UniversalPrintCharArray( const CharType* begin, size_t len, ostream* os) { // The code // const char kFoo[] = "foo"; // generates an array of 4, not 3, elements, with the last one being '\0'. // // Therefore when printing a char array, we don't print the last element if // it's '\0', such that the output matches the string literal as it's // written in the source code. if (len > 0 && begin[len - 1] == '\0') { PrintCharsAsStringTo(begin, len - 1, os); return; } // If, however, the last element in the array is not '\0', e.g. // const char kFoo[] = { 'f', 'o', 'o' }; // we must print the entire array. We also print a message to indicate // that the array is not NUL-terminated. PrintCharsAsStringTo(begin, len, os); *os << " (no terminating NUL)"; } // Prints a (const) char array of 'len' elements, starting at address 'begin'. void UniversalPrintArray(const char* begin, size_t len, ostream* os) { UniversalPrintCharArray(begin, len, os); } // Prints a (const) wchar_t array of 'len' elements, starting at address // 'begin'. void UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) { UniversalPrintCharArray(begin, len, os); } // Prints the given C string to the ostream. void PrintTo(const char* s, ostream* os) { if (s == NULL) { *os << "NULL"; } else { *os << ImplicitCast_<const void*>(s) << " pointing to "; PrintCharsAsStringTo(s, strlen(s), os); } } // MSVC compiler can be configured to define whar_t as a typedef // of unsigned short. Defining an overload for const wchar_t* in that case // would cause pointers to unsigned shorts be printed as wide strings, // possibly accessing more memory than intended and causing invalid // memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when // wchar_t is implemented as a native type. #if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED) // Prints the given wide C string to the ostream. void PrintTo(const wchar_t* s, ostream* os) { if (s == NULL) { *os << "NULL"; } else { *os << ImplicitCast_<const void*>(s) << " pointing to "; PrintCharsAsStringTo(s, std::wcslen(s), os); } } #endif // wchar_t is native // Prints a ::string object. #if GTEST_HAS_GLOBAL_STRING void PrintStringTo(const ::string& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } #endif // GTEST_HAS_GLOBAL_STRING void PrintStringTo(const ::std::string& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } // Prints a ::wstring object. #if GTEST_HAS_GLOBAL_WSTRING void PrintWideStringTo(const ::wstring& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } #endif // GTEST_HAS_GLOBAL_WSTRING #if GTEST_HAS_STD_WSTRING void PrintWideStringTo(const ::std::wstring& s, ostream* os) { PrintCharsAsStringTo(s.data(), s.size(), os); } #endif // GTEST_HAS_STD_WSTRING } // namespace internal } // namespace testing // Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: mheule@google.com (Markus Heule) // // The Google C++ Testing Framework (Google Test) // Indicates that this translation unit is part of Google Test's // implementation. It must come before gtest-internal-inl.h is // included, or there will be a compiler error. This trick exists to // prevent the accidental inclusion of gtest-internal-inl.h in the // user's code. #define GTEST_IMPLEMENTATION_ 1 #undef GTEST_IMPLEMENTATION_ namespace testing { using internal::GetUnitTestImpl; // Gets the summary of the failure message by omitting the stack trace // in it. std::string TestPartResult::ExtractSummary(const char* message) { const char* const stack_trace = strstr(message, internal::kStackTraceMarker); return stack_trace == NULL ? message : std::string(message, stack_trace); } // Prints a TestPartResult object. std::ostream& operator<<(std::ostream& os, const TestPartResult& result) { return os << result.file_name() << ":" << result.line_number() << ": " << (result.type() == TestPartResult::kSuccess ? "Success" : result.type() == TestPartResult::kFatalFailure ? "Fatal failure" : "Non-fatal failure") << ":\n" << result.message() << std::endl; } // Appends a TestPartResult to the array. void TestPartResultArray::Append(const TestPartResult& result) { array_.push_back(result); } // Returns the TestPartResult at the given index (0-based). const TestPartResult& TestPartResultArray::GetTestPartResult(int index) const { if (index < 0 || index >= size()) { printf("\nInvalid index (%d) into TestPartResultArray.\n", index); internal::posix::Abort(); } return array_[index]; } // Returns the number of TestPartResult objects in the array. int TestPartResultArray::size() const { return static_cast<int>(array_.size()); } namespace internal { HasNewFatalFailureHelper::HasNewFatalFailureHelper() : has_new_fatal_failure_(false), original_reporter_(GetUnitTestImpl()-> GetTestPartResultReporterForCurrentThread()) { GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this); } HasNewFatalFailureHelper::~HasNewFatalFailureHelper() { GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread( original_reporter_); } void HasNewFatalFailureHelper::ReportTestPartResult( const TestPartResult& result) { if (result.fatally_failed()) has_new_fatal_failure_ = true; original_reporter_->ReportTestPartResult(result); } } // namespace internal } // namespace testing // Copyright 2008 Google Inc. // All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Author: wan@google.com (Zhanyong Wan) namespace testing { namespace internal { #if GTEST_HAS_TYPED_TEST_P // Skips to the first non-space char in str. Returns an empty string if str // contains only whitespace characters. static const char* SkipSpaces(const char* str) { while (IsSpace(*str)) str++; return str; } static std::vector<std::string> SplitIntoTestNames(const char* src) { std::vector<std::string> name_vec; src = SkipSpaces(src); for (; src != NULL; src = SkipComma(src)) { name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src))); } return name_vec; } // Verifies that registered_tests match the test names in // registered_tests_; returns registered_tests if successful, or // aborts the program otherwise. const char* TypedTestCasePState::VerifyRegisteredTestNames( const char* file, int line, const char* registered_tests) { typedef RegisteredTestsMap::const_iterator RegisteredTestIter; registered_ = true; std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests); Message errors; std::set<std::string> tests; for (std::vector<std::string>::const_iterator name_it = name_vec.begin(); name_it != name_vec.end(); ++name_it) { const std::string& name = *name_it; if (tests.count(name) != 0) { errors << "Test " << name << " is listed more than once.\n"; continue; } bool found = false; for (RegisteredTestIter it = registered_tests_.begin(); it != registered_tests_.end(); ++it) { if (name == it->first) { found = true; break; } } if (found) { tests.insert(name); } else { errors << "No test named " << name << " can be found in this test case.\n"; } } for (RegisteredTestIter it = registered_tests_.begin(); it != registered_tests_.end(); ++it) { if (tests.count(it->first) == 0) { errors << "You forgot to list test " << it->first << ".\n"; } } const std::string& errors_str = errors.GetString(); if (errors_str != "") { fprintf(stderr, "%s %s", FormatFileLocation(file, line).c_str(), errors_str.c_str()); fflush(stderr); posix::Abort(); } return registered_tests; } #endif // GTEST_HAS_TYPED_TEST_P } // namespace internal } // namespace testing
CQMP/Maxent
test/gtest-all.cc
C++
gpl-2.0
381,270
[ 30522, 1013, 1013, 9385, 2263, 1010, 8224, 4297, 1012, 1013, 1013, 2035, 2916, 9235, 1012, 1013, 1013, 1013, 1013, 25707, 1998, 2224, 1999, 3120, 1998, 12441, 3596, 1010, 2007, 2030, 2302, 1013, 1013, 14080, 1010, 30524, 9279, 1996, 2682, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
jsonp({"cep":"89254296","logradouro":"Rua Paulina Bortolini Vieira","bairro":"Rau","cidade":"Jaragu\u00e1 do Sul","uf":"SC","estado":"Santa Catarina"});
lfreneda/cepdb
api/v1/89254296.jsonp.js
JavaScript
cc0-1.0
153
[ 30522, 1046, 3385, 2361, 1006, 1063, 1000, 8292, 2361, 1000, 1024, 1000, 6486, 17788, 20958, 2683, 2575, 1000, 1010, 1000, 8833, 12173, 8162, 2080, 1000, 1024, 1000, 21766, 2050, 2703, 3981, 8945, 5339, 18861, 2072, 20098, 7895, 1000, 1010,...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Pixeez.Objects { public class UsersFavoriteWork { [JsonProperty("id")] public long? Id { get; set; } [JsonProperty("comment")] public string Comment { get; set; } [JsonProperty("tags")] public IList<string> Tags { get; set; } [JsonProperty("publicity")] public string Publicity { get; set; } [JsonProperty("work")] public Work Work { get; set; } } public class NewIllustration { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("image_urls")] public Dictionary<string, string> ImageUrls { get; set; } [JsonProperty("caption")] public string Caption { get; set; } [JsonProperty("restrict")] public int Restrict { get; set; } [JsonProperty("user")] public User ArtistUser { get; set; } [JsonProperty("tags")] public List<Tag> Tags { get; set; } [JsonProperty("tools")] public List<string> Tools { get; set; } [JsonProperty("create_date")] public DateTime Created { get; set; } [JsonProperty("page_count")] public int PageCount { get; set; } [JsonProperty("width")] public int Width { get; set; } [JsonProperty("height")] public int Height { get; set; } [JsonProperty("sanity_level")] public int SanityLevel { get; set; } [JsonProperty("series")] public object Series { get; set; } [JsonProperty("meta_single_page")] public Dictionary<string, string> MetaSinglePage { get; set; } [JsonProperty("meta_pages")] public List<object> MetaPages { get; set; } [JsonProperty("total_view")] public int TotalViews { get; set; } [JsonProperty("total_bookmarks")] public int TotalBookmarks { get; set; } [JsonProperty("is_bookmarked")] public bool IsBookmarked { get; set; } [JsonProperty("visible")] public bool Visible { get; set; } [JsonProperty("is_muted")] public bool Muted { get; set; } public Work GetWork() { var w = new Work() { Id = Id, PageCount = PageCount, TagsNew = Tags, Restrict = Restrict, IsBookmarked = IsBookmarked, Title = Title, Caption = Caption, CreatedTime = Created, Height = Height, Width = Width, ImageUrls = new ImageUrls() { Large = ImageUrls["large"], Original = ImageUrls["large"], Medium = ImageUrls["medium"], SquareMedium = ImageUrls["square_medium"] }, Type = Type, Stats = new WorkStats() { Score = this.TotalBookmarks, ViewsCount = this.TotalViews }, User = ArtistUser }; return w; } } }
CryADsisAM/CryPixiv
Pixeez/Objects/UsersFavoriteWork.cs
C#
mit
3,424
[ 30522, 2478, 8446, 6499, 6199, 1012, 1046, 3385, 1025, 2478, 2291, 1025, 2478, 2291, 1012, 6407, 1012, 12391, 1025, 2478, 2291, 1012, 11409, 4160, 1025, 2478, 2291, 1012, 3793, 1025, 2478, 2291, 1012, 11689, 2075, 1012, 8518, 1025, 3415, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
-- -- Notion statusbar module configuration file -- -- Create a statusbar mod_statusbar.create{ -- First screen, bottom left corner screen=0, pos='bl', -- Set this to true if you want a full-width statusbar fullsize=true, -- Swallow systray windows systray=true, -- Template. Tokens %string are replaced with the value of the -- corresponding meter. Currently supported meters are: -- date date -- load load average (1min, 5min, 15min) -- load_Nmin N minute load average (N=1, 5, 15) -- mail_new mail count (mbox format file $MAIL) -- mail_unread mail count -- mail_total mail count -- mail_*_new mail count (from an alternate mail folder, see below) -- mail_*_unread mail count -- mail_*_total mail count -- -- Space preceded by % adds stretchable space for alignment of variable -- meter value widths. > before meter name aligns right using this -- stretchable space , < left, and | centers. -- Meter values may be zero-padded to a width preceding the meter name. -- These alignment and padding specifiers and the meter name may be -- enclosed in braces {}. -- -- %filler causes things on the marker's sides to be aligned left and -- right, respectively, and %systray is a placeholder for system tray -- windows and icons. -- template="[ %wsname_fullall ] [ %load ] %filler %netmon %date %systray", --template="[ %date || load:% %>load || mail:% %>mail_new/%>mail_total ] %filler%systray", --template="[ %date || load: %05load_1min || mail: %02mail_new/%02mail_total ] %filler%systray", } -- Launch ion-statusd. This must be done after creating any statusbars -- for necessary statusd modules to be parsed from the templates. mod_statusbar.launch_statusd{ -- Date meter date={ -- ISO-8601 date format with additional abbreviated day name date_format='%a %Y-%m-%d %I:%M:%S %p', -- Finnish etc. date format --date_format='%a %d.%m.%Y %H:%M', -- Locale date format (usually shows seconds, which would require -- updating rather often and can be distracting) --date_format='%c', -- Additional date formats. --[[ formats={ time = '%H:%M', -- %date_time } --]] }, -- Load meter load={ --update_interval=10*1000, --important_threshold=1.5, --critical_threshold=4.0, }, -- Mail meter -- -- To monitor more mbox files, add them to the files table. For -- example, add mail_work_new and mail_junk_new to the template -- above, and define them in the files table: -- -- files = { work = "/path/to/work_email", junk = "/path/to/junk" } -- -- Don't use the keyword 'spool' as it's reserved for mbox. mail={ --update_interval=60*1000, --mbox=os.getenv("MAIL"), --files={}, }, -- ifstat ifstat={ program = 'date', }, }
Mariappan/rcfiles
home/.notion/cfg_statusbar.lua
Lua
gpl-2.0
3,051
[ 30522, 1011, 1011, 1011, 1011, 9366, 3570, 8237, 11336, 9563, 5371, 1011, 1011, 1011, 1011, 3443, 1037, 3570, 8237, 16913, 1035, 3570, 8237, 1012, 3443, 1063, 1011, 1011, 2034, 3898, 1010, 3953, 2187, 3420, 3898, 1027, 1014, 1010, 13433, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>exceptions: Not compatible</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.11.2 / exceptions - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> exceptions <small> 8.9.0 <span class="label label-info">Not compatible</span> </small> </h1> <p><em><script>document.write(moment("2020-09-11 16:27:45 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-09-11 16:27:45 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.11.2 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/exceptions&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/Exceptions&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: exceptions&quot; &quot;keyword: continuations&quot; &quot;category: Computer Science/Semantics and Compilation/Semantics&quot; ] authors: [ &quot;Pierre Castéran&quot; ] bug-reports: &quot;https://github.com/coq-contribs/exceptions/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/exceptions.git&quot; synopsis: &quot;Pro[gramm,v]ing with continuations:A development in Coq&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/exceptions/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=9e283687f9337ae021f0b8bf0ea7377e&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-exceptions.8.9.0 coq.8.11.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.2). The following dependencies couldn&#39;t be met: - coq-exceptions -&gt; coq &lt; 8.10~ -&gt; ocaml &lt; 4.03.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-exceptions.8.9.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.05.0-2.0.6/released/8.11.2/exceptions/8.9.0.html
HTML
mit
6,818
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 11374, 1027, 1000, 4372, 1000, 1028, 1026, 2132, 1028, 1026, 18804, 25869, 13462, 1027, 1000, 21183, 2546, 1011, 1022, 1000, 1028, 1026, 18804, 2171, 1027, 1000, 3193, 6442, 1000, 418...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (C) 2006 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ /* * Description: This test just creates a file and have it * extended by the child process. * * This test has no cluster relevance. * * Author : Mark Fasheh * */ #include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <sys/wait.h> #include <stdlib.h> #define DO_FSYNC #define PROGNAME "extend_and_write" #define PRINTERR(err) \ printf("[%d] Error %d (Line %d, Function \"%s\"): \"%s\"\n", \ getpid(), err, __LINE__, __FUNCTION__, strerror(err)) #define SZ 1024 #define NUMWRITES 10240 int count; static void Usage() { printf("\nUsage: %s -h -f <filename> [-s <extend size>]" " [-n <numwrites>]\n", PROGNAME); printf("will create and extend a file, n times.\n\n" "<extend size> Size of the extend (Default=1024)\n" "<numwrites> Number of writes to be performed " "(Default=10240).\n"); exit(1); } int main(int argc, char **argv) { int status = 0; int fd; char filename[256] = "/tmp/extend_and_write.txt"; int off_t = SZ; int loops = NUMWRITES; pid_t pid; // off_t len = SZ; int i, c; if (argc == 1) { Usage(); } opterr = 0; count = argc; while ((c = getopt(argc, argv, ":h:f:s:n:H:-:")) != EOF) { switch (c) { case 'h': Usage(); break; case 'H': Usage(); break; case '-': if (!strcmp(optarg, "help")) Usage(); else { fprintf(stderr, "%s: Invalid option: " "\'--%s\'\n", PROGNAME, optarg); return -EINVAL; } case 'f': snprintf(filename,255,"%s",optarg); if ((*filename == '-')) { fprintf(stderr, "%s: Invalid file name: %s\n", PROGNAME, optarg); return -EINVAL; } break; case 'n': loops = atoi(optarg); if (!loops) { fprintf(stderr, "%s: Invalid numwrites: %s\n", PROGNAME, optarg); return -EINVAL; } break; case 's': off_t = atoi(optarg); if (!off_t) { fprintf(stderr, "%s: Invalid extend size: %s\n", PROGNAME, optarg); return -EINVAL; } break; default: Usage(); break; } } char buffer[off_t]; printf("%s: File will be %d bytes after this run\n", PROGNAME, (2 * off_t * loops)); fd = open(filename, O_CREAT|O_TRUNC|O_RDWR|O_APPEND, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); if (fd == -1) { status = errno; PRINTERR(status); goto bail; } pid = fork(); /* ok, the parent will do the writing, the child the extending */ /* actually, maybe at first they'll both write */ if (pid) { printf("%s: Parent process starting.\n", PROGNAME); memset(buffer, 'A', off_t); for (i = 0; i < loops; i++) { status = write(fd, buffer, off_t); if (status < 0) { PRINTERR(status); goto bail; } if (status != off_t) { printf("%s: (%d) Short write! size = %d," " i=%d\n", PROGNAME, getpid(), status, i); status = 0; goto bail; } // usleep(15); #ifdef DO_FSYNC fsync(fd); #endif } waitpid(pid, NULL, 0); printf("%s: Parent process exiting.\n", PROGNAME); } else { printf("%s: Child process starting.\n", PROGNAME); memset(buffer, 'B', off_t); for (i = 0; i < loops; i++) { status = write(fd, buffer, off_t); if (status < 0) { PRINTERR(status); goto bail; } if (status != off_t) { printf("%s: (%d) Short write! size = %d, " "i=%d\n", PROGNAME, getpid(), status, i); status = 0; goto bail; } // usleep(15); #ifdef DO_FSYNC fsync(fd); #endif } printf("%s: Child process exiting.\n", PROGNAME); } bail: return(status); }
renzhengeek/ocfs2-test
programs/extend_and_write/extend_and_write.c
C
gpl-2.0
4,368
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2294, 14721, 1012, 2035, 2916, 9235, 1012, 1008, 1008, 2023, 2565, 2003, 2489, 4007, 1025, 2017, 2064, 2417, 2923, 3089, 8569, 2618, 2009, 1998, 1013, 2030, 1008, 19933, 2009, 2104, 1996, 3...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# nyc-subway-finder Text-based interface for finding real-time data about New York City subway train arrivals on the 1, 2, 3, 4, 5, 6, and S lines # Requirements: cImage module google.transit module - can be installed using pip: > pip install --upgrade gtfs-realtime-bindings # Description: Subway Finder is a program that takes real-time information from the Metro Transit Authority (MTA) of New York City and converts it into a user-friendly format. The MTA uses the GTFS-realtime protocol to transmit data on train times and stops. To launch the program, run the nyc-subway-finder.py file. # Features: - Allows you to search in real time for New York City subway trains on the 1, 2, 3, 4, 5, 6, and S lines - Simple prompts to help the user find which train they are looking for - When the user input matches more than one station, the user can pick from a list of possible stations - Provides the option to search again or quit after each search # Detailed program breakdown: Our program is based on the Model-View-Controller system. Our model, contained mostly in train.py, is the back end of our program, and contains a class called Train that has all the properties we want the "trains" to have: direction, stops, and arrival time. Each of those abilites is contained inside a method of the class. Our controller is the function that calls our other programs and holds the information until it is displayed to the user. The controller is the program that accesses the real-time feed, passes it onto the model, and coordinates the exchange of information between the model and the view program. The controller contains the functions that allow user input to be non-specific, using regular expression methods to match user inputs to official station names. Finally, our view is the interfaces.py program that puts all of the information out there for the user to see. It consists of a TextInterface class, which contains code that aks for and receives user input and passes it back to the controller. This class also has methods for asking the user whether they want to do another search or exit the program.
simonbr73/nyc-subway-finder
README.md
Markdown
mit
2,123
[ 30522, 1001, 16392, 1011, 10798, 1011, 2424, 2121, 3793, 1011, 2241, 8278, 2005, 4531, 2613, 1011, 2051, 2951, 2055, 2047, 2259, 2103, 10798, 3345, 25470, 2006, 1996, 1015, 1010, 1016, 1010, 1017, 1010, 1018, 1010, 1019, 1010, 1020, 1010, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
jsonp({"cep":"39402235","logradouro":"Rua Jo\u00e3o Paulo I","bairro":"Francisco Peres I","cidade":"Montes Claros","uf":"MG","estado":"Minas Gerais"});
lfreneda/cepdb
api/v1/39402235.jsonp.js
JavaScript
cc0-1.0
152
[ 30522, 1046, 3385, 2361, 1006, 1063, 1000, 8292, 2361, 1000, 1024, 1000, 4464, 12740, 19317, 19481, 1000, 1010, 1000, 8833, 12173, 8162, 2080, 1000, 1024, 1000, 21766, 2050, 8183, 1032, 1057, 8889, 2063, 2509, 2080, 9094, 1045, 1000, 1010, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
import 'element-behaviors' import {reactive, autorun, stringAttribute} from '@lume/element' import {FBXLoader} from 'three/examples/jsm/loaders/FBXLoader.js' import {disposeObjectTree} from '../../utils/three.js' import {Events} from '../../core/Events.js' import {RenderableBehavior} from '../RenderableBehavior.js' import type {StopFunction} from '@lume/element' import type {Group} from 'three/src/objects/Group.js' export type FbxModelBehaviorAttributes = 'src' @reactive export class FbxModelBehavior extends RenderableBehavior { /** Path to a .fbx file. */ @stringAttribute('') src = '' loader?: FBXLoader model?: Group static _observedProperties = ['src', ...(RenderableBehavior._observedProperties || [])] // This is incremented any time we need a pending load() to cancel (f.e. on // src change, or unloadGL cycle), so that the loader will ignore the // result when a version change has happened. #version = 0 #stopFns: StopFunction[] = [] loadGL() { if (!super.loadGL()) return false this.loader = new FBXLoader() this.#stopFns.push( autorun(() => { this.src this.#cleanupModel() this.#version++ this.#loadModel() }), ) return true } unloadGL() { if (!super.unloadGL()) return false for (const stop of this.#stopFns) stop() this.#stopFns.length = 0 this.loader = undefined this.#cleanupModel() // Increment this in case the loader is still loading, so it will ignore the result. this.#version++ return true } #cleanupModel() { if (this.model) disposeObjectTree(this.model) this.model = undefined } #loadModel() { const {src} = this const version = this.#version if (!src) return // In the following fbxLoader.load() callbacks, if __version doesn't // match, it means this.src or this.dracoDecoder changed while // a previous model was loading, in which case we ignore that // result and wait for the next model to load. this.loader!.load( src, model => version === this.#version && this.#setModel(model), progress => version === this.#version && this.element.emit(Events.PROGRESS, progress), error => version === this.#version && this.#onError(error), ) } #onError(error: ErrorEvent) { const message = `Failed to load ${this.element.tagName.toLowerCase()} with src "${ this.src }". See the following error.` console.warn(message) const err = error instanceof ErrorEvent && error.error ? error.error : error console.error(err) this.element.emit(Events.MODEL_ERROR, err) } #setModel(model: Group) { this.model = model this.element.three.add(model) this.element.emit(Events.MODEL_LOAD, {format: 'fbx', model}) this.element.needsUpdate() } } if (!elementBehaviors.has('fbx-model')) elementBehaviors.define('fbx-model', FbxModelBehavior)
trusktr/infamous
packages/lume/src/behaviors/models/FbxModelBehavior.ts
TypeScript
mit
2,797
[ 30522, 12324, 1005, 5783, 1011, 15592, 1005, 12324, 1063, 22643, 1010, 8285, 15532, 1010, 5164, 19321, 3089, 8569, 2618, 1065, 2013, 1005, 1030, 11320, 4168, 1013, 5783, 1005, 12324, 1063, 1042, 2497, 2595, 11066, 2121, 1065, 2013, 1005, 20...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.9 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package org.doubango.tinyWRAP; public class CallSession extends InviteSession { private long swigCPtr; protected CallSession(long cPtr, boolean cMemoryOwn) { super(tinyWRAPJNI.CallSession_SWIGUpcast(cPtr), cMemoryOwn); swigCPtr = cPtr; } protected static long getCPtr(CallSession obj) { return (obj == null) ? 0 : obj.swigCPtr; } protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; tinyWRAPJNI.delete_CallSession(swigCPtr); } swigCPtr = 0; } super.delete(); } public CallSession(SipStack pStack) { this(tinyWRAPJNI.new_CallSession(SipStack.getCPtr(pStack), pStack), true); } public boolean callAudio(String remoteUriString, ActionConfig config) { return tinyWRAPJNI.CallSession_callAudio__SWIG_0(swigCPtr, this, remoteUriString, ActionConfig.getCPtr(config), config); } public boolean callAudio(String remoteUriString) { return tinyWRAPJNI.CallSession_callAudio__SWIG_1(swigCPtr, this, remoteUriString); } public boolean callAudio(SipUri remoteUri, ActionConfig config) { return tinyWRAPJNI.CallSession_callAudio__SWIG_2(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri, ActionConfig.getCPtr(config), config); } public boolean callAudio(SipUri remoteUri) { return tinyWRAPJNI.CallSession_callAudio__SWIG_3(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri); } public boolean callAudioVideo(String remoteUriString, ActionConfig config) { return tinyWRAPJNI.CallSession_callAudioVideo__SWIG_0(swigCPtr, this, remoteUriString, ActionConfig.getCPtr(config), config); } public boolean callAudioVideo(String remoteUriString) { return tinyWRAPJNI.CallSession_callAudioVideo__SWIG_1(swigCPtr, this, remoteUriString); } public boolean callAudioVideo(SipUri remoteUri, ActionConfig config) { return tinyWRAPJNI.CallSession_callAudioVideo__SWIG_2(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri, ActionConfig.getCPtr(config), config); } public boolean callAudioVideo(SipUri remoteUri) { return tinyWRAPJNI.CallSession_callAudioVideo__SWIG_3(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri); } public boolean callVideo(String remoteUriString, ActionConfig config) { return tinyWRAPJNI.CallSession_callVideo__SWIG_0(swigCPtr, this, remoteUriString, ActionConfig.getCPtr(config), config); } public boolean callVideo(String remoteUriString) { return tinyWRAPJNI.CallSession_callVideo__SWIG_1(swigCPtr, this, remoteUriString); } public boolean callVideo(SipUri remoteUri, ActionConfig config) { return tinyWRAPJNI.CallSession_callVideo__SWIG_2(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri, ActionConfig.getCPtr(config), config); } public boolean callVideo(SipUri remoteUri) { return tinyWRAPJNI.CallSession_callVideo__SWIG_3(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri); } public boolean call(String remoteUriString, twrap_media_type_t media, ActionConfig config) { return tinyWRAPJNI.CallSession_call__SWIG_0(swigCPtr, this, remoteUriString, media.swigValue(), ActionConfig.getCPtr(config), config); } public boolean call(String remoteUriString, twrap_media_type_t media) { return tinyWRAPJNI.CallSession_call__SWIG_1(swigCPtr, this, remoteUriString, media.swigValue()); } public boolean call(SipUri remoteUri, twrap_media_type_t media, ActionConfig config) { return tinyWRAPJNI.CallSession_call__SWIG_2(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri, media.swigValue(), ActionConfig.getCPtr(config), config); } public boolean call(SipUri remoteUri, twrap_media_type_t media) { return tinyWRAPJNI.CallSession_call__SWIG_3(swigCPtr, this, SipUri.getCPtr(remoteUri), remoteUri, media.swigValue()); } public boolean setSessionTimer(long timeout, String refresher) { return tinyWRAPJNI.CallSession_setSessionTimer(swigCPtr, this, timeout, refresher); } public boolean set100rel(boolean enabled) { return tinyWRAPJNI.CallSession_set100rel(swigCPtr, this, enabled); } public boolean setRtcp(boolean enabled) { return tinyWRAPJNI.CallSession_setRtcp(swigCPtr, this, enabled); } public boolean setRtcpMux(boolean enabled) { return tinyWRAPJNI.CallSession_setRtcpMux(swigCPtr, this, enabled); } public boolean setSRtpMode(tmedia_srtp_mode_t mode) { return tinyWRAPJNI.CallSession_setSRtpMode(swigCPtr, this, mode.swigValue()); } public boolean setAvpfMode(tmedia_mode_t mode) { return tinyWRAPJNI.CallSession_setAvpfMode(swigCPtr, this, mode.swigValue()); } public boolean setICE(boolean enabled) { return tinyWRAPJNI.CallSession_setICE(swigCPtr, this, enabled); } public boolean setICEStun(boolean enabled) { return tinyWRAPJNI.CallSession_setICEStun(swigCPtr, this, enabled); } public boolean setICETurn(boolean enabled) { return tinyWRAPJNI.CallSession_setICETurn(swigCPtr, this, enabled); } public boolean setSTUNServer(String hostname, int port) { return tinyWRAPJNI.CallSession_setSTUNServer(swigCPtr, this, hostname, port); } public boolean setSTUNCred(String username, String password) { return tinyWRAPJNI.CallSession_setSTUNCred(swigCPtr, this, username, password); } public boolean setQoS(tmedia_qos_stype_t type, tmedia_qos_strength_t strength) { return tinyWRAPJNI.CallSession_setQoS(swigCPtr, this, type.swigValue(), strength.swigValue()); } public boolean hold(ActionConfig config) { return tinyWRAPJNI.CallSession_hold__SWIG_0(swigCPtr, this, ActionConfig.getCPtr(config), config); } public boolean hold() { return tinyWRAPJNI.CallSession_hold__SWIG_1(swigCPtr, this); } public boolean resume(ActionConfig config) { return tinyWRAPJNI.CallSession_resume__SWIG_0(swigCPtr, this, ActionConfig.getCPtr(config), config); } public boolean resume() { return tinyWRAPJNI.CallSession_resume__SWIG_1(swigCPtr, this); } public boolean transfer(String referToUriString, ActionConfig config) { return tinyWRAPJNI.CallSession_transfer__SWIG_0(swigCPtr, this, referToUriString, ActionConfig.getCPtr(config), config); } public boolean transfer(String referToUriString) { return tinyWRAPJNI.CallSession_transfer__SWIG_1(swigCPtr, this, referToUriString); } public boolean acceptTransfer(ActionConfig config) { return tinyWRAPJNI.CallSession_acceptTransfer__SWIG_0(swigCPtr, this, ActionConfig.getCPtr(config), config); } public boolean acceptTransfer() { return tinyWRAPJNI.CallSession_acceptTransfer__SWIG_1(swigCPtr, this); } public boolean rejectTransfer(ActionConfig config) { return tinyWRAPJNI.CallSession_rejectTransfer__SWIG_0(swigCPtr, this, ActionConfig.getCPtr(config), config); } public boolean rejectTransfer() { return tinyWRAPJNI.CallSession_rejectTransfer__SWIG_1(swigCPtr, this); } public boolean sendDTMF(int number) { return tinyWRAPJNI.CallSession_sendDTMF(swigCPtr, this, number); } public long getSessionTransferId() { return tinyWRAPJNI.CallSession_getSessionTransferId(swigCPtr, this); } public boolean sendT140Data(tmedia_t140_data_type_t data_type, java.nio.ByteBuffer data_ptr, long data_size) { return tinyWRAPJNI.CallSession_sendT140Data__SWIG_0(swigCPtr, this, data_type.swigValue(), data_ptr, data_size); } public boolean sendT140Data(tmedia_t140_data_type_t data_type, java.nio.ByteBuffer data_ptr) { return tinyWRAPJNI.CallSession_sendT140Data__SWIG_1(swigCPtr, this, data_type.swigValue(), data_ptr); } public boolean sendT140Data(tmedia_t140_data_type_t data_type) { return tinyWRAPJNI.CallSession_sendT140Data__SWIG_2(swigCPtr, this, data_type.swigValue()); } public boolean setT140Callback(T140Callback pT140Callback) { return tinyWRAPJNI.CallSession_setT140Callback(swigCPtr, this, T140Callback.getCPtr(pT140Callback), pT140Callback); } }
dermotblair/Sipper
android-ngn-stack/src/org/doubango/tinyWRAP/CallSession.java
Java
gpl-3.0
8,341
[ 30522, 1013, 1008, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 101...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
declare module "stream" { import * as events from "events"; class internal extends events.EventEmitter { pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T; } namespace internal { class Stream extends internal { } interface ReadableOptions { highWaterMark?: number; encoding?: string; objectMode?: boolean; read?(this: Readable, size: number): void; destroy?(this: Readable, error: Error | null, callback: (error: Error | null) => void): void; autoDestroy?: boolean; } class Readable extends Stream implements NodeJS.ReadableStream { /** * A utility method for creating Readable Streams out of iterators. */ static from(iterable: Iterable<any> | AsyncIterable<any>, options?: ReadableOptions): Readable; readable: boolean; readonly readableEncoding: BufferEncoding | null; readonly readableEnded: boolean; readonly readableFlowing: boolean | null; readonly readableHighWaterMark: number; readonly readableLength: number; readonly readableObjectMode: boolean; destroyed: boolean; constructor(opts?: ReadableOptions); _read(size: number): void; read(size?: number): any; setEncoding(encoding: string): this; pause(): this; resume(): this; isPaused(): boolean; unpipe(destination?: NodeJS.WritableStream): this; unshift(chunk: any, encoding?: BufferEncoding): void; wrap(oldStream: NodeJS.ReadableStream): this; push(chunk: any, encoding?: string): boolean; _destroy(error: Error | null, callback: (error?: Error | null) => void): void; destroy(error?: Error): void; /** * Event emitter * The defined events on documents including: * 1. close * 2. data * 3. end * 4. readable * 5. error */ addListener(event: "close", listener: () => void): this; addListener(event: "data", listener: (chunk: any) => void): this; addListener(event: "end", listener: () => void): this; addListener(event: "readable", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; emit(event: "close"): boolean; emit(event: "data", chunk: any): boolean; emit(event: "end"): boolean; emit(event: "readable"): boolean; emit(event: "error", err: Error): boolean; emit(event: string | symbol, ...args: any[]): boolean; on(event: "close", listener: () => void): this; on(event: "data", listener: (chunk: any) => void): this; on(event: "end", listener: () => void): this; on(event: "readable", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; once(event: "data", listener: (chunk: any) => void): this; once(event: "end", listener: () => void): this; once(event: "readable", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "data", listener: (chunk: any) => void): this; prependListener(event: "end", listener: () => void): this; prependListener(event: "readable", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "data", listener: (chunk: any) => void): this; prependOnceListener(event: "end", listener: () => void): this; prependOnceListener(event: "readable", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; removeListener(event: "close", listener: () => void): this; removeListener(event: "data", listener: (chunk: any) => void): this; removeListener(event: "end", listener: () => void): this; removeListener(event: "readable", listener: () => void): this; removeListener(event: "error", listener: (err: Error) => void): this; removeListener(event: string | symbol, listener: (...args: any[]) => void): this; [Symbol.asyncIterator](): AsyncIterableIterator<any>; } interface WritableOptions { highWaterMark?: number; decodeStrings?: boolean; defaultEncoding?: string; objectMode?: boolean; emitClose?: boolean; write?(this: Writable, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; writev?(this: Writable, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; destroy?(this: Writable, error: Error | null, callback: (error: Error | null) => void): void; final?(this: Writable, callback: (error?: Error | null) => void): void; autoDestroy?: boolean; } class Writable extends Stream implements NodeJS.WritableStream { readonly writable: boolean; readonly writableEnded: boolean; readonly writableFinished: boolean; readonly writableHighWaterMark: number; readonly writableLength: number; readonly writableObjectMode: boolean; destroyed: boolean; constructor(opts?: WritableOptions); _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; _destroy(error: Error | null, callback: (error?: Error | null) => void): void; _final(callback: (error?: Error | null) => void): void; write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; write(chunk: any, encoding: string, cb?: (error: Error | null | undefined) => void): boolean; setDefaultEncoding(encoding: string): this; end(cb?: () => void): void; end(chunk: any, cb?: () => void): void; end(chunk: any, encoding: string, cb?: () => void): void; cork(): void; uncork(): void; destroy(error?: Error): void; /** * Event emitter * The defined events on documents including: * 1. close * 2. drain * 3. error * 4. finish * 5. pipe * 6. unpipe */ addListener(event: "close", listener: () => void): this; addListener(event: "drain", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "finish", listener: () => void): this; addListener(event: "pipe", listener: (src: Readable) => void): this; addListener(event: "unpipe", listener: (src: Readable) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; emit(event: "close"): boolean; emit(event: "drain"): boolean; emit(event: "error", err: Error): boolean; emit(event: "finish"): boolean; emit(event: "pipe", src: Readable): boolean; emit(event: "unpipe", src: Readable): boolean; emit(event: string | symbol, ...args: any[]): boolean; on(event: "close", listener: () => void): this; on(event: "drain", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; on(event: "finish", listener: () => void): this; on(event: "pipe", listener: (src: Readable) => void): this; on(event: "unpipe", listener: (src: Readable) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; once(event: "drain", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; once(event: "finish", listener: () => void): this; once(event: "pipe", listener: (src: Readable) => void): this; once(event: "unpipe", listener: (src: Readable) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; prependListener(event: "drain", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "finish", listener: () => void): this; prependListener(event: "pipe", listener: (src: Readable) => void): this; prependListener(event: "unpipe", listener: (src: Readable) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "drain", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: "finish", listener: () => void): this; prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; removeListener(event: "close", listener: () => void): this; removeListener(event: "drain", listener: () => void): this; removeListener(event: "error", listener: (err: Error) => void): this; removeListener(event: "finish", listener: () => void): this; removeListener(event: "pipe", listener: (src: Readable) => void): this; removeListener(event: "unpipe", listener: (src: Readable) => void): this; removeListener(event: string | symbol, listener: (...args: any[]) => void): this; } interface DuplexOptions extends ReadableOptions, WritableOptions { allowHalfOpen?: boolean; readableObjectMode?: boolean; writableObjectMode?: boolean; readableHighWaterMark?: number; writableHighWaterMark?: number; read?(this: Duplex, size: number): void; write?(this: Duplex, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; writev?(this: Duplex, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; final?(this: Duplex, callback: (error?: Error | null) => void): void; destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; } // Note: Duplex extends both Readable and Writable. class Duplex extends Readable implements Writable { readonly writable: boolean; readonly writableEnded: boolean; readonly writableFinished: boolean; readonly writableHighWaterMark: number; readonly writableLength: number; readonly writableObjectMode: boolean; constructor(opts?: DuplexOptions); _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; _destroy(error: Error | null, callback: (error: Error | null) => void): void; _final(callback: (error?: Error | null) => void): void; write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; setDefaultEncoding(encoding: string): this; end(cb?: () => void): void; end(chunk: any, cb?: () => void): void; end(chunk: any, encoding?: string, cb?: () => void): void; cork(): void; uncork(): void; } type TransformCallback = (error?: Error | null, data?: any) => void; interface TransformOptions extends DuplexOptions { read?(this: Transform, size: number): void; write?(this: Transform, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; writev?(this: Transform, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; final?(this: Transform, callback: (error?: Error | null) => void): void; destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; transform?(this: Transform, chunk: any, encoding: string, callback: TransformCallback): void; flush?(this: Transform, callback: TransformCallback): void; } class Transform extends Duplex { constructor(opts?: TransformOptions); _transform(chunk: any, encoding: string, callback: TransformCallback): void; _flush(callback: TransformCallback): void; } class PassThrough extends Transform { } interface FinishedOptions { error?: boolean; readable?: boolean; writable?: boolean; } function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options: FinishedOptions, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; namespace finished { function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise<void>; } function pipeline<T extends NodeJS.WritableStream>(stream1: NodeJS.ReadableStream, stream2: T, callback?: (err: NodeJS.ErrnoException | null) => void): T; function pipeline<T extends NodeJS.WritableStream>(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: T, callback?: (err: NodeJS.ErrnoException | null) => void): T; function pipeline<T extends NodeJS.WritableStream>( stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: T, callback?: (err: NodeJS.ErrnoException | null) => void, ): T; function pipeline<T extends NodeJS.WritableStream>( stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: NodeJS.ReadWriteStream, stream5: T, callback?: (err: NodeJS.ErrnoException | null) => void, ): T; function pipeline( streams: ReadonlyArray<NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream>, callback?: (err: NodeJS.ErrnoException | null) => void, ): NodeJS.WritableStream; function pipeline( stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, ...streams: Array<NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException | null) => void)>, ): NodeJS.WritableStream; namespace pipeline { function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.WritableStream): Promise<void>; function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.WritableStream): Promise<void>; function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: NodeJS.WritableStream): Promise<void>; function __promisify__( stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: NodeJS.ReadWriteStream, stream5: NodeJS.WritableStream, ): Promise<void>; function __promisify__(streams: ReadonlyArray<NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream>): Promise<void>; function __promisify__( stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, ...streams: Array<NodeJS.ReadWriteStream | NodeJS.WritableStream>, ): Promise<void>; } interface Pipe { close(): void; hasRef(): boolean; ref(): void; unref(): void; } } export = internal; }
mcliment/DefinitelyTyped
types/node/v12/stream.d.ts
TypeScript
mit
18,046
[ 30522, 13520, 11336, 1000, 5460, 1000, 1063, 12324, 1008, 2004, 2824, 2013, 1000, 2824, 1000, 1025, 2465, 4722, 8908, 2824, 1012, 2724, 23238, 12079, 1063, 8667, 1026, 1056, 8908, 13045, 22578, 1012, 25697, 3085, 21422, 1028, 1006, 7688, 10...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
Licenses ======== New BSD License --------------- Copyright (c) 2013 Jan Brabec 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 "Kdyby Framework" 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. GNU General Public License -------------------------- GPL licenses are very very long, so instead of including them here we offer you URLs with full text: - [GPL version 2](http://www.gnu.org/licenses/gpl-2.0.html) - [GPL version 3](http://www.gnu.org/licenses/gpl-3.0.html)
Aprila/laboratory
vendor/brabijan/images/license.md
Markdown
mit
1,812
[ 30522, 15943, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 2047, 18667, 2094, 6105, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 9385, 1006, 1039, 1007, 2286, 5553, 11655, 4783, 2278, 2035, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# author: brian dillmann # for rscs from Devices.Input import Input from Devices.Timer import Timer from Devices.AnalogInput import AnalogInput from Devices.Output import Output class DeviceManager: def __init__(self): self.inputs = {} self.outputs = {} def addSimpleInput(self, name, location, invert = False): if name in self.inputs: raise KeyError('Cannot create device with name %s because input with that name already exists' % name) self.inputs[name] = Input(name, location, invert) def addTimer(self, name, interval = 's'): if name in self.inputs: raise KeyError('Cannot create device with name %s because input with that name already exists' % name) self.inputs[name] = Timer(name, interval) def addAnalogInput(self, name, location): if name in self.inputs: raise KeyError('Cannot create device with name %s because input with that name already exists' % name) self.inputs[name] = AnalogInput(name, location) def addOutput(self, name, location, invert = False): if name in self.outputs: raise KeyError('Cannot create device with name %s because output with that name already exists' % name) self.outputs[name] = Output(name, location, invert) def read(self, name): if not name in self.inputs: raise KeyError('Cannot find input with name %s, unable to read' % name) return self.inputs[name].read() def turnOn(self, name): if not name in self.outputs: raise KeyError('Cannot find output with name %s, unable to turn on' % name) self.outputs[name].on() def turnOff(self, name): if not name in self.outputs: raise KeyError('Cannot find output with name %s, unable to turn off' % name) self.outputs[name].off()
dillmann/rscs
lib/DeviceManager.py
Python
mit
1,683
[ 30522, 1001, 3166, 1024, 4422, 29454, 12624, 2078, 1001, 2005, 12667, 6169, 2013, 5733, 1012, 7953, 12324, 7953, 2013, 5733, 1012, 25309, 12324, 25309, 2013, 5733, 1012, 11698, 2378, 18780, 12324, 11698, 2378, 18780, 2013, 5733, 1012, 6434, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
import os,json from cgi import escape def unescape(s): s = s.replace("&lt;", "<") s = s.replace("&gt;", ">") # this has to be last: s = s.replace("&amp;", "&") return s class FilesystemMixin: def h_fs_get(_,path,eltName=''): from stat import S_ISDIR data = (escape(open(path).read()) if not S_ISDIR(os.stat(path).st_mode) else [(p,S_ISDIR(os.stat(path+'/'+p).st_mode)) for p in os.listdir(path)]) _.ws.send(json.dumps({"method":"fs_get","result":[path,data,eltName]})) pass def h_fs_put(_,path,data): f=open(path,'w') for x in data: f.write(unescape(x)) f.close() pass def h_fs_system(_,path,eltName='',cwd=None): import subprocess as sp import shlex data=sp.Popen(shlex.split(path),cwd=cwd,stdout=sp.PIPE, stderr=sp.PIPE).communicate() _.ws.send(json.dumps({"method":"fs_system","result":[path,data,eltName]})); pass def h_fs_mkdir (_,path): os.mkdir(path) def h_fs_rmdir (_,path): os.rmdir(path) def h_fs_touch (_,path): open(path,'w').close() def h_fs_unlink(_,path): os.unlink(path) pass class FsApp(FilesystemMixin): def __init__(_,ws):_.ws=ws
val314159/framist
fssvr/fs.py
Python
apache-2.0
1,267
[ 30522, 12324, 9808, 1010, 1046, 3385, 2013, 1039, 5856, 12324, 4019, 13366, 16655, 15782, 5051, 1006, 1055, 1007, 1024, 1055, 1027, 1055, 1012, 5672, 1006, 1000, 1004, 8318, 1025, 1000, 1010, 1000, 1026, 1000, 1007, 1055, 1027, 1055, 1012, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* CryptoJS v3.1.2 code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ var CryptoJS=CryptoJS||function(s,l){var e={},n=e.lib={},p=function(){},b=n.Base={extend:function(c){p.prototype=this;var a=new p;c&&a.mixIn(c);a.hasOwnProperty("init")||(a.init=function(){a.$super.init.apply(this,arguments)});a.init.prototype=a;a.$super=this;return a},create:function(){var c=this.extend();c.init.apply(c,arguments);return c},init:function(){},mixIn:function(c){for(var a in c)c.hasOwnProperty(a)&&(this[a]=c[a]);c.hasOwnProperty("toString")&&(this.toString=c.toString)},clone:function(){return this.init.prototype.extend(this)}}, d=n.WordArray=b.extend({init:function(c,a){c=this.words=c||[];this.sigBytes=a!=l?a:4*c.length},toString:function(c){return(c||q).stringify(this)},concat:function(c){var a=this.words,m=c.words,f=this.sigBytes;c=c.sigBytes;this.clamp();if(f%4)for(var r=0;r<c;r++)a[f+r>>>2]|=(m[r>>>2]>>>24-8*(r%4)&255)<<24-8*((f+r)%4);else if(65535<m.length)for(r=0;r<c;r+=4)a[f+r>>>2]=m[r>>>2];else a.push.apply(a,m);this.sigBytes+=c;return this},clamp:function(){var c=this.words,a=this.sigBytes;c[a>>>2]&=4294967295<< 32-8*(a%4);c.length=s.ceil(a/4)},clone:function(){var c=b.clone.call(this);c.words=this.words.slice(0);return c},random:function(c){for(var a=[],m=0;m<c;m+=4)a.push(4294967296*s.random()|0);return new d.init(a,c)}}),t=e.enc={},q=t.Hex={stringify:function(c){var a=c.words;c=c.sigBytes;for(var m=[],f=0;f<c;f++){var r=a[f>>>2]>>>24-8*(f%4)&255;m.push((r>>>4).toString(16));m.push((r&15).toString(16))}return m.join("")},parse:function(c){for(var a=c.length,m=[],f=0;f<a;f+=2)m[f>>>3]|=parseInt(c.substr(f, 2),16)<<24-4*(f%8);return new d.init(m,a/2)}},a=t.Latin1={stringify:function(c){var a=c.words;c=c.sigBytes;for(var m=[],f=0;f<c;f++)m.push(String.fromCharCode(a[f>>>2]>>>24-8*(f%4)&255));return m.join("")},parse:function(c){for(var a=c.length,m=[],f=0;f<a;f++)m[f>>>2]|=(c.charCodeAt(f)&255)<<24-8*(f%4);return new d.init(m,a)}},v=t.Utf8={stringify:function(c){try{return decodeURIComponent(escape(a.stringify(c)))}catch(u){throw Error("Malformed UTF-8 data");}},parse:function(c){return a.parse(unescape(encodeURIComponent(c)))}}, u=n.BufferedBlockAlgorithm=b.extend({reset:function(){this._data=new d.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=v.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var u=this._data,m=u.words,f=u.sigBytes,r=this.blockSize,e=f/(4*r),e=a?s.ceil(e):s.max((e|0)-this._minBufferSize,0);a=e*r;f=s.min(4*a,f);if(a){for(var b=0;b<a;b+=r)this._doProcessBlock(m,b);b=m.splice(0,a);u.sigBytes-=f}return new d.init(b,f)},clone:function(){var a=b.clone.call(this); a._data=this._data.clone();return a},_minBufferSize:0});n.Hasher=u.extend({cfg:b.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){u.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(u,m){return(new a.init(m)).finalize(u)}},_createHmacHelper:function(a){return function(u,m){return(new w.HMAC.init(a, m)).finalize(u)}}});var w=e.algo={};return e}(Math); (function(){var s=CryptoJS,l=s.lib.WordArray;s.enc.Base64={stringify:function(e){var n=e.words,l=e.sigBytes,b=this._map;e.clamp();e=[];for(var d=0;d<l;d+=3)for(var t=(n[d>>>2]>>>24-8*(d%4)&255)<<16|(n[d+1>>>2]>>>24-8*((d+1)%4)&255)<<8|n[d+2>>>2]>>>24-8*((d+2)%4)&255,q=0;4>q&&d+0.75*q<l;q++)e.push(b.charAt(t>>>6*(3-q)&63));if(n=b.charAt(64))for(;e.length%4;)e.push(n);return e.join("")},parse:function(e){var n=e.length,p=this._map,b=p.charAt(64);b&&(b=e.indexOf(b),-1!=b&&(n=b));for(var b=[],d=0,t=0;t< n;t++)if(t%4){var q=p.indexOf(e.charAt(t-1))<<2*(t%4),a=p.indexOf(e.charAt(t))>>>6-2*(t%4);b[d>>>2]|=(q|a)<<24-8*(d%4);d++}return l.create(b,d)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})(); (function(s){function l(a,b,c,e,m,f,r){a=a+(b&c|~b&e)+m+r;return(a<<f|a>>>32-f)+b}function e(a,b,c,e,m,f,r){a=a+(b&e|c&~e)+m+r;return(a<<f|a>>>32-f)+b}function n(a,b,c,e,m,f,r){a=a+(b^c^e)+m+r;return(a<<f|a>>>32-f)+b}function p(a,b,c,e,m,f,r){a=a+(c^(b|~e))+m+r;return(a<<f|a>>>32-f)+b}for(var b=CryptoJS,d=b.lib,t=d.WordArray,q=d.Hasher,d=b.algo,a=[],v=0;64>v;v++)a[v]=4294967296*s.abs(s.sin(v+1))|0;d=d.MD5=q.extend({_doReset:function(){this._hash=new t.init([1732584193,4023233417,2562383102,271733878])}, _doProcessBlock:function(b,d){for(var c=0;16>c;c++){var q=d+c,m=b[q];b[q]=(m<<8|m>>>24)&16711935|(m<<24|m>>>8)&4278255360}var c=this._hash.words,q=b[d+0],m=b[d+1],f=b[d+2],r=b[d+3],x=b[d+4],t=b[d+5],s=b[d+6],v=b[d+7],y=b[d+8],z=b[d+9],A=b[d+10],B=b[d+11],C=b[d+12],D=b[d+13],E=b[d+14],F=b[d+15],g=c[0],h=c[1],j=c[2],k=c[3],g=l(g,h,j,k,q,7,a[0]),k=l(k,g,h,j,m,12,a[1]),j=l(j,k,g,h,f,17,a[2]),h=l(h,j,k,g,r,22,a[3]),g=l(g,h,j,k,x,7,a[4]),k=l(k,g,h,j,t,12,a[5]),j=l(j,k,g,h,s,17,a[6]),h=l(h,j,k,g,v,22,a[7]), g=l(g,h,j,k,y,7,a[8]),k=l(k,g,h,j,z,12,a[9]),j=l(j,k,g,h,A,17,a[10]),h=l(h,j,k,g,B,22,a[11]),g=l(g,h,j,k,C,7,a[12]),k=l(k,g,h,j,D,12,a[13]),j=l(j,k,g,h,E,17,a[14]),h=l(h,j,k,g,F,22,a[15]),g=e(g,h,j,k,m,5,a[16]),k=e(k,g,h,j,s,9,a[17]),j=e(j,k,g,h,B,14,a[18]),h=e(h,j,k,g,q,20,a[19]),g=e(g,h,j,k,t,5,a[20]),k=e(k,g,h,j,A,9,a[21]),j=e(j,k,g,h,F,14,a[22]),h=e(h,j,k,g,x,20,a[23]),g=e(g,h,j,k,z,5,a[24]),k=e(k,g,h,j,E,9,a[25]),j=e(j,k,g,h,r,14,a[26]),h=e(h,j,k,g,y,20,a[27]),g=e(g,h,j,k,D,5,a[28]),k=e(k,g, h,j,f,9,a[29]),j=e(j,k,g,h,v,14,a[30]),h=e(h,j,k,g,C,20,a[31]),g=n(g,h,j,k,t,4,a[32]),k=n(k,g,h,j,y,11,a[33]),j=n(j,k,g,h,B,16,a[34]),h=n(h,j,k,g,E,23,a[35]),g=n(g,h,j,k,m,4,a[36]),k=n(k,g,h,j,x,11,a[37]),j=n(j,k,g,h,v,16,a[38]),h=n(h,j,k,g,A,23,a[39]),g=n(g,h,j,k,D,4,a[40]),k=n(k,g,h,j,q,11,a[41]),j=n(j,k,g,h,r,16,a[42]),h=n(h,j,k,g,s,23,a[43]),g=n(g,h,j,k,z,4,a[44]),k=n(k,g,h,j,C,11,a[45]),j=n(j,k,g,h,F,16,a[46]),h=n(h,j,k,g,f,23,a[47]),g=p(g,h,j,k,q,6,a[48]),k=p(k,g,h,j,v,10,a[49]),j=p(j,k,g,h, E,15,a[50]),h=p(h,j,k,g,t,21,a[51]),g=p(g,h,j,k,C,6,a[52]),k=p(k,g,h,j,r,10,a[53]),j=p(j,k,g,h,A,15,a[54]),h=p(h,j,k,g,m,21,a[55]),g=p(g,h,j,k,y,6,a[56]),k=p(k,g,h,j,F,10,a[57]),j=p(j,k,g,h,s,15,a[58]),h=p(h,j,k,g,D,21,a[59]),g=p(g,h,j,k,x,6,a[60]),k=p(k,g,h,j,B,10,a[61]),j=p(j,k,g,h,f,15,a[62]),h=p(h,j,k,g,z,21,a[63]);c[0]=c[0]+g|0;c[1]=c[1]+h|0;c[2]=c[2]+j|0;c[3]=c[3]+k|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32;var m=s.floor(c/ 4294967296);b[(d+64>>>9<<4)+15]=(m<<8|m>>>24)&16711935|(m<<24|m>>>8)&4278255360;b[(d+64>>>9<<4)+14]=(c<<8|c>>>24)&16711935|(c<<24|c>>>8)&4278255360;a.sigBytes=4*(b.length+1);this._process();a=this._hash;b=a.words;for(c=0;4>c;c++)d=b[c],b[c]=(d<<8|d>>>24)&16711935|(d<<24|d>>>8)&4278255360;return a},clone:function(){var a=q.clone.call(this);a._hash=this._hash.clone();return a}});b.MD5=q._createHelper(d);b.HmacMD5=q._createHmacHelper(d)})(Math); (function(){var s=CryptoJS,l=s.lib,e=l.Base,n=l.WordArray,l=s.algo,p=l.EvpKDF=e.extend({cfg:e.extend({keySize:4,hasher:l.MD5,iterations:1}),init:function(b){this.cfg=this.cfg.extend(b)},compute:function(b,d){for(var e=this.cfg,q=e.hasher.create(),a=n.create(),l=a.words,p=e.keySize,e=e.iterations;l.length<p;){s&&q.update(s);var s=q.update(b).finalize(d);q.reset();for(var c=1;c<e;c++)s=q.finalize(s),q.reset();a.concat(s)}a.sigBytes=4*p;return a}});s.EvpKDF=function(b,d,e){return p.create(e).compute(b, d)}})(); CryptoJS.lib.Cipher||function(s){var l=CryptoJS,e=l.lib,n=e.Base,p=e.WordArray,b=e.BufferedBlockAlgorithm,d=l.enc.Base64,t=l.algo.EvpKDF,q=e.Cipher=b.extend({cfg:n.extend(),createEncryptor:function(a,f){return this.create(this._ENC_XFORM_MODE,a,f)},createDecryptor:function(a,f){return this.create(this._DEC_XFORM_MODE,a,f)},init:function(a,f,c){this.cfg=this.cfg.extend(c);this._xformMode=a;this._key=f;this.reset()},reset:function(){b.reset.call(this);this._doReset()},process:function(a){this._append(a);return this._process()}, finalize:function(a){a&&this._append(a);return this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(a){return{encrypt:function(f,b,d){return("string"==typeof b?G:c).encrypt(a,f,b,d)},decrypt:function(f,b,d){return("string"==typeof b?G:c).decrypt(a,f,b,d)}}}});e.StreamCipher=q.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var a=l.mode={},v=function(a,f,b){var c=this._iv;c?this._iv=s:c=this._prevBlock;for(var d=0;d<b;d++)a[f+d]^= c[d]},u=(e.BlockCipherMode=n.extend({createEncryptor:function(a,f){return this.Encryptor.create(a,f)},createDecryptor:function(a,f){return this.Decryptor.create(a,f)},init:function(a,f){this._cipher=a;this._iv=f}})).extend();u.Encryptor=u.extend({processBlock:function(a,f){var b=this._cipher,c=b.blockSize;v.call(this,a,f,c);b.encryptBlock(a,f);this._prevBlock=a.slice(f,f+c)}});u.Decryptor=u.extend({processBlock:function(a,f){var b=this._cipher,c=b.blockSize,d=a.slice(f,f+c);b.decryptBlock(a,f);v.call(this, a,f,c);this._prevBlock=d}});a=a.CBC=u;u=(l.pad={}).Pkcs7={pad:function(a,f){for(var b=4*f,b=b-a.sigBytes%b,c=b<<24|b<<16|b<<8|b,d=[],e=0;e<b;e+=4)d.push(c);b=p.create(d,b);a.concat(b)},unpad:function(a){a.sigBytes-=a.words[a.sigBytes-1>>>2]&255}};e.BlockCipher=q.extend({cfg:q.cfg.extend({mode:a,padding:u}),reset:function(){q.reset.call(this);var a=this.cfg,b=a.iv,a=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var c=a.createEncryptor;else c=a.createDecryptor,this._minBufferSize=1;this._mode=c.call(a, this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else b=this._process(!0),a.unpad(b);return b},blockSize:4});var w=e.CipherParams=n.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}}),a=(l.format={}).OpenSSL={stringify:function(a){var b=a.ciphertext;a=a.salt;return(a?p.create([1398893684, 1701076831]).concat(a).concat(b):b).toString(d)},parse:function(a){a=d.parse(a);var b=a.words;if(1398893684==b[0]&&1701076831==b[1]){var c=p.create(b.slice(2,4));b.splice(0,4);a.sigBytes-=16}return w.create({ciphertext:a,salt:c})}},c=e.SerializableCipher=n.extend({cfg:n.extend({format:a}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d);b=e.finalize(b);e=e.cfg;return w.create({ciphertext:b,key:c,iv:e.iv,algorithm:a,mode:e.mode,padding:e.padding,blockSize:a.blockSize,formatter:d.format})}, decrypt:function(a,b,c,d){d=this.cfg.extend(d);b=this._parse(b,d.format);return a.createDecryptor(c,d).finalize(b.ciphertext)},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),l=(l.kdf={}).OpenSSL={execute:function(a,b,c,d){d||(d=p.random(8));a=t.create({keySize:b+c}).compute(a,d);c=p.create(a.words.slice(b),4*c);a.sigBytes=4*b;return w.create({key:a,iv:c,salt:d})}},G=e.PasswordBasedCipher=c.extend({cfg:c.cfg.extend({kdf:l}),encrypt:function(a,b,d,e){e=this.cfg.extend(e);d=e.kdf.execute(d, a.keySize,a.ivSize);e.iv=d.iv;a=c.encrypt.call(this,a,b,d.key,e);a.mixIn(d);return a},decrypt:function(a,b,d,e){e=this.cfg.extend(e);b=this._parse(b,e.format);d=e.kdf.execute(d,a.keySize,a.ivSize,b.salt);e.iv=d.iv;return c.decrypt.call(this,a,b,d.key,e)}})}(); (function(){function s(){for(var b=this._S,d=this._i,e=this._j,q=0,a=0;4>a;a++){var d=(d+1)%256,e=(e+b[d])%256,l=b[d];b[d]=b[e];b[e]=l;q|=b[(b[d]+b[e])%256]<<24-8*a}this._i=d;this._j=e;return q}var l=CryptoJS,e=l.lib.StreamCipher,n=l.algo,p=n.RC4=e.extend({_doReset:function(){for(var b=this._key,d=b.words,b=b.sigBytes,e=this._S=[],l=0;256>l;l++)e[l]=l;for(var a=l=0;256>l;l++){var n=l%b,a=(a+e[l]+(d[n>>>2]>>>24-8*(n%4)&255))%256,n=e[l];e[l]=e[a];e[a]=n}this._i=this._j=0},_doProcessBlock:function(b, d){b[d]^=s.call(this)},keySize:8,ivSize:0});l.RC4=e._createHelper(p);n=n.RC4Drop=p.extend({cfg:p.cfg.extend({drop:192}),_doReset:function(){p._doReset.call(this);for(var b=this.cfg.drop;0<b;b--)s.call(this)}});l.RC4Drop=e._createHelper(n)})();
quenlang/NetopGO
static/scripts/libs/cryptojs/rollups/rc4.js
JavaScript
apache-2.0
12,159
[ 30522, 1013, 1008, 19888, 29147, 2015, 1058, 2509, 1012, 1015, 1012, 1016, 3642, 1012, 8224, 1012, 4012, 1013, 1052, 1013, 19888, 2080, 1011, 1046, 2015, 1006, 1039, 1007, 2268, 1011, 2286, 2011, 5076, 9587, 4779, 1012, 2035, 2916, 9235, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/***************************************************************************** * * PROJECT: Multi Theft Auto v1.0 * LICENSE: See LICENSE in the top level directory * FILE: sdk/game/CControllerConfigManager.h * PURPOSE: Controller configuration manager interface * * Multi Theft Auto is available from http://www.multitheftauto.com/ * *****************************************************************************/ #ifndef __CGAME_CONTROLLER_CONFIG_MANAGER #define __CGAME_CONTROLLER_CONFIG_MANAGER // FROM VC, unlikely that they were changed though #define GTA_KEY_NO_MOUSE_BUTTON 0 #define GTA_KEY_LMOUSE 1 #define GTA_KEY_MMOUSE 2 #define GTA_KEY_RMOUSE 3 #define GTA_KEY_MSCROLLUP 4 #define GTA_KEY_MSCROLLDOWN 5 #define GTA_KEY_MXB1 6 #define GTA_KEY_MXB2 7 #define GTA_KEY_SPACE 32 #define GTA_KEY_COMMA 44 #define GTA_KEY_MINUS 45 /* - on main keyboard */ #define GTA_KEY_PERIOD 46 /* . on main keyboard */ #define GTA_KEY_SLASH 47 /* / on main keyboard */ #define GTA_KEY_0 48 #define GTA_KEY_1 49 #define GTA_KEY_2 50 #define GTA_KEY_3 51 #define GTA_KEY_4 52 #define GTA_KEY_5 53 #define GTA_KEY_6 54 #define GTA_KEY_7 55 #define GTA_KEY_8 56 #define GTA_KEY_9 57 #define GTA_KEY_EQUALS 61 #define GTA_KEY_A 65 #define GTA_KEY_B 66 #define GTA_KEY_C 67 #define GTA_KEY_D 68 #define GTA_KEY_E 69 #define GTA_KEY_F 70 #define GTA_KEY_G 71 #define GTA_KEY_H 72 #define GTA_KEY_I 73 #define GTA_KEY_J 74 #define GTA_KEY_K 75 #define GTA_KEY_L 76 #define GTA_KEY_M 77 #define GTA_KEY_N 78 #define GTA_KEY_O 79 #define GTA_KEY_P 80 #define GTA_KEY_Q 81 #define GTA_KEY_R 82 #define GTA_KEY_S 83 #define GTA_KEY_T 84 #define GTA_KEY_U 85 #define GTA_KEY_V 86 #define GTA_KEY_W 87 #define GTA_KEY_X 88 #define GTA_KEY_Y 89 #define GTA_KEY_Z 90 #define GTA_KEY_HASH 35 #define GTA_KEY_SEMICOLON 59 #define GTA_KEY_APOSTROPHE 39 #define GTA_KEY_LBRACKET 91 #define GTA_KEY_BACKSLASH 92 #define GTA_KEY_RBRACKET 93 #define GTA_KEY_GRAVE 96 /* accent grave */ #define GTA_KEY_F1 1001 #define GTA_KEY_F2 1002 #define GTA_KEY_F3 1003 #define GTA_KEY_F4 1004 #define GTA_KEY_F5 1005 #define GTA_KEY_F6 1006 #define GTA_KEY_F7 1007 #define GTA_KEY_F8 1009 #define GTA_KEY_F9 1009 #define GTA_KEY_F10 1010 #define GTA_KEY_F11 1011 #define GTA_KEY_F12 1012 #define GTA_KEY_INSERT 1013 /* Insert on arrow keypad */ #define GTA_KEY_DELETE 1014 /* Delete on arrow keypad */ #define GTA_KEY_HOME 1015 /* Home on arrow keypad */ #define GTA_KEY_END 1016 /* End on arrow keypad */ #define GTA_KEY_PGUP 1017 /* PgUp on arrow keypad */ #define GTA_KEY_PGDN 1018 /* PgDn on arrow keypad */ #define GTA_KEY_UP 1019 /* UpArrow on arrow keypad */ #define GTA_KEY_DOWN 1020 /* DownArrow on arrow keypad */ #define GTA_KEY_LEFT 1021 /* LeftArrow on arrow keypad */ #define GTA_KEY_RIGHT 1022 /* RightArrow on arrow keypad */ #define GTA_KEY_DIVIDE 1023 /* / on numeric keypad */ #define GTA_KEY_MULTIPLY 1024 /* * on numeric keypad */ #define GTA_KEY_ADD 1025 /* + on numeric keypad */ #define GTA_KEY_SUBTRACT 1026 /* - on numeric keypad */ #define GTA_KEY_DECIMAL 1027 /* . on numeric keypad */ #define GTA_KEY_NUMPAD1 1028 #define GTA_KEY_NUMPAD2 1029 #define GTA_KEY_NUMPAD3 1030 #define GTA_KEY_NUMPAD4 1031 #define GTA_KEY_NUMPAD5 1032 #define GTA_KEY_NUMLOCK 1033 #define GTA_KEY_NUMPAD6 1034 #define GTA_KEY_NUMPAD7 1035 #define GTA_KEY_NUMPAD8 1036 #define GTA_KEY_NUMPAD9 1037 #define GTA_KEY_NUMPAD0 1038 #define GTA_KEY_NUMPADENTER 1039 /* Enter on numeric keypad */ #define GTA_KEY_SCROLL 1040 /* Scroll Lock */ #define GTA_KEY_PAUSE 1041 /* Pause */ #define GTA_KEY_BACK 1042 /* backspace */ #define GTA_KEY_TAB 1043 #define GTA_KEY_CAPSLOCK 1044 /* Caps Lock */ #define GTA_KEY_RETURN 1045 /* Enter on main keyboard */ #define GTA_KEY_LSHIFT 1046 #define GTA_KEY_RSHIFT 1047 #define GTA_KEY_LCONTROL 1049 #define GTA_KEY_RCONTROL 1050 #define GTA_KEY_LMENU 1051 /* left Alt */ #define GTA_KEY_RMENU 1052 /* right Alt */ #define GTA_KEY_LWIN 1053 /* Left Windows key */ #define GTA_KEY_RWIN 1054 /* Right Windows key */ #define NO_KEY_DEFINED 1056 /* FROM VC: #define KEYBOARD 0 #define OPTIONAL_EXTRA_KEY 1 #define MOUSE 2 #define JOY_STICK 3 */ enum eControllerType { KEYBOARD = 0, OPTIONAL_EXTRA, MOUSE, JOYSTICK }; enum eControllerAction { FIRE = 0, NEXT_WEAPON = 2, PREVIOUS_WEAPON, FORWARDS, BACKWARDS, LEFT, RIGHT, ZOOM_IN, ZOOM_OUT, ENTER_EXIT, CHANGE_CAMERA, JUMP, SPRINT, LOOK_BEHIND, CROUCH, ACTION, WALK, VEHICLE_FIRE, VEHICLE_SECONDARY_FIRE, VEHICLE_LEFT, VEHICLE_RIGHT, STEER_FORWARDS_DOWN, STEER_BACK_UP, ACCELERATE, BRAKE_REVERSE, RADIO_NEXT, RADIO_PREVIOUS, RADIO_USER_TRACK_SKIP, HORN, SUB_MISSION, HANDBRAKE, VEHICLE_LOOK_LEFT = 0x22, VEHICLE_LOOK_RIGHT, VEHICLE_LOOK_BEHIND, VEHICLE_MOUSE_LOOK, SPECIAL_CONTROL_LEFT, SPECIAL_CONTROL_RIGHT, SPECIAL_CONTROL_DOWN, SPECIAL_CONTROL_UP, AIM_WEAPON = 0x2D, CONVERSATION_YES = 0x2F, CONVERSATION_NO, GROUP_CONTROL_FORWARDS, GROUP_CONTROL_BACK, }; class CControllerConfigManager { public: virtual void SetControllerKeyAssociatedWithAction ( eControllerAction action, int iKey, eControllerType controllerType )=0; virtual int GetControllerKeyAssociatedWithAction ( eControllerAction action, eControllerType controllerType )=0; virtual void SetClassicControls ( bool bClassicControls ) = 0; virtual void SetMouseInverted ( bool bInverted ) = 0; virtual void SetFlyWithMouse ( bool bFlyWithMouse ) = 0; virtual void SetSteerWithMouse ( bool bSteerWithMouse ) = 0; virtual void SuspendSteerAndFlyWithMouse ( bool bSuspend ) = 0; virtual float GetVerticalAimSensitivity ( void ) = 0; virtual void SetVerticalAimSensitivity ( float fSensitivity ) = 0; virtual float GetVerticalAimSensitivityRawValue ( void ) = 0; virtual void SetVerticalAimSensitivityRawValue ( float fRawValue ) = 0; }; #endif
Whitetigerswt/gtasa_crashfix
crashes/crashes/sdk/game/CControllerConfigManager.h
C
gpl-3.0
7,559
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 30524, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 2622, 10...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 com.facebook.buck.features.project.intellij; import com.facebook.buck.core.exceptions.HumanReadableException; import com.facebook.buck.core.util.log.Logger; import com.facebook.buck.features.project.intellij.model.ModuleIndexEntry; import com.facebook.buck.util.xml.XmlDomParser; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet.Builder; import java.io.IOException; import java.io.InputStream; import java.nio.file.Paths; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** Responsible for parsing an existing modules.xml file */ public class IntellijModulesListParser { private static Logger LOG = Logger.get(IntellijModulesListParser.class); /** * @param modulesFile modules.xml input stream * @return A list of module entries as specified by the modules.xml file * @throws IOException */ public ImmutableSet<ModuleIndexEntry> getAllModules(InputStream modulesFile) throws IOException { final Document doc; try { doc = XmlDomParser.parse(modulesFile); } catch (SAXException e) { LOG.error("Cannot read modules.xml file", e); throw new HumanReadableException( "Could not update 'modules.xml' file because it is malformed", e); } final Builder<ModuleIndexEntry> builder = ImmutableSet.builder(); try { XPath xpath = XPathFactory.newInstance().newXPath(); final NodeList moduleList = (NodeList) xpath .compile("/project/component/modules/module") .evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < moduleList.getLength(); i++) { final Element moduleEntry = (Element) moduleList.item(i); if (!moduleEntry.hasAttribute("filepath")) { continue; } String filepath = moduleEntry.getAttribute("filepath"); String fileurl = moduleEntry.getAttribute("fileurl"); String filepathWithoutProjectPrefix; // The template has a hardcoded $PROJECT_DIR$/ prefix, so we need to strip that out // of the value we pass to ST if (filepath.startsWith("$PROJECT_DIR$")) { filepathWithoutProjectPrefix = filepath.substring("$PROJECT_DIR$".length() + 1); } else { filepathWithoutProjectPrefix = filepath; } builder.add( ModuleIndexEntry.builder() .setFilePath(Paths.get(filepathWithoutProjectPrefix)) .setFileUrl(fileurl) .setGroup( moduleEntry.hasAttribute("group") ? moduleEntry.getAttribute("group") : null) .build()); } } catch (XPathExpressionException e) { throw new HumanReadableException("Illegal xpath expression.", e); } return builder.build(); } }
zpao/buck
src/com/facebook/buck/features/project/intellij/IntellijModulesListParser.java
Java
apache-2.0
3,637
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 9130, 1010, 4297, 1012, 1998, 2049, 18460, 1012, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1008, 2017, 2089, 2025, 2...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php if ( ! defined( 'ABSPATH' ) ) exit; /** * Unfortunately WordPress supports PHP 5.2 even though * everyone should now be using at least PHP 5.3. * * To be compatible with PHP 5.2 below you will find functions * that are required in order to make this plugin work correctly. */ add_action( 'admin_notices', 'jmfe_old_php_notice' ); add_action( 'admin_init', 'jmfe_old_php_notice_ignore' ); // PHP 5.2 does not have array_replace_recursive if ( ! function_exists( 'array_replace_recursive' ) ) { function array_replace_recursive( $array, $array1 ) { if ( ! function_exists( 'compat_array_recurse' ) ) { function compat_array_recurse( $array, $array1 ) { foreach ( $array1 as $key => $value ) { // create new key in $array, if it is empty or not an array if ( ! isset( $array[ $key ] ) || ( isset( $array[ $key ] ) && ! is_array( $array[ $key ] ) ) ) { $array[ $key ] = array(); } // overwrite the value in the base array if ( is_array( $value ) ) { $value = compat_array_recurse( $array[ $key ], $value ); } $array[ $key ] = $value; } return $array; } } // handle the arguments, merge one by one $args = func_get_args(); $array = $args[ 0 ]; if ( ! is_array( $array ) ) { return $array; } for ( $i = 1; $i < count( $args ); $i ++ ) { if ( is_array( $args[ $i ] ) ) { $array = compat_array_recurse( $array, $args[ $i ] ); } } return $array; } } if ( ! function_exists( 'jmfe_old_php_notice' ) ) { function jmfe_old_php_notice() { $user_id = get_current_user_id(); if ( ! get_option( 'jmfe_old_php_notice' ) ) { echo '<div class="error"><p>'; printf( __( 'Your server is using a <strong>VERY OLD</strong> and unsupported version of PHP, version 5.2 or older. <a href="%1$s" target="_blank">EOL (End of Life)</a> for PHP 5.2 was about <strong>%2$s ago</strong>!!<br /><br />It is <strong>strongly</strong> recommended that you upgrade to PHP 5.3 or newer...you can upgrade PHP or <a href="%3$s">Hide this Notice Forever!</a><br/><br />Did you know im also the Founder and CEO of Host Tornado?<br/><a href="%4$s" target="_blank">Contact me</a> for an exclusive sMyles Plugins customer promo code discount for any shared <strong>SSD (Solid State Drive)</strong> hosting packages! Data centers in Florida USA, Arizona USA, Montreal Canada, and France. Your site will run faster than it ever has, or your money back!', 'wp-job-manager-field-editor' ), 'http://php.net/eol.php', human_time_diff( '1294272000', current_time( 'timestamp' ) ), '?jmfe_old_php_notice=0', 'https://plugins.smyl.es/contact' ); echo "</p></div>"; } } } if ( ! function_exists( 'jmfe_old_php_notice_ignore' ) ) { function jmfe_old_php_notice_ignore() { if ( isset( $_GET[ 'jmfe_old_php_notice' ] ) && '0' == $_GET[ 'jmfe_old_php_notice' ] ) { add_option( 'jmfe_old_php_notice', 'true' ); } } } if ( ! function_exists( 'str_getcsv' ) ) { function str_getcsv( $input, $delimiter = ',', $enclosure = '"', $escape = '\\', $eol = '\n' ) { if ( is_string( $input ) && ! empty( $input ) ) { $output = array(); $tmp = preg_split( "/" . $eol . "/", $input ); if ( is_array( $tmp ) && ! empty( $tmp ) ) { while ( list( $line_num, $line ) = each( $tmp ) ) { if ( preg_match( "/" . $escape . $enclosure . "/", $line ) ) { while ( $strlen = strlen( $line ) ) { $pos_delimiter = strpos( $line, $delimiter ); $pos_enclosure_start = strpos( $line, $enclosure ); if ( is_int( $pos_delimiter ) && is_int( $pos_enclosure_start ) && ( $pos_enclosure_start < $pos_delimiter ) ) { $enclosed_str = substr( $line, 1 ); $pos_enclosure_end = strpos( $enclosed_str, $enclosure ); $enclosed_str = substr( $enclosed_str, 0, $pos_enclosure_end ); $output[ $line_num ][ ] = $enclosed_str; $offset = $pos_enclosure_end + 3; } else { if ( empty( $pos_delimiter ) && empty( $pos_enclosure_start ) ) { $output[ $line_num ][ ] = substr( $line, 0 ); $offset = strlen( $line ); } else { $output[ $line_num ][ ] = substr( $line, 0, $pos_delimiter ); $offset = ( ! empty( $pos_enclosure_start ) && ( $pos_enclosure_start < $pos_delimiter ) ) ? $pos_enclosure_start : $pos_delimiter + 1; } } $line = substr( $line, $offset ); } } else { $line = preg_split( "/" . $delimiter . "/", $line ); /* * Validating against pesky extra line breaks creating false rows. */ if ( is_array( $line ) && ! empty( $line[ 0 ] ) ) { $output[ $line_num ] = $line; } } } return $output; } else { return FALSE; } } else { return FALSE; } } }
Zduhamel/PT-JOB-FUSION
wp-content/plugins/wp-job-manager-field-editor/includes/compatibility.php
PHP
gpl-2.0
4,925
[ 30522, 1026, 1029, 25718, 2065, 1006, 999, 4225, 1006, 1005, 14689, 15069, 1005, 1007, 1007, 6164, 1025, 1013, 1008, 1008, 1008, 6854, 2773, 20110, 6753, 25718, 1019, 1012, 1016, 2130, 2295, 1008, 3071, 2323, 2085, 2022, 2478, 2012, 2560, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * twl6030_usb - TWL6030 USB transceiver, talking to OMAP OTG driver. * * Copyright (C) 2010 Texas Instruments Incorporated - http://www.ti.com * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Author: Hema HK <hemahk@ti.com> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * */ #include <linux/module.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/platform_device.h> #include <linux/io.h> #include <linux/usb/musb-omap.h> #include <linux/usb/phy_companion.h> #include <linux/usb/omap_usb.h> #include <linux/i2c/twl.h> #include <linux/regulator/consumer.h> #include <linux/err.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/of.h> /* usb register definitions */ #define USB_VENDOR_ID_LSB 0x00 #define USB_VENDOR_ID_MSB 0x01 #define USB_PRODUCT_ID_LSB 0x02 #define USB_PRODUCT_ID_MSB 0x03 #define USB_VBUS_CTRL_SET 0x04 #define USB_VBUS_CTRL_CLR 0x05 #define USB_ID_CTRL_SET 0x06 #define USB_ID_CTRL_CLR 0x07 #define USB_VBUS_INT_SRC 0x08 #define USB_VBUS_INT_LATCH_SET 0x09 #define USB_VBUS_INT_LATCH_CLR 0x0A #define USB_VBUS_INT_EN_LO_SET 0x0B #define USB_VBUS_INT_EN_LO_CLR 0x0C #define USB_VBUS_INT_EN_HI_SET 0x0D #define USB_VBUS_INT_EN_HI_CLR 0x0E #define USB_ID_INT_SRC 0x0F #define USB_ID_INT_LATCH_SET 0x10 #define USB_ID_INT_LATCH_CLR 0x11 #define USB_ID_INT_EN_LO_SET 0x12 #define USB_ID_INT_EN_LO_CLR 0x13 #define USB_ID_INT_EN_HI_SET 0x14 #define USB_ID_INT_EN_HI_CLR 0x15 #define USB_OTG_ADP_CTRL 0x16 #define USB_OTG_ADP_HIGH 0x17 #define USB_OTG_ADP_LOW 0x18 #define USB_OTG_ADP_RISE 0x19 #define USB_OTG_REVISION 0x1A /* to be moved to LDO */ #define TWL6030_MISC2 0xE5 #define TWL6030_CFG_LDO_PD2 0xF5 #define TWL6030_BACKUP_REG 0xFA #define STS_HW_CONDITIONS 0x21 /* In module TWL6030_MODULE_PM_MASTER */ #define STS_HW_CONDITIONS 0x21 #define STS_USB_ID BIT(2) /* In module TWL6030_MODULE_PM_RECEIVER */ #define VUSB_CFG_TRANS 0x71 #define VUSB_CFG_STATE 0x72 #define VUSB_CFG_VOLTAGE 0x73 /* in module TWL6030_MODULE_MAIN_CHARGE */ #define CHARGERUSB_CTRL1 0x8 #define CONTROLLER_STAT1 0x03 #define VBUS_DET BIT(2) struct twl6030_usb { struct phy_companion comparator; struct device *dev; /* for vbus reporting with irqs disabled */ spinlock_t lock; struct regulator *usb3v3; /* used to set vbus, in atomic path */ struct work_struct set_vbus_work; int irq1; int irq2; enum omap_musb_vbus_id_status linkstat; u8 asleep; bool irq_enabled; bool vbus_enable; const char *regulator; }; #define comparator_to_twl(x) container_of((x), struct twl6030_usb, comparator) /*-------------------------------------------------------------------------*/ static inline int twl6030_writeb(struct twl6030_usb *twl, u8 module, u8 data, u8 address) { int ret = 0; ret = twl_i2c_write_u8(module, data, address); if (ret < 0) dev_err(twl->dev, "Write[0x%x] Error %d\n", address, ret); return ret; } static inline u8 twl6030_readb(struct twl6030_usb *twl, u8 module, u8 address) { u8 data; int ret; ret = twl_i2c_read_u8(module, &data, address); if (ret >= 0) ret = data; else dev_err(twl->dev, "readb[0x%x,0x%x] Error %d\n", module, address, ret); return ret; } static int twl6030_start_srp(struct phy_companion *comparator) { struct twl6030_usb *twl = comparator_to_twl(comparator); twl6030_writeb(twl, TWL_MODULE_USB, 0x24, USB_VBUS_CTRL_SET); twl6030_writeb(twl, TWL_MODULE_USB, 0x84, USB_VBUS_CTRL_SET); mdelay(100); twl6030_writeb(twl, TWL_MODULE_USB, 0xa0, USB_VBUS_CTRL_CLR); return 0; } static int twl6030_usb_ldo_init(struct twl6030_usb *twl) { /* Set to OTG_REV 1.3 and turn on the ID_WAKEUP_COMP */ twl6030_writeb(twl, TWL6030_MODULE_ID0 , 0x1, TWL6030_BACKUP_REG); /* Program CFG_LDO_PD2 register and set VUSB bit */ twl6030_writeb(twl, TWL6030_MODULE_ID0 , 0x1, TWL6030_CFG_LDO_PD2); /* Program MISC2 register and set bit VUSB_IN_VBAT */ twl6030_writeb(twl, TWL6030_MODULE_ID0 , 0x10, TWL6030_MISC2); twl->usb3v3 = regulator_get(twl->dev, twl->regulator); if (IS_ERR(twl->usb3v3)) return -ENODEV; /* Program the USB_VBUS_CTRL_SET and set VBUS_ACT_COMP bit */ twl6030_writeb(twl, TWL_MODULE_USB, 0x4, USB_VBUS_CTRL_SET); /* * Program the USB_ID_CTRL_SET register to enable GND drive * and the ID comparators */ twl6030_writeb(twl, TWL_MODULE_USB, 0x14, USB_ID_CTRL_SET); return 0; } static ssize_t twl6030_usb_vbus_show(struct device *dev, struct device_attribute *attr, char *buf) { struct twl6030_usb *twl = dev_get_drvdata(dev); unsigned long flags; int ret = -EINVAL; spin_lock_irqsave(&twl->lock, flags); switch (twl->linkstat) { case OMAP_MUSB_VBUS_VALID: ret = snprintf(buf, PAGE_SIZE, "vbus\n"); break; case OMAP_MUSB_ID_GROUND: ret = snprintf(buf, PAGE_SIZE, "id\n"); break; case OMAP_MUSB_VBUS_OFF: ret = snprintf(buf, PAGE_SIZE, "none\n"); break; default: ret = snprintf(buf, PAGE_SIZE, "UNKNOWN\n"); } spin_unlock_irqrestore(&twl->lock, flags); return ret; } static DEVICE_ATTR(vbus, 0444, twl6030_usb_vbus_show, NULL); static irqreturn_t twl6030_usb_irq(int irq, void *_twl) { struct twl6030_usb *twl = _twl; enum omap_musb_vbus_id_status status = OMAP_MUSB_UNKNOWN; u8 vbus_state, hw_state; int ret; hw_state = twl6030_readb(twl, TWL6030_MODULE_ID0, STS_HW_CONDITIONS); vbus_state = twl6030_readb(twl, TWL_MODULE_MAIN_CHARGE, CONTROLLER_STAT1); if (!(hw_state & STS_USB_ID)) { if (vbus_state & VBUS_DET) { ret = regulator_enable(twl->usb3v3); if (ret) dev_err(twl->dev, "Failed to enable usb3v3\n"); twl->asleep = 1; status = OMAP_MUSB_VBUS_VALID; twl->linkstat = status; omap_musb_mailbox(status); } else { if (twl->linkstat != OMAP_MUSB_UNKNOWN) { status = OMAP_MUSB_VBUS_OFF; twl->linkstat = status; omap_musb_mailbox(status); if (twl->asleep) { regulator_disable(twl->usb3v3); twl->asleep = 0; } } } } sysfs_notify(&twl->dev->kobj, NULL, "vbus"); return IRQ_HANDLED; } static irqreturn_t twl6030_usbotg_irq(int irq, void *_twl) { struct twl6030_usb *twl = _twl; enum omap_musb_vbus_id_status status = OMAP_MUSB_UNKNOWN; u8 hw_state; int ret; hw_state = twl6030_readb(twl, TWL6030_MODULE_ID0, STS_HW_CONDITIONS); if (hw_state & STS_USB_ID) { ret = regulator_enable(twl->usb3v3); if (ret) dev_err(twl->dev, "Failed to enable usb3v3\n"); twl->asleep = 1; twl6030_writeb(twl, TWL_MODULE_USB, 0x1, USB_ID_INT_EN_HI_CLR); twl6030_writeb(twl, TWL_MODULE_USB, 0x10, USB_ID_INT_EN_HI_SET); status = OMAP_MUSB_ID_GROUND; twl->linkstat = status; omap_musb_mailbox(status); } else { twl6030_writeb(twl, TWL_MODULE_USB, 0x10, USB_ID_INT_EN_HI_CLR); twl6030_writeb(twl, TWL_MODULE_USB, 0x1, USB_ID_INT_EN_HI_SET); } twl6030_writeb(twl, TWL_MODULE_USB, status, USB_ID_INT_LATCH_CLR); return IRQ_HANDLED; } static int twl6030_enable_irq(struct twl6030_usb *twl) { twl6030_writeb(twl, TWL_MODULE_USB, 0x1, USB_ID_INT_EN_HI_SET); twl6030_interrupt_unmask(0x05, REG_INT_MSK_LINE_C); twl6030_interrupt_unmask(0x05, REG_INT_MSK_STS_C); twl6030_interrupt_unmask(TWL6030_CHARGER_CTRL_INT_MASK, REG_INT_MSK_LINE_C); twl6030_interrupt_unmask(TWL6030_CHARGER_CTRL_INT_MASK, REG_INT_MSK_STS_C); twl6030_usb_irq(twl->irq2, twl); twl6030_usbotg_irq(twl->irq1, twl); return 0; } static void otg_set_vbus_work(struct work_struct *data) { struct twl6030_usb *twl = container_of(data, struct twl6030_usb, set_vbus_work); /* * Start driving VBUS. Set OPA_MODE bit in CHARGERUSB_CTRL1 * register. This enables boost mode. */ if (twl->vbus_enable) twl6030_writeb(twl, TWL_MODULE_MAIN_CHARGE , 0x40, CHARGERUSB_CTRL1); else twl6030_writeb(twl, TWL_MODULE_MAIN_CHARGE , 0x00, CHARGERUSB_CTRL1); } static int twl6030_set_vbus(struct phy_companion *comparator, bool enabled) { struct twl6030_usb *twl = comparator_to_twl(comparator); twl->vbus_enable = enabled; schedule_work(&twl->set_vbus_work); return 0; } static int twl6030_usb_probe(struct platform_device *pdev) { u32 ret; struct twl6030_usb *twl; int status, err; struct device_node *np = pdev->dev.of_node; struct device *dev = &pdev->dev; struct twl4030_usb_data *pdata = dev_get_platdata(dev); twl = devm_kzalloc(dev, sizeof(*twl), GFP_KERNEL); if (!twl) return -ENOMEM; twl->dev = &pdev->dev; twl->irq1 = platform_get_irq(pdev, 0); twl->irq2 = platform_get_irq(pdev, 1); twl->linkstat = OMAP_MUSB_UNKNOWN; twl->comparator.set_vbus = twl6030_set_vbus; twl->comparator.start_srp = twl6030_start_srp; ret = omap_usb2_set_comparator(&twl->comparator); if (ret == -ENODEV) { dev_info(&pdev->dev, "phy not ready, deferring probe"); return -EPROBE_DEFER; } if (np) { twl->regulator = "usb"; } else if (pdata) { if (pdata->features & TWL6032_SUBCLASS) twl->regulator = "ldousb"; else twl->regulator = "vusb"; } else { dev_err(&pdev->dev, "twl6030 initialized without pdata\n"); return -EINVAL; } /* init spinlock for workqueue */ spin_lock_init(&twl->lock); err = twl6030_usb_ldo_init(twl); if (err) { dev_err(&pdev->dev, "ldo init failed\n"); return err; } platform_set_drvdata(pdev, twl); if (device_create_file(&pdev->dev, &dev_attr_vbus)) dev_warn(&pdev->dev, "could not create sysfs file\n"); INIT_WORK(&twl->set_vbus_work, otg_set_vbus_work); twl->irq_enabled = true; status = request_threaded_irq(twl->irq1, NULL, twl6030_usbotg_irq, IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING | IRQF_ONESHOT, "twl6030_usb", twl); if (status < 0) { dev_err(&pdev->dev, "can't get IRQ %d, err %d\n", twl->irq1, status); device_remove_file(twl->dev, &dev_attr_vbus); return status; } status = request_threaded_irq(twl->irq2, NULL, twl6030_usb_irq, IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING | IRQF_ONESHOT, "twl6030_usb", twl); if (status < 0) { dev_err(&pdev->dev, "can't get IRQ %d, err %d\n", twl->irq2, status); free_irq(twl->irq1, twl); device_remove_file(twl->dev, &dev_attr_vbus); return status; } twl->asleep = 0; twl6030_enable_irq(twl); dev_info(&pdev->dev, "Initialized TWL6030 USB module\n"); return 0; } static int twl6030_usb_remove(struct platform_device *pdev) { struct twl6030_usb *twl = platform_get_drvdata(pdev); twl6030_interrupt_mask(TWL6030_USBOTG_INT_MASK, REG_INT_MSK_LINE_C); twl6030_interrupt_mask(TWL6030_USBOTG_INT_MASK, REG_INT_MSK_STS_C); free_irq(twl->irq1, twl); free_irq(twl->irq2, twl); regulator_put(twl->usb3v3); device_remove_file(twl->dev, &dev_attr_vbus); cancel_work_sync(&twl->set_vbus_work); return 0; } #ifdef CONFIG_OF static const struct of_device_id twl6030_usb_id_table[] = { { .compatible = "ti,twl6030-usb" }, {} }; MODULE_DEVICE_TABLE(of, twl6030_usb_id_table); #endif static struct platform_driver twl6030_usb_driver = { .probe = twl6030_usb_probe, .remove = twl6030_usb_remove, .driver = { .name = "twl6030_usb", .owner = THIS_MODULE, .of_match_table = of_match_ptr(twl6030_usb_id_table), }, }; static int __init twl6030_usb_init(void) { return platform_driver_register(&twl6030_usb_driver); } subsys_initcall(twl6030_usb_init); static void __exit twl6030_usb_exit(void) { platform_driver_unregister(&twl6030_usb_driver); } module_exit(twl6030_usb_exit); MODULE_ALIAS("platform:twl6030_usb"); MODULE_AUTHOR("Hema HK <hemahk@ti.com>"); MODULE_DESCRIPTION("TWL6030 USB transceiver driver"); MODULE_LICENSE("GPL");
maoze/linux-3-14-for-arm
linux-3.14/drivers/usb/phy/phy-twl6030-usb.c
C
gpl-3.0
12,145
[ 30522, 1013, 1008, 1008, 1056, 13668, 16086, 14142, 1035, 18833, 1011, 1056, 13668, 16086, 30524, 3331, 2000, 18168, 9331, 27178, 2290, 4062, 1012, 1008, 1008, 9385, 1006, 1039, 1007, 2230, 3146, 5693, 5100, 1011, 8299, 1024, 1013, 1013, 74...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/////////////////////////////////////////////////////////////////////////// // C++ code generated with wxFormBuilder (version Apr 10 2012) // http://www.wxformbuilder.org/ // // PLEASE DO "NOT" EDIT THIS FILE! /////////////////////////////////////////////////////////////////////////// #ifndef __DIALOG_LAYERS_SELECT_TO_PCB_BASE_H__ #define __DIALOG_LAYERS_SELECT_TO_PCB_BASE_H__ #include <wx/artprov.h> #include <wx/xrc/xmlres.h> #include <wx/intl.h> #include "dialog_shim.h" #include <wx/sizer.h> #include <wx/gdicmn.h> #include <wx/statline.h> #include <wx/font.h> #include <wx/colour.h> #include <wx/settings.h> #include <wx/string.h> #include <wx/statbox.h> #include <wx/stattext.h> #include <wx/combobox.h> #include <wx/button.h> #include <wx/dialog.h> /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /// Class LAYERS_MAP_DIALOG_BASE /////////////////////////////////////////////////////////////////////////////// class LAYERS_MAP_DIALOG_BASE : public DIALOG_SHIM { DECLARE_EVENT_TABLE() private: // Private event handlers void _wxFB_OnBrdLayersCountSelection( wxCommandEvent& event ){ OnBrdLayersCountSelection( event ); } void _wxFB_OnStoreSetup( wxCommandEvent& event ){ OnStoreSetup( event ); } void _wxFB_OnGetSetup( wxCommandEvent& event ){ OnGetSetup( event ); } void _wxFB_OnResetClick( wxCommandEvent& event ){ OnResetClick( event ); } void _wxFB_OnCancelClick( wxCommandEvent& event ){ OnCancelClick( event ); } void _wxFB_OnOkClick( wxCommandEvent& event ){ OnOkClick( event ); } protected: enum { ID_LAYERS_MAP_DIALOG_BASE = 1000, ID_M_STATICLINESEP, ID_M_STATICTEXTCOPPERLAYERCOUNT, ID_M_COMBOCOPPERLAYERSCOUNT, ID_STORE_CHOICE, ID_GET_PREVIOUS_CHOICE, ID_RESET_CHOICE }; wxStaticBoxSizer* sbSizerLayersTable; wxFlexGridSizer* m_flexLeftColumnBoxSizer; wxStaticLine* m_staticlineSep; wxStaticText* m_staticTextCopperlayerCount; wxComboBox* m_comboCopperLayersCount; wxButton* m_buttonStore; wxButton* m_buttonRetrieve; wxButton* m_buttonReset; wxStaticLine* m_staticline1; wxStdDialogButtonSizer* m_sdbSizerButtons; wxButton* m_sdbSizerButtonsOK; wxButton* m_sdbSizerButtonsCancel; // Virtual event handlers, overide them in your derived class virtual void OnBrdLayersCountSelection( wxCommandEvent& event ) { event.Skip(); } virtual void OnStoreSetup( wxCommandEvent& event ) { event.Skip(); } virtual void OnGetSetup( wxCommandEvent& event ) { event.Skip(); } virtual void OnResetClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnCancelClick( wxCommandEvent& event ) { event.Skip(); } virtual void OnOkClick( wxCommandEvent& event ) { event.Skip(); } public: LAYERS_MAP_DIALOG_BASE( wxWindow* parent, wxWindowID id = ID_LAYERS_MAP_DIALOG_BASE, const wxString& title = _("Layer selection:"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize( 400,286 ), long style = wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER ); ~LAYERS_MAP_DIALOG_BASE(); }; #endif //__DIALOG_LAYERS_SELECT_TO_PCB_BASE_H__
peabody124/kicad
gerbview/dialogs/dialog_layers_select_to_pcb_base.h
C
lgpl-2.1
3,252
[ 30522, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 1013, 101...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #ifdef AWS_MULTI_FRAMEWORK #import <AWSRuntime/AmazonServiceRequestConfig.h> #else #import "../AmazonServiceRequestConfig.h" #endif /** * Delete Security Group Request */ @interface EC2DeleteSecurityGroupRequest:AmazonServiceRequestConfig { NSString *groupName; NSString *groupId; } /** * The name of the Amazon EC2 security group to delete. */ @property (nonatomic, retain) NSString *groupName; /** * The ID of the Amazon EC2 security group to delete. */ @property (nonatomic, retain) NSString *groupId; /** * Default constructor for a new DeleteSecurityGroupRequest object. Callers should use the * property methods to initialize this object after creating it. */ -(id)init; /** * Constructs a new DeleteSecurityGroupRequest object. * Callers should use properties to initialize any additional object members. * * @param theGroupName The name of the Amazon EC2 security group to * delete. */ -(id)initWithGroupName:(NSString *)theGroupName; /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. */ -(NSString *)description; @end
jetthoughts/motion-recorder
vendor/Pods/AWSiOSSDK/src/include/EC2/EC2DeleteSecurityGroupRequest.h
C
mit
1,750
[ 30522, 1013, 1008, 1008, 9385, 2230, 1011, 2286, 9733, 1012, 4012, 1010, 4297, 1012, 2030, 2049, 18460, 1012, 2035, 2916, 9235, 1012, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#ifndef FRC971_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_ #define FRC971_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_ #include "aos/common/controls/polytope.h" #ifdef INCLUDE_971_INFRASTRUCTURE #include "frc971/control_loops/drivetrain/drivetrain.q.h" #endif //INCLUDE_971_INFRASTRUCTURE #include "frc971/control_loops/state_feedback_loop.h" #include "frc971/control_loops/drivetrain/drivetrain_config.h" namespace frc971 { namespace control_loops { namespace drivetrain { class PolyDrivetrain { public: enum Gear { HIGH, LOW, SHIFTING_UP, SHIFTING_DOWN }; PolyDrivetrain(const DrivetrainConfig &dt_config); int controller_index() const { return loop_->controller_index(); } bool IsInGear(Gear gear) { return gear == LOW || gear == HIGH; } // Computes the speed of the motor given the hall effect position and the // speed of the robot. double MotorSpeed(const constants::ShifterHallEffect &hall_effect, double shifter_position, double velocity); // Computes the states of the shifters for the left and right drivetrain sides // given a requested state. void UpdateGears(Gear requested_gear); // Computes the next state of a shifter given the current state and the // requested state. Gear UpdateSingleGear(Gear requested_gear, Gear current_gear); void SetGoal(double wheel, double throttle, bool quickturn, bool highgear); #ifdef INCLUDE_971_INFRASTRUCTURE void SetPosition( const ::frc971::control_loops::DrivetrainQueue::Position *position); #else //INCLUDE_971_INFRASTRUCTURE void SetPosition( const DrivetrainPosition *position); #endif //INCLUDE_971_INFRASTRUCTURE double FilterVelocity(double throttle); double MaxVelocity(); void Update(); #ifdef INCLUDE_971_INFRASTRUCTURE void SendMotors(::frc971::control_loops::DrivetrainQueue::Output *output); #else //INCLUDE_971_INFRASTRUCTURE void SendMotors(DrivetrainOutput *output); #endif //INCLUDE_971_INFRASTRUCTURE private: StateFeedbackLoop<7, 2, 3> kf_; const ::aos::controls::HPolytope<2> U_Poly_; ::std::unique_ptr<StateFeedbackLoop<2, 2, 2>> loop_; const double ttrust_; double wheel_; double throttle_; bool quickturn_; int stale_count_; double position_time_delta_; Gear left_gear_; Gear right_gear_; #ifdef INCLUDE_971_INFRASTRUCTURE ::frc971::control_loops::DrivetrainQueue::Position last_position_; ::frc971::control_loops::DrivetrainQueue::Position position_; #else //INCLUDE_971_INFRASTRUCTURE DrivetrainPosition last_position_; DrivetrainPosition position_; #endif //INCLUDE_971_INFRASTRUCTURE int counter_; DrivetrainConfig dt_config_; }; } // namespace drivetrain } // namespace control_loops } // namespace frc971 #endif // FRC971_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
FRC1296/CheezyDriver2016
frc971/control_loops/drivetrain/polydrivetrain.h
C
bsd-2-clause
2,780
[ 30522, 1001, 2065, 13629, 2546, 10424, 2278, 2683, 2581, 2487, 1035, 2491, 1035, 15932, 1035, 3298, 23654, 1035, 26572, 23663, 23654, 1035, 1044, 1035, 1001, 9375, 10424, 2278, 2683, 2581, 2487, 1035, 2491, 1035, 15932, 1035, 3298, 23654, 1...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * USE - UML based specification environment * Copyright (C) 1999-2004 Mark Richters, University of Bremen * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* $ProjectHeader: use 2-1-0-release.1 Sun, 09 May 2004 13:57:11 +0200 mr $ */ package org.tzi.use.gui.views; import java.awt.print.PageFormat; /** * Views with print facility implement this interface. * * @version $ProjectVersion: 2-1-0-release.1 $ * @author Mark Richters */ public interface PrintableView { void printView(PageFormat pf); }
stormymauldin/stuff
src/main/org/tzi/use/gui/views/PrintableView.java
Java
gpl-2.0
1,182
[ 30522, 1013, 1008, 1008, 2224, 1011, 8529, 2140, 2241, 12827, 4044, 1008, 9385, 1006, 1039, 1007, 2639, 1011, 2432, 2928, 20105, 2015, 1010, 2118, 1997, 16314, 1008, 1008, 2023, 2565, 2003, 2489, 4007, 1025, 2017, 2064, 2417, 2923, 3089, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php $thumb_id = get_post_thumbnail_id(); $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'large'); $thumb_url = $thumb_url_array[0]; $excerpt = get_the_excerpt(); ?> <article class="snippet snippet-full"> <a href="<?php the_permalink(); ?>" class="plain-link"> <div class="snippet-thumbnail" style="background-image:url('<?php echo $thumb_url; ?>');"> <span>&nbsp;</span> </div> </a> <h4 class="entry-title below"> <a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a> </h4> <?php get_template_part('templates/entry-meta'); ?> <div class="entry-summary"> <?php the_excerpt(); ?> </div> </article>
dgaultiere/the-good-shepherd
templates/content-snippet-post-full.php
PHP
mit
673
[ 30522, 1026, 1029, 25718, 1002, 7639, 1035, 8909, 1027, 2131, 1035, 2695, 1035, 30524, 24471, 2140, 1035, 9140, 1027, 1059, 2361, 1035, 2131, 1035, 14449, 1035, 3746, 1035, 5034, 2278, 1006, 1002, 7639, 1035, 8909, 1010, 1005, 2312, 1005, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
//Author// //Miroslav Vitkov 2013 //sir.vorac(at)gmail(dot)com //License// //Beerware #include "OnOffController.h" #include <stdlib.h> #include <string.h> error_t ONOFFcreate(ONOFF_o **obj, const ONOFFconfig_s *const config){ if(!config) return ERROR_NULL_POINTER; *obj = (ONOFF_o*)malloc(sizeof(ONOFF_o)); if(*obj == NULL) return ERROR_ALLOCATION_FAILURE; memcpy((void*)&(**obj).config, (void*)config, sizeof(ONOFFconfig_s)); (**obj).report.memFootprint = sizeof(ONOFF_o); (**obj).data.previousOutput = 0; return SUCCESS; }
MiroslavVitkov/micli
legacy/control/src/onoff/OnOffCreateDestroy.c
C
mit
545
[ 30522, 1013, 1013, 3166, 1013, 1013, 1013, 1013, 14719, 23085, 6819, 2102, 7724, 2286, 1013, 1013, 2909, 1012, 29536, 22648, 1006, 2012, 1007, 20917, 4014, 1006, 11089, 1007, 4012, 1013, 1013, 6105, 1013, 1013, 1013, 1013, 5404, 8059, 1001,...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * Created by PhpStorm. * User: olivier * Date: 01/02/15 * Time: 00:58 */ namespace AppBundle\Entity; use Doctrine\ORM\EntityRepository; /** * BusinessServiceRepository */ class BusinessServiceRepository extends EntityRepository { public function findByRefList(array $refList) { $qb = $this->createQueryBuilder('s'); $qb->where($qb->expr()->in('s.ref', $refList)); return $qb->getQuery()->execute(); } public function findEnabled() { return $this->findBy(array('enabled' => '1')); } /** * get services enabled only by default or with a suffix if $filterEnabled=false * @param bool $filterEnabled * @return array */ public function getChoices($filterEnabled = true) { if ($filterEnabled) { } $qb = $this->createQueryBuilder('s'); $qb->select('s.ref, s.name, s.enabled'); $results = $qb->getQuery()->execute(); $choices = []; foreach ($results as $item) { if ($item['enabled'] === true) { $choices[$item['ref']] = $item['name']; } else { if ($filterEnabled === false) { $choices[$item['ref']] = sprintf('%s (désactivé)', $item['name']); } else { unset($choices[$item['ref']]); } } } return $choices; } }
casual-web/autodom
src/AppBundle/Entity/BusinessServiceRepository.php
PHP
mit
1,434
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 2580, 2011, 25718, 19718, 1012, 1008, 5310, 1024, 14439, 1008, 3058, 1024, 5890, 1013, 6185, 1013, 2321, 1008, 2051, 1024, 4002, 1024, 5388, 1008, 1013, 3415, 15327, 10439, 27265, 2571, 1032...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
""" websocket - WebSocket client library for Python Copyright (C) 2010 Hiroki Ohtani(liris) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA """ import logging _logger = logging.getLogger('websocket') try: from logging import NullHandler except ImportError: class NullHandler(logging.Handler): def emit(self, record): pass _logger.addHandler(NullHandler()) _traceEnabled = False __all__ = ["enableTrace", "dump", "error", "warning", "debug", "trace", "isEnabledForError", "isEnabledForDebug", "isEnabledForTrace"] def enableTrace(traceable, handler = logging.StreamHandler()): """ turn on/off the traceability. traceable: boolean value. if set True, traceability is enabled. """ global _traceEnabled _traceEnabled = traceable if traceable: _logger.addHandler(handler) _logger.setLevel(logging.DEBUG) def dump(title, message): if _traceEnabled: _logger.debug("--- " + title + " ---") _logger.debug(message) _logger.debug("-----------------------") def error(msg): _logger.error(msg) def warning(msg): _logger.warning(msg) def debug(msg): _logger.debug(msg) def trace(msg): if _traceEnabled: _logger.debug(msg) def isEnabledForError(): return _logger.isEnabledFor(logging.ERROR) def isEnabledForDebug(): return _logger.isEnabledFor(logging.DEBUG) def isEnabledForTrace(): return _traceEnabled
vert-x3/vertx-web
vertx-web/src/test/sockjs-protocol/websocket/_logging.py
Python
apache-2.0
2,165
[ 30522, 1000, 1000, 1000, 4773, 6499, 19869, 2102, 1011, 4773, 6499, 19869, 2102, 7396, 3075, 2005, 18750, 9385, 1006, 1039, 1007, 2230, 7632, 27923, 2072, 2821, 17681, 1006, 5622, 6935, 1007, 2023, 3075, 2003, 2489, 4007, 1025, 2017, 2064, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * Sound3D - An open source 3D Audio Library * * Copyright (c) 2013 Jorma Rebane * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */
RedFox20/Sound3D
LICENSE.md
Markdown
mit
1,194
[ 30522, 1013, 1008, 1008, 1008, 2614, 29097, 1011, 2019, 2330, 3120, 7605, 5746, 3075, 1008, 1008, 9385, 1006, 1039, 1007, 2286, 8183, 17830, 2128, 27543, 1008, 1008, 6656, 2003, 2182, 3762, 4379, 1010, 2489, 1997, 3715, 1010, 2000, 2151, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package com.aws.global.dao; import java.util.ArrayList; import com.aws.global.classes.Pizza; import com.aws.global.common.base.BaseDAO; import com.aws.global.mapper.PizzaRowMapper; public class PizzaDAO extends BaseDAO{ //SQL Statement when user adds a pizza to his inventory public void addPizza(String pizzaName, int pizzaPrice) { String sql = "INSERT INTO PIZZA (pizza_id, pizza_name, pizza_price) VALUES (NULL, ?, ?);"; getJdbcTemplate().update(sql, new Object[] { pizzaName, pizzaPrice}); } //SQL Statement when user wants to get a list of pizzas public ArrayList<Pizza> getAllPizza() { String sql = "SELECT * FROM Pizza"; ArrayList<Pizza> pizzas = (ArrayList<Pizza>) getJdbcTemplate().query(sql, new PizzaRowMapper()); return pizzas; } //SQL Statement when user wants to get a pizza record using a pizza id public Pizza getPizzaById(int id) { String sql = "SELECT * FROM PIZZA WHERE pizza_id = ?"; Pizza pizza = (Pizza)getJdbcTemplate().queryForObject( sql, new Object[] { id }, new PizzaRowMapper()); return pizza; } //SQL Statement when user wants to update a certain pizza's information public void editPizza(String pizza_name, int pizza_price, int id) { String sql = "UPDATE PIZZA SET pizza_name = ?, pizza_price = ? WHERE pizza_id = ?;"; getJdbcTemplate().update(sql, new Object[] { pizza_name, pizza_price, id }); } //SQL Statement when user wants to delete a pizza information public void deletePizza(int id) { String sql = "DELETE FROM PIZZA WHERE pizza_id = ?"; getJdbcTemplate().update(sql, new Object[] { id }); } }
sethbusque/pizzaccio
src_custom/com/aws/global/dao/PizzaDAO.java
Java
mit
1,598
[ 30522, 7427, 4012, 1012, 22091, 2015, 1012, 3795, 1012, 4830, 2080, 1025, 12324, 9262, 1012, 21183, 4014, 1012, 9140, 9863, 1025, 12324, 4012, 1012, 22091, 2015, 1012, 3795, 1012, 4280, 1012, 10733, 1025, 12324, 4012, 1012, 22091, 2015, 101...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office"> <head><title>SimpleLinqToObjects</title></head> <body> <p>This program is the Hello World of the LINQ samples and is designed to show you how simple LINQ to Objects queries can be. It shows the minimal code necessary to write a LINQ to Objects query over a list.</p> </body> </html>
SiddharthMishraPersonal/StudyMaterials
Linq/CSharpSamples/LinqSamples/SimpleLinqToObjects/ReadMe.html
HTML
mit
386
[ 30522, 1026, 16129, 20950, 3619, 1024, 1058, 1027, 1000, 24471, 2078, 1024, 8040, 28433, 2015, 1011, 7513, 1011, 4012, 1024, 1058, 19968, 1000, 20950, 3619, 1024, 1051, 1027, 1000, 24471, 2078, 1024, 8040, 28433, 2015, 1011, 7513, 1011, 401...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright 2014 http4s.org * * 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.http4s.blaze.http.http2 /** Representation of outbound streams * * For outbound streams we need a concrete StreamState to send messages to, but we can't expect * that we will have HEADERS to send right when it is born, so we need to make the stream ID lazy * since they must be used in monotonically increasing order. * * @note * this is a marker trait */ private trait OutboundStreamState extends StreamState
http4s/blaze
http/src/main/scala/org/http4s/blaze/http/http2/OutboundStreamState.scala
Scala
apache-2.0
1,036
[ 30522, 1013, 1008, 1008, 9385, 2297, 8299, 2549, 2015, 1012, 8917, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1008, 2017, 2089, 2025, 2224, 2023, 5371, 3272, 1999, 12...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="pl"> <head> <!-- Generated by javadoc --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Overview List (Play! 2.x Provider for Play! 2.5.x 1.0.0-rc5 API)</title> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> <script type="text/javascript" src="script.js"></script> </head> <body> <div class="indexHeader"><span><a href="allclasses-frame.html" target="packageFrame">All&nbsp;Classes</a></span></div> <div class="indexContainer"> <h2 title="Packages">Packages</h2> <ul title="Packages"> <li><a href="com/google/code/play2/provider/play25/package-frame.html" target="packageFrame">com.google.code.play2.provider.play25</a></li> <li><a href="com/google/code/play2/provider/play25/run/package-frame.html" target="packageFrame">com.google.code.play2.provider.play25.run</a></li> </ul> </div> <p>&nbsp;</p> </body> </html>
play2-maven-plugin/play2-maven-plugin.github.io
play2-maven-plugin/1.0.0-rc5/play2-providers/play2-provider-play25/apidocs/overview-frame.html
HTML
apache-2.0
1,006
[ 30522, 1026, 999, 9986, 13874, 16129, 2270, 1000, 1011, 1013, 1013, 1059, 2509, 2278, 1013, 1013, 26718, 2094, 16129, 1018, 1012, 5890, 17459, 1013, 1013, 4372, 1000, 1000, 8299, 1024, 1013, 1013, 7479, 1012, 1059, 2509, 1012, 8917, 1013, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* http://fiidmi.fi/documentation/customer_order_history */ module.exports = { "bonus": { "type": "object", "properties": { "session_id": { "type": "string", "minLength": 2, "maxLength": 50 }, "restaurant_id": { "type": "string", "minLength": 1, "maxLength": 50 } }, "required": ["session_id", "restaurant_id"] }, "po_credit": { "type": "object", "properties": { "session_id": { "type": "string", "minLength": 2, "maxLength": 50 } }, "required": ["session_id", "order_id"] } };
tidhr/node-fiidmi
lib/api/3.3/customer/information.js
JavaScript
mit
526
[ 30522, 1013, 1008, 8299, 1024, 1013, 1013, 10882, 3593, 4328, 1012, 10882, 1013, 12653, 1013, 8013, 1035, 2344, 1035, 2381, 1008, 1013, 11336, 1012, 14338, 1027, 1063, 1000, 6781, 1000, 1024, 1063, 1000, 2828, 1000, 1024, 1000, 4874, 1000, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
import math as mth import numpy as np #---------------------- # J Matthews, 21/02 # This is a file containing useful constants for python coding # # Units in CGS unless stated # #---------------------- #H=6.62606957E-27 HEV=4.13620e-15 #C=29979245800.0 #BOLTZMANN=1.3806488E-16 VERY_BIG=1e50 H=6.6262e-27 HC=1.98587e-16 HEV=4.13620e-15 # Planck's constant in eV HRYD=3.04005e-16 # NSH 1204 Planck's constant in Rydberg C =2.997925e10 G=6.670e-8 BOLTZMANN =1.38062e-16 WIEN= 5.879e10 # NSH 1208 Wien Disp Const in frequency units H_OVER_K=4.799437e-11 STEFAN_BOLTZMANN =5.6696e-5 THOMPSON=0.66524e-24 PI = 3.1415927 MELEC = 9.10956e-28 E= 4.8035e-10 # Electric charge in esu MPROT = 1.672661e-24 MSOL = 1.989e33 PC= 3.08e18 YR = 3.1556925e7 PI_E2_OVER_MC=0.02655103 # Classical cross-section PI_E2_OVER_M =7.96e8 ALPHA= 7.297351e-3 # Fine structure constant BOHR= 0.529175e-8 # Bohr radius CR= 3.288051e15 #Rydberg frequency for H != Ryd freq for infinite mass ANGSTROM = 1.e-8 #Definition of an Angstrom in units of this code, e.g. cm EV2ERGS =1.602192e-12 RADIAN= 57.29578 RYD2ERGS =2.1798741e-11 PARSEC=3.086E18
jhmatthews/panlens
constants.py
Python
gpl-2.0
1,157
[ 30522, 12324, 8785, 2004, 11047, 2232, 12324, 16371, 8737, 2100, 2004, 27937, 1001, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1011, 1001, 1046, 12351, 1010,...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/***************************************************************************** * x264: h264 encoder ***************************************************************************** * Copyright (C) 2005 Tuukka Toivonen <tuukkat@ee.oulu.fi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA. *****************************************************************************/ #ifndef X264_VISUALIZE_H #define X264_VISUALIZE_H #include "common.h" void x264_visualize_init( x264_t *h ); void x264_visualize_mb( x264_t *h ); void x264_visualize_show( x264_t *h ); void x264_visualize_close( x264_t *h ); #endif
tudinfse/fex
src/parsec/x264/src/visualize.h
C
mit
1,272
[ 30522, 1013, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 30524, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 1008, 10...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v0.1.92: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v0.1.92 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1_boolean.html">Boolean</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">v8::Boolean Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classv8_1_1_boolean.html">v8::Boolean</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>BooleanValue</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#adc2a7a92a120675bbd4c992163a20869">Equals</a>(Handle&lt; Value &gt; that) const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>Int32Value</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>IntegerValue</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#aaee0b144087d20eae02314c9393ff80f">IsArray</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#a0aceb7645e71b096df5cd73d1252b1b0">IsBoolean</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a8bc11fab0aded4a805722ab6df173cae">IsDate</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#a7ac61a325c18af8dcb6d7d5bf47d2503">IsExternal</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a68c0296071d01ca899825d7643cf495a">IsFalse</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#a05532a34cdd215f273163830ed8b77e7">IsFunction</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a01e1db51c65b2feace248b7acbf71a2c">IsInt32</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#aa2c6ed8ef832223a7e2cd81e6ac61c78">IsNull</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a1bd51e3e55f67c65b9a8f587fbffb7c7">IsNumber</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#a355b7991c5c978c0341f6f961b63c5a2">IsObject</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#ab23a34b7df62806808e01b0908bf5f00">IsString</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"><span class="mlabel">inline</span></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#a8f27462322186b295195eecb3e81d6d7">IsTrue</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr class="even"><td class="entry"><a class="el" href="classv8_1_1_value.html#a783c89631bac4ef3c4b909f40cc2b8d8">IsUint32</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#aea287b745656baa8a12a2ae1d69744b6">IsUndefined</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>New</b>(bool value) (defined in <a class="el" href="classv8_1_1_boolean.html">v8::Boolean</a>)</td><td class="entry"><a class="el" href="classv8_1_1_boolean.html">v8::Boolean</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">static</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>NumberValue</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>StrictEquals</b>(Handle&lt; Value &gt; that) const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr><td class="entry"><a class="el" href="classv8_1_1_value.html#ae810be0ae81a87f677592d0176daac48">ToArrayIndex</a>() const </td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ToBoolean</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>ToDetailString</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ToInt32</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>ToInteger</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ToNumber</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>ToObject</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>ToString</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>ToUint32</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>Uint32Value</b>() const (defined in <a class="el" href="classv8_1_1_value.html">v8::Value</a>)</td><td class="entry"><a class="el" href="classv8_1_1_value.html">v8::Value</a></td><td class="entry"></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>Value</b>() const (defined in <a class="el" href="classv8_1_1_boolean.html">v8::Boolean</a>)</td><td class="entry"><a class="el" href="classv8_1_1_boolean.html">v8::Boolean</a></td><td class="entry"></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Aug 11 2015 23:44:42 for V8 API Reference Guide for node.js v0.1.92 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
v8-dox/v8-dox.github.io
e72b7b8/html/classv8_1_1_boolean-members.html
HTML
mit
12,646
[ 30522, 1026, 999, 9986, 13874, 16129, 2270, 1000, 1011, 1013, 1013, 1059, 2509, 2278, 1013, 1013, 26718, 2094, 1060, 11039, 19968, 1015, 1012, 1014, 17459, 1013, 1013, 4372, 1000, 1000, 8299, 1024, 1013, 1013, 7479, 1012, 1059, 2509, 1012, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# General Information for Windows This file describes how to install, or build, and use Julia on Windows. For more general information about Julia, please see the [main README](https://github.com/JuliaLang/julia/blob/master/README.md) or the [documentation](http://docs.julialang.org/). # Unicode font support The built-in Windows fonts have rather poor coverage of the Unicode character space. The free [`DejaVu Sans Mono`](http://dejavu-fonts.org/) font can be used as a replacement font in the Windows console. Since Windows 2000, simply downloading the font and installing it is insufficient, since Windows keeps a list of approved fonts in the registry. Instructions for adding fonts to the terminal are available at: [http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q247815](http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q247815) Additionally, rather than sticking with the default command prompt, you may want to use a different terminal emulator program, such as [`Conemu`](https://code.google.com/p/conemu-maximus5/) or [`Mintty`](https://code.google.com/p/mintty/) (note that running Julia on Mintty needs a copy of `stty.exe` in your `%PATH%` to work properly). Alternatively, you may prefer the features of a more full-function IDE, such as [`LightTable`](https://github.com/one-more-minute/Jupiter-LT), [`Sublime-IJulia`](https://github.com/quinnj/Sublime-IJulia), [`IJulia`](https://github.com/JuliaLang/IJulia.jl), or [`Julia Studio`](http://forio.com/labs/julia-studio/). # Binary distribution Julia runs on Windows XP-SP2 and later (including Windows Vista, Windows 7, and Windows 8). Both the 32-bit and 64-bit versions are supported. The 32-bit (i686) binary will run on either a 32-bit and 64-bit operating system. The 64-bit (x86_64) binary will only run on 64-bit Windows and will otherwise refuse to launch. 1. Download and install [7-Zip](http://www.7-zip.org/download.html). Install the full program, not just the command line version. 2. [Download](http://julialang.org/downloads) the latest version of Julia. Extract the binary to a reasonable destination folder, e.g. `C:\julia`. 3. Double-click the file `julia.bat` to launch Julia. # Line endings Julia uses binary-mode files exclusively. Unlike many other Window's programs, if you write '\n' to a file, you get a '\n' in the file, not some other bit pattern. This matches the behavior exhibited by other operating systems. If you have installed msysGit, it is suggested, but not required, that you configure your system msysGit to use the same convention: git config --global core.eol = lf git config --global core.autocrlf = input or edit `%USERPROFILE%\.gitconfig` and add/edit the lines: [core] eol = lf autocrlf = input # Source distribution ## Supported build platforms - Windows 8: supported (32 and 64 bits) - Windows 7: supported (32 and 64 bits) - Windows Vista: unknown - Windows XP: not supported (however, there have been some reports of success following the msys2 steps) ## Compiling with MinGW/MSYS2 ### MSYS2 provides a robust MSYS experience. ### The instructions in this section were tested with the latest versions of all packages specified as of 2014-02-28. 1. Install [7-Zip](http://www.7-zip.org/download.html). 2. Install [Python 2.x](http://www.python.org/download/releases). Do **not** install Python 3. 3. Install [MinGW-builds](http://sourceforge.net/projects/mingwbuilds/), a Windows port of GCC, as follows. Do **not** use the regular MinGW distribution. 1. Download the [MinGW-builds installer](http://downloads.sourceforge.net/project/mingwbuilds/mingw-builds-install/mingw-builds-install.exe). 2. Run the installer. When prompted, choose: - Version: the most recent version (these instructions were tested with 4.8.1) - Architecture: `x32` or `x64` as appropriate and desired. - Threads: `win32` (not posix) - Exception: `sjlj` (for x32) or `seh` (for x64). Do not choose dwarf2. - Build revision: most recent available (tested with 5) 3. Do **not** install to a directory with spaces in the name. You will have to change the default installation path, for example, - `C:\mingw-builds\x64-4.8.1-win32-seh-rev5` for 64 bits - `C:\mingw-builds\x32-4.8.1-win32-sjlj-rev5` for 32 bits 4. Install and configure [MSYS2](http://sourceforge.net/projects/msys2), a minimal POSIX-like environment for Windows. 1. Download the latest base [32-bit](http://sourceforge.net/projects/msys2/files/Base/i686/) or [64-bit](http://sourceforge.net/projects/msys2/files/Base/x86_64/) distribution, consistent with the architecture you chose for MinGW-builds. The archive will have a name like `msys2-base-x86_64-yyyymmdd.tar.xz` and these instructions were tested with `msys2-base-x86_64-20140216.tar.xz`. 2. Using [7-Zip](http://www.7-zip.org/download.html), extract the archive to any convenient directory. - *N.B.* Some versions of this archive contain zero-byte files that clash with existing files. If prompted, choose **not** to overwrite existing files. - You may need to extract the tarball in a separate step. This will create an `msys32` or `msys64` directory, according to the architecture you chose. - Move the `msys32` or `msys64` directory into your MinGW-builds directory, which is `C:\mingw-builds` if you followed the suggestions in step 3. We will omit the "32" or "64" in the steps below and refer to this as "the msys directory". 3. Double-click `msys2_shell.bat` in the msys directory. This will initialize MSYS2. The shell will tell you to `exit` and restart the shell. For now, ignore it. 4. Update MSYS2 and install packages required to build julia, using the `pacman` package manager included in MSYS2: ``` pacman-key --init #Download keys pacman -Syu #Update package database and full system upgrade ``` Now `exit` the MSYS2 shell and restart it, *even if you already restarted it above*. This is necessary in case the system upgrade updated the main MSYS2 libs. Reopen the MSYS2 shell and continue with: ``` pacman -S diffutils git m4 make patch tar msys/openssh ``` 5. Configure your MSYS2 shell for convenience: ``` echo "mount C:/Python27 /python" >> ~/.bashrc # uncomment ONE of the following two lines #echo "mount C:/mingw-builds/x64-4.8.1-win32-seh-rev5/mingw64 /mingw" >> ~/.bashrc #echo "mount C:/mingw-builds/x32-4.8.1-win32-sjlj-rev5/mingw32 /mingw" >> ~/.bashrc echo "export PATH=/usr/local/bin:/usr/bin:/opt/bin:/mingw/bin:/python" >> ~/.bashrc ``` *N.B.* The `export` clobbers whatever `$PATH` is already defined. This is suggested to avoid path-masking. If you use MSYS2 for purposes other than building Julia, you may prefer to append rather than clobber. *N.B.* All of the path-separators in the mount commands are unix-style. 6. Configuration of the toolchain is complete. Now `exit` the MSYS2 shell. 5. Build Julia and its dependencies from source. 1. Relaunch the MSYS2 shell and type ``` . ~/.bashrc # Some versions of MSYS2 do not run this automatically ``` Ignore any warnings you see from `mount` about `/mingw` and `/python` not existing. 2. Get the Julia sources and start the build: ``` git clone https://github.com/JuliaLang/julia.git cd julia make -j 4 # Adjust the number of cores (4) to match your build environment. ``` 3. The Julia build can (as of 2014-02-28) fail after building OpenBLAS. This appears (?) to be a result of the OpenBLAS build trying to run the Microsoft Visual C++ `lib.exe` tool -- which we don't need to do -- without checking for its existence. This uncaught error kills the Julia build. If this happens, follow the instructions in the helpful error message and continue the build, *viz.* ``` cd deps/openblas-v0.2.9.rc1 # This path will depend on the version of OpenBLAS. make install cd ../.. make -j 4 # Adjust the number of cores (4) to match your build environment. ``` 4. Some versions of PCRE (*e.g.* 8.31) will compile correctly but fail a test. This will cause the Julia build to fail. To circumvent testing for PCRE and allow the rest of the build to continue, ``` touch deps/pcre-8.31/checked # This path will depend on the version of PCRE. make -j 4 # Adjust the number of cores (4) to match your build environment. ``` 6. Setup Package Development Environment 1. The `Pkg` module in Base provides many convenient tools for [developing and publishing packages](http://docs.julialang.org/en/latest/manual/packages/). One of the packages added through pacman above was `openssh`, which will allow secure access to GitHub APIs. Follow GitHub's [guide](https://help.github.com/articles/generating-ssh-keys) to setting up SSH keys to ensure your local machine can communicate with GitHub effectively. 5. In case of the issues with building packages (i.e. ICU fails to build with the following error message ```error compiling xp_parse: error compiling xp_make_parser: could not load module libexpat-1: %```) run ```make win-extras``` and then copy everything from the ```dist-extras``` folder into ```usr/bin```. ## Building on Windows with MinGW-builds/MSYS ### The MSYS build of `make` is fragile and may not reliably support parallel builds. Use MSYS2 as described above, if you can. If you must use MSYS, take care to notice the special comments in this section. 1. Install [7-Zip](http://www.7-zip.org/download.html). 2. Install [Python 2.x](http://www.python.org/download/releases). Do **not** install Python 3. 3. Install [MinGW-builds](http://sourceforge.net/projects/mingwbuilds/), a Windows port of GCC. as follows. Do **not** use the regular MinGW distribution. 1. Download the [MinGW-builds installer](http://downloads.sourceforge.net/project/mingwbuilds/mingw-builds-install/mingw-builds-install.exe). 2. Run the installer. When prompted, choose: - Version: the most recent version (these instructions were tested with 4.8.1) - Architecture: x32 or x64 as appropriate and desired. - Threads: win32 (not posix) - Exception: sjlj (for x32) or seh (for x64). Do not choose dwarf2. - Build revision: most recent available (tested with 5) 3. Do **not** install to a directory with spaces in the name. You will have to change the default installation path. The following instructions will assume `C:\mingw-builds\x64-4.8.1-win32-seh-rev5\mingw64`. 4. Download and extract the [MSYS distribution for MinGW-builds](http://sourceforge.net/projects/mingwbuilds/files/external-binary-packages/) (e.g. msys+7za+wget+svn+git+mercurial+cvs-rev13.7z) to a directory *without* spaces in the name, e.g. `C:/mingw-builds/msys`. 5. Download the [MSYS distribution of make](http://sourceforge.net/projects/mingw/files/MSYS/Base/make) and use this `make.exe` to replace the one in the `mingw64\bin` subdirectory of the MinGW-builds installation. 6. Run the `msys.bat` installed in Step 4. Set up MSYS by running at the MSYS prompt: ``` mount C:/mingw-builds/x64-4.8.1-win32-seh-rev5/mingw64 /mingw mount C:/Python27 /python export PATH=$PATH:/mingw/bin:/python ``` Replace the directories as appropriate. 7. Download the Julia source repository and build it ``` git clone https://github.com/JuliaLang/julia.git cd julia make ``` *Tips:* - The MSYS build of `make` is fragile and will occasionally corrupt the build process. You can minimize the changes of this occurring by only running `make` in serial, i.e. avoid the `-j` argument. - When the build process fails for no apparent reason, try running `make` again. - Sometimes, `make` will appear to hang, consuming 100% cpu but without apparent progress. If this happens, kill `make` from the Task Manager and try again. - Expect this to take a very long time (dozens of hours is not uncommon). - If `make` fails complaining that `./flisp/flisp` is not found, force `make` to build FemtoLisp before Julia by running `make -C src/flisp && make`. 8. Run Julia with _either_ of: - Using `make` ``` make run-julia ``` (the full syntax is `make run-julia[-release|-debug]`) - Using the Julia executables directly ``` usr/bin/julia ``` ## Cross-compiling If you prefer to cross-compile, the following steps should get you started. ### Ubuntu and Mac Dependencies (these steps will work for almost any linux platform) First, you will need to ensure your system has the required dependencies. We need wine (>=1.7.5), a system compiler, and some downloaders. On Ubuntu: apt-add-repository ppa:ubuntu-wine/ppa apt-get upate apt-get install wine1.7 subversion cvs gcc wget p7zip-full On Mac: Install XCode, XCode command line tools, X11 (now [XQuartz](http://xquartz.macosforge.org/)), and [MacPorts](http://www.macports.org/install.php) or [Homebrew](http://mxcl.github.io/homebrew/). Then run ```port install wine wget``` or ```brew install wine wget```, as appropriate. On Both: Unfortunately, the version of gcc installed by Ubuntu is currently 4.6, which does not compile OpenBLAS correctly. On Mac, the situation is the same: the version in MacPorts is very old and Homebrew does not have it. So first we need to get a cross-compile version of gcc. Most binary packages appear to not include gfortran, so we will need to compile it from source (or ask @vtjnash to send you a tgz of his build). This is typically quite a bit of work, so we will use [this script](https://code.google.com/p/mingw-w64-dgn/) to make it easy. 1. `svn checkout http://mingw-w64-dgn.googlecode.com/svn/trunk/ mingw-w64-dgn` 2. `cd mingw-w64-dgn` 3. edit `rebuild_cross.sh` and make the following two changes: a. uncomment `export MAKE_OPT="-j 2"`, if appropriate for your machine b. add `fortran` to the end of `--enable-languages=c,c++,objc,obj-c++` 5. `bash update_source.sh` 4. `bash rebuild_cross.sh` 5. `mv cross ~/cross-w64` 6. `export PATH=$HOME/cross-w64/bin:$PATH` # NOTE: it is important that you remember to always do this before using make in the following steps!, you can put this line in your .profile to make it easy Then we can essentially just repeat these steps for the 32-bit compiler, reusing some of the work: 7. `cd ..` 8. `cp -a mingw-w64-dgn mingw-w32-dgn` 9. `cd mingw-w32-dgn` 10. `rm -r cross build` 11. `bash rebuild_cross.sh 32r` 12. `mv cross ~/cross-w32` 13. `export PATH=$HOME/cross-w32/bin:$PATH` # NOTE: it is important that you remember to always do this before using make in the following steps!, you can put this line in your .profile to make it easy Note: for systems that support rpm-based package managers, the OpenSUSE build service appears to contain a fully up-to-date versions of the necessary dependencies. ### Arch Linux Dependencies 1. Install the following packages from the official Arch repository: `sudo pacman -S cloog gcc-ada libmpc p7zip ppl subversion zlib` 2. The rest of the prerequisites consist of the mingw-w64 packages, which are available in the AUR Arch repository. They must be installed exactly in the order they are given or else their installation will fail. The `yaourt` package manager is used for illustration purposes; you may instead follow the [Arch instructions for installing packages from AUR](https://wiki.archlinux.org/index.php/Arch_User_Repository#Installing_packages) or may use your preferred package manager. To start with, install `mingw-w64-binutils` via the command `yaourt -S mingw-w64-binutils` 3. `yaourt -S mingw-w64-headers-svn` 4. `yaourt -S mingw-w64-headers-bootstrap` 5. `yaourt -S mingw-w64-gcc-base` 6. `yaourt -S mingw-w64-crt-svn` 7. Remove `mingw-w64-headers-bootstrap` without removing its dependent mingw-w64 installed packages by using the command `yaourt -Rdd mingw-w64-headers-bootstrap` 8. `yaourt -S mingw-w64-winpthreads` 9. Remove `mingw-w64-gcc-base` without removing its installed mingw-w64 dependencies: `yaourt -Rdd mingw-w64-gcc-base` 10. Complete the installation of the required `mingw-w64` packages: `yaourt -S mingw-w64-gcc` ### Cross-building Julia Finally, the build and install process for Julia: 1. `git clone https://github.com/JuliaLang/julia.git julia-win32` 2. `echo override XC_HOST = i686-w64-mingw32 >> Make.user` 3. `make` 4. `make win-extras` (Necessary before running `make dist`p) 5. `make dist` 6. move the julia-* directory / zip file to the target machine If you are building for 64-bit windows, the steps are essentially the same. Just replace i686 in XC_HOST with x86_64. (note: on Mac, wine only runs in 32-bit mode) ## Windows Build Debugging ### Build process is slow/eats memory/hangs my computer - Disable the Windows [Superfetch](http://en.wikipedia.org/wiki/Windows_Vista_I/O_technologies#SuperFetch) and [Program Compatibility Assistant](http://blogs.msdn.com/b/cjacks/archive/2011/11/22/managing-the-windows-7-program-compatibility-assistant-pca.aspx) services, as they are known to have [spurious interactions]((https://cygwin.com/ml/cygwin/2011-12/msg00058.html)) with MinGW/Cygwin. As mentioned in the link above: excessive memory use by `svchost` specifically may be investigated in the Task Manager by clicking on the high-memory `svchost.exe` process and selecting `Go to Services`. Disable child services one-by-one until a culprit is found. - Beware of [BLODA](https://cygwin.com/faq/faq.html#faq.using.bloda) The [vmmap](http://technet.microsoft.com/en-us/sysinternals/dd535533.aspx) tool is indispensable for identifying such software conflicts. Use vmmap to inspect the list of loaded DLLs for bash, mintty, or another persistent process used to drive the build. Essentially *any* DLL outside of the Windows System directory is potential BLODA.
shubhamg31/columbus_julia
lib/julia/README.windows.md
Markdown
apache-2.0
17,806
[ 30522, 1001, 2236, 2592, 2005, 3645, 2023, 5371, 5577, 2129, 2000, 16500, 1010, 2030, 3857, 1010, 1998, 2224, 6423, 2006, 3645, 1012, 2005, 2062, 2236, 2592, 2055, 6423, 1010, 3531, 2156, 1996, 1031, 2364, 3191, 4168, 1033, 1006, 16770, 1...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * * (C) COPYRIGHT 2011-2013 ARM Limited. All rights reserved. * * This program is free software and is provided to you under the terms of the * GNU General Public License version 2 as published by the Free Software * Foundation, and any use by you of this program is subject to the terms * of such GNU licence. * * A copy of the licence is included with the program, and can also be obtained * from Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ /** * @file mali_kbase_js.h * Job Scheduler APIs. */ #ifndef _KBASE_JS_H_ #define _KBASE_JS_H_ #include <malisw/mali_malisw.h> #include "mali_kbase_js_defs.h" #include "mali_kbase_js_policy.h" #include "mali_kbase_defs.h" #include "mali_kbase_js_ctx_attr.h" /** * @addtogroup base_api * @{ */ /** * @addtogroup base_kbase_api * @{ */ /** * @addtogroup kbase_js Job Scheduler Internal APIs * @{ * * These APIs are Internal to KBase and are available for use by the * @ref kbase_js_policy "Job Scheduler Policy APIs" */ /** * @brief Initialize the Job Scheduler * * The kbasep_js_device_data sub-structure of \a kbdev must be zero * initialized before passing to the kbasep_js_devdata_init() function. This is * to give efficient error path code. */ mali_error kbasep_js_devdata_init(kbase_device * const kbdev); /** * @brief Halt the Job Scheduler. * * It is safe to call this on \a kbdev even if it the kbasep_js_device_data * sub-structure was never initialized/failed initialization, to give efficient * error-path code. * * For this to work, the kbasep_js_device_data sub-structure of \a kbdev must * be zero initialized before passing to the kbasep_js_devdata_init() * function. This is to give efficient error path code. * * It is a Programming Error to call this whilst there are still kbase_context * structures registered with this scheduler. * */ void kbasep_js_devdata_halt(kbase_device *kbdev); /** * @brief Terminate the Job Scheduler * * It is safe to call this on \a kbdev even if it the kbasep_js_device_data * sub-structure was never initialized/failed initialization, to give efficient * error-path code. * * For this to work, the kbasep_js_device_data sub-structure of \a kbdev must * be zero initialized before passing to the kbasep_js_devdata_init() * function. This is to give efficient error path code. * * It is a Programming Error to call this whilst there are still kbase_context * structures registered with this scheduler. */ void kbasep_js_devdata_term(kbase_device *kbdev); /** * @brief Initialize the Scheduling Component of a kbase_context on the Job Scheduler. * * This effectively registers a kbase_context with a Job Scheduler. * * It does not register any jobs owned by the kbase_context with the scheduler. * Those must be separately registered by kbasep_js_add_job(). * * The kbase_context must be zero intitialized before passing to the * kbase_js_init() function. This is to give efficient error path code. */ mali_error kbasep_js_kctx_init(kbase_context * const kctx); /** * @brief Terminate the Scheduling Component of a kbase_context on the Job Scheduler * * This effectively de-registers a kbase_context from its Job Scheduler * * It is safe to call this on a kbase_context that has never had or failed * initialization of its jctx.sched_info member, to give efficient error-path * code. * * For this to work, the kbase_context must be zero intitialized before passing * to the kbase_js_init() function. * * It is a Programming Error to call this whilst there are still jobs * registered with this context. */ void kbasep_js_kctx_term(kbase_context *kctx); /** * @brief Add a job chain to the Job Scheduler, and take necessary actions to * schedule the context/run the job. * * This atomically does the following: * - Update the numbers of jobs information (including NSS state changes) * - Add the job to the run pool if necessary (part of init_job) * * Once this is done, then an appropriate action is taken: * - If the ctx is scheduled, it attempts to start the next job (which might be * this added job) * - Otherwise, and if this is the first job on the context, it enqueues it on * the Policy Queue * * The Policy's Queue can be updated by this in the following ways: * - In the above case that this is the first job on the context * - If the job is high priority and the context is not scheduled, then it * could cause the Policy to schedule out a low-priority context, allowing * this context to be scheduled in. * * If the context is already scheduled on the RunPool, then adding a job to it * is guarenteed not to update the Policy Queue. And so, the caller is * guarenteed to not need to try scheduling a context from the Run Pool - it * can safely assert that the result is MALI_FALSE. * * It is a programming error to have more than U32_MAX jobs in flight at a time. * * The following locking conditions are made on the caller: * - it must \em not hold kbasep_js_kctx_info::ctx::jsctx_mutex. * - it must \em not hold kbasep_js_device_data::runpool_irq::lock (as this will be * obtained internally) * - it must \em not hold kbasep_js_device_data::runpool_mutex (as this will be * obtained internally) * - it must \em not hold kbasep_jd_device_data::queue_mutex (again, it's used internally). * * @return MALI_TRUE indicates that the Policy Queue was updated, and so the * caller will need to try scheduling a context onto the Run Pool. * @return MALI_FALSE indicates that no updates were made to the Policy Queue, * so no further action is required from the caller. This is \b always returned * when the context is currently scheduled. */ mali_bool kbasep_js_add_job(kbase_context *kctx, kbase_jd_atom *atom); /** * @brief Remove a job chain from the Job Scheduler, except for its 'retained state'. * * Completely removing a job requires several calls: * - kbasep_js_copy_atom_retained_state(), to capture the 'retained state' of * the atom * - kbasep_js_remove_job(), to partially remove the atom from the Job Scheduler * - kbasep_js_runpool_release_ctx_and_katom_retained_state(), to release the * remaining state held as part of the job having been run. * * In the common case of atoms completing normally, this set of actions is more optimal for spinlock purposes than having kbasep_js_remove_job() handle all of the actions. * * In the case of cancelling atoms, it is easier to call kbasep_js_remove_cancelled_job(), which handles all the necessary actions. * * It is a programming error to call this when: * - \a atom is not a job belonging to kctx. * - \a atom has already been removed from the Job Scheduler. * - \a atom is still in the runpool: * - it has not been removed with kbasep_js_policy_dequeue_job() * - or, it has not been removed with kbasep_js_policy_dequeue_job_irq() * * Do not use this for removing jobs being killed by kbase_jd_cancel() - use * kbasep_js_remove_cancelled_job() instead. * * The following locking conditions are made on the caller: * - it must hold kbasep_js_kctx_info::ctx::jsctx_mutex. * */ void kbasep_js_remove_job(kbase_device *kbdev, kbase_context *kctx, kbase_jd_atom *atom); /** * @brief Completely remove a job chain from the Job Scheduler, in the case * where the job chain was cancelled. * * This is a variant of kbasep_js_remove_job() that takes care of removing all * of the retained state too. This is generally useful for cancelled atoms, * which need not be handled in an optimal way. * * As such, this can cause an NSS/SS state transition. In this case, slots that * previously could not have jobs submitted to might now be submittable to. For * this reason, and NSS/SS state transition will cause the Scheduler to try to * submit new jobs on the jm_slots. * * It is a programming error to call this when: * - \a atom is not a job belonging to kctx. * - \a atom has already been removed from the Job Scheduler. * - \a atom is still in the runpool: * - it is not being killed with kbasep_jd_cancel() * - or, it has not been removed with kbasep_js_policy_dequeue_job() * - or, it has not been removed with kbasep_js_policy_dequeue_job_irq() * * The following locking conditions are made on the caller: * - it must hold kbasep_js_kctx_info::ctx::jsctx_mutex. * - it must \em not hold the kbasep_js_device_data::runpool_irq::lock, (as this will be * obtained internally) * - it must \em not hold kbasep_js_device_data::runpool_mutex (as this could be * obtained internally) */ void kbasep_js_remove_cancelled_job(kbase_device *kbdev, kbase_context *kctx, kbase_jd_atom *katom); /** * @brief Refcount a context as being busy, preventing it from being scheduled * out. * * @note This function can safely be called from IRQ context. * * The following locking conditions are made on the caller: * - it must \em not hold the kbasep_js_device_data::runpool_irq::lock, because * it will be used internally. * * @return value != MALI_FALSE if the retain succeeded, and the context will not be scheduled out. * @return MALI_FALSE if the retain failed (because the context is being/has been scheduled out). */ mali_bool kbasep_js_runpool_retain_ctx(kbase_device *kbdev, kbase_context *kctx); /** * @brief Refcount a context as being busy, preventing it from being scheduled * out. * * @note This function can safely be called from IRQ context. * * The following locks must be held by the caller: * - kbasep_js_device_data::runpool_irq::lock * * @return value != MALI_FALSE if the retain succeeded, and the context will not be scheduled out. * @return MALI_FALSE if the retain failed (because the context is being/has been scheduled out). */ mali_bool kbasep_js_runpool_retain_ctx_nolock(kbase_device *kbdev, kbase_context *kctx); /** * @brief Lookup a context in the Run Pool based upon its current address space * and ensure that is stays scheduled in. * * The context is refcounted as being busy to prevent it from scheduling * out. It must be released with kbasep_js_runpool_release_ctx() when it is no * longer required to stay scheduled in. * * @note This function can safely be called from IRQ context. * * The following locking conditions are made on the caller: * - it must \em not hold the kbasep_js_device_data::runpoool_irq::lock, because * it will be used internally. * * @return a valid kbase_context on success, which has been refcounted as being busy. * @return NULL on failure, indicating that no context was found in \a as_nr */ kbase_context *kbasep_js_runpool_lookup_ctx(kbase_device *kbdev, int as_nr); /** * @brief Handling the requeuing/killing of a context that was evicted from the * policy queue or runpool. * * This should be used whenever handing off a context that has been evicted * from the policy queue or the runpool: * - If the context is not dying and has jobs, it gets re-added to the policy * queue * - Otherwise, it is not added * * In addition, if the context is dying the jobs are killed asynchronously. * * In all cases, the Power Manager active reference is released * (kbase_pm_context_idle()) whenever the has_pm_ref parameter is true. \a * has_pm_ref must be set to false whenever the context was not previously in * the runpool and does not hold a Power Manager active refcount. Note that * contexts in a rollback of kbasep_js_try_schedule_head_ctx() might have an * active refcount even though they weren't in the runpool. * * The following locking conditions are made on the caller: * - it must hold kbasep_js_kctx_info::ctx::jsctx_mutex. * - it must \em not hold kbasep_jd_device_data::queue_mutex (as this will be * obtained internally) */ void kbasep_js_runpool_requeue_or_kill_ctx(kbase_device *kbdev, kbase_context *kctx, mali_bool has_pm_ref); /** * @brief Release a refcount of a context being busy, allowing it to be * scheduled out. * * When the refcount reaches zero and the context \em might be scheduled out * (depending on whether the Scheudling Policy has deemed it so, or if it has run * out of jobs). * * If the context does get scheduled out, then The following actions will be * taken as part of deschduling a context: * - For the context being descheduled: * - If the context is in the processing of dying (all the jobs are being * removed from it), then descheduling also kills off any jobs remaining in the * context. * - If the context is not dying, and any jobs remain after descheduling the * context then it is re-enqueued to the Policy's Queue. * - Otherwise, the context is still known to the scheduler, but remains absent * from the Policy Queue until a job is next added to it. * - In all descheduling cases, the Power Manager active reference (obtained * during kbasep_js_try_schedule_head_ctx()) is released (kbase_pm_context_idle()). * * Whilst the context is being descheduled, this also handles actions that * cause more atoms to be run: * - Attempt submitting atoms when the Context Attributes on the Runpool have * changed. This is because the context being scheduled out could mean that * there are more opportunities to run atoms. * - Attempt submitting to a slot that was previously blocked due to affinity * restrictions. This is usually only necessary when releasing a context * happens as part of completing a previous job, but is harmless nonetheless. * - Attempt scheduling in a new context (if one is available), and if necessary, * running a job from that new context. * * Unlike retaining a context in the runpool, this function \b cannot be called * from IRQ context. * * It is a programming error to call this on a \a kctx that is not currently * scheduled, or that already has a zero refcount. * * The following locking conditions are made on the caller: * - it must \em not hold the kbasep_js_device_data::runpool_irq::lock, because * it will be used internally. * - it must \em not hold kbasep_js_kctx_info::ctx::jsctx_mutex. * - it must \em not hold kbasep_js_device_data::runpool_mutex (as this will be * obtained internally) * - it must \em not hold the kbase_device::as[n].transaction_mutex (as this will be obtained internally) * - it must \em not hold kbasep_jd_device_data::queue_mutex (as this will be * obtained internally) * */ void kbasep_js_runpool_release_ctx(kbase_device *kbdev, kbase_context *kctx); /** * @brief Variant of kbasep_js_runpool_release_ctx() that handles additional * actions from completing an atom. * * This is usually called as part of completing an atom and releasing the * refcount on the context held by the atom. * * Therefore, the extra actions carried out are part of handling actions queued * on a completed atom, namely: * - Releasing the atom's context attributes * - Retrying the submission on a particular slot, because we couldn't submit * on that slot from an IRQ handler. * * The locking conditions of this function are the same as those for * kbasep_js_runpool_release_ctx() */ void kbasep_js_runpool_release_ctx_and_katom_retained_state(kbase_device *kbdev, kbase_context *kctx, kbasep_js_atom_retained_state *katom_retained_state); /** * @brief Try to submit the next job on a \b particular slot whilst in IRQ * context, and whilst the caller already holds the runpool IRQ spinlock. * * \a *submit_count will be checked against * KBASE_JS_MAX_JOB_SUBMIT_PER_SLOT_PER_IRQ to see whether too many jobs have * been submitted. This is to prevent the IRQ handler looping over lots of GPU * NULL jobs, which may complete whilst the IRQ handler is still processing. \a * submit_count itself should point to kbase_device::slot_submit_count_irq[ \a js ], * which is initialized to zero on entry to the IRQ handler. * * The following locks must be held by the caller: * - kbasep_js_device_data::runpool_irq::lock * * @return truthful (i.e. != MALI_FALSE) if too many jobs were submitted from * IRQ. Therefore, this indicates that submission should be retried from a * work-queue, by using * kbasep_js_try_run_next_job_on_slot_nolock()/kbase_js_try_run_jobs_on_slot(). * @return MALI_FALSE if submission had no problems: the GPU is either already * full of jobs in the HEAD and NEXT registers, or we were able to get enough * jobs from the Run Pool to fill the GPU's HEAD and NEXT registers. */ mali_bool kbasep_js_try_run_next_job_on_slot_irq_nolock(kbase_device *kbdev, int js, s8 *submit_count); /** * @brief Try to submit the next job on a particular slot, outside of IRQ context * * This obtains the Job Slot lock for the duration of the call only. * * Unlike kbasep_js_try_run_next_job_on_slot_irq_nolock(), there is no limit on * submission, because eventually IRQ_THROTTLE will kick in to prevent us * getting stuck in a loop of submitting GPU NULL jobs. This is because the IRQ * handler will be delayed, and so this function will eventually fill up the * space in our software 'submitted' slot (kbase_jm_slot::submitted). * * In addition, there's no return value - we'll run the maintenence functions * on the Policy's Run Pool, but if there's nothing there after that, then the * Run Pool is truely empty, and so no more action need be taken. * * The following locking conditions are made on the caller: * - it must hold kbasep_js_device_data::runpool_mutex * - it must hold kbasep_js_device_data::runpool_irq::lock * * This must only be called whilst the GPU is powered - for example, when * kbdev->jsdata.nr_user_contexts_running > 0. * * @note The caller \em might be holding one of the * kbasep_js_kctx_info::ctx::jsctx_mutex locks. * */ void kbasep_js_try_run_next_job_on_slot_nolock(kbase_device *kbdev, int js); /** * @brief Try to submit the next job for each slot in the system, outside of IRQ context * * This will internally call kbasep_js_try_run_next_job_on_slot_nolock(), so similar * locking conditions on the caller are required. * * The following locking conditions are made on the caller: * - it must hold kbasep_js_device_data::runpool_mutex * - it must hold kbasep_js_device_data::runpool_irq::lock * * @note The caller \em might be holding one of the * kbasep_js_kctx_info::ctx::jsctx_mutex locks. * */ void kbasep_js_try_run_next_job_nolock(kbase_device *kbdev); /** * @brief Try to schedule the next context onto the Run Pool * * This checks whether there's space in the Run Pool to accommodate a new * context. If so, it attempts to dequeue a context from the Policy Queue, and * submit this to the Run Pool. * * If the scheduling succeeds, then it also makes a call to * kbasep_js_try_run_next_job_nolock(), in case the new context has jobs * matching the job slot requirements, but no other currently scheduled context * has such jobs. * * Whilst attempting to obtain a context from the policy queue, or add a * context to the runpool, this function takes a Power Manager active * reference. If for any reason a context cannot be added to the runpool, any * reference obtained is released once the context is safely back in the policy * queue. If no context was available on the policy queue, any reference * obtained is released too. * * Only if the context gets placed in the runpool does the Power Manager active * reference stay held (and is effectively now owned by the * context/runpool). It is only released once the context is removed * completely, or added back to the policy queue * (e.g. kbasep_js_runpool_release_ctx(), * kbasep_js_runpool_requeue_or_kill_ctx(), etc) * * If any of these actions fail (Run Pool Full, Policy Queue empty, can't get * PM active reference due to a suspend, etc) then any actions taken are rolled * back and the function just returns normally. * * The following locking conditions are made on the caller: * - it must \em not hold the kbasep_js_device_data::runpool_irq::lock, because * it will be used internally. * - it must \em not hold kbasep_js_device_data::runpool_mutex (as this will be * obtained internally) * - it must \em not hold the kbase_device::as[n].transaction_mutex (as this will be obtained internally) * - it must \em not hold kbasep_jd_device_data::queue_mutex (again, it's used internally). * - it must \em not hold kbasep_js_kctx_info::ctx::jsctx_mutex, because it will * be used internally. * */ void kbasep_js_try_schedule_head_ctx(kbase_device *kbdev); /** * @brief Schedule in a privileged context * * This schedules a context in regardless of the context priority. * If the runpool is full, a context will be forced out of the runpool and the function will wait * for the new context to be scheduled in. * The context will be kept scheduled in (and the corresponding address space reserved) until * kbasep_js_release_privileged_ctx is called). * * The following locking conditions are made on the caller: * - it must \em not hold the kbasep_js_device_data::runpool_irq::lock, because * it will be used internally. * - it must \em not hold kbasep_js_device_data::runpool_mutex (as this will be * obtained internally) * - it must \em not hold the kbase_device::as[n].transaction_mutex (as this will be obtained internally) * - it must \em not hold kbasep_jd_device_data::queue_mutex (again, it's used internally). * - it must \em not hold kbasep_js_kctx_info::ctx::jsctx_mutex, because it will * be used internally. * */ void kbasep_js_schedule_privileged_ctx(kbase_device *kbdev, kbase_context *kctx); /** * @brief Release a privileged context, allowing it to be scheduled out. * * See kbasep_js_runpool_release_ctx for potential side effects. * * The following locking conditions are made on the caller: * - it must \em not hold the kbasep_js_device_data::runpool_irq::lock, because * it will be used internally. * - it must \em not hold kbasep_js_kctx_info::ctx::jsctx_mutex. * - it must \em not hold kbasep_js_device_data::runpool_mutex (as this will be * obtained internally) * - it must \em not hold the kbase_device::as[n].transaction_mutex (as this will be obtained internally) * */ void kbasep_js_release_privileged_ctx(kbase_device *kbdev, kbase_context *kctx); /** * @brief Handle the Job Scheduler component for the IRQ of a job finishing * * This does the following: * -# Releases resources held by the atom * -# if \a end_timestamp != NULL, updates the runpool's notion of time spent by a running ctx * -# determines whether a context should be marked for scheduling out * -# examines done_code to determine whether to submit the next job on the slot * (picking from all ctxs in the runpool) * * In addition, if submission didn't happen (the submit-from-IRQ function * failed or done_code didn't specify to start new jobs), then this sets a * message on katom that submission needs to be retried from the worker thread. * * Normally, the time calculated from end_timestamp is rounded up to the * minimum time precision. Therefore, to ensure the job is recorded as not * spending any time, then set end_timestamp to NULL. For example, this is necessary when * evicting jobs from JSn_HEAD_NEXT (because they didn't actually run). * * NOTE: It's possible to move the steps (2) and (3) (inc calculating job's time * used) into the worker (outside of IRQ context), but this may allow a context * to use up to twice as much timeslice as is allowed by the policy. For * policies that order by time spent, this is not a problem for overall * 'fairness', but can still increase latency between contexts. * * The following locking conditions are made on the caller: * - it must hold kbasep_js_device_data::runpoool_irq::lock */ void kbasep_js_job_done_slot_irq(kbase_jd_atom *katom, int slot_nr, ktime_t *end_timestamp, kbasep_js_atom_done_code done_code); /** * @brief Try to submit the next job on each slot * * The following locks may be used: * - kbasep_js_device_data::runpool_mutex * - kbasep_js_device_data::runpool_irq::lock */ void kbase_js_try_run_jobs(kbase_device *kbdev); /** * @brief Try to submit the next job on a specfic slot * * The following locking conditions are made on the caller: * * - it must \em not hold kbasep_js_device_data::runpool_mutex (as this will be * obtained internally) * - it must \em not hold kbasep_js_device_data::runpool_irq::lock (as this * will be obtained internally) * */ void kbase_js_try_run_jobs_on_slot(kbase_device *kbdev, int js); /** * @brief Handle releasing cores for power management and affinity management, * ensuring that cores are powered down and affinity tracking is updated. * * This must only be called on an atom that is not currently running, and has * not been re-queued onto the context (and so does not need locking) * * This function enters at the following @ref kbase_atom_coreref_state states: * - NO_CORES_REQUESTED * - WAITING_FOR_REQUESTED_CORES * - RECHECK_AFFINITY * - READY * * It transitions the above states back to NO_CORES_REQUESTED by the end of the * function call (possibly via intermediate states). * * No locks need be held by the caller, since this takes the necessary Power * Management locks itself. The runpool_irq.lock is not taken (the work that * requires it is handled by kbase_js_affinity_submit_to_blocked_slots() ). * * @note The corresponding kbasep_js_job_check_ref_cores() is private to the * Job Scheduler, and is called automatically when running the next job. */ void kbasep_js_job_check_deref_cores(kbase_device *kbdev, struct kbase_jd_atom *katom); /** * @brief Suspend the job scheduler during a Power Management Suspend event. * * Causes all contexts to be removed from the runpool, and prevents any * contexts from (re)entering the runpool. * * This does not handle suspending the one privileged context: the caller must * instead do this by by suspending the GPU HW Counter Instrumentation. * * This will eventually cause all Power Management active references held by * contexts on the runpool to be released, without running any more atoms. * * The caller must then wait for all Power Mangement active refcount to become * zero before completing the suspend. * * The emptying mechanism may take some time to complete, since it can wait for * jobs to complete naturally instead of forcing them to end quickly. However, * this is bounded by the Job Scheduling Policy's Job Timeouts. Hence, this * function is guaranteed to complete in a finite time whenever the Job * Scheduling Policy implements Job Timeouts (such as those done by CFS). */ void kbasep_js_suspend(kbase_device *kbdev); /** * @brief Resume the Job Scheduler after a Power Management Resume event. * * This restores the actions from kbasep_js_suspend(): * - Schedules contexts back into the runpool * - Resumes running atoms on the GPU */ void kbasep_js_resume(kbase_device *kbdev); /* * Helpers follow */ /** * @brief Check that a context is allowed to submit jobs on this policy * * The purpose of this abstraction is to hide the underlying data size, and wrap up * the long repeated line of code. * * As with any mali_bool, never test the return value with MALI_TRUE. * * The caller must hold kbasep_js_device_data::runpool_irq::lock. */ static INLINE mali_bool kbasep_js_is_submit_allowed(kbasep_js_device_data *js_devdata, kbase_context *kctx) { u16 test_bit; /* Ensure context really is scheduled in */ KBASE_DEBUG_ASSERT(kctx->as_nr != KBASEP_AS_NR_INVALID); KBASE_DEBUG_ASSERT(kctx->jctx.sched_info.ctx.is_scheduled != MALI_FALSE); test_bit = (u16) (1u << kctx->as_nr); return (mali_bool) (js_devdata->runpool_irq.submit_allowed & test_bit); } /** * @brief Allow a context to submit jobs on this policy * * The purpose of this abstraction is to hide the underlying data size, and wrap up * the long repeated line of code. * * The caller must hold kbasep_js_device_data::runpool_irq::lock. */ static INLINE void kbasep_js_set_submit_allowed(kbasep_js_device_data *js_devdata, kbase_context *kctx) { u16 set_bit; /* Ensure context really is scheduled in */ KBASE_DEBUG_ASSERT(kctx->as_nr != KBASEP_AS_NR_INVALID); KBASE_DEBUG_ASSERT(kctx->jctx.sched_info.ctx.is_scheduled != MALI_FALSE); set_bit = (u16) (1u << kctx->as_nr); KBASE_DEBUG_PRINT_INFO(KBASE_JM, "JS: Setting Submit Allowed on %p (as=%d)", kctx, kctx->as_nr); js_devdata->runpool_irq.submit_allowed |= set_bit; } /** * @brief Prevent a context from submitting more jobs on this policy * * The purpose of this abstraction is to hide the underlying data size, and wrap up * the long repeated line of code. * * The caller must hold kbasep_js_device_data::runpool_irq::lock. */ static INLINE void kbasep_js_clear_submit_allowed(kbasep_js_device_data *js_devdata, kbase_context *kctx) { u16 clear_bit; u16 clear_mask; /* Ensure context really is scheduled in */ KBASE_DEBUG_ASSERT(kctx->as_nr != KBASEP_AS_NR_INVALID); KBASE_DEBUG_ASSERT(kctx->jctx.sched_info.ctx.is_scheduled != MALI_FALSE); clear_bit = (u16) (1u << kctx->as_nr); clear_mask = ~clear_bit; KBASE_DEBUG_PRINT_INFO(KBASE_JM, "JS: Clearing Submit Allowed on %p (as=%d)", kctx, kctx->as_nr); js_devdata->runpool_irq.submit_allowed &= clear_mask; } /** * @brief Manage the 'retry_submit_on_slot' part of a kbase_jd_atom */ static INLINE void kbasep_js_clear_job_retry_submit(kbase_jd_atom *atom) { atom->retry_submit_on_slot = KBASEP_JS_RETRY_SUBMIT_SLOT_INVALID; } static INLINE void kbasep_js_set_job_retry_submit_slot(kbase_jd_atom *atom, int js) { KBASE_DEBUG_ASSERT(0 <= js && js <= BASE_JM_MAX_NR_SLOTS); atom->retry_submit_on_slot = js; } /** * Create an initial 'invalid' atom retained state, that requires no * atom-related work to be done on releasing with * kbasep_js_runpool_release_ctx_and_katom_retained_state() */ static INLINE void kbasep_js_atom_retained_state_init_invalid(kbasep_js_atom_retained_state *retained_state) { retained_state->event_code = BASE_JD_EVENT_NOT_STARTED; retained_state->core_req = KBASEP_JS_ATOM_RETAINED_STATE_CORE_REQ_INVALID; retained_state->retry_submit_on_slot = KBASEP_JS_RETRY_SUBMIT_SLOT_INVALID; } /** * Copy atom state that can be made available after jd_done_nolock() is called * on that atom. */ static INLINE void kbasep_js_atom_retained_state_copy(kbasep_js_atom_retained_state *retained_state, const kbase_jd_atom *katom) { retained_state->event_code = katom->event_code; retained_state->core_req = katom->core_req; retained_state->retry_submit_on_slot = katom->retry_submit_on_slot; } /** * @brief Determine whether an atom has finished (given its retained state), * and so should be given back to userspace/removed from the system. * * Reasons for an atom not finishing include: * - Being soft-stopped (and so, the atom should be resubmitted sometime later) * * @param[in] katom_retained_state the retained state of the atom to check * @return MALI_FALSE if the atom has not finished * @return !=MALI_FALSE if the atom has finished */ static INLINE mali_bool kbasep_js_has_atom_finished(const kbasep_js_atom_retained_state *katom_retained_state) { return (mali_bool) (katom_retained_state->event_code != BASE_JD_EVENT_STOPPED && katom_retained_state->event_code != BASE_JD_EVENT_REMOVED_FROM_NEXT); } /** * @brief Determine whether a kbasep_js_atom_retained_state is valid * * An invalid kbasep_js_atom_retained_state is allowed, and indicates that the * code should just ignore it. * * @param[in] katom_retained_state the atom's retained state to check * @return MALI_FALSE if the retained state is invalid, and can be ignored * @return !=MALI_FALSE if the retained state is valid */ static INLINE mali_bool kbasep_js_atom_retained_state_is_valid(const kbasep_js_atom_retained_state *katom_retained_state) { return (mali_bool) (katom_retained_state->core_req != KBASEP_JS_ATOM_RETAINED_STATE_CORE_REQ_INVALID); } static INLINE mali_bool kbasep_js_get_atom_retry_submit_slot(const kbasep_js_atom_retained_state *katom_retained_state, int *res) { int js = katom_retained_state->retry_submit_on_slot; *res = js; return (mali_bool) (js >= 0); } #if KBASE_DEBUG_DISABLE_ASSERTS == 0 /** * Debug Check the refcount of a context. Only use within ASSERTs * * Obtains kbasep_js_device_data::runpool_irq::lock * * @return negative value if the context is not scheduled in * @return current refcount of the context if it is scheduled in. The refcount * is not guarenteed to be kept constant. */ static INLINE int kbasep_js_debug_check_ctx_refcount(kbase_device *kbdev, kbase_context *kctx) { unsigned long flags; kbasep_js_device_data *js_devdata; int result = -1; int as_nr; KBASE_DEBUG_ASSERT(kbdev != NULL); KBASE_DEBUG_ASSERT(kctx != NULL); js_devdata = &kbdev->js_data; spin_lock_irqsave(&js_devdata->runpool_irq.lock, flags); as_nr = kctx->as_nr; if (as_nr != KBASEP_AS_NR_INVALID) result = js_devdata->runpool_irq.per_as_data[as_nr].as_busy_refcount; spin_unlock_irqrestore(&js_devdata->runpool_irq.lock, flags); return result; } #endif /* KBASE_DEBUG_DISABLE_ASSERTS == 0 */ /** * @brief Variant of kbasep_js_runpool_lookup_ctx() that can be used when the * context is guarenteed to be already previously retained. * * It is a programming error to supply the \a as_nr of a context that has not * been previously retained/has a busy refcount of zero. The only exception is * when there is no ctx in \a as_nr (NULL returned). * * The following locking conditions are made on the caller: * - it must \em not hold the kbasep_js_device_data::runpoool_irq::lock, because * it will be used internally. * * @return a valid kbase_context on success, with a refcount that is guarenteed * to be non-zero and unmodified by this function. * @return NULL on failure, indicating that no context was found in \a as_nr */ static INLINE kbase_context *kbasep_js_runpool_lookup_ctx_noretain(kbase_device *kbdev, int as_nr) { unsigned long flags; kbasep_js_device_data *js_devdata; kbase_context *found_kctx; kbasep_js_per_as_data *js_per_as_data; KBASE_DEBUG_ASSERT(kbdev != NULL); KBASE_DEBUG_ASSERT(0 <= as_nr && as_nr < BASE_MAX_NR_AS); js_devdata = &kbdev->js_data; js_per_as_data = &js_devdata->runpool_irq.per_as_data[as_nr]; spin_lock_irqsave(&js_devdata->runpool_irq.lock, flags); found_kctx = js_per_as_data->kctx; KBASE_DEBUG_ASSERT(found_kctx == NULL || js_per_as_data->as_busy_refcount > 0); spin_unlock_irqrestore(&js_devdata->runpool_irq.lock, flags); return found_kctx; } /** * This will provide a conversion from time (us) to ticks of the gpu clock * based on the minimum available gpu frequency. * This is usually good to compute best/worst case (where the use of current * frequency is not valid due to DVFS). * e.g.: when you need the number of cycles to guarantee you won't wait for * longer than 'us' time (you might have a shorter wait). */ static INLINE u32 kbasep_js_convert_us_to_gpu_ticks_min_freq(kbase_device *kbdev, u32 us) { u32 gpu_freq = kbdev->gpu_props.props.core_props.gpu_freq_khz_min; KBASE_DEBUG_ASSERT(0 != gpu_freq); return us * (gpu_freq / 1000); } /** * This will provide a conversion from time (us) to ticks of the gpu clock * based on the maximum available gpu frequency. * This is usually good to compute best/worst case (where the use of current * frequency is not valid due to DVFS). * e.g.: When you need the number of cycles to guarantee you'll wait at least * 'us' amount of time (but you might wait longer). */ static INLINE u32 kbasep_js_convert_us_to_gpu_ticks_max_freq(kbase_device *kbdev, u32 us) { u32 gpu_freq = kbdev->gpu_props.props.core_props.gpu_freq_khz_max; KBASE_DEBUG_ASSERT(0 != gpu_freq); return us * (u32) (gpu_freq / 1000); } /** * This will provide a conversion from ticks of the gpu clock to time (us) * based on the minimum available gpu frequency. * This is usually good to compute best/worst case (where the use of current * frequency is not valid due to DVFS). * e.g.: When you need to know the worst-case wait that 'ticks' cycles will * take (you guarantee that you won't wait any longer than this, but it may * be shorter). */ static INLINE u32 kbasep_js_convert_gpu_ticks_to_us_min_freq(kbase_device *kbdev, u32 ticks) { u32 gpu_freq = kbdev->gpu_props.props.core_props.gpu_freq_khz_min; KBASE_DEBUG_ASSERT(0 != gpu_freq); return ticks / gpu_freq * 1000; } /** * This will provide a conversion from ticks of the gpu clock to time (us) * based on the maximum available gpu frequency. * This is usually good to compute best/worst case (where the use of current * frequency is not valid due to DVFS). * e.g.: When you need to know the best-case wait for 'tick' cycles (you * guarantee to be waiting for at least this long, but it may be longer). */ static INLINE u32 kbasep_js_convert_gpu_ticks_to_us_max_freq(kbase_device *kbdev, u32 ticks) { u32 gpu_freq = kbdev->gpu_props.props.core_props.gpu_freq_khz_max; KBASE_DEBUG_ASSERT(0 != gpu_freq); return ticks / gpu_freq * 1000; } /** @} *//* end group kbase_js */ /** @} *//* end group base_kbase_api */ /** @} *//* end group base_api */ #endif /* _KBASE_JS_H_ */
exynos-reference/kernel
drivers/gpu/arm/t6xx/kbase/src/common/mali_kbase_js.h
C
gpl-2.0
37,266
[ 30522, 1013, 1008, 1008, 1008, 1006, 1039, 1007, 9385, 2249, 1011, 2286, 2849, 3132, 1012, 2035, 2916, 9235, 1012, 1008, 1008, 2023, 2565, 2003, 2489, 4007, 1998, 2003, 3024, 2000, 2017, 2104, 1996, 3408, 1997, 1996, 1008, 27004, 2236, 22...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>killerbee.openear.gps.gps'</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="killerbee-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="http://code.google.com/p/killerbee/">KillerBee</a></th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="killerbee-module.html">Package&nbsp;killerbee</a> :: <a href="killerbee.openear-module.html">Package&nbsp;openear</a> :: <a href="killerbee.openear.gps-module.html">Package&nbsp;gps</a> :: Module&nbsp;gps' </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="killerbee.openear.gps.gps%27-module.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== MODULE DESCRIPTION ==================== --> <h1 class="epydoc">Module gps'</h1><p class="nomargin-top"><span class="codelink"><a href="killerbee.openear.gps.gps%27-pysrc.html">source&nbsp;code</a></span></p> <!-- ==================== CLASSES ==================== --> <a name="section-Classes"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Classes</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Classes" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="killerbee.openear.gps.gps%27.gps-class.html" class="summary-name">gps</a><br /> Client interface to a running gpsd instance. </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="killerbee.openear.gps.gps%27.gpsdata-class.html" class="summary-name">gpsdata</a><br /> Position, track, velocity and status information returned by a GPS. </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a href="killerbee.openear.gps.gps%27.gpsfix-class.html" class="summary-name">gpsfix</a> </td> </tr> </table> <!-- ==================== FUNCTIONS ==================== --> <a name="section-Functions"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Functions</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Functions" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a name="isnan"></a><span class="summary-sig-name">isnan</span>(<span class="summary-sig-arg">x</span>)</span></td> <td align="right" valign="top"> <span class="codelink"><a href="killerbee.openear.gps.gps%27-pysrc.html#isnan">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> </table> <!-- ==================== VARIABLES ==================== --> <a name="section-Variables"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Variables</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Variables" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="AIS_SET"></a><span class="summary-name">AIS_SET</span> = <code title="268435456">268435456</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="ALTITUDE_SET"></a><span class="summary-name">ALTITUDE_SET</span> = <code title="16">16</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="ATTITUDE_SET"></a><span class="summary-name">ATTITUDE_SET</span> = <code title="16384">16384</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="AUXDATA_SET"></a><span class="summary-name">AUXDATA_SET</span> = <code title="2147483648">2147483648</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CLIMBERR_SET"></a><span class="summary-name">CLIMBERR_SET</span> = <code title="2097152">2097152</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="CLIMB_SET"></a><span class="summary-name">CLIMB_SET</span> = <code title="128">128</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="DEVICEID_SET"></a><span class="summary-name">DEVICEID_SET</span> = <code title="16777216">16777216</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="DEVICELIST_SET"></a><span class="summary-name">DEVICELIST_SET</span> = <code title="8388608">8388608</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="DEVICE_SET"></a><span class="summary-name">DEVICE_SET</span> = <code title="4194304">4194304</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="DOP_SET"></a><span class="summary-name">DOP_SET</span> = <code title="1024">1024</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="ERROR_SET"></a><span class="summary-name">ERROR_SET</span> = <code title="33554432">33554432</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="GPSD_PORT"></a><span class="summary-name">GPSD_PORT</span> = <code title="'2947'"><code class="variable-quote">'</code><code class="variable-string">2947</code><code class="variable-quote">'</code></code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="HERR_SET"></a><span class="summary-name">HERR_SET</span> = <code title="4096">4096</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="LATLON_SET"></a><span class="summary-name">LATLON_SET</span> = <code title="8">8</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MAXCHANNELS"></a><span class="summary-name">MAXCHANNELS</span> = <code title="20">20</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MODE_2D"></a><span class="summary-name">MODE_2D</span> = <code title="2">2</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MODE_3D"></a><span class="summary-name">MODE_3D</span> = <code title="3">3</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MODE_NO_FIX"></a><span class="summary-name">MODE_NO_FIX</span> = <code title="1">1</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="MODE_SET"></a><span class="summary-name">MODE_SET</span> = <code title="512">512</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="NaN"></a><span class="summary-name">NaN</span> = <code title="nan">nan</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="ONLINE_SET"></a><span class="summary-name">ONLINE_SET</span> = <code title="1">1</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="PACKET_SET"></a><span class="summary-name">PACKET_SET</span> = <code title="536870912">536870912</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="POLICY_SET"></a><span class="summary-name">POLICY_SET</span> = <code title="32768">32768</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="RAW_SET"></a><span class="summary-name">RAW_SET</span> = <code title="131072">131072</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="RTCM2_SET"></a><span class="summary-name">RTCM2_SET</span> = <code title="67108864">67108864</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="RTCM3_SET"></a><span class="summary-name">RTCM3_SET</span> = <code title="134217728">134217728</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SATELLITE_SET"></a><span class="summary-name">SATELLITE_SET</span> = <code title="65536">65536</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SIGNAL_STRENGTH_UNKNOWN"></a><span class="summary-name">SIGNAL_STRENGTH_UNKNOWN</span> = <code title="nan">nan</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SPEEDERR_SET"></a><span class="summary-name">SPEEDERR_SET</span> = <code title="524288">524288</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="SPEED_SET"></a><span class="summary-name">SPEED_SET</span> = <code title="32">32</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="STATUS_DGPS_FIX"></a><span class="summary-name">STATUS_DGPS_FIX</span> = <code title="2">2</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="STATUS_FIX"></a><span class="summary-name">STATUS_FIX</span> = <code title="1">1</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="STATUS_NO_FIX"></a><span class="summary-name">STATUS_NO_FIX</span> = <code title="0">0</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="STATUS_SET"></a><span class="summary-name">STATUS_SET</span> = <code title="256">256</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="TIMERR_SET"></a><span class="summary-name">TIMERR_SET</span> = <code title="4">4</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="TIME_SET"></a><span class="summary-name">TIME_SET</span> = <code title="2">2</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="TRACKERR_SET"></a><span class="summary-name">TRACKERR_SET</span> = <code title="1048576">1048576</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="TRACK_SET"></a><span class="summary-name">TRACK_SET</span> = <code title="64">64</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="UNION_SET"></a><span class="summary-name">UNION_SET</span> = <code title="511707136">511707136</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="USED_SET"></a><span class="summary-name">USED_SET</span> = <code title="262144">262144</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="VERR_SET"></a><span class="summary-name">VERR_SET</span> = <code title="8192">8192</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="VERSION_SET"></a><span class="summary-name">VERSION_SET</span> = <code title="2048">2048</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_DEVICE"></a><span class="summary-name">WATCH_DEVICE</span> = <code title="64">64</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_DISABLE"></a><span class="summary-name">WATCH_DISABLE</span> = <code title="0">0</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_ENABLE"></a><span class="summary-name">WATCH_ENABLE</span> = <code title="1">1</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_JSON"></a><span class="summary-name">WATCH_JSON</span> = <code title="2">2</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_NEWSTYLE"></a><span class="summary-name">WATCH_NEWSTYLE</span> = <code title="128">128</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_NMEA"></a><span class="summary-name">WATCH_NMEA</span> = <code title="4">4</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_OLDSTYLE"></a><span class="summary-name">WATCH_OLDSTYLE</span> = <code title="65536">65536</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_RARE"></a><span class="summary-name">WATCH_RARE</span> = <code title="8">8</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_RAW"></a><span class="summary-name">WATCH_RAW</span> = <code title="16">16</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="WATCH_SCALED"></a><span class="summary-name">WATCH_SCALED</span> = <code title="32">32</code> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <a name="__package__"></a><span class="summary-name">__package__</span> = <code title="'killerbee.openear.gps'"><code class="variable-quote">'</code><code class="variable-string">killerbee.openear.gps</code><code class="variable-quote">'</code></code> </td> </tr> </table> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="killerbee-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="http://code.google.com/p/killerbee/">KillerBee</a></th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Mon Dec 30 17:49:12 2013 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
rfmcpherson/killerbee
doc/killerbee.openear.gps.gps'-module.html
HTML
bsd-3-clause
22,847
[ 30522, 1026, 1029, 20950, 2544, 1027, 1000, 1015, 1012, 1014, 1000, 17181, 1027, 1000, 2004, 6895, 2072, 1000, 1029, 1028, 1026, 999, 9986, 13874, 16129, 2270, 1000, 1011, 1013, 1013, 1059, 2509, 2278, 1013, 1013, 26718, 2094, 1060, 11039, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Temporary shim to keep a couple dependencies working in Chromium. #ifndef SkOrderedReadBuffer_DEFINED # define SkOrderedReadBuffer_DEFINED # include "src/core/SkReadBuffer.h" typedef SkReadBuffer SkOrderedReadBuffer; #endif
satya-das/cppparser
test/e2e/test_master/skia/src/core/SkOrderedReadBuffer.h
C
mit
229
[ 30522, 1013, 1013, 5741, 11895, 2213, 2000, 2562, 1037, 3232, 12530, 15266, 2551, 1999, 10381, 21716, 5007, 1012, 1001, 2065, 13629, 2546, 15315, 8551, 6850, 16416, 18939, 16093, 7512, 1035, 4225, 1001, 9375, 15315, 8551, 6850, 16416, 18939, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
#!/bin/bash echo "#########################################" echo "Building node version 0.12.15" echo "#########################################" docker build -t dockbit/node:0.12.15 .
Dockbit/library
node/0.12.15/build.sh
Shell
apache-2.0
187
[ 30522, 1001, 999, 1013, 8026, 1013, 24234, 9052, 1000, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 1001, 100...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * \file PancakeNode.hpp * * * * \author eaburns * \date 18-01-2010 */ #include "search/Node.hpp" #include "pancake/PancakeTypes.hpp" #include "pancake/PancakeState.hpp" #if !defined(_PANCAKE_NODE_H_) #define _PANCAKE_NODE_H_ typedef Node<PancakeState14, PancakeCost> PancakeNode14; #endif // !_PANCAKE_NODE_H_
bradlarsen/switchback
src/pancake/PancakeNode.hpp
C++
bsd-3-clause
326
[ 30522, 1013, 1008, 30524, 6090, 17955, 13874, 2015, 1012, 6522, 2361, 1000, 1001, 2421, 1000, 6090, 17955, 1013, 28470, 12259, 1012, 6522, 2361, 1000, 1001, 2065, 999, 4225, 1006, 1035, 6090, 17955, 1035, 13045, 1035, 1044, 1035, 1007, 1001...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (C) 2010 ETH Zurich * * This file is part of Fosstrak (www.fosstrak.org) and * was developed as part of the webofthings.com initiative. * * Fosstrak is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * Fosstrak is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Fosstrak; if not, write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA */ package org.fosstrak.webadapters.epcis.model.events; import org.fosstrak.webadapters.epcis.model.Entry; import org.fosstrak.webadapters.epcis.ws.generated.EPCISEventType; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * The JAXB class to handle Quantity Events of the EPCIS Webadapter model * @author Mathias Mueller mathias.mueller(at)unifr.ch, <a href="http://www.guinard.org">Dominique Guinard</a> */ @XmlRootElement(namespace = "fosstrak.org/epcis/restadapter") @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) public class QuantityEvent extends EPCISEvent { public QuantityEvent() {} /** * Constructs the event class. * * * @param event * @param index */ public QuantityEvent(EPCISEventType event) { super(event); initFillSpecificData(); super.setUp(); } protected String getEpcClass() { String res = ""; if (epcClass != null) { res = epcClass; } return res; } protected String getQuantity() { String res = ""; if (quantity != Integer.MIN_VALUE) { res = "" + quantity; } return res; } /** * Method description * * * @return */ @XmlElement(name = "quantity") public Entry getQuantityEntry() { return quantityEntry; } /** * Method description * * * @param quantityEntry */ public void setQuantityEntry(Entry quantityEntry) { this.quantityEntry = quantityEntry; } /** * Method description * * * @return */ @XmlElement(name = "epcClass") public Entry getEpcClassEntry() { return epcClassEntry; } /** * Method description * * * @param epcClassEntry */ public void setEpcClassEntry(Entry epcClassEntry) { this.epcClassEntry = epcClassEntry; } /** * Method description * */ @Override public void initFillSpecificData() { if (!getQuantity().equals("")) { quantityEntry = new Entry(); quantityEntry.setValue(getQuantity()); } if (!getEpcClass().equals("")) { epcClassEntry = new Entry(); epcClassEntry.setValue(getEpcClass()); } } /** * Method description * * * @param otherEvent * * @return */ @Override public boolean isSubclassLikeEvent(EPCISEvent otherEvent) { boolean res = true; if (!(otherEvent instanceof QuantityEvent)) { return false; } QuantityEvent otherSubclassEvent = (QuantityEvent) otherEvent; try { if (!(getEpcClassEntry().getValue().equals(otherSubclassEvent.getEpcClassEntry().getValue()))) { return false; } } catch (Exception ex) {} try { if (!(getQuantityEntry().getValue().equals(otherSubclassEvent.getQuantityEntry().getValue()))) { return false; } } catch (Exception ex) {} return res; } }
Fosstrak/fosstrak-webadapters
src/main/java/org/fosstrak/webadapters/epcis/model/events/QuantityEvent.java
Java
gpl-3.0
4,102
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 2230, 3802, 2232, 10204, 1008, 1008, 2023, 5371, 2003, 2112, 1997, 1042, 15094, 6494, 2243, 1006, 7479, 1012, 1042, 15094, 6494, 2243, 1012, 8917, 1007, 1998, 1008, 2001, 2764, 2004, 2112, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package storm.contrib.spring.topology.component; import backtype.storm.Config; import backtype.storm.topology.ComponentConfigurationDeclarer; /** * [Class Description] * * @author Grant Henke * @since 12/4/12 */ public class ComponentConfig implements IComponentConfig { protected Config configuration; protected Boolean debug; protected Integer maxSpoutPending; protected Integer maxTaskParallelism; protected ComponentConfig() { this.configuration = null; this.debug = null; this.maxSpoutPending = null; this.maxTaskParallelism = null; } public Config getConfiguration() { return configuration; } public void setConfiguration(final Config configuration) { this.configuration = configuration; } public Boolean getDebug() { return debug; } public void setDebug(final Boolean debug) { this.debug = debug; } public Integer getMaxSpoutPending() { return maxSpoutPending; } public void setMaxSpoutPending(final Integer maxSpoutPending) { this.maxSpoutPending = maxSpoutPending; } public Integer getMaxTaskParallelism() { return maxTaskParallelism; } public void setMaxTaskParallelism(final Integer maxTaskParallelism) { this.maxTaskParallelism = maxTaskParallelism; } protected void addConfigToComponent(final ComponentConfigurationDeclarer componentConfigurationDeclarer) { if (configuration != null) { componentConfigurationDeclarer.addConfigurations(configuration); } if (debug != null) { componentConfigurationDeclarer.setDebug(debug); } if (maxSpoutPending != null) { componentConfigurationDeclarer.setMaxSpoutPending(maxSpoutPending); } if (maxTaskParallelism != null) { componentConfigurationDeclarer.setMaxTaskParallelism(maxTaskParallelism); } } }
granthenke/storm-spring
src/main/java/storm/contrib/spring/topology/component/ComponentConfig.java
Java
apache-2.0
1,974
[ 30522, 7427, 4040, 1012, 9530, 18886, 2497, 1012, 3500, 1012, 19587, 1012, 6922, 1025, 12324, 2067, 13874, 1012, 4040, 1012, 9530, 8873, 2290, 1025, 12324, 2067, 13874, 1012, 4040, 1012, 19587, 1012, 6922, 8663, 8873, 27390, 3370, 3207, 204...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
$demoPath = 'C:\Dropbox\GitRepos\MIcrosoftVIrtualAcademy\Testing PowerShell with Pester\Demos' ## Ensure no functions were just copied/pasted into session Remove-Item Function:\Start-ClusterTest,Function:\Restart-Cluster,Function:\Test-ClusterProblem -ErrorAction Ignore ## Import the ClusterTest module into the session Import-Module "$demoPath\Introduction\Project 1 - PowerShell Project\ClusterTest.psd1" ## Notice only a single function is exported Get-Command -Module ClusterTest ## One test from the Start-ClusterTest describe block above. ## Not all of the functions that are referenced inside of Start-ClusterTest are exported. ## FAIL! describe 'Start-ClusterTest' { ## Create mocks to simply let the function execute and essentially do nothing mock 'Write-Host' mock 'Test-ClusterProblem' { $true } mock 'Restart-Cluster' ## Null it 'tests the correct cluster' { $assMParams = @{ CommandName = 'Test-ClusterProblem' Times = 1 Exactly = $true ParameterFilter = { $ClusterName -eq 'DOESNOTMATTER' } } Assert-MockCalled @assMParams } } ## Mocks must be able to access functions to work. Use InModuleScope InModuleScope 'ClusterTest' { describe 'Start-ClusterTest' { ## Create mocks to simply let the function execute and essentially do nothing mock 'Write-Host' mock 'Test-ClusterProblem' { $true } mock 'Restart-Cluster' $result = Start-ClusterTest -ClusterName 'DOESNOTMATTER' it 'tests the correct cluster' { $assMParams = @{ CommandName = 'Test-ClusterProblem' Times = 1 Exactly = $true ParameterFilter = { $ClusterName -eq 'DOESNOTMATTER' } } Assert-MockCalled @assMParams } } }
kidchenko/playground
powershell-testing-powerShell-with-pester/Demos/Callouts/MockModules.ps1
PowerShell
mit
1,699
[ 30522, 1002, 9703, 15069, 1027, 1005, 1039, 1024, 1032, 4530, 8758, 1032, 21025, 7913, 6873, 2015, 1032, 7513, 21663, 26302, 2721, 21869, 8029, 1032, 5604, 4204, 18223, 2007, 20739, 2121, 1032, 18267, 1005, 1001, 1001, 5676, 2053, 4972, 202...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
Releasenotes tntdb 1.3 ====================== Major optimization of oracle driver ----------------------------------- The oracle driver got a major optimization. When reading multiple rows, previously each row was requested separately from OCI. Now multiple rows are fetched in a single OCI call and passed row by row to the application. Add support for cxxtools::String (unicode string class) ------------------------------------------------------- Cxxtools has a string class, which supports unicode. Tntdb now has full support for it. Unicode strings can be read and written transparently. Bugfixes and optimizations -------------------------- Some minor bugfixes and optimizations are done in tntdb.
deniskin82/tntdb
Releasenotes-1.3.markdown
Markdown
lgpl-2.1
707
[ 30522, 2713, 20564, 24048, 18939, 1015, 1012, 1017, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 1027, 2350, 20600, 1997, 14721, 4062, 1011, 1011, 1011, 1011, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<h2><?php _e('Membership Pages','membership'); ?></h2> <p><?php _e('First and foremost keep if you use the “Create Page” button here, you can then go and add content to that page from the Page Admin area. If you edited the page for the subscription form, the form would appear below your content.','membership'); ?></p> <h2><?php _e('Registration Page','membership'); ?></h2> <p><?php _e('Decide which page in our WordPress site we will use for the registration page where users can grab a subscription. If the page does not exist in the drop down then click on the button Create Page button (Clicking this multiple times will create multiple pages).','membership'); ?></p> <h3><?php _e('Form Type','membership'); ?></h3> <p><?php _e('There are two options here.','membership'); ?></p> <p><?php _e('<strong>Original Membership Form</strong> – With this option when a user clicks the signup button they will be sent to another page to complete the process.','membership'); ?></p> <p><?php _e('<strong>Popup Registration Form</strong> - This will give your users a nice in page pop up.','membership'); ?></p> <h2><?php _e('Registration Completed Page','membership'); ?></h2> <p><?php _e('Really as it states, this is the page your users will see once they signup successfully and make any payments due. Create the page here and you can go edit it to put anything you wish on there.','membership'); ?></p> <h2><?php _e('Account Page','membership'); ?></h2> <p><?php _e('The Account Page is where you users can go and edit their account details.','membership'); ?></p> <h2><?php _e('Protected Content Page','membership'); ?></h2> <p><?php _e('When you protect a post or page, this is the content a user will be directed to if they do not have a subscription with access. That will prevent the user without a subscription accessing the content direct.','membership'); ?></p> <p><?php _e('You can edit this page direct, make a huge splash there with some flashy graphics or promotional text promoting why people should upgrade to a snazzy subscription from your website. Even link them to your signup page.','membership'); ?></p>
vapvarun/MicrocerptBIZ
wp-content/plugins/membership/membershipincludes/help/help.optionspages.php
PHP
gpl-2.0
2,143
[ 30522, 1026, 1044, 2475, 1028, 1026, 1029, 25718, 1035, 1041, 1006, 1005, 5779, 5530, 1005, 1010, 1005, 5779, 1005, 1007, 1025, 1029, 1028, 1026, 1013, 1044, 2475, 1028, 1026, 1052, 1028, 1026, 1029, 25718, 1035, 1041, 1006, 1005, 2034, 1...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
module EM class LineProcessor < EM::P::LineAndTextProtocol attr_accessor :on_line def receive_line(line) if on_line EM.next_tick do on_line.call line end end end end end
minefold/em-process-buffer
lib/eventmachine/line_processor.rb
Ruby
mit
224
[ 30522, 11336, 7861, 2465, 2240, 21572, 9623, 21748, 1026, 7861, 1024, 1024, 1052, 1024, 1024, 2240, 5685, 18209, 21572, 3406, 25778, 2012, 16344, 1035, 3229, 2953, 1024, 2006, 1035, 2240, 13366, 4374, 1035, 2240, 1006, 2240, 1007, 2065, 200...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("8.MultiplyEvensByOdds")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("8.MultiplyEvensByOdds")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid("0ff61c9c-a0e5-4e13-a2b3-af1d7ca4f5d3")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
MiraNedeva/SoftUni
Programming Fundamentals C#/2.Methods And Debugging-Lab/Multiply Evens By Odds/Properties/AssemblyInfo.cs
C#
mit
1,540
[ 30522, 2478, 2291, 1012, 9185, 1025, 2478, 2291, 1012, 2448, 7292, 1012, 21624, 8043, 7903, 2229, 1025, 2478, 2291, 1012, 2448, 7292, 1012, 6970, 11923, 2121, 7903, 2229, 1025, 1013, 1013, 4649, 2592, 2015, 2236, 2229, 9064, 1037, 4895, 3...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
var component function help() { return component = Qt.createComponent("NearbyDevices.qml"); }
meego-tablet-ux/meego-ux-settings
Bluetooth/helper.js
JavaScript
apache-2.0
96
[ 30522, 13075, 6922, 3853, 2393, 1006, 1007, 1063, 2709, 6922, 1027, 1053, 2102, 1012, 3443, 9006, 29513, 3372, 1006, 1000, 3518, 24844, 23522, 1012, 1053, 19968, 1000, 1007, 1025, 1065, 102, 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, 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...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package com.bitlimit.NPCs; import de.kumpelblase2.remoteentities.RemoteEntities; import de.kumpelblase2.remoteentities.api.DespawnReason; import de.kumpelblase2.remoteentities.api.RemoteEntity; import de.kumpelblase2.remoteentities.api.thinking.InteractBehavior; import de.kumpelblase2.remoteentities.api.thinking.goals.DesireLookAtNearest; import de.kumpelblase2.remoteentities.api.thinking.goals.DesireLookRandomly; import de.kumpelblase2.remoteentities.entities.RemotePlayer; import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.event.weather.WeatherChangeEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; public class BlacksmithInteractBehavior extends InteractBehavior { private static Material defaultItem = Material.DIAMOND_AXE; private final Plugin plugin; public BlacksmithInteractBehavior(RemoteEntity inEntity) { super(inEntity); this.plugin = inEntity.getManager().getPlugin(); this.onEntityUpdate(); } public void onEntityUpdate() { if (this.m_entity.getBukkitEntity() == null) { return; } this.m_entity.setPushable(false); this.m_entity.setStationary(true); Player npc = (Player)this.m_entity.getBukkitEntity(); npc.setCanPickupItems(false); // Set tools and armor. ItemStack axe = new ItemStack(defaultItem); axe.addUnsafeEnchantment(Enchantment.SILK_TOUCH, 10); npc.setItemInHand(axe); // Armor ItemStack[] armor = new ItemStack[4]; armor[3] = new ItemStack(Material.LEATHER_HELMET); armor[2] = new ItemStack(Material.LEATHER_CHESTPLATE); armor[1] = new ItemStack(Material.IRON_LEGGINGS); armor[0] = new ItemStack(Material.LEATHER_BOOTS); // Set it backwards just for our own sanity. for (ItemStack itemStack : armor) itemStack.addUnsafeEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL, 10); // Give it that glowing feeling. npc.getInventory().setArmorContents(armor); // Set it. } public void onInteract(Player inPlayer) { } public void onRightClickInteractEventWithPlayer(Player player) { RemotePlayer behaviorEntity = (RemotePlayer) this.getRemoteEntity(); Player npc = behaviorEntity.getBukkitEntity(); ItemStack actionItem = player.getItemInHand(); if (actionItem.getType() == Material.NAME_TAG) { if (actionItem.getItemMeta().hasDisplayName()) { String previousName = behaviorEntity.getName(); behaviorEntity.setName(ChatColor.ITALIC + actionItem.getItemMeta().getDisplayName()); Bukkit.broadcastMessage(ChatColor.GOLD + previousName + " is now " + behaviorEntity.getName()); this.onEntityUpdate(); return; } else { player.sendMessage(ChatColor.GOLD + "This entity's ID is \"" + behaviorEntity.getID() + "\"."); return; } } if (npc.getItemInHand().getType() != defaultItem) { player.sendMessage(ChatColor.AQUA + npc.getDisplayName() + ChatColor.RED + " is busy!"); return; } else if (actionItem.getMaxStackSize() != 1) { return; } else if (actionItem.getType() == Material.POTION) { return; } else if (actionItem.getDurability() == 0) { player.sendMessage(ChatColor.RED + "Item is fully repaired."); return; } // Creative mode users will be using this as a utility. if (player.getGameMode() == GameMode.CREATIVE) { actionItem.setDurability((short)0); return; // Repair instantly and call it a day. } // Record where the player had the item for their convenience. int indexOfPreviouslyHeldItem = player.getInventory().getHeldItemSlot(); // Take the item from the player and put it in the NPC's hand. player.setItemInHand(new ItemStack(Material.AIR)); npc.setItemInHand(actionItem); // Capture the NPC's location and grab the closest anvil. Location npcLocation = npc.getLocation(); Location destination = closestLocation(npcLocation, Material.ANVIL); // Disable the NPC gazing around. DesireLookRandomly desireLookRandomly = behaviorEntity.getMind().getMovementDesire(DesireLookRandomly.class); desireLookRandomly.stopExecuting(); DesireLookAtNearest desireLookAtNearest = behaviorEntity.getMind().getMovementDesire(DesireLookAtNearest.class); behaviorEntity.move(destination); behaviorEntity.lookAt(destination); double distanceAway = npcLocation.distance(destination); class FinishRepairTrip implements Runnable { private final Player npc; private final Location gaze; public FinishRepairTrip(Player npc, Location gaze) { this.npc = npc; this.gaze = gaze; } public void run() { if (!this.gaze.equals(this.npc.getLocation())) // Pretend he's working at the anvil. npc.setSneaking(true); Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { public void run() { npc.setSneaking(false); // Return to standing. npc.getWorld().playSound(npc.getLocation(), Sound.ANVIL_USE, 1F, 1F); // Simulate a repair. :P } }, 20L); } } Long wait = Math.round((distanceAway / 4) * 20); // Calculates the time needed to wait for the next operation (this is all async, so the delay isn't pre-factored. Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new FinishRepairTrip(npc, destination), wait); // Actually repair the item. actionItem.setDurability((short) 0); class ReturnNPC implements Runnable { private final Location returnLocation; private final RemotePlayer entity; private final Player toLookAt; public ReturnNPC(Location returnLocation, RemotePlayer entity, Player player) { this.returnLocation = returnLocation; this.entity = entity; this.toLookAt = player; } public void run() { // Walk the NPC back to its original location. this.entity.move(this.returnLocation); // Turn back to the player to correspond with te walking. entity.lookAt(this.toLookAt); } } Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new ReturnNPC(npcLocation, behaviorEntity, player), wait + 20L); // Ran once the NPC is actually back near the player. class ReturnItem implements Runnable { private final Player player; private final ItemStack item; private final Player npc; private final int attemptSlot; public ReturnItem(Player player, ItemStack item, Player npc, int attemptSlot) { this.player = player; this.item = item; this.npc = npc; this.attemptSlot = attemptSlot; } public void run() { if (this.player.getInventory().getItem(this.attemptSlot) == null && this.player.isOnline()) { // Called if the player still has a free slot where the item originated from. this.player.getInventory().setItem(this.attemptSlot, this.item); } else if (this.player.getInventory().firstEmpty() != -1 && this.player.isOnline()) { // Called if the player has a free space, but it's not the origin slot. this.player.getInventory().setItem(this.player.getInventory().firstEmpty(), this.item); } else { // Called only if the player isn't online or has a full inventory. Avoid if possible to prevent item destruction. npc.getLocation().getWorld().dropItem(npc.getLocation(), this.item); } // Display anvil-names, if it has one. if (item.getItemMeta().hasDisplayName()) { this.player.sendMessage(ChatColor.AQUA + this.npc.getDisplayName() + ChatColor.GREEN + " repaired " + ChatColor.YELLOW + item.getItemMeta().getDisplayName() + ChatColor.GREEN + "."); } else { this.player.sendMessage(ChatColor.AQUA + this.npc.getDisplayName() + ChatColor.GREEN + " repaired your " + ChatColor.YELLOW + item.getType().name().replace("_", " ").toLowerCase() + ChatColor.GREEN + "."); } // Put the blacksmith's default item back in his hand. ItemStack axe = new ItemStack(defaultItem); axe.addEnchantment(Enchantment.SILK_TOUCH, 1); npc.setItemInHand(axe); // Grab the RemoteEntity to perform logic operations. RemoteEntity entity = RemoteEntities.getRemoteEntityFromEntity(this.npc); // Restore normal livelihood into the blacksmith. DesireLookAtNearest desireLookAtNearest = entity.getMind().getMovementDesire(DesireLookAtNearest.class); DesireLookRandomly desireLookRandomly = entity.getMind().getMovementDesire(DesireLookRandomly.class); // desireLookAtNearest.setLookPossibility(1.0F); desireLookRandomly.startExecuting(); } } Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new ReturnItem(player, actionItem, npc, indexOfPreviouslyHeldItem), (wait * 2) + 20L); } // Grab the nearest location of a block with a certain material/type. private Location closestLocation(Location origin, Material type) { World world = origin.getWorld(); for (int x = origin.getBlockX() - 4; x <= origin.getBlockX() + 8; x = x + 1) { for (int z = origin.getBlockZ() - 4; z <= origin.getBlockZ() + 8; z = z + 1) { for (int y = origin.getBlockY() - 4; y <= origin.getBlockY() + 8; y = y + 1) { Block block = world.getBlockAt(x, y, z); if (block.getType() == type) return block.getLocation(); } } } return origin; } }
BitLimit/NPCs
src/main/java/com/bitlimit/NPCs/BlacksmithInteractBehavior.java
Java
mit
10,711
[ 30522, 7427, 4012, 1012, 2978, 17960, 4183, 1012, 27937, 6169, 1025, 12324, 2139, 1012, 13970, 8737, 2884, 28522, 3366, 2475, 1012, 6556, 4765, 6447, 1012, 6556, 4765, 6447, 1025, 12324, 2139, 1012, 13970, 8737, 2884, 28522, 3366, 2475, 101...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Contributing guidelines ## How to become a contributor and submit your own code ### Contributor License Agreements We'd love to accept your patches! Before we can take them, we have to jump a couple of legal hurdles. Please fill out either the individual or corporate Contributor License Agreement (CLA). * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](http://code.google.com/legal/individual-cla-v1.0.html). * If you work for a company that wants to allow you to contribute your work, then you'll need to sign a [corporate CLA](http://code.google.com/legal/corporate-cla-v1.0.html). Follow either of the two links above to access the appropriate CLA and instructions for how to sign and return it. Once we receive it, we'll be able to accept your pull requests. ***NOTE***: Only original source code from you and other people that have signed the CLA can be accepted into the main repository. ### Contributing code If you have improvements to Copybara, send us your pull requests!
google/copybara
CONTRIBUTING.md
Markdown
apache-2.0
1,101
[ 30522, 1001, 8020, 11594, 1001, 1001, 2129, 2000, 2468, 1037, 12130, 1998, 12040, 2115, 2219, 3642, 1001, 1001, 1001, 12130, 6105, 10540, 2057, 1005, 1040, 2293, 2000, 5138, 2115, 13864, 999, 2077, 2057, 2064, 2202, 2068, 1010, 2057, 2031, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=false; target-densityDpi=medium-dpi" /> <title>Chicago BusTracker</title> <script src="/usr/palm/frameworks/mojo/mojo.js" type="text/javascript" x-mojo-version="1"></script> <link href="stylesheets/ctabustracker.css" media="screen" rel="stylesheet" type="text/css"> </head> <body id="BT"> </body> </html>
ifeanyi/webos-chi-bustracker
index.html
HTML
apache-2.0
461
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 1028, 1026, 2132, 1028, 1026, 18804, 2171, 1027, 1000, 3193, 6442, 1000, 4180, 1027, 1000, 9381, 1027, 5080, 1011, 9381, 1025, 3988, 1011, 4094, 1027, 1015, 1012, 1014, 1025, 4555, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* Theme Name: circuitmedia-site Layout: Content-Sidebar */ .content-area { float: left; margin: 0 -25% 0 0; width: 100%; } .site-main { margin: 0 25% 0 0; } .site-content .widget-area { float: right; overflow: hidden; width: 25%; } .site-footer { clear: both; width: 100%; }
Jhorton4/Jhorton_CircuitMedia
wp-content/themes/circuitmedia_site/layouts/content-sidebar.css
CSS
gpl-2.0
285
[ 30522, 1013, 1008, 4323, 2171, 1024, 4984, 16969, 1011, 2609, 9621, 1024, 4180, 1011, 2217, 8237, 1008, 1013, 1012, 4180, 1011, 2181, 1063, 14257, 1024, 2187, 1025, 7785, 1024, 1014, 1011, 2423, 1003, 1014, 30524, 1011, 2364, 1063, 7785, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package Classes::Sentry4; our @ISA = qw(Classes::Device); sub init { my $self = shift; if ($self->mode =~ /device::hardware::health/) { $self->analyze_and_check_environmental_subsystem('Classes::Sentry4::Components::EnvironmentalSubsystem'); } elsif ($self->mode =~ /device::power::health/) { $self->analyze_and_check_environmental_subsystem('Classes::Sentry4::Components::PowerSubsystem'); } else { $self->no_such_mode(); } if (! $self->check_messages()) { $self->add_ok('hardware working fine'); } }
lausser/check_pdu_health
plugins-scripts/Classes/Sentry4.pm
Perl
gpl-2.0
534
[ 30522, 7427, 4280, 1024, 1024, 2741, 2854, 2549, 1025, 2256, 1030, 18061, 1027, 1053, 2860, 1006, 4280, 1024, 1024, 5080, 1007, 1025, 4942, 1999, 4183, 1063, 2026, 1002, 2969, 1027, 5670, 1025, 2065, 1006, 1002, 2969, 1011, 1028, 5549, 10...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** * Rooms * Pokemon Showdown - http://pokemonshowdown.com/ * * Every chat room and battle is a room, and what they do is done in * rooms.js. There's also a global room which every user is in, and * handles miscellaneous things like welcoming the user. * * @license MIT license */ const TIMEOUT_EMPTY_DEALLOCATE = 10 * 60 * 1000; const TIMEOUT_INACTIVE_DEALLOCATE = 40 * 60 * 1000; const REPORT_USER_STATS_INTERVAL = 1000 * 60 * 10; var fs = require('fs'); /* global Rooms: true */ var Rooms = module.exports = getRoom; var rooms = Rooms.rooms = Object.create(null); var Room = (function () { function Room(roomid, title) { this.id = roomid; this.title = (title || roomid); this.users = Object.create(null); this.log = []; this.bannedUsers = Object.create(null); this.bannedIps = Object.create(null); } Room.prototype.title = ""; Room.prototype.type = 'chat'; Room.prototype.lastUpdate = 0; Room.prototype.log = null; Room.prototype.users = null; Room.prototype.userCount = 0; Room.prototype.send = function (message, errorArgument) { if (errorArgument) throw new Error("Use Room#sendUser"); if (this.id !== 'lobby') message = '>' + this.id + '\n' + message; Sockets.channelBroadcast(this.id, message); }; Room.prototype.sendAuth = function (message) { for (var i in this.users) { var user = this.users[i]; if (user.connected && user.can('receiveauthmessages', null, this)) { user.sendTo(this, message); } } }; Room.prototype.sendUser = function (user, message) { user.sendTo(this, message); }; Room.prototype.add = function (message) { if (typeof message !== 'string') throw new Error("Deprecated message type"); this.logEntry(message); if (this.logTimes && message.substr(0, 3) === '|c|') { message = '|c:|' + (~~(Date.now() / 1000)) + '|' + message.substr(3); } this.log.push(message); }; Room.prototype.logEntry = function () {}; Room.prototype.addRaw = function (message) { this.add('|raw|' + message); }; Room.prototype.getLogSlice = function (amount) { var log = this.log.slice(amount); log.unshift('|:|' + (~~(Date.now() / 1000))); return log; }; Room.prototype.chat = function (user, message, connection) { // Battle actions are actually just text commands that are handled in // parseCommand(), which in turn often calls Simulator.prototype.sendFor(). // Sometimes the call to sendFor is done indirectly, by calling // room.decision(), where room.constructor === BattleRoom. message = CommandParser.parse(message, this, user, connection); if (message) { this.add('|c|' + user.getIdentity(this.id) + '|' + message); } this.update(); }; return Room; })(); var GlobalRoom = (function () { function GlobalRoom(roomid) { this.id = roomid; // init battle rooms this.battleCount = 0; this.searchers = []; // Never do any other file IO synchronously // but this is okay to prevent race conditions as we start up PS this.lastBattle = 0; try { this.lastBattle = parseInt(fs.readFileSync('logs/lastbattle.txt')) || 0; } catch (e) {} // file doesn't exist [yet] this.chatRoomData = []; try { this.chatRoomData = JSON.parse(fs.readFileSync('config/chatrooms.json')); if (!Array.isArray(this.chatRoomData)) this.chatRoomData = []; } catch (e) {} // file doesn't exist [yet] if (!this.chatRoomData.length) { this.chatRoomData = [{ title: 'Lobby', isOfficial: true, autojoin: true }, { title: 'Staff', isPrivate: true, staffRoom: true, staffAutojoin: true }]; } this.chatRooms = []; this.autojoin = []; // rooms that users autojoin upon connecting this.staffAutojoin = []; // rooms that staff autojoin upon connecting for (var i = 0; i < this.chatRoomData.length; i++) { if (!this.chatRoomData[i] || !this.chatRoomData[i].title) { console.log('ERROR: Room number ' + i + ' has no data.'); continue; } var id = toId(this.chatRoomData[i].title); console.log("NEW CHATROOM: " + id); var room = Rooms.createChatRoom(id, this.chatRoomData[i].title, this.chatRoomData[i]); this.chatRooms.push(room); if (room.autojoin) this.autojoin.push(id); if (room.staffAutojoin) this.staffAutojoin.push(id); } // this function is complex in order to avoid several race conditions var self = this; this.writeNumRooms = (function () { var writing = false; var lastBattle; // last lastBattle to be written to file var finishWriting = function () { writing = false; if (lastBattle < self.lastBattle) { self.writeNumRooms(); } }; return function () { if (writing) return; // batch writing lastbattle.txt for every 10 battles if (lastBattle >= self.lastBattle) return; lastBattle = self.lastBattle + 10; writing = true; fs.writeFile('logs/lastbattle.txt.0', '' + lastBattle, function () { // rename is atomic on POSIX, but will throw an error on Windows fs.rename('logs/lastbattle.txt.0', 'logs/lastbattle.txt', function (err) { if (err) { // This should only happen on Windows. fs.writeFile('logs/lastbattle.txt', '' + lastBattle, finishWriting); return; } finishWriting(); }); }); }; })(); this.writeChatRoomData = (function () { var writing = false; var writePending = false; // whether or not a new write is pending var finishWriting = function () { writing = false; if (writePending) { writePending = false; self.writeChatRoomData(); } }; return function () { if (writing) { writePending = true; return; } writing = true; var data = JSON.stringify(self.chatRoomData).replace(/\{"title"\:/g, '\n{"title":').replace(/\]$/, '\n]'); fs.writeFile('config/chatrooms.json.0', data, function () { // rename is atomic on POSIX, but will throw an error on Windows fs.rename('config/chatrooms.json.0', 'config/chatrooms.json', function (err) { if (err) { // This should only happen on Windows. fs.writeFile('config/chatrooms.json', data, finishWriting); return; } finishWriting(); }); }); }; })(); // init users this.users = {}; this.userCount = 0; // cache of `Object.size(this.users)` this.maxUsers = 0; this.maxUsersDate = 0; this.reportUserStatsInterval = setInterval( this.reportUserStats.bind(this), REPORT_USER_STATS_INTERVAL ); } GlobalRoom.prototype.type = 'global'; GlobalRoom.prototype.formatListText = '|formats'; GlobalRoom.prototype.reportUserStats = function () { if (this.maxUsersDate) { LoginServer.request('updateuserstats', { date: this.maxUsersDate, users: this.maxUsers }, function () {}); this.maxUsersDate = 0; } LoginServer.request('updateuserstats', { date: Date.now(), users: this.userCount }, function () {}); }; GlobalRoom.prototype.getFormatListText = function () { var formatListText = '|formats'; var curSection = ''; for (var i in Tools.data.Formats) { var format = Tools.data.Formats[i]; if (!format.challengeShow && !format.searchShow) continue; var section = format.section; if (section === undefined) section = format.mod; if (!section) section = ''; if (section !== curSection) { curSection = section; formatListText += '|,' + (format.column || 1) + '|' + section; } formatListText += '|' + format.name; if (!format.challengeShow) formatListText += ',,'; else if (!format.searchShow) formatListText += ','; if (format.team) formatListText += ',#'; } return formatListText; }; GlobalRoom.prototype.getRoomList = function (filter) { var roomList = {}; var total = 0; for (var i in Rooms.rooms) { var room = Rooms.rooms[i]; if (!room || !room.active || room.isPrivate) continue; if (filter && filter !== room.format && filter !== true) continue; var roomData = {}; if (room.active && room.battle) { if (room.battle.players[0]) roomData.p1 = room.battle.players[0].getIdentity(); if (room.battle.players[1]) roomData.p2 = room.battle.players[1].getIdentity(); } if (!roomData.p1 || !roomData.p2) continue; roomList[room.id] = roomData; total++; if (total >= 100) break; } return roomList; }; GlobalRoom.prototype.getRooms = function () { var roomsData = {official:[], chat:[], userCount: this.userCount, battleCount: this.battleCount}; for (var i = 0; i < this.chatRooms.length; i++) { var room = this.chatRooms[i]; if (!room) continue; if (room.isPrivate) continue; (room.isOfficial ? roomsData.official : roomsData.chat).push({ title: room.title, desc: room.desc, userCount: room.userCount }); } return roomsData; }; GlobalRoom.prototype.cancelSearch = function (user) { var success = false; user.cancelChallengeTo(); for (var i = 0; i < this.searchers.length; i++) { var search = this.searchers[i]; var searchUser = Users.get(search.userid); if (!searchUser.connected) { this.searchers.splice(i, 1); i--; continue; } if (searchUser === user) { this.searchers.splice(i, 1); i--; if (!success) { searchUser.send('|updatesearch|' + JSON.stringify({searching: false})); success = true; } continue; } } return success; }; GlobalRoom.prototype.searchBattle = function (user, formatid) { if (!user.connected) return; formatid = toId(formatid); user.prepBattle(formatid, 'search', null, this.finishSearchBattle.bind(this, user, formatid)); }; GlobalRoom.prototype.finishSearchBattle = function (user, formatid, result) { if (!result) return; // tell the user they've started searching var newSearchData = { format: formatid }; user.send('|updatesearch|' + JSON.stringify({searching: newSearchData})); // get the user's rating before actually starting to search var newSearch = { userid: user.userid, formatid: formatid, team: user.team, rating: 1000, time: new Date().getTime() }; var self = this; user.doWithMMR(formatid, function (mmr, error) { if (error) { user.popup("Connection to ladder server failed with error: " + error + "; please try again later"); return; } newSearch.rating = mmr; self.addSearch(newSearch, user); }); }; GlobalRoom.prototype.matchmakingOK = function (search1, search2, user1, user2) { // users must be different if (user1 === user2) return false; // users must have different IPs if (user1.latestIp === user2.latestIp) return false; // users must not have been matched immediately previously if (user1.lastMatch === user2.userid || user2.lastMatch === user1.userid) return false; // search must be within range var searchRange = 100, formatid = search1.formatid, elapsed = Math.abs(search1.time - search2.time); if (formatid === 'ou' || formatid === 'oucurrent' || formatid === 'randombattle') searchRange = 50; searchRange += elapsed / 300; // +1 every .3 seconds if (searchRange > 300) searchRange = 300; if (Math.abs(search1.rating - search2.rating) > searchRange) return false; user1.lastMatch = user2.userid; user2.lastMatch = user1.userid; return true; }; GlobalRoom.prototype.addSearch = function (newSearch, user) { if (!user.connected) return; for (var i = 0; i < this.searchers.length; i++) { var search = this.searchers[i]; var searchUser = Users.get(search.userid); if (!searchUser || !searchUser.connected) { this.searchers.splice(i, 1); i--; continue; } if (newSearch.formatid === search.formatid && searchUser === user) return; // only one search per format if (newSearch.formatid === search.formatid && this.matchmakingOK(search, newSearch, searchUser, user)) { this.cancelSearch(user, true); this.cancelSearch(searchUser, true); user.send('|updatesearch|' + JSON.stringify({searching: false})); this.startBattle(searchUser, user, search.formatid, true, search.team, newSearch.team); return; } } this.searchers.push(newSearch); }; GlobalRoom.prototype.send = function (message, user) { if (user) { user.sendTo(this, message); } else { Sockets.channelBroadcast(this.id, message); } }; GlobalRoom.prototype.sendAuth = function (message) { for (var i in this.users) { var user = this.users[i]; if (user.connected && user.can('receiveauthmessages', null, this)) { user.sendTo(this, message); } } }; GlobalRoom.prototype.add = function (message) { if (rooms.lobby) rooms.lobby.add(message); }; GlobalRoom.prototype.addRaw = function (message) { if (rooms.lobby) rooms.lobby.addRaw(message); }; GlobalRoom.prototype.addChatRoom = function (title) { var id = toId(title); if (rooms[id]) return false; var chatRoomData = { title: title }; var room = Rooms.createChatRoom(id, title, chatRoomData); this.chatRoomData.push(chatRoomData); this.chatRooms.push(room); this.writeChatRoomData(); return true; }; GlobalRoom.prototype.deregisterChatRoom = function (id) { id = toId(id); var room = rooms[id]; if (!room) return false; // room doesn't exist if (!room.chatRoomData) return false; // room isn't registered // deregister from global chatRoomData // looping from the end is a pretty trivial optimization, but the // assumption is that more recently added rooms are more likely to // be deleted for (var i = this.chatRoomData.length - 1; i >= 0; i--) { if (id === toId(this.chatRoomData[i].title)) { this.chatRoomData.splice(i, 1); this.writeChatRoomData(); break; } } delete room.chatRoomData; return true; }; GlobalRoom.prototype.delistChatRoom = function (id) { id = toId(id); if (!rooms[id]) return false; // room doesn't exist for (var i = this.chatRooms.length - 1; i >= 0; i--) { if (id === this.chatRooms[i].id) { this.chatRooms.splice(i, 1); break; } } }; GlobalRoom.prototype.removeChatRoom = function (id) { id = toId(id); var room = rooms[id]; if (!room) return false; // room doesn't exist room.destroy(); return true; }; GlobalRoom.prototype.autojoinRooms = function (user, connection) { // we only autojoin regular rooms if the client requests it with /autojoin // note that this restriction doesn't apply to staffAutojoin for (var i = 0; i < this.autojoin.length; i++) { user.joinRoom(this.autojoin[i], connection); } }; GlobalRoom.prototype.checkAutojoin = function (user, connection) { if (user.isStaff) { for (var i = 0; i < this.staffAutojoin.length; i++) { user.joinRoom(this.staffAutojoin[i], connection); } } }; GlobalRoom.prototype.onJoinConnection = function (user, connection) { var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n'; connection.send(initdata + this.formatListText); if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list }; GlobalRoom.prototype.onJoin = function (user, connection, merging) { if (!user) return false; // ??? if (this.users[user.userid]) return user; this.users[user.userid] = user; if (++this.userCount > this.maxUsers) { this.maxUsers = this.userCount; this.maxUsersDate = Date.now(); } if (!merging) { var initdata = '|updateuser|' + user.name + '|' + (user.named ? '1' : '0') + '|' + user.avatar + '\n'; connection.send(initdata + this.formatListText); if (this.chatRooms.length > 2) connection.send('|queryresponse|rooms|null'); // should display room list } return user; }; GlobalRoom.prototype.onRename = function (user, oldid, joining) { delete this.users[oldid]; this.users[user.userid] = user; return user; }; GlobalRoom.prototype.onUpdateIdentity = function () {}; GlobalRoom.prototype.onLeave = function (user) { if (!user) return; // ... delete this.users[user.userid]; --this.userCount; this.cancelSearch(user, true); }; GlobalRoom.prototype.startBattle = function (p1, p2, format, rated, p1team, p2team) { var newRoom; p1 = Users.get(p1); p2 = Users.get(p2); if (!p1 || !p2) { // most likely, a user was banned during the battle start procedure this.cancelSearch(p1, true); this.cancelSearch(p2, true); return; } if (p1 === p2) { this.cancelSearch(p1, true); this.cancelSearch(p2, true); p1.popup("You can't battle your own account. Please use something like Private Browsing to battle yourself."); return; } if (this.lockdown) { this.cancelSearch(p1, true); this.cancelSearch(p2, true); p1.popup("The server is shutting down. Battles cannot be started at this time."); p2.popup("The server is shutting down. Battles cannot be started at this time."); return; } //console.log('BATTLE START BETWEEN: ' + p1.userid + ' ' + p2.userid); var i = this.lastBattle + 1; var formaturlid = format.toLowerCase().replace(/[^a-z0-9]+/g, ''); while(rooms['battle-' + formaturlid + i]) { i++; } this.lastBattle = i; rooms.global.writeNumRooms(); newRoom = this.addRoom('battle-' + formaturlid + '-' + i, format, p1, p2, this.id, rated); p1.joinRoom(newRoom); p2.joinRoom(newRoom); newRoom.joinBattle(p1, p1team); newRoom.joinBattle(p2, p2team); this.cancelSearch(p1, true); this.cancelSearch(p2, true); if (Config.reportbattles && rooms.lobby) { rooms.lobby.add('|b|' + newRoom.id + '|' + p1.getIdentity() + '|' + p2.getIdentity()); } if (Config.logladderip && rated) { if (!this.ladderIpLog) { this.ladderIpLog = fs.createWriteStream('logs/ladderip/ladderip.txt', {flags: 'a'}); } this.ladderIpLog.write(p1.userid+': '+p1.latestIp+'\n'); this.ladderIpLog.write(p2.userid+': '+p2.latestIp+'\n'); } return newRoom; }; GlobalRoom.prototype.addRoom = function (room, format, p1, p2, parent, rated) { room = Rooms.createBattle(room, format, p1, p2, parent, rated); return room; }; GlobalRoom.prototype.removeRoom = function (room) {}; GlobalRoom.prototype.chat = function (user, message, connection) { if (rooms.lobby) return rooms.lobby.chat(user, message, connection); message = CommandParser.parse(message, this, user, connection); if (message) { connection.sendPopup("You can't send messages directly to the server."); } }; return GlobalRoom; })(); var BattleRoom = (function () { function BattleRoom(roomid, format, p1, p2, parentid, rated) { Room.call(this, roomid, "" + p1.name + " vs. " + p2.name); this.modchat = (Config.battlemodchat || false); format = '' + (format || ''); this.format = format; this.auth = {}; //console.log("NEW BATTLE"); var formatid = toId(format); if (rated && Tools.getFormat(formatid).rated !== false) { rated = { p1: p1.userid, p2: p2.userid, format: format }; } else { rated = false; } this.rated = rated; this.battle = Simulator.create(this.id, format, rated, this); this.parentid = parentid || ''; this.p1 = p1 || ''; this.p2 = p2 || ''; this.sideTicksLeft = [21, 21]; if (!rated) this.sideTicksLeft = [28, 28]; this.sideTurnTicks = [0, 0]; this.disconnectTickDiff = [0, 0]; if (Config.forcetimer) this.requestKickInactive(false); } BattleRoom.prototype = Object.create(Room.prototype); BattleRoom.prototype.type = 'battle'; BattleRoom.prototype.resetTimer = null; BattleRoom.prototype.resetUser = ''; BattleRoom.prototype.expireTimer = null; BattleRoom.prototype.active = false; BattleRoom.prototype.push = function (message) { if (typeof message === 'string') { this.log.push(message); } else { this.log = this.log.concat(message); } }; BattleRoom.prototype.win = function (winner) { if (this.rated) { var winnerid = toId(winner); var rated = this.rated; this.rated = false; var p1score = 0.5; if (winnerid === rated.p1) { p1score = 1; } else if (winnerid === rated.p2) { p1score = 0; } var p1 = rated.p1; if (Users.getExact(rated.p1)) p1 = Users.getExact(rated.p1).name; var p2 = rated.p2; if (Users.getExact(rated.p2)) p2 = Users.getExact(rated.p2).name; //update.updates.push('[DEBUG] uri: ' + Config.loginserver + 'action.php?act=ladderupdate&serverid=' + Config.serverid + '&p1=' + encodeURIComponent(p1) + '&p2=' + encodeURIComponent(p2) + '&score=' + p1score + '&format=' + toId(rated.format) + '&servertoken=[token]'); if (!rated.p1 || !rated.p2) { this.push('|raw|ERROR: Ladder not updated: a player does not exist'); } else { winner = Users.get(winnerid); if (winner && !winner.authenticated) { this.sendUser(winner, '|askreg|' + winner.userid); } var p1rating, p2rating; // update rankings this.push('|raw|Ladder updating...'); var self = this; LoginServer.request('ladderupdate', { p1: p1, p2: p2, score: p1score, format: toId(rated.format) }, function (data, statusCode, error) { if (!self.battle) { console.log('room expired before ladder update was received'); return; } if (!data) { self.addRaw('Ladder (probably) updated, but score could not be retrieved (' + error + ').'); // log the battle anyway if (!Tools.getFormat(self.format).noLog) { self.logBattle(p1score); } return; } else if (data.errorip) { self.addRaw("This server's request IP " + data.errorip + " is not a registered server."); return; } else { try { p1rating = data.p1rating; p2rating = data.p2rating; //self.add("Ladder updated."); var oldacre = Math.round(data.p1rating.oldacre); var acre = Math.round(data.p1rating.acre); var reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'winning' : (p1score < 0.01 ? 'losing' : 'tying')); if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons; self.addRaw(Tools.escapeHTML(p1) + '\'s rating: ' + oldacre + ' &rarr; <strong>' + acre + '</strong><br />(' + reasons + ')'); oldacre = Math.round(data.p2rating.oldacre); acre = Math.round(data.p2rating.acre); reasons = '' + (acre - oldacre) + ' for ' + (p1score > 0.99 ? 'losing' : (p1score < 0.01 ? 'winning' : 'tying')); if (reasons.substr(0, 1) !== '-') reasons = '+' + reasons; self.addRaw(Tools.escapeHTML(p2) + '\'s rating: ' + oldacre + ' &rarr; <strong>' + acre + '</strong><br />(' + reasons + ')'); Users.get(p1).cacheMMR(rated.format, data.p1rating); Users.get(p2).cacheMMR(rated.format, data.p2rating); self.update(); } catch(e) { self.addRaw('There was an error calculating rating changes.'); self.update(); } if (!Tools.getFormat(self.format).noLog) { self.logBattle(p1score, p1rating, p2rating); } } }); } } rooms.global.battleCount += 0 - (this.active ? 1 : 0); this.active = false; this.update(); }; // logNum = 0 : spectator log // logNum = 1, 2 : player log // logNum = 3 : replay log BattleRoom.prototype.getLog = function (logNum) { var log = []; for (var i = 0; i < this.log.length; ++i) { var line = this.log[i]; if (line === '|split') { log.push(this.log[i + logNum + 1]); i += 4; } else { log.push(line); } } return log; }; BattleRoom.prototype.getLogForUser = function (user) { var logNum = this.battle.getSlot(user) + 1; if (logNum < 0) logNum = 0; return this.getLog(logNum); }; BattleRoom.prototype.update = function (excludeUser) { if (this.log.length <= this.lastUpdate) return; Sockets.subchannelBroadcast(this.id, '>' + this.id + '\n\n' + this.log.slice(this.lastUpdate).join('\n')); this.lastUpdate = this.log.length; // empty rooms time out after ten minutes var hasUsers = false; for (var i in this.users) { hasUsers = true; break; } if (!hasUsers) { if (!this.expireTimer) { this.expireTimer = setTimeout(this.tryExpire.bind(this), TIMEOUT_EMPTY_DEALLOCATE); } } else { if (this.expireTimer) clearTimeout(this.expireTimer); this.expireTimer = setTimeout(this.tryExpire.bind(this), TIMEOUT_INACTIVE_DEALLOCATE); } }; BattleRoom.prototype.logBattle = function (p1score, p1rating, p2rating) { var logData = this.battle.logData; logData.p1rating = p1rating; logData.p2rating = p2rating; logData.endType = this.battle.endType; if (!p1rating) logData.ladderError = true; logData.log = BattleRoom.prototype.getLog.call(logData, 3); // replay log (exact damage) var date = new Date(); var logfolder = date.format('{yyyy}-{MM}'); var logsubfolder = date.format('{yyyy}-{MM}-{dd}'); var curpath = 'logs/' + logfolder; var self = this; fs.mkdir(curpath, '0755', function () { var tier = self.format.toLowerCase().replace(/[^a-z0-9]+/g, ''); curpath += '/' + tier; fs.mkdir(curpath, '0755', function () { curpath += '/' + logsubfolder; fs.mkdir(curpath, '0755', function () { fs.writeFile(curpath + '/' + self.id + '.log.json', JSON.stringify(logData)); }); }); }); // asychronicity //console.log(JSON.stringify(logData)); }; BattleRoom.prototype.tryExpire = function () { this.expire(); }; BattleRoom.prototype.getInactiveSide = function () { if (this.battle.players[0] && !this.battle.players[1]) return 1; if (this.battle.players[1] && !this.battle.players[0]) return 0; return this.battle.inactiveSide; }; BattleRoom.prototype.forfeit = function (user, message, side) { if (!this.battle || this.battle.ended || !this.battle.started) return false; if (!message) message = ' forfeited.'; if (side === undefined) { if (user && user.userid === this.battle.playerids[0]) side = 0; if (user && user.userid === this.battle.playerids[1]) side = 1; } if (side === undefined) return false; var ids = ['p1', 'p2']; var otherids = ['p2', 'p1']; var name = 'Player ' + (side + 1); if (user) { name = user.name; } else if (this.rated) { name = this.rated[ids[side]]; } this.add('|-message|' + name + message); this.battle.endType = 'forfeit'; this.battle.send('win', otherids[side]); rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; this.update(); return true; }; BattleRoom.prototype.sendPlayer = function (num, message) { var player = this.battle.getPlayer(num); if (!player) return false; this.sendUser(player, message); }; BattleRoom.prototype.kickInactive = function () { clearTimeout(this.resetTimer); this.resetTimer = null; if (!this.battle || this.battle.ended || !this.battle.started) return false; var inactiveSide = this.getInactiveSide(); var ticksLeft = [0, 0]; if (inactiveSide !== 1) { // side 0 is inactive this.sideTurnTicks[0]--; this.sideTicksLeft[0]--; } if (inactiveSide !== 0) { // side 1 is inactive this.sideTurnTicks[1]--; this.sideTicksLeft[1]--; } ticksLeft[0] = Math.min(this.sideTurnTicks[0], this.sideTicksLeft[0]); ticksLeft[1] = Math.min(this.sideTurnTicks[1], this.sideTicksLeft[1]); if (ticksLeft[0] && ticksLeft[1]) { if (inactiveSide === 0 || inactiveSide === 1) { // one side is inactive var inactiveTicksLeft = ticksLeft[inactiveSide]; var inactiveUser = this.battle.getPlayer(inactiveSide); if (inactiveTicksLeft % 3 === 0 || inactiveTicksLeft <= 4) { this.send('|inactive|' + (inactiveUser ? inactiveUser.name : 'Player ' + (inactiveSide + 1)) + ' has ' + (inactiveTicksLeft * 10) + ' seconds left.'); } } else { // both sides are inactive var inactiveUser0 = this.battle.getPlayer(0); if (inactiveUser0 && (ticksLeft[0] % 3 === 0 || ticksLeft[0] <= 4)) { this.sendUser(inactiveUser0, '|inactive|' + inactiveUser0.name + ' has ' + (ticksLeft[0] * 10) + ' seconds left.'); } var inactiveUser1 = this.battle.getPlayer(1); if (inactiveUser1 && (ticksLeft[1] % 3 === 0 || ticksLeft[1] <= 4)) { this.sendUser(inactiveUser1, '|inactive|' + inactiveUser1.name + ' has ' + (ticksLeft[1] * 10) + ' seconds left.'); } } this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000); return; } if (inactiveSide < 0) { if (ticksLeft[0]) inactiveSide = 1; else if (ticksLeft[1]) inactiveSide = 0; } this.forfeit(this.battle.getPlayer(inactiveSide), ' lost due to inactivity.', inactiveSide); this.resetUser = ''; }; BattleRoom.prototype.requestKickInactive = function (user, force) { if (this.resetTimer) { if (user) this.sendUser(user, '|inactive|The inactivity timer is already counting down.'); return false; } if (user) { if (!force && this.battle.getSlot(user) < 0) return false; this.resetUser = user.userid; this.send('|inactive|Battle timer is now ON: inactive players will automatically lose when time\'s up. (requested by ' + user.name + ')'); } else if (user === false) { this.resetUser = '~'; this.add('|inactive|Battle timer is ON: inactive players will automatically lose when time\'s up.'); } // a tick is 10 seconds var maxTicksLeft = 15; // 2 minutes 30 seconds if (!this.battle.p1 || !this.battle.p2) { // if a player has left, don't wait longer than 6 ticks (1 minute) maxTicksLeft = 6; } if (!this.rated) maxTicksLeft = 30; this.sideTurnTicks = [maxTicksLeft, maxTicksLeft]; var inactiveSide = this.getInactiveSide(); if (inactiveSide < 0) { // add 10 seconds to bank if they're below 160 seconds if (this.sideTicksLeft[0] < 16) this.sideTicksLeft[0]++; if (this.sideTicksLeft[1] < 16) this.sideTicksLeft[1]++; } this.sideTicksLeft[0]++; this.sideTicksLeft[1]++; if (inactiveSide !== 1) { // side 0 is inactive var ticksLeft0 = Math.min(this.sideTicksLeft[0] + 1, maxTicksLeft); this.sendPlayer(0, '|inactive|You have ' + (ticksLeft0 * 10) + ' seconds to make your decision.'); } if (inactiveSide !== 0) { // side 1 is inactive var ticksLeft1 = Math.min(this.sideTicksLeft[1] + 1, maxTicksLeft); this.sendPlayer(1, '|inactive|You have ' + (ticksLeft1 * 10) + ' seconds to make your decision.'); } this.resetTimer = setTimeout(this.kickInactive.bind(this), 10 * 1000); return true; }; BattleRoom.prototype.nextInactive = function () { if (this.resetTimer) { this.update(); clearTimeout(this.resetTimer); this.resetTimer = null; this.requestKickInactive(); } }; BattleRoom.prototype.stopKickInactive = function (user, force) { if (!force && user && user.userid !== this.resetUser) return false; if (this.resetTimer) { clearTimeout(this.resetTimer); this.resetTimer = null; this.send('|inactiveoff|Battle timer is now OFF.'); return true; } return false; }; BattleRoom.prototype.kickInactiveUpdate = function () { if (!this.rated) return false; if (this.resetTimer) { var inactiveSide = this.getInactiveSide(); var changed = false; if ((!this.battle.p1 || !this.battle.p2) && !this.disconnectTickDiff[0] && !this.disconnectTickDiff[1]) { if ((!this.battle.p1 && inactiveSide === 0) || (!this.battle.p2 && inactiveSide === 1)) { var inactiveUser = this.battle.getPlayer(inactiveSide); if (!this.battle.p1 && inactiveSide === 0 && this.sideTurnTicks[0] > 7) { this.disconnectTickDiff[0] = this.sideTurnTicks[0] - 7; this.sideTurnTicks[0] = 7; changed = true; } else if (!this.battle.p2 && inactiveSide === 1 && this.sideTurnTicks[1] > 7) { this.disconnectTickDiff[1] = this.sideTurnTicks[1] - 7; this.sideTurnTicks[1] = 7; changed = true; } if (changed) { this.send('|inactive|' + (inactiveUser ? inactiveUser.name : 'Player ' + (inactiveSide + 1)) + ' disconnected and has a minute to reconnect!'); return true; } } } else if (this.battle.p1 && this.battle.p2) { // Only one of the following conditions should happen, but do // them both since you never know... if (this.disconnectTickDiff[0]) { this.sideTurnTicks[0] = this.sideTurnTicks[0] + this.disconnectTickDiff[0]; this.disconnectTickDiff[0] = 0; changed = 0; } if (this.disconnectTickDiff[1]) { this.sideTurnTicks[1] = this.sideTurnTicks[1] + this.disconnectTickDiff[1]; this.disconnectTickDiff[1] = 0; changed = 1; } if (changed !== false) { var user = this.battle.getPlayer(changed); this.send('|inactive|' + (user ? user.name : 'Player ' + (changed + 1)) + ' reconnected and has ' + (this.sideTurnTicks[changed] * 10) + ' seconds left!'); return true; } } } return false; }; BattleRoom.prototype.decision = function (user, choice, data) { this.battle.sendFor(user, choice, data); if (this.active !== this.battle.active) { rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; } this.update(); }; // This function is only called when the room is not empty. // Joining an empty room calls this.join() below instead. BattleRoom.prototype.onJoinConnection = function (user, connection) { this.sendUser(connection, '|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n')); // this handles joining a battle in which a user is a participant, // where the user has already identified before attempting to join // the battle this.battle.resendRequest(user); }; BattleRoom.prototype.onJoin = function (user, connection) { if (!user) return false; if (this.users[user.userid]) return user; if (user.named) { this.add('|join|' + user.name); this.update(); } this.users[user.userid] = user; this.userCount++; this.sendUser(connection, '|init|battle\n|title|' + this.title + '\n' + this.getLogForUser(user).join('\n')); return user; }; BattleRoom.prototype.onRename = function (user, oldid, joining) { if (joining) { this.add('|join|' + user.name); } var resend = joining || !this.battle.playerTable[oldid]; if (this.battle.playerTable[oldid]) { if (this.rated) { this.add('|message|' + user.name + ' forfeited by changing their name.'); this.battle.lose(oldid); this.battle.leave(oldid); resend = false; } else { this.battle.rename(); } } delete this.users[oldid]; this.users[user.userid] = user; this.update(); if (resend) { // this handles a named user renaming themselves into a user in the // battle (i.e. by using /nick) this.battle.resendRequest(user); } return user; }; BattleRoom.prototype.onUpdateIdentity = function () {}; BattleRoom.prototype.onLeave = function (user) { if (!user) return; // ... if (user.battles[this.id]) { this.battle.leave(user); rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; } else if (!user.named) { delete this.users[user.userid]; return; } delete this.users[user.userid]; this.userCount--; this.add('|leave|' + user.name); if (Object.isEmpty(this.users)) { rooms.global.battleCount += 0 - (this.active ? 1 : 0); this.active = false; } this.update(); this.kickInactiveUpdate(); }; BattleRoom.prototype.joinBattle = function (user, team) { var slot; if (this.rated) { if (this.rated.p1 === user.userid) { slot = 0; } else if (this.rated.p2 === user.userid) { slot = 1; } else { user.popup("This is a rated battle; your username must be " + this.rated.p1 + " or " + this.rated.p2 + " to join."); return false; } } if (this.battle.active) { user.popup("This battle already has two players."); return false; } this.auth[user.userid] = '\u2605'; this.battle.join(user, slot, team); rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; if (this.active) { this.title = "" + this.battle.p1 + " vs. " + this.battle.p2; this.send('|title|' + this.title); } this.update(); this.kickInactiveUpdate(); }; BattleRoom.prototype.leaveBattle = function (user) { if (!user) return false; // ... if (user.battles[this.id]) { this.battle.leave(user); } else { return false; } this.auth[user.userid] = '+'; rooms.global.battleCount += (this.battle.active ? 1 : 0) - (this.active ? 1 : 0); this.active = this.battle.active; this.update(); this.kickInactiveUpdate(); return true; }; BattleRoom.prototype.expire = function () { this.send('|expire|'); this.destroy(); }; BattleRoom.prototype.destroy = function () { // deallocate ourself // remove references to ourself for (var i in this.users) { this.users[i].leaveRoom(this); delete this.users[i]; } this.users = null; rooms.global.removeRoom(this.id); // deallocate children and get rid of references to them if (this.battle) { this.battle.destroy(); } this.battle = null; if (this.resetTimer) { clearTimeout(this.resetTimer); } this.resetTimer = null; // get rid of some possibly-circular references delete rooms[this.id]; }; return BattleRoom; })(); var ChatRoom = (function () { function ChatRoom(roomid, title, options) { Room.call(this, roomid, title); if (options) { this.chatRoomData = options; Object.merge(this, options); } this.logTimes = true; this.logFile = null; this.logFilename = ''; this.destroyingLog = false; if (!this.modchat) this.modchat = (Config.chatmodchat || false); if (Config.logchat) { this.rollLogFile(true); this.logEntry = function (entry, date) { var timestamp = (new Date()).format('{HH}:{mm}:{ss} '); this.logFile.write(timestamp + entry + '\n'); }; this.logEntry('NEW CHATROOM: ' + this.id); if (Config.loguserstats) { setInterval(this.logUserStats.bind(this), Config.loguserstats); } } if (Config.reportjoinsperiod) { this.userList = this.getUserList(); this.reportJoinsQueue = []; } } ChatRoom.prototype = Object.create(Room.prototype); ChatRoom.prototype.type = 'chat'; ChatRoom.prototype.reportRecentJoins = function () { delete this.reportJoinsInterval; if (this.reportJoinsQueue.length === 0) { // nothing to report return; } if (Config.reportjoinsperiod) { this.userList = this.getUserList(); } this.send(this.reportJoinsQueue.join('\n')); this.reportJoinsQueue.length = 0; }; ChatRoom.prototype.rollLogFile = function (sync) { var mkdir = sync ? function (path, mode, callback) { try { fs.mkdirSync(path, mode); } catch (e) {} // directory already exists callback(); } : fs.mkdir; var date = new Date(); var basepath = 'logs/chat/' + this.id + '/'; var self = this; mkdir(basepath, '0755', function () { var path = date.format('{yyyy}-{MM}'); mkdir(basepath + path, '0755', function () { if (self.destroyingLog) return; path += '/' + date.format('{yyyy}-{MM}-{dd}') + '.txt'; if (path !== self.logFilename) { self.logFilename = path; if (self.logFile) self.logFile.destroySoon(); self.logFile = fs.createWriteStream(basepath + path, {flags: 'a'}); // Create a symlink to today's lobby log. // These operations need to be synchronous, but it's okay // because this code is only executed once every 24 hours. var link0 = basepath + 'today.txt.0'; try { fs.unlinkSync(link0); } catch (e) {} // file doesn't exist try { fs.symlinkSync(path, link0); // `basepath` intentionally not included try { fs.renameSync(link0, basepath + 'today.txt'); } catch (e) {} // OS doesn't support atomic rename } catch (e) {} // OS doesn't support symlinks } var timestamp = +date; date.advance('1 hour').reset('minutes').advance('1 second'); setTimeout(self.rollLogFile.bind(self), +date - timestamp); }); }); }; ChatRoom.prototype.destroyLog = function (initialCallback, finalCallback) { this.destroyingLog = true; initialCallback(); if (this.logFile) { this.logEntry = function () { }; this.logFile.on('close', finalCallback); this.logFile.destroySoon(); } else { finalCallback(); } }; ChatRoom.prototype.logUserStats = function () { var total = 0; var guests = 0; var groups = {}; Config.groupsranking.forEach(function (group) { groups[group] = 0; }); for (var i in this.users) { var user = this.users[i]; ++total; if (!user.named) { ++guests; } ++groups[user.group]; } var entry = '|userstats|total:' + total + '|guests:' + guests; for (var i in groups) { entry += '|' + i + ':' + groups[i]; } this.logEntry(entry); }; ChatRoom.prototype.getUserList = function () { var buffer = ''; var counter = 0; for (var i in this.users) { if (!this.users[i].named) { continue; } counter++; buffer += ',' + this.users[i].getIdentity(this.id); } var msg = '|users|' + counter + buffer; return msg; }; ChatRoom.prototype.reportJoin = function (entry) { if (Config.reportjoinsperiod) { if (!this.reportJoinsInterval) { this.reportJoinsInterval = setTimeout( this.reportRecentJoins.bind(this), Config.reportjoinsperiod ); } this.reportJoinsQueue.push(entry); } else { this.send(entry); } this.logEntry(entry); }; ChatRoom.prototype.update = function () { if (this.log.length <= this.lastUpdate) return; var entries = this.log.slice(this.lastUpdate); if (this.reportJoinsQueue && this.reportJoinsQueue.length) { clearTimeout(this.reportJoinsInterval); delete this.reportJoinsInterval; Array.prototype.unshift.apply(entries, this.reportJoinsQueue); this.reportJoinsQueue.length = 0; this.userList = this.getUserList(); } var update = entries.join('\n'); if (this.log.length > 100) { this.log.splice(0, this.log.length - 100); } this.lastUpdate = this.log.length; this.send(update); }; ChatRoom.prototype.getIntroMessage = function () { var html = this.introMessage || ''; if (this.modchat) { if (html) html += '<br /><br />'; html += '<div class="broadcast-red">'; html += 'Must be rank ' + this.modchat + ' or higher to talk right now.'; html += '</div>'; } if (html) return '\n|raw|<div class="infobox">' + html + '</div>'; return ''; }; ChatRoom.prototype.onJoinConnection = function (user, connection) { var userList = this.userList ? this.userList : this.getUserList(); this.sendUser(connection, '|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.getLogSlice(-25).join('\n') + this.getIntroMessage()); if (global.Tournaments && Tournaments.get(this.id)) { Tournaments.get(this.id).updateFor(user, connection); } }; ChatRoom.prototype.onJoin = function (user, connection, merging) { if (!user) return false; // ??? if (this.users[user.userid]) return user; if (user.named && Config.reportjoins) { this.add('|j|' + user.getIdentity(this.id)); this.update(); } else if (user.named) { var entry = '|J|' + user.getIdentity(this.id); this.reportJoin(entry); } this.users[user.userid] = user; this.userCount++; if (!merging) { var userList = this.userList ? this.userList : this.getUserList(); this.sendUser(connection, '|init|chat\n|title|' + this.title + '\n' + userList + '\n' + this.getLogSlice(-100).join('\n') + this.getIntroMessage()); } if (global.Tournaments && Tournaments.get(this.id)) { Tournaments.get(this.id).updateFor(user, connection); } return user; }; ChatRoom.prototype.onRename = function (user, oldid, joining) { delete this.users[oldid]; if (this.bannedUsers && (user.userid in this.bannedUsers || user.autoconfirmed in this.bannedUsers)) { this.bannedUsers[oldid] = true; for (var ip in user.ips) this.bannedIps[ip] = true; user.leaveRoom(this); var alts = user.getAlts(); for (var i = 0; i < alts.length; ++i) { this.bannedUsers[toId(alts[i])] = true; Users.getExact(alts[i]).leaveRoom(this); } return; } this.users[user.userid] = user; var entry; if (joining) { if (Config.reportjoins) { entry = '|j|' + user.getIdentity(this.id); } else { entry = '|J|' + user.getIdentity(this.id); } } else if (!user.named) { entry = '|L| ' + oldid; } else { entry = '|N|' + user.getIdentity(this.id) + '|' + oldid; } if (Config.reportjoins) { this.add(entry); } else { this.reportJoin(entry); } if (global.Tournaments && Tournaments.get(this.id)) { Tournaments.get(this.id).updateFor(user); } return user; }; /** * onRename, but without a userid change */ ChatRoom.prototype.onUpdateIdentity = function (user) { if (user && user.connected && user.named) { if (!this.users[user.userid]) return false; var entry = '|N|' + user.getIdentity(this.id) + '|' + user.userid; this.reportJoin(entry); } }; ChatRoom.prototype.onLeave = function (user) { if (!user) return; // ... delete this.users[user.userid]; this.userCount--; if (user.named && Config.reportjoins) { this.add('|l|' + user.getIdentity(this.id)); } else if (user.named) { var entry = '|L|' + user.getIdentity(this.id); this.reportJoin(entry); } }; ChatRoom.prototype.destroy = function () { // deallocate ourself // remove references to ourself for (var i in this.users) { this.users[i].leaveRoom(this); delete this.users[i]; } this.users = null; rooms.global.deregisterChatRoom(this.id); rooms.global.delistChatRoom(this.id); // get rid of some possibly-circular references delete rooms[this.id]; }; return ChatRoom; })(); // to make sure you don't get null returned, pass the second argument function getRoom(roomid, fallback) { if (roomid && roomid.id) return roomid; if (!roomid) roomid = 'default'; if (!rooms[roomid] && fallback) { return rooms.global; } return rooms[roomid]; } Rooms.get = getRoom; Rooms.createBattle = function (roomid, format, p1, p2, parent, rated) { if (roomid && roomid.id) return roomid; if (!p1 || !p2) return false; if (!roomid) roomid = 'default'; if (!rooms[roomid]) { // console.log("NEW BATTLE ROOM: " + roomid); ResourceMonitor.countBattle(p1.latestIp, p1.name); ResourceMonitor.countBattle(p2.latestIp, p2.name); rooms[roomid] = new BattleRoom(roomid, format, p1, p2, parent, rated); } return rooms[roomid]; }; Rooms.createChatRoom = function (roomid, title, data) { var room; if ((room = rooms[roomid])) return room; room = rooms[roomid] = new ChatRoom(roomid, title, data); return room; }; console.log("NEW GLOBAL: global"); rooms.global = new GlobalRoom('global'); Rooms.GlobalRoom = GlobalRoom; Rooms.BattleRoom = BattleRoom; Rooms.ChatRoom = ChatRoom; Rooms.global = rooms.global; Rooms.lobby = rooms.lobby;
Nineage/Showdown-Boilerplate
rooms.js
JavaScript
mit
46,612
[ 30522, 1013, 1008, 1008, 1008, 4734, 1008, 20421, 24419, 1011, 8299, 1024, 1013, 1013, 20421, 22231, 21724, 12384, 1012, 4012, 1013, 1008, 1008, 2296, 11834, 2282, 1998, 2645, 2003, 1037, 2282, 1010, 1998, 2054, 2027, 2079, 2003, 2589, 1999...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/* * Copyright (c) OSGi Alliance (2012). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * OSGi JMX Framework Wiring Package Version 1.1. * * <p> * Bundles wishing to use this package must list the package in the * Import-Package header of the bundle's manifest. This package has two types of * users: the consumers that use the API in this package and the providers that * implement the API in this package. * * <p> * Example import for consumers using the API in this package: * <p> * {@code Import-Package: org.osgi.jmx.framework.wiring; version="[1.1,2.0)"} * <p> * Example import for providers implementing the API in this package: * <p> * {@code Import-Package: org.osgi.jmx.framework.wiring; version="[1.1,1.2)"} * * @version $Id: 9710af79a8da06986298af0dede257cbcbb6c487 $ */ package org.osgi.jmx.framework.wiring;
eclipse/gemini.managment
org.eclipse.gemini.management/src/main/java/org/osgi/jmx/framework/wiring/package-info.java
Java
apache-2.0
1,392
[ 30522, 1013, 1008, 1008, 9385, 1006, 1039, 1007, 9808, 5856, 4707, 1006, 2262, 1007, 1012, 2035, 2916, 9235, 1012, 1008, 1008, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1008, 20...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Copyright 2015 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import logging import os from oslo_concurrency import processutils as putils from oslo_config import cfg from taskflow.patterns import linear_flow as lf from taskflow import task from glance import i18n _ = i18n._ _LI = i18n._LI _LE = i18n._LE _LW = i18n._LW LOG = logging.getLogger(__name__) convert_task_opts = [ cfg.StrOpt('conversion_format', default=None, choices=('qcow2', 'raw', 'vmdk'), help=_("The format to which images will be automatically " "converted.")), ] CONF = cfg.CONF # NOTE(flaper87): Registering under the taskflow_executor section # for now. It seems a waste to have a whole section dedicated to a # single task with a single option. CONF.register_opts(convert_task_opts, group='taskflow_executor') class _Convert(task.Task): conversion_missing_warned = False def __init__(self, task_id, task_type, image_repo): self.task_id = task_id self.task_type = task_type self.image_repo = image_repo super(_Convert, self).__init__( name='%s-Convert-%s' % (task_type, task_id)) def execute(self, image_id, file_path): # NOTE(flaper87): A format must be explicitly # specified. There's no "sane" default for this # because the dest format may work differently depending # on the environment OpenStack is running in. conversion_format = CONF.taskflow_executor.conversion_format if conversion_format is None: if not _Convert.conversion_missing_warned: msg = (_LW('The conversion format is None, please add a value ' 'for it in the config file for this task to ' 'work: %s') % self.task_id) LOG.warn(msg) _Convert.conversion_missing_warned = True return # TODO(flaper87): Check whether the image is in the desired # format already. Probably using `qemu-img` just like the # `Introspection` task. dest_path = os.path.join(CONF.task.work_dir, "%s.converted" % image_id) stdout, stderr = putils.trycmd('qemu-img', 'convert', '-O', conversion_format, file_path, dest_path, log_errors=putils.LOG_ALL_ERRORS) if stderr: raise RuntimeError(stderr) os.rename(dest_path, file_path.split("file://")[-1]) return file_path def revert(self, image_id, result=None, **kwargs): # NOTE(flaper87): If result is None, it probably # means this task failed. Otherwise, we would have # a result from its execution. if result is None: return fs_path = result.split("file://")[-1] if os.path.exists(fs_path): os.path.remove(fs_path) def get_flow(**kwargs): """Return task flow for converting images to different formats. :param task_id: Task ID. :param task_type: Type of the task. :param image_repo: Image repository used. """ task_id = kwargs.get('task_id') task_type = kwargs.get('task_type') image_repo = kwargs.get('image_repo') return lf.Flow(task_type).add( _Convert(task_id, task_type, image_repo), )
saeki-masaki/glance
glance/async/flows/convert.py
Python
apache-2.0
3,953
[ 30522, 1001, 9385, 2325, 7480, 2696, 3600, 3192, 1001, 2035, 2916, 9235, 1012, 1001, 1001, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 2017, 2089, 1001, 2025, 2224, 2023, 5371, 32...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package main import ( "bytes" "context" "log" "net/http" "net/http/httptest" "strings" "testing" "time" strings_app "github.com/utrack/clay/integration/client_cancel_request/app/strings" strings_pb "github.com/utrack/clay/integration/client_cancel_request/pkg/strings" ) func TestCancelRequest(t *testing.T) { ts := testServer() errlog := bytes.NewBuffer([]byte{}) ts.Config.ErrorLog = log.New(errlog, "", 0) defer func() { ts.Close() if errlog.Len() > 0 { t.Fatalf("expected no errors, got: %s", errlog.Bytes()) } }() httpClient := ts.Client() client := strings_pb.NewStringsHTTPClient(httpClient, ts.URL) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond) defer cancel() client.ToUpper(ctx, &strings_pb.String{Str: strings.Repeat("s", 10*1024)}) } func testServer() *httptest.Server { mux := http.NewServeMux() desc := strings_app.NewStrings().GetDescription() desc.RegisterHTTP(mux) mux.Handle("/swagger.json", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/javascript") w.Write(desc.SwaggerDef()) })) ts := httptest.NewServer(mux) return ts }
utrack/clay
integration/client_cancel_request/main_test.go
GO
mit
1,183
[ 30522, 7427, 2364, 12324, 1006, 1000, 27507, 1000, 1000, 6123, 1000, 1000, 8833, 1000, 1000, 5658, 1013, 8299, 1000, 1000, 5658, 1013, 8299, 1013, 8299, 22199, 1000, 1000, 7817, 1000, 1000, 5604, 1000, 1000, 2051, 1000, 7817, 1035, 10439, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!-- Safe sample input : get the field userData from the variable $_GET via an object sanitize : use of the function htmlspecialchars. Sanitizes the query but has a high chance to produce unexpected results File : use of untrusted data in the body --> <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.--> <!DOCTYPE html> <html> <head/> <body> <?php class Input{ private $input; public function getInput(){ return $this->input; } public function __construct(){ $this->input = $_GET['UserData'] ; } } $temp = new Input(); $tainted = $temp->getInput(); $tainted = htmlspecialchars($tainted, ENT_QUOTES); echo $tainted ; ?> <h1>Hello World!</h1> </body> </html>
stivalet/PHP-Vulnerability-test-suite
XSS/CWE_79/safe/CWE_79__object-classicGet__func_htmlspecialchars__Use_untrusted_data-body.php
PHP
mit
1,542
[ 30522, 1026, 999, 1011, 1011, 3647, 7099, 7953, 1024, 2131, 1996, 2492, 5310, 2850, 2696, 2013, 1996, 8023, 1002, 1035, 2131, 3081, 2019, 4874, 2624, 25090, 4371, 1024, 2224, 1997, 1996, 3853, 16129, 13102, 8586, 4818, 7507, 2869, 1012, 2...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
module Miro class DominantColors attr_accessor :src_image_path def initialize(src_image_path, image_type = nil) @src_image_path = src_image_path @image_type = image_type end def to_hex return histogram.map{ |item| item[1].html } if Miro.histogram? sorted_pixels.collect { |pixel| ChunkyPNG::Color.to_hex(pixel, false) } end def to_rgb return histogram.map { |item| item[1].to_rgb.to_a } if Miro.histogram? sorted_pixels.collect { |pixel| ChunkyPNG::Color.to_truecolor_bytes(pixel) } end def to_rgba return histogram.map { |item| item[1].css_rgba } if Miro.histogram? sorted_pixels.collect { |pixel| ChunkyPNG::Color.to_truecolor_alpha_bytes(pixel) } end def to_hsl histogram.map { |item| item[1].to_hsl.to_a } if Miro.histogram? end def to_cmyk histogram.map { |item| item[1].to_cmyk.to_a } if Miro.histogram? end def to_yiq histogram.map { |item| item[1].to_yiq.to_a } if Miro.histogram? end def by_percentage return nil if Miro.histogram? sorted_pixels pixel_count = @pixels.size sorted_pixels.collect { |pixel| @grouped_pixels[pixel].size / pixel_count.to_f } end def sorted_pixels @sorted_pixels ||= extract_colors_from_image end def histogram @histogram ||= downsample_and_histogram.sort_by { |item| item[0] }.reverse end private def downsample_and_histogram @source_image = open_source_image hstring = Cocaine::CommandLine.new(Miro.options[:image_magick_path], image_magick_params). run(:in => File.expand_path(@source_image.path), :resolution => Miro.options[:resolution], :colors => Miro.options[:color_count].to_s, :quantize => Miro.options[:quantize]) cleanup_temporary_files! parse_result(hstring) end def parse_result(hstring) hstring.scan(/(\d*):.*(#[0-9A-Fa-f]*)/).collect do |match| [match[0].to_i, Object.const_get("Color::#{Miro.options[:quantize].upcase}").from_html(match[1])] end end def extract_colors_from_image downsample_colors_and_convert_to_png! colors = sort_by_dominant_color cleanup_temporary_files! colors end def downsample_colors_and_convert_to_png! @source_image = open_source_image @downsampled_image = open_downsampled_image Cocaine::CommandLine.new(Miro.options[:image_magick_path], image_magick_params). run(:in => File.expand_path(@source_image.path), :resolution => Miro.options[:resolution], :colors => Miro.options[:color_count].to_s, :quantize => Miro.options[:quantize], :out => File.expand_path(@downsampled_image.path)) end def open_source_image return File.open(@src_image_path) unless remote_source_image? original_extension = @image_type || URI.parse(@src_image_path).path.split('.').last tempfile = Tempfile.open(["source", ".#{original_extension}"]) remote_file_data = open(@src_image_path).read tempfile.write(should_force_encoding? ? remote_file_data.force_encoding("UTF-8") : remote_file_data) tempfile.close tempfile end def should_force_encoding? Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('1.9') end def open_downsampled_image tempfile = Tempfile.open(["downsampled", '.png']) tempfile.binmode tempfile end def image_magick_params if Miro.histogram? "':in[0]' -resize :resolution -colors :colors -colorspace :quantize -quantize :quantize -alpha remove -format %c histogram:info:" else "':in[0]' -resize :resolution -colors :colors -colorspace :quantize -quantize :quantize :out" end end def group_pixels_by_color @pixels ||= ChunkyPNG::Image.from_file(File.expand_path(@downsampled_image.path)).pixels @grouped_pixels ||= @pixels.group_by { |pixel| pixel } end def sort_by_dominant_color group_pixels_by_color.sort_by { |k,v| v.size }.reverse.flatten.uniq end def cleanup_temporary_files! @source_image.close! if remote_source_image? @downsampled_image.close! if @downsampled_image end def remote_source_image? @src_image_path =~ /^https?:\/\// end end end
oxoooo/miro
lib/miro/dominant_colors.rb
Ruby
mit
4,361
[ 30522, 11336, 14719, 2080, 2465, 7444, 18717, 2015, 2012, 16344, 1035, 3229, 2953, 1024, 5034, 2278, 1035, 3746, 1035, 4130, 13366, 3988, 4697, 1006, 5034, 2278, 1035, 3746, 1035, 4130, 1010, 3746, 1035, 2828, 1027, 9152, 2140, 1007, 1030, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/** File Name: expression-014.js Corresponds To: ecma/Expressions/11.2.2-9-n.js ECMA Section: 11.2.2. The new operator Description: Author: christine@netscape.com Date: 12 november 1997 */ var SECTION = "expression-014.js"; var VERSION = "ECMA_1"; var TITLE = "The new operator"; var BUGNUMBER= "327765"; startTest(); writeHeaderToLog( SECTION + " "+ TITLE); var tc = 0; var testcases = new Array(); var BOOLEAN = new Boolean(); var result = "Failed"; var exception = "No exception thrown"; var expect = "Passed"; try { result = new BOOLEAN(); } catch ( e ) { result = expect; exception = e.toString(); } testcases[tc++] = new TestCase( SECTION, "BOOLEAN = new Boolean(); result = new BOOLEAN()" + " (threw " + exception +")", expect, result ); test();
danialbehzadi/Nokia-RM-1013-2.0.0.11
webkit/Source/JavaScriptCore/tests/mozilla/ecma_2/Exceptions/expression-014.js
JavaScript
gpl-3.0
966
[ 30522, 1013, 1008, 1008, 5371, 2171, 1024, 3670, 1011, 5890, 2549, 1012, 1046, 2015, 14788, 2000, 1024, 14925, 2863, 1013, 11423, 1013, 2340, 1012, 1016, 1012, 1016, 1011, 1023, 1011, 1050, 1012, 1046, 2015, 14925, 2863, 2930, 1024, 2340, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<?php /** * Axis * * This file is part of Axis. * * Axis is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Axis is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Axis. If not, see <http://www.gnu.org/licenses/>. * * @category Axis * @package Axis_Cache * @subpackage Axis_Cache_Backend * @copyright Copyright 2008-2012 Axis * @license GNU Public License V3.0 */ /** * * @category Axis * @package Axis_Cache * @subpackage Axis_Cache_Backend * @author Axis Core Team <core@axiscommerce.com> */ class Axis_Cache_Backend_File extends Zend_Cache_Backend_File { private $_disabledTags = array(); /** * * @param array $options */ public function __construct(array $options = array()) { parent::__construct($options); $this->_disabledTags = Axis::single('core/cache')->getDisabled(); } /** * Extended parent save method * Save some string datas into a cache record * * Note : $data is always "string" (serialization is done by the * core not by the backend) * * @param string $data Datas to cache * @param string $id Cache id * @param array $tags Array of strings, the cache record will be tagged by each string entry * @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime) * @return boolean true if no problem */ public function save($data, $id, $tags = array(), $specificLifetime = false) { if (count(array_intersect($tags, $this->_disabledTags))) { return false; } if (!$specificLifetime && count($tags)) { $specificLifetime = Axis::single('core/cache')->getLifetimeByTags($tags); } return parent::save($data, $id, $tags, $specificLifetime); } /** * Extended parent load method * Test if a cache is available for the given id and (if yes) return it (false else) * * @param string $id cache id * @param boolean $doNotTestCacheValidity if set to true, the cache validity won't be tested * @return string|false cached datas */ public function load($id, $doNotTestCacheValidity = false) { $metadatas = $this->getMetadatas($id); if (count($metadatas['tags'])) { if (count(array_intersect($metadatas['tags'], $this->_disabledTags))) { return false; } } return parent::load($id, $doNotTestCacheValidity); } /** * Extended parent test method * Test if a cache is available or not (for the given id) * * @param string $id cache id * @return mixed false (a cache is not available) or "last modified" timestamp (int) of the available cache record */ public function test($id) { $metadatas = $this->getMetadatas($id); if (count($metadatas['tags'])) { if (count(array_intersect($metadatas['tags'], $this->_disabledTags))) { return false; } } return parent::test($id); } }
axis/axiscommerce
library/Axis/Cache/Backend/File.php
PHP
gpl-3.0
3,607
[ 30522, 1026, 1029, 25718, 1013, 1008, 1008, 1008, 8123, 1008, 1008, 2023, 5371, 2003, 2112, 1997, 8123, 1012, 1008, 1008, 8123, 2003, 2489, 4007, 1024, 2017, 2064, 2417, 2923, 3089, 8569, 2618, 2009, 1998, 1013, 2030, 19933, 1008, 2009, 2...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
version https://git-lfs.github.com/spec/v1 oid sha256:ad911cfe35ed2702a6023f24dac7e20b7b1d64e5583cd53411e87b5c10fa0c35 size 16080
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.16.0/series-column/series-column-coverage.js
JavaScript
mit
130
[ 30522, 2544, 16770, 1024, 1013, 1013, 21025, 2102, 1011, 1048, 10343, 1012, 21025, 2705, 12083, 1012, 4012, 1013, 28699, 1013, 1058, 2487, 1051, 3593, 21146, 17788, 2575, 1024, 4748, 2683, 14526, 2278, 7959, 19481, 2098, 22907, 2692, 2475, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
package uk.ac.ebi.subs.arrayexpress.repo; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import uk.ac.ebi.subs.arrayexpress.model.SampleDataRelationship; import java.util.List; public interface SampleDataRelatioshipRepository extends MongoRepository<SampleDataRelationship, String> { @Query(value="{ 'assay.sampleUses.sampleRef.accession': ?0 }") Page<SampleDataRelationship> findBySampleAccession(String sampleAccession, Pageable pageable); @Query("{ 'assay.sampleUses.sampleRef.accession' : { $in : ?0 } }") List<SampleDataRelationship> findBySampleAccessions(String[] sampleAccessions); }
EMBL-EBI-SUBS/subs
subs-aeagent/src/main/java/uk/ac/ebi/subs/arrayexpress/repo/SampleDataRelatioshipRepository.java
Java
apache-2.0
787
[ 30522, 7427, 2866, 1012, 9353, 1012, 1041, 5638, 1012, 4942, 2015, 1012, 9140, 10288, 20110, 1012, 16360, 2080, 1025, 12324, 8917, 1012, 3500, 15643, 6198, 1012, 2951, 1012, 5884, 1012, 3931, 1025, 12324, 8917, 30524, 1012, 3500, 15643, 619...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// run-pass const _FOO: fn() -> String = || "foo".into(); pub fn bar() -> fn() -> String { || "bar".into() } fn main(){}
aidancully/rust
src/test/ui/consts/not_const_clusure_in_const.rs
Rust
apache-2.0
128
[ 30522, 1013, 1013, 2448, 1011, 3413, 9530, 3367, 1035, 29379, 1024, 1042, 2078, 1006, 1007, 1011, 1028, 5164, 1027, 1064, 1064, 1000, 29379, 1000, 1012, 2046, 1006, 1007, 1025, 9047, 1042, 2078, 3347, 1006, 1007, 1011, 1028, 1042, 2078, 1...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
'use strict'; export interface IPrint extends ng.resource.IResource<IPrint> { printOptions: any; } export interface IPrintResource extends ng.resource.IResourceClass<IPrint> {} export class PrintResource { /* @ngInject */ public static Print($resource: ng.resource.IResourceService): IPrintResource { var url = '/api/print'; var resource = $resource(url, {}); return <IPrintResource> resource; } }
marksmall/mapuse
src/app/components/print/print.resource.ts
TypeScript
mit
424
[ 30522, 1005, 2224, 9384, 1005, 1025, 9167, 8278, 12997, 6657, 2102, 8908, 12835, 1012, 7692, 1012, 20868, 2229, 8162, 3401, 1026, 12997, 6657, 2102, 1028, 1063, 6140, 7361, 9285, 1024, 2151, 1025, 1065, 9167, 8278, 12997, 6657, 19168, 8162,...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// RUN: %clang_cc1 %s -triple=x86_64-apple-darwin10 -emit-llvm -o - -fcxx-exceptions -fexceptions | FileCheck %s typedef typeof(sizeof(0)) size_t; // This just shouldn't crash. namespace test0 { struct allocator { allocator(); allocator(const allocator&); ~allocator(); }; void f(); void g(bool b, bool c) { if (b) { if (!c) throw allocator(); return; } f(); } } namespace test1 { struct A { A(int); A(int, int); ~A(); void *p; }; A *a() { // CHECK: define [[A:%.*]]* @_ZN5test11aEv() // CHECK: [[NEW:%.*]] = call noalias i8* @_Znwm(i64 8) // CHECK-NEXT: [[CAST:%.*]] = bitcast i8* [[NEW]] to [[A]]* // CHECK-NEXT: invoke void @_ZN5test11AC1Ei([[A]]* [[CAST]], i32 5) // CHECK: ret [[A]]* [[CAST]] // CHECK: call void @_ZdlPv(i8* [[NEW]]) return new A(5); } A *b() { // CHECK: define [[A:%.*]]* @_ZN5test11bEv() // CHECK: [[NEW:%.*]] = call noalias i8* @_Znwm(i64 8) // CHECK-NEXT: [[CAST:%.*]] = bitcast i8* [[NEW]] to [[A]]* // CHECK-NEXT: [[FOO:%.*]] = invoke i32 @_ZN5test13fooEv() // CHECK: invoke void @_ZN5test11AC1Ei([[A]]* [[CAST]], i32 [[FOO]]) // CHECK: ret [[A]]* [[CAST]] // CHECK: call void @_ZdlPv(i8* [[NEW]]) extern int foo(); return new A(foo()); } struct B { B(); ~B(); operator int(); int x; }; B makeB(); A *c() { // CHECK: define [[A:%.*]]* @_ZN5test11cEv() // CHECK: [[ACTIVE:%.*]] = alloca i1 // CHECK-NEXT: [[NEW:%.*]] = call noalias i8* @_Znwm(i64 8) // CHECK-NEXT: store i1 true, i1* [[ACTIVE]] // CHECK-NEXT: [[CAST:%.*]] = bitcast i8* [[NEW]] to [[A]]* // CHECK-NEXT: invoke void @_ZN5test11BC1Ev([[B:%.*]]* [[T0:%.*]]) // CHECK: [[T1:%.*]] = getelementptr inbounds [[B]]* [[T0]], i32 0, i32 0 // CHECK-NEXT: [[T2:%.*]] = load i32* [[T1]], align 4 // CHECK-NEXT: invoke void @_ZN5test11AC1Ei([[A]]* [[CAST]], i32 [[T2]]) // CHECK: store i1 false, i1* [[ACTIVE]] // CHECK-NEXT: invoke void @_ZN5test11BD1Ev([[B]]* [[T0]]) // CHECK: ret [[A]]* [[CAST]] // CHECK: [[ISACTIVE:%.*]] = load i1* [[ACTIVE]] // CHECK-NEXT: br i1 [[ISACTIVE]] // CHECK: call void @_ZdlPv(i8* [[NEW]]) return new A(B().x); } // rdar://11904428 // Terminate landing pads should call __cxa_begin_catch first. // CHECK: define linkonce_odr hidden void @__clang_call_terminate(i8*) [[NI_NR_NUW:#[0-9]+]] // CHECK-NEXT: [[T0:%.*]] = call i8* @__cxa_begin_catch(i8* %0) [[NUW:#[0-9]+]] // CHECK-NEXT: call void @_ZSt9terminatev() [[NR_NUW:#[0-9]+]] // CHECK-NEXT: unreachable A *d() { // CHECK: define [[A:%.*]]* @_ZN5test11dEv() // CHECK: [[ACTIVE:%.*]] = alloca i1 // CHECK-NEXT: [[NEW:%.*]] = call noalias i8* @_Znwm(i64 8) // CHECK-NEXT: store i1 true, i1* [[ACTIVE]] // CHECK-NEXT: [[CAST:%.*]] = bitcast i8* [[NEW]] to [[A]]* // CHECK-NEXT: invoke void @_ZN5test11BC1Ev([[B:%.*]]* [[T0:%.*]]) // CHECK: [[T1:%.*]] = invoke i32 @_ZN5test11BcviEv([[B]]* [[T0]]) // CHECK: invoke void @_ZN5test11AC1Ei([[A]]* [[CAST]], i32 [[T1]]) // CHECK: store i1 false, i1* [[ACTIVE]] // CHECK-NEXT: invoke void @_ZN5test11BD1Ev([[B]]* [[T0]]) // CHECK: ret [[A]]* [[CAST]] // CHECK: [[ISACTIVE:%.*]] = load i1* [[ACTIVE]] // CHECK-NEXT: br i1 [[ISACTIVE]] // CHECK: call void @_ZdlPv(i8* [[NEW]]) return new A(B()); } A *e() { // CHECK: define [[A:%.*]]* @_ZN5test11eEv() // CHECK: [[ACTIVE:%.*]] = alloca i1 // CHECK-NEXT: [[NEW:%.*]] = call noalias i8* @_Znwm(i64 8) // CHECK-NEXT: store i1 true, i1* [[ACTIVE]] // CHECK-NEXT: [[CAST:%.*]] = bitcast i8* [[NEW]] to [[A]]* // CHECK-NEXT: invoke void @_ZN5test11BC1Ev([[B:%.*]]* [[T0:%.*]]) // CHECK: [[T1:%.*]] = invoke i32 @_ZN5test11BcviEv([[B]]* [[T0]]) // CHECK: invoke void @_ZN5test11BC1Ev([[B]]* [[T2:%.*]]) // CHECK: [[T3:%.*]] = invoke i32 @_ZN5test11BcviEv([[B]]* [[T2]]) // CHECK: invoke void @_ZN5test11AC1Eii([[A]]* [[CAST]], i32 [[T1]], i32 [[T3]]) // CHECK: store i1 false, i1* [[ACTIVE]] // CHECK-NEXT: invoke void @_ZN5test11BD1Ev([[B]]* [[T2]]) // CHECK: invoke void @_ZN5test11BD1Ev([[B]]* [[T0]]) // CHECK: ret [[A]]* [[CAST]] // CHECK: [[ISACTIVE:%.*]] = load i1* [[ACTIVE]] // CHECK-NEXT: br i1 [[ISACTIVE]] // CHECK: call void @_ZdlPv(i8* [[NEW]]) return new A(B(), B()); } A *f() { return new A(makeB().x); } A *g() { return new A(makeB()); } A *h() { return new A(makeB(), makeB()); } A *i() { // CHECK: define [[A:%.*]]* @_ZN5test11iEv() // CHECK: [[X:%.*]] = alloca [[A]]*, align 8 // CHECK: [[ACTIVE:%.*]] = alloca i1 // CHECK: [[NEW:%.*]] = call noalias i8* @_Znwm(i64 8) // CHECK-NEXT: store i1 true, i1* [[ACTIVE]] // CHECK-NEXT: [[CAST:%.*]] = bitcast i8* [[NEW]] to [[A]]* // CHECK-NEXT: invoke void @_ZN5test15makeBEv([[B:%.*]]* sret [[T0:%.*]]) // CHECK: [[T1:%.*]] = invoke i32 @_ZN5test11BcviEv([[B]]* [[T0]]) // CHECK: invoke void @_ZN5test11AC1Ei([[A]]* [[CAST]], i32 [[T1]]) // CHECK: store i1 false, i1* [[ACTIVE]] // CHECK-NEXT: store [[A]]* [[CAST]], [[A]]** [[X]], align 8 // CHECK: invoke void @_ZN5test15makeBEv([[B:%.*]]* sret [[T2:%.*]]) // CHECK: [[RET:%.*]] = load [[A]]** [[X]], align 8 // CHECK: invoke void @_ZN5test11BD1Ev([[B]]* [[T2]]) // CHECK: invoke void @_ZN5test11BD1Ev([[B]]* [[T0]]) // CHECK: ret [[A]]* [[RET]] // CHECK: [[ISACTIVE:%.*]] = load i1* [[ACTIVE]] // CHECK-NEXT: br i1 [[ISACTIVE]] // CHECK: call void @_ZdlPv(i8* [[NEW]]) A *x; return (x = new A(makeB()), makeB(), x); } } namespace test2 { struct A { A(int); A(int, int); ~A(); void *p; void *operator new(size_t); void operator delete(void*, size_t); }; A *a() { // CHECK: define [[A:%.*]]* @_ZN5test21aEv() // CHECK: [[NEW:%.*]] = call i8* @_ZN5test21AnwEm(i64 8) // CHECK-NEXT: [[CAST:%.*]] = bitcast i8* [[NEW]] to [[A]]* // CHECK-NEXT: invoke void @_ZN5test21AC1Ei([[A]]* [[CAST]], i32 5) // CHECK: ret [[A]]* [[CAST]] // CHECK: invoke void @_ZN5test21AdlEPvm(i8* [[NEW]], i64 8) // CHECK: call void @__clang_call_terminate(i8* {{%.*}}) [[NR_NUW]] return new A(5); } } namespace test3 { struct A { A(int); A(int, int); A(const A&); ~A(); void *p; void *operator new(size_t, void*, double); void operator delete(void*, void*, double); }; void *foo(); double bar(); A makeA(), *makeAPtr(); A *a() { // CHECK: define [[A:%.*]]* @_ZN5test31aEv() // CHECK: [[FOO:%.*]] = call i8* @_ZN5test33fooEv() // CHECK: [[BAR:%.*]] = call double @_ZN5test33barEv() // CHECK: [[NEW:%.*]] = call i8* @_ZN5test31AnwEmPvd(i64 8, i8* [[FOO]], double [[BAR]]) // CHECK-NEXT: [[CAST:%.*]] = bitcast i8* [[NEW]] to [[A]]* // CHECK-NEXT: invoke void @_ZN5test31AC1Ei([[A]]* [[CAST]], i32 5) // CHECK: ret [[A]]* [[CAST]] // CHECK: invoke void @_ZN5test31AdlEPvS1_d(i8* [[NEW]], i8* [[FOO]], double [[BAR]]) // CHECK: call void @__clang_call_terminate(i8* {{%.*}}) [[NR_NUW]] return new(foo(),bar()) A(5); } // rdar://problem/8439196 A *b(bool cond) { // CHECK: define [[A:%.*]]* @_ZN5test31bEb(i1 zeroext // CHECK: [[SAVED0:%.*]] = alloca i8* // CHECK-NEXT: [[SAVED1:%.*]] = alloca i8* // CHECK-NEXT: [[CLEANUPACTIVE:%.*]] = alloca i1 // CHECK: [[COND:%.*]] = trunc i8 {{.*}} to i1 // CHECK-NEXT: store i1 false, i1* [[CLEANUPACTIVE]] // CHECK-NEXT: br i1 [[COND]] return (cond ? // CHECK: [[FOO:%.*]] = call i8* @_ZN5test33fooEv() // CHECK-NEXT: [[NEW:%.*]] = call i8* @_ZN5test31AnwEmPvd(i64 8, i8* [[FOO]], double [[CONST:.*]]) // CHECK-NEXT: store i8* [[NEW]], i8** [[SAVED0]] // CHECK-NEXT: store i8* [[FOO]], i8** [[SAVED1]] // CHECK-NEXT: store i1 true, i1* [[CLEANUPACTIVE]] // CHECK-NEXT: [[CAST:%.*]] = bitcast i8* [[NEW]] to [[A]]* // CHECK-NEXT: invoke void @_ZN5test35makeAEv([[A]]* sret [[CAST]]) // CHECK: br label // -> cond.end new(foo(),10.0) A(makeA()) : // CHECK: [[MAKE:%.*]] = call [[A]]* @_ZN5test38makeAPtrEv() // CHECK: br label // -> cond.end makeAPtr()); // cond.end: // CHECK: [[RESULT:%.*]] = phi [[A]]* {{.*}}[[CAST]]{{.*}}[[MAKE]] // CHECK: ret [[A]]* [[RESULT]] // in the EH path: // CHECK: [[ISACTIVE:%.*]] = load i1* [[CLEANUPACTIVE]] // CHECK-NEXT: br i1 [[ISACTIVE]] // CHECK: [[V0:%.*]] = load i8** [[SAVED0]] // CHECK-NEXT: [[V1:%.*]] = load i8** [[SAVED1]] // CHECK-NEXT: invoke void @_ZN5test31AdlEPvS1_d(i8* [[V0]], i8* [[V1]], double [[CONST]]) } } namespace test4 { struct A { A(int); A(int, int); ~A(); void *p; void *operator new(size_t, void*, void*); void operator delete(void*, size_t, void*, void*); // not a match }; A *a() { // CHECK: define [[A:%.*]]* @_ZN5test41aEv() // CHECK: [[FOO:%.*]] = call i8* @_ZN5test43fooEv() // CHECK-NEXT: [[BAR:%.*]] = call i8* @_ZN5test43barEv() // CHECK-NEXT: [[NEW:%.*]] = call i8* @_ZN5test41AnwEmPvS1_(i64 8, i8* [[FOO]], i8* [[BAR]]) // CHECK-NEXT: [[CAST:%.*]] = bitcast i8* [[NEW]] to [[A]]* // CHECK-NEXT: call void @_ZN5test41AC1Ei([[A]]* [[CAST]], i32 5) // CHECK-NEXT: ret [[A]]* [[CAST]] extern void *foo(), *bar(); return new(foo(),bar()) A(5); } } // PR7908 namespace test5 { struct T { T(); ~T(); }; struct A { A(const A &x, const T &t = T()); ~A(); }; void foo(); // CHECK: define void @_ZN5test54testEv() // CHECK: [[EXNSLOT:%.*]] = alloca i8* // CHECK-NEXT: [[SELECTORSLOT:%.*]] = alloca i32 // CHECK-NEXT: [[A:%.*]] = alloca [[A_T:%.*]], align 1 // CHECK-NEXT: [[T:%.*]] = alloca [[T_T:%.*]], align 1 // CHECK-NEXT: invoke void @_ZN5test53fooEv() // CHECK: [[EXN:%.*]] = load i8** [[EXNSLOT]] // CHECK-NEXT: [[ADJ:%.*]] = call i8* @__cxa_get_exception_ptr(i8* [[EXN]]) // CHECK-NEXT: [[SRC:%.*]] = bitcast i8* [[ADJ]] to [[A_T]]* // CHECK-NEXT: invoke void @_ZN5test51TC1Ev([[T_T]]* [[T]]) // CHECK: invoke void @_ZN5test51AC1ERKS0_RKNS_1TE([[A_T]]* [[A]], [[A_T]]* [[SRC]], [[T_T]]* [[T]]) // CHECK: invoke void @_ZN5test51TD1Ev([[T_T]]* [[T]]) // CHECK: call i8* @__cxa_begin_catch(i8* [[EXN]]) [[NUW]] // CHECK-NEXT: invoke void @_ZN5test51AD1Ev([[A_T]]* [[A]]) // CHECK: call void @__cxa_end_catch() void test() { try { foo(); } catch (A a) { } } } // PR9303: invalid assert on this namespace test6 { bool cond(); void test() { try { lbl: if (cond()) goto lbl; } catch (...) { } } } // PR9298 namespace test7 { struct A { A(); ~A(); }; struct B { // The throw() operator means that a bad allocation is signalled // with a null return, which means that the initializer is // evaluated conditionally. static void *operator new(size_t size) throw(); B(const A&, B*); ~B(); }; B *test() { // CHECK: define [[B:%.*]]* @_ZN5test74testEv() // CHECK: [[OUTER_NEW:%.*]] = alloca i1 // CHECK-NEXT: alloca [[A:%.*]], // CHECK-NEXT: alloca i8* // CHECK-NEXT: alloca i32 // CHECK-NEXT: [[OUTER_A:%.*]] = alloca i1 // CHECK-NEXT: alloca i8* // CHECK-NEXT: [[INNER_NEW:%.*]] = alloca i1 // CHECK-NEXT: alloca [[A]] // CHECK-NEXT: [[INNER_A:%.*]] = alloca i1 // Allocate the outer object. // CHECK-NEXT: [[NEW:%.*]] = call i8* @_ZN5test71BnwEm( // CHECK-NEXT: icmp eq i8* [[NEW]], null // These stores, emitted before the outermost conditional branch, // deactivate the temporary cleanups. // CHECK-NEXT: store i1 false, i1* [[OUTER_NEW]] // CHECK-NEXT: store i1 false, i1* [[OUTER_A]] // CHECK-NEXT: store i1 false, i1* [[INNER_NEW]] // CHECK-NEXT: store i1 false, i1* [[INNER_A]] // CHECK-NEXT: br i1 // We passed the first null check; activate that cleanup and continue. // CHECK: store i1 true, i1* [[OUTER_NEW]] // CHECK-NEXT: bitcast // Create the first A temporary and activate that cleanup. // CHECK-NEXT: invoke void @_ZN5test71AC1Ev( // CHECK: store i1 true, i1* [[OUTER_A]] // Allocate the inner object. // CHECK-NEXT: [[NEW:%.*]] = call i8* @_ZN5test71BnwEm( // CHECK-NEXT: icmp eq i8* [[NEW]], null // CHECK-NEXT: br i1 // We passed the second null check; save that pointer, activate // that cleanup, and continue. // CHECK: store i8* [[NEW]] // CHECK-NEXT: store i1 true, i1* [[INNER_NEW]] // CHECK-NEXT: bitcast // Build the second A temporary and activate that cleanup. // CHECK-NEXT: invoke void @_ZN5test71AC1Ev( // CHECK: store i1 true, i1* [[INNER_A]] // Build the inner B object and deactivate the inner delete cleanup. // CHECK-NEXT: invoke void @_ZN5test71BC1ERKNS_1AEPS0_( // CHECK: store i1 false, i1* [[INNER_NEW]] // CHECK: phi // Build the outer B object and deactivate the outer delete cleanup. // CHECK-NEXT: invoke void @_ZN5test71BC1ERKNS_1AEPS0_( // CHECK: store i1 false, i1* [[OUTER_NEW]] // CHECK: phi // CHECK-NEXT: store [[B]]* // Destroy the inner A object. // CHECK-NEXT: load i1* [[INNER_A]] // CHECK-NEXT: br i1 // CHECK: invoke void @_ZN5test71AD1Ev( // Destroy the outer A object. // CHECK: load i1* [[OUTER_A]] // CHECK-NEXT: br i1 // CHECK: invoke void @_ZN5test71AD1Ev( return new B(A(), new B(A(), 0)); } } // Just don't crash. namespace test8 { struct A { // Having both of these is required to trigger the assert we're // trying to avoid. A(const A&); A&operator=(const A&); ~A(); }; A makeA(); void test() { throw makeA(); } // CHECK: define void @_ZN5test84testEv } // Make sure we generate the correct code for the delete[] call which // happens if A::A() throws. (We were previously calling delete[] on // a pointer to the first array element, not the pointer returned by new[].) // PR10870 namespace test9 { struct A { A(); ~A(); }; A* test() { return new A[10]; } // CHECK: define {{%.*}}* @_ZN5test94testEv // CHECK: [[TEST9_NEW:%.*]] = call noalias i8* @_Znam // CHECK: call void @_ZdaPv(i8* [[TEST9_NEW]]) } // In a destructor with a function-try-block, a return statement in a // catch handler behaves differently from running off the end of the // catch handler. PR13102. namespace test10 { extern void cleanup(); extern bool suppress; struct A { ~A(); }; A::~A() try { cleanup(); } catch (...) { return; } // CHECK: define void @_ZN6test101AD1Ev( // CHECK: invoke void @_ZN6test107cleanupEv() // CHECK-NOT: rethrow // CHECK: ret void struct B { ~B(); }; B::~B() try { cleanup(); } catch (...) {} // CHECK: define void @_ZN6test101BD1Ev( // CHECK: invoke void @_ZN6test107cleanupEv() // CHECK: call i8* @__cxa_begin_catch // CHECK-NEXT: invoke void @__cxa_rethrow() // CHECK: unreachable struct C { ~C(); }; C::~C() try { cleanup(); } catch (...) { if (suppress) return; } // CHECK: define void @_ZN6test101CD1Ev( // CHECK: invoke void @_ZN6test107cleanupEv() // CHECK: call i8* @__cxa_begin_catch // CHECK-NEXT: load i8* @_ZN6test108suppressE, align 1 // CHECK-NEXT: trunc // CHECK-NEXT: br i1 // CHECK: call void @__cxa_end_catch() // CHECK-NEXT: br label // CHECK: invoke void @__cxa_rethrow() // CHECK: unreachable } // Ensure that an exception in a constructor destroys // already-constructed array members. PR14514 namespace test11 { struct A { A(); ~A() {} }; struct C { A single; A array[2][3]; C(); }; C::C() { throw 0; } // CHECK: define void @_ZN6test111CC2Ev( // CHECK: [[THIS:%.*]] = load [[C:%.*]]** {{%.*}} // Construct single. // CHECK-NEXT: [[SINGLE:%.*]] = getelementptr inbounds [[C]]* [[THIS]], i32 0, i32 0 // CHECK-NEXT: call void @_ZN6test111AC1Ev([[A:%.*]]* [[SINGLE]]) // Construct array. // CHECK-NEXT: [[ARRAY:%.*]] = getelementptr inbounds [[C]]* [[THIS]], i32 0, i32 1 // CHECK-NEXT: [[ARRAYBEGIN:%.*]] = getelementptr inbounds [2 x [3 x [[A]]]]* [[ARRAY]], i32 0, i32 0, i32 0 // CHECK-NEXT: [[ARRAYEND:%.*]] = getelementptr inbounds [[A]]* [[ARRAYBEGIN]], i64 6 // CHECK-NEXT: br label // CHECK: [[CUR:%.*]] = phi [[A]]* [ [[ARRAYBEGIN]], {{%.*}} ], [ [[NEXT:%.*]], {{%.*}} ] // CHECK-NEXT: invoke void @_ZN6test111AC1Ev([[A:%.*]]* [[CUR]]) // CHECK: [[NEXT]] = getelementptr inbounds [[A]]* [[CUR]], i64 1 // CHECK-NEXT: [[DONE:%.*]] = icmp eq [[A]]* [[NEXT]], [[ARRAYEND]] // CHECK-NEXT: br i1 [[DONE]], // throw 0; // CHECK: invoke void @__cxa_throw( // Landing pad 1, from constructor in array-initialization loop: // CHECK: landingpad // - First, destroy already-constructed bits of array. // CHECK: [[EMPTY:%.*]] = icmp eq [[A]]* [[ARRAYBEGIN]], [[CUR]] // CHECK-NEXT: br i1 [[EMPTY]] // CHECK: [[AFTER:%.*]] = phi [[A]]* [ [[CUR]], {{%.*}} ], [ [[ELT:%.*]], {{%.*}} ] // CHECK-NEXT: [[ELT]] = getelementptr inbounds [[A]]* [[AFTER]], i64 -1 // CHECK-NEXT: invoke void @_ZN6test111AD1Ev([[A]]* [[ELT]]) // CHECK: [[DONE:%.*]] = icmp eq [[A]]* [[ELT]], [[ARRAYBEGIN]] // CHECK-NEXT: br i1 [[DONE]], // - Next, chain to cleanup for single. // CHECK: br label // Landing pad 2, from throw site. // CHECK: landingpad // - First, destroy all of array. // CHECK: [[ARRAYBEGIN:%.*]] = getelementptr inbounds [2 x [3 x [[A]]]]* [[ARRAY]], i32 0, i32 0, i32 0 // CHECK-NEXT: [[ARRAYEND:%.*]] = getelementptr inbounds [[A]]* [[ARRAYBEGIN]], i64 6 // CHECK-NEXT: br label // CHECK: [[AFTER:%.*]] = phi [[A]]* [ [[ARRAYEND]], {{%.*}} ], [ [[ELT:%.*]], {{%.*}} ] // CHECK-NEXT: [[ELT]] = getelementptr inbounds [[A]]* [[AFTER]], i64 -1 // CHECK-NEXT: invoke void @_ZN6test111AD1Ev([[A]]* [[ELT]]) // CHECK: [[DONE:%.*]] = icmp eq [[A]]* [[ELT]], [[ARRAYBEGIN]] // CHECK-NEXT: br i1 [[DONE]], // - Next, chain to cleanup for single. // CHECK: br label // Finally, the cleanup for single. // CHECK: invoke void @_ZN6test111AD1Ev([[A]]* [[SINGLE]]) // CHECK: br label // CHECK: resume // (After this is a terminate landingpad.) } // CHECK: attributes [[NI_NR_NUW]] = { noinline noreturn nounwind }
dbrumley/recfi
llvm-3.3/tools/clang/test/CodeGenCXX/exceptions.cpp
C++
mit
18,915
[ 30522, 1013, 1013, 2448, 1024, 1003, 6338, 2290, 1035, 10507, 2487, 1003, 1055, 1011, 6420, 1027, 1060, 20842, 1035, 4185, 1011, 6207, 1011, 11534, 10790, 1011, 12495, 2102, 1011, 2222, 2615, 2213, 1011, 1051, 1011, 1011, 4429, 20348, 1011,...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functional tests for Stack and ParallelStack Ops.""" import numpy as np from tensorflow.python import tf2 from tensorflow.python.eager import context from tensorflow.python.eager import def_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_array_ops from tensorflow.python.ops import gradient_checker_v2 from tensorflow.python.platform import test def np_split_squeeze(array, axis): axis_len = array.shape[axis] return [ np.squeeze( arr, axis=(axis,)) for arr in np.split( array, axis_len, axis=axis) ] class StackOpTest(test.TestCase): def randn(self, shape, dtype): data = np.random.randn(*shape) if dtype == np.bool_: return data < 0 # Naive casting yields True with P(1)! else: return data.astype(dtype) def testSimple(self): np.random.seed(7) for shape in (2,), (3,), (2, 3), (3, 2), (8, 2, 10): rank = len(shape) for axis in range(-rank, rank): for dtype in [np.bool_, np.float32, np.int32, np.int64]: data = self.randn(shape, dtype) xs = np_split_squeeze(data, axis) # Stack back into a single tensorflow tensor with self.subTest(shape=shape, axis=axis, dtype=dtype): c = array_ops.stack(xs, axis=axis) self.assertAllEqual(c, data) def testSimpleParallelCPU(self): # tf.parallel_stack is only supported in graph mode. with ops.Graph().as_default(): np.random.seed(7) with test_util.device(use_gpu=False): for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2), (100, 24, 24, 3): with self.subTest(shape=shape): data = self.randn(shape, np.float32) xs = list(map(constant_op.constant, data)) c = array_ops.parallel_stack(xs) self.assertAllEqual(c, data) def testParallelConcatShapeZero(self): if not tf2.enabled(): self.skipTest("only fails in TF2") @def_function.function def f(): y = gen_array_ops.parallel_concat(values=[["tf"]], shape=0) return y with self.assertRaisesRegex(errors.InvalidArgumentError, r"0th dimension of value .* is less than"): f() def testSimpleParallelGPU(self): # tf.parallel_stack is only supported in graph mode. with ops.Graph().as_default(): with test_util.device(use_gpu=True): for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2), (100, 24, 24, 3): with self.subTest(shape=shape): data = self.randn(shape, np.float32) xs = list(map(constant_op.constant, data)) c = array_ops.parallel_stack(xs) self.assertAllEqual(c, data) def testConst(self): np.random.seed(7) with test_util.use_gpu(): # Verify that shape induction works with shapes produced via const stack a = constant_op.constant([1, 2, 3, 4, 5, 6]) b = array_ops.reshape(a, array_ops.stack([2, 3])) self.assertAllEqual(b.get_shape(), [2, 3]) # Check on a variety of shapes and types for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2), (8, 2, 10): for dtype in [np.bool_, np.float32, np.int16, np.int32, np.int64]: with self.subTest(shape=shape, dtype=dtype): data = self.randn(shape, dtype) # Stack back into a single tensorflow tensor directly using np array c = array_ops.stack(data) if not context.executing_eagerly(): # This is implemented via a Const: self.assertEqual(c.op.type, "Const") self.assertAllEqual(c, data) # Python lists also work for 1-D case: if len(shape) == 1: data_list = list(data) cl = array_ops.stack(data_list) if not context.executing_eagerly(): self.assertEqual(cl.op.type, "Const") self.assertAllEqual(cl, data) def testConstParallelCPU(self): # tf.parallel_stack is only supported in graph mode. with ops.Graph().as_default(): np.random.seed(7) with test_util.device(use_gpu=False): for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2), (8, 2, 10): with self.subTest(shape=shape): data = self.randn(shape, np.float32) if len(shape) == 1: data_list = list(data) cl = array_ops.parallel_stack(data_list) self.assertAllEqual(cl, data) data = self.randn(shape, np.float32) c = array_ops.parallel_stack(data) self.assertAllEqual(c, data) def testConstParallelGPU(self): # tf.parallel_stack is only supported in graph mode. with ops.Graph().as_default(): np.random.seed(7) with test_util.device(use_gpu=True): for shape in (2,), (3,), (2, 3), (3, 2), (4, 3, 2): with self.subTest(shape=shape): data = self.randn(shape, np.float32) if len(shape) == 1: data_list = list(data) cl = array_ops.parallel_stack(data_list) self.assertAllEqual(cl, data) data = self.randn(shape, np.float32) c = array_ops.parallel_stack(data) self.assertAllEqual(c, data) def testGradientsAxis0(self): np.random.seed(7) for shape in (2,), (3,), (2, 3), (3, 2), (8, 2, 10): data = np.random.randn(*shape) with self.subTest(shape=shape): with self.cached_session(): def func(*xs): return array_ops.stack(xs) # TODO(irving): Remove list() once we handle maps correctly xs = list(map(constant_op.constant, data)) theoretical, numerical = gradient_checker_v2.compute_gradient( func, xs) self.assertAllClose(theoretical, numerical) def testGradientsAxis1(self): np.random.seed(7) for shape in (2, 3), (3, 2), (8, 2, 10): data = np.random.randn(*shape) out_shape = list(shape[1:]) out_shape.insert(1, shape[0]) with self.subTest(shape=shape): with self.cached_session(): def func(*inp): return array_ops.stack(inp, axis=1) # TODO(irving): Remove list() once we handle maps correctly xs = list(map(constant_op.constant, data)) theoretical, numerical = gradient_checker_v2.compute_gradient( func, xs) self.assertAllClose(theoretical, numerical) def testZeroSizeCPU(self): # tf.parallel_stack is only supported in graph mode. with ops.Graph().as_default(): # Verify that stack doesn't crash for zero size inputs with test_util.device(use_gpu=False): for shape in (0,), (3, 0), (0, 3): with self.subTest(shape=shape): x = np.zeros((2,) + shape).astype(np.int32) p = self.evaluate(array_ops.stack(list(x))) self.assertAllEqual(p, x) p = self.evaluate(array_ops.parallel_stack(list(x))) self.assertAllEqual(p, x) def testZeroSizeGPU(self): # tf.parallel_stack is only supported in graph mode. with ops.Graph().as_default(): # Verify that stack doesn't crash for zero size inputs with test_util.device(use_gpu=True): for shape in (0,), (3, 0), (0, 3): with self.subTest(shape=shape): x = np.zeros((2,) + shape).astype(np.int32) p = self.evaluate(array_ops.stack(list(x))) self.assertAllEqual(p, x) p = self.evaluate(array_ops.parallel_stack(list(x))) self.assertAllEqual(p, x) def testAxis0DefaultCPU(self): # tf.parallel_stack is only supported in graph mode. with ops.Graph().as_default(): with test_util.device(use_gpu=False): t = [constant_op.constant([1, 2, 3]), constant_op.constant([4, 5, 6])] stacked = self.evaluate(array_ops.stack(t)) parallel_stacked = self.evaluate(array_ops.parallel_stack(t)) expected = np.array([[1, 2, 3], [4, 5, 6]]) self.assertAllEqual(stacked, expected) self.assertAllEqual(parallel_stacked, expected) def testAxis0DefaultGPU(self): # tf.parallel_stack is only supported in graph mode. with ops.Graph().as_default(): with test_util.device(use_gpu=True): t = [constant_op.constant([1, 2, 3]), constant_op.constant([4, 5, 6])] stacked = self.evaluate(array_ops.stack(t)) parallel_stacked = self.evaluate(array_ops.parallel_stack(t)) expected = np.array([[1, 2, 3], [4, 5, 6]]) self.assertAllEqual(stacked, expected) self.assertAllEqual(parallel_stacked, expected) def testAgainstNumpy(self): # For 1 to 5 dimensions. for shape in (3,), (2, 2, 3), (4, 1, 2, 2), (8, 2, 10): rank = len(shape) expected = self.randn(shape, np.float32) for dtype in [np.bool_, np.float32, np.int32, np.int64]: # For all the possible axis to split it, including negative indices. for axis in range(-rank, rank): test_arrays = np_split_squeeze(expected, axis) with self.cached_session(): with self.subTest(shape=shape, dtype=dtype, axis=axis): actual_pack = array_ops.stack(test_arrays, axis=axis) self.assertEqual(expected.shape, actual_pack.get_shape()) actual_pack = self.evaluate(actual_pack) actual_stack = array_ops.stack(test_arrays, axis=axis) self.assertEqual(expected.shape, actual_stack.get_shape()) actual_stack = self.evaluate(actual_stack) self.assertNDArrayNear(expected, actual_stack, 1e-6) def testDimOutOfRange(self): t = [constant_op.constant([1, 2, 3]), constant_op.constant([4, 5, 6])] with self.assertRaisesRegex(ValueError, r"Argument `axis` = 2 not in range \[-2, 2\)"): array_ops.stack(t, axis=2) def testDimOutOfNegativeRange(self): t = [constant_op.constant([1, 2, 3]), constant_op.constant([4, 5, 6])] with self.assertRaisesRegex(ValueError, r"Argument `axis` = -3 not in range \[-2, 2\)"): array_ops.stack(t, axis=-3) def testComplex(self): np.random.seed(7) with self.session(): for shape in (2,), (3,), (2, 3), (3, 2), (8, 2, 10): for dtype in [np.complex64, np.complex128]: with self.subTest(shape=shape, dtype=dtype): data = self.randn(shape, dtype) xs = list(map(constant_op.constant, data)) c = array_ops.stack(xs) self.assertAllEqual(self.evaluate(c), data) class AutomaticStackingTest(test.TestCase): def testSimple(self): self.assertAllEqual([1, 0, 2], ops.convert_to_tensor([1, constant_op.constant(0), 2])) self.assertAllEqual([[0, 0, 0], [0, 1, 0], [0, 0, 0]], ops.convert_to_tensor([[0, 0, 0], [0, constant_op.constant(1), 0], [0, 0, 0]])) self.assertAllEqual([[0, 0, 0], [0, 1, 0], [0, 0, 0]], ops.convert_to_tensor([[0, 0, 0], constant_op.constant([0, 1, 0]), [0, 0, 0]])) self.assertAllEqual([[0, 0, 0], [0, 1, 0], [0, 0, 0]], ops.convert_to_tensor([ constant_op.constant([0, 0, 0]), constant_op.constant([0, 1, 0]), constant_op.constant([0, 0, 0]) ])) def testWithNDArray(self): with self.session(): result = ops.convert_to_tensor([[[0., 0.], constant_op.constant([1., 1.])], np.array( [[2., 2.], [3., 3.]], dtype=np.float32)]) self.assertAllEqual([[[0., 0.], [1., 1.]], [[2., 2.], [3., 3.]]], self.evaluate(result)) def testDtype(self): t_0 = ops.convert_to_tensor([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]) self.assertEqual(dtypes.float32, t_0.dtype) t_1 = ops.convert_to_tensor([[0., 0., 0.], constant_op.constant( [0., 0., 0.], dtype=dtypes.float64), [0., 0., 0.]]) self.assertEqual(dtypes.float64, t_1.dtype) t_2 = ops.convert_to_tensor( [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]], dtype=dtypes.float64) self.assertEqual(dtypes.float64, t_2.dtype) t_3 = ops.convert_to_tensor( [[0., 0., 0.], constant_op.constant([0., 0., 0.], dtype=dtypes.float64), [0., 0., 0.] ], dtype=dtypes.float32) self.assertEqual(dtypes.float32, t_3.dtype) t_4 = ops.convert_to_tensor( [constant_op.constant([0., 0., 0.], dtype=dtypes.float64)], dtype=dtypes.float32) self.assertEqual(dtypes.float32, t_4.dtype) with self.assertRaises(TypeError): ops.convert_to_tensor([ constant_op.constant( [0., 0., 0.], dtype=dtypes.float32), constant_op.constant( [0., 0., 0.], dtype=dtypes.float64), [0., 0., 0.] ]) def testDtypeConversionWhenTensorDtypeMismatch(self): t_0 = ops.convert_to_tensor([0., 0., 0.]) self.assertEqual(dtypes.float32, t_0.dtype) t_1 = ops.convert_to_tensor([0, 0, 0]) self.assertEqual(dtypes.int32, t_1.dtype) t_2 = ops.convert_to_tensor([t_0, t_0, t_1], dtype=dtypes.float64) self.assertEqual(dtypes.float64, t_2.dtype) if __name__ == "__main__": test.main()
Intel-Corporation/tensorflow
tensorflow/python/kernel_tests/array_ops/stack_op_test.py
Python
apache-2.0
14,594
[ 30522, 1001, 9385, 2325, 1996, 23435, 12314, 6048, 1012, 2035, 2916, 9235, 1012, 1001, 1001, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1001, 2017, 2089, 2025, 2224, 2023, 5371, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
dofile(minetest.get_modpath(minetest.get_current_modname()).."/zcg.lua") dofile(minetest.get_modpath(minetest.get_current_modname()).."/cooking.lua") dofile(minetest.get_modpath(minetest.get_current_modname()).."/protection.lua") dofile(minetest.get_modpath(minetest.get_current_modname()).."/master.lua") --Inventory Plus inventory_plus = {} inventory_plus.set_inventory_formspec = function(player, formspec) minetest.show_formspec(player:get_player_name(), "custom", formspec) end minetest.register_on_player_receive_fields(function(player,formname,fields) if fields.main then local name = player:get_player_name() local formspec_armor = armor:get_armor_formspec(name) if formspec_armor ~= nil then minetest.show_formspec(player:get_player_name(), "armor", formspec_armor) end end end) --book minetest.register_craft({ output = 'encyclopedia:crafts_book', recipe = { {'group:stick', 'group:stick', 'group:stick'}, {'group:stick', 'default:book', 'group:stick'}, {'group:stick', 'group:stick', 'group:stick'}, } }) minetest.register_craft({ output = 'encyclopedia:cooking_book', recipe = { {'default:coal_lump', 'default:coal_lump', 'default:coal_lump'}, {'default:coal_lump', 'default:book', 'default:coal_lump'}, {'default:coal_lump', 'default:coal_lump', 'default:coal_lump'}, } }) minetest.register_craft({ output = 'encyclopedia:protection_book', recipe = { {'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'}, {'default:steel_ingot', 'encyclopedia:crafts_book', 'default:steel_ingot'}, {'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'}, } }) minetest.register_craft({ output = 'encyclopedia:master_book', recipe = { {'encyclopedia:cooking_book', '', ''}, {'encyclopedia:protection_book', '', ''}, {'encyclopedia:crafts_book', '', ''}, } })
KasBrick/encyclopedia
init.lua
Lua
lgpl-2.1
1,843
[ 30522, 2079, 8873, 2571, 1006, 3067, 22199, 1012, 2131, 1035, 16913, 15069, 1006, 3067, 22199, 1012, 2131, 1035, 2783, 1035, 16913, 18442, 1006, 1007, 1007, 1012, 1012, 1000, 1013, 1062, 2278, 2290, 1012, 11320, 2050, 1000, 1007, 2079, 8873...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Canvas.v1.Managers; using Canvas.v1.Models; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Canvas.v1.Test.Managers { [TestClass] public class AccountsManagerTests : ResourceManagerTest { private readonly AccountsManager _accountsManager; public AccountsManagerTests() { _accountsManager = new AccountsManager(_config.Object, _service, _converter, _authRepository); } [TestMethod] public async Task GetAllAccounts() { const string content = @"[{""id"":1234,""name"":""Indiana University"",""parent_account_id"":null,""root_account_id"":null,""workflow_state"":""active"",""default_storage_quota_mb"":500,""default_user_storage_quota_mb"":100,""default_group_storage_quota_mb"":300,""default_time_zone"":""America/New_York""}]"; ArrangeSuccessfulResponse<IEnumerable<Account>>(content); var accounts = await _accountsManager.GetAll(); Assert.AreEqual(accounts.Count(), 1); Account account = accounts.Single(); Assert.AreEqual(account.Id, 1234); Assert.AreEqual(account.Name, "Indiana University"); Assert.AreEqual(account.ParentAccountId, null); Assert.AreEqual(account.RootAccountId, null); Assert.AreEqual(account.WorkflowState, AccountWorkflowState.Active); Assert.AreEqual(account.DefaultStorageQuotaMB, 500); Assert.AreEqual(account.DefaultUserStorageQuotaMB, 100); Assert.AreEqual(account.DefaultGroupStorageQuotaMB, 300); Assert.AreEqual(account.DefaultTimeZone, "America/New_York"); } [TestMethod] public async Task GetAllCourses() { const string content = @"[{""account_id"":1,""root_account_id"":8765,""course_code"":""VID DEMO 101"",""default_view"":""feed"",""id"":5678,""name"":""Video Demo"",""start_at"":""2014-03-27T00:00:00Z"",""end_at"":""2014-04-27T00:00:00Z"",""public_syllabus"":true,""storage_quota_mb"":500,""apply_assignment_group_weights"":true,""calendar"":{""ics"":""https://iu.test.instructure.com/feeds/calendars/course_abcd.ics""},""sis_course_id"":""SIS Course ID"",""integration_id"":""Integration ID"",""hide_final_grades"":true,""workflow_state"":""available""}]"; ArrangeSuccessfulResponse<IEnumerable<Course>>(content); var courses = await _accountsManager.GetCourses(1); Assert.AreEqual(courses.Count(), 1); var course = courses.Single(); Assert.AreEqual(course.Id, 5678); Assert.AreEqual(course.AccountId, 1); Assert.AreEqual(course.RootAccountId, 8765); Assert.AreEqual(course.IntegrationId, "Integration ID"); Assert.AreEqual(course.SisCourseId, "SIS Course ID"); Assert.AreEqual(course.Name, "Video Demo"); Assert.AreEqual(course.CourseCode, "VID DEMO 101"); Assert.AreEqual(course.WorkflowState, CourseWorkflowState.Available); Assert.AreEqual(course.ApplyAssignmentGroupWeights, true); Assert.AreEqual(course.HideFinalGrades, true); Assert.AreEqual(course.PublicSyllabus, true); Assert.AreEqual(course.StorageQuotaMB, 500); Assert.AreEqual(course.StartAt, new DateTime(2014, 3, 27)); Assert.AreEqual(course.EndAt, new DateTime(2014, 4, 27)); Assert.IsNotNull(course.Calendar); Assert.AreEqual(course.Calendar.Ics, "https://iu.test.instructure.com/feeds/calendars/course_abcd.ics"); } } }
unizin/canvas-windows-sdk-v1
Canvas.v1.Test/Managers/AccountsManagerTests.cs
C#
apache-2.0
3,705
[ 30522, 2478, 2291, 1025, 2478, 2291, 1012, 6407, 1012, 12391, 1025, 2478, 2291, 1012, 11409, 4160, 1025, 2478, 2291, 1012, 11689, 2075, 1012, 8518, 1025, 2478, 10683, 1012, 1058, 2487, 1012, 10489, 1025, 2478, 10683, 1012, 1058, 2487, 1012,...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
<!DOCTYPE html> <html> <head> <title>Punchcard demo</title> <link rel="stylesheet" href="punchcard.css"> <script type="text/javascript" src="punchcard.js"></script> <script type="text/javascript"> window.onload = function() { var data = { range: { min: 0, max: 20}, xAxis: ['2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015'], rows: [ { label: 'This is the first row', samples: [0,0,1,0,0,0,6,10,11,230]}, { label: 'This is the second row', samples: [0,0,0,0,1,0,3,4,17,10]}, { label: 'This is the third row', samples: [0,0,0,0,0,1,2,8,13,11]}, { label: 'This is the forth row', samples: [0,0,0,1,0,3,5,7,9,9]}, { label: 'This is the 5 row', samples: [0,0,1,0,0,0,6,10,11,23]}, { label: 'This is the 6 row', samples: [0,0,0,0,1,0,3,4,17,10]}, { label: 'This is the 7 row', samples: [0,0,0,0,0,1,2,8,13,11]}, { label: 'This is the 8 row very long description indeed', samples: [0,0,0,1,0,3,5,7,9,9]}, { label: 'This is the 9 row', samples: [0,0,1,0,0,0,6,10,11,23]}, { label: 'This is the 10 row', samples: [0,0,0,0,1,0,3,4,17,10]}, { label: 'This is the 11 row', samples: [0,0,0,0,0,1,2,8,13,11]}, { label: 'This is the 12 row ', samples: [0,0,0,1,0,3,5,7,9,9]}, { label: 'This is the 13 row', samples: [0,0,1,0,0,0,6,10,11,23]}, { label: 'This is the 14 row', samples: [0,0,0,0,1,0,3,4,17,10]}, { label: 'This is the 15 row', samples: [0,0,0,0,0,1,2,8,13,11]}, { label: 'This is the 16 row ', samples: [0,0,0,1,0,3,5,7,9,9]}, { label: 'This is the 17 row', samples: [0,0,1,0,0,0,6,10,11,23]}, { label: 'This is the 18 row', samples: [0,0,0,0,1,0,3,4,17,10]}, { label: 'This is the 19 row', samples: [0,0,0,0,0,1,2,8,13,11]}, { label: 'This is the 20 row ', samples: [0,0,0,1,0,3,5,7,9,9]}, ] }; var p = window.punchcard; p.init(); var node = p.generate(data); document.getElementById("graph").appendChild(node); }; </script> </head> <body> This this a punchcard demo! <div id="graph" class="punchcard"></div> </body> </html>
nbigot/punchcardjs
punchcard_demo.html
HTML
apache-2.0
2,034
[ 30522, 1026, 999, 9986, 13874, 16129, 1028, 1026, 16129, 1028, 1026, 2132, 1028, 1026, 2516, 1028, 8595, 11522, 9703, 1026, 1013, 2516, 1028, 1026, 4957, 2128, 2140, 1027, 1000, 6782, 21030, 2102, 1000, 17850, 12879, 1027, 1000, 8595, 11522...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <chrono> #include <memory> #include <string> #include <utility> #include "rclcpp/rclcpp.hpp" #include "test_communication/msg/u_int32.hpp" int main(int argc, char ** argv) { rclcpp::init(argc, argv); auto start = std::chrono::steady_clock::now(); auto node = rclcpp::Node::make_shared("test_subscription_valid_data"); auto callback = [](const test_communication::msg::UInt32::ConstSharedPtr received_message) -> void { printf("received message #%u\n", received_message->data); if (received_message->data == 0) { fprintf(stderr, "received message data was never sent\n"); rclcpp::shutdown(); throw std::runtime_error("received message data was never sent"); } }; auto subscriber = node->create_subscription<test_communication::msg::UInt32>( "test_subscription_valid_data", 10, callback); rclcpp::WallRate message_rate(5); { auto publisher = node->create_publisher<test_communication::msg::UInt32>( "test_subscription_valid_data", 10); message_rate.sleep(); uint32_t index = 1; // publish a few messages, all with data > 0 while (rclcpp::ok() && index <= 5) { printf("publishing message #%u\n", index); auto msg = std::make_unique<test_communication::msg::UInt32>(); msg->data = index; publisher->publish(std::move(msg)); ++index; message_rate.sleep(); rclcpp::spin_some(node); } message_rate.sleep(); rclcpp::spin_some(node); } // the publisher goes out of scope and the subscriber should be not receive any callbacks anymore message_rate.sleep(); rclcpp::spin_some(node); auto end = std::chrono::steady_clock::now(); std::chrono::duration<float> diff = (end - start); printf("published and subscribed for %f seconds\n", diff.count()); rclcpp::shutdown(); return 0; }
ros2/system_tests
test_communication/test/test_subscription_valid_data.cpp
C++
apache-2.0
2,474
[ 30522, 1013, 1013, 9385, 2325, 2330, 3120, 21331, 3192, 1010, 4297, 1012, 1013, 1013, 1013, 1013, 7000, 2104, 1996, 15895, 6105, 1010, 2544, 1016, 1012, 1014, 1006, 1996, 1000, 6105, 1000, 1007, 1025, 1013, 1013, 2017, 2089, 2025, 2224, 2...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/app'; ReactDOM.render(<App />, document.getElementById('main'));
jiaola/marc-editor
src/js/main.js
JavaScript
apache-2.0
158
[ 30522, 12324, 10509, 2013, 1005, 10509, 1005, 1025, 12324, 10509, 9527, 2013, 1005, 10509, 1011, 14383, 1005, 1025, 12324, 10439, 2013, 1005, 1012, 1013, 6177, 1013, 10439, 1005, 1025, 10509, 9527, 1012, 17552, 1006, 1026, 10439, 1013, 1028, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
{%- assign _author = site.data.authors[include.article.author] | default: site.author -%} {%- if include.html != false -%} {%- include snippets/assign.html target=site.data.variables.default.page.show_date source0=layout.show_date source1=include.article.show_date -%} {%- assign _show_date = __return -%} {%- if _show_date and include.article.date -%} {%- assign _show_date = true -%} {%- else -%} {%- assign _show_date = false -%} {%- endif -%} {%- assign _show_author = include.article.author -%} {%- include snippets/assign.html target=site.data.variables.default.page.pageview source0=layout.pageview source1=page.pageview -%} {%- assign _pageview = __return -%} {%- if _pageview or include.show_pageview -%} {%- assign _pageview = true -%} {%- else -%} {%- assign _pageview = false -%} {%- endif -%} {%- assign _paths_archive = site.paths.archive | default: site.data.variables.default.paths.archive -%} {%- if _show_tags or _show_author or _show_date or _pageview -%} <div class="article__info clearfix"> {%- if _show_author or _show_date or _pageview -%} <ul class="right-col menu"> {%- if _show_author -%} <li><i class="far fa-user"></i> <span>{{ page.author }}</span></li> {%- endif -%} {%- if _show_date -%} <li> {%- include snippets/get-locale-string.html key='ARTICLE_DATE_FORMAT' -%} <i class="far fa-calendar-alt"></i> <span>{{ include.article.date | date: __return }}</span> </li> {%- endif -%} {%- if _pageview -%} {%- if site.pageview.provider -%} {%- include snippets/get-locale-string.html key='VIEWS' -%} {%- assign _locale_views = __return -%} <li><i class="far fa-eye"></i> <span class="js-pageview" data-page-key="{{ include.article.key }}">0</span> {{ _locale_views }}</li> {%- endif -%} {%- endif -%} </ul> {%- endif -%} </div> {%- endif -%} {%- endif -%} {%- if include.semantic != false -%} {%- if _author -%} <meta itemprop="author" content="{{ _author.name }}"/> {%- endif -%} {%- if include.article.date -%} <meta itemprop="datePublished" content="{{ include.article.date | date_to_xmlschema }}"> {%- endif -%} {%- endif -%}
JohnSnowLabs/spark-nlp
docs/_includes/article-info-author.html
HTML
apache-2.0
2,369
[ 30522, 1063, 1003, 1011, 23911, 1035, 3166, 1027, 2609, 1012, 2951, 1012, 6048, 1031, 2421, 1012, 3720, 1012, 3166, 1033, 1064, 12398, 1024, 2609, 1012, 3166, 1011, 1003, 1065, 1063, 1003, 1011, 2065, 2421, 1012, 16129, 999, 1027, 6270, 1...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
{% extends "reddit/base.html" %} {% block title %}Canal {{channel.name}}{% endblock %} {% block content %} <h2>#{{channel.slug}}</h2> <ul> {% for announce in announces %} <li> <span style="color: red;"><b>[Anuncio]</b></span> <a href="{% url 'channel' channel.slug %}comments/{{announce.uuid}}/{{announce.title|slugify}}/">{{ announce.title }}</a> </li> {% endfor %} {% for question in questions %} <li> {% if not question.announce and question.solved%} <span style="color: orange;"><b>(Solucionada)</b></span> {% else %} <span style="color: green;"><b>({{question.get_label_display}})</b></span> {% endif %} <a href="{% url 'channel' channel.slug %}comments/{{question.uuid}}/{{question.title|slugify}}/">{{ question.title }}</a> </li> {% endfor %} </ul> {% if user.is_authenticated %} <p> Hola {{user}},<br> <a href="./comment/">Crear una pregunta en {{channel.name}}</a> </p> {% endif %} <a href="/r/">Volver</a> {% endblock %}
hcosta/escueladevideojuegos.net-backend-django
edv/reddit/templates/reddit/channel.html
HTML
gpl-3.0
1,009
[ 30522, 1063, 1003, 8908, 1000, 2417, 23194, 1013, 2918, 1012, 16129, 1000, 1003, 1065, 1063, 1003, 3796, 2516, 1003, 1065, 5033, 1063, 1063, 3149, 1012, 2171, 1065, 1065, 1063, 1003, 2203, 23467, 1003, 1065, 1063, 1003, 3796, 4180, 1003, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
/*! * Module dependencies. */ var util = require('util'), moment = require('moment'), super_ = require('../Type'); /** * Date FieldType Constructor * @extends Field * @api public */ function datearray(list, path, options) { this._nativeType = [Date]; this._defaultSize = 'medium'; this._underscoreMethods = ['format']; this._properties = ['formatString']; this.parseFormatString = options.parseFormat || 'YYYY-MM-DD'; this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY'); if (this.formatString && 'string' !== typeof this.formatString) { throw new Error('FieldType.Date: options.format must be a string.'); } datearray.super_.call(this, list, path, options); } /*! * Inherit from Field */ util.inherits(datearray, super_); /** * Formats the field value * * @api public */ datearray.prototype.format = function(item, format) { if (format || this.formatString) { return item.get(this.path) ? moment(item.get(this.path)).format(format || this.formatString) : ''; } else { return item.get(this.path) || ''; } }; /** * Checks that a valid array of dates has been provided in a data object * * An empty value clears the stored value and is considered valid * * @api public */ datearray.prototype.inputIsValid = function(data, required, item) { var value = this.getValueFromData(data); var parseFormatString = this.parseFormatString; if ('string' === typeof value) { if (!moment(value, parseFormatString).isValid()) { return false; } value = [value]; } if (required) { if (value === undefined && item && item.get(this.path) && item.get(this.path).length) { return true; } if (value === undefined || !Array.isArray(value)) { return false; } if (Array.isArray(value) && !value.length) { return false; } } if (Array.isArray(value)) { // filter out empty fields value = value.filter(function(date) { return date.trim() !== ''; }); // if there are no values left, and requried is true, return false if (required && !value.length) { return false; } // if any date in the array is invalid, return false if (value.some(function (dateValue) { return !moment(dateValue, parseFormatString).isValid(); })) { return false; } } return (value === undefined || Array.isArray(value)); }; /** * Updates the value for this field in the item from a data object * * @api public */ datearray.prototype.updateItem = function(item, data, callback) { var value = this.getValueFromData(data); if (value !== undefined) { if (Array.isArray(value)) { // Only save valid dates value = value.filter(function(date) { return moment(date).isValid(); }); } if (value === null) { value = []; } if ('string' === typeof value) { if (moment(value).isValid()) { value = [value]; } } if (Array.isArray(value)) { item.set(this.path, value); } } else item.set(this.path, []); process.nextTick(callback); }; /*! * Export class */ module.exports = datearray;
riyadhalnur/keystone
fields/types/datearray/DateArrayType.js
JavaScript
mit
3,038
[ 30522, 1013, 1008, 999, 1008, 11336, 12530, 15266, 1012, 1008, 1013, 13075, 21183, 4014, 1027, 5478, 1006, 1005, 21183, 4014, 1005, 1007, 1010, 2617, 1027, 5478, 1006, 1005, 2617, 1005, 1007, 1010, 3565, 1035, 1027, 5478, 1006, 1005, 1012, ...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...
import {MatSelectModule} from '@angular/material/select'; import {MatSelectHarness} from './select-harness'; import {runHarnessTests} from './shared.spec'; describe('Non-MDC-based MatSelectHarness', () => { runHarnessTests(MatSelectModule, MatSelectHarness); });
Jefiozie/material2
src/material/select/testing/select-harness.spec.ts
TypeScript
mit
266
[ 30522, 12324, 1063, 22281, 12260, 6593, 5302, 8566, 2571, 1065, 2013, 1005, 1030, 16108, 1013, 3430, 1013, 7276, 1005, 1025, 12324, 1063, 22281, 30524, 4207, 1012, 28699, 1005, 1025, 6235, 1006, 1005, 2512, 1011, 9108, 2278, 1011, 2241, 222...
[ 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1...
[ -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100...