text
stringlengths
2
100k
meta
dict
# CVS $Revision$ $Author$ -- Mon Nov 10 23:40:38 2008 -- reformated by prettylst.pl v1.38 (build 8180) # # Spycraft PCGen dataset by Eddy Anthony # SOURCELONG:AEG Spycraft SOURCESHORT:Spycraft SOURCEWEB:http://www.crafty-games.com/product_catalog/spycraftfirsted SOURCEDATE:2003-01 # Personal Vehicles ---------------------------- # Equipment Name Type Contains Cost Size Source Page Modify VAR ATC (3-wheeler) TYPE:Vehicle.Personal.Standard.Container CONTAINS:*UNLIM COST:2 SIZE:M SOURCEPAGE:p.147 BONUS:VAR|VEHICLESPEED|150 BONUS:VAR|VEHICLEDEFENSE|15 BONUS:VAR|VEHICLEHANDLING|5 BONUS:VAR|VEHICLEWOUNDPOINTS|20 BONUS:VAR|VEHICLEHARDNESS|2 Bicycle TYPE:Vehicle.Personal.Standard.Container CONTAINS:*UNLIM COST:0 SIZE:M SOURCEPAGE:p.147 BONUS:VAR|VEHICLESPEED|50 BONUS:VAR|VEHICLEDEFENSE|16 BONUS:VAR|VEHICLEHANDLING|6 BONUS:VAR|VEHICLEWOUNDPOINTS|30 BONUS:VAR|VEHICLEHARDNESS|1 Jet Ski TYPE:Vehicle.Personal.Standard.Container CONTAINS:*UNLIM COST:1 SIZE:M SOURCEPAGE:p.147 BONUS:VAR|VEHICLESPEED|150 BONUS:VAR|VEHICLEDEFENSE|14 BONUS:VAR|VEHICLEHANDLING|4 BONUS:VAR|VEHICLEWOUNDPOINTS|30 BONUS:VAR|VEHICLEHARDNESS|1 Motorcycle (Chopper) TYPE:Vehicle.Personal.Standard.Container CONTAINS:*UNLIM COST:3 SIZE:L SOURCEPAGE:p.147 BONUS:VAR|VEHICLESPEED|400 BONUS:VAR|VEHICLEDEFENSE|15 BONUS:VAR|VEHICLEHANDLING|6 BONUS:VAR|VEHICLEWOUNDPOINTS|50 BONUS:VAR|VEHICLEHARDNESS|2 Motorcycle (Dirt Bike) TYPE:Vehicle.Personal.Standard.Container CONTAINS:*UNLIM COST:1 SIZE:M SOURCEPAGE:p.147 BONUS:VAR|VEHICLESPEED|200 BONUS:VAR|VEHICLEDEFENSE|16 BONUS:VAR|VEHICLEHANDLING|6 BONUS:VAR|VEHICLEWOUNDPOINTS|30 BONUS:VAR|VEHICLEHARDNESS|2 Motorcycle (Racing) TYPE:Vehicle.Personal.Standard.Container CONTAINS:*UNLIM COST:4 SIZE:L SOURCEPAGE:p.147 BONUS:VAR|VEHICLESPEED|750 BONUS:VAR|VEHICLEDEFENSE|17 BONUS:VAR|VEHICLEHANDLING|7 BONUS:VAR|VEHICLEWOUNDPOINTS|25 BONUS:VAR|VEHICLEHARDNESS|2 Motorcycle (Street) TYPE:Vehicle.Personal.Standard.Container CONTAINS:*UNLIM COST:2 SIZE:M SOURCEPAGE:p.147 BONUS:VAR|VEHICLESPEED|500 BONUS:VAR|VEHICLEDEFENSE|18 BONUS:VAR|VEHICLEHANDLING|8 BONUS:VAR|VEHICLEWOUNDPOINTS|35 BONUS:VAR|VEHICLEHARDNESS|1 Quad (4-wheeler) TYPE:Vehicle.Personal.Standard.Container CONTAINS:*UNLIM COST:2 SIZE:M SOURCEPAGE:p.147 BONUS:VAR|VEHICLESPEED|200 BONUS:VAR|VEHICLEDEFENSE|16 BONUS:VAR|VEHICLEHANDLING|6 BONUS:VAR|VEHICLEWOUNDPOINTS|50 BONUS:VAR|VEHICLEHARDNESS|2 Snowmobile TYPE:Vehicle.Personal.Standard.Container CONTAINS:*UNLIM COST:2 SIZE:M SOURCEPAGE:p.147 BONUS:VAR|VEHICLESPEED|250 BONUS:VAR|VEHICLEDEFENSE|16 BONUS:VAR|VEHICLEHANDLING|6 BONUS:VAR|VEHICLEWOUNDPOINTS|50 BONUS:VAR|VEHICLEHARDNESS|2 # Mounts --------------------------------------- Camel TYPE:Vehicle.Mount.Standard.Container CONTAINS:*UNLIM COST:2 SIZE:L SOURCEPAGE:p.147 BONUS:VAR|VEHICLESPEED|30 BONUS:VAR|VEHICLEDEFENSE|13 BONUS:VAR|VEHICLEHANDLING|-1 BONUS:VAR|VEHICLEWOUNDPOINTS|15 BONUS:VAR|VEHICLEHARDNESS|0 Horse TYPE:Vehicle.Mount.Standard.Container CONTAINS:*UNLIM COST:2 SIZE:L SOURCEPAGE:p.147 BONUS:VAR|VEHICLESPEED|40 BONUS:VAR|VEHICLEDEFENSE|13 BONUS:VAR|VEHICLEHANDLING|0 BONUS:VAR|VEHICLEWOUNDPOINTS|12 BONUS:VAR|VEHICLEHARDNESS|0 Mule TYPE:Vehicle.Mount.Standard.Container CONTAINS:*UNLIM COST:2 SIZE:L SOURCEPAGE:p.147 BONUS:VAR|VEHICLESPEED|30 BONUS:VAR|VEHICLEDEFENSE|13 BONUS:VAR|VEHICLEHANDLING|-3 BONUS:VAR|VEHICLEWOUNDPOINTS|14 BONUS:VAR|VEHICLEHARDNESS|0 # Cars ----------------------------------------- Car (Classic) TYPE:Vehicle.Automobile.Standard.Container CONTAINS:*UNLIM COST:3 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|500 BONUS:VAR|VEHICLEDEFENSE|5 BONUS:VAR|VEHICLEHANDLING|-4 BONUS:VAR|VEHICLEWOUNDPOINTS|100 BONUS:VAR|VEHICLEHARDNESS|6 Car (Compact) TYPE:Vehicle.Automobile.Standard.Container CONTAINS:*UNLIM COST:3 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|500 BONUS:VAR|VEHICLEDEFENSE|11 BONUS:VAR|VEHICLEHANDLING|2 BONUS:VAR|VEHICLEWOUNDPOINTS|80 BONUS:VAR|VEHICLEHARDNESS|4 Car (Economy) TYPE:Vehicle.Automobile.Standard.Container CONTAINS:*UNLIM COST:2 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|500 BONUS:VAR|VEHICLEDEFENSE|9 BONUS:VAR|VEHICLEHANDLING|0 BONUS:VAR|VEHICLEWOUNDPOINTS|80 BONUS:VAR|VEHICLEHARDNESS|4 Car (Limo) TYPE:Vehicle.Automobile.Standard.Container CONTAINS:*UNLIM COST:5 SIZE:H SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|350 BONUS:VAR|VEHICLEDEFENSE|4 BONUS:VAR|VEHICLEHANDLING|-5 BONUS:VAR|VEHICLEWOUNDPOINTS|140 BONUS:VAR|VEHICLEHARDNESS|7 Car (Luxury) TYPE:Vehicle.Automobile.Standard.Container CONTAINS:*UNLIM COST:4 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|550 BONUS:VAR|VEHICLEDEFENSE|7 BONUS:VAR|VEHICLEHANDLING|-2 BONUS:VAR|VEHICLEWOUNDPOINTS|110 BONUS:VAR|VEHICLEHARDNESS|7 Car (Mid-Size) TYPE:Vehicle.Automobile.Standard.Container CONTAINS:*UNLIM COST:3 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|550 BONUS:VAR|VEHICLEDEFENSE|9 BONUS:VAR|VEHICLEHANDLING|0 BONUS:VAR|VEHICLEWOUNDPOINTS|90 BONUS:VAR|VEHICLEHARDNESS|5 Car (Muscle) TYPE:Vehicle.Automobile.Standard.Container CONTAINS:*UNLIM COST:3 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|650 BONUS:VAR|VEHICLEDEFENSE|8 BONUS:VAR|VEHICLEHANDLING|-1 BONUS:VAR|VEHICLEWOUNDPOINTS|110 BONUS:VAR|VEHICLEHARDNESS|7 Car (Police) TYPE:Vehicle.Automobile.Standard.Container CONTAINS:*UNLIM COST:4 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|700 BONUS:VAR|VEHICLEDEFENSE|13 BONUS:VAR|VEHICLEHANDLING|+4 BONUS:VAR|VEHICLEWOUNDPOINTS|110 BONUS:VAR|VEHICLEHARDNESS|7 Car (Sedan) TYPE:Vehicle.Automobile.Standard.Container CONTAINS:*UNLIM COST:3 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|600 BONUS:VAR|VEHICLEDEFENSE|10 BONUS:VAR|VEHICLEHANDLING|+1 BONUS:VAR|VEHICLEWOUNDPOINTS|100 BONUS:VAR|VEHICLEHARDNESS|6 Car (Sports) TYPE:Vehicle.Automobile.Standard.Container CONTAINS:*UNLIM COST:4 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|800 BONUS:VAR|VEHICLEDEFENSE|14 BONUS:VAR|VEHICLEHANDLING|+5 BONUS:VAR|VEHICLEWOUNDPOINTS|70 BONUS:VAR|VEHICLEHARDNESS|3 Car (Station Wagon) TYPE:Vehicle.Automobile.Standard.Container CONTAINS:*UNLIM COST:2 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|500 BONUS:VAR|VEHICLEDEFENSE|6 BONUS:VAR|VEHICLEHANDLING|-3 BONUS:VAR|VEHICLEWOUNDPOINTS|100 BONUS:VAR|VEHICLEHARDNESS|6 Car (Sub-compact) TYPE:Vehicle.Automobile.Standard.Container CONTAINS:*UNLIM COST:1 SIZE:M SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|450 BONUS:VAR|VEHICLEDEFENSE|13 BONUS:VAR|VEHICLEHANDLING|3 BONUS:VAR|VEHICLEWOUNDPOINTS|70 BONUS:VAR|VEHICLEHARDNESS|3 # Trucks --------------------------------------- Ambulance TYPE:Vehicle.Truck.Standard.Container CONTAINS:*UNLIM COST:4 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|550 BONUS:VAR|VEHICLEDEFENSE|6 BONUS:VAR|VEHICLEHANDLING|-3 BONUS:VAR|VEHICLEWOUNDPOINTS|120 BONUS:VAR|VEHICLEHARDNESS|6 Box Truck TYPE:Vehicle.Truck.Standard.Container CONTAINS:*UNLIM COST:5 SIZE:H SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|500 BONUS:VAR|VEHICLEDEFENSE|3 BONUS:VAR|VEHICLEHANDLING|-6 BONUS:VAR|VEHICLEWOUNDPOINTS|140 BONUS:VAR|VEHICLEHARDNESS|8 Bus TYPE:Vehicle.Truck.Standard.Container CONTAINS:*UNLIM COST:6 SIZE:G SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|450 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|-7 BONUS:VAR|VEHICLEWOUNDPOINTS|150 BONUS:VAR|VEHICLEHARDNESS|9 Humvee TYPE:Vehicle.Truck.Standard.Container CONTAINS:*UNLIM COST:8 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|500 BONUS:VAR|VEHICLEDEFENSE|4 BONUS:VAR|VEHICLEHANDLING|-5 BONUS:VAR|VEHICLEWOUNDPOINTS|170 BONUS:VAR|VEHICLEHARDNESS|10 Jeep TYPE:Vehicle.Truck.Standard.Container CONTAINS:*UNLIM COST:2 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|600 BONUS:VAR|VEHICLEDEFENSE|10 BONUS:VAR|VEHICLEHANDLING|1 BONUS:VAR|VEHICLEWOUNDPOINTS|100 BONUS:VAR|VEHICLEHARDNESS|5 Mini-van TYPE:Vehicle.Truck.Standard.Container CONTAINS:*UNLIM COST:3 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|600 BONUS:VAR|VEHICLEDEFENSE|8 BONUS:VAR|VEHICLEHANDLING|-1 BONUS:VAR|VEHICLEWOUNDPOINTS|110 BONUS:VAR|VEHICLEHARDNESS|5 Off-road TYPE:Vehicle.Truck.Standard.Container CONTAINS:*UNLIM COST:2 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|600 BONUS:VAR|VEHICLEDEFENSE|9 BONUS:VAR|VEHICLEHANDLING|0 BONUS:VAR|VEHICLEWOUNDPOINTS|110 BONUS:VAR|VEHICLEHARDNESS|5 Pick-up TYPE:Vehicle.Truck.Standard.Container CONTAINS:*UNLIM COST:3 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|550 BONUS:VAR|VEHICLEDEFENSE|7 BONUS:VAR|VEHICLEHANDLING|-2 BONUS:VAR|VEHICLEWOUNDPOINTS|120 BONUS:VAR|VEHICLEHARDNESS|6 Semi (empty) TYPE:Vehicle.Truck.Standard.Container CONTAINS:*UNLIM COST:7 SIZE:G SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|450 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|-8 BONUS:VAR|VEHICLEWOUNDPOINTS|150 BONUS:VAR|VEHICLEHARDNESS|9 Semi (loaded) TYPE:Vehicle.Truck.Standard.Container CONTAINS:*UNLIM COST:7 SIZE:G SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|450 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|-9 BONUS:VAR|VEHICLEWOUNDPOINTS|150 BONUS:VAR|VEHICLEHARDNESS|9 SUV TYPE:Vehicle.Truck.Standard.Container CONTAINS:*UNLIM COST:4 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|500 BONUS:VAR|VEHICLEDEFENSE|5 BONUS:VAR|VEHICLEHANDLING|-4 BONUS:VAR|VEHICLEWOUNDPOINTS|140 BONUS:VAR|VEHICLEHARDNESS|7 Van TYPE:Vehicle.Truck.Standard.Container CONTAINS:*UNLIM COST:4 SIZE:L SOURCEPAGE:p.148 BONUS:VAR|VEHICLESPEED|550 BONUS:VAR|VEHICLEDEFENSE|5 BONUS:VAR|VEHICLEHANDLING|-4 BONUS:VAR|VEHICLEWOUNDPOINTS|130 BONUS:VAR|VEHICLEHARDNESS|7 # Water Vehicles ------------------------------- Aircraft Carrier TYPE:Vehicle.Watercraft.Standard.Container CONTAINS:*UNLIM COST:20 SIZE:C SOURCEPAGE:p.149 BONUS:VAR|VEHICLESPEED|200 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|-15 BONUS:VAR|VEHICLEWOUNDPOINTS|1000 BONUS:VAR|VEHICLEHARDNESS|15 Canoe TYPE:Vehicle.Watercraft.Standard.Container CONTAINS:*UNLIM COST:0 SIZE:M SOURCEPAGE:p.149 BONUS:VAR|VEHICLESPEED|40 BONUS:VAR|VEHICLEDEFENSE|8 BONUS:VAR|VEHICLEHANDLING|-2 BONUS:VAR|VEHICLEWOUNDPOINTS|10 BONUS:VAR|VEHICLEHARDNESS|1 Diving Bell TYPE:Vehicle.Watercraft.Standard.Container CONTAINS:*UNLIM COST:2 SIZE:L SOURCEPAGE:p.149 BONUS:VAR|VEHICLESPEED|20 BONUS:VAR|VEHICLEDEFENSE|4 BONUS:VAR|VEHICLEHANDLING|0 BONUS:VAR|VEHICLEWOUNDPOINTS|50 BONUS:VAR|VEHICLEHARDNESS|5 Diving Drone TYPE:Vehicle.Watercraft.Standard.Container CONTAINS:*UNLIM COST:3 SIZE:S SOURCEPAGE:p.149 BONUS:VAR|VEHICLESPEED|10 BONUS:VAR|VEHICLEDEFENSE|13 BONUS:VAR|VEHICLEHANDLING|2 BONUS:VAR|VEHICLEWOUNDPOINTS|40 BONUS:VAR|VEHICLEHARDNESS|3 Fishing Boat TYPE:Vehicle.Watercraft.Standard.Container CONTAINS:*UNLIM COST:3 SIZE:H SOURCEPAGE:p.149 BONUS:VAR|VEHICLESPEED|80 BONUS:VAR|VEHICLEDEFENSE|8 BONUS:VAR|VEHICLEHANDLING|0 BONUS:VAR|VEHICLEWOUNDPOINTS|75 BONUS:VAR|VEHICLEHARDNESS|3 Luxury Liner TYPE:Vehicle.Watercraft.Standard.Container CONTAINS:*UNLIM COST:12 SIZE:C SOURCEPAGE:p.149 BONUS:VAR|VEHICLESPEED|100 BONUS:VAR|VEHICLEDEFENSE|3 BONUS:VAR|VEHICLEHANDLING|-10 BONUS:VAR|VEHICLEWOUNDPOINTS|500 BONUS:VAR|VEHICLEHARDNESS|7 Mini-Sub TYPE:Vehicle.Watercraft.Standard.Container CONTAINS:*UNLIM COST:5 SIZE:L SOURCEPAGE:p.149 BONUS:VAR|VEHICLESPEED|150 BONUS:VAR|VEHICLEDEFENSE|10 BONUS:VAR|VEHICLEHANDLING|1 BONUS:VAR|VEHICLEWOUNDPOINTS|75 BONUS:VAR|VEHICLEHARDNESS|4 Oil Tanker TYPE:Vehicle.Watercraft.Standard.Container CONTAINS:*UNLIM COST:15 SIZE:C SOURCEPAGE:p.149 BONUS:VAR|VEHICLESPEED|80 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|-13 BONUS:VAR|VEHICLEWOUNDPOINTS|700 BONUS:VAR|VEHICLEHARDNESS|10 Rowboat TYPE:Vehicle.Watercraft.Standard.Container CONTAINS:*UNLIM COST:0 SIZE:M SOURCEPAGE:p.149 BONUS:VAR|VEHICLESPEED|30 BONUS:VAR|VEHICLEDEFENSE|7 BONUS:VAR|VEHICLEHANDLING|-3 BONUS:VAR|VEHICLEWOUNDPOINTS|15 BONUS:VAR|VEHICLEHARDNESS|2 Speedboat TYPE:Vehicle.Watercraft.Standard.Container CONTAINS:*UNLIM COST:3 SIZE:L SOURCEPAGE:p.149 BONUS:VAR|VEHICLESPEED|400 BONUS:VAR|VEHICLEDEFENSE|14 BONUS:VAR|VEHICLEHANDLING|5 BONUS:VAR|VEHICLEWOUNDPOINTS|60 BONUS:VAR|VEHICLEHARDNESS|3 Submarine TYPE:Vehicle.Watercraft.Standard.Container CONTAINS:*UNLIM COST:9 SIZE:C SOURCEPAGE:p.149 BONUS:VAR|VEHICLESPEED|150 BONUS:VAR|VEHICLEDEFENSE|3 BONUS:VAR|VEHICLEHANDLING|-6 BONUS:VAR|VEHICLEWOUNDPOINTS|100 BONUS:VAR|VEHICLEHARDNESS|8 Submersible Car TYPE:Vehicle.Watercraft.Standard.Container CONTAINS:*UNLIM COST:7 SIZE:L SOURCEPAGE:p.149 BONUS:VAR|VEHICLESPEED|100 BONUS:VAR|VEHICLEDEFENSE|13 BONUS:VAR|VEHICLEHANDLING|4 BONUS:VAR|VEHICLEWOUNDPOINTS|85 BONUS:VAR|VEHICLEHARDNESS|5 Swamp Boat TYPE:Vehicle.Watercraft.Standard.Container CONTAINS:*UNLIM COST:4 SIZE:L SOURCEPAGE:p.149 BONUS:VAR|VEHICLESPEED|200 BONUS:VAR|VEHICLEDEFENSE|13 BONUS:VAR|VEHICLEHANDLING|4 BONUS:VAR|VEHICLEWOUNDPOINTS|40 BONUS:VAR|VEHICLEHARDNESS|3 Zodiac TYPE:Vehicle.Watercraft.Standard.Container CONTAINS:*UNLIM COST:3 SIZE:L SOURCEPAGE:p.149 BONUS:VAR|VEHICLESPEED|150 BONUS:VAR|VEHICLEDEFENSE|12 BONUS:VAR|VEHICLEHANDLING|3 BONUS:VAR|VEHICLEWOUNDPOINTS|20 BONUS:VAR|VEHICLEHARDNESS|1 # Air Vehicles --------------------------------- Autogyro TYPE:Vehicle.Aircraft.Standard.Container CONTAINS:*UNLIM COST:7 SIZE:L SOURCEPAGE:p.150 BONUS:VAR|VEHICLESPEED|200 BONUS:VAR|VEHICLEDEFENSE|15 BONUS:VAR|VEHICLEHANDLING|6 BONUS:VAR|VEHICLEWOUNDPOINTS|30 BONUS:VAR|VEHICLEHARDNESS|3 Fighter jet TYPE:Vehicle.Aircraft.Standard.Container CONTAINS:*UNLIM COST:18 SIZE:L SOURCEPAGE:p.150 BONUS:VAR|VEHICLESPEED|4000 BONUS:VAR|VEHICLEDEFENSE|20 BONUS:VAR|VEHICLEHANDLING|12 BONUS:VAR|VEHICLEWOUNDPOINTS|100 BONUS:VAR|VEHICLEHARDNESS|8 Gunship TYPE:Vehicle.Aircraft.Standard.Container CONTAINS:*UNLIM COST:16 SIZE:L SOURCEPAGE:p.150 BONUS:VAR|VEHICLESPEED|1200 BONUS:VAR|VEHICLEDEFENSE|16 BONUS:VAR|VEHICLEHANDLING|8 BONUS:VAR|VEHICLEWOUNDPOINTS|100 BONUS:VAR|VEHICLEHARDNESS|7 Hang glider TYPE:Vehicle.Aircraft.Standard.Container CONTAINS:*UNLIM COST:2 SIZE:L SOURCEPAGE:p.150 BONUS:VAR|VEHICLESPEED|50 BONUS:VAR|VEHICLEDEFENSE|10 BONUS:VAR|VEHICLEHANDLING|1 BONUS:VAR|VEHICLEWOUNDPOINTS|15 BONUS:VAR|VEHICLEHARDNESS|2 Helicopter TYPE:Vehicle.Aircraft.Standard.Container CONTAINS:*UNLIM COST:9 SIZE:L SOURCEPAGE:p.150 BONUS:VAR|VEHICLESPEED|1000 BONUS:VAR|VEHICLEDEFENSE|14 BONUS:VAR|VEHICLEHANDLING|5 BONUS:VAR|VEHICLEWOUNDPOINTS|75 BONUS:VAR|VEHICLEHARDNESS|5 Hot air balloon TYPE:Vehicle.Aircraft.Standard.Container CONTAINS:*UNLIM COST:1 SIZE:L SOURCEPAGE:p.150 BONUS:VAR|VEHICLESPEED|0 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|0 BONUS:VAR|VEHICLEWOUNDPOINTS|10 BONUS:VAR|VEHICLEHARDNESS|0 Jetpack TYPE:Vehicle.Aircraft.Standard.Container CONTAINS:*UNLIM COST:4 SIZE:L SOURCEPAGE:p.150 BONUS:VAR|VEHICLESPEED|500 BONUS:VAR|VEHICLEDEFENSE|18 BONUS:VAR|VEHICLEHANDLING|7 BONUS:VAR|VEHICLEWOUNDPOINTS|25 BONUS:VAR|VEHICLEHARDNESS|1 Jumbo jet TYPE:Vehicle.Aircraft.Standard.Container CONTAINS:*UNLIM COST:12 SIZE:L SOURCEPAGE:p.150 BONUS:VAR|VEHICLESPEED|3100 BONUS:VAR|VEHICLEDEFENSE|3 BONUS:VAR|VEHICLEHANDLING|-1 BONUS:VAR|VEHICLEWOUNDPOINTS|120 BONUS:VAR|VEHICLEHARDNESS|6 Parasail TYPE:Vehicle.Aircraft.Standard.Container CONTAINS:*UNLIM COST:2 SIZE:L SOURCEPAGE:p.150 BONUS:VAR|VEHICLESPEED|100 BONUS:VAR|VEHICLEDEFENSE|9 BONUS:VAR|VEHICLEHANDLING|0 BONUS:VAR|VEHICLEWOUNDPOINTS|15 BONUS:VAR|VEHICLEHARDNESS|1 Space shuttle TYPE:Vehicle.Aircraft.Standard.Container CONTAINS:*UNLIM COST:40 SIZE:L SOURCEPAGE:p.150 BONUS:VAR|VEHICLESPEED|10000 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|-5 BONUS:VAR|VEHICLEWOUNDPOINTS|600 BONUS:VAR|VEHICLEHARDNESS|10 Ultralight TYPE:Vehicle.Aircraft.Standard.Container CONTAINS:*UNLIM COST:3 SIZE:L SOURCEPAGE:p.150 BONUS:VAR|VEHICLESPEED|250 BONUS:VAR|VEHICLEDEFENSE|12 BONUS:VAR|VEHICLEHANDLING|3 BONUS:VAR|VEHICLEWOUNDPOINTS|40 BONUS:VAR|VEHICLEHARDNESS|4 VTOL TYPE:Vehicle.Aircraft.Standard.Container CONTAINS:*UNLIM COST:15 SIZE:L SOURCEPAGE:p.150 BONUS:VAR|VEHICLESPEED|650 BONUS:VAR|VEHICLEDEFENSE|10 BONUS:VAR|VEHICLEHANDLING|2 BONUS:VAR|VEHICLEWOUNDPOINTS|100 BONUS:VAR|VEHICLEHARDNESS|7 Zeppelin TYPE:Vehicle.Aircraft.Standard.Container CONTAINS:*UNLIM COST:8 SIZE:L SOURCEPAGE:p.150 BONUS:VAR|VEHICLESPEED|350 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|-6 BONUS:VAR|VEHICLEWOUNDPOINTS|60 BONUS:VAR|VEHICLEHARDNESS|1 # Armored and Heavy Vehicles ------------------- 2.5 ton Truck TYPE:Vehicle.Armored.Standard.Container CONTAINS:*UNLIM COST:8 SIZE:H SOURCEPAGE:p.151 BONUS:VAR|VEHICLESPEED|400 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|-7 BONUS:VAR|VEHICLEWOUNDPOINTS|220 BONUS:VAR|VEHICLEHARDNESS|11 AAV TYPE:Vehicle.Armored.Standard.Container CONTAINS:*UNLIM COST:11 SIZE:H SOURCEPAGE:p.151 BONUS:VAR|VEHICLESPEED|300 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|-6 BONUS:VAR|VEHICLEWOUNDPOINTS|260 BONUS:VAR|VEHICLEHARDNESS|13 APC TYPE:Vehicle.Armored.Standard.Container CONTAINS:*UNLIM COST:8 SIZE:H SOURCEPAGE:p.151 BONUS:VAR|VEHICLESPEED|400 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|-8 BONUS:VAR|VEHICLEWOUNDPOINTS|240 BONUS:VAR|VEHICLEHARDNESS|12 Armored Car TYPE:Vehicle.Armored.Standard.Container CONTAINS:*UNLIM COST:7 SIZE:L SOURCEPAGE:p.151 BONUS:VAR|VEHICLESPEED|400 BONUS:VAR|VEHICLEDEFENSE|5 BONUS:VAR|VEHICLEHANDLING|-4 BONUS:VAR|VEHICLEWOUNDPOINTS|220 BONUS:VAR|VEHICLEHARDNESS|11 Bullet Train TYPE:Vehicle.Train.Standard.Container CONTAINS:*UNLIM COST:14 SIZE:C SOURCEPAGE:p.151 BONUS:VAR|VEHICLESPEED|900 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|0 BONUS:VAR|VEHICLEWOUNDPOINTS|300 BONUS:VAR|VEHICLEHARDNESS|12 Half-track TYPE:Vehicle.Armored.Standard.Container CONTAINS:*UNLIM COST:9 SIZE:H SOURCEPAGE:p.151 BONUS:VAR|VEHICLESPEED|350 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|-9 BONUS:VAR|VEHICLEWOUNDPOINTS|240 BONUS:VAR|VEHICLEHARDNESS|12 Hovercraft TYPE:Vehicle.Amphibious.Standard.Container CONTAINS:*UNLIM COST:10 SIZE:G SOURCEPAGE:p.151 BONUS:VAR|VEHICLESPEED|300 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|-5 BONUS:VAR|VEHICLEWOUNDPOINTS|200 BONUS:VAR|VEHICLEHARDNESS|10 Tank TYPE:Vehicle.Armored.Standard.Container CONTAINS:*UNLIM COST:13 SIZE:H SOURCEPAGE:p.151 BONUS:VAR|VEHICLESPEED|450 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|-10 BONUS:VAR|VEHICLEWOUNDPOINTS|280 BONUS:VAR|VEHICLEHARDNESS|14 Train TYPE:Vehicle.Train.Standard.Container CONTAINS:*UNLIM COST:12 SIZE:C SOURCEPAGE:p.151 BONUS:VAR|VEHICLESPEED|350 BONUS:VAR|VEHICLEDEFENSE|2 BONUS:VAR|VEHICLEHANDLING|0 BONUS:VAR|VEHICLEWOUNDPOINTS|300 BONUS:VAR|VEHICLEHARDNESS|13 # # End #
{ "pile_set_name": "Github" }
/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef MODULES_AUDIO_PROCESSING_TRANSIENT_DYADIC_DECIMATOR_H_ #define MODULES_AUDIO_PROCESSING_TRANSIENT_DYADIC_DECIMATOR_H_ #include <cstdlib> // Provides a set of static methods to perform dyadic decimations. namespace webrtc { // Returns the proper length of the output buffer that you should use for the // given |in_length| and decimation |odd_sequence|. // Return -1 on error. inline size_t GetOutLengthToDyadicDecimate(size_t in_length, bool odd_sequence) { size_t out_length = in_length / 2; if (in_length % 2 == 1 && !odd_sequence) { ++out_length; } return out_length; } // Performs a dyadic decimation: removes every odd/even member of a sequence // halving its overall length. // Arguments: // in: array of |in_length|. // odd_sequence: If false, the odd members will be removed (1, 3, 5, ...); // if true, the even members will be removed (0, 2, 4, ...). // out: array of |out_length|. |out_length| must be large enough to // hold the decimated output. The necessary length can be provided by // GetOutLengthToDyadicDecimate(). // Must be previously allocated. // Returns the number of output samples, -1 on error. template <typename T> static size_t DyadicDecimate(const T* in, size_t in_length, bool odd_sequence, T* out, size_t out_length) { size_t half_length = GetOutLengthToDyadicDecimate(in_length, odd_sequence); if (!in || !out || in_length <= 0 || out_length < half_length) { return 0; } size_t output_samples = 0; size_t index_adjustment = odd_sequence ? 1 : 0; for (output_samples = 0; output_samples < half_length; ++output_samples) { out[output_samples] = in[output_samples * 2 + index_adjustment]; } return output_samples; } } // namespace webrtc #endif // MODULES_AUDIO_PROCESSING_TRANSIENT_DYADIC_DECIMATOR_H_
{ "pile_set_name": "Github" }
/* Copyright Massachusetts Institute of Technology 1985 */ #include "copyright.h" /* * XMenu: MIT Project Athena, X Window system menu package * * XMenuSetFreeze - Forcibly set the menu freeze mode switch * overriding the Xdefaults setting. * This is necessary in some situations. * * Author: Tony Della Fera, DEC * January 29, 1986 * */ #include "XMenuInt.h" void XMenuSetFreeze(register XMenu *menu, register int freeze) /* Menu object to be modified. */ /* Freeze mode? */ { /* * Set the freeze mode switch. */ menu->freeze = freeze; }
{ "pile_set_name": "Github" }
import random from boopak.package import * from boodle import agent, stereo from boodle import builtin play = bimport('org.boodler.play') nature = bimport('org.emacspeak.nature') water = bimport('org.boodler.old.water') wavesounds = [ water.waves_lapping, water.waves_light, water.waves_rough, water.waves_floopy, water.water_rushing, water.water_pouring, water.water_rapids ] class SurfWaves(agent.Agent): """Orchestrate wave agents SurfWaveSounds and SurfBackgroundWaves""" def run(self): bc = self.new_channel_pan( stereo.compose(stereo.scalexy(1.1), stereo.shiftxy(0, 1.25))) ag = nature.Nightingales( 0, 30, # Duration 0.1, 1.0, # volume 1) self.sched_agent(ag, 0, bc) bc = self.new_channel_pan( stereo.compose(stereo.scalexy(1.3), stereo.shiftxy(0, -1.25))) ag = nature.Cuckoos( 0, 60, # Duration 0.05, 0.75, # volume 1) self.sched_agent(ag, 0, bc) ag = nature.FlMockingBirds( 0, 1200, # Duration 0.05, 0.75, # volume 1) self.sched_agent(ag, 0, bc) for i in range(8): y = 1 + i * 0.05 sc = self.new_channel_pan( stereo.compose(stereo.scalexy(1.4), stereo.shiftxy(0, y))) ag = SurfBackgroundWaves() self.sched_agent(ag, i * 5, sc) sc = self.new_channel_pan( stereo.compose(stereo.scalexy(1.4), stereo.shiftxy(0, -y))) ag = SurfWaveSounds() self.sched_agent(ag, i * 10, sc) class SurfWaveSounds(agent.Agent): def run(self): ag = play.IntermittentSoundsList(mindelay=1.0, maxdelay=8.0, minpitch=0.2, maxpitch=1.0, minvol=0.02, maxvol=0.5, maxpan=1.25, sounds=wavesounds) self.sched_agent(ag) class SurfBackgroundWaves(agent.Agent): def run(self): p = random.uniform(0.2, 1.0) v = random.uniform(0.01, 0.5) d = random.uniform(0.3, 12.0) pan = random.uniform(-1.25, 1.25) dur = self.sched_note_pan(water.waves_light, pan, pitch=p, volume=v) self.resched(dur * d)
{ "pile_set_name": "Github" }
%---------------------------------------------------------------------------% % vim: ft=mercury ts=4 sw=4 et %---------------------------------------------------------------------------% % Copyright (C) 1994-2012 The University of Melbourne. % This file may only be copied under the terms of the GNU General % Public License - see the file COPYING in the Mercury distribution. %---------------------------------------------------------------------------% % % File: mode_errors.m. % Main author: fjh. % % This module contains all the error-reporting routines for the mode-checker. % %---------------------------------------------------------------------------% :- module check_hlds.mode_errors. :- interface. :- import_module check_hlds.mode_info. :- import_module hlds. :- import_module hlds.hlds_goal. :- import_module hlds.hlds_module. :- import_module hlds.hlds_pred. :- import_module mdbcomp. :- import_module mdbcomp.prim_data. :- import_module parse_tree. :- import_module parse_tree.error_util. :- import_module parse_tree.parse_tree_out_info. :- import_module parse_tree.prog_data. :- import_module parse_tree.set_of_var. :- import_module assoc_list. :- import_module bool. :- import_module list. :- import_module maybe. %---------------------------------------------------------------------------% :- type merge_context ---> merge_disj ; merge_if_then_else ; merge_stm_atomic. :- type merge_error ---> merge_error(prog_var, assoc_list(prog_context, mer_inst)). :- type delayed_goal ---> delayed_goal( set_of_progvar, % The vars the goal is waiting on. mode_error_info, % The reason the goal can't be scheduled. hlds_goal % The goal itself. ). :- type var_multimode_pred_error ---> no_matching_mode(list(prog_var)) ; more_than_one_matching_mode(list(prog_var)) ; some_ho_args_non_ground(list(prog_var)). :- type pred_var_multimode_pred_error ---> pred_var_multimode_pred_error(pred_id, var_multimode_pred_error). :- type mode_error ---> mode_error_disj(merge_context, list(merge_error)) % Different arms of a disjunction result in different insts % for some non-local variables. ; mode_error_par_conj(list(merge_error)) % Different arms of a parallel conj result in mutually exclusive % bindings - i.e. the process of unifying the instmaps from the end % of each branch failed. ; mode_error_higher_order_pred_var(pred_or_func, prog_var, mer_inst, arity) % The predicate variable in a higher-order predicate or function % call didn't have a higher-order predicate or function inst % of the appropriate arity. ; mode_error_poly_unify(prog_var, mer_inst) % A variable in a polymorphic unification with unknown % type has inst other than `ground' or `any'. ; mode_error_var_is_live(prog_var) % Call to a predicate which will clobber its argument, % but the argument is still live. ; mode_error_var_has_inst(prog_var, mer_inst, mer_inst, maybe(pred_var_multimode_pred_error)) % Call to a predicate with an insufficiently % instantiated variable (for preds with one mode). ; mode_error_unify_pred(prog_var, mode_error_unify_rhs, mer_type, pred_or_func) % An attempt was made to unify two higher-order % predicate or function variables. ; mode_error_implied_mode(prog_var, mer_inst, mer_inst) % A call to a predicate with an overly instantiated variable % would use an implied mode of the predicate, but we can't % introduce a simple unification after calling the predicate in a % principal mode because the relevant variable has complex inst % (such as any). ; mode_error_no_mode_decl % A call to a predicate for which there are no mode declarations % (and mode inference is not enabled). ; mode_error_no_matching_mode(list(prog_var), list(mer_inst), list(list(mer_inst))) % Call to a predicate with an insufficiently instantiated variable % (for preds with >1 mode). % % The first two arguments give the argument vars of the call % and their insts at the time of the call. % % If the third argument is a nonempty list, then every member % of that list gives the list of the required initial insts % of the argument vars. % % All the lists of insts must have exactly one inst for % each var in the list of vars. ; mode_error_in_callee(list(prog_var), list(mer_inst), pred_id, proc_id, list(mode_error_info)) % Call to a predicate with initial argument insts for which mode % inference gave a mode error in the callee. ; mode_error_bind_var(var_lock_reason, prog_var, mer_inst, mer_inst) % Attempt to bind a non-local variable inside a negated context, % or attempt to re-bind a variable in a parallel conjunct. ; mode_error_non_local_lambda_var(prog_var, mer_inst) % Attempt to pass a live non-ground var as a non-local variable % to a lambda goal. ; mode_error_unify_var_var(prog_var, prog_var, mer_inst, mer_inst) % Attempt to unify two free variables. ; mode_error_unify_var_functor(prog_var, cons_id, list(prog_var), mer_inst, list(mer_inst)) % Attempt to unify a free var with a functor containing % free arguments. ; mode_error_unify_var_lambda(prog_var, mer_inst, mer_inst) % Some sort of error in attempt to unify a variable with lambda % expression. ; mode_error_unify_var_multimode_pred(prog_var, pred_id, var_multimode_pred_error) % Some sort of error in attempt to take address of a multi-moded % predicate. ; mode_error_conj(list(delayed_goal), schedule_culprit) % A conjunction contains one or more unscheduleable goals; % schedule_culprit gives the reason why they couldn't be scheduled. ; mode_error_final_inst(int, prog_var, mer_inst, mer_inst, final_inst_error) % One of the head variables did not have the expected final inst % on exit from the proc. ; purity_error_should_be_in_promise_purity_scope( negated_context_desc, prog_var) % The condition of an if-then-else or the body of a negation % contained an inst any non-local, but was not inside a % promise_purity scope. ; purity_error_lambda_should_be_any(list(prog_var)). % A ground lambda term contains inst any non-locals, and is not % marked impure. :- type negated_context_desc ---> if_then_else ; negation. :- type schedule_culprit ---> goal_itself_was_impure ; goals_followed_by_impure_goal(hlds_goal) ; conj_floundered. % We have reached the end of a conjunction % and there were still delayed goals. :- type final_inst_error ---> too_instantiated ; not_instantiated_enough ; wrongly_instantiated. % A catchall for anything that does not % fit into the above two categories. :- type mode_error_unify_rhs ---> error_at_var(prog_var) ; error_at_functor(cons_id, list(prog_var)) ; error_at_lambda(list(prog_var), list(from_to_insts)). :- type mode_error_info ---> mode_error_info( set_of_progvar, % The variables which caused the error % (we will attempt to reschedule the goal % if one of these variables becomes % more instantiated). mode_error, % The nature of the error. prog_context, % Where the error occurred. mode_context % Where the error occurred. ). :- type mode_warning ---> cannot_succeed_var_var(prog_var, prog_var, mer_inst, mer_inst) ; cannot_succeed_var_functor(prog_var, mer_inst, cons_id) ; cannot_succeed_ground_occur_check(prog_var, cons_id). :- type mode_warning_info ---> mode_warning_info( mode_warning, % The nature of the error. prog_context, % Where the error occurred. mode_context % Where the error occurred. ). %---------------------------------------------------------------------------% % Initialize the mode_context. % :- pred mode_context_init(mode_context::out) is det. % Return an error for a predicate with no mode declarations % unless mode inference is enabled and the predicate is local. % XXX This predicate should be included in the types above. % :- func maybe_report_error_no_modes(module_info, pred_id, pred_info) = list(error_spec). % Report an error for the case when two mode declarations % declare indistinguishable modes. % XXX This predicate should be included in the types above. % :- func report_indistinguishable_modes_error(module_info, proc_id, proc_id, pred_id, pred_info) = error_spec. :- type include_detism_on_modes ---> include_detism_on_modes ; do_not_include_detism_on_modes. % Generate the inferred `mode' declarations for a list of pred_ids. % The include_detism_on_modes argument indicates whether or not % to write out determinism annotations on the modes. (It should only % be set to `include_detism_on_modes' _after_ determinism analysis.) % :- pred report_mode_inference_messages_for_preds(module_info::in, include_detism_on_modes::in, list(pred_id)::in, list(error_spec)::in, list(error_spec)::out) is det. :- func mode_decl_to_string(output_lang, proc_id, pred_info) = string. :- func mode_error_info_to_spec(mode_info, mode_error_info) = error_spec. :- func mode_warning_info_to_spec(mode_info, mode_warning_info) = error_spec. :- func should_report_mode_warning_for_pred_origin(pred_origin) = bool. %---------------------------------------------------------------------------% %---------------------------------------------------------------------------% :- implementation. :- import_module check_hlds.inst_match. :- import_module check_hlds.inst_test. :- import_module check_hlds.inst_util. :- import_module check_hlds.mode_util. :- import_module hlds.error_msg_inst. :- import_module hlds.hlds_error_util. :- import_module hlds.hlds_out. :- import_module hlds.hlds_out.hlds_out_goal. :- import_module hlds.hlds_out.hlds_out_util. :- import_module hlds.status. :- import_module hlds.vartypes. :- import_module libs. :- import_module libs.globals. :- import_module libs.op_mode. :- import_module libs.options. :- import_module mdbcomp.sym_name. :- import_module parse_tree.mercury_to_mercury. :- import_module parse_tree.parse_tree_out_pred_decl. :- import_module parse_tree.parse_tree_out_term. :- import_module parse_tree.prog_mode. :- import_module parse_tree.prog_out. :- import_module parse_tree.prog_util. :- import_module int. :- import_module io. % used only for a typeclass instance :- import_module map. :- import_module multi_map. :- import_module pair. :- import_module require. :- import_module string. :- import_module term. :- import_module varset. %---------------------------------------------------------------------------% mode_context_init(mode_context_uninitialized). %---------------------------------------------------------------------------% maybe_report_error_no_modes(ModuleInfo, PredId, PredInfo) = Specs :- pred_info_get_status(PredInfo, PredStatus), % XXX STATUS ( if PredStatus = pred_status(status_local) then module_info_get_globals(ModuleInfo, Globals), globals.lookup_bool_option(Globals, infer_modes, InferModesOpt), ( InferModesOpt = yes, Specs = [] ; InferModesOpt = no, pred_info_get_markers(PredInfo, Markers), ( if check_marker(Markers, marker_no_pred_decl) then % Generate an error_spec that prints nothing. % While we don't want the user to see the error message, % we need the severity_error to stop the compiler % from proceeding to process this predicate further. % For example, to determinism analysis, where it could % generate misleading errors about the determinism declaration % (added implicitly by the compiler) being wrong. % There is no risk of the compilation failing without % *any* error indication, since we generated an error message % when we added the marker. Msgs = [] else PredDesc = describe_one_pred_name(ModuleInfo, should_not_module_qualify, PredId), MainPieces = [words("Error: no mode declaration for")] ++ PredDesc ++ [suffix("."), nl], VerbosePieces = [words("(Use"), quote("--infer-modes"), words("to enable mode inference.)"), nl], Msgs = [simple_msg(Context, [always(MainPieces), verbose_only(verbose_once, VerbosePieces)])] ), pred_info_get_context(PredInfo, Context), Spec = error_spec($pred, severity_error, phase_mode_check(report_in_any_mode), Msgs), Specs = [Spec] ) else pred_info_get_context(PredInfo, Context), Pieces = [words("Error: no mode declaration for exported")] ++ describe_one_pred_name(ModuleInfo, should_module_qualify, PredId) ++ [suffix("."), nl], Spec = simplest_spec($pred, severity_error, phase_mode_check(report_in_any_mode), Context, Pieces), Specs = [Spec] ). %---------------------------------------------------------------------------% report_indistinguishable_modes_error(ModuleInfo, OldProcId, NewProcId, PredId, PredInfo) = Spec :- pred_info_get_proc_table(PredInfo, Procs), map.lookup(Procs, OldProcId, OldProcInfo), map.lookup(Procs, NewProcId, NewProcInfo), proc_info_get_context(OldProcInfo, OldContext), proc_info_get_context(NewProcInfo, NewContext), MainPieces = [words("In mode declarations for ")] ++ describe_one_pred_name(ModuleInfo, should_module_qualify, PredId) ++ [suffix(":"), nl, words("error: duplicate mode declaration."), nl], VerbosePieces = [words("Modes"), words_quote(mode_decl_to_string(output_mercury, OldProcId, PredInfo)), words("and"), words_quote(mode_decl_to_string(output_mercury, NewProcId, PredInfo)), words("are indistinguishable.")], OldPieces = [words("Here is the conflicting mode declaration.")], Spec = error_spec($pred, severity_error, phase_mode_check(report_in_any_mode), [simple_msg(NewContext, [always(MainPieces), verbose_only(verbose_always, VerbosePieces)]), simplest_msg(OldContext, OldPieces)]). %---------------------------------------------------------------------------% report_mode_inference_messages_for_preds(_, _, [], !Specs). report_mode_inference_messages_for_preds(ModuleInfo, OutputDetism, [PredId | PredIds], !Specs) :- module_info_pred_info(ModuleInfo, PredId, PredInfo), pred_info_get_markers(PredInfo, Markers), ( if check_marker(Markers, marker_infer_modes) then ProcIds = pred_info_all_procids(PredInfo), pred_info_get_proc_table(PredInfo, Procs), report_mode_inference_messages_for_procs(ModuleInfo, OutputDetism, PredInfo, Procs, ProcIds, !Specs) else true ), report_mode_inference_messages_for_preds(ModuleInfo, OutputDetism, PredIds, !Specs). % Generate the inferred `mode' declarations for a list of proc_ids. % :- pred report_mode_inference_messages_for_procs(module_info::in, include_detism_on_modes::in, pred_info::in, proc_table::in, list(proc_id)::in, list(error_spec)::in, list(error_spec)::out) is det. report_mode_inference_messages_for_procs(_, _, _, _, [], !Specs). report_mode_inference_messages_for_procs(ModuleInfo, OutputDetism, PredInfo, Procs, [ProcId | ProcIds], !Specs) :- module_info_get_globals(ModuleInfo, Globals), globals.lookup_bool_option(Globals, verbose_errors, VerboseErrors), map.lookup(Procs, ProcId, ProcInfo), ( if ( % We always output `Inferred :- mode ...' proc_info_is_valid_mode(ProcInfo) ; % We only output `REJECTED :- mode ...' % if --verbose-errors is enabled VerboseErrors = yes ) then Spec = report_mode_inference_message(ModuleInfo, OutputDetism, PredInfo, ProcInfo), !:Specs = [Spec | !.Specs] else true ), report_mode_inference_messages_for_procs(ModuleInfo, OutputDetism, PredInfo, Procs, ProcIds, !Specs). % Return a description of the inferred mode declaration for the given % predicate or function. % :- func report_mode_inference_message(module_info, include_detism_on_modes, pred_info, proc_info) = error_spec. report_mode_inference_message(ModuleInfo, OutputDetism, PredInfo, ProcInfo) = Spec :- PredName = pred_info_name(PredInfo), Name = unqualified(PredName), pred_info_get_context(PredInfo, Context), PredArity = pred_info_orig_arity(PredInfo), some [!ArgModes, !MaybeDet] ( proc_info_get_argmodes(ProcInfo, !:ArgModes), % We need to strip off the extra type_info arguments inserted at the % front by polymorphism.m - we only want the last `PredArity' of them. % list.length(!.ArgModes, NumArgModes), NumToDrop = NumArgModes - PredArity, ( if list.drop(NumToDrop, !ArgModes) then true else unexpected($pred, "list.drop failed") ), varset.init(VarSet), PredOrFunc = pred_info_is_pred_or_func(PredInfo), ( OutputDetism = include_detism_on_modes, proc_info_get_inferred_determinism(ProcInfo, Detism), !:MaybeDet = yes(Detism) ; OutputDetism = do_not_include_detism_on_modes, !:MaybeDet = no ), ( if proc_info_is_valid_mode(ProcInfo) then Verb = "Inferred" else Verb = "REJECTED", % Replace the final insts with dummy insts '...', since they % won't be valid anyway -- they are just the results of whatever % partial inference we did before detecting the error. mode_list_get_initial_insts(ModuleInfo, !.ArgModes, InitialInsts), DummyInst = defined_inst(user_inst(unqualified("..."), [])), list.duplicate(PredArity, DummyInst, FinalInsts), !:ArgModes = list.map(func(I - F) = from_to_mode(I, F), assoc_list.from_corresponding_lists(InitialInsts, FinalInsts)), % Likewise delete the determinism. !:MaybeDet = no ), strip_builtin_qualifiers_from_mode_list(!ArgModes), ( PredOrFunc = pf_predicate, MaybeWithInst = maybe.no, Detail = mercury_pred_mode_decl_to_string(output_debug, VarSet, Name, !.ArgModes, MaybeWithInst, !.MaybeDet) ; PredOrFunc = pf_function, pred_args_to_func_args(!.ArgModes, FuncArgModes, RetMode), Detail = mercury_func_mode_decl_to_string(output_debug, VarSet, Name, FuncArgModes, RetMode, !.MaybeDet) ), Pieces = [words(Verb), words(Detail), nl], Spec = conditional_spec($pred, inform_inferred_modes, yes, severity_informational, phase_mode_check(report_in_any_mode), [simplest_msg(Context, Pieces)]) ). %---------------------------------------------------------------------------% mode_decl_to_string(Lang, ProcId, PredInfo) = String :- PredOrFunc = pred_info_is_pred_or_func(PredInfo), Name0 = pred_info_name(PredInfo), Name = unqualified(Name0), pred_info_get_proc_table(PredInfo, Procs), map.lookup(Procs, ProcId, ProcInfo), proc_info_declared_argmodes(ProcInfo, Modes0), proc_info_get_declared_determinism(ProcInfo, MaybeDet), varset.init(InstVarSet), strip_builtin_qualifiers_from_mode_list(Modes0, Modes), String = mercury_mode_subdecl_to_string(Lang, PredOrFunc, InstVarSet, Name, Modes, MaybeDet). %---------------------------------------------------------------------------% mode_error_info_to_spec(ModeInfo0, ModeErrorInfo) = Spec :- some [!ModeInfo] ( !:ModeInfo = ModeInfo0, ModeErrorInfo = mode_error_info(_, ModeError, Context, ModeContext), mode_info_set_context(Context, !ModeInfo), mode_info_set_mode_context(ModeContext, !ModeInfo), Spec = mode_error_to_spec(!.ModeInfo, ModeError) ). :- func mode_error_to_spec(mode_info, mode_error) = error_spec. mode_error_to_spec(ModeInfo, ModeError) = Spec :- ( ModeError = mode_error_disj(MergeContext, MergeErrors), Spec = mode_error_disj_to_spec(ModeInfo, MergeContext, MergeErrors) ; ModeError = mode_error_par_conj(MergeErrors), Spec = mode_error_par_conj_to_spec(ModeInfo, MergeErrors) ; ModeError = mode_error_higher_order_pred_var(PredOrFunc, Var, Inst, Arity), Spec = mode_error_higher_order_pred_var_to_spec(ModeInfo, PredOrFunc, Var, Inst, Arity) ; ModeError = mode_error_poly_unify(Var, Inst), Spec = mode_error_poly_unify_to_spec(ModeInfo, Var, Inst) ; ModeError = mode_error_var_is_live(Var), Spec = mode_error_var_is_live_to_spec(ModeInfo, Var) ; ModeError = mode_error_var_has_inst(Var, InstA, InstB, MaybeMultiMode), Spec = mode_error_var_has_inst_to_spec(ModeInfo, Var, InstA, InstB, MaybeMultiMode) ; ModeError = mode_error_unify_pred(Var, RHS, Type, PredOrFunc), Spec = mode_error_unify_pred_to_spec(ModeInfo, Var, RHS, Type, PredOrFunc) ; ModeError = mode_error_implied_mode(Var, InstA, InstB), Spec = mode_error_implied_mode_to_spec(ModeInfo, Var, InstA, InstB) ; ModeError = mode_error_no_mode_decl, Spec = mode_error_no_mode_decl_to_spec(ModeInfo) ; ModeError = mode_error_bind_var(Reason, Var, InstA, InstB), Spec = mode_error_bind_var_to_spec(ModeInfo, Reason, Var, InstA, InstB) ; ModeError = mode_error_non_local_lambda_var(Var, Inst), Spec = mode_error_non_local_lambda_var_to_spec(ModeInfo, Var, Inst) ; ModeError = mode_error_unify_var_var(VarA, VarB, InstA, InstB), Spec = mode_error_unify_var_var_to_spec(ModeInfo, VarA, VarB, InstA, InstB) ; ModeError = mode_error_unify_var_lambda(VarA, InstA, InstB), Spec = mode_error_unify_var_lambda_to_spec(ModeInfo, VarA, InstA, InstB) ; ModeError = mode_error_unify_var_multimode_pred(VarA, PredId, MultiModeError), Spec = mode_error_unify_var_multimode_pred_to_spec(ModeInfo, VarA, PredId, MultiModeError) ; ModeError = mode_error_unify_var_functor(Var, Name, Args, Inst, ArgInsts), Spec = mode_error_unify_var_functor_to_spec(ModeInfo, Var, Name, Args, Inst, ArgInsts) ; ModeError = mode_error_conj(Errors, Culprit), Spec = mode_error_conj_to_spec(ModeInfo, Errors, Culprit) ; ModeError = mode_error_no_matching_mode(Vars, Insts, InitialInsts), Spec = mode_error_no_matching_mode_to_spec(ModeInfo, Vars, Insts, InitialInsts) ; ModeError = mode_error_in_callee(Vars, Insts, CalleePredId, CalleeProcId, CalleeErrors), Spec = mode_error_in_callee_to_spec(ModeInfo, Vars, Insts, CalleePredId, CalleeProcId, CalleeErrors) ; ModeError = mode_error_final_inst(ArgNum, Var, VarInst, Inst, Reason), Spec = mode_error_final_inst_to_spec(ModeInfo, ArgNum, Var, VarInst, Inst, Reason) ; ModeError = purity_error_should_be_in_promise_purity_scope(NegCtxt, Var), Spec = purity_error_should_be_in_promise_purity_scope_to_spec(NegCtxt, ModeInfo, Var) ; ModeError = purity_error_lambda_should_be_any(Vars), Spec = purity_error_lambda_should_be_any_to_spec(ModeInfo, Vars) ). mode_warning_info_to_spec(!.ModeInfo, Warning) = Spec :- Warning = mode_warning_info(ModeWarning, Context, ModeContext), mode_info_set_context(Context, !ModeInfo), mode_info_set_mode_context(ModeContext, !ModeInfo), ( ModeWarning = cannot_succeed_var_var(VarA, VarB, InstA, InstB), Spec = mode_warning_cannot_succeed_var_var(!.ModeInfo, VarA, VarB, InstA, InstB) ; ModeWarning = cannot_succeed_var_functor(Var, Inst, ConsId), Spec = mode_warning_cannot_succeed_var_functor(!.ModeInfo, Var, Inst, ConsId) ; ModeWarning = cannot_succeed_ground_occur_check(Var, ConsId), Spec = mode_warning_cannot_succeed_ground_occur_check(!.ModeInfo, Var, ConsId) ). %---------------------------------------------------------------------------% :- func mode_error_conj_to_spec(mode_info, list(delayed_goal), schedule_culprit) = error_spec. mode_error_conj_to_spec(ModeInfo, Errors, Culprit) = Spec :- mode_info_get_context(ModeInfo, Context), ( Errors = [], unexpected($pred, "no errors") ; Errors = [Error], Msgs1 = mode_error_conjunct_to_msgs(Context, ModeInfo, Error) ; Errors = [_, _ | _], % If there is more than one error, we use the setting of % --verbose-errors to decide between reporting just one and % reporting them all. Unfortunately, We can't use the % verbose_and_nonverbose functor of the error_msg_component type % to package up the two cases, because we need to package up % multiple messages, each with its own context. list.filter(is_error_important, Errors, ImportantErrors, OtherErrors), mode_info_get_module_info(ModeInfo, ModuleInfo), module_info_get_globals(ModuleInfo, Globals), globals.lookup_bool_option(Globals, verbose_errors, VerboseErrors), ( VerboseErrors = no, % In the absence of --verbose-errors, report only one error. % We prefer that this be an important error. ( ImportantErrors = [FirstImportantError | _], ConjMsgs = mode_error_conjunct_to_msgs(Context, ModeInfo, FirstImportantError) ; ImportantErrors = [], ( OtherErrors = [FirstOtherError | _], ConjMsgs = mode_error_conjunct_to_msgs(Context, ModeInfo, FirstOtherError) ; OtherErrors = [], unexpected($pred, "no errors of any kind") ) ), % MoreMsg is there to indicate that --verbose-errors would yield % more information. MoreMsg = simple_msg(Context, [verbose_only(verbose_always, [])]), Msgs1 = ConjMsgs ++ [MoreMsg] ; VerboseErrors = yes, Preamble = mode_info_context_preamble(ModeInfo), ConjPieces = [words("mode error in conjunction. The next"), fixed(int_to_string(list.length(Errors))), words("error messages indicate"), words("possible causes of this error.")], Msgs1Start = [simplest_msg(Context, Preamble ++ ConjPieces)], Msgs1Rest0 = list.map( mode_error_conjunct_to_msgs(Context, ModeInfo), ImportantErrors ++ OtherErrors), Msgs1Rest = list.map(prefix_with_blank_line(Context), Msgs1Rest0), Msgs1 = Msgs1Start ++ list.condense(Msgs1Rest) ) ), % If the goal(s) couldn't be scheduled because we couldn't reorder things % past an impure goal, then report that. ( Culprit = conj_floundered, % We have already reported everything we can. Msgs2 = [] ; Culprit = goal_itself_was_impure, Pieces = [words("The goal could not be reordered,"), words("because it was impure.")], Msgs2 = [simplest_msg(Context, Pieces)] ; Culprit = goals_followed_by_impure_goal(ImpureGoal), ImpureGoal = hlds_goal(_, ImpureGoalInfo), ImpureGoalContext = goal_info_get_context(ImpureGoalInfo), Pieces1 = [words("The goal could not be reordered,"), words("because it was followed by an impure goal.")], Pieces2 = [words("This is the location of the impure goal.")], Msgs2 = [simplest_msg(Context, Pieces1), simplest_msg(ImpureGoalContext, Pieces2)] ), Spec = error_spec($pred, severity_error, phase_mode_check(report_in_any_mode), Msgs1 ++ Msgs2). :- func prefix_with_blank_line(prog_context, list(error_msg)) = list(error_msg). prefix_with_blank_line(Context, Msgs) = [BlankMsg | Msgs] :- BlankMsg = simplest_msg(Context, [blank_line]). :- pred is_error_important(delayed_goal::in) is semidet. is_error_important(Error) :- Error = delayed_goal(_, mode_error_info(_, ModeError, _, ModeContext), _), ( if % An error is important unless it is a non-explicit unification, % i.e. a head unification or a call argument unification. ModeContext = mode_context_unify(unify_context(UnifyContext, _), _), UnifyContext \= umc_explicit, % Except that errors in lambda goals are important even if the % unification that creates the lambda goal is an implicit one. ModeError \= mode_error_non_local_lambda_var(_, _) then fail else true ). :- func mode_error_conjunct_to_msgs(prog_context, mode_info, delayed_goal) = list(error_msg). mode_error_conjunct_to_msgs(Context, !.ModeInfo, DelayedGoal) = Msgs :- mode_info_get_module_info(!.ModeInfo, ModuleInfo), module_info_get_globals(ModuleInfo, Globals), DelayedGoal = delayed_goal(Vars, Error, Goal), Error = mode_error_info(_, ModeError, ErrorContext, ModeContext), mode_info_set_context(ErrorContext, !ModeInfo), mode_info_set_mode_context(ModeContext, !ModeInfo), SubSpec0 = mode_error_to_spec(!.ModeInfo, ModeError), extract_spec_msgs(Globals, SubSpec0, SubMsgs), globals.lookup_bool_option(Globals, debug_modes, DebugModes), ( DebugModes = no, Msgs = SubMsgs ; DebugModes = yes, set_of_var.to_sorted_list(Vars, VarList), mode_info_get_varset(!.ModeInfo, VarSet), VarNames = mercury_vars_to_name_only(VarSet, VarList), Pieces1 = [words("Floundered goal, waiting on {"), words(VarNames), words("}:"), nl], Msg1 = simplest_msg(Context, Pieces1), % XXX Shouldn't we check debug_modes_verbose instead of very_verbose? globals.lookup_bool_option(Globals, very_verbose, VeryVerbose), ( VeryVerbose = no, Msgs = [Msg1] ++ SubMsgs ; VeryVerbose = yes, Pieces2 = [always([nl]), 'new print_anything'( write_indented_goal(ModuleInfo, VarSet, Goal))], Msg2 = error_msg(no, do_not_treat_as_first, 0, Pieces2), Msgs = [Msg1, Msg2] ++ SubMsgs ) ). :- type write_indented_goal ---> write_indented_goal(module_info, prog_varset, hlds_goal). :- instance error_util.print_anything(write_indented_goal) where [ ( print_anything(write_indented_goal(ModuleInfo, VarSet, Goal), !IO) :- io.write_string("\t\t", !IO), module_info_get_globals(ModuleInfo, Globals), OutInfo = init_hlds_out_info(Globals, output_debug), write_goal(OutInfo, ModuleInfo, VarSet, print_name_only, 2, ".\n", Goal, !IO) ) ]. %---------------------------------------------------------------------------% :- func mode_error_disj_to_spec(mode_info, merge_context, list(merge_error)) = error_spec. mode_error_disj_to_spec(ModeInfo, MergeContext, MergeErrors) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), MainPieces = [words("mode mismatch in "), words(merge_context_to_string(MergeContext)), suffix("."), nl], MergeMsgLists = list.map( merge_error_to_msgs(ModeInfo, Context, is_disjunctive), MergeErrors), list.condense(MergeMsgLists, MergeMsgs), Spec = error_spec($pred, severity_error, phase_mode_check(report_in_any_mode), [simplest_msg(Context, Preamble ++ MainPieces) | MergeMsgs]). :- func mode_error_par_conj_to_spec(mode_info, list(merge_error)) = error_spec. mode_error_par_conj_to_spec(ModeInfo, MergeErrors) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), MainPieces = [words("mode error: mutually exclusive bindings"), words("in parallel conjunction."), words("(The current implementation does not permit"), words("parallel conjunctions to fail.)"), nl], MergeMsgLists = list.map( merge_error_to_msgs(ModeInfo, Context, is_not_disjunctive), MergeErrors), list.condense(MergeMsgLists, MergeMsgs), Spec = error_spec($pred, severity_error, phase_mode_check(report_in_any_mode), [simplest_msg(Context, Preamble ++ MainPieces) | MergeMsgs]). %---------------------% :- func merge_context_to_string(merge_context) = string. merge_context_to_string(merge_disj) = "disjunction". merge_context_to_string(merge_if_then_else) = "if-then-else". merge_context_to_string(merge_stm_atomic) = "atomic". %---------------------% :- type maybe_is_disjunctive ---> is_not_disjunctive ; is_disjunctive. :- func merge_error_to_msgs(mode_info, prog_context, maybe_is_disjunctive, merge_error) = list(error_msg). merge_error_to_msgs(ModeInfo, MainContext, IsDisjunctive, MergeError) = Msgs :- MergeError = merge_error(Var, ContextsInsts0), mode_info_get_module_info(ModeInfo, ModuleInfo), mode_info_get_varset(ModeInfo, VarSet), VarNamePiece = quote(mercury_var_to_name_only(VarSet, Var)), list.sort(ContextsInsts0, ContextsInsts), count_ground_insts(ModuleInfo, ContextsInsts, 0, NumGroundInsts, 0, NumAllInsts), ( if IsDisjunctive = is_disjunctive, NumGroundInsts < NumAllInsts, NumGroundInsts * 2 > NumAllInsts then % More than half the insts are ground, so it is likely that they % were *all* intended to be ground, but not all actually *are* ground, % which is likely to be the bug. CommonPieces = [words("The variable"), VarNamePiece, words("is ground"), words("in"), int_fixed(NumGroundInsts), words("out of"), int_fixed(NumAllInsts), words("branches."), nl], VerbosePieces = [words("It has the following instantiation states."), nl], ( if NumAllInsts - NumGroundInsts > 1 then NonVerbosePieces = [words("It has non-ground instantiation states"), words("in the following branches."), nl] else % The message for the non-ground branch will *say* % it is for such a branch. NonVerbosePieces = [] ), VarMsg = simple_msg(MainContext, [always(CommonPieces), verbose_and_nonverbose(VerbosePieces, NonVerbosePieces)]), InstMsgs = list.map( report_inst_in_context(ModeInfo, VarNamePiece, report_inst_and_ground_vs_nonground), ContextsInsts), Msgs = [VarMsg | InstMsgs] else if IsDisjunctive = is_disjunctive, 0 < NumGroundInsts, NumGroundInsts < NumAllInsts then VarPieces = [words("The variable"), VarNamePiece, words("is ground in some branches but not others."), nl], VarMsg = simplest_msg(MainContext, VarPieces), InstMsgs = list.map( report_inst_in_context(ModeInfo, VarNamePiece, report_ground_vs_nonground_only), ContextsInsts), Msgs = [VarMsg | InstMsgs] else VarPieces = [words("The variable"), VarNamePiece, words("has the following instantiation states."), nl], VarMsg = simplest_msg(MainContext, VarPieces), InstMsgs = list.map( report_inst_in_context(ModeInfo, VarNamePiece, report_inst_only), ContextsInsts), Msgs = [VarMsg | InstMsgs] ). %---------------------% :- pred count_ground_insts(module_info::in, assoc_list(prog_context, mer_inst)::in, int::in, int::out, int::in, int::out) is det. count_ground_insts(_ModuleInfo, [], !NumGroundInsts, !NumAllInsts). count_ground_insts(ModuleInfo, [ContextInst | ContextsInsts], !NumGroundInsts, !NumAllInsts) :- ContextInst = _Context - Inst, ( if inst_is_ground(ModuleInfo, Inst) then !:NumGroundInsts = !.NumGroundInsts + 1 else true ), !:NumAllInsts = !.NumAllInsts + 1, count_ground_insts(ModuleInfo, ContextsInsts, !NumGroundInsts, !NumAllInsts). %---------------------% :- type report_inst_how ---> report_inst_only ; report_ground_vs_nonground_only ; report_inst_and_ground_vs_nonground. :- func report_inst_in_context(mode_info, format_component, report_inst_how, pair(prog_context, mer_inst)) = error_msg. report_inst_in_context(ModeInfo, VarNamePiece, ReportIsGround, Context - Inst) = Msg :- ( ReportIsGround = report_inst_only, Pieces = report_inst_in_branch(ModeInfo, VarNamePiece, no, Inst), Msg = simplest_msg(Context, Pieces) ; ReportIsGround = report_ground_vs_nonground_only, mode_info_get_module_info(ModeInfo, ModuleInfo), ( if inst_is_ground(ModuleInfo, Inst) then Pieces = report_inst_in_branch_simple(VarNamePiece, "ground") else if ( Inst = free ; Inst = free(_) ) then Pieces = report_inst_in_branch_simple(VarNamePiece, "free") else Pieces = report_inst_in_branch_simple(VarNamePiece, "not ground") ), Msg = simplest_msg(Context, Pieces) ; ReportIsGround = report_inst_and_ground_vs_nonground, mode_info_get_module_info(ModeInfo, ModuleInfo), ( if inst_is_ground(ModuleInfo, Inst) then Pieces = report_inst_in_branch(ModeInfo, VarNamePiece, yes(ground), Inst), Msg = simple_msg(Context, [verbose_and_nonverbose(Pieces, [])]) else Pieces = report_inst_in_branch(ModeInfo, VarNamePiece, yes(nonground), Inst), Msg = simplest_msg(Context, Pieces) ) ). :- type ground_or_nonground ---> ground ; nonground. :- func report_inst_in_branch(mode_info, format_component, maybe(ground_or_nonground), mer_inst) = list(format_component). report_inst_in_branch(ModeInfo, VarNamePiece, MaybeGroundOrNonGround, Inst) = Pieces :- ( MaybeGroundOrNonGround = no, ( if Inst = ground(shared, none_or_default_func) then Pieces = report_inst_in_branch_simple(VarNamePiece, "ground") else if ( Inst = free ; Inst = free(_) ) then Pieces = report_inst_in_branch_simple(VarNamePiece, "free") else IntroPieces = [words("In this branch,"), VarNamePiece, words("has instantiatedness")], Pieces = report_inst_in_branch_detail(ModeInfo, IntroPieces, Inst) ) ; MaybeGroundOrNonGround = yes(ground), ( if Inst = ground(shared, none_or_default_func) then Pieces = report_inst_in_branch_simple(VarNamePiece, "ground") else IntroPieces = [words("In this branch,"), VarNamePiece, words("has the ground instantiatedness")], Pieces = report_inst_in_branch_detail(ModeInfo, IntroPieces, Inst) ) ; MaybeGroundOrNonGround = yes(nonground), ( if ( Inst = free ; Inst = free(_) ) then Pieces = report_inst_in_branch_simple(VarNamePiece, "free") else IntroPieces = [words("In this branch,"), VarNamePiece, words("has the non-ground instantiatedness")], Pieces = report_inst_in_branch_detail(ModeInfo, IntroPieces, Inst) ) ). :- func report_inst_in_branch_simple(format_component, string) = list(format_component). report_inst_in_branch_simple(VarNamePiece, FreeOrGround) = Pieces :- MainPieces = [words("In this branch,"), VarNamePiece, words("is"), words(FreeOrGround), suffix("."), nl], Pieces = [nl_indent_delta(1) | MainPieces] ++ [nl_indent_delta(-1)]. :- func report_inst_in_branch_detail(mode_info, list(format_component), mer_inst) = list(format_component). report_inst_in_branch_detail(ModeInfo, IntroPieces, Inst) = Pieces :- Pieces = [nl_indent_delta(1) | IntroPieces] ++ [nl_indent_delta(1) | report_inst(ModeInfo, fixed_short_inst, [suffix("."), nl_indent_delta(-2)], [], [suffix("."), nl_indent_delta(-2)], Inst)]. %---------------------------------------------------------------------------% :- func mode_error_bind_var_to_spec(mode_info, var_lock_reason, prog_var, mer_inst, mer_inst) = error_spec. mode_error_bind_var_to_spec(ModeInfo, Reason, Var, VarInst, Inst) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), ( Reason = var_lock_negation, ReasonStr = "attempt to bind a non-local variable inside a negation." ; Reason = var_lock_if_then_else, ReasonStr = "attempt to bind a non-local variable" ++ " inside the condition of an if-then-else." ; Reason = var_lock_lambda(PredOrFunc), PredOrFuncS = prog_out.pred_or_func_to_str(PredOrFunc), ReasonStr = "attempt to bind a non-local variable inside" ++ " a " ++ PredOrFuncS ++ " lambda goal." ; Reason = var_lock_trace_goal, ReasonStr = "attempt to bind a non-local variable inside a trace goal." ; Reason = var_lock_atomic_goal, ReasonStr = "attempt to bind outer state variables inside an " ++ "atomic goal." ; Reason = var_lock_par_conj, ReasonStr = "attempt to bind a non-local variable" ++ " inside more than one parallel conjunct." ), MainPieces = [words("scope error:"), words(ReasonStr), nl, words("Variable"), quote(mercury_var_to_name_only(VarSet, Var)) | has_inst_expected_inst_was(ModeInfo, VarInst, Inst)], ( Reason = var_lock_negation, VerbosePieces = [words("A negation is only allowed to bind variables"), words("which are local to the negation, i.e. those which are"), words("implicitly existentially quantified"), words("inside the scope of the negation."), nl] ; Reason = var_lock_if_then_else, VerbosePieces = [words("The condition of an if-then-else is only"), words("allowed to bind variables which are local to the"), words("condition or which occur only in the condition"), words("and the"), quote("then"), words("part."), nl] ; Reason = var_lock_lambda(_), VerbosePieces = [words("A lambda goal is only allowed to bind"), words("its arguments and variables local to the "), words("lambda expression."), nl] ; Reason = var_lock_trace_goal, VerbosePieces = [words("A trace goal is only allowed to bind variables"), words("which are local to the trace goal."), nl] ; Reason = var_lock_atomic_goal, VerbosePieces = [words("An atomic goal may not use the state variables"), words("belonging to the outer scope."), nl] ; Reason = var_lock_par_conj, VerbosePieces = [words("A nonlocal variable of a parallel conjunction"), words("may be bound in at most one conjunct."), nl] ), Spec = error_spec($pred, severity_error, phase_mode_check(report_in_any_mode), [simple_msg(Context, [always(Preamble ++ MainPieces), verbose_only(verbose_always, VerbosePieces)])]). %---------------------------------------------------------------------------% :- func mode_error_non_local_lambda_var_to_spec(mode_info, prog_var, mer_inst) = error_spec. mode_error_non_local_lambda_var_to_spec(ModeInfo, Var, VarInst) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), Pieces = [words("mode error: variable"), quote(mercury_var_to_name_only(VarSet, Var)) | has_instantiatedness(ModeInfo, VarInst, ",")] ++ [words("expected instantiatedness for non-local variables"), words("of lambda goals is"), quote("ground"), suffix("."), nl], Spec = simplest_spec($pred, severity_error, phase_mode_check(report_in_any_mode), Context, Preamble ++ Pieces). %---------------------------------------------------------------------------% :- func mode_error_in_callee_to_spec(mode_info, list(prog_var), list(mer_inst), pred_id, proc_id, list(mode_error_info)) = error_spec. mode_error_in_callee_to_spec(!.ModeInfo, Vars, Insts, CalleePredId, CalleeProcId, CalleeModeErrors) = Spec :- Preamble = mode_info_context_preamble(!.ModeInfo), mode_info_get_module_info(!.ModeInfo, ModuleInfo), mode_info_get_context(!.ModeInfo, Context), mode_info_get_varset(!.ModeInfo, VarSet), ( Vars = [], unexpected($pred, "Vars = []") ; Vars = [Var], MainPieces = [words("mode error: argument"), quote(mercury_var_to_name_only(VarSet, Var)), words("has the following inst:"), nl_indent_delta(1)] ; Vars = [_, _ | _], MainPieces = [words("mode error: arguments"), quote(mercury_vars_to_name_only(VarSet, Vars)), words("have the following insts:"), nl_indent_delta(1)] ), NoMatchPieces = inst_list_to_sep_lines(!.ModeInfo, Insts) ++ [words("which does not match any of the valid modes for")], CalleePredIdPieces = describe_one_pred_name(ModuleInfo, should_module_qualify, CalleePredId), VerboseCalleePieces = [words("the callee"), prefix("(")] ++ CalleePredIdPieces ++ [suffix(")"), nl, words("because of the following error."), nl], VerbosePieces = MainPieces ++ NoMatchPieces ++ VerboseCalleePieces, NonVerboseCalleePieces = [words("the callee, because of the following error."), nl], NonVerbosePieces = MainPieces ++ NoMatchPieces ++ NonVerboseCalleePieces, InitMsg = simple_msg(Context, [always(Preamble), verbose_and_nonverbose(VerbosePieces, NonVerbosePieces)]), ( CalleeModeErrors = [First | _], First = mode_error_info(_, CalleeModeError, CalleeContext, CalleeModeContext), mode_info_set_pred_id(CalleePredId, !ModeInfo), mode_info_set_proc_id(CalleeProcId, !ModeInfo), mode_info_set_context(CalleeContext, !ModeInfo), mode_info_set_mode_context(CalleeModeContext, !ModeInfo), CalleeModeErrorSpec0 = mode_error_to_spec(!.ModeInfo, CalleeModeError), module_info_get_globals(ModuleInfo, Globals), extract_spec_msgs(Globals, CalleeModeErrorSpec0, LaterMsgs0), ( LaterMsgs0 = [], LaterMsgs = [] ; LaterMsgs0 = [LaterHead0 | LaterTail], ( LaterHead0 = simplest_msg(LaterContext, Pieces), LaterHead = error_msg(yes(LaterContext), treat_as_first, 0, [always(Pieces)]) ; LaterHead0 = simple_msg(LaterContext, Components), LaterHead = error_msg(yes(LaterContext), treat_as_first, 0, Components) ; LaterHead0 = error_msg(MaybeLaterContext, _, Indent, Components), LaterHead = error_msg(MaybeLaterContext, treat_as_first, Indent, Components) ), LaterMsgs = [LaterHead | LaterTail] ), Spec = error_spec($pred, severity_error, phase_mode_check(report_in_any_mode), [InitMsg | LaterMsgs]) ; CalleeModeErrors = [], unexpected($pred, "no error") ). %---------------------------------------------------------------------------% :- func mode_error_no_matching_mode_to_spec(mode_info, list(prog_var), list(mer_inst), list(list(mer_inst))) = error_spec. mode_error_no_matching_mode_to_spec(ModeInfo, Vars, Insts, InitialInsts) = Spec :- list.length(Vars, NumVars), list.length(Insts, NumInsts), expect(unify(NumVars, NumInsts), $pred, "NumVars != NumInsts"), PrefixPieces = mode_info_context_preamble(ModeInfo) ++ [words("mode error:")], mode_info_get_mode_context(ModeInfo, ModeContext), mode_info_get_module_info(ModeInfo, ModuleInfo), ( ModeContext = mode_context_call(ModeCallId, _), ( ModeCallId = mode_call_generic(GenericCallId), CallId = generic_call_id(GenericCallId), ( GenericCallId = gcid_higher_order(_, PredOrFunc, _) ; GenericCallId = gcid_class_method(_, PFSymNameArity), PFSymNameArity = pf_sym_name_arity(PredOrFunc, _, _) ; ( GenericCallId = gcid_event_call(_) ; GenericCallId = gcid_cast(_) ), PredOrFunc = pf_predicate ), % XXX Setting NumExtra to 0 means that we do not separate out % any arguments added by polymorphism.m. Since most higher order % values are monomorphic, this should not be too much of a loss. % If and when it becomes one, this should be fixed. NumExtra = 0 ; ModeCallId = mode_call_plain(PredId), mode_info_get_pf_sym_name_arity(ModeInfo, PredId, PFSymNameArity), CallId = plain_call_id(PFSymNameArity), module_info_pred_info(ModuleInfo, PredId, PredInfo), pred_info_get_orig_arity(PredInfo, OrigArity), PredOrFunc = pred_info_is_pred_or_func(PredInfo), NumExtra = NumVars - OrigArity ) ; ( ModeContext = mode_context_unify(_, _) ; ModeContext = mode_context_uninitialized ), unexpected($pred, "invalid context") ), ( if NumExtra > 0 then % The callee's argument list contains extra typeinfo and/or % typeclass_info arguments added by polymorphism.m. Usually, % these extra arguments are all already ground, which means that % they cannot be insufficiently instantiated. And since users cannot % require them to have any inst more specific than ground, they % cannot be the cause of any mode errors. This is why we do not % report their instantiations. % % In the unusual case that some extra variable is *not* ground, % they *could* possibly be the cause of a mode error, so we *do* list % their instantiation states, but we do so separately, in an effort % to avoid confusing users. list.det_split_list(NumExtra, Vars, ExtraVars, UserVars), list.det_split_list(NumExtra, Insts, ExtraInsts, UserInsts), UserArgPieces = [words("argument")], UserVarInstPieces = arg_inst_mismatch_pieces(ModeInfo, UserArgPieces, PredOrFunc, UserVars, UserInsts), ( if list.all_true(inst_is_ground(ModuleInfo), ExtraInsts) then VarListInstPieces = UserVarInstPieces else ExtraArgPieces = [words("the compiler-generated argument")], ExtraVarInstPieces = arg_inst_mismatch_pieces(ModeInfo, ExtraArgPieces, pf_predicate, ExtraVars, ExtraInsts), VarListInstPieces = ExtraVarInstPieces ++ UserVarInstPieces ) else UserArgPieces = [words("argument")], VarListInstPieces = arg_inst_mismatch_pieces(ModeInfo, UserArgPieces, PredOrFunc, Vars, Insts) ), NoMatchPieces = [words("which does not match any of the modes for"), words(call_id_to_string(CallId)), suffix("."), nl], mode_info_get_var_types(ModeInfo, VarTypes), construct_argnum_var_type_inst_tuples(VarTypes, Vars, Insts, 1, ArgTuples), find_satisfied_initial_insts_in_procs(ModuleInfo, ArgTuples, InitialInsts, 0, map.init, ArgNumMatchedProcs), report_any_never_matching_args(ModeInfo, ArgNumMatchedProcs, NumExtra, ArgTuples, BadArgPieces), Pieces = PrefixPieces ++ VarListInstPieces ++ NoMatchPieces ++ BadArgPieces, mode_info_get_context(ModeInfo, Context), Spec = simplest_spec($pred, severity_error, phase_mode_check(report_in_any_mode), Context, Pieces). %---------------------% :- func arg_inst_mismatch_pieces(mode_info, list(format_component), pred_or_func, list(prog_var), list(mer_inst)) = list(format_component). arg_inst_mismatch_pieces(ModeInfo, ArgPieces, PredOrFunc, Vars, Insts) = Pieces :- mode_info_get_varset(ModeInfo, VarSet), ( Vars = [], Pieces = [] ; Vars = [HeadVar | TailVars], ( PredOrFunc = pf_predicate, ( TailVars = [], Pieces = ArgPieces ++ [quote(mercury_var_to_name_only(VarSet, HeadVar)), words("has the following inst:"), nl_indent_delta(1)] ++ inst_list_to_sep_lines(ModeInfo, Insts) % inst_list_to_sep_lines does nl_indent_delta(-1). ; TailVars = [_ | _], Pieces = ArgPieces ++ [suffix("s"), quote(mercury_vars_to_name_only(VarSet, Vars)), words("have the following insts:"), nl_indent_delta(1)] ++ inst_list_to_sep_lines(ModeInfo, Insts) % inst_list_to_sep_lines does nl_indent_delta(-1). ) ; PredOrFunc = pf_function, list.det_split_last(Vars, ArgVars, ReturnVar), ( ArgVars = [], Pieces = [words("the return value"), quote(mercury_var_to_name_only(VarSet, ReturnVar)), words("has the following inst:"), nl_indent_delta(1)] ++ inst_list_to_sep_lines(ModeInfo, Insts) % inst_list_to_sep_lines does nl_indent_delta(-1). ; ( ArgVars = [_], SuffixPieces = [] ; ArgVars = [_, _ | _], SuffixPieces = [suffix("s")] ), Pieces = ArgPieces ++ SuffixPieces ++ [quote(mercury_vars_to_name_only(VarSet, ArgVars)), words("and the return value"), quote(mercury_var_to_name_only(VarSet, ReturnVar)), words("have the following insts:"), nl_indent_delta(1)] ++ inst_list_to_sep_lines(ModeInfo, Insts) % inst_list_to_sep_lines does nl_indent_delta(-1). ) ) ). %---------------------% :- type argnum_var_type_inst ---> argnum_var_type_inst(int, prog_var, mer_type, mer_inst). :- pred construct_argnum_var_type_inst_tuples(vartypes::in, list(prog_var)::in, list(mer_inst)::in, int::in, list(argnum_var_type_inst)::out) is det. construct_argnum_var_type_inst_tuples(_VarTypes, [], [], _ArgNum, []). construct_argnum_var_type_inst_tuples(_VarTypes, [], [_ | _], _ArgNum, _) :- unexpected($pred, "length mismatch"). construct_argnum_var_type_inst_tuples(_VarTypes, [_ | _], [], _ArgNum, _) :- unexpected($pred, "length mismatch"). construct_argnum_var_type_inst_tuples(VarTypes, [Var | Vars], [Inst | Insts], ArgNum, [ArgTuple | ArgTuples]) :- lookup_var_type(VarTypes, Var, Type), ArgTuple = argnum_var_type_inst(ArgNum, Var, Type, Inst), construct_argnum_var_type_inst_tuples(VarTypes, Vars, Insts, ArgNum + 1, ArgTuples). :- pred find_satisfied_initial_insts_in_procs(module_info::in, list(argnum_var_type_inst)::in, list(list(mer_inst))::in, int::in, multi_map(int, int)::in, multi_map(int, int)::out) is det. find_satisfied_initial_insts_in_procs(_ModuleInfo, _ArgTuples, [], _ProcNum, !ArgNumMatchedProcs). find_satisfied_initial_insts_in_procs(ModuleInfo, ArgTuples, [Proc | Procs], ProcNum, !ArgNumMatchedProcs) :- find_satisfied_initial_insts_in_proc(ModuleInfo, ArgTuples, Proc, ProcNum, !ArgNumMatchedProcs), find_satisfied_initial_insts_in_procs(ModuleInfo, ArgTuples, Procs, ProcNum + 1, !ArgNumMatchedProcs). :- pred find_satisfied_initial_insts_in_proc(module_info::in, list(argnum_var_type_inst)::in, list(mer_inst)::in, int::in, multi_map(int, int)::in, multi_map(int, int)::out) is det. find_satisfied_initial_insts_in_proc(_ModuleInfo, [], [], _ProcNum, !ArgNumMatchedProcs). find_satisfied_initial_insts_in_proc(_ModuleInfo, [], [_ | _], _ProcNum, !ArgNumMatchedProcs) :- unexpected($pred, "length mismatch"). find_satisfied_initial_insts_in_proc(_ModuleInfo, [_ | _], [], _ProcNum, !ArgNumMatchedProcs) :- unexpected($pred, "length mismatch"). find_satisfied_initial_insts_in_proc(ModuleInfo, [ArgTuple | ArgTuples], [ProcInitialInst | ProcInitialInsts], ProcNum, !ArgNumMatchedProcs) :- ArgTuple = argnum_var_type_inst(ArgNum, _Var, VarType, VarInst), ( if inst_matches_initial_sub(VarInst, ProcInitialInst, VarType, ModuleInfo, _UpdatedModuleInfo, map.init, _Subst) then multi_map.add(ArgNum, ProcNum, !ArgNumMatchedProcs) else true ), find_satisfied_initial_insts_in_proc(ModuleInfo, ArgTuples, ProcInitialInsts, ProcNum, !ArgNumMatchedProcs). :- pred report_any_never_matching_args(mode_info::in, multi_map(int, int)::in, int::in, list(argnum_var_type_inst)::in, list(format_component)::out) is det. report_any_never_matching_args(_ModeInfo, _ArgNumMatchedProcs, _NumExtra, [], []). report_any_never_matching_args(ModeInfo, ArgNumMatchedProcs, NumExtra, [ArgTuple | ArgTuples], BadArgPieces) :- report_any_never_matching_args(ModeInfo, ArgNumMatchedProcs, NumExtra, ArgTuples, BadArgPiecesTail), ArgTuple = argnum_var_type_inst(ArgNum, Var, _VarType, VarInst), ( if map.search(ArgNumMatchedProcs, ArgNum, _) then BadArgPieces = BadArgPiecesTail else ( if ArgNum =< NumExtra then ArgNumPieces = [words("The compiler-generated"), nth_fixed(ArgNum), words("argument")] else ArgNumPieces = [words("The"), nth_fixed(ArgNum - NumExtra), words("argument")] ), mode_info_get_module_info(ModeInfo, ModuleInfo), ( if inst_contains_higher_order(ModuleInfo, VarInst) then HOPieces = [words("(For higher order insts like this,"), words("the mismatch is sometimes caused by"), words("the arity of the predicate or function"), words("being different in the inst than in the type.)"), nl] else HOPieces = [] ), mode_info_get_varset(ModeInfo, VarSet), BadArgPieces = ArgNumPieces ++ [quote(mercury_var_to_name_only(VarSet, Var)), words("has inst")] ++ report_inst(ModeInfo, quote_short_inst, [suffix(",")], [nl_indent_delta(1)], [suffix(","), nl_indent_delta(-1)], VarInst) ++ [words("which does not match any of those modes."), nl] ++ HOPieces ++ BadArgPiecesTail ). %---------------------------------------------------------------------------% :- func mode_error_higher_order_pred_var_to_spec(mode_info, pred_or_func, prog_var, mer_inst, arity) = error_spec. mode_error_higher_order_pred_var_to_spec(ModeInfo, PredOrFunc, Var, VarInst, Arity) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), % Don't let the specification of the expected arity be broken up, % since that would make the error message harder to read. ( PredOrFunc = pf_predicate, ExpectingPieces = [words("expecting higher-order pred inst"), fixed("of arity " ++ int_to_string(Arity) ++ "."), nl] ; PredOrFunc = pf_function, ExpectingPieces = [words("expecting higher-order func inst"), fixed("of arity " ++ int_to_string(Arity - 1) ++ "."), nl] ), Pieces = [words("mode error: variable"), quote(mercury_var_to_name_only(VarSet, Var)) | has_instantiatedness(ModeInfo, VarInst, ",")] ++ ExpectingPieces, Spec = simplest_spec($pred, severity_error, phase_mode_check(report_in_any_mode), Context, Preamble ++ Pieces). :- func mode_error_poly_unify_to_spec(mode_info, prog_var, mer_inst) = error_spec. mode_error_poly_unify_to_spec(ModeInfo, Var, VarInst) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), MainPieces = [words("in polymorphically-typed unification:"), nl, words("mode error: variable"), quote(mercury_var_to_name_only(VarSet, Var)) | has_instantiatedness(ModeInfo, VarInst, ",")] ++ [words("expected instantiatedness was"), quote("ground"), words("or"), quote("any"), suffix("."), nl], VerbosePieces = [words("When unifying two variables whose type"), words("will not be known until runtime, the variables must both"), words("be ground (or have inst"), quote("any"), suffix(")."), words("Unifications of polymorphically-typed variables with"), words("partially instantiated modes are not allowed.")], Spec = error_spec($pred, severity_error, phase_mode_check(report_in_any_mode), [simple_msg(Context, [always(Preamble ++ MainPieces), verbose_only(verbose_once, VerbosePieces)])]). :- func mode_error_var_is_live_to_spec(mode_info, prog_var) = error_spec. mode_error_var_is_live_to_spec(ModeInfo, Var) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), Pieces = [words("unique-mode error: the called procedure"), words("would clobber its argument, but variable"), quote(mercury_var_to_name_only(VarSet, Var)), words("is still live."), nl], Spec = simplest_spec($pred, severity_error, phase_mode_check(report_in_any_mode), Context, Preamble ++ Pieces). :- func mode_error_var_has_inst_to_spec(mode_info, prog_var, mer_inst, mer_inst, maybe(pred_var_multimode_pred_error)) = error_spec. mode_error_var_has_inst_to_spec(ModeInfo, Var, VarInst, Inst, MaybeMultiModeError) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), MainPieces = [words("mode error: variable"), quote(mercury_var_to_name_only(VarSet, Var)) | has_inst_expected_inst_was(ModeInfo, VarInst, Inst)], MainMsgs = [simplest_msg(Context, Preamble ++ MainPieces)], ( MaybeMultiModeError = no, Spec = error_spec($pred, severity_error, phase_mode_check(report_in_any_mode), MainMsgs) ; MaybeMultiModeError = yes(MultiModeError), ConnectPieces = [words("This may have been caused by"), words("the following error."), nl], ConnectMsgs = [simplest_msg(Context, ConnectPieces)], MultiModeError = pred_var_multimode_pred_error(PredId, MultiMode), SubSpec0 = mode_error_unify_var_multimode_pred_to_spec(ModeInfo, Var, PredId, MultiMode), mode_info_get_module_info(ModeInfo, ModuleInfo), module_info_get_globals(ModuleInfo, Globals), extract_spec_msgs(Globals, SubSpec0, SubMsgs), Spec = error_spec($pred, severity_error, phase_mode_check(report_in_any_mode), MainMsgs ++ ConnectMsgs ++ SubMsgs) ). :- func mode_error_implied_mode_to_spec(mode_info, prog_var, mer_inst, mer_inst) = error_spec. mode_error_implied_mode_to_spec(ModeInfo, Var, VarInst, Inst) = Spec :- % This "error" message is really a "sorry, not implemented" message. % We only print the message if we will actually generate code. mode_info_get_module_info(ModeInfo, ModuleInfo), module_info_get_globals(ModuleInfo, Globals), globals.get_op_mode(Globals, OpMode), mode_info_get_context(ModeInfo, Context), ( if OpMode = opm_top_args(opma_augment(opmau_generate_code(_))) then Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_varset(ModeInfo, VarSet), Pieces = [words("sorry, implied modes not implemented."), nl, words("Variable"), quote(mercury_var_to_name_only(VarSet, Var)) | has_inst_expected_inst_was(ModeInfo, VarInst, Inst)], Spec = simplest_spec($pred, severity_error, phase_mode_check(report_in_any_mode), Context, Preamble ++ Pieces) else Spec = error_spec($pred, severity_informational, phase_mode_check(report_in_any_mode), [simple_msg(Context, [])]) ). :- func mode_error_no_mode_decl_to_spec(mode_info) = error_spec. mode_error_no_mode_decl_to_spec(ModeInfo) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), Pieces = [words("no mode declaration for called predicate."), nl], Spec = simplest_spec($pred, severity_error, phase_mode_check(report_in_any_mode), Context, Preamble ++ Pieces). :- func mode_error_unify_pred_to_spec(mode_info, prog_var, mode_error_unify_rhs, mer_type, pred_or_func) = error_spec. mode_error_unify_pred_to_spec(ModeInfo, X, RHS, Type, PredOrFunc) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), mode_info_get_instvarset(ModeInfo, InstVarSet), mode_info_get_module_info(ModeInfo, ModuleInfo), ( RHS = error_at_var(Y), RHSStr = mercury_var_to_name_only(VarSet, Y) ; RHS = error_at_functor(ConsId, ArgVars), RHSStr = functor_cons_id_to_string(ModuleInfo, VarSet, print_name_only, ConsId, ArgVars) ; RHS = error_at_lambda(ArgVars, ArgFromToInsts), ArgModes = list.map(from_to_insts_to_mode, ArgFromToInsts), RHSStr = "lambda([" ++ var_modes_to_string(VarSet, InstVarSet, print_name_only, ArgVars, ArgModes) ++ "] ... )" ), varset.init(TypeVarSet), MainPieces = [words("In unification of"), quote(mercury_var_to_name_only(VarSet, X)), words("with"), quote(RHSStr), suffix(":"), nl, words("mode error: attempt at higher-order unification."), nl, words("Cannot unify two terms of type"), quote(mercury_type_to_string(TypeVarSet, print_name_only, Type)), suffix("."), nl], VerbosePieces = [words("Your code is trying to test whether two "), words(prog_out.pred_or_func_to_full_str(PredOrFunc) ++ "s"), words("are equal, by unifying them."), words("In the general case, testing equivalence of"), words(prog_out.pred_or_func_to_full_str(PredOrFunc) ++ "s"), words("is an undecidable problem,"), words("and so this is not allowed by the Mercury mode system."), words("In some cases, you can achieve the same effect by"), words("writing an explicit universal quantification, e.g."), quote("all [X] call(P, X) <=> call(Q, X)"), suffix(","), words("instead of"), quote("P = Q"), suffix(".")], Spec = error_spec($pred, severity_error, phase_mode_check(report_in_any_mode), [simple_msg(Context, [always(Preamble ++ MainPieces), verbose_only(verbose_once, VerbosePieces)])]). %---------------------------------------------------------------------------% :- func mode_error_unify_var_var_to_spec(mode_info, prog_var, prog_var, mer_inst, mer_inst) = error_spec. mode_error_unify_var_var_to_spec(ModeInfo, X, Y, InstX, InstY) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), Pieces = [words("mode error in unification of"), quote(mercury_var_to_name_only(VarSet, X)), words("and"), quote(mercury_var_to_name_only(VarSet, Y)), suffix("."), nl, words("Variable"), quote(mercury_var_to_name_only(VarSet, X)) | has_instantiatedness(ModeInfo, InstX, ",")] ++ [words("variable"), quote(mercury_var_to_name_only(VarSet, Y)) | has_instantiatedness(ModeInfo, InstY, ".")], Spec = simplest_spec($pred, severity_error, phase_mode_check(report_in_any_mode), Context, Preamble ++ Pieces). %---------------------------------------------------------------------------% :- func mode_error_unify_var_lambda_to_spec(mode_info, prog_var, mer_inst, mer_inst) = error_spec. mode_error_unify_var_lambda_to_spec(ModeInfo, X, InstX, InstY) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), Pieces = [words("mode error in unification of"), quote(mercury_var_to_name_only(VarSet, X)), words("and lambda expression."), nl, words("Variable"), quote(mercury_var_to_name_only(VarSet, X)) | has_instantiatedness(ModeInfo, InstX, ",")] ++ [words("lambda expression") | has_instantiatedness(ModeInfo, InstY, ".")], Spec = simplest_spec($pred, severity_error, phase_mode_check(report_in_any_mode), Context, Preamble ++ Pieces). %---------------------------------------------------------------------------% :- func mode_error_unify_var_multimode_pred_to_spec(mode_info, prog_var, pred_id, var_multimode_pred_error) = error_spec. mode_error_unify_var_multimode_pred_to_spec(ModeInfo, X, PredId, MultiModeError) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), mode_info_get_module_info(ModeInfo, ModuleInfo), module_info_pred_info(ModuleInfo, PredId, PredInfo), PredOrFunc = pred_info_is_pred_or_func(PredInfo), PredModule = pred_info_module(PredInfo), PredName = pred_info_name(PredInfo), QualifiedName = qualified(PredModule, PredName), Arity = pred_info_orig_arity(PredInfo), adjust_func_arity(PredOrFunc, FuncArity, Arity), StartPieces = [words("mode error in unification of"), quote(mercury_var_to_name_only(VarSet, X)), words("and higher-order term based on multi-moded"), p_or_f(PredOrFunc), qual_sym_name_arity(sym_name_arity(QualifiedName, FuncArity)), suffix("."), nl], ( MultiModeError = some_ho_args_non_ground(NonGroundArgVars), VarOrVars = choose_number(NonGroundArgVars, "variable", "variables"), NonGroundArgVarPieces = named_and_unnamed_vars_to_pieces(VarSet, NonGroundArgVars), DetailPieces = [words("The higher order argument"), words(VarOrVars)] ++ NonGroundArgVarPieces ++ [words("should be ground, but are not."), nl] ; ( MultiModeError = no_matching_mode(ArgVars), MatchPieces = [words(choose_number(ArgVars, "does", "do")), words("not match any")] ; MultiModeError = more_than_one_matching_mode(ArgVars), MatchPieces = [words(choose_number(ArgVars, "matches", "match")), words("more than one")] ), ModeOrModes = choose_number(ArgVars, "mode", "modes"), VarOrVars = choose_number(ArgVars, "variable", "variables"), ArgVarPieces = named_and_unnamed_vars_to_pieces(VarSet, ArgVars), DetailPieces = [words("The"), words(ModeOrModes), words("of the argument"), words(VarOrVars)] ++ ArgVarPieces ++ MatchPieces ++ [words("of the called"), p_or_f(PredOrFunc), suffix("'s"), words("modes."), nl] ), Spec = simplest_spec($pred, severity_error, phase_mode_check(report_in_any_mode), Context, Preamble ++ StartPieces ++ DetailPieces). :- func named_and_unnamed_vars_to_pieces(prog_varset, list(prog_var)) = list(format_component). named_and_unnamed_vars_to_pieces(VarSet, Vars) = Pieces :- list.filter_map(varset.search_name(VarSet), Vars, NamedVarNames, UnnamedVars), ( NamedVarNames = [], Pieces = [] ; NamedVarNames = [_ | _], NamedVarPieces = list_to_pieces(NamedVarNames), ( UnnamedVars = [], Pieces = NamedVarPieces ; UnnamedVars = [_ | _], Pieces = [words("including") | NamedVarPieces] ) ). %---------------------------------------------------------------------------% :- func mode_error_unify_var_functor_to_spec(mode_info, prog_var, cons_id, list(prog_var), mer_inst, list(mer_inst)) = error_spec. mode_error_unify_var_functor_to_spec(ModeInfo, X, ConsId, Args, InstX, ArgInsts) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), mode_info_get_module_info(ModeInfo, ModuleInfo), FunctorConsIdStr = functor_cons_id_to_string(ModuleInfo, VarSet, print_name_only, ConsId, Args), ConsIdStr = mercury_cons_id_to_string(does_not_need_brackets, ConsId), FakeTermInst = defined_inst(user_inst(unqualified(ConsIdStr), ArgInsts)), Pieces = [words("mode error in unification of"), quote(mercury_var_to_name_only(VarSet, X)), words("and"), words_quote(FunctorConsIdStr), suffix("."), nl, words("Variable"), quote(mercury_var_to_name_only(VarSet, X)) | has_instantiatedness(ModeInfo, InstX, ",")] ++ [words("term"), words_quote(FunctorConsIdStr) | has_instantiatedness(ModeInfo, FakeTermInst, ".")], Spec = simplest_spec($pred, severity_error, phase_mode_check(report_in_any_mode), Context, Preamble ++ Pieces). %---------------------------------------------------------------------------% :- func mode_warning_cannot_succeed_var_var(mode_info, prog_var, prog_var, mer_inst, mer_inst) = error_spec. mode_warning_cannot_succeed_var_var(ModeInfo, X, Y, InstX, InstY) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), Pieces = [words("warning: unification of"), quote(mercury_var_to_name_only(VarSet, X)), words("and"), quote(mercury_var_to_name_only(VarSet, Y)), words("cannot succeed."), nl, quote(mercury_var_to_name_only(VarSet, X)) | has_instantiatedness(ModeInfo, InstX, ",")] ++ [quote(mercury_var_to_name_only(VarSet, Y)) | has_instantiatedness(ModeInfo, InstY, ".")], Spec = simplest_spec($pred, severity_warning, phase_mode_check(report_only_if_in_all_modes), Context, Preamble ++ Pieces). :- func mode_warning_cannot_succeed_var_functor(mode_info, prog_var, mer_inst, cons_id) = error_spec. mode_warning_cannot_succeed_var_functor(ModeInfo, X, InstX, ConsId) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), Pieces = [words("warning: unification of"), quote(mercury_var_to_name_only(VarSet, X)), words("and"), words(mercury_cons_id_to_string(does_not_need_brackets, ConsId)), words("cannot succeed."), nl, quote(mercury_var_to_name_only(VarSet, X)) | has_instantiatedness(ModeInfo, InstX, ".")], Spec = simplest_spec($pred, severity_warning, phase_mode_check(report_only_if_in_all_modes), Context, Preamble ++ Pieces). :- func mode_warning_cannot_succeed_ground_occur_check(mode_info, prog_var, cons_id) = error_spec. mode_warning_cannot_succeed_ground_occur_check(ModeInfo, X, ConsId) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), Pieces = [words("warning: unification of"), quote(mercury_var_to_name_only(VarSet, X)), words("and"), words(mercury_cons_id_to_string(does_not_need_brackets, ConsId)), words("cannot succeed, because"), quote(mercury_var_to_name_only(VarSet, X)), words("cannot be equal to a term containing itself."), nl], Spec = simplest_spec($pred, severity_warning, phase_mode_check(report_in_any_mode), Context, Preamble ++ Pieces). %---------------------------------------------------------------------------% :- func mode_info_context_preamble(mode_info) = list(format_component). mode_info_context_preamble(ModeInfo) = Pieces :- mode_info_get_module_info(ModeInfo, ModuleInfo), mode_info_get_pred_id(ModeInfo, PredId), mode_info_get_proc_id(ModeInfo, ProcId), module_info_pred_proc_info(ModuleInfo, PredId, ProcId, PredInfo, ProcInfo), pred_info_get_origin(PredInfo, PredOrigin), ( if PredOrigin = origin_instance_method(MethodName, _) then Name0 = unqualify_name(MethodName), ExtraMethodPieces = [words("type class method implementation for")] else Name0 = pred_info_name(PredInfo), ExtraMethodPieces = [] ), PredOrFunc = pred_info_is_pred_or_func(PredInfo), mode_info_get_instvarset(ModeInfo, InstVarSet), Name = unqualified(Name0), pred_info_get_markers(PredInfo, PredMarkers), proc_info_declared_argmodes(ProcInfo, Modes0), strip_builtin_qualifiers_from_mode_list(Modes0, Modes), MaybeDet = no, ModeSubDeclStr = mercury_mode_subdecl_to_string(output_debug, PredOrFunc, InstVarSet, Name, Modes, MaybeDet), mode_info_get_mode_context(ModeInfo, ModeContext), ModeContextPieces = mode_context_to_pieces(ModeInfo, ModeContext, PredMarkers), Pieces = [words("In clause for")] ++ ExtraMethodPieces ++ [words_quote(ModeSubDeclStr), suffix(":"), nl] ++ ModeContextPieces. %---------------------------------------------------------------------------% % XXX some parts of the mode context never get set up :- func mode_context_to_pieces(mode_info, mode_context, pred_markers) = list(format_component). mode_context_to_pieces(ModeInfo, ModeContext, Markers) = Pieces :- ( ModeContext = mode_context_uninitialized, Pieces = [] ; ModeContext = mode_context_call(ModeCallId, ArgNum), ( ModeCallId = mode_call_plain(PredId), mode_info_get_pf_sym_name_arity(ModeInfo, PredId, PFSymNameArity), CallId = plain_call_id(PFSymNameArity) ; ModeCallId = mode_call_generic(GenericCallId), CallId = generic_call_id(GenericCallId) ), Pieces = [words("in"), words(call_arg_id_to_string(CallId, ArgNum, Markers)), suffix(":"), nl] ; ModeContext = mode_context_unify(UnifyContext, _Side), unify_context_first_to_pieces(is_not_first, _, UnifyContext, [], Pieces) ). %---------------------------------------------------------------------------% :- func mode_error_final_inst_to_spec(mode_info, int, prog_var, mer_inst, mer_inst, final_inst_error) = error_spec. mode_error_final_inst_to_spec(ModeInfo, ArgNum, Var, VarInst, ExpInst, Reason) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), ( Reason = too_instantiated, Problem = "became too instantiated." ; Reason = not_instantiated_enough, Problem = "did not get sufficiently instantiated." ; Reason = wrongly_instantiated, % I don't think this can happen. But just in case... Problem = "had the wrong instantiatedness." ), Pieces = [words("mode error: argument"), fixed(int_to_string(ArgNum)), words(Problem), nl, words("Final instantiatedness of"), quote(mercury_var_to_name_only(VarSet, Var)), words("was") | report_inst(ModeInfo, quote_short_inst, [suffix(","), nl], [nl_indent_delta(1)], [suffix(","), nl_indent_delta(-1)], VarInst)] ++ [words("expected final instantiatedness was") | report_inst(ModeInfo, quote_short_inst, [suffix("."), nl], [nl_indent_delta(1)], [suffix("."), nl_indent_delta(-1)], ExpInst)], Spec = simplest_spec($pred, severity_error, phase_mode_check(report_in_any_mode), Context, Preamble ++ Pieces). %---------------------------------------------------------------------------% :- func purity_error_should_be_in_promise_purity_scope_to_spec( negated_context_desc, mode_info, prog_var) = error_spec. purity_error_should_be_in_promise_purity_scope_to_spec(NegCtxtDesc, ModeInfo, Var) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), ( NegCtxtDesc = if_then_else, Pieces = [words("purity error: if-then-else should be inside"), words("a promise_purity scope because non-local variable"), quote(mercury_var_to_name_only(VarSet, Var)), words("has inst"), quote("any"), words("and appears in the condition."), nl] ; NegCtxtDesc = negation, Pieces = [words("purity error: negation should be inside"), words("a promise_purity scope because non-local variable"), quote(mercury_var_to_name_only(VarSet, Var)), words("has inst"), quote("any"), words("and appears in the body."), nl] ), Spec = simplest_spec($pred, severity_error, phase_mode_check(report_in_any_mode), Context, Preamble ++ Pieces). %---------------------------------------------------------------------------% :- func purity_error_lambda_should_be_any_to_spec(mode_info, list(prog_var)) = error_spec. purity_error_lambda_should_be_any_to_spec(ModeInfo, Vars) = Spec :- Preamble = mode_info_context_preamble(ModeInfo), mode_info_get_context(ModeInfo, Context), mode_info_get_varset(ModeInfo, VarSet), Pieces = [words("purity error: lambda is"), quote("ground"), words("but contains the following non-local variables"), words("whose insts contain"), quote("any"), suffix(":"), words(mercury_vars_to_name_only(VarSet, Vars)), suffix("."), nl], Always = always(Preamble ++ Pieces), VerboseOnly = verbose_only(verbose_once, [words("Predicate expressions"), words("with inst"), quote("any"), words("can be written"), quote("any_pred(Args) is det :- ..."), suffix("."), words("Function expressions with inst"), quote("any"), words("can be written"), quote("any_func(Args) = Result is det :- ..."), suffix("."), nl]), Spec = error_spec($pred, severity_error, phase_mode_check(report_in_any_mode), [simple_msg(Context, [Always, VerboseOnly])]). %---------------------------------------------------------------------------% should_report_mode_warning_for_pred_origin(origin_special_pred(_, _)) = no. should_report_mode_warning_for_pred_origin(origin_instance_method(_, _)) = no. should_report_mode_warning_for_pred_origin(origin_class_method(_, _)) = no. should_report_mode_warning_for_pred_origin(origin_transformed(_, _, _)) = no. should_report_mode_warning_for_pred_origin(origin_created(_)) = no. should_report_mode_warning_for_pred_origin(origin_assertion(_, _)) = no. should_report_mode_warning_for_pred_origin(origin_lambda(_, _, _)) = yes. should_report_mode_warning_for_pred_origin(origin_solver_type(_, _, _)) = no. should_report_mode_warning_for_pred_origin(origin_tabling(_, _)) = no. should_report_mode_warning_for_pred_origin(origin_mutable(_, _, _)) = no. should_report_mode_warning_for_pred_origin(origin_initialise) = no. should_report_mode_warning_for_pred_origin(origin_finalise) = no. should_report_mode_warning_for_pred_origin(origin_user(_)) = yes. %---------------------------------------------------------------------------% :- func inst_list_to_sep_lines(mode_info, list(mer_inst)) = list(format_component). inst_list_to_sep_lines(_ModeInfo, []) = []. inst_list_to_sep_lines(ModeInfo, [Inst | Insts]) = Pieces :- ( Insts = [], Pieces = report_inst(ModeInfo, fixed_short_inst, [nl_indent_delta(-1)], [], [nl_indent_delta(-1)], Inst) ; Insts = [_ | _], HeadPieces = report_inst(ModeInfo, fixed_short_inst, [suffix(","), nl], [], [suffix(","), nl], Inst), TailPieces = inst_list_to_sep_lines(ModeInfo, Insts), Pieces = HeadPieces ++ TailPieces ). %---------------------------------------------------------------------------% :- func has_inst_expected_inst_was(mode_info, mer_inst, mer_inst) = list(format_component). has_inst_expected_inst_was(ModeInfo, ActualInst, ExpectedInst) = has_instantiatedness(ModeInfo, ActualInst, ",") ++ expected_inst_was(ModeInfo, ExpectedInst). :- func has_instantiatedness(mode_info, mer_inst, string) = list(format_component). has_instantiatedness(ModeInfo, Inst, Suffix) = [words("has instantiatedness") | report_inst(ModeInfo, quote_short_inst, [suffix(Suffix), nl], [nl_indent_delta(1)], [suffix(Suffix), nl_indent_delta(-1)], Inst)]. :- func expected_inst_was(mode_info, mer_inst) = list(format_component). expected_inst_was(ModeInfo, Inst) = [words("expected instantiatedness was") | report_inst(ModeInfo, quote_short_inst, [suffix("."), nl], [nl_indent_delta(1)], [suffix("."), nl_indent_delta(-1)], Inst)]. %---------------------------------------------------------------------------% :- func report_inst(mode_info, short_inst, list(format_component), list(format_component), list(format_component), mer_inst) = list(format_component). report_inst(ModeInfo, ShortInstQF, ShortInstSuffix, LongInstPrefix, LongInstSuffix, Inst0) = Pieces :- mode_info_get_module_info(ModeInfo, ModuleInfo), mode_info_get_instvarset(ModeInfo, InstVarSet), Pieces = error_msg_inst(ModuleInfo, InstVarSet, expand_named_insts, ShortInstQF, ShortInstSuffix, LongInstPrefix, LongInstSuffix, Inst0). %---------------------------------------------------------------------------% :- end_module check_hlds.mode_errors. %---------------------------------------------------------------------------%
{ "pile_set_name": "Github" }
/* * 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.aliyuncs.cloudapi.model.v20160714; import com.aliyuncs.AcsResponse; import com.aliyuncs.cloudapi.transform.v20160714.SetDomainCertificateResponseUnmarshaller; import com.aliyuncs.transform.UnmarshallerContext; /** * @author auto create * @version */ public class SetDomainCertificateResponse extends AcsResponse { private String requestId; public String getRequestId() { return this.requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } @Override public SetDomainCertificateResponse getInstance(UnmarshallerContext context) { return SetDomainCertificateResponseUnmarshaller.unmarshall(this, context); } }
{ "pile_set_name": "Github" }
// Copyright 2017, OpenCensus Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package view import ( "bytes" "errors" "fmt" "reflect" "sort" "sync/atomic" "time" "go.opencensus.io/metric/metricdata" "go.opencensus.io/stats" "go.opencensus.io/tag" ) // View allows users to aggregate the recorded stats.Measurements. // Views need to be passed to the Register function to be before data will be // collected and sent to Exporters. type View struct { Name string // Name of View. Must be unique. If unset, will default to the name of the Measure. Description string // Description is a human-readable description for this view. // TagKeys are the tag keys describing the grouping of this view. // A single Row will be produced for each combination of associated tag values. TagKeys []tag.Key // Measure is a stats.Measure to aggregate in this view. Measure stats.Measure // Aggregation is the aggregation function tp apply to the set of Measurements. Aggregation *Aggregation } // WithName returns a copy of the View with a new name. This is useful for // renaming views to cope with limitations placed on metric names by various // backends. func (v *View) WithName(name string) *View { vNew := *v vNew.Name = name return &vNew } // same compares two views and returns true if they represent the same aggregation. func (v *View) same(other *View) bool { if v == other { return true } if v == nil { return false } return reflect.DeepEqual(v.Aggregation, other.Aggregation) && v.Measure.Name() == other.Measure.Name() } // ErrNegativeBucketBounds error returned if histogram contains negative bounds. // // Deprecated: this should not be public. var ErrNegativeBucketBounds = errors.New("negative bucket bounds not supported") // canonicalize canonicalizes v by setting explicit // defaults for Name and Description and sorting the TagKeys func (v *View) canonicalize() error { if v.Measure == nil { return fmt.Errorf("cannot register view %q: measure not set", v.Name) } if v.Aggregation == nil { return fmt.Errorf("cannot register view %q: aggregation not set", v.Name) } if v.Name == "" { v.Name = v.Measure.Name() } if v.Description == "" { v.Description = v.Measure.Description() } if err := checkViewName(v.Name); err != nil { return err } sort.Slice(v.TagKeys, func(i, j int) bool { return v.TagKeys[i].Name() < v.TagKeys[j].Name() }) sort.Float64s(v.Aggregation.Buckets) for _, b := range v.Aggregation.Buckets { if b < 0 { return ErrNegativeBucketBounds } } // drop 0 bucket silently. v.Aggregation.Buckets = dropZeroBounds(v.Aggregation.Buckets...) return nil } func dropZeroBounds(bounds ...float64) []float64 { for i, bound := range bounds { if bound > 0 { return bounds[i:] } } return []float64{} } // viewInternal is the internal representation of a View. type viewInternal struct { view *View // view is the canonicalized View definition associated with this view. subscribed uint32 // 1 if someone is subscribed and data need to be exported, use atomic to access collector *collector metricDescriptor *metricdata.Descriptor } func newViewInternal(v *View) (*viewInternal, error) { return &viewInternal{ view: v, collector: &collector{make(map[string]AggregationData), v.Aggregation}, metricDescriptor: viewToMetricDescriptor(v), }, nil } func (v *viewInternal) subscribe() { atomic.StoreUint32(&v.subscribed, 1) } func (v *viewInternal) unsubscribe() { atomic.StoreUint32(&v.subscribed, 0) } // isSubscribed returns true if the view is exporting // data by subscription. func (v *viewInternal) isSubscribed() bool { return atomic.LoadUint32(&v.subscribed) == 1 } func (v *viewInternal) clearRows() { v.collector.clearRows() } func (v *viewInternal) collectedRows() []*Row { return v.collector.collectedRows(v.view.TagKeys) } func (v *viewInternal) addSample(m *tag.Map, val float64, attachments map[string]interface{}, t time.Time) { if !v.isSubscribed() { return } sig := string(encodeWithKeys(m, v.view.TagKeys)) v.collector.addSample(sig, val, attachments, t) } // A Data is a set of rows about usage of the single measure associated // with the given view. Each row is specific to a unique set of tags. type Data struct { View *View Start, End time.Time Rows []*Row } // Row is the collected value for a specific set of key value pairs a.k.a tags. type Row struct { Tags []tag.Tag Data AggregationData } func (r *Row) String() string { var buffer bytes.Buffer buffer.WriteString("{ ") buffer.WriteString("{ ") for _, t := range r.Tags { buffer.WriteString(fmt.Sprintf("{%v %v}", t.Key.Name(), t.Value)) } buffer.WriteString(" }") buffer.WriteString(fmt.Sprintf("%v", r.Data)) buffer.WriteString(" }") return buffer.String() } // Equal returns true if both rows are equal. Tags are expected to be ordered // by the key name. Even both rows have the same tags but the tags appear in // different orders it will return false. func (r *Row) Equal(other *Row) bool { if r == other { return true } return reflect.DeepEqual(r.Tags, other.Tags) && r.Data.equal(other.Data) } const maxNameLength = 255 // Returns true if the given string contains only printable characters. func isPrintable(str string) bool { for _, r := range str { if !(r >= ' ' && r <= '~') { return false } } return true } func checkViewName(name string) error { if len(name) > maxNameLength { return fmt.Errorf("view name cannot be larger than %v", maxNameLength) } if !isPrintable(name) { return fmt.Errorf("view name needs to be an ASCII string") } return nil }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <suite name="SuiteTwo"> <!-- If add more test cases In this suite, You need to add them as bellow. --> <test name="SuiteTwoCaseOne"> <classes> <class name="com.stta.SuiteTwo.SuiteTwoCaseOne" ></class> </classes> </test> <test name="SuiteTwoCaseTwo"> <classes> <class name="com.stta.SuiteTwo.SuiteTwoCaseTwo" ></class> </classes> </test> </suite>
{ "pile_set_name": "Github" }
Menu commands are called by there name and a number of options parameters. The following forms are valid syntax command without parameters : menucmd command with one parameter : menucmd "xyz" command with two parameters : menucmd 123, "abc def" command with two parameters : menucmd(456,"abc") Most menu commands run without any parameters at all, and most are taken straight from the main and xfer menus. Additional commands are added to manage the menu system as well as a few commands which will help you to emulate other BBSes. =============================================================================
{ "pile_set_name": "Github" }
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("placeholder","el",{title:"Ιδιότητες Υποκαθιστόμενου Κειμένου",toolbar:"Δημιουργία Υποκαθιστόμενου Κειμένου",name:"Όνομα Υποκαθιστόμενου Κειμένου",invalidName:"Το υποκαθιστόμενου κειμένο πρέπει να μην είναι κενό και να μην έχει κανέναν από τους ακόλουθους χαρακτήρες: [, ], \x3c, \x3e",pathName:"υποκαθιστόμενο κείμενο"});
{ "pile_set_name": "Github" }
package com.google.android.play.core.splitinstall; import android.os.RemoteException; import com.google.android.play.core.remote.RemoteTask; import com.google.android.play.core.tasks.TaskWrapper; import java.util.List; final class StartInstallTask extends RemoteTask { private final SplitInstallService mSplitInstallService; private final TaskWrapper<Integer> mTask; private final List<String> moduleNames; StartInstallTask(SplitInstallService installService, TaskWrapper task, List<String> moduleNames, TaskWrapper<Integer> taskSame) { super(task); this.mSplitInstallService = installService; this.moduleNames = moduleNames; this.mTask = taskSame; } @Override protected void execute() { try { mSplitInstallService.mSplitRemoteManager.getIInterface().startInstall( this.mSplitInstallService.mPackageName, SplitInstallService.wrapModuleNames(moduleNames), SplitInstallService.wrapVersionCode(), new StartInstallCallback(mSplitInstallService, mTask) ); } catch (RemoteException e) { SplitInstallService.playCore.error(e, "startInstall(%s)", this.moduleNames); this.mTask.setException(new RuntimeException(e)); } } }
{ "pile_set_name": "Github" }
{ "name": "hot-reloading-example", "version": "0.0.1", "description": "Counters app with hot reloading of components", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Simon Friis Vindum", "license": "MIT", "devDependencies": { "babel-core": "^5.8.22", "babel-loader": "^5.3.2", "css-loader": "^0.16.0", "style-loader": "^0.12.3", "webpack": "^1.11.0" }, "dependencies": { "ramda": "^0.17.1", "snabbdom": "^0.2.6", "union-type": "^0.1.6" } }
{ "pile_set_name": "Github" }
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build ignore package main import ( "flag" "log" "golang.org/x/text/internal/gen" "golang.org/x/text/internal/triegen" "golang.org/x/text/internal/ucd" ) var outputFile = flag.String("out", "tables.go", "output file") func main() { gen.Init() gen.Repackage("gen_trieval.go", "trieval.go", "bidi") gen.Repackage("gen_ranges.go", "ranges_test.go", "bidi") genTables() } // bidiClass names and codes taken from class "bc" in // https://www.unicode.org/Public/8.0.0/ucd/PropertyValueAliases.txt var bidiClass = map[string]Class{ "AL": AL, // ArabicLetter "AN": AN, // ArabicNumber "B": B, // ParagraphSeparator "BN": BN, // BoundaryNeutral "CS": CS, // CommonSeparator "EN": EN, // EuropeanNumber "ES": ES, // EuropeanSeparator "ET": ET, // EuropeanTerminator "L": L, // LeftToRight "NSM": NSM, // NonspacingMark "ON": ON, // OtherNeutral "R": R, // RightToLeft "S": S, // SegmentSeparator "WS": WS, // WhiteSpace "FSI": Control, "PDF": Control, "PDI": Control, "LRE": Control, "LRI": Control, "LRO": Control, "RLE": Control, "RLI": Control, "RLO": Control, } func genTables() { if numClass > 0x0F { log.Fatalf("Too many Class constants (%#x > 0x0F).", numClass) } w := gen.NewCodeWriter() defer w.WriteVersionedGoFile(*outputFile, "bidi") gen.WriteUnicodeVersion(w) t := triegen.NewTrie("bidi") // Build data about bracket mapping. These bits need to be or-ed with // any other bits. orMask := map[rune]uint64{} xorMap := map[rune]int{} xorMasks := []rune{0} // First value is no-op. ucd.Parse(gen.OpenUCDFile("BidiBrackets.txt"), func(p *ucd.Parser) { r1 := p.Rune(0) r2 := p.Rune(1) xor := r1 ^ r2 if _, ok := xorMap[xor]; !ok { xorMap[xor] = len(xorMasks) xorMasks = append(xorMasks, xor) } entry := uint64(xorMap[xor]) << xorMaskShift switch p.String(2) { case "o": entry |= openMask case "c", "n": default: log.Fatalf("Unknown bracket class %q.", p.String(2)) } orMask[r1] = entry }) w.WriteComment(` xorMasks contains masks to be xor-ed with brackets to get the reverse version.`) w.WriteVar("xorMasks", xorMasks) done := map[rune]bool{} insert := func(r rune, c Class) { if !done[r] { t.Insert(r, orMask[r]|uint64(c)) done[r] = true } } // Insert the derived BiDi properties. ucd.Parse(gen.OpenUCDFile("extracted/DerivedBidiClass.txt"), func(p *ucd.Parser) { r := p.Rune(0) class, ok := bidiClass[p.String(1)] if !ok { log.Fatalf("%U: Unknown BiDi class %q", r, p.String(1)) } insert(r, class) }) visitDefaults(insert) // TODO: use sparse blocks. This would reduce table size considerably // from the looks of it. sz, err := t.Gen(w) if err != nil { log.Fatal(err) } w.Size += sz } // dummy values to make methods in gen_common compile. The real versions // will be generated by this file to tables.go. var ( xorMasks []rune )
{ "pile_set_name": "Github" }
# # Makefile to run all tests for Vim on VMS # # Authors: Zoltan Arpadffy, <[email protected]> # Sandor Kopanyi, <[email protected]> # # Last change: 2016 Nov 04 # # This has been tested on VMS 6.2 to 8.3 on DEC Alpha, VAX and IA64. # Edit the lines in the Configuration section below to select. # # Execute with: # mms/descrip=Make_vms.mms # Cleanup with: # mms/descrip=Make_vms.mms clean # # Make files are MMK compatible. # # NOTE: You can run this script just in X/Window environment. It will # create a new terminals, therefore you have to set up your DISPLAY # logical. More info in VMS documentation or with: help set disp. # ####################################################################### # Configuration section. ####################################################################### # Uncomment if you want tests in GUI mode. Terminal mode is default. # WANT_GUI = YES # Comment out if you want to run Unix specific tests as well, but please # be aware, that on OpenVMS will fail, because of cat, rm, etc commands # and directory handling. # WANT_UNIX = YES # Comment out if you want to run Win32 specific tests as well, but please # be aware, that on OpenVMS will fail, because of cat, rm, etc commands # and directory handling. # WANT_WIN = YES # Comment out if you want to run spell checker tests. # They fail because VMS does not support file names. # WANT_SPELL = YES # Comment out if you want to run mzschema tests. # It fails because VMS does not support this feature yet. # WANT_MZSCH = YES # Comment out if you have ODS-5 file system # HAVE_ODS5 = YES # Comment out if you have gzip on your system # HAVE_GZIP = YES # Comment out if you have GNU compatible diff on your system # HAVE_GDIFF = YES # Comment out if you have ICONV support # HAVE_ICONV = YES # Comment out if you have LUA support # HAVE_LUA = YES # Comment out if you have PYTHON support # HAVE_PYTHON = YES ####################################################################### # End of configuration section. # # Please, do not change anything below without programming experience. ####################################################################### VIMPROG = <->vim.exe .SUFFIXES : .out .in SCRIPT = test1.out test3.out \ test14.out \ test29.out \ test30.out test37.out test39.out \ test42.out test44.out test48.out test49.out \ test64.out test69.out \ test72.out test77a.out test88.out \ test94.out test95.out test99.out test108.out \ test_eval.out # Known problems: # test17: ? # # test30: bug, most probably - a problem around mac format # # test59: Failed/Hangs - VMS does not support spell files (file names # with too many dots). # # test72: bug - Vim hangs at :rename (while rename works well otherwise) # test78: bug - Vim dies at :recover Xtest # test85: no Lua interface # test89: bug - findfile() does not work on VMS (just in the current directory) # test102: Just ODS-5 supports space and special chars in the filename. # On ODS-2 tests fail. .IFDEF WANT_GUI SCRIPT_GUI = test16.out GUI_OPTION = -g .ENDIF .IFDEF WANT_UNIX SCRIPT_UNIX = test10.out test17.out test27.out test49.out .ENDIF .IFDEF WANT_WIN SCRIPT_WIN = test52.out .ENDIF .IFDEF WANT_SPELL SCRIPT_SPELL = test59.out .ENDIF .IFDEF WANT_MZSCH SCRIPT_MZSCH = test70.out .ENDIF .IFDEF HAVE_ODS5 SCRIPT_ODS5 = test102.out .ENDIF .IFDEF HAVE_GZIP SCRIPT_GZIP = test11.out .ENDIF .IFDEF HAVE_GDIFF SCRIPT_GDIFF = test47.out .ENDIF .IFDEF HAVE_LUA SCRIPT_LUA = test85.out .ENDIF .IFDEF HAVE_PYTHON SCRIPT_PYTHON = test86.out test87.out .ENDIF .in.out : -@ !clean up before doing the test -@ if "''F$SEARCH("test.out.*")'" .NES. "" then delete/noconfirm/nolog test.out.* -@ if "''F$SEARCH("$*.out.*")'" .NES. "" then delete/noconfirm/nolog $*.out.* -@ ! define TMP if not set - some tests use it -@ if "''F$TRNLNM("TMP")'" .EQS. "" then define/nolog TMP [] -@ write sys$output " " -@ write sys$output "-----------------------------------------------" -@ write sys$output " "$*" " -@ write sys$output "-----------------------------------------------" -@ !run the test -@ create/term/wait/nodetach mcr $(VIMPROG) $(GUI_OPTION) -u vms.vim --noplugin -s dotest.in $*.in -@ !analyse the result -@ directory /size/date test.out -@ if "''F$SEARCH("test.out.*")'" .NES. "" then rename/nolog test.out $*.out -@ if "''F$SEARCH("$*.out.*")'" .NES. "" then differences /par $*.out $*.ok; -@ !clean up after the test -@ if "''F$SEARCH("Xdotest.*")'" .NES. "" then delete/noconfirm/nolog Xdotest.*.* -@ if "''F$SEARCH("Xtest.*")'" .NES. "" then delete/noconfirm/nolog Xtest.*.* all : clean nolog $(START_WITH) $(SCRIPT) $(SCRIPT_GUI) $(SCRIPT_UNIX) $(SCRIPT_WIN) $(SCRIPT_SPELL) $(SCRIPT_ODS5) $(SCRIPT_GZIP) \ $(SCRIPT_GDIFF) $(SCRIPT_MZSCH) $(SCRIPT_LUA) $(SCRIPT_PYTHON) nolog -@ write sys$output " " -@ write sys$output "-----------------------------------------------" -@ write sys$output " All done" -@ write sys$output "-----------------------------------------------" -@ deassign sys$output -@ delete/noconfirm/nolog x*.*.* -@ type test.log nolog : -@ define sys$output test.log -@ write sys$output "-----------------------------------------------" -@ write sys$output " Standard VIM test cases" -@ write sys$output "-----------------------------------------------" -@ write sys$output " OpenVMS version: ''F$GETSYI("VERSION")'" -@ write sys$output " Vim version:" -@ mcr $(VIMPROG) --version -@ write sys$output " Test date:" -@ show time -@ write sys$output "-----------------------------------------------" -@ write sys$output " Test results:" -@ write sys$output "-----------------------------------------------" -@ write sys$output "MAKE_VMS.MMS options:" -@ write sys$output " WANT_GUI = ""$(WANT_GUI)"" " -@ write sys$output " WANT_UNIX = ""$(WANT_UNIX)"" " -@ write sys$output " WANT_WIN = ""$(WANT_WIN)"" " -@ write sys$output " WANT_SPELL = ""$(WANT_SPELL)"" " -@ write sys$output " WANT_MZSCH = ""$(WANT_MZSCH)"" " -@ write sys$output " HAVE_ODS5 = ""$(HAVE_ODS5)"" " -@ write sys$output " HAVE_GZIP = ""$(HAVE_GZIP)"" " -@ write sys$output " HAVE_GDIFF = ""$(HAVE_GDIFF)"" " -@ write sys$output " HAVE_ICONV = ""$(HAVE_ICONV)"" " -@ write sys$output " HAVE_LUA = ""$(HAVE_LUA)"" " -@ write sys$output " HAVE_PYTHON= ""$(HAVE_PYTHON)"" " -@ write sys$output "Default vimrc file is VMS.VIM:" -@ write sys$output "-----------------------------------------------" -@ type VMS.VIM clean : -@ if "''F$SEARCH("*.out")'" .NES. "" then delete/noconfirm/nolog *.out.* -@ if "''F$SEARCH("test.log")'" .NES. "" then delete/noconfirm/nolog test.log.* -@ if "''F$SEARCH("test.ok")'" .NES. "" then delete/noconfirm/nolog test.ok.* -@ if "''F$SEARCH("Xdotest.*")'" .NES. "" then delete/noconfirm/nolog Xdotest.*.* -@ if "''F$SEARCH("Xtest*.*")'" .NES. "" then delete/noconfirm/nolog Xtest*.*.* -@ if "''F$SEARCH("XX*.*")'" .NES. "" then delete/noconfirm/nolog XX*.*.* -@ if "''F$SEARCH("_un_*.*")'" .NES. "" then delete/noconfirm/nolog _un_*.*.* -@ if "''F$SEARCH("*.*_sw*")'" .NES. "" then delete/noconfirm/nolog *.*_sw*.* -@ if "''F$SEARCH("*.failed")'" .NES. "" then delete/noconfirm/nolog *.failed.* -@ if "''F$SEARCH("*.rej")'" .NES. "" then delete/noconfirm/nolog *.rej.* -@ if "''F$SEARCH("tiny.vim")'" .NES. "" then delete/noconfirm/nolog tiny.vim.* -@ if "''F$SEARCH("small.vim")'" .NES. "" then delete/noconfirm/nolog small.vim.* -@ if "''F$SEARCH("mbyte.vim")'" .NES. "" then delete/noconfirm/nolog mbyte.vim.* -@ if "''F$SEARCH("mzscheme.vim")'" .NES. "" then delete/noconfirm/nolog mzscheme.vim.* -@ if "''F$SEARCH("lua.vim")'" .NES. "" then delete/noconfirm/nolog lua.vim.* -@ if "''F$SEARCH("viminfo.*")'" .NES. "" then delete/noconfirm/nolog viminfo.*.*
{ "pile_set_name": "Github" }
// pattern matcher crashes here trying to synthesize an unneeded outer test. // no-symbol does not have an owner // at scala.reflect.internal.SymbolTable.abort(SymbolTable.scala:49) // at scala.tools.nsc.Global.abort(Global.scala:253) // at scala.reflect.internal.Symbols$NoSymbol.owner(Symbols.scala:3248) // at scala.reflect.internal.Symbols$Symbol.effectiveOwner(Symbols.scala:678) // at scala.reflect.internal.Symbols$Symbol.isDefinedInPackage(Symbols.scala:664) // at scala.reflect.internal.TreeGen.mkAttributedSelect(TreeGen.scala:188) // at scala.reflect.internal.TreeGen.mkAttributedRef(TreeGen.scala:124) // at scala.tools.nsc.ast.TreeDSL$CODE$.REF(TreeDSL.scala:308) // at scala.tools.nsc.typechecker.PatternMatching$TreeMakers$TypeTestTreeMaker$treeCondStrategy$.outerTest(PatternMatching.scala:1209) class Crash { type Alias = C#T val c = new C val t = new c.T // Crash via a Typed Pattern... (t: Any) match { case e: Alias => } // ... or via a Typed Extractor Pattern. object Extractor { def unapply(a: Alias): Option[Any] = None } (t: Any) match { case Extractor() => case _ => } // checking that correct outer tests are applied when // aliases for path dependent types are involved. val c2 = new C type CdotT = c.T type C2dotT = c2.T val outerField = t.getClass.getDeclaredFields.find(_.getName contains ("outer")).get outerField.setAccessible(true) (t: Any) match { case _: C2dotT => println(s"!!! wrong match. t.outer=${outerField.get(t)} / c2 = $c2") // this matches on 2.10.0 case _: CdotT => case _ => println(s"!!! wrong match. t.outer=${outerField.get(t)} / c = $c") } } class C { class T } object Test extends App { new Crash }
{ "pile_set_name": "Github" }
synopsis : cro-magnon ayla loses her mother to an earthquake and escapes certain death by a lion . reluctantly rescued by a neanderthal clan who likes to have sex doggy-style , ayla grows up to become a blond , feminist supermodel who challenges the neanderthal patriarchy by throwing rocks and giving birth without a mate . comments : allow me to state for the record that i find daryl hannah an appealing presence in movies . she proved quite charming as the intelligent astronomer in the romantic comedy roxanne and equally creepy as pris in the sci-fi classic blade runner . the clan of the cave bear clearly tries to capitalize on hannah as a selling point : the poster art bears a striking closeup of hannah in tribal paint and the video box prominently features her name in lettering the same size as the title . not even her starring role in this turkey , unfortunately , can save it from being an unbelievable exercise in cheese . it's so uniquely bad ( a film dealing with prehistoric man that actually tries , and miserably fails , to be serious ) that it's oddly fascinating . the ridiculous attempt at drama here leaves the audience somehow transfixed , wanting to see how this dud plays out . the clan of the cave bear is based upon a popular novel by jean m . auel . to this day , the book possesses a loyal cult following . i remember a dear friend of mine had a dog-eared copy of the novel she had read as a child with all the so-called dirty parts blacked out with marker by her grandmother . i have never read this book , but i sure hope it's 10 , 000 times better than its film adaptation . if not , then i'm at a complete loss to explain its popularity . the clan of the cave bear immediately opens with a comically absurd scene . a young ayla , looking much like drew barrymore in e . t . , tramps about in the woods . with her cute little ponytails and fur wrapped about her , the audience's expectations of a convincing portrayal of prehistory are immediately shattered . what follows is a laughably choreographed sequence in which an earthquake swallows up ayla's mother ( a blonde with fur pants . . . er , leggings ) . tearful ayla looks on as the cameraman shakes the camera . . . well , as the earthquake slowly recedes . a hungry lion becomes interested in her for lunch , but the screaming six-year-old manages to outrun the king of the wild and find a safe haven . i won't detail the story any further ; this seems enough to illustrate my point . this movie is really stupid . it never even gives the audience a chance to suspend their disbelief . also , the obvious comparison between the appearance of cro-magnon man in prehistory and the rise of feminism in our century is about as subtle as burning a wonderbra in front of charlton heston . the movie doesn't just suggest this message ; it whacks the message into the audience with a two-by-four . a blond , gorgeous woman challenges the social laws of a bunch of people in gaudy brown wigs . she's of the " new people " ; they're of the " old people " with " the memories . " yep . we get it . we get it . the clan of the cave bear apparently received an academy award nomination for best make-up , which surprises me . the movie depends upon a lot of make-up obviously , but much of it is unconvincing . as stated before , daryl hannah is daryl hannah here ; she looks like she just stepped out of the shower all the time . the rest of the characters have dark make-up of some sort smeared over them to look like dirt . the face-painting that's occasionally seen is perhaps the only notable work here in my mind . this movie also suffers from its new age trappings . maybe the music sounded a lot more fresh or original during 1985 , but now it sounds dated and cliched , like poorly conceived elevator music . add to this the film's faux-mysticism , including spirit animals and dream visions , and a narrator who sounds like a psychic you'd expect to hear on a 1-900 number , and you get a movie that has serious problems being serious . the clan of the cave bear is rated r , though it's probably one of the most inoffensive offensive films i've seen in quite a while . it contains several scenes of sex sans nudity . the violence mostly consists of hunting scenes . the funniest moment of the movie occurs when a neanderthal in love with ayla attempts to rescue her from a ferocious bear . the bear bites his head off and the audience sees it rolling about . although this may sound gratuitous , i'm sure , it's so cheesy that it probably won't bother most people . the clan of the cave bear is a bad movie . however , as i wrote at the beginning of this review , it does have the distinction of originality . typically when i think of bottom-of-the-barrel films dealing with early man , fantasy movies involving dinosaurs ( who did not exist at the same time as man ) and raquel welch come to mind . the clan of the cave bear tries so hard to be serious that , though it's so bad , the audience is still interested by the unique setting and characters of the movie ( which is why i awarded this turkey two stars ) . i have to think that fans of the book would be disappointed with this film version ; however , i'm only basing this observation on the fact that the book is almost invariably better than the movie . i shudder to think that it could be otherwise . . .
{ "pile_set_name": "Github" }
/* * Copyright (c) 2018-2020 Arm Limited. * * SPDX-License-Identifier: MIT * * 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. */ #ifndef ARM_COMPUTE_WRAPPER_STORE_H #define ARM_COMPUTE_WRAPPER_STORE_H #include <arm_neon.h> namespace arm_compute { namespace wrapper { #define VSTORE_IMPL(stype, vtype, prefix, postfix) \ inline void vstore(stype *ptr, vtype val) \ { \ prefix##_##postfix(ptr, val); \ } VSTORE_IMPL(uint8_t, uint8x8_t, vst1, u8) VSTORE_IMPL(uint8_t, uint8x8x2_t, vst2, u8) VSTORE_IMPL(int8_t, int8x8_t, vst1, s8) VSTORE_IMPL(int8_t, int8x8x2_t, vst2, s8) VSTORE_IMPL(uint16_t, uint16x4_t, vst1, u16) VSTORE_IMPL(int16_t, int16x4_t, vst1, s16) VSTORE_IMPL(uint32_t, uint32x2_t, vst1, u32) VSTORE_IMPL(int32_t, int32x2_t, vst1, s32) //VSTORE_IMPL(uint64_t, 1, vst1, u64) //VSTORE_IMPL(int64_t, 1, vst1, s64) VSTORE_IMPL(float, float32x2_t, vst1, f32) #ifdef __ARM_FEATURE_FP16_VECTOR_ARITHMETIC VSTORE_IMPL(float16_t, float16x4_t, vst1, f16) #endif // __ARM_FEATURE_FP16_VECTOR_ARITHMETIC VSTORE_IMPL(uint8_t, uint8x16_t, vst1q, u8) VSTORE_IMPL(int8_t, int8x16_t, vst1q, s8) VSTORE_IMPL(uint16_t, uint16x8_t, vst1q, u16) VSTORE_IMPL(int16_t, int16x8_t, vst1q, s16) VSTORE_IMPL(uint32_t, uint32x4_t, vst1q, u32) VSTORE_IMPL(int32_t, int32x4_t, vst1q, s32) //VSTORE_IMPL(uint64_t, 2, vst1q, u64) //VSTORE_IMPL(int64_t, 2, vst1q, s64) VSTORE_IMPL(float, float32x4_t, vst1q, f32) #ifdef __ARM_FEATURE_FP16_VECTOR_ARITHMETIC VSTORE_IMPL(float16_t, float16x8_t, vst1q, f16) #endif // __ARM_FEATURE_FP16_VECTOR_ARITHMETIC #undef VSTORE_IMPL } // namespace wrapper } // namespace arm_compute #endif /* ARM_COMPUTE_WRAPPER_STORE_H */
{ "pile_set_name": "Github" }
<?php declare(strict_types=1); /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ namespace TYPO3\CMS\Frontend\Tests\Unit\Page; use PHPUnit\Framework\TestCase; use TYPO3\CMS\Core\Utility\PermutationUtility; use TYPO3\CMS\Frontend\Page\CacheHashConfiguration; class CacheHashConfigurationTest extends TestCase { public function nonArrayValueThrowsExceptionDataProvider(): array { return PermutationUtility::meltArrayItems([ [ CacheHashConfiguration::ASPECT_CACHED_PARAMETERS_WHITELIST, CacheHashConfiguration::ASPECT_EXCLUDED_PARAMETERS, CacheHashConfiguration::ASPECT_EXCLUDED_PARAMETERS, CacheHashConfiguration::ASPECT_REQUIRED_CACHE_HASH_PRESENCE_PARAMETERS, ], ['true', true, 1, new \stdClass()], ]); } /** * @param string $aspect * @param mixed $value * * @test * @dataProvider nonArrayValueThrowsExceptionDataProvider */ public function nonArrayValueThrowsException(string $aspect, $value): void { $this->expectException(\LogicException::class); $this->expectExceptionCode(1580225311); new CacheHashConfiguration([$aspect => $value]); } public function nonScalarValueThrowsExceptionDataProvider(): array { return PermutationUtility::meltArrayItems([ [ CacheHashConfiguration::ASPECT_CACHED_PARAMETERS_WHITELIST, CacheHashConfiguration::ASPECT_EXCLUDED_PARAMETERS, CacheHashConfiguration::ASPECT_EXCLUDED_PARAMETERS, CacheHashConfiguration::ASPECT_REQUIRED_CACHE_HASH_PRESENCE_PARAMETERS, ], [null, [], new \stdClass()] ]); } /** * @param string $aspect * @param mixed $value * * @test * @dataProvider nonScalarValueThrowsExceptionDataProvider */ public function nonScalarValueThrowsException(string $aspect, $value): void { $this->expectException(\LogicException::class); $this->expectExceptionCode(1580225312); new CacheHashConfiguration([$aspect => [$value]]); } public function emptyIndicatedValueThrowsExceptionDataProvider(): array { return PermutationUtility::meltArrayItems([ [ CacheHashConfiguration::ASPECT_CACHED_PARAMETERS_WHITELIST, CacheHashConfiguration::ASPECT_EXCLUDED_PARAMETERS, CacheHashConfiguration::ASPECT_EXCLUDED_PARAMETERS, CacheHashConfiguration::ASPECT_REQUIRED_CACHE_HASH_PRESENCE_PARAMETERS, ], ['=', '^', '~'] ]); } /** * @param string $aspect * @param string $value * * @test * @dataProvider emptyIndicatedValueThrowsExceptionDataProvider */ public function emptyIndicatedValueThrowsException(string $aspect, string $value): void { $this->expectException(\LogicException::class); $this->expectExceptionCode(1580225313); new CacheHashConfiguration([$aspect => [$value]]); } public function equalsResolvesParameterValueDataProvider(): array { return PermutationUtility::meltArrayItems([ [ CacheHashConfiguration::ASPECT_CACHED_PARAMETERS_WHITELIST, CacheHashConfiguration::ASPECT_EXCLUDED_PARAMETERS, CacheHashConfiguration::ASPECT_EXCLUDED_PARAMETERS, CacheHashConfiguration::ASPECT_REQUIRED_CACHE_HASH_PRESENCE_PARAMETERS, ], [['equals-a', '=equals-b', '^equals', '~equals']], [['equals-a', 'equals-b']], [['eq', 'equals', 'other', 'prefixed-equals-other']] ]); } /** * @param string $aspect * @param array $values * @param array $positives * @param array $negatives * * @test * @dataProvider equalsResolvesParameterValueDataProvider */ public function equalsResolvesParameterValue(string $aspect, array $values, array $positives, array $negatives): void { $configuration = new CacheHashConfiguration([$aspect => $values]); foreach ($positives as $probe) { self::assertTrue($configuration->equals($aspect, $probe), $probe); } foreach ($negatives as $probe) { self::assertFalse($configuration->equals($aspect, $probe), $probe); } } public function startsWithResolvesParameterValueDataProvider(): array { return PermutationUtility::meltArrayItems([ [ CacheHashConfiguration::ASPECT_CACHED_PARAMETERS_WHITELIST, CacheHashConfiguration::ASPECT_EXCLUDED_PARAMETERS, CacheHashConfiguration::ASPECT_EXCLUDED_PARAMETERS, CacheHashConfiguration::ASPECT_REQUIRED_CACHE_HASH_PRESENCE_PARAMETERS, ], [['equals-a', '=equals-b', '^equals', '~equals']], [['equals', 'equals-a', 'equals-b', 'equals-other']], [['eq', 'other', 'prefixed-equals-other']] ]); } /** * @param string $aspect * @param array $values * @param array $positives * @param array $negatives * * @test * @dataProvider startsWithResolvesParameterValueDataProvider */ public function startsWithResolvesParameterValue(string $aspect, array $values, array $positives, array $negatives): void { $configuration = new CacheHashConfiguration([$aspect => $values]); foreach ($positives as $probe) { self::assertTrue($configuration->startsWith($aspect, $probe), $probe); } foreach ($negatives as $probe) { self::assertFalse($configuration->startsWith($aspect, $probe), $probe); } } public function containsResolvesParameterValueDataProvider(): array { return PermutationUtility::meltArrayItems([ [ CacheHashConfiguration::ASPECT_CACHED_PARAMETERS_WHITELIST, CacheHashConfiguration::ASPECT_EXCLUDED_PARAMETERS, CacheHashConfiguration::ASPECT_EXCLUDED_PARAMETERS, CacheHashConfiguration::ASPECT_REQUIRED_CACHE_HASH_PRESENCE_PARAMETERS, ], [['equals-a', '=equals-b', '^equals', '~equals']], [['equals', 'equals-a', 'equals-b', 'equals-other', 'prefixed-equals-other']], [['eq', 'other']] ]); } /** * @param string $aspect * @param array $values * @param array $positives * @param array $negatives * * @test * @dataProvider containsResolvesParameterValueDataProvider */ public function containsResolvesParameterValue(string $aspect, array $values, array $positives, array $negatives): void { $configuration = new CacheHashConfiguration([$aspect => $values]); foreach ($positives as $probe) { self::assertTrue($configuration->contains($aspect, $probe), $probe); } foreach ($negatives as $probe) { self::assertFalse($configuration->contains($aspect, $probe), $probe); } } public function appliesResolvesParameterValueDataProvider(): array { // currently using "contains" data provider, could have own test sets as well return $this->containsResolvesParameterValueDataProvider(); } /** * @param string $aspect * @param array $values * @param array $positives * @param array $negatives * * @test * @dataProvider appliesResolvesParameterValueDataProvider */ public function appliesResolvesParameterValue(string $aspect, array $values, array $positives, array $negatives): void { $configuration = new CacheHashConfiguration([$aspect => $values]); foreach ($positives as $probe) { self::assertTrue($configuration->applies($aspect, $probe), $probe); } foreach ($negatives as $probe) { self::assertFalse($configuration->applies($aspect, $probe), $probe); } } }
{ "pile_set_name": "Github" }
package com.netflix.discovery.internal.util; import com.netflix.archaius.api.Config; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; /** * @author David Liu */ public class InternalPrefixedConfigTest { @Test public void testPrefixes() { Config configInstance = Mockito.mock(Config.class); InternalPrefixedConfig config = new InternalPrefixedConfig(configInstance); Assert.assertEquals("", config.getNamespace()); config = new InternalPrefixedConfig(configInstance, "foo"); Assert.assertEquals("foo.", config.getNamespace()); config = new InternalPrefixedConfig(configInstance, "foo", "bar"); Assert.assertEquals("foo.bar.", config.getNamespace()); } }
{ "pile_set_name": "Github" }
// Copyright 2008 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_REGEXP_REGEXP_MACRO_ASSEMBLER_TRACER_H_ #define V8_REGEXP_REGEXP_MACRO_ASSEMBLER_TRACER_H_ #include "src/regexp/regexp-macro-assembler.h" namespace v8 { namespace internal { // Decorator on a RegExpMacroAssembler that write all calls. class RegExpMacroAssemblerTracer: public RegExpMacroAssembler { public: RegExpMacroAssemblerTracer(Isolate* isolate, RegExpMacroAssembler* assembler); virtual ~RegExpMacroAssemblerTracer(); virtual void AbortedCodeGeneration(); virtual int stack_limit_slack() { return assembler_->stack_limit_slack(); } virtual bool CanReadUnaligned() { return assembler_->CanReadUnaligned(); } virtual void AdvanceCurrentPosition(int by); // Signed cp change. virtual void AdvanceRegister(int reg, int by); // r[reg] += by. virtual void Backtrack(); virtual void Bind(Label* label); virtual void CheckAtStart(Label* on_at_start); virtual void CheckCharacter(unsigned c, Label* on_equal); virtual void CheckCharacterAfterAnd(unsigned c, unsigned and_with, Label* on_equal); virtual void CheckCharacterGT(uc16 limit, Label* on_greater); virtual void CheckCharacterLT(uc16 limit, Label* on_less); virtual void CheckGreedyLoop(Label* on_tos_equals_current_position); virtual void CheckNotAtStart(int cp_offset, Label* on_not_at_start); virtual void CheckNotBackReference(int start_reg, bool read_backward, Label* on_no_match); virtual void CheckNotBackReferenceIgnoreCase(int start_reg, bool read_backward, bool unicode, Label* on_no_match); virtual void CheckNotCharacter(unsigned c, Label* on_not_equal); virtual void CheckNotCharacterAfterAnd(unsigned c, unsigned and_with, Label* on_not_equal); virtual void CheckNotCharacterAfterMinusAnd(uc16 c, uc16 minus, uc16 and_with, Label* on_not_equal); virtual void CheckCharacterInRange(uc16 from, uc16 to, Label* on_in_range); virtual void CheckCharacterNotInRange(uc16 from, uc16 to, Label* on_not_in_range); virtual void CheckBitInTable(Handle<ByteArray> table, Label* on_bit_set); virtual void CheckPosition(int cp_offset, Label* on_outside_input); virtual bool CheckSpecialCharacterClass(uc16 type, Label* on_no_match); virtual void Fail(); virtual Handle<HeapObject> GetCode(Handle<String> source); virtual void GoTo(Label* label); virtual void IfRegisterGE(int reg, int comparand, Label* if_ge); virtual void IfRegisterLT(int reg, int comparand, Label* if_lt); virtual void IfRegisterEqPos(int reg, Label* if_eq); virtual IrregexpImplementation Implementation(); virtual void LoadCurrentCharacter(int cp_offset, Label* on_end_of_input, bool check_bounds = true, int characters = 1); virtual void PopCurrentPosition(); virtual void PopRegister(int register_index); virtual void PushBacktrack(Label* label); virtual void PushCurrentPosition(); virtual void PushRegister(int register_index, StackCheckFlag check_stack_limit); virtual void ReadCurrentPositionFromRegister(int reg); virtual void ReadStackPointerFromRegister(int reg); virtual void SetCurrentPositionFromEnd(int by); virtual void SetRegister(int register_index, int to); virtual bool Succeed(); virtual void WriteCurrentPositionToRegister(int reg, int cp_offset); virtual void ClearRegisters(int reg_from, int reg_to); virtual void WriteStackPointerToRegister(int reg); private: RegExpMacroAssembler* assembler_; }; } // namespace internal } // namespace v8 #endif // V8_REGEXP_REGEXP_MACRO_ASSEMBLER_TRACER_H_
{ "pile_set_name": "Github" }
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import libc import func POSIX.getenv /// A class to have better control on tty output streams: standard output and standard error. /// Allows operations like cursor movement and colored text output on tty. public final class TerminalController { /// Terminal color choices. public enum Color { case noColor case red case green case yellow case cyan case white case black case grey /// Returns the color code which can be prefixed on a string to display it in that color. fileprivate var string: String { switch self { case .noColor: return "" case .red: return "\u{001B}[31m" case .green: return "\u{001B}[32m" case .yellow: return "\u{001B}[33m" case .cyan: return "\u{001B}[36m" case .white: return "\u{001B}[37m" case .black: return "\u{001B}[30m" case .grey: return "\u{001B}[30;1m" } } } /// Pointer to output stream to operate on. private var stream: LocalFileOutputByteStream /// Width of the terminal. public let width: Int /// Code to clear the line on a tty. private let clearLineString = "\u{001B}[2K" /// Code to end any currently active wrapping. private let resetString = "\u{001B}[0m" /// Code to make string bold. private let boldString = "\u{001B}[1m" /// Constructs the instance if the stream is a tty. public init?(stream: LocalFileOutputByteStream) { // Make sure this file stream is tty. guard isatty(fileno(stream.filePointer)) != 0 else { return nil } width = TerminalController.terminalWidth() ?? 80 // Assume default if we are not able to determine. self.stream = stream } /// Tries to get the terminal width first using COLUMNS env variable and /// if that fails ioctl method testing on stdout stream. /// /// - Returns: Current width of terminal if it was determinable. public static func terminalWidth() -> Int? { // Try to get from environment. if let columns = POSIX.getenv("COLUMNS"), let width = Int(columns) { return width } // Try determining using ioctl. var ws = winsize() if ioctl(1, UInt(TIOCGWINSZ), &ws) == 0 { return Int(ws.ws_col) } return nil } /// Flushes the stream. public func flush() { stream.flush() } /// Clears the current line and moves the cursor to beginning of the line.. public func clearLine() { stream <<< clearLineString <<< "\r" flush() } /// Moves the cursor y columns up. public func moveCursor(up: Int) { stream <<< "\u{001B}[\(up)A" flush() } /// Writes a string to the stream. public func write(_ string: String, inColor color: Color = .noColor, bold: Bool = false) { writeWrapped(string, inColor: color, bold: bold, stream: stream) flush() } /// Inserts a new line character into the stream. public func endLine() { stream <<< "\n" flush() } /// Wraps the string into the color mentioned. public func wrap(_ string: String, inColor color: Color, bold: Bool = false) -> String { let stream = BufferedOutputByteStream() writeWrapped(string, inColor: color, bold: bold, stream: stream) guard let string = stream.bytes.asString else { fatalError("Couldn't get string value from stream.") } return string } private func writeWrapped(_ string: String, inColor color: Color, bold: Bool = false, stream: OutputByteStream) { // Don't wrap if string is empty or color is no color. guard !string.isEmpty && color != .noColor else { stream <<< string return } stream <<< color.string <<< (bold ? boldString : "") <<< string <<< resetString } }
{ "pile_set_name": "Github" }
// RUN: %clang_cc1 -triple i386-unknown-unknown -emit-llvm -fexceptions -fcxx-exceptions -std=c++11 -o - %s | FileCheck %s struct non_trivial { non_trivial(); ~non_trivial() noexcept(false); }; non_trivial::non_trivial() {} non_trivial::~non_trivial() noexcept(false) {} // We use a virtual base to ensure that the constructor // delegation optimization (complete->base) can't be // performed. struct delegator { non_trivial n; delegator(); delegator(int); delegator(char); delegator(bool); }; delegator::delegator() { throw 0; } delegator::delegator(bool) {} // CHECK-LABEL: define {{.*}} @_ZN9delegatorC2Ec // CHECK: {{.*}} @_ZN9delegatorC2Eb // CHECK: void @__cxa_throw // CHECK: void @__clang_call_terminate // CHECK: {{.*}} @_ZN9delegatorD2Ev // CHECK-LABEL: define {{.*}} @_ZN9delegatorC1Ec // CHECK: {{.*}} @_ZN9delegatorC1Eb // CHECK: void @__cxa_throw // CHECK: void @__clang_call_terminate // CHECK: {{.*}} @_ZN9delegatorD1Ev delegator::delegator(char) : delegator(true) { throw 0; } // CHECK-LABEL: define {{.*}} @_ZN9delegatorC2Ei // CHECK: {{.*}} @_ZN9delegatorC2Ev // CHECK-NOT: void @_ZSt9terminatev // CHECK: ret // CHECK-NOT: void @_ZSt9terminatev // CHECK-LABEL: define {{.*}} @_ZN9delegatorC1Ei // CHECK: {{.*}} @_ZN9delegatorC1Ev // CHECK-NOT: void @_ZSt9terminatev // CHECK: ret // CHECK-NOT: void @_ZSt9terminatev delegator::delegator(int) : delegator() {} namespace PR12890 { class X { int x; X() = default; X(int); }; X::X(int) : X() {} } // CHECK: define {{.*}} @_ZN7PR128901XC1Ei(%"class.PR12890::X"* %this, i32) // CHECK: call void @llvm.memset.p0i8.{{i32|i64}}(i8* align 4 {{.*}}, i8 0, {{i32|i64}} 4, i1 false) namespace PR14588 { void other(); class Base { public: Base() { squawk(); } virtual ~Base() {} virtual void squawk() { other(); } }; class Foo : public virtual Base { public: Foo(); Foo(const void * inVoid); virtual ~Foo() {} virtual void squawk() { other(); } }; // CHECK-LABEL: define void @_ZN7PR145883FooC1Ev(%"class.PR14588::Foo"* // CHECK: call void @_ZN7PR145883FooC1EPKv( // CHECK: invoke void @_ZN7PR145885otherEv() // CHECK: call void @_ZN7PR145883FooD1Ev // CHECK: resume Foo::Foo() : Foo(__null) { other(); } Foo::Foo(const void *inVoid) { squawk(); } }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC") * Copyright (c) 1996-1999 by Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdio.h> #include <string.h> #if defined(_MSC_VER) && _MSC_VER < 1600 # include "uv/stdint-msvc2008.h" #else # include <stdint.h> #endif #include "uv.h" #include "uv-common.h" #ifdef _WIN32 #pragma warning(disable : 6001) #endif #define UV__INET_ADDRSTRLEN 16 #define UV__INET6_ADDRSTRLEN 46 static int inet_ntop4(const unsigned char *src, char *dst, size_t size); static int inet_ntop6(const unsigned char *src, char *dst, size_t size); static int inet_pton4(const char *src, unsigned char *dst); static int inet_pton6(const char *src, unsigned char *dst); int uv_inet_ntop(int af, const void* src, char* dst, size_t size) { switch (af) { case AF_INET: return (inet_ntop4((const unsigned char*)src, dst, size)); case AF_INET6: return (inet_ntop6((const unsigned char*)src, dst, size)); default: return UV_EAFNOSUPPORT; } /* NOTREACHED */ } static int inet_ntop4(const unsigned char *src, char *dst, size_t size) { static const char fmt[] = "%u.%u.%u.%u"; char tmp[UV__INET_ADDRSTRLEN]; int l; l = snprintf(tmp, sizeof(tmp), fmt, src[0], src[1], src[2], src[3]); if (l <= 0 || (size_t) l >= size) { return UV_ENOSPC; } uv__strscpy(dst, tmp, size); return 0; } static int inet_ntop6(const unsigned char *src, char *dst, size_t size) { /* * Note that int32_t and int16_t need only be "at least" large enough * to contain a value of the specified size. On some systems, like * Crays, there is no such thing as an integer variable with 16 bits. * Keep this in mind if you think this function should have been coded * to use pointer overlays. All the world's not a VAX. */ char tmp[UV__INET6_ADDRSTRLEN], *tp; struct { int base, len; } best, cur; unsigned int words[sizeof(struct in6_addr) / sizeof(uint16_t)]; int i; /* * Preprocess: * Copy the input (bytewise) array into a wordwise array. * Find the longest run of 0x00's in src[] for :: shorthanding. */ memset(words, '\0', sizeof words); for (i = 0; i < (int) sizeof(struct in6_addr); i++) words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3)); best.base = -1; best.len = 0; cur.base = -1; cur.len = 0; for (i = 0; i < (int) ARRAY_SIZE(words); i++) { if (words[i] == 0) { if (cur.base == -1) cur.base = i, cur.len = 1; else cur.len++; } else { if (cur.base != -1) { if (best.base == -1 || cur.len > best.len) best = cur; cur.base = -1; } } } if (cur.base != -1) { if (best.base == -1 || cur.len > best.len) best = cur; } if (best.base != -1 && best.len < 2) best.base = -1; /* * Format the result. */ tp = tmp; for (i = 0; i < (int) ARRAY_SIZE(words); i++) { /* Are we inside the best run of 0x00's? */ if (best.base != -1 && i >= best.base && i < (best.base + best.len)) { if (i == best.base) *tp++ = ':'; continue; } /* Are we following an initial run of 0x00s or any real hex? */ if (i != 0) *tp++ = ':'; /* Is this address an encapsulated IPv4? */ if (i == 6 && best.base == 0 && (best.len == 6 || (best.len == 7 && words[7] != 0x0001) || (best.len == 5 && words[5] == 0xffff))) { int err = inet_ntop4(src+12, tp, sizeof tmp - (tp - tmp)); if (err) return err; tp += strlen(tp); break; } tp += sprintf(tp, "%x", words[i]); } /* Was it a trailing run of 0x00's? */ if (best.base != -1 && (best.base + best.len) == ARRAY_SIZE(words)) *tp++ = ':'; *tp++ = '\0'; if (UV_E2BIG == uv__strscpy(dst, tmp, size)) return UV_ENOSPC; return 0; } int uv_inet_pton(int af, const char* src, void* dst) { if (src == NULL || dst == NULL) return UV_EINVAL; switch (af) { case AF_INET: return (inet_pton4(src, (unsigned char*)dst)); case AF_INET6: { int len; char tmp[UV__INET6_ADDRSTRLEN], *s; const char *p; s = (char*) src; p = strchr(src, '%'); if (p != NULL) { s = tmp; len = p - src; if (len > UV__INET6_ADDRSTRLEN-1) return UV_EINVAL; memcpy(s, src, len); s[len] = '\0'; } return inet_pton6(s, (unsigned char*)dst); } default: return UV_EAFNOSUPPORT; } /* NOTREACHED */ } static int inet_pton4(const char *src, unsigned char *dst) { static const char digits[] = "0123456789"; int saw_digit, octets, ch; unsigned char tmp[sizeof(struct in_addr)], *tp; saw_digit = 0; octets = 0; *(tp = tmp) = 0; while ((ch = *src++) != '\0') { const char *pch; if ((pch = strchr(digits, ch)) != NULL) { unsigned int nw = *tp * 10 + (pch - digits); if (saw_digit && *tp == 0) return UV_EINVAL; if (nw > 255) return UV_EINVAL; *tp = nw; if (!saw_digit) { if (++octets > 4) return UV_EINVAL; saw_digit = 1; } } else if (ch == '.' && saw_digit) { if (octets == 4) return UV_EINVAL; *++tp = 0; saw_digit = 0; } else return UV_EINVAL; } if (octets < 4) return UV_EINVAL; memcpy(dst, tmp, sizeof(struct in_addr)); return 0; } static int inet_pton6(const char *src, unsigned char *dst) { static const char xdigits_l[] = "0123456789abcdef", xdigits_u[] = "0123456789ABCDEF"; unsigned char tmp[sizeof(struct in6_addr)], *tp, *endp, *colonp; const char *xdigits, *curtok; int ch, seen_xdigits; unsigned int val; memset((tp = tmp), '\0', sizeof tmp); endp = tp + sizeof tmp; colonp = NULL; /* Leading :: requires some special handling. */ if (*src == ':') if (*++src != ':') return UV_EINVAL; curtok = src; seen_xdigits = 0; val = 0; while ((ch = *src++) != '\0') { const char *pch; if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL) pch = strchr((xdigits = xdigits_u), ch); if (pch != NULL) { val <<= 4; val |= (pch - xdigits); if (++seen_xdigits > 4) return UV_EINVAL; continue; } if (ch == ':') { curtok = src; if (!seen_xdigits) { if (colonp) return UV_EINVAL; colonp = tp; continue; } else if (*src == '\0') { return UV_EINVAL; } if (tp + sizeof(uint16_t) > endp) return UV_EINVAL; *tp++ = (unsigned char) (val >> 8) & 0xff; *tp++ = (unsigned char) val & 0xff; seen_xdigits = 0; val = 0; continue; } if (ch == '.' && ((tp + sizeof(struct in_addr)) <= endp)) { int err = inet_pton4(curtok, tp); if (err == 0) { tp += sizeof(struct in_addr); seen_xdigits = 0; break; /*%< '\\0' was seen by inet_pton4(). */ } } return UV_EINVAL; } if (seen_xdigits) { if (tp + sizeof(uint16_t) > endp) return UV_EINVAL; *tp++ = (unsigned char) (val >> 8) & 0xff; *tp++ = (unsigned char) val & 0xff; } if (colonp != NULL) { /* * Since some memmove()'s erroneously fail to handle * overlapping regions, we'll do the shift by hand. */ const int n = tp - colonp; int i; if (tp == endp) return UV_EINVAL; for (i = 1; i <= n; i++) { endp[- i] = colonp[n - i]; colonp[n - i] = 0; } tp = endp; } if (tp != endp) return UV_EINVAL; memcpy(dst, tmp, sizeof tmp); return 0; }
{ "pile_set_name": "Github" }
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // // System call support for AMD64, FreeBSD // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-56 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-80 JMP syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-104 JMP syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-56 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 JMP syscall·RawSyscall6(SB)
{ "pile_set_name": "Github" }
//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains some templates that are useful if you are working with the // STL at all. // // No library is required when using these functions. // //===----------------------------------------------------------------------===// #ifndef LLVM_ADT_STLEXTRAS_H #define LLVM_ADT_STLEXTRAS_H #include <algorithm> // for std::all_of #include <cassert> #include <cstddef> // for std::size_t #include <cstdlib> // for qsort #include <functional> #include <iterator> #include <limits> #include <memory> #include <tuple> #include <utility> // for std::pair #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/iterator.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" namespace llvm { // Only used by compiler if both template types are the same. Useful when // using SFINAE to test for the existence of member functions. template <typename T, T> struct SameType; namespace detail { template <typename RangeT> using IterOfRange = decltype(std::begin(std::declval<RangeT &>())); template <typename RangeT> using ValueOfRange = typename std::remove_reference<decltype( *std::begin(std::declval<RangeT &>()))>::type; } // End detail namespace //===----------------------------------------------------------------------===// // Extra additions to <functional> //===----------------------------------------------------------------------===// template<class Ty> struct identity : public std::unary_function<Ty, Ty> { Ty &operator()(Ty &self) const { return self; } const Ty &operator()(const Ty &self) const { return self; } }; template<class Ty> struct less_ptr : public std::binary_function<Ty, Ty, bool> { bool operator()(const Ty* left, const Ty* right) const { return *left < *right; } }; template<class Ty> struct greater_ptr : public std::binary_function<Ty, Ty, bool> { bool operator()(const Ty* left, const Ty* right) const { return *right < *left; } }; /// An efficient, type-erasing, non-owning reference to a callable. This is /// intended for use as the type of a function parameter that is not used /// after the function in question returns. /// /// This class does not own the callable, so it is not in general safe to store /// a function_ref. template<typename Fn> class function_ref; template<typename Ret, typename ...Params> class function_ref<Ret(Params...)> { Ret (*callback)(intptr_t callable, Params ...params); intptr_t callable; template<typename Callable> static Ret callback_fn(intptr_t callable, Params ...params) { return (*reinterpret_cast<Callable*>(callable))( std::forward<Params>(params)...); } public: function_ref() : callback(nullptr) {} template <typename Callable> function_ref(Callable &&callable, typename std::enable_if< !std::is_same<typename std::remove_reference<Callable>::type, function_ref>::value>::type * = nullptr) : callback(callback_fn<typename std::remove_reference<Callable>::type>), callable(reinterpret_cast<intptr_t>(&callable)) {} Ret operator()(Params ...params) const { return callback(callable, std::forward<Params>(params)...); } operator bool() const { return callback; } }; // deleter - Very very very simple method that is used to invoke operator // delete on something. It is used like this: // // for_each(V.begin(), B.end(), deleter<Interval>); // template <class T> inline void deleter(T *Ptr) { delete Ptr; } //===----------------------------------------------------------------------===// // Extra additions to <iterator> //===----------------------------------------------------------------------===// // mapped_iterator - This is a simple iterator adapter that causes a function to // be applied whenever operator* is invoked on the iterator. // template <class RootIt, class UnaryFunc> class mapped_iterator { RootIt current; UnaryFunc Fn; public: typedef typename std::iterator_traits<RootIt>::iterator_category iterator_category; typedef typename std::iterator_traits<RootIt>::difference_type difference_type; typedef decltype(std::declval<UnaryFunc>()(*std::declval<RootIt>())) value_type; typedef void pointer; //typedef typename UnaryFunc::result_type *pointer; typedef void reference; // Can't modify value returned by fn typedef RootIt iterator_type; inline const RootIt &getCurrent() const { return current; } inline const UnaryFunc &getFunc() const { return Fn; } inline explicit mapped_iterator(const RootIt &I, UnaryFunc F) : current(I), Fn(F) {} inline value_type operator*() const { // All this work to do this return Fn(*current); // little change } mapped_iterator &operator++() { ++current; return *this; } mapped_iterator &operator--() { --current; return *this; } mapped_iterator operator++(int) { mapped_iterator __tmp = *this; ++current; return __tmp; } mapped_iterator operator--(int) { mapped_iterator __tmp = *this; --current; return __tmp; } mapped_iterator operator+(difference_type n) const { return mapped_iterator(current + n, Fn); } mapped_iterator &operator+=(difference_type n) { current += n; return *this; } mapped_iterator operator-(difference_type n) const { return mapped_iterator(current - n, Fn); } mapped_iterator &operator-=(difference_type n) { current -= n; return *this; } reference operator[](difference_type n) const { return *(*this + n); } bool operator!=(const mapped_iterator &X) const { return !operator==(X); } bool operator==(const mapped_iterator &X) const { return current == X.current; } bool operator<(const mapped_iterator &X) const { return current < X.current; } difference_type operator-(const mapped_iterator &X) const { return current - X.current; } }; template <class Iterator, class Func> inline mapped_iterator<Iterator, Func> operator+(typename mapped_iterator<Iterator, Func>::difference_type N, const mapped_iterator<Iterator, Func> &X) { return mapped_iterator<Iterator, Func>(X.getCurrent() - N, X.getFunc()); } // map_iterator - Provide a convenient way to create mapped_iterators, just like // make_pair is useful for creating pairs... // template <class ItTy, class FuncTy> inline mapped_iterator<ItTy, FuncTy> map_iterator(const ItTy &I, FuncTy F) { return mapped_iterator<ItTy, FuncTy>(I, F); } /// Helper to determine if type T has a member called rbegin(). template <typename Ty> class has_rbegin_impl { typedef char yes[1]; typedef char no[2]; template <typename Inner> static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr); template <typename> static no& test(...); public: static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes); }; /// Metafunction to determine if T& or T has a member called rbegin(). template <typename Ty> struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> { }; // Returns an iterator_range over the given container which iterates in reverse. // Note that the container must have rbegin()/rend() methods for this to work. template <typename ContainerTy> auto reverse(ContainerTy &&C, typename std::enable_if<has_rbegin<ContainerTy>::value>::type * = nullptr) -> decltype(make_range(C.rbegin(), C.rend())) { return make_range(C.rbegin(), C.rend()); } // Returns a std::reverse_iterator wrapped around the given iterator. template <typename IteratorTy> std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) { return std::reverse_iterator<IteratorTy>(It); } // Returns an iterator_range over the given container which iterates in reverse. // Note that the container must have begin()/end() methods which return // bidirectional iterators for this to work. template <typename ContainerTy> auto reverse( ContainerTy &&C, typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr) -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)), llvm::make_reverse_iterator(std::begin(C)))) { return make_range(llvm::make_reverse_iterator(std::end(C)), llvm::make_reverse_iterator(std::begin(C))); } /// An iterator adaptor that filters the elements of given inner iterators. /// /// The predicate parameter should be a callable object that accepts the wrapped /// iterator's reference type and returns a bool. When incrementing or /// decrementing the iterator, it will call the predicate on each element and /// skip any where it returns false. /// /// \code /// int A[] = { 1, 2, 3, 4 }; /// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; }); /// // R contains { 1, 3 }. /// \endcode template <typename WrappedIteratorT, typename PredicateT> class filter_iterator : public iterator_adaptor_base< filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT, typename std::common_type< std::forward_iterator_tag, typename std::iterator_traits< WrappedIteratorT>::iterator_category>::type> { using BaseT = iterator_adaptor_base< filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT, typename std::common_type< std::forward_iterator_tag, typename std::iterator_traits<WrappedIteratorT>::iterator_category>:: type>; struct PayloadType { WrappedIteratorT End; PredicateT Pred; }; Optional<PayloadType> Payload; void findNextValid() { assert(Payload && "Payload should be engaged when findNextValid is called"); while (this->I != Payload->End && !Payload->Pred(*this->I)) BaseT::operator++(); } // Construct the begin iterator. The begin iterator requires to know where end // is, so that it can properly stop when it hits end. filter_iterator(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred) : BaseT(std::move(Begin)), Payload(PayloadType{std::move(End), std::move(Pred)}) { findNextValid(); } // Construct the end iterator. It's not incrementable, so Payload doesn't // have to be engaged. filter_iterator(WrappedIteratorT End) : BaseT(End) {} public: using BaseT::operator++; filter_iterator &operator++() { BaseT::operator++(); findNextValid(); return *this; } template <typename RT, typename PT> friend iterator_range<filter_iterator<detail::IterOfRange<RT>, PT>> make_filter_range(RT &&, PT); }; /// Convenience function that takes a range of elements and a predicate, /// and return a new filter_iterator range. /// /// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the /// lifetime of that temporary is not kept by the returned range object, and the /// temporary is going to be dropped on the floor after the make_iterator_range /// full expression that contains this function call. template <typename RangeT, typename PredicateT> iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>> make_filter_range(RangeT &&Range, PredicateT Pred) { using FilterIteratorT = filter_iterator<detail::IterOfRange<RangeT>, PredicateT>; return make_range(FilterIteratorT(std::begin(std::forward<RangeT>(Range)), std::end(std::forward<RangeT>(Range)), std::move(Pred)), FilterIteratorT(std::end(std::forward<RangeT>(Range)))); } // forward declarations required by zip_shortest/zip_first template <typename R, typename UnaryPredicate> bool all_of(R &&range, UnaryPredicate P); template <size_t... I> struct index_sequence; template <class... Ts> struct index_sequence_for; namespace detail { using std::declval; // We have to alias this since inlining the actual type at the usage site // in the parameter list of iterator_facade_base<> below ICEs MSVC 2017. template<typename... Iters> struct ZipTupleType { typedef std::tuple<decltype(*declval<Iters>())...> type; }; template <typename ZipType, typename... Iters> using zip_traits = iterator_facade_base< ZipType, typename std::common_type<std::bidirectional_iterator_tag, typename std::iterator_traits< Iters>::iterator_category...>::type, // ^ TODO: Implement random access methods. typename ZipTupleType<Iters...>::type, typename std::iterator_traits<typename std::tuple_element< 0, std::tuple<Iters...>>::type>::difference_type, // ^ FIXME: This follows boost::make_zip_iterator's assumption that all // inner iterators have the same difference_type. It would fail if, for // instance, the second field's difference_type were non-numeric while the // first is. typename ZipTupleType<Iters...>::type *, typename ZipTupleType<Iters...>::type>; template <typename ZipType, typename... Iters> struct zip_common : public zip_traits<ZipType, Iters...> { using Base = zip_traits<ZipType, Iters...>; using value_type = typename Base::value_type; std::tuple<Iters...> iterators; protected: template <size_t... Ns> value_type deref(index_sequence<Ns...>) const { return value_type(*std::get<Ns>(iterators)...); } template <size_t... Ns> decltype(iterators) tup_inc(index_sequence<Ns...>) const { return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...); } template <size_t... Ns> decltype(iterators) tup_dec(index_sequence<Ns...>) const { return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...); } public: zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {} value_type operator*() { return deref(index_sequence_for<Iters...>{}); } const value_type operator*() const { return deref(index_sequence_for<Iters...>{}); } ZipType &operator++() { iterators = tup_inc(index_sequence_for<Iters...>{}); return *reinterpret_cast<ZipType *>(this); } ZipType &operator--() { static_assert(Base::IsBidirectional, "All inner iterators must be at least bidirectional."); iterators = tup_dec(index_sequence_for<Iters...>{}); return *reinterpret_cast<ZipType *>(this); } }; template <typename... Iters> struct zip_first : public zip_common<zip_first<Iters...>, Iters...> { using Base = zip_common<zip_first<Iters...>, Iters...>; bool operator==(const zip_first<Iters...> &other) const { return std::get<0>(this->iterators) == std::get<0>(other.iterators); } zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {} }; template <typename... Iters> class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> { template <size_t... Ns> bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const { return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) != std::get<Ns>(other.iterators)...}, identity<bool>{}); } public: using Base = zip_common<zip_shortest<Iters...>, Iters...>; bool operator==(const zip_shortest<Iters...> &other) const { return !test(other, index_sequence_for<Iters...>{}); } zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {} }; template <template <typename...> class ItType, typename... Args> class zippy { public: using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>; using iterator_category = typename iterator::iterator_category; using value_type = typename iterator::value_type; using difference_type = typename iterator::difference_type; using pointer = typename iterator::pointer; using reference = typename iterator::reference; private: std::tuple<Args...> ts; template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const { return iterator(std::begin(std::get<Ns>(ts))...); } template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const { return iterator(std::end(std::get<Ns>(ts))...); } public: iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); } iterator end() const { return end_impl(index_sequence_for<Args...>{}); } zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {} }; } // End detail namespace /// zip iterator for two or more iteratable types. template <typename T, typename U, typename... Args> detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u, Args &&... args) { return detail::zippy<detail::zip_shortest, T, U, Args...>( std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); } /// zip iterator that, for the sake of efficiency, assumes the first iteratee to /// be the shortest. template <typename T, typename U, typename... Args> detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u, Args &&... args) { return detail::zippy<detail::zip_first, T, U, Args...>( std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...); } /// Iterator wrapper that concatenates sequences together. /// /// This can concatenate different iterators, even with different types, into /// a single iterator provided the value types of all the concatenated /// iterators expose `reference` and `pointer` types that can be converted to /// `ValueT &` and `ValueT *` respectively. It doesn't support more /// interesting/customized pointer or reference types. /// /// Currently this only supports forward or higher iterator categories as /// inputs and always exposes a forward iterator interface. template <typename ValueT, typename... IterTs> class concat_iterator : public iterator_facade_base<concat_iterator<ValueT, IterTs...>, std::forward_iterator_tag, ValueT> { typedef typename concat_iterator::iterator_facade_base BaseT; /// We store both the current and end iterators for each concatenated /// sequence in a tuple of pairs. /// /// Note that something like iterator_range seems nice at first here, but the /// range properties are of little benefit and end up getting in the way /// because we need to do mutation on the current iterators. std::tuple<std::pair<IterTs, IterTs>...> IterPairs; /// Attempts to increment a specific iterator. /// /// Returns true if it was able to increment the iterator. Returns false if /// the iterator is already at the end iterator. template <size_t Index> bool incrementHelper() { auto &IterPair = std::get<Index>(IterPairs); if (IterPair.first == IterPair.second) return false; ++IterPair.first; return true; } /// Increments the first non-end iterator. /// /// It is an error to call this with all iterators at the end. template <size_t... Ns> void increment(index_sequence<Ns...>) { // Build a sequence of functions to increment each iterator if possible. bool (concat_iterator::*IncrementHelperFns[])() = { &concat_iterator::incrementHelper<Ns>...}; // Loop over them, and stop as soon as we succeed at incrementing one. for (auto &IncrementHelperFn : IncrementHelperFns) if ((this->*IncrementHelperFn)()) return; llvm_unreachable("Attempted to increment an end concat iterator!"); } /// Returns null if the specified iterator is at the end. Otherwise, /// dereferences the iterator and returns the address of the resulting /// reference. template <size_t Index> ValueT *getHelper() const { auto &IterPair = std::get<Index>(IterPairs); if (IterPair.first == IterPair.second) return nullptr; return &*IterPair.first; } /// Finds the first non-end iterator, dereferences, and returns the resulting /// reference. /// /// It is an error to call this with all iterators at the end. template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const { // Build a sequence of functions to get from iterator if possible. ValueT *(concat_iterator::*GetHelperFns[])() const = { &concat_iterator::getHelper<Ns>...}; // Loop over them, and return the first result we find. for (auto &GetHelperFn : GetHelperFns) if (ValueT *P = (this->*GetHelperFn)()) return *P; llvm_unreachable("Attempted to get a pointer from an end concat iterator!"); } public: /// Constructs an iterator from a squence of ranges. /// /// We need the full range to know how to switch between each of the /// iterators. template <typename... RangeTs> explicit concat_iterator(RangeTs &&... Ranges) : IterPairs({std::begin(Ranges), std::end(Ranges)}...) {} using BaseT::operator++; concat_iterator &operator++() { increment(index_sequence_for<IterTs...>()); return *this; } ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); } bool operator==(const concat_iterator &RHS) const { return IterPairs == RHS.IterPairs; } }; namespace detail { /// Helper to store a sequence of ranges being concatenated and access them. /// /// This is designed to facilitate providing actual storage when temporaries /// are passed into the constructor such that we can use it as part of range /// based for loops. template <typename ValueT, typename... RangeTs> class concat_range { public: typedef concat_iterator<ValueT, decltype(std::begin(std::declval<RangeTs &>()))...> iterator; private: std::tuple<RangeTs...> Ranges; template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) { return iterator(std::get<Ns>(Ranges)...); } template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) { return iterator(make_range(std::end(std::get<Ns>(Ranges)), std::end(std::get<Ns>(Ranges)))...); } public: iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); } iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); } concat_range(RangeTs &&... Ranges) : Ranges(std::forward<RangeTs>(Ranges)...) {} }; } /// Concatenated range across two or more ranges. /// /// The desired value type must be explicitly specified. template <typename ValueT, typename... RangeTs> detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) { static_assert(sizeof...(RangeTs) > 1, "Need more than one range to concatenate!"); return detail::concat_range<ValueT, RangeTs...>( std::forward<RangeTs>(Ranges)...); } //===----------------------------------------------------------------------===// // Extra additions to <utility> //===----------------------------------------------------------------------===// /// \brief Function object to check whether the first component of a std::pair /// compares less than the first component of another std::pair. struct less_first { template <typename T> bool operator()(const T &lhs, const T &rhs) const { return lhs.first < rhs.first; } }; /// \brief Function object to check whether the second component of a std::pair /// compares less than the second component of another std::pair. struct less_second { template <typename T> bool operator()(const T &lhs, const T &rhs) const { return lhs.second < rhs.second; } }; // A subset of N3658. More stuff can be added as-needed. /// \brief Represents a compile-time sequence of integers. template <class T, T... I> struct integer_sequence { typedef T value_type; static constexpr size_t size() { return sizeof...(I); } }; /// \brief Alias for the common case of a sequence of size_ts. template <size_t... I> struct index_sequence : integer_sequence<std::size_t, I...> {}; template <std::size_t N, std::size_t... I> struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {}; template <std::size_t... I> struct build_index_impl<0, I...> : index_sequence<I...> {}; /// \brief Creates a compile-time integer sequence for a parameter pack. template <class... Ts> struct index_sequence_for : build_index_impl<sizeof...(Ts)> {}; /// Utility type to build an inheritance chain that makes it easy to rank /// overload candidates. template <int N> struct rank : rank<N - 1> {}; template <> struct rank<0> {}; /// \brief traits class for checking whether type T is one of any of the given /// types in the variadic list. template <typename T, typename... Ts> struct is_one_of { static const bool value = false; }; template <typename T, typename U, typename... Ts> struct is_one_of<T, U, Ts...> { static const bool value = std::is_same<T, U>::value || is_one_of<T, Ts...>::value; }; /// \brief traits class for checking whether type T is a base class for all /// the given types in the variadic list. template <typename T, typename... Ts> struct are_base_of { static const bool value = true; }; template <typename T, typename U, typename... Ts> struct are_base_of<T, U, Ts...> { static const bool value = std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value; }; //===----------------------------------------------------------------------===// // Extra additions for arrays //===----------------------------------------------------------------------===// /// Find the length of an array. template <class T, std::size_t N> constexpr inline size_t array_lengthof(T (&)[N]) { return N; } /// Adapt std::less<T> for array_pod_sort. template<typename T> inline int array_pod_sort_comparator(const void *P1, const void *P2) { if (std::less<T>()(*reinterpret_cast<const T*>(P1), *reinterpret_cast<const T*>(P2))) return -1; if (std::less<T>()(*reinterpret_cast<const T*>(P2), *reinterpret_cast<const T*>(P1))) return 1; return 0; } /// get_array_pod_sort_comparator - This is an internal helper function used to /// get type deduction of T right. template<typename T> inline int (*get_array_pod_sort_comparator(const T &)) (const void*, const void*) { return array_pod_sort_comparator<T>; } /// array_pod_sort - This sorts an array with the specified start and end /// extent. This is just like std::sort, except that it calls qsort instead of /// using an inlined template. qsort is slightly slower than std::sort, but /// most sorts are not performance critical in LLVM and std::sort has to be /// template instantiated for each type, leading to significant measured code /// bloat. This function should generally be used instead of std::sort where /// possible. /// /// This function assumes that you have simple POD-like types that can be /// compared with std::less and can be moved with memcpy. If this isn't true, /// you should use std::sort. /// /// NOTE: If qsort_r were portable, we could allow a custom comparator and /// default to std::less. template<class IteratorTy> inline void array_pod_sort(IteratorTy Start, IteratorTy End) { // Don't inefficiently call qsort with one element or trigger undefined // behavior with an empty sequence. auto NElts = End - Start; if (NElts <= 1) return; qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start)); } template <class IteratorTy> inline void array_pod_sort( IteratorTy Start, IteratorTy End, int (*Compare)( const typename std::iterator_traits<IteratorTy>::value_type *, const typename std::iterator_traits<IteratorTy>::value_type *)) { // Don't inefficiently call qsort with one element or trigger undefined // behavior with an empty sequence. auto NElts = End - Start; if (NElts <= 1) return; qsort(&*Start, NElts, sizeof(*Start), reinterpret_cast<int (*)(const void *, const void *)>(Compare)); } //===----------------------------------------------------------------------===// // Extra additions to <algorithm> //===----------------------------------------------------------------------===// /// For a container of pointers, deletes the pointers and then clears the /// container. template<typename Container> void DeleteContainerPointers(Container &C) { for (auto V : C) delete V; C.clear(); } /// In a container of pairs (usually a map) whose second element is a pointer, /// deletes the second elements and then clears the container. template<typename Container> void DeleteContainerSeconds(Container &C) { for (auto &V : C) delete V.second; C.clear(); } /// Provide wrappers to std::all_of which take ranges instead of having to pass /// begin/end explicitly. template <typename R, typename UnaryPredicate> bool all_of(R &&Range, UnaryPredicate P) { return std::all_of(std::begin(Range), std::end(Range), P); } /// Provide wrappers to std::any_of which take ranges instead of having to pass /// begin/end explicitly. template <typename R, typename UnaryPredicate> bool any_of(R &&Range, UnaryPredicate P) { return std::any_of(std::begin(Range), std::end(Range), P); } /// Provide wrappers to std::none_of which take ranges instead of having to pass /// begin/end explicitly. template <typename R, typename UnaryPredicate> bool none_of(R &&Range, UnaryPredicate P) { return std::none_of(std::begin(Range), std::end(Range), P); } /// Provide wrappers to std::find which take ranges instead of having to pass /// begin/end explicitly. template <typename R, typename T> auto find(R &&Range, const T &Val) -> decltype(std::begin(Range)) { return std::find(std::begin(Range), std::end(Range), Val); } /// Provide wrappers to std::find_if which take ranges instead of having to pass /// begin/end explicitly. template <typename R, typename UnaryPredicate> auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) { return std::find_if(std::begin(Range), std::end(Range), P); } template <typename R, typename UnaryPredicate> auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) { return std::find_if_not(std::begin(Range), std::end(Range), P); } /// Provide wrappers to std::remove_if which take ranges instead of having to /// pass begin/end explicitly. template <typename R, typename UnaryPredicate> auto remove_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) { return std::remove_if(std::begin(Range), std::end(Range), P); } /// Provide wrappers to std::copy_if which take ranges instead of having to /// pass begin/end explicitly. template <typename R, typename OutputIt, typename UnaryPredicate> OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) { return std::copy_if(std::begin(Range), std::end(Range), Out, P); } /// Wrapper function around std::find to detect if an element exists /// in a container. template <typename R, typename E> bool is_contained(R &&Range, const E &Element) { return std::find(std::begin(Range), std::end(Range), Element) != std::end(Range); } /// Wrapper function around std::count to count the number of times an element /// \p Element occurs in the given range \p Range. template <typename R, typename E> auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(std::begin(Range))>::difference_type { return std::count(std::begin(Range), std::end(Range), Element); } /// Wrapper function around std::count_if to count the number of times an /// element satisfying a given predicate occurs in a range. template <typename R, typename UnaryPredicate> auto count_if(R &&Range, UnaryPredicate P) -> typename std::iterator_traits< decltype(std::begin(Range))>::difference_type { return std::count_if(std::begin(Range), std::end(Range), P); } /// Wrapper function around std::transform to apply a function to a range and /// store the result elsewhere. template <typename R, typename OutputIt, typename UnaryPredicate> OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) { return std::transform(std::begin(Range), std::end(Range), d_first, P); } /// Provide wrappers to std::partition which take ranges instead of having to /// pass begin/end explicitly. template <typename R, typename UnaryPredicate> auto partition(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) { return std::partition(std::begin(Range), std::end(Range), P); } /// \brief Given a range of type R, iterate the entire range and return a /// SmallVector with elements of the vector. This is useful, for example, /// when you want to iterate a range and then sort the results. template <unsigned Size, typename R> SmallVector<typename std::remove_const<detail::ValueOfRange<R>>::type, Size> to_vector(R &&Range) { return {std::begin(Range), std::end(Range)}; } /// Provide a container algorithm similar to C++ Library Fundamentals v2's /// `erase_if` which is equivalent to: /// /// C.erase(remove_if(C, pred), C.end()); /// /// This version works for any container with an erase method call accepting /// two iterators. template <typename Container, typename UnaryPredicate> void erase_if(Container &C, UnaryPredicate P) { C.erase(remove_if(C, P), C.end()); } //===----------------------------------------------------------------------===// // Extra additions to <memory> //===----------------------------------------------------------------------===// // Implement make_unique according to N3656. /// \brief Constructs a `new T()` with the given args and returns a /// `unique_ptr<T>` which owns the object. /// /// Example: /// /// auto p = make_unique<int>(); /// auto p = make_unique<std::tuple<int, int>>(0, 1); template <class T, class... Args> typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type make_unique(Args &&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } /// \brief Constructs a `new T[n]` with the given args and returns a /// `unique_ptr<T[]>` which owns the object. /// /// \param n size of the new array. /// /// Example: /// /// auto p = make_unique<int[]>(2); // value-initializes the array with 0's. template <class T> typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0, std::unique_ptr<T>>::type make_unique(size_t n) { return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]()); } /// This function isn't used and is only here to provide better compile errors. template <class T, class... Args> typename std::enable_if<std::extent<T>::value != 0>::type make_unique(Args &&...) = delete; struct FreeDeleter { void operator()(void* v) { ::free(v); } }; template<typename First, typename Second> struct pair_hash { size_t operator()(const std::pair<First, Second> &P) const { return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second); } }; /// A functor like C++14's std::less<void> in its absence. struct less { template <typename A, typename B> bool operator()(A &&a, B &&b) const { return std::forward<A>(a) < std::forward<B>(b); } }; /// A functor like C++14's std::equal<void> in its absence. struct equal { template <typename A, typename B> bool operator()(A &&a, B &&b) const { return std::forward<A>(a) == std::forward<B>(b); } }; /// Binary functor that adapts to any other binary functor after dereferencing /// operands. template <typename T> struct deref { T func; // Could be further improved to cope with non-derivable functors and // non-binary functors (should be a variadic template member function // operator()). template <typename A, typename B> auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) { assert(lhs); assert(rhs); return func(*lhs, *rhs); } }; namespace detail { template <typename R> class enumerator_iter; template <typename R> struct result_pair { friend class enumerator_iter<R>; result_pair() : Index(-1) {} result_pair(std::size_t Index, IterOfRange<R> Iter) : Index(Index), Iter(Iter) {} result_pair<R> &operator=(const result_pair<R> &Other) { Index = Other.Index; Iter = Other.Iter; return *this; } std::size_t index() const { return Index; } const ValueOfRange<R> &value() const { return *Iter; } ValueOfRange<R> &value() { return *Iter; } private: std::size_t Index; IterOfRange<R> Iter; }; template <typename R> class enumerator_iter : public iterator_facade_base< enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>, typename std::iterator_traits<IterOfRange<R>>::difference_type, typename std::iterator_traits<IterOfRange<R>>::pointer, typename std::iterator_traits<IterOfRange<R>>::reference> { using result_type = result_pair<R>; public: explicit enumerator_iter(IterOfRange<R> EndIter) : Result(std::numeric_limits<size_t>::max(), EndIter) { } enumerator_iter(std::size_t Index, IterOfRange<R> Iter) : Result(Index, Iter) {} result_type &operator*() { return Result; } const result_type &operator*() const { return Result; } enumerator_iter<R> &operator++() { assert(Result.Index != std::numeric_limits<size_t>::max()); ++Result.Iter; ++Result.Index; return *this; } bool operator==(const enumerator_iter<R> &RHS) const { // Don't compare indices here, only iterators. It's possible for an end // iterator to have different indices depending on whether it was created // by calling std::end() versus incrementing a valid iterator. return Result.Iter == RHS.Result.Iter; } enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) { Result = Other.Result; return *this; } private: result_type Result; }; template <typename R> class enumerator { public: explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {} enumerator_iter<R> begin() { return enumerator_iter<R>(0, std::begin(TheRange)); } enumerator_iter<R> end() { return enumerator_iter<R>(std::end(TheRange)); } private: R TheRange; }; } /// Given an input range, returns a new range whose values are are pair (A,B) /// such that A is the 0-based index of the item in the sequence, and B is /// the value from the original sequence. Example: /// /// std::vector<char> Items = {'A', 'B', 'C', 'D'}; /// for (auto X : enumerate(Items)) { /// printf("Item %d - %c\n", X.index(), X.value()); /// } /// /// Output: /// Item 0 - A /// Item 1 - B /// Item 2 - C /// Item 3 - D /// template <typename R> detail::enumerator<R> enumerate(R &&TheRange) { return detail::enumerator<R>(std::forward<R>(TheRange)); } namespace detail { template <typename F, typename Tuple, std::size_t... I> auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>) -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) { return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...); } } /// Given an input tuple (a1, a2, ..., an), pass the arguments of the /// tuple variadically to f as if by calling f(a1, a2, ..., an) and /// return the result. template <typename F, typename Tuple> auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl( std::forward<F>(f), std::forward<Tuple>(t), build_index_impl< std::tuple_size<typename std::decay<Tuple>::type>::value>{})) { using Indices = build_index_impl< std::tuple_size<typename std::decay<Tuple>::type>::value>; return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t), Indices{}); } } // End llvm namespace #endif
{ "pile_set_name": "Github" }
#!/usr/bin/env python import sys from rqt_rotors.hil_plugin import HilPlugin from rqt_gui.main import Main plugin = 'rqt_rotors.hil_plugin.HilPlugin' main = Main(filename=plugin) sys.exit(main.main(sys.argv, standalone=plugin))
{ "pile_set_name": "Github" }
#include "IRremote.h" #include "IRremoteInt.h" #include "ir_Lego_PF_BitStreamEncoder.h" //============================================================================== // L EEEEEE EEEE OOOO // L E E O O // L EEEE E EEE O O // L E E E O O LEGO Power Functions // LLLLLL EEEEEE EEEE OOOO Copyright (c) 2016 Philipp Henkel //============================================================================== // Supported Devices // LEGO® Power Functions IR Receiver 8884 //+============================================================================= // #if SEND_LEGO_PF #if DEBUG namespace { void logFunctionParameters(uint16_t data, bool repeat) { DBG_PRINT("sendLegoPowerFunctions(data="); DBG_PRINT(data); DBG_PRINT(", repeat="); DBG_PRINTLN(repeat?"true)" : "false)"); } } // anonymous namespace #endif // DEBUG void IRsend::sendLegoPowerFunctions(uint16_t data, bool repeat) { #if DEBUG ::logFunctionParameters(data, repeat); #endif // DEBUG enableIROut(38); static LegoPfBitStreamEncoder bitStreamEncoder; bitStreamEncoder.reset(data, repeat); do { mark(bitStreamEncoder.getMarkDuration()); space(bitStreamEncoder.getPauseDuration()); } while (bitStreamEncoder.next()); } #endif // SEND_LEGO_PF
{ "pile_set_name": "Github" }
.. i18n: .. index:: .. i18n: single: Configuration .. i18n: single: Administration .. .. index:: single: Configuration single: Administration .. i18n: .. _ch-config: .. i18n: .. i18n: ****************************** .. i18n: Configuration & Administration .. i18n: ****************************** .. .. _ch-config: ****************************** 配置与系统管理 ****************************** .. i18n: *This chapter is for the administrators of an OpenERP system. .. i18n: You will learn to configure OpenERP to match it to your company's needs and .. i18n: those of each individual user of the system.* .. *This chapter is for the administrators of an OpenERP system. You will learn to configure OpenERP to match it to your company's needs and those of each individual user of the system.* .. i18n: OpenERP gives you great flexibility in configuring and using it, letting you modify .. i18n: its appearance, the general way it functions and the different analysis tools chosen to match your .. i18n: company's needs most closely. These configuration changes are carried out through the user .. i18n: interface. .. OpenERP gives you great flexibility in configuring and using it, letting you modify its appearance, the general way it functions and the different analysis tools chosen to match your company's needs most closely. These configuration changes are carried out through the user interface. .. i18n: Users can each arrange their own welcome page and their own menu, and you can also personalize .. i18n: OpenERP by assigning each user their own dashboard on their welcome page to provide them with the .. i18n: most up to date information. Then, they can immediately see the information most relevant to them .. i18n: each time they sign in. .. Users can each arrange their own welcome page and their own menu, and you can also personalize OpenERP by assigning each user their own dashboard on their welcome page to provide them with the most up to date information. Then, they can immediately see the information most relevant to them each time they sign in. .. i18n: And OpenERP's main menu can be entirely reorganized. The management of access rights lets you .. i18n: assign certain functions to specific system users. You can also assign groups to the user, .. i18n: which lets him move system documents from state to state (such as .. i18n: the ability to approve employee expense requests). .. And OpenERP's main menu can be entirely reorganized. The management of access rights lets you assign certain functions to specific system users. You can also assign groups to the user, which lets him move system documents from state to state (such as the ability to approve employee expense requests). .. i18n: .. index:: .. i18n: single: configuration .. i18n: single: configuration; parametrization .. i18n: single: configuration; personalization .. i18n: single: configuration; customization .. i18n: single: configuration; setup .. i18n: .. .. .. index:: single: configuration single: configuration; parametrization single: configuration; personalization single: configuration; customization single: configuration; setup .. .. i18n: .. note:: Configuration, Parametrization, Personalization, Customization .. i18n: .. i18n: The word *personalization* is sometimes used in this book where you might expect to find .. i18n: *configuration* or *customization*. .. i18n: .. i18n: *Customization* generally refers to something that requires a bit of technical effort .. i18n: (such as creating specialized code modules) and creates a non-standard system. .. i18n: .. i18n: *Configuration* is less radical – it is the general process of setting all .. i18n: the parameters of the software to fit the needs of your system (often called *parametrization* or *setup*). .. i18n: Configuration is also, by convention, the name of the sub-menu below each of OpenERP's top-level menus that .. i18n: is accessible only to the administrative user for that section. .. i18n: .. i18n: *Personalization* is just that subset of configuration options that shapes the system to the .. i18n: particular operational and/or stylistic wishes of a person or company. .. .. note:: Configuration, Parametrization, Personalization, Customization The word *personalization* is sometimes used in this book where you might expect to find *configuration* or *customization*. *Customization* generally refers to something that requires a bit of technical effort (such as creating specialized code modules) and creates a non-standard system. *Configuration* is less radical – it is the general process of setting all the parameters of the software to fit the needs of your system (often called *parametrization* or *setup*). Configuration is also, by convention, the name of the sub-menu below each of OpenERP's top-level menus that is accessible only to the administrative user for that section. *Personalization* is just that subset of configuration options that shapes the system to the particular operational and/or stylistic wishes of a person or company. .. i18n: Using the *OpenOffice Report Designer* module (:mod:`base_report_designer`), you can change any part of any of the reports .. i18n: produced by the system. The system administrator can configure each report to modify its layout and .. i18n: style, or even the data that is provided there. .. Using the *OpenOffice Report Designer* module (:mod:`base_report_designer`), you can change any part of any of the reports produced by the system. The system administrator can configure each report to modify its layout and style, or even the data that is provided there. .. i18n: .. note:: The OpenOffice Report Designer .. i18n: .. i18n: The OpenOffice Report Designer plug-in enables you not only to configure the reports of the basic products in .. i18n: OpenERP, but also to create entirely new report templates. .. i18n: When the user uses OpenERP's client interface, OpenOffice can create a report template .. i18n: that has access to all the data available to any OpenERP document type. .. i18n: .. i18n: You can easily create fax documents, quotations, or any other commercial document. .. i18n: This functionality enables you to considerably extend the productivity of your salespeople who have .. i18n: to send many proposals to customers. .. .. note:: The OpenOffice Report Designer The OpenOffice Report Designer plug-in enables you not only to configure the reports of the basic products in OpenERP, but also to create entirely new report templates. When the user uses OpenERP's client interface, OpenOffice can create a report template that has access to all the data available to any OpenERP document type. You can easily create fax documents, quotations, or any other commercial document. This functionality enables you to considerably extend the productivity of your salespeople who have to send many proposals to customers. .. i18n: Finally, you will see how to import your data into OpenERP automatically, to migrate all of your .. i18n: data in one single go. .. Finally, you will see how to import your data into OpenERP automatically, to migrate all of your data in one single go. .. i18n: For this chapter, you should start with a fresh database that includes demo data, .. i18n: with :mod:`sale` and its dependencies installed and no particular chart of accounts configured. .. For this chapter, you should start with a fresh database that includes demo data, with :mod:`sale` and its dependencies installed and no particular chart of accounts configured. .. i18n: .. raw:: html .. i18n: .. i18n: <div class="all-toctree"> .. .. raw:: html <div class="all-toctree"> .. i18n: .. toctree:: .. i18n: .. i18n: 8_20_Config_module .. i18n: 8_20_Config_menu .. i18n: 8_20_Config_accessRights .. i18n: 8_20_Config_workflow .. i18n: 8_20_Config_reports .. i18n: 8_20_Config_import_export .. .. toctree:: 8_20_Config_module 8_20_Config_menu 8_20_Config_accessRights 8_20_Config_workflow 8_20_Config_reports 8_20_Config_import_export .. i18n: .. raw:: html .. i18n: .. i18n: </div> .. i18n: .. i18n: .. Copyright © Open Object Press. All rights reserved. .. .. raw:: html </div> .. Copyright © Open Object Press. All rights reserved. .. i18n: .. You may take electronic copy of this publication and distribute it if you don't .. i18n: .. change the content. You can also print a copy to be read by yourself only. .. .. You may take electronic copy of this publication and distribute it if you don't .. change the content. You can also print a copy to be read by yourself only. .. i18n: .. We have contracts with different publishers in different countries to sell and .. i18n: .. distribute paper or electronic based versions of this book (translated or not) .. i18n: .. in bookstores. This helps to distribute and promote the OpenERP product. It .. i18n: .. also helps us to create incentives to pay contributors and authors using author .. i18n: .. rights of these sales. .. .. We have contracts with different publishers in different countries to sell and .. distribute paper or electronic based versions of this book (translated or not) .. in bookstores. This helps to distribute and promote the OpenERP product. It .. also helps us to create incentives to pay contributors and authors using author .. rights of these sales. .. i18n: .. Due to this, grants to translate, modify or sell this book are strictly .. i18n: .. forbidden, unless Tiny SPRL (representing Open Object Press) gives you a .. i18n: .. written authorisation for this. .. .. Due to this, grants to translate, modify or sell this book are strictly .. forbidden, unless Tiny SPRL (representing Open Object Press) gives you a .. written authorisation for this. .. i18n: .. Many of the designations used by manufacturers and suppliers to distinguish their .. i18n: .. products are claimed as trademarks. Where those designations appear in this book, .. i18n: .. and Open Object Press was aware of a trademark claim, the designations have been .. i18n: .. printed in initial capitals. .. .. Many of the designations used by manufacturers and suppliers to distinguish their .. products are claimed as trademarks. Where those designations appear in this book, .. and Open Object Press was aware of a trademark claim, the designations have been .. printed in initial capitals. .. i18n: .. While every precaution has been taken in the preparation of this book, the publisher .. i18n: .. and the authors assume no responsibility for errors or omissions, or for damages .. i18n: .. resulting from the use of the information contained herein. .. .. While every precaution has been taken in the preparation of this book, the publisher .. and the authors assume no responsibility for errors or omissions, or for damages .. resulting from the use of the information contained herein. .. i18n: .. Published by Open Object Press, Grand Rosière, Belgium .. .. Published by Open Object Press, Grand Rosière, Belgium
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xamarin.Forms; using Xamarin.Forms.Xaml; [assembly: XamlCompilation(XamlCompilationOptions.Compile)] namespace FlexLayoutDemos { public partial class App : Application { public App () { InitializeComponent(); MainPage = new NavigationPage(new HomePage()); } protected override void OnStart () { // Handle when your app starts } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } }
{ "pile_set_name": "Github" }
({ next: "Ďalej", previous: "Predchádzajúci", done: "Hotovo" })
{ "pile_set_name": "Github" }
<resources> <string name="app_name">Pie Message</string> <string name="action_settings">Settings</string> <string name="title_activity_message">MessageActivity</string> <string name="insert_number"><![CDATA[<Insert Number>]]></string> <string name="title_activity_conversation">ConversationActivity</string> <string name="hello_world">Hello world!</string> <string name="pref_socket_address_key">prefSocketAddress</string> <string name="welcome_title">Welcome to\nPie Message!</string> </resources>
{ "pile_set_name": "Github" }
################################################################################ # # gdbm # ################################################################################ GDBM_VERSION = 1.11 GDBM_SITE = $(BR2_GNU_MIRROR)/gdbm GDBM_LICENSE = GPLv3+ GDBM_LICENSE_FILES = COPYING GDBM_INSTALL_STAGING = YES $(eval $(autotools-package))
{ "pile_set_name": "Github" }
# Copyright 2015 F5 Networks 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. # from f5.bigip import ManagementRoot from f5.bigip.tm.asm.signatures import Signature from f5.sdk_exception import MissingRequiredCreationParameter import mock import pytest from six import iterkeys @pytest.fixture def FakeSignature(): fake_asm = mock.MagicMock() fake_sig = Signature(fake_asm) fake_sig._meta_data['bigip'].tmos_version = '11.6.0' return fake_sig class TestExportSignature(object): def test_create_two(self, fakeicontrolsession): b = ManagementRoot('192.168.1.1', 'admin', 'admin') t1 = b.tm.asm.signatures_s.signature t2 = b.tm.asm.signatures_s.signature assert t1 is t2 def test_create_no_args(self, FakeSignature): with pytest.raises(MissingRequiredCreationParameter): FakeSignature.create() def test_collection(self, fakeicontrolsession): b = ManagementRoot('192.168.1.1', 'admin', 'admin') t = b.tm.asm.signatures_s test_meta = t._meta_data['attribute_registry'] test_meta2 = t._meta_data['allowed_lazy_attributes'] kind = 'tm:asm:signatures:signaturestate' assert kind in list(iterkeys(test_meta)) assert Signature in test_meta2 assert t._meta_data['object_has_stats'] is False
{ "pile_set_name": "Github" }
<help page="Element Manager"> <p>This is the Element Manager, where you create and edit Elements. Elements are instances of Element Types, and are the building blocks of story and media documents. You should first read <a href="http://bricolagecms.org/docs/current/api/Bric::ElementAdmin" onclick="var newWin = window.open('http://bricolagecms.org/docs/current/api/Bric::ElementAdmin'); newWin.focus(true); return false;">Bric::ElementAdmin</a> in order to understand how to plan your element hierarchy.</p> <p> <dl> <dt>Search</dt> <dd>Searches Elements by name. Do a blank search to list all Categories or click a letter for an alphabetical list. You can also select a type of element to list using the 'Pick a Type' menu.</dd> <dt>Add a New Element</dt> <dd>Click this link to create a new Element. It brings you to the Element Profile page.</dd> <dt>Existing Elements</dt> <dd>Click <em>Edit</em> to modify an Element's profile. Click <em>Log</em> to view its event history. To delete an Element, check the Delete box, scroll to the bottom of the page and click the <em>Delete Checked</em> button.</dd> </dl> </p> </help>
{ "pile_set_name": "Github" }
//** // Print Stylesheet //** @media print { header, nav, footer { display: none; } img { max-width: 500px; } body { font: 14pt Georgia, "Times New Roman", Times, serif; line-height: 1.3; } }
{ "pile_set_name": "Github" }
package liquibase.integration.ant; import junit.framework.TestSuite; import org.apache.ant.antunit.junit3.AntUnitSuite; import org.apache.ant.antunit.junit4.AntUnitSuiteRunner; import org.junit.runner.RunWith; import java.io.File; import java.net.URISyntaxException; import java.net.URL; @RunWith(AntUnitSuiteRunner.class) public class GenerateChangeLogTaskTest extends AbstractAntTaskTest { public static TestSuite suite() throws URISyntaxException { setProperties(); URL resource = GenerateChangeLogTaskTest.class.getResource("/liquibase/integration/ant/GenerateChangeLogTaskTest.xml"); File file = new File(resource.toURI()); return new AntUnitSuite(file, GenerateChangeLogTaskTest.class); } }
{ "pile_set_name": "Github" }
@addTagHelper *, WebVella.Erp.Plugins.Core @addTagHelper *, WebVella.Erp.Web @addTagHelper *, WebVella.TagHelpers @using WebVella.Erp.Web.Utils; @using WebVella.Erp.Web; @using WebVella.Erp.Api.Models; @using WebVella.Erp.Plugins.Project.Components; @{ var options = (PcProjectWidgetTasksQueue.PcProjectWidgetTasksQueueOptions)ViewBag.Options; var erpRequest = (ErpRequestContext)ViewBag.RequestContext; var typeSelectOptions = (List<SelectOption>)ViewBag.TypeOptions; } <wv-row> <wv-column span="4"> <wv-field-datasource name="project_id" value="@options.ProjectId" label-text="Project Id" page-id="erpRequest.Page.Id"></wv-field-datasource> </wv-column> <wv-column span="4"> <wv-field-datasource name="user_id" value="@options.UserId" label-text="User Id" page-id="erpRequest.Page.Id"></wv-field-datasource> </wv-column> <wv-column span="4"> <wv-field-select name="type" value="@options.Type" label-text="Type" options="typeSelectOptions.ToWvSelectOption()" required="true"></wv-field-select> </wv-column> </wv-row>
{ "pile_set_name": "Github" }
// Copyright (c) 2020 10X Genomics, Inc. All rights reserved. package refactoring import ( "fmt" "os" "strings" "github.com/martian-lang/martian/martian/syntax" ) // RemoveUnusedOutputs finds outputs for pipelines and removes them if they are // not bound in any reference, and the pipeline in question is not listed in // topCalls. // // The asts must be fully compiled, and in order to be accurite should contain // the entire set of mros. // // Pipelines will only be edited if they're in the call graph for one or more // topCalls. func RemoveUnusedOutputs(topCalls StringSet, asts []*syntax.Ast) Edit { if len(asts) == 0 { return nil } outputs := make(map[decId]StringSet, len(asts[0].Pipelines)+1) usedPipes := make(map[decId]*syntax.Pipeline) for _, ast := range asts { for _, pipe := range ast.Pipelines { if topCalls.Contains(pipe.Id) { usedPipes[makeDecId(pipe)] = pipe // Add child pipeline outputs to the set of pipelines to // possibly trim. Pipelines which aren't in the call graph // for any top-level pipeline won't get changed. populateChildPipelineOuts(pipe, outputs) } } // Remove top-call pipelines which might also be children of other top // calls for _, pipe := range ast.Pipelines { if topCalls.Contains(pipe.Id) { delete(outputs, makeDecId(pipe)) } } } for len(usedPipes) > 0 && len(outputs) > 0 { newUsed := make(map[decId]*syntax.Pipeline, len(asts[0].Pipelines)+len(usedPipes)) for _, pipe := range usedPipes { usePipeOuts(pipe, newUsed, outputs) } usedPipes = newUsed } if len(outputs) == 0 { return nil } edits := make(editSet, 0, len(outputs)) for id, outputs := range outputs { pipe := getPipeline(id, asts) if pipe != nil { for output := range outputs { fmt.Fprintf(os.Stderr, "Output %s of pipeline %s at %s:%d is not used.\n", output, pipe.Id, pipe.File().FileName, pipe.Line()) edits = append(edits, &removePipelineOutput{ Pipeline: pipe, Output: output, }) } // Remove inputs which are no longer bound. edits = removeUnboundPipelineInputs(pipe, outputs, nil, asts, edits) } } return edits } func populateChildPipelineOuts(pipe *syntax.Pipeline, outputs map[decId]StringSet) { for _, callable := range pipe.Callables.Table { if p, ok := callable.(*syntax.Pipeline); ok && p != nil { if p.OutParams != nil && len(pipe.OutParams.List) > 0 { dec := makeDecId(pipe) if _, ok := outputs[dec]; !ok { outputs[dec] = makePipeOutSet(pipe) } } populateChildPipelineOuts(p, outputs) } } } func getPipeline(id decId, asts []*syntax.Ast) *syntax.Pipeline { for _, ast := range asts { if ast != nil { for _, pipe := range ast.Pipelines { if pipe.Id == id.Name && syntax.DefiningFile(pipe) == id.File { return pipe } } } } return nil } func makePipeOutSet(pipe *syntax.Pipeline) StringSet { outs := make(StringSet, len(pipe.OutParams.List)) for _, param := range pipe.OutParams.List { if !HasKeepComment(param) { outs.Add(param.Id) } } return outs } func usePipeOuts(pipe *syntax.Pipeline, usedPipes map[decId]*syntax.Pipeline, outputs map[decId]StringSet) { if pipe.Retain != nil { for _, ref := range pipe.Retain.Refs { removeCallRef(ref, pipe.Callables.Table, usedPipes, outputs) } } if pipe.Ret != nil { removeBoundCallRefs(pipe.Ret.Bindings, pipe.Callables.Table, usedPipes, outputs) } for _, call := range pipe.Calls { removeBoundCallRefs(call.Bindings, pipe.Callables.Table, usedPipes, outputs) if call.Modifiers != nil && call.Modifiers.Bindings != nil { removeBoundCallRefs(call.Modifiers.Bindings, pipe.Callables.Table, usedPipes, outputs) } } } func removeBoundCallRefs(bindings *syntax.BindStms, callables map[string]syntax.Callable, usedPipes map[decId]*syntax.Pipeline, outputs map[decId]StringSet) { if bindings == nil { return } for _, b := range bindings.List { if b != nil { for _, ref := range b.Exp.FindRefs() { removeCallRef(ref, callables, usedPipes, outputs) } } } } func removeCallRef(ref *syntax.RefExp, callables map[string]syntax.Callable, usedPipes map[decId]*syntax.Pipeline, outputs map[decId]StringSet) { if ref.Kind == syntax.KindCall { c := callables[ref.Id] if c != nil { dec := makeDecId(c) if p, ok := c.(*syntax.Pipeline); ok { usedPipes[dec] = p } if ref.OutputId == "" { // Use all the outs delete(outputs, dec) } else if set, ok := outputs[dec]; ok { if i := strings.IndexByte(ref.OutputId, '.'); i < 0 { set.Remove(ref.OutputId) } else { set.Remove(ref.OutputId[:i]) } if len(set) == 0 { delete(outputs, dec) } } } } } type removePipelineOutput struct { Pipeline *syntax.Pipeline Output string } func (e removePipelineOutput) Apply(ast *syntax.Ast) (int, error) { for _, pipe := range ast.Pipelines { if pipe.Id == e.Pipeline.Id && pipe.File().FullPath == e.Pipeline.File().FullPath { return e.removeParam(pipe) + e.removeRet(pipe), nil } } return 0, nil } func (e removePipelineOutput) removeParam(pipe *syntax.Pipeline) int { if pipe.OutParams == nil { return 0 } for i, param := range pipe.OutParams.List { if param.Id == e.Output { delete(pipe.OutParams.Table, e.Output) if i == 0 { pipe.OutParams.List = pipe.OutParams.List[1:] } else if i == len(pipe.OutParams.List)-1 { pipe.OutParams.List = pipe.OutParams.List[:i] } else { pipe.OutParams.List = append(pipe.OutParams.List[:i:i], pipe.OutParams.List[i+1:]...) } return 1 } } return 0 } func (e removePipelineOutput) removeRet(pipe *syntax.Pipeline) int { if pipe.Ret == nil || pipe.Ret.Bindings == nil { return 0 } for i, param := range pipe.Ret.Bindings.List { if param.Id == e.Output { delete(pipe.Ret.Bindings.Table, e.Output) if i == 0 { pipe.Ret.Bindings.List = pipe.Ret.Bindings.List[1:] } else if i == len(pipe.Ret.Bindings.List)-1 { pipe.Ret.Bindings.List = pipe.Ret.Bindings.List[:i] } else { pipe.Ret.Bindings.List = append(pipe.Ret.Bindings.List[:i:i], pipe.Ret.Bindings.List[i+1:]...) } return 1 } } return 0 }
{ "pile_set_name": "Github" }
/* * 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.shardingsphere.scaling.core.execute.executor.importer; import org.apache.shardingsphere.scaling.core.execute.executor.ShardingScalingExecutor; import org.apache.shardingsphere.scaling.core.execute.executor.channel.Channel; /** * Importer. */ public interface Importer extends ShardingScalingExecutor { /** * Set channel. * * @param channel channel */ void setChannel(Channel channel); /** * Write data to channel. */ void write(); }
{ "pile_set_name": "Github" }
package com.android.dp.book.chapter27.builder; //具体的 Computer 类,Macbook public class Samsung extends SmartDevice { protected Samsung() { } @Override public void setOS() { mOS = "三星 Android系统"; } }
{ "pile_set_name": "Github" }
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On
{ "pile_set_name": "Github" }
/* Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(__has_feature) || !__has_feature(objc_arc) #error "This file requires ARC support." #endif #import "GTMReadMonitorInputStream.h" @implementation GTMReadMonitorInputStream { NSInputStream *_inputStream; // Encapsulated stream that does the work. NSThread *_thread; // Thread in which this object was created. NSArray *_runLoopModes; // Modes for calling callbacks, when necessary. } @synthesize readDelegate = _readDelegate; @synthesize readSelector = _readSelector; @synthesize runLoopModes = _runLoopModes; // We'll forward all unhandled messages to the NSInputStream class or to the encapsulated input // stream. This is needed for all messages sent to NSInputStream which aren't handled by our // superclass; that includes various private run loop calls. + (NSMethodSignature *)methodSignatureForSelector:(SEL)selector { return [NSInputStream methodSignatureForSelector:selector]; } + (void)forwardInvocation:(NSInvocation*)invocation { [invocation invokeWithTarget:[NSInputStream class]]; } - (BOOL)respondsToSelector:(SEL)selector { return [_inputStream respondsToSelector:selector]; } - (NSMethodSignature*)methodSignatureForSelector:(SEL)selector { return [_inputStream methodSignatureForSelector:selector]; } - (void)forwardInvocation:(NSInvocation*)invocation { [invocation invokeWithTarget:_inputStream]; } #pragma mark - + (instancetype)inputStreamWithStream:(NSInputStream *)input { return [[self alloc] initWithStream:input]; } - (instancetype)initWithStream:(NSInputStream *)input { self = [super init]; if (self) { _inputStream = input; _thread = [NSThread currentThread]; } return self; } - (instancetype)init { [self doesNotRecognizeSelector:_cmd]; return nil; } #pragma mark - - (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len { // Read from the encapsulated stream. NSInteger numRead = [_inputStream read:buffer maxLength:len]; if (numRead > 0) { if (_readDelegate && _readSelector) { // Call the read selector with the buffer and number of bytes actually read into it. BOOL isOnOriginalThread = [_thread isEqual:[NSThread currentThread]]; if (isOnOriginalThread) { // Invoke immediately. NSData *data = [NSData dataWithBytesNoCopy:buffer length:(NSUInteger)numRead freeWhenDone:NO]; [self invokeReadSelectorWithBuffer:data]; } else { // Copy the buffer into an NSData to be retained by the performSelector, // and invoke on the proper thread. SEL sel = @selector(invokeReadSelectorWithBuffer:); NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numRead]; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Warc-performSelector-leaks" if (_runLoopModes) { [self performSelector:sel onThread:_thread withObject:data waitUntilDone:NO modes:_runLoopModes]; } else { [self performSelector:sel onThread:_thread withObject:data waitUntilDone:NO]; } #pragma clang diagnostic pop } } } return numRead; } - (void)invokeReadSelectorWithBuffer:(NSData *)data { const void *buffer = data.bytes; int64_t length = (int64_t)data.length; id argSelf = self; id readDelegate = _readDelegate; if (readDelegate) { NSMethodSignature *signature = [readDelegate methodSignatureForSelector:_readSelector]; NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature]; [invocation setSelector:_readSelector]; [invocation setTarget:readDelegate]; [invocation setArgument:&argSelf atIndex:2]; [invocation setArgument:&buffer atIndex:3]; [invocation setArgument:&length atIndex:4]; [invocation invoke]; } } - (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len { return [_inputStream getBuffer:buffer length:len]; } - (BOOL)hasBytesAvailable { return [_inputStream hasBytesAvailable]; } #pragma mark Standard messages // Pass expected messages to our encapsulated stream. // // We want our encapsulated NSInputStream to handle the standard messages; // we don't want the superclass to handle them. - (void)open { [_inputStream open]; } - (void)close { [_inputStream close]; } - (id)delegate { return [_inputStream delegate]; } - (void)setDelegate:(id)delegate { [_inputStream setDelegate:delegate]; } - (id)propertyForKey:(NSString *)key { return [_inputStream propertyForKey:key]; } - (BOOL)setProperty:(id)property forKey:(NSString *)key { return [_inputStream setProperty:property forKey:key]; } - (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode { [_inputStream scheduleInRunLoop:aRunLoop forMode:mode]; } - (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode { [_inputStream removeFromRunLoop:aRunLoop forMode:mode]; } - (NSStreamStatus)streamStatus { return [_inputStream streamStatus]; } - (NSError *)streamError { return [_inputStream streamError]; } @end
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title> Sürümler </title> </head> <body bgcolor="#ffffff"> <h1>Sürümler</h1> <p> Aşağıdaki sürümler yapıldı: <table> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="2_7_0.html">2.7.0</a></td><td>hata düzeltme ve geliştirme sürümü</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="2_6_0.html">2.6.0</a></td><td>hata düzeltme ve geliştirme sürümü</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="2_5_0.html">2.5.0</a></td><td>hata düzeltme ve geliştirme sürümü</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="2_4_3.html">2.4.3</a></td><td>hata düzeltme ve geliştirme sürümü</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="2_4_2.html">2.4.2</a></td><td>hata düzeltme ve az miktarda geliştirme sürümü</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="2_4_1.html">2.4.1</a></td><td>önemli güvenlik düzeltmeler içerir - kullanıcılar en kısa zamanda yükseltmek için teşvik edilir</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="2_4_0.html">2.4.0</a></td><td>saldırı modu, adv fuzzing, adv tarama seçenekleri ve çok daha fazlasını içerir</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="2_3_1.html">2.3.1</a></td><td>hata düzeltme sürümü</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="2_3_0.html">2.3.0</a></td><td>tarayıcı yan etkinlikleri, genişletilmiş kimlik doğrulama, standart dışı uygulama desteği ve çok daha fazlasını içerir</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="2_2_2.html">2.2.2</a></td><td>hata düzeltme sürümü</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="2_2_1.html">2.2.1</a></td><td>hata düzeltme sürümü</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="2_2_0.html">2.2.0</a></td><td>gelişmiş komut dosyası, Zest ve Plug-n-Hack desteği içerir</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="2_1_0.html">2.1.0</a></td><td>hata düzeltme ve az miktarda geliştirme sürümü</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="2_0_0.html">2.0.0</a></td><td>eklenti pazarını, değiştirilen örümceği ve yeni Ajax örümceğini, WebSockets'ı, hızlı başlangıç sekmesini ve çok daha fazlasını içerir</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="1_4_1.html">1.4.1</a></td><td>hata düzeltme sürümü</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="1_4_0.html">1.4.0</a></td><td>sözdizimi vurgulama, fuzzdb entegrasyonu, gelişmiş XSS tarayıcı ve takılabilir uzantıları içerir</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="1_3_4.html">1.3.4</a></td><td>hata düzeltme ve kullanılabilirlik sürümü</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="1_3_3.html">1.3.3</a></td><td>hata düzeltme sürümü</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="1_3_2.html">1.3.2</a></td><td>hata düzeltme sürümü</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="1_3_1.html">1.3.1</a></td><td>hata düzeltme sürümü</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="1_3_0.html">1.3.0</a></td><td>bulandırma, yeni bir API, tamamen uluslararası hale getirme ve beanshell entegrasyonu içerir</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="1_2_0.html">1.2.0</a></td><td>bellek sızıntısı ve çağrılan uygulamaları içerir</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="1_1_0.html">1.1.0</a></td><td>ilk OWASP markalı versiyonu ve kaba kuvvet ve port tarayıcılar dahil</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td><a href="1_0_0.html">1.0.0</a></td><td>ilk sürüm</td></tr> </table> <h2>Ayrıca bakınız</h2> <table> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td> <a href="../intro.html">Tanıtım</a></td><td>ZAP tanıtımı</td></tr> <tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td><td> <a href="../paros.html">Paros Proxy'si</a></td><td>ZAP bir çatallanmadır</td></tr> </table> </body> </html>
{ "pile_set_name": "Github" }
// Protocol Buffers for Go with Gadgets // // Copyright (c) 2018, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // 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. // // 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. // +build !purego !appengine,!js // This file contains the implementation of the proto field accesses using package unsafe. package proto import ( "reflect" "unsafe" ) func (p pointer) getRef() pointer { return pointer{p: (unsafe.Pointer)(&p.p)} } func (p pointer) appendRef(v pointer, typ reflect.Type) { slice := p.getSlice(typ) elem := v.asPointerTo(typ).Elem() newSlice := reflect.Append(slice, elem) slice.Set(newSlice) } func (p pointer) getSlice(typ reflect.Type) reflect.Value { sliceTyp := reflect.SliceOf(typ) slice := p.asPointerTo(sliceTyp) slice = slice.Elem() return slice }
{ "pile_set_name": "Github" }
/* Generate shifts for 1-D regularized autoregression double sides (include the trace self for 3D shifts). */ /* Copyright (C) 2012 University of Texas at Austin 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 02111-1307 USA */ #include <rsf.h> int main(int argc, char* argv[]) { int n1, is, ns, esize, pad; off_t i2, n2; char *trace, *zero; sf_file in, shift; sf_init(argc,argv); in = sf_input("in"); shift = sf_output("out"); if (!sf_histint(in,"n1",&n1)) sf_error("No n1= in input"); n2 = sf_leftsize(in,1); if (!sf_histint(in,"esize",&esize)) { esize=sf_esize(in); } else if (0>=esize) { sf_error("cannot handle esize=%d",esize); } if (!sf_getint("ns",&ns)) sf_error("Need ns="); /* number of shifts */ if (ns >= n1) sf_error("ns=%d is too large",ns); sf_putint(shift,"n2",2*ns+1); sf_shiftdim(in, shift, 2); sf_fileflush(shift,in); sf_setform(in,SF_NATIVE); sf_setform(shift,SF_NATIVE); n1 *= esize; trace = sf_charalloc(n1); zero = sf_charalloc(n1); memset(zero,0,n1); for (i2=0; i2 < n2; i2++) { sf_charread(trace,n1,in); for (is=ns; is >= 0; is--) { pad = is*esize; sf_charwrite(zero,pad,shift); sf_charwrite(trace,n1-pad,shift); } for (is=1; is <= ns; is++) { pad = is*esize; sf_charwrite(trace+pad,n1-pad,shift); sf_charwrite(zero,pad,shift); } } exit(0); }
{ "pile_set_name": "Github" }
// +build js package runewidth func IsEastAsian() bool { // TODO: Implement this for the web. Detect east asian in a compatible way, and return true. return false }
{ "pile_set_name": "Github" }
addSbtPlugin("com.thoughtworks.sbt-best-practice" % "sbt-best-practice" % "7.2.0") addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.2") addSbtPlugin("com.dwijnand" % "sbt-dynver" % "4.0.0") addSbtPlugin("com.jsuereth" % "sbt-pgp" % "2.0.1") addSbtPlugin("org.lyranthe.sbt" % "partial-unification" % "1.1.2") addSbtPlugin("com.thoughtworks.example" % "sbt-example" % "7.0.1") addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.3.7") addSbtPlugin("com.thoughtworks.sbt-scala-js-map" % "sbt-scala-js-map" % "4.0.0") addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.33")
{ "pile_set_name": "Github" }
<?php return array( 'Select' => 'Tallózás', 'Deselect_All' => 'Kijelölés törlése', 'Select_All' => 'Összes kijelölése', 'Erase' => 'Törlés', 'Open' => 'Megnyitás', 'Confirm_del' => 'Biztosan törlöd ezt a fájlt?', 'All' => 'Összes', 'Files' => 'fájl', 'Images' => 'Képek', 'Archives' => 'Tömörített', 'Error_Upload' => 'A kiválasztott fájl mérete túl nagy!', 'Error_extension' => 'A megadott kiterjesztésű fájl nem engedélyezett.', 'Upload_file' => 'Fájl feltöltése', 'Filters' => 'Szűrő', 'Videos' => 'Videó', 'Music' => 'Zene', 'New_Folder' => 'Új mappa', 'Folder_Created' => 'Mappa létrehozva', 'Existing_Folder' => 'Mappa már létezik', 'Confirm_Folder_del' => 'Biztosan törlöd a könyvtárat és annak tartalmát?', 'Return_Files_List' => 'Vissza a fájllistához', 'Preview' => 'Előnézet', 'Download' => 'Letöltés', 'Insert_Folder_Name' => 'Mappa neve:', 'Root' => 'root', 'Rename' => 'Átnevezés', 'Back' => 'vissza', 'View' => 'Nézet', 'View_list' => 'Lista', 'View_columns_list' => 'Oszlopok', 'View_boxes' => 'Miniatűrök', 'Toolbar' => 'Eszközök', 'Actions' => 'Műveletek', 'Rename_existing_file' => 'A fájl már létezik', 'Rename_existing_folder' => 'A mappa már létezik', 'Empty_name' => 'A név nincs megadva', 'Text_filter' => 'szűrés', 'Swipe_help' => 'Húzd az egered a fájl/mappa nevére, hogy lásd az opciókat.', 'Upload_base' => 'Féltöltés a számítógépről', 'Upload_base_help' => "Húzza ide a feltölteni kívánt fájlokat, vagy kattintson a 'Fájl(ok) hozzáadása gombra. Ha kiválasztotta a fájlokat kattintson a 'Feltöltés indítása' gomba. Miután elkészült a feltöltés kattintson a fenti 'Vissza a fájllistához' gombra.", 'Upload_add_files' => 'Fájl(ok) hozzáadása', 'Upload_start' => 'Feltöltés elindítása', 'Upload_error_messages' =>array( 1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini', 2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form', 3 => 'The uploaded file was only partially uploaded', 4 => 'No file was uploaded', 6 => 'Missing a temporary folder', 7 => 'Failed to write file to disk', 8 => 'A PHP extension stopped the file upload', 'post_max_size' => 'The uploaded file exceeds the post_max_size directive in php.ini', 'max_file_size' => 'A fájl mérete túl nagy!', 'min_file_size' => 'A fájl mérete túl kicsi!', 'accept_file_types' => 'Filetype not allowed', 'max_number_of_files' => 'Maximum number of files exceeded', 'max_width' => 'A kép mérete elérte a maximális szélességet!', 'min_width' => 'A kép mérete nem éri el a minimális szélességet!', 'max_height' => 'A kép mérete elérte a maximális magasságot!', 'min_height' => 'A kép mérete nem éri el a minimális magasságot!', 'abort' => 'File upload aborted', 'image_resize' => 'A kép átméretézése sikertelen!' ), 'Upload_url' => 'Feltöltés URL-ről', 'Type_dir' => 'Mappa', 'Type' => 'Típus', 'Dimension' => 'Felbontás', 'Size' => 'Méret', 'Date' => 'Dátum', 'Filename' => 'Név', 'Operations' => 'Műveletek', 'Date_type' => 'y-m-d', 'OK' => 'OK', 'Cancel' => 'Mégse', 'Sorting' => 'Rendezés', 'Show_url' => 'URL megjelenítése', 'Extract' => 'Kibontás ide', 'File_info' => 'Fájl info', 'Edit_image' => 'Kép szerkesztése', 'Duplicate' => 'Klónozás', 'Folders' => 'mappa', 'Copy' => 'Másolás', 'Cut' => 'Kivágás', 'Paste' => 'Beillesztés', 'CB' => 'VL', // clipboard 'Paste_Here' => 'Beillesztés ebbe a mappába.', 'Paste_Confirm' => 'Biztos vagy benne, hogy ebbe a mappába szeretnéd beilleszteni a fájlokat? A létező fájlok/mappák felül lesznek írva.', 'Paste_Failed' => 'A beillesztés sikertelen!', 'Clear_Clipboard' => 'Vágólap törlése', 'Clear_Clipboard_Confirm' => 'Biztosan törlöd a vágólap tartalmát?', 'Files_ON_Clipboard' => 'Fájlok találhatóak a vágólapon.', 'Copy_Cut_Size_Limit' => 'A kiválasztott fájlok/mappák túl nagyok a %shoz. Limit: %d MB/művelet', // %s = cut or copy 'Copy_Cut_Count_Limit' => 'Túl sok fájlt választottál ki a %shoz. Limit: %d fájl/művelet', // %s = cut or copy 'Copy_Cut_Not_Allowed' => 'A %s nem engedélyezett.', // %s(1) = cut or copy, %s(2) = files or folders 'Image_Editor_No_Save' => 'A kép mentése sikertelen.', 'Image_Editor_Exit' => "Exit", 'Image_Editor_Save' => "Save", 'Zip_No_Extract' => 'Kicsomagolás sikertelen. Lehet, hogy korrupt a fájl.', 'Zip_Invalid' => 'Ez a kiterjesztés nem támogatott. Támogatott: zip, gz, tar.', 'Dir_No_Write' => 'A kiválasztott mappa nem írható.', 'Function_Disabled' => 'A %s funkciót letiltotta a szerver.', // %s = cut or copy 'File_Permission' => 'Engedélyek', 'File_Permission_Not_Allowed' => 'A %s jogainak a megváltoztatása nem engedélyezett.', // %s = files or folders 'File_Permission_Recursive' => 'Rekurzív beállítás az almappákra?', 'File_Permission_Wrong_Mode' => "A beírt engedély nem megfelelő.", 'User' => 'Felhasználó', 'Group' => 'Csoport', 'Yes' => 'Igen', 'No' => 'Nem', 'Lang_Not_Found' => 'A nyelv nem található.', 'Lang_Change' => 'Nyelv megváltoztatása', 'File_Not_Found' => 'A fájl nem található.', 'File_Open_Edit_Not_Allowed' => 'Nincs jogod %s a fájlt.', // %s = open or edit 'Edit' => 'Szerkesztés', 'Edit_File' => "Fájl szerkesztése", 'File_Save_OK' => "Fájl sikeresen mentve.", 'File_Save_Error' => "Hiba történt a fájl mentése közben.", 'New_File' => 'Új fájl', 'No_Extension' => 'Meg kell adnod a fájl kiterjesztését.', 'Valid_Extensions' => 'Elfogadott kiterjesztések: %s', // %s = txt,log etc. 'Upload_message' => "Drop file here to upload", 'SERVER ERROR' => "SERVER ERROR", 'forbidden' => "Forbiden", 'wrong path' => "Wrong path", 'wrong name' => "Wrong name", 'wrong extension' => "Wrong extension", 'wrong option' => "Wrong option", 'wrong data' => "Wrong data", 'wrong action' => "Wrong action", 'wrong sub-action' => "Wrong sub-actio", 'no action passed' => "No action passed", 'no path' => "No path", 'no file' => "No file", 'view type number missing' => "View type number missing", 'Not enough Memory' => "Not enough Memory", 'max_size_reached' => "Your image folder has reach its maximale size of %d MB.", //%d = max overall size 'B' => "B", 'KB' => "KB", 'MB' => "MB", 'GB' => "GB", 'TB' => "TB", 'total size' => "Total size", );
{ "pile_set_name": "Github" }
import subprocess import ajenti from ajenti.api import * from ajenti.plugins.main.api import SectionPlugin from ajenti.ui import on from ajenti.ui.binder import Binder from reconfigure.configs import FSTabConfig from reconfigure.items.fstab import FilesystemData import disks class Mount (object): def __init__(self): self.device = '' self.mountpoint = '' self.type = '' self.option = '' @plugin class MountsBackend (BasePlugin): def __init__(self): self.reload() def reload(self): self.filesystems = [] try: df_data = subprocess.check_output(['df', '-P']) except: return for l in df_data.splitlines()[1:]: f = Mount() l = l.split() f.device = l[0] if f.device == 'map' and ajenti.platform == 'osx': continue f.mountpoint = l[5] f.used = int(l[2]) * 1024 f.size = int(l[1]) * 1024 f.usage = 1.0 * f.used / f.size self.filesystems.append(f) @plugin class Filesystems (SectionPlugin): def init(self): self.title = _('Filesystems') self.icon = 'hdd' self.category = _('System') self.append(self.ui.inflate('fstab:main')) self.find('type').labels = ['Auto', 'EXT2', 'EXT3', 'EXT4', 'NTFS', 'FAT', 'ZFS', 'ReiserFS', 'Samba', 'None', 'Loop'] self.find('type').values = ['auto', 'ext2', 'ext3', 'ext4', 'ntfs', 'vfat', 'zfs', 'reiser', 'smb', 'none', 'loop'] self.fstab_config = FSTabConfig(path='/etc/fstab') self.mounts = MountsBackend.get() self.binder = Binder(None, self) self.find('fstab').find('filesystems').new_item = lambda c: FilesystemData() def post_mount_bind(object, collection, item, ui): ui.find('umount').on('click', self.on_umount, item) self.find('mounts').find('filesystems').post_item_bind = post_mount_bind def on_page_load(self): self.refresh() def on_umount(self, mount): subprocess.call(['umount', mount.mountpoint]) self.context.notify('info', _('Unmounted')) self.refresh() @on('mount-all', 'click') def on_mount_all(self): self.save() if subprocess.call(['mount', '-a']): self.context.notify('error', _('mount -a failed')) self.refresh() @on('refresh', 'click') def refresh(self): self.binder.unpopulate() self.reload_disks() self.fstab_config.load() self.fstab = self.fstab_config.tree self.mounts.reload() self.binder.setup(self).populate() def reload_disks(self): lst = disks.list_devices(by_uuid=True, by_id=True, by_label=True) self.find('device').labels = [x[0] for x in lst] self.find('device').values = [x[1] for x in lst] @on('save', 'click') def save(self): self.binder.update() self.fstab_config.save() self.context.notify('info', _('Saved'))
{ "pile_set_name": "Github" }
# Set the warning/log level to 3 -W3 # output grf -ftr #bitmap mode -gb # Set the bit depth to 4 (16 colors) -gB4 #The Transperant colour of 0xFF00FF -gT FF00FF ################## # Old Parameters #-W3 # disable alpha and set opaque bit for all pixels #-gT! # use lz77 compression #-gzl # 16 bit bitmap #-gB16 ##################
{ "pile_set_name": "Github" }
/*! * \file turb_convection.hpp * \brief Delarations of numerics classes for discretization of * convective fluxes in turbulence problems. * \author F. Palacios, T. Economon * \version 7.0.6 "Blackbird" * * SU2 Project Website: https://su2code.github.io * * The SU2 Project is maintained by the SU2 Foundation * (http://su2foundation.org) * * Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md) * * SU2 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. * * SU2 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 SU2. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "../CNumerics.hpp" /*! * \class CUpwScalar * \brief Template class for scalar upwind fluxes between nodes i and j. * \details This class serves as a template for the scalar upwinding residual * classes. The general structure of a scalar upwinding calculation is the * same for many different models, which leads to a lot of repeated code. * By using the template design pattern, these sections of repeated code are * moved to this shared base class, and the specifics of each model * are implemented by derived classes. In order to add a new residual * calculation for a convection residual, extend this class and implement * the pure virtual functions with model-specific behavior. * \ingroup ConvDiscr * \author C. Pederson, A. Bueno., and A. Campos. */ class CUpwScalar : public CNumerics { protected: su2double q_ij = 0.0, /*!< \brief Projected velocity at the face. */ a0 = 0.0, /*!< \brief The maximum of the face-normal velocity and 0 */ a1 = 0.0, /*!< \brief The minimum of the face-normal velocity and 0 */ *Flux = nullptr, /*!< \brief Final result, diffusive flux/residual. */ **Jacobian_i = nullptr, /*!< \brief Flux Jacobian w.r.t. node i. */ **Jacobian_j = nullptr; /*!< \brief Flux Jacobian w.r.t. node j. */ const bool implicit = false, incompressible = false, dynamic_grid = false; /*! * \brief A pure virtual function; Adds any extra variables to AD */ virtual void ExtraADPreaccIn() = 0; /*! * \brief Model-specific steps in the ComputeResidual method, derived classes * compute the Flux and its Jacobians via this method. * \param[in] config - Definition of the particular problem. */ virtual void FinishResidualCalc(const CConfig* config) = 0; public: /*! * \brief Constructor of the class. * \param[in] val_nDim - Number of dimensions of the problem. * \param[in] val_nVar - Number of variables of the problem. * \param[in] config - Definition of the particular problem. */ CUpwScalar(unsigned short val_nDim, unsigned short val_nVar, const CConfig* config); /*! * \brief Destructor of the class. */ ~CUpwScalar(void) override; /*! * \brief Compute the scalar upwind flux between two nodes i and j. * \param[in] config - Definition of the particular problem. * \return A lightweight const-view (read-only) of the residual/flux and Jacobians. */ ResidualType<> ComputeResidual(const CConfig* config) override; }; /*! * \class CUpwSca_TurbSA * \brief Class for doing a scalar upwind solver for the Spalar-Allmaras turbulence model equations. * \ingroup ConvDiscr * \author A. Bueno. */ class CUpwSca_TurbSA final : public CUpwScalar { private: /*! * \brief Adds any extra variables to AD */ void ExtraADPreaccIn() override; /*! * \brief SA specific steps in the ComputeResidual method * \param[in] config - Definition of the particular problem. */ void FinishResidualCalc(const CConfig* config) override; public: /*! * \brief Constructor of the class. * \param[in] val_nDim - Number of dimensions of the problem. * \param[in] val_nVar - Number of variables of the problem. * \param[in] config - Definition of the particular problem. */ CUpwSca_TurbSA(unsigned short val_nDim, unsigned short val_nVar, const CConfig* config); }; /*! * \class CUpwSca_TurbSST * \brief Class for doing a scalar upwind solver for the Menter SST turbulence model equations. * \ingroup ConvDiscr * \author A. Campos. */ class CUpwSca_TurbSST final : public CUpwScalar { private: /*! * \brief Adds any extra variables to AD */ void ExtraADPreaccIn() override; /*! * \brief SST specific steps in the ComputeResidual method * \param[in] config - Definition of the particular problem. */ void FinishResidualCalc(const CConfig* config) override; public: /*! * \brief Constructor of the class. * \param[in] val_nDim - Number of dimensions of the problem. * \param[in] val_nVar - Number of variables of the problem. * \param[in] config - Definition of the particular problem. */ CUpwSca_TurbSST(unsigned short val_nDim, unsigned short val_nVar, const CConfig* config); };
{ "pile_set_name": "Github" }
{-# LANGUAGE OverloadedStrings #-} -- | -- A worker that simulates some work with a timeout -- And send back "World" -- Connect REP socket to tcp://*:5560 -- Expects "Hello" from client, replies with "World" -- module Main where import System.ZMQ4.Monadic import Control.Monad (forever) import Data.ByteString.Char8 (unpack) import Control.Concurrent (threadDelay) import Text.Printf main :: IO () main = runZMQ $ do responder <- socket Rep connect responder "tcp://localhost:5560" forever $ do receive responder >>= liftIO . printf "Received request: [%s]\n" . unpack -- Simulate doing some 'work' for 1 second liftIO $ threadDelay (1 * 1000 * 1000) send responder [] "World"
{ "pile_set_name": "Github" }
package com.fasterxml.jackson.databind.introspect; import java.util.Objects; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.exc.InvalidDefinitionException; public class TestAutoDetect extends BaseMapTest { // 21-Sep-2017, tatu: With 2.x, private delegating ctor was acceptable; with 3.x // must be non-private OR annotated static class ProtectedBean { String a; protected ProtectedBean(String a) { this.a = a; } } // Private scalar constructor ok, but only if annotated (or level changed) static class PrivateBeanAnnotated { String a; @JsonCreator private PrivateBeanAnnotated(String a) { this.a = a; } } static class PrivateBeanNonAnnotated { String a; private PrivateBeanNonAnnotated(String a) { this.a = a; } } // test for [databind#1347], config overrides for visibility @JsonPropertyOrder(alphabetic=true) static class Feature1347SerBean { public int field = 2; public int getValue() { return 3; } } // let's promote use of fields; but not block setters yet @JsonAutoDetect(fieldVisibility=Visibility.NON_PRIVATE) static class Feature1347DeserBean { int value; public void setValue(int x) { throw new IllegalArgumentException("Should NOT get called"); } } // For [databind#2789] @SuppressWarnings("unused") @JsonAutoDetect( getterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, fieldVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE) @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", visible = true) @JsonSubTypes({ @JsonSubTypes.Type(name = "CLASS_A", value = DataClassA.class) }) private static abstract class DataParent2789 { @JsonProperty("type") @JsonTypeId private final DataType2789 type; DataParent2789() { super(); this.type = null; } DataParent2789(final DataType2789 type) { super(); this.type = Objects.requireNonNull(type); } public DataType2789 getType() { return this.type; } } private static final class DataClassA extends DataParent2789 { DataClassA() { super(DataType2789.CLASS_A); } } private enum DataType2789 { CLASS_A; } /* /******************************************************** /* Unit tests /******************************************************** */ private final ObjectMapper MAPPER = newJsonMapper(); public void testProtectedDelegatingCtor() throws Exception { // first, default settings, with which construction works ok ObjectMapper m = new ObjectMapper(); ProtectedBean bean = m.readValue(quote("abc"), ProtectedBean.class); assertEquals("abc", bean.a); // then by increasing visibility requirement: m = jsonMapperBuilder() .changeDefaultVisibility(vc -> vc.withScalarConstructorVisibility(JsonAutoDetect.Visibility.PUBLIC_ONLY)) .build(); try { m.readValue("\"abc\"", ProtectedBean.class); fail("Expected exception for missing constructor"); } catch (JsonProcessingException e) { verifyException(e, InvalidDefinitionException.class, "no String-argument constructor/factory"); } } public void testPrivateDelegatingCtor() throws Exception { // first, default settings, with which construction works ok ObjectMapper m = new ObjectMapper(); PrivateBeanAnnotated bean = m.readValue(quote("abc"), PrivateBeanAnnotated.class); assertEquals("abc", bean.a); // but not so much without try { m.readValue("\"abc\"", PrivateBeanNonAnnotated.class); fail("Expected exception for missing constructor"); } catch (JsonProcessingException e) { verifyException(e, InvalidDefinitionException.class, "no String-argument constructor/factory"); } // except if we lower requirement m = jsonMapperBuilder() .changeDefaultVisibility(vc -> vc.withScalarConstructorVisibility(JsonAutoDetect.Visibility.ANY)) .build(); bean = m.readValue(quote("xyz"), PrivateBeanAnnotated.class); assertEquals("xyz", bean.a); } // [databind#1347] public void testVisibilityConfigOverridesForSer() throws Exception { // first, by default, both field/method should be visible final Feature1347SerBean input = new Feature1347SerBean(); assertEquals(aposToQuotes("{'field':2,'value':3}"), MAPPER.writeValueAsString(input)); ObjectMapper mapper = jsonMapperBuilder() .withConfigOverride(Feature1347SerBean.class, o -> o.setVisibility(JsonAutoDetect.Value.construct(PropertyAccessor.GETTER, Visibility.NONE))) .build(); assertEquals(aposToQuotes("{'field':2}"), mapper.writeValueAsString(input)); } // [databind#1347] public void testVisibilityConfigOverridesForDeser() throws Exception { final String JSON = aposToQuotes("{'value':3}"); // by default, should throw exception try { /*Feature1347DeserBean bean =*/ MAPPER.readValue(JSON, Feature1347DeserBean.class); fail("Should not pass"); } catch (JsonMappingException e) { verifyException(e, "Should NOT get called"); } // but when instructed to ignore setter, should work ObjectMapper mapper = jsonMapperBuilder() .withConfigOverride(Feature1347DeserBean.class, o -> o.setVisibility(JsonAutoDetect.Value.construct(PropertyAccessor.SETTER, Visibility.NONE))) .build(); Feature1347DeserBean result = mapper.readValue(JSON, Feature1347DeserBean.class); assertEquals(3, result.value); } // [databind#2789] public void testAnnotatedFieldIssue2789() throws Exception { final String json = MAPPER.writeValueAsString(new DataClassA()); final DataParent2789 copy = MAPPER.readValue(json, DataParent2789.class); assertEquals(DataType2789.CLASS_A, copy.getType()); } }
{ "pile_set_name": "Github" }
<?php namespace WeDevs\Dokan\Upgrade\Upgrades; use WeDevs\Dokan\Abstracts\DokanUpgrader; class V_2_9_13 extends DokanUpgrader { /** * Update single product multi vendor module table * * @return void */ public static function update_spmv_product_map_table() { global $wpdb; $map_table = $wpdb->prefix . 'dokan_product_map'; if ( $wpdb->get_var( $wpdb->prepare( 'show tables like %s', $map_table ) ) !== $map_table ) { return; } $columns = $wpdb->get_results( "describe {$map_table}" ); $columns = array_filter( $columns, function ( $column ) { return 'visibility' === $column->Field; } ); if ( empty( $columns ) ) { $wpdb->query( "alter table {$map_table} add column visibility tinyint(1) default 1" ); } } }
{ "pile_set_name": "Github" }
--- title: Using Built-in WixUI Dialog Sets layout: documentation --- # Using Built-in WixUI Dialog Sets The WixUI dialog library contains the following built-in dialog sets that provide a familiar wizard-style setup user interface. 1. [WixUI_Advanced](dialog_reference/WixUI_advanced.html) 1. [WixUI_FeatureTree](dialog_reference/WixUI_featuretree.html) 1. [WixUI_InstallDir](dialog_reference/WixUI_installdir.html) 1. [WixUI_Minimal](dialog_reference/WixUI_minimal.html) 1. [WixUI_Mondo](dialog_reference/WixUI_mondo.html) The built-in WixUI dialog sets are also customizable, from the bitmaps shown in the UI to adding and removing custom dialogs. See [Customizing the WixUI Dialog Sets](WixUI_customizations.html) for additional information. ## How to add a built-in WixUI dialog set to a product installer Assuming you have an existing installer that is functional but is just lacking a user interface, here are the steps you need to follow to include a built-in WixUI dialog set: <ol> <li>Add a UIRef element to your setup authoring that has an Id that matches the name of one of the dialog sets described above. For example: <pre> &lt;Product ...&gt; &lt;UIRef Id="WixUI_InstallDir" /&gt; &lt;/Product&gt; </pre> </li> <li>Pass the -ext and -cultures switches to [light.exe](~/overview/light.html) to reference the WixUIExtension. For example: <pre> light -ext WixUIExtension -cultures:en-us Product.wixobj -out Product.msi </pre> <p>Note - If you are using WiX in Visual Studio you can add the WixUIExtension using the Add Reference dialog and the necessary command lines will automatically be added when linking your .msi. To do this, use the following steps:</p> <ol> <li>Open your WiX project in Visual Studio</li> <li>Right click on your project in Solution Explorer and select Add Reference...</li> <li>Select the <strong>WixUIExtension.dll</strong> assembly from the list and click Add</li> <li>Close the Add Reference dialog</li> </ol> </li> </ol>
{ "pile_set_name": "Github" }
const fs = require('fs'); const html = fs.readFileSync('./dist/index.html'); const jsFile = fs.readdirSync('dist').find(s => s.endsWith('.js')); const jsFileContents = fs.readFileSync('./dist/' + jsFile); const newHTML = html .toString() .replace(/<script.*<\/script>/gm, '') .replace('</body>', `<script>${jsFileContents}</script></body>`); fs.writeFileSync('./dist/index.html', newHTML);
{ "pile_set_name": "Github" }
# Runtime v2 Runtime v2 introduces a first class shim API for runtime authors to integrate with containerd. The shim API is minimal and scoped to the execution lifecycle of a container. ## Binary Naming Users specify the runtime they wish to use when creating a container. The runtime can also be changed via a container update. ```bash > ctr run --runtime io.containerd.runc.v1 ``` When a user specifies a runtime name, `io.containerd.runc.v1`, they will specify the name and version of the runtime. This will be translated by containerd into a binary name for the shim. `io.containerd.runc.v1` -> `containerd-shim-runc-v1` containerd keeps the `containerd-shim-*` prefix so that users can `ps aux | grep containerd-shim` to see running shims on their system. ## Shim Authoring This section is dedicated to runtime authors wishing to build a shim. It will detail how the API works and different considerations when building shim. ### Commands Container information is provided to a shim in two ways. The OCI Runtime Bundle and on the `Create` rpc request. #### `start` Each shim MUST implement a `start` subcommand. This command will launch new shims. The start command MUST accept the following flags: * `-namespace` the namespace for the container * `-address` the address of the containerd's main socket * `-publish-binary` the binary path to publish events back to containerd * `-id` the id of the container The start command, as well as all binary calls to the shim, has the bundle for the container set as the `cwd`. The start command MUST return an address to a shim for containerd to issue API requests for container operations. The start command can either start a new shim or return an address to an existing shim based on the shim's logic. #### `delete` Each shim MUST implement a `delete` subcommand. This command allows containerd to delete any container resources created, mounted, and/or run by a shim when containerd can no longer communicate over rpc. This happens if a shim is SIGKILL'd with a running container. These resources will need to be cleaned up when containerd looses the connection to a shim. This is also used when containerd boots and reconnects to shims. If a bundle is still on disk but containerd cannot connect to a shim, the delete command is invoked. The delete command MUST accept the following flags: * `-namespace` the namespace for the container * `-address` the address of the containerd's main socket * `-publish-binary` the binary path to publish events back to containerd * `-id` the id of the container * `-bundle` the path to the bundle to delete. On non-Windows platforms this will match `cwd` The delete command will be executed in the container's bundle as its `cwd` except for on the Windows platform. ### Host Level Shim Configuration containerd does not provide any host level configuration for shims via the API. If a shim needs configuration from the user with host level information across all instances, a shim specific configuration file can be setup. ### Container Level Shim Configuration On the create request, there is a generic `*protobuf.Any` that allows a user to specify container level configuration for the shim. ```proto message CreateTaskRequest { string id = 1; ... google.protobuf.Any options = 10; } ``` A shim author can create their own protobuf message for configuration and clients can import and provide this information is needed. ### I/O I/O for a container is provided by the client to the shim via fifo on Linux, named pipes on Windows, or log files on disk. The paths to these files are provided on the `Create` rpc for the initial creation and on the `Exec` rpc for additional processes. ```proto message CreateTaskRequest { string id = 1; bool terminal = 4; string stdin = 5; string stdout = 6; string stderr = 7; } ``` ```proto message ExecProcessRequest { string id = 1; string exec_id = 2; bool terminal = 3; string stdin = 4; string stdout = 5; string stderr = 6; } ``` Containers that are to be launched with an interactive terminal will have the `terminal` field set to `true`, data is still copied over the files(fifos,pipes) in the same way as non interactive containers. ### Root Filesystems The root filesystem for the containers is provided by on the `Create` rpc. Shims are responsible for managing the lifecycle of the filesystem mount during the lifecycle of a container. ```proto message CreateTaskRequest { string id = 1; string bundle = 2; repeated containerd.types.Mount rootfs = 3; ... } ``` The mount protobuf message is: ```proto message Mount { // Type defines the nature of the mount. string type = 1; // Source specifies the name of the mount. Depending on mount type, this // may be a volume name or a host path, or even ignored. string source = 2; // Target path in container string target = 3; // Options specifies zero or more fstab style mount options. repeated string options = 4; } ``` Shims are responsible for mounting the filesystem into the `rootfs/` directory of the bundle. Shims are also responsible for unmounting of the filesystem. During a `delete` binary call, the shim MUST ensure that filesystem is also unmounted. Filesystems are provided by the containerd snapshotters. ### Events The Runtime v2 supports an async event model. In order for the an upstream caller (such as Docker) to get these events in the correct order a Runtime v2 shim MUST implement the following events where `Compliance=MUST`. This avoids race conditions between the shim and shim client where for example a call to `Start` can signal a `TaskExitEventTopic` before even returning the results from the `Start` call. With these guarantees of a Runtime v2 shim a call to `Start` is required to have published the async event `TaskStartEventTopic` before the shim can publish the `TaskExitEventTopic`. #### Tasks | Topic | Compliance | Description | | ----- | ---------- | ----------- | | `runtime.TaskCreateEventTopic` | MUST | When a task is successfully created | | `runtime.TaskStartEventTopic` | MUST (follow `TaskCreateEventTopic`) | When a task is successfully started | | `runtime.TaskExitEventTopic` | MUST (follow `TaskStartEventTopic`) | When a task exits expected or unexpected | | `runtime.TaskDeleteEventTopic` | MUST (follow `TaskExitEventTopic` or `TaskCreateEventTopic` if never started) | When a task is removed from a shim | | `runtime.TaskPausedEventTopic` | SHOULD | When a task is successfully paused | | `runtime.TaskResumedEventTopic` | SHOULD (follow `TaskPausedEventTopic`) | When a task is successfully resumed | | `runtime.TaskCheckpointedEventTopic` | SHOULD | When a task is checkpointed | | `runtime.TaskOOMEventTopic` | SHOULD | If the shim collects Out of Memory events | #### Execs | Topic | Compliance | Description | | ----- | ---------- | ----------- | | `runtime.TaskExecAddedEventTopic` | MUST (follow `TaskCreateEventTopic` ) | When an exec is successfully added | | `runtime.TaskExecStartedEventTopic` | MUST (follow `TaskExecAddedEventTopic`) | When an exec is successfully started | | `runtime.TaskExitEventTopic` | MUST (follow `TaskExecStartedEventTopic`) | When an exec (other than the init exec) exits expected or unexpected | | `runtime.TaskDeleteEventTopic` | SHOULD (follow `TaskExitEventTopic` or `TaskExecAddedEventTopic` if never started) | When an exec is removed from a shim | ### Other #### Unsupported rpcs If a shim does not or cannot implement an rpc call, it MUST return a `github.com/containerd/containerd/errdefs.ErrNotImplemented` error. #### Debugging and Shim Logs A fifo on unix or named pipe on Windows will be provided to the shim. It can be located inside the `cwd` of the shim named "log". The shims can use the existing `github.com/containerd/containerd/log` package to log debug messages. Messages will automatically be output in the containerd's daemon logs with the correct fields and runtime set. #### ttrpc [ttrpc](https://github.com/containerd/ttrpc) is the only currently supported protocol for shims. It works with standard protobufs and GRPC services as well as generating clients. The only difference between grpc and ttrpc is the wire protocol. ttrpc removes the http stack in order to save memory and binary size to keep shims small. It is recommended to use ttrpc in your shim but grpc support is also in development.
{ "pile_set_name": "Github" }
#!/usr/bin/env python """ SWIG generation server. Listens for connections from swig generation clients and runs swig in the requested fashion, sending back the results. """ # Future imports from __future__ import absolute_import from __future__ import print_function # Python modules import argparse import io import logging import os import select import shutil import socket import struct import sys import tempfile import traceback # LLDB modules import use_lldb_suite from lldbsuite.support import fs from lldbsuite.support import sockutil # package imports from . import local from . import remote default_port = 8537 def add_subparser_args(parser): parser.add_argument( "--port", action="store", default=default_port, help=("The local port to bind to")) parser.add_argument( "--swig-executable", action="store", default=fs.find_executable("swig"), dest="swig_executable") def finalize_subparser_options(options): pass def initialize_listening_socket(options): logging.debug("Creating socket...") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) logging.info("Binding to ip address '', port {}".format(options.port)) s.bind(('', options.port)) logging.debug("Putting socket in listen mode...") s.listen() return s def accept_once(sock, options): logging.debug("Waiting for connection...") while True: rlist, wlist, xlist = select.select([sock], [], [], 0.5) if not rlist: continue client, addr = sock.accept() logging.info("Received connection from {}".format(addr)) data_size = struct.unpack("!I", sockutil.recvall(client, 4))[0] logging.debug("Expecting {} bytes of data from client" .format(data_size)) data = sockutil.recvall(client, data_size) logging.info("Received {} bytes of data from client" .format(len(data))) pack_location = None try: tempfolder = os.path.join(tempfile.gettempdir(), "swig-bot") os.makedirs(tempfolder, exist_ok=True) pack_location = tempfile.mkdtemp(dir=tempfolder) logging.debug("Extracting archive to {}".format(pack_location)) local.unpack_archive(pack_location, data) logging.debug("Successfully unpacked archive...") config_file = os.path.normpath(os.path.join(pack_location, "config.json")) parsed_config = remote.parse_config(io.open(config_file)) config = local.LocalConfig() config.languages = parsed_config["languages"] config.swig_executable = options.swig_executable config.src_root = pack_location config.target_dir = os.path.normpath( os.path.join(config.src_root, "output")) logging.info( "Running swig. languages={}, swig={}, src_root={}, target={}" .format(config.languages, config.swig_executable, config.src_root, config.target_dir)) status = local.generate(config) logging.debug("Finished running swig. Packaging up files {}" .format(os.listdir(config.target_dir))) zip_data = io.BytesIO() zip_file = local.pack_archive(zip_data, config.target_dir, None) response_status = remote.serialize_response_status(status) logging.debug("Sending response status {}".format(response_status)) logging.info("(swig output) -> swig_output.json") zip_file.writestr("swig_output.json", response_status) zip_file.close() response_data = zip_data.getvalue() logging.info("Sending {} byte response".format(len(response_data))) client.sendall(struct.pack("!I", len(response_data))) client.sendall(response_data) finally: if pack_location is not None: logging.debug("Removing temporary folder {}" .format(pack_location)) shutil.rmtree(pack_location) def accept_loop(sock, options): while True: try: accept_once(sock, options) except Exception as e: error = traceback.format_exc() logging.error("An error occurred while processing the connection.") logging.error(error) def run(options): print(options) sock = initialize_listening_socket(options) accept_loop(sock, options) return options
{ "pile_set_name": "Github" }
package chaction.style { /* 软件名称:chplayer 软件作者:http://www.chplayer.com 开源软件协议:Mozilla Public License, version 2.0(MPL 2.0) MPL 2.0协议英文(原文,正本)查看地址:https://www.mozilla.org/en-US/MPL/2.0/ MPL 2.0协议中文(翻译)查看地址:http://www.chplayer.com/res/Mozilla_Public_License_2.0_Simplified_Chinese_Reference.txt 文件最后更新日期:2017-03-17 */ import flash.display.Stage; import flash.display.Sprite; import chaction.act.element; public class logo extends Sprite { private var S: Stage = null; private var L: Sprite = null; public function logo(s: Stage = null, f: Object = null):void { // constructor code S = s; if (f.hasOwnProperty("logo") && f["logo"] != "") { var obj: Object = { text: f["logo"], size: 28, bgAlpha: 0 }; L = element.newPromptText(obj); S.addChild(L); changeCoor(); } } public function changeCoor(): void { //修改坐标 var stageW:int=S.stageWidth; var stageH:int=S.stageHeight; if (L != null) { L.x = stageW - L.width; //L.y =10; } } } }
{ "pile_set_name": "Github" }
(* symbol.sml the signature *) (* $Log: symbol.sml,v $ Revision 1.4 1992/09/15 17:06:52 jont Added strict less than functions for all the symbol types Revision 1.3 1991/11/21 16:00:03 jont Added copyright message Revision 1.2 91/11/19 12:16:26 jont Merging in comments from Ten15 branch to main trunk Revision 1.1.1.1 91/11/19 11:06:30 jont Added comments for DRA on functions Revision 1.1 91/06/07 10:57:59 colin Initial revision Copyright 2013 Ravenbrook Limited <http://www.ravenbrook.com/>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 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 HOLDER 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. *) (* This module defines a type Symbol and functions for manipulating them. This conceals the string nature of symbols and would allow one to add more information to the symbol type. The functions are all self-explanatory. Symbols are used throughout the compiler for identifiers, via the basics/ident.sml module. N.B. qualified identifiers (foo.bar.baz) are represented using lists of symbols. *) signature SYMBOL = sig eqtype Symbol val symbol_name : Symbol -> string val find_symbol : string -> Symbol val eq_symbol : Symbol * Symbol -> bool val symbol_lt : Symbol * Symbol -> bool val symbol_order: Symbol * Symbol -> bool end
{ "pile_set_name": "Github" }
<!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"/> <title>arm_correlate_q31.d File Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="cmsis.css" rel="stylesheet" type="text/css" /> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> </head> <body> <div id="top"><!-- do not remove this div! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 46px;"> <td id="proglogo"><img alt="CMSIS Logo" src="CMSIS_Logo_Final.png"></td> <td style="padding-left: 0.5em;"> <div id="projectname">CMSIS-DSP &#160;<span id="projectnumber">Verison 1.1.0</span> </div> <div id="projectbrief">CMSIS DSP Software Library</div> </td> </tr> </tbody> </table> </div> <div id="CMSISnav" class="tabs1"> <ul class="tablist"> <li><a href="../../General/html/index.html"><span>CMSIS</span></a></li> <li><a href="../../Core/html/index.html"><span>CORE</span></a></li> <li class="current"><a href="../../DSP/html/index.html"><span>DSP</span></a></li> <li><a href="../../RTOS/html/index.html"><span>RTOS API</span></a></li> <li><a href="../../SVD/html/index.html"><span>SVD</span></a></li> </ul> </div> <!-- Generated by Doxygen 1.7.5.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="modules.html"><span>Reference</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> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> initNavTree('arm__correlate__q31_8d.html',''); </script> <div id="doc-content"> <div class="header"> <div class="headertitle"> <div class="title">arm_correlate_q31.d File Reference</div> </div> </div> <div class="contents"> </div> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="arm__correlate__q31_8d.html">arm_correlate_q31.d</a> </li> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&#160;</span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark">&#160;</span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark">&#160;</span>Defines</a></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> <li class="footer">Generated on Wed Mar 28 2012 15:38:06 for CMSIS-DSP by ARM Ltd. All rights reserved. <!-- <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.5.1 </li> --> </li> </ul> </div> </body> </html>
{ "pile_set_name": "Github" }
// // LoginRequest.m // TILLiveSDKShow // // Created by wilderliao on 16/11/30. // Copyright © 2016年 Tencent. All rights reserved. // #import "LoginRequest.h" @implementation LoginRequest - (NSString *)url { // return @"https://sxb.qcloud.com/sxb/index.php?svc=account&cmd=login"; NSString *host = [self hostUrl]; return [NSString stringWithFormat:@"%@svc=account&cmd=login",host]; } - (NSDictionary *)packageParams { NSDictionary *paramDic = @{ @"appid" : @([ShowAppId intValue]), @"id" : _identifier, @"pwd" : _pwd, @"appid" : @([[ILiveSDK getInstance] getAppId]) }; return paramDic; } - (Class)responseDataClass { return [LoginResponceData class]; } @end @implementation LoginResponceData @end
{ "pile_set_name": "Github" }
{ "name": "test", "dependencies": { "fake": "x" } }
{ "pile_set_name": "Github" }
# #About: This will install postfix # --- - hosts: '{{inventory}}' become: yes roles: - postfix
{ "pile_set_name": "Github" }
package session import ( "sync" "github.com/256dpi/gomqtt/packet" ) // PacketStore is a goroutine safe packet store. type PacketStore struct { packets map[packet.ID]packet.Generic mutex sync.RWMutex } // NewPacketStore returns a new PacketStore. func NewPacketStore() *PacketStore { return &PacketStore{ packets: make(map[packet.ID]packet.Generic), } } // NewPacketStoreWithPackets returns a new PacketStore with the provided packets. func NewPacketStoreWithPackets(packets []packet.Generic) *PacketStore { // prepare store store := &PacketStore{ packets: make(map[packet.ID]packet.Generic), } // add packets for _, pkt := range packets { store.Save(pkt) } return store } // Save will store a packet in the store. An eventual existing packet with the // same id gets quietly overwritten. func (s *PacketStore) Save(pkt packet.Generic) { s.mutex.Lock() defer s.mutex.Unlock() id, ok := packet.GetID(pkt) if ok { s.packets[id] = pkt } } // Lookup will retrieve a packet from the store. func (s *PacketStore) Lookup(id packet.ID) packet.Generic { s.mutex.RLock() defer s.mutex.RUnlock() return s.packets[id] } // Delete will remove a packet from the store. func (s *PacketStore) Delete(id packet.ID) { s.mutex.Lock() defer s.mutex.Unlock() delete(s.packets, id) } // All will return all packets currently saved in the store. func (s *PacketStore) All() []packet.Generic { s.mutex.RLock() defer s.mutex.RUnlock() var all []packet.Generic for _, pkt := range s.packets { all = append(all, pkt) } return all } // Reset will reset the store. func (s *PacketStore) Reset() { s.mutex.Lock() defer s.mutex.Unlock() s.packets = make(map[packet.ID]packet.Generic) }
{ "pile_set_name": "Github" }
--- title: Content Summaries linktitle: Summaries description: Hugo generates summaries of your content. date: 2017-01-10 publishdate: 2017-01-10 lastmod: 2017-01-10 categories: [content management] keywords: [summaries,abstracts,read more] menu: docs: parent: "content-management" weight: 90 weight: 90 #rem draft: false aliases: [/content/summaries/,/content-management/content-summaries/] toc: true --- With the use of the `.Summary` [page variable][pagevariables], Hugo generates summaries of content to use as a short version in summary views. ## Summary Splitting Options * Automatic Summary Split * Manual Summary Split * Front Matter Summary It is natural to accompany the summary with links to the original content, and a common design pattern is to see this link in the form of a "Read More ..." button. See the `.RelPermalink`, `.Permalink`, and `.Truncated` [page variables][pagevariables]. ### Automatic Summary Splitting By default, Hugo automatically takes the first 70 words of your content as its summary and stores it into the `.Summary` page variable for use in your templates. You may customize the summary length by setting `summaryLength` in your [site configuration](/getting-started/configuration/). {{% note %}} You can customize how HTML tags in the summary are loaded using functions such as `plainify` and `safeHTML`. {{% /note %}} {{% note %}} The Hugo-defined summaries are set to use word count calculated by splitting the text by one or more consecutive whitespace characters. If you are creating content in a `CJK` language and want to use Hugo's automatic summary splitting, set `hasCJKLanguage` to `true` in your [site configuration](/getting-started/configuration/). {{% /note %}} ### Manual Summary Splitting Alternatively, you may add the <code>&#60;&#33;&#45;&#45;more&#45;&#45;&#62;</code> summary divider where you want to split the article. For [Org mode content][org], use `# more` where you want to split the article. Content that comes before the summary divider will be used as that content's summary and stored in the `.Summary` page variable with all HTML formatting intact. {{% note "Summary Divider"%}} The concept of a *summary divider* is not unique to Hugo. It is also called the "more tag" or "excerpt separator" in other literature. {{% /note %}} Pros : Freedom, precision, and improved rendering. All HTML tags and formatting are preserved. Cons : Extra work for content authors, since they need to remember to type <code>&#60;&#33;&#45;&#45;more&#45;&#45;&#62;</code> (or `# more` for [org content][org]) in each content file. This can be automated by adding the summary divider below the front matter of an [archetype](/content-management/archetypes/). {{% warning "Be Precise with the Summary Divider" %}} Be careful to enter <code>&#60;&#33;&#45;&#45;more&#45;&#45;&#62;</code> exactly; i.e., all lowercase and with no whitespace. {{% /warning %}} ### Front Matter Summary You might want your summary to be something other than the text that starts the article. In this case you can provide a separate summary in the `summary` variable of the article front matter. Pros : Complete freedom of text independent of the content of the article. Markup can be used within the summary. Cons : Extra work for content authors as they need to write an entirely separate piece of text as the summary of the article. ## Summary Selection Order Because there are multiple ways in which a summary can be specified it is useful to understand the order of selection Hugo follows when deciding on the text to be returned by `.Summary`. It is as follows: 1. If there is a <code>&#60;&#33;&#45;&#45;more&#45;&#45;&#62;</code> summary divider present in the article the text up to the divider will be provided as per the manual summary split method 2. If there is a `summary` variable in the article front matter the value of the variable will be provided as per the front matter summary method 3. The text at the start of the article will be provided as per the automatic summary split method {{% warning "Competing selections" %}} Hugo uses the _first_ of the above steps that returns text. So if, for example, your article has both `summary` variable in its front matter and a <code>&#60;&#33;&#45;&#45;more&#45;&#45;&#62;</code> summary divider Hugo will use the manual summary split method. {{% /warning %}} ## Example: First 10 Articles with Summaries You can show content summaries with the following code. You could use the following snippet, for example, in a [section template][]. {{< code file="page-list-with-summaries.html" >}} {{ range first 10 .Pages }} <article> <!-- this <div> includes the title summary --> <div> <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a></h2> {{ .Summary }} </div> {{ if .Truncated }} <!-- This <div> includes a read more link, but only if the summary is truncated... --> <div> <a href="{{ .RelPermalink }}">Read More…</a> </div> {{ end }} </article> {{ end }} {{< /code >}} Note how the `.Truncated` boolean variable value may be used to hide the "Read More..." link when the content is not truncated; i.e., when the summary contains the entire article. [org]: /content-management/formats/ [pagevariables]: /variables/page/ [section template]: /templates/section-templates/
{ "pile_set_name": "Github" }
[![Stories in Ready](https://badge.waffle.io/sciactive/pnotify.png?label=ready&title=Ready)](http://waffle.io/sciactive/pnotify) [![Stories in Progress](https://badge.waffle.io/sciactive/pnotify.png?label=in progress&title=In Progress)](http://waffle.io/sciactive/pnotify) PNotify is a JavaScript notification plugin, developed by SciActive. PNotify can also provide [desktop notifications](http://sciactive.com/pnotify/#web-notifications) based on the [Web Notifications spec](http://www.w3.org/TR/notifications/). If desktop notifications are not available or not allowed, PNotify will fall back to displaying the notice as a regular, in-browser notice. Demos ===== http://sciactive.com/pnotify/ Requirements ============ jQuery (1.6 or higher) Getting Started =============== You can include PNotify using Bower, NPM, or a custom download. PNotify custom download comes with the following files: * `pnotify.custom.js` & `pnotify.custom.min.js` (Minified) * `pnotify.custom.css` & `pnotify.custom.min.css` (Minified) So here's how you'd include them on your page: ```html <script type="text/javascript" src="pnotify.custom.min.js"></script> <link href="pnotify.custom.min.css" media="all" rel="stylesheet" type="text/css" /> ``` Now you can use PNotify like this: ```html <script type="text/javascript"> $(function(){ new PNotify({ title: 'Regular Notice', text: 'Check me out! I\'m a notice.' }); }); </script> ``` If you are not using any UI library, you can use the included styling, called Bright Theme. It is the default. If you are using Bootstrap version 2, include this line somewhere before your first notice: ```js PNotify.prototype.options.styling = "bootstrap2"; ``` If you are using Bootstrap version 3, include this line somewhere before your first notice: ```js PNotify.prototype.options.styling = "bootstrap3"; ``` If you are using jQuery UI, include this line somewhere before your first notice: ```js PNotify.prototype.options.styling = "jqueryui"; ``` If you are using Bootstrap 3 with Font Awesome, include this line somewhere before your first notice: ```js PNotify.prototype.options.styling = "fontawesome"; ``` Stacks ====== A stack is an object which PNotify uses to determine where to position notices. A stack has two mandatory properties, `dir1` and `dir2`. `dir1` is the first direction in which the notices are stacked. When the notices run out of room in the window, they will move over in the direction specified by `dir2`. The directions can be `"up"`, `"down"`, `"right"`, or `"left"`. Stacks are independent of each other, so a stack doesn't know and doesn't care if it overlaps (and blocks) another stack. The default stack, which can be changed like any other default, goes down, then left. Stack objects are used and manipulated by PNotify, and therefore, should be a variable when passed. So, calling something like `new PNotify({stack: {"dir1": "down", "dir2": "left"}});` will **NOT** work. It will create a notice, but that notice will be in its own stack and may overlap other notices. Modal Stacks ------------ You can set a stack as modal by setting the "modal" property to true. A modal stack creates an overlay behind it when any of its notices are open. When the last notice within it is removed, the overlay is hidden. If the "overlay_close" property is set to true, then clicking the overlay will cause all of the notices in that stack to be removed. Example Stacks -------------- ```js var stack_topleft = {"dir1": "down", "dir2": "right", "push": "top"}; var stack_bottomleft = {"dir1": "right", "dir2": "up", "push": "top"}; var stack_modal = {"dir1": "down", "dir2": "right", "push": "top", "modal": true, "overlay_close": true}; var stack_bar_top = {"dir1": "down", "dir2": "right", "push": "top", "spacing1": 0, "spacing2": 0}; var stack_bar_bottom = {"dir1": "up", "dir2": "right", "spacing1": 0, "spacing2": 0}; var stack_context = {"dir1": "down", "dir2": "left", "context": $("#stack-context")}; ``` This stack is initially positioned through code instead of CSS. ```js var stack_bottomright = {"dir1": "up", "dir2": "left", "firstpos1": 25, "firstpos2": 25}; ``` This is done through two extra variables. `firstpos1` and `firstpos2` are pixel values, relative to a viewport edge. `dir1` and `dir2`, respectively, determine which edge. It is calculated as follows: * `dir = "up"` - firstpos is relative to the bottom of viewport. * `dir = "down"` - firstpos is relative to the top of viewport. * `dir = "right"` - firstpos is relative to the left of viewport. * `dir = "left"` - firstpos is relative to the right of viewport. To create a stack in the top left, define the stack: ```js var stack_topleft = {"dir1": "down", "dir2": "right"}; ``` and then add two options to your pnotify call: ``` addclass: "stack-topleft", // This is one of the included default classes. stack: stack_topleft ``` There are several CSS classes included which will position your notices for you: * `stack-topleft` * `stack-bottomleft` * `stack-bottomright` * `stack-modal` You can create your own custom position and movement by defining a custom stack. Configuration Defaults / Options ================================ * `title: false` - The notice's title. * `title_escape: false` - Whether to escape the content of the title. (Not allow HTML.) * `text: false` - The notice's text. * `text_escape: false` - Whether to escape the content of the text. (Not allow HTML.) * `styling: "brighttheme"` - What styling classes to use. (Can be either "brighttheme", "jqueryui", "bootstrap2", "bootstrap3", "fontawesome", or a custom style object. See the source in the end of pnotify.js for the properties in a style object.) * `addclass: ""` - Additional classes to be added to the notice. (For custom styling.) * `cornerclass: ""` - Class to be added to the notice for corner styling. * `auto_display: true` - Display the notice when it is created. Turn this off to add notifications to the history without displaying them. * `width: "300px"` - Width of the notice. * `min_height: "16px"` - Minimum height of the notice. It will expand to fit content. * `type: "notice"` - Type of the notice. "notice", "info", "success", or "error". * `icon: true` - Set icon to true to use the default icon for the selected style/type, false for no icon, or a string for your own icon class. * `animation: "fade"` - The animation to use when displaying and hiding the notice. "none", "show", "fade", and "slide" are built in to jQuery. Others require jQuery UI. Use an object with effect_in and effect_out to use different effects. * `animate_speed: "slow"` - Speed at which the notice animates in and out. "slow", "def" or "normal", "fast" or number of milliseconds. * `position_animate_speed: 500` - Specify a specific duration of position animation. * `opacity: 1` - Opacity of the notice. * `shadow: true` - Display a drop shadow. * `hide: true` - After a delay, remove the notice. * `delay: 8000` - Delay in milliseconds before the notice is removed. * `mouse_reset: true` - Reset the hide timer if the mouse moves over the notice. * `remove: true` - Remove the notice's elements from the DOM after it is removed. * `insert_brs: true` - Change new lines to br tags. * `stack: {"dir1": "down", "dir2": "left", "push": "bottom", "spacing1": 25, "spacing2": 25, "context": $("body"), "modal": false}` - The stack on which the notices will be placed. Also controls the direction the notices stack. Desktop Module -------------- `desktop: {` * `desktop: false` - Display the notification as a desktop notification. * `fallback: true` - If desktop notifications are not supported or allowed, fall back to a regular notice. * `icon: null` - The URL of the icon to display. If false, no icon will show. If null, a default icon will show. * `tag: null` - Using a tag lets you update an existing notice, or keep from duplicating notices between tabs. If you leave tag null, one will be generated, facilitating the "update" function. * `text: null` - Optionally display different text for the desktop `}` Buttons Module -------------- `buttons: {` * `closer: true` - Provide a button for the user to manually close the notice. * `closer_hover: true` - Only show the closer button on hover. * `sticker: true` - Provide a button for the user to manually stick the notice. * `sticker_hover: true` - Only show the sticker button on hover. * `show_on_nonblock: false` - Show the buttons even when the nonblock module is in use. * `labels: {close: "Close", stick: "Stick"}` - Lets you change the displayed text, facilitating internationalization. * `classes: {closer: null, pin_up: null, pin_down: null}` - The classes to use for button icons. Leave them null to use the classes from the styling you're using. `}` NonBlock Module --------------- `nonblock: {` * `nonblock: false` - Create a non-blocking notice. It lets the user click elements underneath it. * `nonblock_opacity: .2` - The opacity of the notice (if it's non-blocking) when the mouse is over it. `}` Mobile Module ------------- `mobile: {` * `swipe_dismiss: true` - Let the user swipe the notice away. * `styling: true` - Styles the notice to look good on mobile. `}` Animate Module -------------- `animate: {` * `animate: false` - Use animate.css to animate the notice. * `in_class: ""` - The class to use to animate the notice in. * `out_class: ""` - The class to use to animate the notice out. `}` The Animate module also creates a method, `attention`, on notices which accepts an attention grabber class from Animate.css and callback to be called on completion of the animation. Confirm Module -------------- `confirm: {` * `confirm: false` - Make a confirmation box. * `prompt: false` - Make a prompt. * `prompt_class: ""` - Classes to add to the input element of the prompt. * `prompt_default: ""` - The default value of the prompt. * `prompt_multi_line: false` - Whether the prompt should accept multiple lines of text. * `align: "right"` - Where to align the buttons. (right, center, left, justify) * `buttons: [{text: "Ok", addClass: "", promptTrigger: true, click: function(notice, value){ notice.remove(); notice.get().trigger("pnotify.confirm", [notice, value]); }},{text: "Cancel", addClass: "", click: function(notice){ notice.remove(); notice.get().trigger("pnotify.cancel", notice); }}]` - The buttons to display, and their callbacks. If a button has promptTrigger set to true, it will be triggered when the user hits enter in a single line prompt. If you want only one button, use null as the second entry of your array to remove the cancel button. `}` History Module -------------- `history: {` * `history: true` - Place the notice in the history. * `menu: false` - Display a pull down menu to redisplay previous notices. * `fixed: true` - Make the pull down menu fixed to the top of the viewport. * `maxonscreen: Infinity` - Maximum number of notifications to have onscreen. * `labels: {redisplay: "Redisplay", all: "All", last: "Last"}` - Lets you change the displayed text, facilitating internationalization. `}` Reference Module -------------- `reference: {` * `putThing: false` - Provide a thing for stuff. Turned off by default. * `labels: {text: "Spin Around"}` - If you are displaying any text, you should use a labels options to support internationalization. `}` Callbacks Module ================ The callback options all expect one argument, a function, which will be called when that event occurs. They can be included in the options object passed to PNotify() just like the core options. If the function returns false on the "before_open" or "before_close" callback, that event will be canceled. * `before_init` - This option is called before the notice has been initialized. It accepts one argument, the options object. * `after_init` - This option is called after the notice has been initialized. It accepts one argument, the notice object. * `before_open` - This option is called before the notice has been displayed. It accepts one argument, the notice object. * `after_open` - This option is called after the notice has been displayed. It accepts one argument, the notice object. * `before_close` - This option is called before the notice closes. It accepts one argument, the notice object. * `after_close` - This option is called after the notice closes. It accepts one argument, the notice object. Utility Functions ================= * `PNotify.reload(root)` - Reinitialize PNotify. PNotify, in a browser, is initialized with window as the root. Returns the created PNotify object. * `PNotify.removeAll()` - Remove all notices. * `PNotify.removeStack(stack)` - Remove all the notices in a stack. * `PNotify.positionAll(animate)` - Reposition the notices, optionally animating their movement. * `notice.open()` - Open the notice. * `notice.remove()` - Remove the notice. * `notice.get()` - Get the notice's DOM element. Using PNotify with RequireJS ============================ When they detect AMD/RequireJS, PNotify core defines the named module "pnotify", and PNotify's modules each define names like "pnotify.module". The following example shows the use of the nonblock and desktop modules with RequireJS. ```js requirejs(['pnotify', 'pnotify.nonblock', 'pnotify.desktop'], function(PNotify){ PNotify.desktop.permission(); new PNotify({ title: 'Desktop Notice', text: 'If you\'ve given me permission, I\'ll appear as a desktop notification. If you haven\'t, I\'ll still appear as a regular PNotify notice.', desktop: { desktop: true }, nonblock: { nonblock: true } }); }); ``` Licensing and Additional Info ============================= PNotify is distributed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0). See http://sciactive.com/pnotify/ for download, more information, and examples.
{ "pile_set_name": "Github" }
dependencies: \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/crypto/cipher_extra/e_ssl3.c \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Build/Intermediates/Pods.build/Debug-iphonesimulator/BoringSSL.build/module.modulemap \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/Target\ Support\ Files/BoringSSL/BoringSSL-prefix.pch \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/aead.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/base.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/is_boringssl.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/opensslconf.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/cipher.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/err.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/hmac.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/digest.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/md5.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/mem.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/sha.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/crypto/cipher_extra/internal.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/crypto/cipher_extra/../internal.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/ex_data.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/stack.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/type_check.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/thread.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/crypto/cipher_extra/../fipsmodule/cipher/internal.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/include/openssl/aes.h \ /Users/nikhilsridhar/Desktop/Geofirestore-ios/Example/Pods/BoringSSL/crypto/cipher_extra/../fipsmodule/cipher/../modes/internal.h
{ "pile_set_name": "Github" }
# babel-plugin-transform-es2015-classes > Compile ES2015 classes to ES5 ## Caveats Built-in classes such as `Date`, `Array`, `DOM` etc cannot be properly subclassed due to limitations in ES5 (for the [es2015-classes](http://babeljs.io/docs/plugins/transform-es2015-classes) plugin). You can try to use [babel-plugin-transform-builtin-extend](https://github.com/loganfsmyth/babel-plugin-transform-builtin-extend) based on `Object.setPrototypeOf` and `Reflect.construct`, but it also has some limitations. ## Installation ```sh npm install --save-dev babel-plugin-transform-es2015-classes ``` ## Usage ### Via `.babelrc` (Recommended) **.babelrc** ```js // without options { "plugins": ["transform-es2015-classes"] } // with options { "plugins": [ ["transform-es2015-classes", { "loose": true }] ] } ``` ### Via CLI ```sh babel --plugins transform-es2015-classes script.js ``` ### Via Node API ```javascript require("babel-core").transform("code", { plugins: ["transform-es2015-classes"] }); ``` ## Options ### `loose` `boolean`, defaults to `false`. #### Method enumerability Please note that in loose mode class methods **are** enumerable. This is not in line with the spec and you may run into issues. #### Method assignment Under loose mode, methods are defined on the class prototype with simple assignments instead of being defined. This can result in the following not working: ```javascript class Foo { set bar() { throw new Error("foo!"); } } class Bar extends Foo { bar() { // will throw an error when this method is defined } } ``` When `Bar.prototype.foo` is defined it triggers the setter on `Foo`. This is a case that is very unlikely to appear in production code however it's something to keep in mind.
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <robot name="turtlebot_gazebo" xmlns:xacro="http://ros.org/wiki/xacro"> <!-- Microsoft Kinect / ASUS Xtion PRO Live for simulation --> <xacro:macro name="turtlebot_sim_3dsensor"> <gazebo reference="camera_link"> <sensor type="depth" name="camera"> <always_on>true</always_on> <update_rate>20.0</update_rate> <camera> <horizontal_fov>${60.0*M_PI/180.0}</horizontal_fov> <image> <format>R8G8B8</format> <width>640</width> <height>480</height> </image> <clip> <near>0.05</near> <far>8.0</far> </clip> </camera> <plugin name="kinect_camera_controller" filename="libgazebo_ros_openni_kinect.so"> <cameraName>camera</cameraName> <alwaysOn>true</alwaysOn> <updateRate>10</updateRate> <imageTopicName>rgb/image_raw</imageTopicName> <depthImageTopicName>depth/image_raw</depthImageTopicName> <pointCloudTopicName>depth/points</pointCloudTopicName> <cameraInfoTopicName>rgb/camera_info</cameraInfoTopicName> <depthImageCameraInfoTopicName>depth/camera_info</depthImageCameraInfoTopicName> <frameName>camera_depth_optical_frame</frameName> <baseline>0.1</baseline> <distortion_k1>0.0</distortion_k1> <distortion_k2>0.0</distortion_k2> <distortion_k3>0.0</distortion_k3> <distortion_t1>0.0</distortion_t1> <distortion_t2>0.0</distortion_t2> <pointCloudCutoff>0.4</pointCloudCutoff> </plugin> </sensor> </gazebo> </xacro:macro> </robot>
{ "pile_set_name": "Github" }
<Window x:Class="OsEngine.Entity.ProxiesUi" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Proxies" Height="349.555" Width="662" MinWidth="690" MinHeight="200" Topmost="True" Style="{StaticResource WindowStyleCanResize}" WindowStartupLocation="CenterScreen" Icon="/Images/OsLogo.ico"> <Grid> <Rectangle Margin="5,5,5,37"/> <Button Name="ButtonDelete" Content="Delete" HorizontalAlignment="Right" Margin="0,0,10,10" VerticalAlignment="Bottom" Width="120" Click="ButtonDelete_Click"/> <WindowsFormsHost Name="Host" Margin="10,10,10,42"/> <Button x:Name="ButtonДобавить" Content="Add" HorizontalAlignment="Right" Margin="0,0,144,10" VerticalAlignment="Bottom" Width="120" Click="ButtonДобавить_Click"/> </Grid> </Window>
{ "pile_set_name": "Github" }
{include file="CRM/common/TrackingFields.tpl"} <div class="crm-block crm-form-block crm-eventcart-participantsandprices"> {if $contact} <div class="messages status no-popup"> {ts 1=$contact.display_name}Welcome %1{/ts}. (<a href="{crmURL p='civicrm/event/cart_checkout' q="cid=0&reset=1"}" title="{ts}Click here to register a different person for this event.{/ts}">{ts 1=$contact.display_name}Not %1, or want to register a different person{/ts}</a>?)</div> {/if} {foreach from=$events_in_carts key=index item=event_in_cart} {if !$event_in_cart.main_conference_event_id} {assign var=event_id value=$event_in_cart->event_id} <h3 class="event-title"> {$event_in_cart->event->title} ({$event_in_cart->event->start_date|date_format:"%m/%d/%Y %l:%M%p"}) </h3> <fieldset class="event_form"> <div class="participants crm-section" id="event_{$event_in_cart->event_id}_participants"> {foreach from=$event_in_cart->participants item=participant} {include file="CRM/Event/Cart/Form/Checkout/Participant.tpl"} {/foreach} <a class="link-add" href="#" onclick="add_participant({$event_in_cart->event_cart->id}, {$event_in_cart->event_id}); return false;">{ts}Add Another Participant{/ts}</a> </div> {if $event_in_cart->event->is_monetary} <div class="price_choices crm-section"> {foreach from=$price_fields_for_event.$event_id key=price_index item=price_field_name} <div class="label"> {$form.$price_field_name.label} </div> <div class="content"> {$form.$price_field_name.html|replace:'/label>&nbsp;':'/label><br>'} </div> {/foreach} </div> {else} <p>{ts}There is no charge for this event.{/ts}</p> {/if} </fieldset> {/if} {/foreach} <div id="crm-submit-buttons" class="crm-submit-buttons"> {include file="CRM/common/formButtons.tpl" location="bottom"} </div> {include file="CRM/Event/Cart/Form/viewCartLink.tpl"} </div> {literal} <script type="text/javascript"> //<![CDATA[ function add_participant( cart_id, event_id ) { var max_index = 0; var matcher = new RegExp("event_" + event_id + "_participant_(\\d+)"); cj('#event_' + event_id + '_participants .participant').each( function(index) { matches = matcher.exec(cj(this).attr('id')); index = parseInt(matches[1]); if (index > max_index) { max_index = index; } } ); // FIXME: this get should be a post according to restful standards cj.get(CRM.url("civicrm/ajax/event/add_participant_to_cart?snippet=1", {cart_id: cart_id, event_id: event_id}), function(data) { cj('#event_' + event_id + '_participants').append(data).trigger('crmLoad'); } ); } function delete_participant( event_id, participant_id ) { // FIXME: this get should be a post according to restful standards cj('#event_' + event_id + '_participant_' + participant_id).remove(); cj.get(CRM.url("civicrm/ajax/event/remove_participant_from_cart", {id: participant_id})); } //XXX missing cj('#ajax_error').ajaxError( function( e, xrh, settings, exception ) { cj(this).append('<div class="error">{/literal}{ts escape='js'}Error adding a participant at{/ts}{literal} ' + settings.url + ': ' + exception); } ); //]]> </script> {/literal}
{ "pile_set_name": "Github" }
Building mintty requires gcc >=3.x for Cygwin or MSYS. It can not be built with a MinGW compiler, because it relies on some Unix facilities that are not available on plain Windows, in particular pseudo terminal devices (ptys). To compile, just run 'make'. (Add a -j option as desired.) To install, simply copy mintty.exe to an appropriate place, e.g. /bin. See the top of the Makefile for further make targets and options.
{ "pile_set_name": "Github" }
/* * Copyright (C) 2020 The Android Open Source Project * * 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.android.server.location.gnss; import static com.google.common.truth.Truth.assertThat; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.os.Handler; import android.os.Looper; import android.platform.test.annotations.Presubmit; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; /** * Unit tests for {@link GnssMeasurementsProvider}. */ @RunWith(RobolectricTestRunner.class) @Presubmit public class GnssMeasurementsProviderTest { @Mock private GnssMeasurementsProvider.GnssMeasurementProviderNative mMockNative; private GnssMeasurementsProvider mTestProvider; @Before public void setUp() { MockitoAnnotations.initMocks(this); when(mMockNative.startMeasurementCollection(anyBoolean())).thenReturn(true); when(mMockNative.stopMeasurementCollection()).thenReturn(true); mTestProvider = new GnssMeasurementsProvider(RuntimeEnvironment.application, new Handler(Looper.myLooper()), mMockNative) { @Override public boolean isGpsEnabled() { return true; } }; } @Test public void register_nativeStarted() { mTestProvider.registerWithService(); verify(mMockNative).startMeasurementCollection(anyBoolean()); } @Test public void unregister_nativeStopped() { mTestProvider.registerWithService(); mTestProvider.unregisterFromService(); verify(mMockNative).stopMeasurementCollection(); } @Test public void isSupported_nativeIsSupported() { when(mMockNative.isMeasurementSupported()).thenReturn(true); assertThat(mTestProvider.isAvailableInPlatform()).isTrue(); when(mMockNative.isMeasurementSupported()).thenReturn(false); assertThat(mTestProvider.isAvailableInPlatform()).isFalse(); } @Test public void register_resume_started() { mTestProvider.registerWithService(); mTestProvider.resumeIfStarted(); verify(mMockNative, times(2)).startMeasurementCollection(anyBoolean()); } @Test public void unregister_resume_notStarted() { mTestProvider.registerWithService(); mTestProvider.unregisterFromService(); mTestProvider.resumeIfStarted(); verify(mMockNative, times(1)).startMeasurementCollection(anyBoolean()); } }
{ "pile_set_name": "Github" }
<!-- Copyright (C) 2017-2018 Titus Cieslewski, RPG, University of Zurich, Switzerland You can contact the author at <titus at ifi dot uzh dot ch> Copyright (C) 2017-2018 Siddharth Choudhary, College of Computing, Georgia Institute of Technology, Atlanta, GA, USA Copyright (C) 2017-2018 Davide Scaramuzza, RPG, University of Zurich, Switzerland This file is part of dslam_open. dslam_open 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. dslam_open 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 dslam_open. If not, see <http://www.gnu.org/licenses/>. --> <package format="2"> <name>dslam</name> <version>0.0.0</version> <description> Data-Efficient Decentralized Visual SLAM </description> <author>Titus Cieslewski</author> <maintainer email="[email protected]">Titus Cieslewski</maintainer> <license>GPL-3.0</license> <buildtool_depend>catkin</buildtool_depend> <buildtool_depend>catkin_simple</buildtool_depend> <depend>ceres_catkin</depend> <depend>orb_slam_2</depend> <depend>rpg_common</depend> <depend>rpg_common_ros</depend> </package>
{ "pile_set_name": "Github" }
Output is: 0
{ "pile_set_name": "Github" }
from django.contrib.auth.models import AnonymousUser from django.http import HttpResponse from django.test import TestCase from django.test.client import RequestFactory from oscar.apps.basket import middleware class TestBasketMiddleware(TestCase): @staticmethod def get_response_for_test(request): return HttpResponse() def setUp(self): self.middleware = middleware.BasketMiddleware(self.get_response_for_test) self.request = RequestFactory().get('/') self.request.user = AnonymousUser() self.middleware(self.request) def test_basket_is_attached_to_request(self): self.assertTrue(hasattr(self.request, 'basket')) def test_strategy_is_attached_to_basket(self): self.assertTrue(hasattr(self.request.basket, 'strategy')) def test_strategy_is_attached_to_request(self): self.assertTrue(hasattr(self.request, 'strategy')) def test_get_cookie_basket_handles_invalid_signatures(self): request_factory = RequestFactory() request_factory.cookies['oscar_open_basket'] = '1:NOTAVALIDHASH' request = request_factory.get('/') request.cookies_to_delete = [] cookie_basket = self.middleware.get_cookie_basket("oscar_open_basket", request, None) self.assertEqual(None, cookie_basket) self.assertIn("oscar_open_basket", request.cookies_to_delete)
{ "pile_set_name": "Github" }
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This code is made available to you under your choice of the following sets * of licensing terms: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Copyright 2016 Mozilla Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "pkixgtest.h" #include "mozpkix/pkixder.h" #include "mozpkix/pkixutil.h" using namespace mozilla::pkix; using namespace mozilla::pkix::test; namespace mozilla { namespace pkix { extern Result CheckExtendedKeyUsage(EndEntityOrCA endEntityOrCA, const Input* encodedExtendedKeyUsage, KeyPurposeId requiredEKU, TrustDomain& trustDomain, Time notBefore); } } // namespace mozilla::pkix class pkixcheck_CheckExtendedKeyUsage : public ::testing::Test { protected: DefaultCryptoTrustDomain mTrustDomain; }; #define ASSERT_BAD(x) ASSERT_EQ(Result::ERROR_INADEQUATE_CERT_TYPE, x) // tlv_id_kp_OCSPSigning and tlv_id_kp_serverAuth are defined in pkixtestutil.h // python DottedOIDToCode.py --tlv id-kp-clientAuth 1.3.6.1.5.5.7.3.2 static const uint8_t tlv_id_kp_clientAuth[] = { 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02 }; // python DottedOIDToCode.py --tlv id-kp-codeSigning 1.3.6.1.5.5.7.3.3 static const uint8_t tlv_id_kp_codeSigning[] = { 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x03 }; // python DottedOIDToCode.py --tlv id_kp_emailProtection 1.3.6.1.5.5.7.3.4 static const uint8_t tlv_id_kp_emailProtection[] = { 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x04 }; // python DottedOIDToCode.py --tlv id-Netscape-stepUp 2.16.840.1.113730.4.1 static const uint8_t tlv_id_Netscape_stepUp[] = { 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42, 0x04, 0x01 }; // python DottedOIDToCode.py --tlv unknownOID 1.3.6.1.4.1.13769.666.666.666.1.500.9.3 static const uint8_t tlv_unknownOID[] = { 0x06, 0x12, 0x2b, 0x06, 0x01, 0x04, 0x01, 0xeb, 0x49, 0x85, 0x1a, 0x85, 0x1a, 0x85, 0x1a, 0x01, 0x83, 0x74, 0x09, 0x03 }; // python DottedOIDToCode.py --tlv anyExtendedKeyUsage 2.5.29.37.0 static const uint8_t tlv_anyExtendedKeyUsage[] = { 0x06, 0x04, 0x55, 0x1d, 0x25, 0x00 }; TEST_F(pkixcheck_CheckExtendedKeyUsage, none) { // The input Input is nullptr. This means the cert had no extended key usage // extension. This is always valid except for when the certificate is an // end-entity and the required usage is id-kp-OCSPSigning. ASSERT_EQ(Success, CheckExtendedKeyUsage(EndEntityOrCA::MustBeEndEntity, nullptr, KeyPurposeId::anyExtendedKeyUsage, mTrustDomain, Now())); ASSERT_EQ(Success, CheckExtendedKeyUsage(EndEntityOrCA::MustBeCA, nullptr, KeyPurposeId::anyExtendedKeyUsage, mTrustDomain, Now())); ASSERT_EQ(Success, CheckExtendedKeyUsage(EndEntityOrCA::MustBeEndEntity, nullptr, KeyPurposeId::id_kp_serverAuth, mTrustDomain, Now())); ASSERT_EQ(Success, CheckExtendedKeyUsage(EndEntityOrCA::MustBeCA, nullptr, KeyPurposeId::id_kp_serverAuth, mTrustDomain, Now())); ASSERT_EQ(Success, CheckExtendedKeyUsage(EndEntityOrCA::MustBeEndEntity, nullptr, KeyPurposeId::id_kp_clientAuth, mTrustDomain, Now())); ASSERT_EQ(Success, CheckExtendedKeyUsage(EndEntityOrCA::MustBeCA, nullptr, KeyPurposeId::id_kp_clientAuth, mTrustDomain, Now())); ASSERT_EQ(Success, CheckExtendedKeyUsage(EndEntityOrCA::MustBeEndEntity, nullptr, KeyPurposeId::id_kp_codeSigning, mTrustDomain, Now())); ASSERT_EQ(Success, CheckExtendedKeyUsage(EndEntityOrCA::MustBeCA, nullptr, KeyPurposeId::id_kp_codeSigning, mTrustDomain, Now())); ASSERT_EQ(Success, CheckExtendedKeyUsage(EndEntityOrCA::MustBeEndEntity, nullptr, KeyPurposeId::id_kp_emailProtection, mTrustDomain, Now())); ASSERT_EQ(Success, CheckExtendedKeyUsage(EndEntityOrCA::MustBeCA, nullptr, KeyPurposeId::id_kp_emailProtection, mTrustDomain, Now())); ASSERT_BAD(CheckExtendedKeyUsage(EndEntityOrCA::MustBeEndEntity, nullptr, KeyPurposeId::id_kp_OCSPSigning, mTrustDomain, Now())); ASSERT_EQ(Success, CheckExtendedKeyUsage(EndEntityOrCA::MustBeCA, nullptr, KeyPurposeId::id_kp_OCSPSigning, mTrustDomain, Now())); } static const Input empty_null; TEST_F(pkixcheck_CheckExtendedKeyUsage, empty) { // The input Input is empty. The cert has an empty extended key usage // extension, which is syntactically invalid. ASSERT_BAD(CheckExtendedKeyUsage(EndEntityOrCA::MustBeEndEntity, &empty_null, KeyPurposeId::id_kp_serverAuth, mTrustDomain, Now())); ASSERT_BAD(CheckExtendedKeyUsage(EndEntityOrCA::MustBeCA, &empty_null, KeyPurposeId::id_kp_serverAuth, mTrustDomain, Now())); static const uint8_t dummy = 0x00; Input empty_nonnull; ASSERT_EQ(Success, empty_nonnull.Init(&dummy, 0)); ASSERT_BAD(CheckExtendedKeyUsage(EndEntityOrCA::MustBeEndEntity, &empty_nonnull, KeyPurposeId::id_kp_serverAuth, mTrustDomain, Now())); ASSERT_BAD(CheckExtendedKeyUsage(EndEntityOrCA::MustBeCA, &empty_nonnull, KeyPurposeId::id_kp_serverAuth, mTrustDomain, Now())); } struct EKUTestcase { ByteString ekuSEQUENCE; KeyPurposeId keyPurposeId; Result expectedResultEndEntity; Result expectedResultCA; }; ::std::ostream& operator<<(::std::ostream& os, const EKUTestcase&) { return os << "TODO (bug 1318770)"; } class CheckExtendedKeyUsageTest : public ::testing::Test , public ::testing::WithParamInterface<EKUTestcase> { protected: DefaultCryptoTrustDomain mTrustDomain; }; TEST_P(CheckExtendedKeyUsageTest, EKUTestcase) { const EKUTestcase& param(GetParam()); Input encodedEKU; ASSERT_EQ(Success, encodedEKU.Init(param.ekuSEQUENCE.data(), param.ekuSEQUENCE.length())); ASSERT_EQ(param.expectedResultEndEntity, CheckExtendedKeyUsage(EndEntityOrCA::MustBeEndEntity, &encodedEKU, param.keyPurposeId, mTrustDomain, Now())); ASSERT_EQ(param.expectedResultCA, CheckExtendedKeyUsage(EndEntityOrCA::MustBeCA, &encodedEKU, param.keyPurposeId, mTrustDomain, Now())); } #define SINGLE_EKU_SUCCESS(oidBytes, keyPurposeId) \ { TLV(der::SEQUENCE, BytesToByteString(oidBytes)), keyPurposeId, \ Success, Success } #define SINGLE_EKU_SUCCESS_CA(oidBytes, keyPurposeId) \ { TLV(der::SEQUENCE, BytesToByteString(oidBytes)), keyPurposeId, \ Result::ERROR_INADEQUATE_CERT_TYPE, Success } #define SINGLE_EKU_FAILURE(oidBytes, keyPurposeId) \ { TLV(der::SEQUENCE, BytesToByteString(oidBytes)), keyPurposeId, \ Result::ERROR_INADEQUATE_CERT_TYPE, Result::ERROR_INADEQUATE_CERT_TYPE } #define DOUBLE_EKU_SUCCESS(oidBytes1, oidBytes2, keyPurposeId) \ { TLV(der::SEQUENCE, \ BytesToByteString(oidBytes1) + BytesToByteString(oidBytes2)), \ keyPurposeId, \ Success, Success } #define DOUBLE_EKU_SUCCESS_CA(oidBytes1, oidBytes2, keyPurposeId) \ { TLV(der::SEQUENCE, \ BytesToByteString(oidBytes1) + BytesToByteString(oidBytes2)), \ keyPurposeId, \ Result::ERROR_INADEQUATE_CERT_TYPE, Success } #define DOUBLE_EKU_FAILURE(oidBytes1, oidBytes2, keyPurposeId) \ { TLV(der::SEQUENCE, \ BytesToByteString(oidBytes1) + BytesToByteString(oidBytes2)), \ keyPurposeId, \ Result::ERROR_INADEQUATE_CERT_TYPE, Result::ERROR_INADEQUATE_CERT_TYPE } static const EKUTestcase EKU_TESTCASES[] = { SINGLE_EKU_SUCCESS(tlv_id_kp_serverAuth, KeyPurposeId::anyExtendedKeyUsage), SINGLE_EKU_SUCCESS(tlv_id_kp_serverAuth, KeyPurposeId::id_kp_serverAuth), SINGLE_EKU_FAILURE(tlv_id_kp_serverAuth, KeyPurposeId::id_kp_clientAuth), SINGLE_EKU_FAILURE(tlv_id_kp_serverAuth, KeyPurposeId::id_kp_codeSigning), SINGLE_EKU_FAILURE(tlv_id_kp_serverAuth, KeyPurposeId::id_kp_emailProtection), SINGLE_EKU_FAILURE(tlv_id_kp_serverAuth, KeyPurposeId::id_kp_OCSPSigning), SINGLE_EKU_SUCCESS(tlv_id_kp_clientAuth, KeyPurposeId::anyExtendedKeyUsage), SINGLE_EKU_FAILURE(tlv_id_kp_clientAuth, KeyPurposeId::id_kp_serverAuth), SINGLE_EKU_SUCCESS(tlv_id_kp_clientAuth, KeyPurposeId::id_kp_clientAuth), SINGLE_EKU_FAILURE(tlv_id_kp_clientAuth, KeyPurposeId::id_kp_codeSigning), SINGLE_EKU_FAILURE(tlv_id_kp_clientAuth, KeyPurposeId::id_kp_emailProtection), SINGLE_EKU_FAILURE(tlv_id_kp_clientAuth, KeyPurposeId::id_kp_OCSPSigning), SINGLE_EKU_SUCCESS(tlv_id_kp_codeSigning, KeyPurposeId::anyExtendedKeyUsage), SINGLE_EKU_FAILURE(tlv_id_kp_codeSigning, KeyPurposeId::id_kp_serverAuth), SINGLE_EKU_FAILURE(tlv_id_kp_codeSigning, KeyPurposeId::id_kp_clientAuth), SINGLE_EKU_SUCCESS(tlv_id_kp_codeSigning, KeyPurposeId::id_kp_codeSigning), SINGLE_EKU_FAILURE(tlv_id_kp_codeSigning, KeyPurposeId::id_kp_emailProtection), SINGLE_EKU_FAILURE(tlv_id_kp_codeSigning, KeyPurposeId::id_kp_OCSPSigning), SINGLE_EKU_SUCCESS(tlv_id_kp_emailProtection, KeyPurposeId::anyExtendedKeyUsage), SINGLE_EKU_FAILURE(tlv_id_kp_emailProtection, KeyPurposeId::id_kp_serverAuth), SINGLE_EKU_FAILURE(tlv_id_kp_emailProtection, KeyPurposeId::id_kp_clientAuth), SINGLE_EKU_FAILURE(tlv_id_kp_emailProtection, KeyPurposeId::id_kp_codeSigning), SINGLE_EKU_SUCCESS(tlv_id_kp_emailProtection, KeyPurposeId::id_kp_emailProtection), SINGLE_EKU_FAILURE(tlv_id_kp_emailProtection, KeyPurposeId::id_kp_OCSPSigning), // For end-entities, if id-kp-OCSPSigning is present, no usage is allowed // except OCSPSigning. SINGLE_EKU_SUCCESS_CA(tlv_id_kp_OCSPSigning, KeyPurposeId::anyExtendedKeyUsage), SINGLE_EKU_FAILURE(tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_serverAuth), SINGLE_EKU_FAILURE(tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_clientAuth), SINGLE_EKU_FAILURE(tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_codeSigning), SINGLE_EKU_FAILURE(tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_emailProtection), SINGLE_EKU_SUCCESS(tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_OCSPSigning), SINGLE_EKU_SUCCESS(tlv_id_Netscape_stepUp, KeyPurposeId::anyExtendedKeyUsage), // For compatibility, id-Netscape-stepUp is treated as equivalent to // id-kp-serverAuth for CAs. SINGLE_EKU_SUCCESS_CA(tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_serverAuth), SINGLE_EKU_FAILURE(tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_clientAuth), SINGLE_EKU_FAILURE(tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_codeSigning), SINGLE_EKU_FAILURE(tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_emailProtection), SINGLE_EKU_FAILURE(tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_OCSPSigning), SINGLE_EKU_SUCCESS(tlv_unknownOID, KeyPurposeId::anyExtendedKeyUsage), SINGLE_EKU_FAILURE(tlv_unknownOID, KeyPurposeId::id_kp_serverAuth), SINGLE_EKU_FAILURE(tlv_unknownOID, KeyPurposeId::id_kp_clientAuth), SINGLE_EKU_FAILURE(tlv_unknownOID, KeyPurposeId::id_kp_codeSigning), SINGLE_EKU_FAILURE(tlv_unknownOID, KeyPurposeId::id_kp_emailProtection), SINGLE_EKU_FAILURE(tlv_unknownOID, KeyPurposeId::id_kp_OCSPSigning), SINGLE_EKU_SUCCESS(tlv_anyExtendedKeyUsage, KeyPurposeId::anyExtendedKeyUsage), SINGLE_EKU_FAILURE(tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_serverAuth), SINGLE_EKU_FAILURE(tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_clientAuth), SINGLE_EKU_FAILURE(tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_codeSigning), SINGLE_EKU_FAILURE(tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_emailProtection), SINGLE_EKU_FAILURE(tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_id_kp_clientAuth, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_id_kp_clientAuth, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_id_kp_clientAuth, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_kp_clientAuth, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_kp_clientAuth, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_kp_clientAuth, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_id_kp_codeSigning, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_id_kp_codeSigning, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_kp_codeSigning, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_id_kp_codeSigning, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_kp_codeSigning, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_kp_codeSigning, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_id_kp_emailProtection, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_id_kp_emailProtection, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_kp_emailProtection, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_kp_emailProtection, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_id_kp_emailProtection, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_kp_emailProtection, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS_CA(tlv_id_kp_serverAuth, tlv_id_kp_OCSPSigning, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_SUCCESS_CA(tlv_id_kp_serverAuth, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_id_Netscape_stepUp, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_unknownOID, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_unknownOID, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_unknownOID, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_unknownOID, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_unknownOID, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_unknownOID, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_anyExtendedKeyUsage, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_SUCCESS(tlv_id_kp_serverAuth, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_serverAuth, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_clientAuth, tlv_id_kp_codeSigning, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_id_kp_codeSigning, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_SUCCESS(tlv_id_kp_clientAuth, tlv_id_kp_codeSigning, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_SUCCESS(tlv_id_kp_clientAuth, tlv_id_kp_codeSigning, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_id_kp_codeSigning, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_id_kp_codeSigning, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_clientAuth, tlv_id_kp_emailProtection, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_id_kp_emailProtection, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_SUCCESS(tlv_id_kp_clientAuth, tlv_id_kp_emailProtection, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_id_kp_emailProtection, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_clientAuth, tlv_id_kp_emailProtection, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_id_kp_emailProtection, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS_CA(tlv_id_kp_clientAuth, tlv_id_kp_OCSPSigning, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_SUCCESS_CA(tlv_id_kp_clientAuth, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_SUCCESS(tlv_id_kp_clientAuth, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_clientAuth, tlv_id_Netscape_stepUp, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_SUCCESS_CA(tlv_id_kp_clientAuth, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_SUCCESS(tlv_id_kp_clientAuth, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_clientAuth, tlv_unknownOID, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_unknownOID, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_SUCCESS(tlv_id_kp_clientAuth, tlv_unknownOID, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_unknownOID, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_unknownOID, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_unknownOID, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_clientAuth, tlv_anyExtendedKeyUsage, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_SUCCESS(tlv_id_kp_clientAuth, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_clientAuth, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_codeSigning, tlv_id_kp_emailProtection, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_id_kp_emailProtection, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_id_kp_emailProtection, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_SUCCESS(tlv_id_kp_codeSigning, tlv_id_kp_emailProtection, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_codeSigning, tlv_id_kp_emailProtection, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_id_kp_emailProtection, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS_CA(tlv_id_kp_codeSigning, tlv_id_kp_OCSPSigning, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_SUCCESS_CA(tlv_id_kp_codeSigning, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_SUCCESS(tlv_id_kp_codeSigning, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_codeSigning, tlv_id_Netscape_stepUp, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_SUCCESS_CA(tlv_id_kp_codeSigning, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_SUCCESS(tlv_id_kp_codeSigning, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_codeSigning, tlv_unknownOID, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_unknownOID, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_unknownOID, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_SUCCESS(tlv_id_kp_codeSigning, tlv_unknownOID, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_unknownOID, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_unknownOID, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_codeSigning, tlv_anyExtendedKeyUsage, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_SUCCESS(tlv_id_kp_codeSigning, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_codeSigning, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS_CA(tlv_id_kp_emailProtection, tlv_id_kp_OCSPSigning, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_FAILURE(tlv_id_kp_emailProtection, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_emailProtection, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_emailProtection, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_SUCCESS_CA(tlv_id_kp_emailProtection, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_SUCCESS(tlv_id_kp_emailProtection, tlv_id_kp_OCSPSigning, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_emailProtection, tlv_id_Netscape_stepUp, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_SUCCESS_CA(tlv_id_kp_emailProtection, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_emailProtection, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_emailProtection, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_emailProtection, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_emailProtection, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_emailProtection, tlv_unknownOID, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_FAILURE(tlv_id_kp_emailProtection, tlv_unknownOID, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_emailProtection, tlv_unknownOID, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_emailProtection, tlv_unknownOID, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_emailProtection, tlv_unknownOID, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_emailProtection, tlv_unknownOID, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_emailProtection, tlv_anyExtendedKeyUsage, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_FAILURE(tlv_id_kp_emailProtection, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_emailProtection, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_emailProtection, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_SUCCESS(tlv_id_kp_emailProtection, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_kp_emailProtection, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS_CA(tlv_id_kp_OCSPSigning, tlv_id_Netscape_stepUp, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_SUCCESS_CA(tlv_id_kp_OCSPSigning, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_OCSPSigning, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_OCSPSigning, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_OCSPSigning, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_SUCCESS(tlv_id_kp_OCSPSigning, tlv_id_Netscape_stepUp, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS_CA(tlv_id_kp_OCSPSigning, tlv_unknownOID, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_FAILURE(tlv_id_kp_OCSPSigning, tlv_unknownOID, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_OCSPSigning, tlv_unknownOID, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_OCSPSigning, tlv_unknownOID, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_OCSPSigning, tlv_unknownOID, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_SUCCESS(tlv_id_kp_OCSPSigning, tlv_unknownOID, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS_CA(tlv_id_kp_OCSPSigning, tlv_anyExtendedKeyUsage, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_FAILURE(tlv_id_kp_OCSPSigning, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_OCSPSigning, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_kp_OCSPSigning, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_kp_OCSPSigning, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_SUCCESS(tlv_id_kp_OCSPSigning, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_Netscape_stepUp, tlv_unknownOID, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_SUCCESS_CA(tlv_id_Netscape_stepUp, tlv_unknownOID, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_Netscape_stepUp, tlv_unknownOID, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_Netscape_stepUp, tlv_unknownOID, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_Netscape_stepUp, tlv_unknownOID, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_Netscape_stepUp, tlv_unknownOID, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_id_Netscape_stepUp, tlv_anyExtendedKeyUsage, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_SUCCESS_CA(tlv_id_Netscape_stepUp, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_id_Netscape_stepUp, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_id_Netscape_stepUp, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_id_Netscape_stepUp, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_id_Netscape_stepUp, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_OCSPSigning), DOUBLE_EKU_SUCCESS(tlv_unknownOID, tlv_anyExtendedKeyUsage, KeyPurposeId::anyExtendedKeyUsage), DOUBLE_EKU_FAILURE(tlv_unknownOID, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_serverAuth), DOUBLE_EKU_FAILURE(tlv_unknownOID, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_clientAuth), DOUBLE_EKU_FAILURE(tlv_unknownOID, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_codeSigning), DOUBLE_EKU_FAILURE(tlv_unknownOID, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_emailProtection), DOUBLE_EKU_FAILURE(tlv_unknownOID, tlv_anyExtendedKeyUsage, KeyPurposeId::id_kp_OCSPSigning), }; INSTANTIATE_TEST_CASE_P(pkixcheck_CheckExtendedKeyUsage, CheckExtendedKeyUsageTest, ::testing::ValuesIn(EKU_TESTCASES)); struct EKUChainTestcase { ByteString ekuExtensionEE; ByteString ekuExtensionCA; KeyPurposeId keyPurposeId; Result expectedResult; }; ::std::ostream& operator<<(::std::ostream& os, const EKUChainTestcase&) { return os << "TODO (bug 1318770)"; } class CheckExtendedKeyUsageChainTest : public ::testing::Test , public ::testing::WithParamInterface<EKUChainTestcase> { }; static ByteString CreateCert(const char* issuerCN, const char* subjectCN, EndEntityOrCA endEntityOrCA, ByteString encodedEKU) { static long serialNumberValue = 0; ++serialNumberValue; ByteString serialNumber(CreateEncodedSerialNumber(serialNumberValue)); EXPECT_FALSE(ENCODING_FAILED(serialNumber)); ByteString issuerDER(CNToDERName(issuerCN)); ByteString subjectDER(CNToDERName(subjectCN)); ByteString extensions[3]; extensions[0] = CreateEncodedBasicConstraints(endEntityOrCA == EndEntityOrCA::MustBeCA, nullptr, Critical::Yes); EXPECT_FALSE(ENCODING_FAILED(extensions[0])); if (encodedEKU.length() > 0) { extensions[1] = encodedEKU; } ScopedTestKeyPair reusedKey(CloneReusedKeyPair()); ByteString certDER(CreateEncodedCertificate( v3, sha256WithRSAEncryption(), serialNumber, issuerDER, oneDayBeforeNow, oneDayAfterNow, subjectDER, *reusedKey, extensions, *reusedKey, sha256WithRSAEncryption())); EXPECT_FALSE(ENCODING_FAILED(certDER)); return certDER; } class EKUTrustDomain final : public DefaultCryptoTrustDomain { public: explicit EKUTrustDomain(ByteString issuerCertDER) : mIssuerCertDER(issuerCertDER) { } private: Result GetCertTrust(EndEntityOrCA, const CertPolicyId&, Input candidateCert, TrustLevel& trustLevel) override { trustLevel = InputEqualsByteString(candidateCert, mIssuerCertDER) ? TrustLevel::TrustAnchor : TrustLevel::InheritsTrust; return Success; } Result FindIssuer(Input, IssuerChecker& checker, Time) override { Input derCert; Result rv = derCert.Init(mIssuerCertDER.data(), mIssuerCertDER.length()); if (rv != Success) { return rv; } bool keepGoing; return checker.Check(derCert, nullptr, keepGoing); } Result CheckRevocation(EndEntityOrCA, const CertID&, Time, Duration, const Input*, const Input*, const Input*) override { return Success; } Result IsChainValid(const DERArray&, Time, const CertPolicyId&) override { return Success; } ByteString mIssuerCertDER; }; TEST_P(CheckExtendedKeyUsageChainTest, EKUChainTestcase) { const EKUChainTestcase& param(GetParam()); ByteString issuerCertDER(CreateCert("CA", "CA", EndEntityOrCA::MustBeCA, param.ekuExtensionCA)); ByteString subjectCertDER(CreateCert("CA", "EE", EndEntityOrCA::MustBeEndEntity, param.ekuExtensionEE)); EKUTrustDomain trustDomain(issuerCertDER); Input subjectCertDERInput; ASSERT_EQ(Success, subjectCertDERInput.Init(subjectCertDER.data(), subjectCertDER.length())); ASSERT_EQ(param.expectedResult, BuildCertChain(trustDomain, subjectCertDERInput, Now(), EndEntityOrCA::MustBeEndEntity, KeyUsage::noParticularKeyUsageRequired, param.keyPurposeId, CertPolicyId::anyPolicy, nullptr)); } // python DottedOIDToCode.py --tlv id-ce-extKeyUsage 2.5.29.37 static const uint8_t tlv_id_ce_extKeyUsage[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 }; static inline ByteString CreateEKUExtension(ByteString ekuOIDs) { return TLV(der::SEQUENCE, BytesToByteString(tlv_id_ce_extKeyUsage) + TLV(der::OCTET_STRING, TLV(der::SEQUENCE, ekuOIDs))); } static const EKUChainTestcase EKU_CHAIN_TESTCASES[] = { { // Both end-entity and CA have id-kp-serverAuth => should succeed CreateEKUExtension(BytesToByteString(tlv_id_kp_serverAuth)), CreateEKUExtension(BytesToByteString(tlv_id_kp_serverAuth)), KeyPurposeId::id_kp_serverAuth, Success }, { // CA has no EKU extension => should succeed CreateEKUExtension(BytesToByteString(tlv_id_kp_serverAuth)), ByteString(), KeyPurposeId::id_kp_serverAuth, Success }, { // End-entity has no EKU extension => should succeed ByteString(), CreateEKUExtension(BytesToByteString(tlv_id_kp_serverAuth)), KeyPurposeId::id_kp_serverAuth, Success }, { // No EKU extensions at all => should succeed ByteString(), ByteString(), KeyPurposeId::id_kp_serverAuth, Success }, { // CA has EKU without id-kp-serverAuth => should fail CreateEKUExtension(BytesToByteString(tlv_id_kp_serverAuth)), CreateEKUExtension(BytesToByteString(tlv_id_kp_clientAuth)), KeyPurposeId::id_kp_serverAuth, Result::ERROR_INADEQUATE_CERT_TYPE }, { // End-entity has EKU without id-kp-serverAuth => should fail CreateEKUExtension(BytesToByteString(tlv_id_kp_clientAuth)), CreateEKUExtension(BytesToByteString(tlv_id_kp_serverAuth)), KeyPurposeId::id_kp_serverAuth, Result::ERROR_INADEQUATE_CERT_TYPE }, { // Both end-entity and CA have EKU without id-kp-serverAuth => should fail CreateEKUExtension(BytesToByteString(tlv_id_kp_clientAuth)), CreateEKUExtension(BytesToByteString(tlv_id_kp_clientAuth)), KeyPurposeId::id_kp_serverAuth, Result::ERROR_INADEQUATE_CERT_TYPE }, { // End-entity has no EKU, CA doesn't have id-kp-serverAuth => should fail ByteString(), CreateEKUExtension(BytesToByteString(tlv_id_kp_clientAuth)), KeyPurposeId::id_kp_serverAuth, Result::ERROR_INADEQUATE_CERT_TYPE }, { // End-entity doesn't have id-kp-serverAuth, CA has no EKU => should fail CreateEKUExtension(BytesToByteString(tlv_id_kp_clientAuth)), ByteString(), KeyPurposeId::id_kp_serverAuth, Result::ERROR_INADEQUATE_CERT_TYPE }, { // CA has id-Netscape-stepUp => should succeed CreateEKUExtension(BytesToByteString(tlv_id_kp_serverAuth)), CreateEKUExtension(BytesToByteString(tlv_id_Netscape_stepUp)), KeyPurposeId::id_kp_serverAuth, Success }, { // End-entity has id-Netscape-stepUp => should fail CreateEKUExtension(BytesToByteString(tlv_id_Netscape_stepUp)), CreateEKUExtension(BytesToByteString(tlv_id_kp_serverAuth)), KeyPurposeId::id_kp_serverAuth, Result::ERROR_INADEQUATE_CERT_TYPE }, { // End-entity and CA have id-kp-serverAuth and id-kp-clientAuth => should // succeed CreateEKUExtension(BytesToByteString(tlv_id_kp_serverAuth) + BytesToByteString(tlv_id_kp_clientAuth)), CreateEKUExtension(BytesToByteString(tlv_id_kp_serverAuth) + BytesToByteString(tlv_id_kp_clientAuth)), KeyPurposeId::id_kp_serverAuth, Success }, { // End-entity has id-kp-serverAuth and id-kp-OCSPSigning => should fail CreateEKUExtension(BytesToByteString(tlv_id_kp_serverAuth) + BytesToByteString(tlv_id_kp_OCSPSigning)), CreateEKUExtension(BytesToByteString(tlv_id_kp_serverAuth) + BytesToByteString(tlv_id_kp_clientAuth)), KeyPurposeId::id_kp_serverAuth, Result::ERROR_INADEQUATE_CERT_TYPE }, { // CA has id-kp-serverAuth and id-kp-OCSPSigning => should succeed CreateEKUExtension(BytesToByteString(tlv_id_kp_serverAuth) + BytesToByteString(tlv_id_kp_clientAuth)), CreateEKUExtension(BytesToByteString(tlv_id_kp_serverAuth) + BytesToByteString(tlv_id_kp_OCSPSigning)), KeyPurposeId::id_kp_serverAuth, Success }, }; INSTANTIATE_TEST_CASE_P(pkixcheck_CheckExtendedKeyUsage, CheckExtendedKeyUsageChainTest, ::testing::ValuesIn(EKU_CHAIN_TESTCASES));
{ "pile_set_name": "Github" }
// // RKTwitterViewController.m // RKTwitter // // Created by Blake Watters on 9/5/10. // Copyright (c) 2009-2012 RestKit. All rights reserved. // #import "RKTwitterViewController.h" #import "RKTweet.h" static void RKTwitterShowAlertWithError(NSError *error) { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; } @interface RKTwitterViewController () <UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate> @property (nonatomic, weak) IBOutlet UITableView *tableView; @property (nonatomic, strong) NSFetchedResultsController *fetchedResultsController; @end @implementation RKTwitterViewController - (void)viewDidLoad { [super viewDidLoad]; // Set debug logging level. Set to 'RKLogLevelTrace' to see JSON payload RKLogConfigureByName("RestKit/Network", RKLogLevelDebug); // Setup View and Table View self.title = @"RestKit Tweets"; NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Tweet"]; NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:NO]; fetchRequest.sortDescriptors = @[descriptor]; NSError *error = nil; // Setup fetched results self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[RKManagedObjectStore defaultStore].mainQueueManagedObjectContext sectionNameKeyPath:nil cacheName:nil]; [self.fetchedResultsController setDelegate:self]; BOOL fetchSuccessful = [self.fetchedResultsController performFetch:&error]; NSAssert([[self.fetchedResultsController fetchedObjects] count], @"Seeding didn't work..."); if (! fetchSuccessful) { RKTwitterShowAlertWithError(error); } [self loadData]; } - (void)loadData { // Load the object model via RestKit [[RKObjectManager sharedManager] getObjectsAtPath:@"/status/user_timeline/RestKit" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { RKLogInfo(@"Load complete: Table should refresh..."); [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"LastUpdatedAt"]; [[NSUserDefaults standardUserDefaults] synchronize]; } failure:^(RKObjectRequestOperation *operation, NSError *error) { RKLogError(@"Load failed with error: %@", error); RKTwitterShowAlertWithError(error); }]; } - (IBAction)refresh:(id)sender { // Load the object model via RestKit [self loadData]; } #pragma mark UITableViewDelegate methods - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { RKTweet *status = [self.fetchedResultsController objectAtIndexPath:indexPath]; CGSize size = [[status text] sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(300, 9000)]; return size.height + 10; } #pragma mark UITableViewDataSource methods - (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section { id<NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultsController.sections objectAtIndex:section]; return [sectionInfo numberOfObjects]; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { NSDate *lastUpdatedAt = [[NSUserDefaults standardUserDefaults] objectForKey:@"LastUpdatedAt"]; NSString *dateString = [NSDateFormatter localizedStringFromDate:lastUpdatedAt dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterMediumStyle]; if (nil == dateString) { dateString = @"Never"; } return [NSString stringWithFormat:@"Last Load: %@", dateString]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *reuseIdentifier = @"Tweet Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; if (nil == cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier]; cell.textLabel.font = [UIFont systemFontOfSize:14]; cell.textLabel.numberOfLines = 0; cell.textLabel.backgroundColor = [UIColor clearColor]; cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"listbg.png"]]; } RKTweet *status = [self.fetchedResultsController objectAtIndexPath:indexPath]; cell.textLabel.text = status.text; return cell; } #pragma mark NSFetchedResultsControllerDelegate methods - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller { [self.tableView reloadData]; } @end
{ "pile_set_name": "Github" }
GOTO MAIN REM $INCLUDE: 'mem.in.bas' REM $INCLUDE: 'types.in.bas' REM $INCLUDE: 'readline.in.bas' REM $INCLUDE: 'reader.in.bas' REM $INCLUDE: 'printer.in.bas' REM $INCLUDE: 'env.in.bas' REM $INCLUDE: 'core.in.bas' REM $INCLUDE: 'debug.in.bas' REM READ is inlined in RE REM QUASIQUOTE(A) -> R SUB QUASIQUOTE GOSUB TYPE_A IF T<5 OR T>8 THEN GOTO QQ_UNCHANGED IF T=5 OR T=8 THEN GOTO QQ_QUOTE IF T=7 THEN GOTO QQ_VECTOR IF (Z%(A+1)=0) THEN GOTO QQ_LIST R=Z%(A+2) IF (Z%(R)AND 31)<>5 THEN GOTO QQ_LIST IF S$(Z%(R+1))<>"unquote" THEN GOTO QQ_LIST GOTO QQ_UNQUOTE QQ_UNCHANGED: R=A GOSUB INC_REF_R GOTO QQ_DONE QQ_QUOTE: REM ['quote, ast] B$="quote":T=5:GOSUB STRING B=R:GOSUB LIST2 AY=B:GOSUB RELEASE GOTO QQ_DONE QQ_VECTOR: REM ['vec, (qq_foldr ast)] CALL QQ_FOLDR A=R B$="vec":T=5:GOSUB STRING:B=R GOSUB LIST2 AY=A:GOSUB RELEASE AY=B:GOSUB RELEASE GOTO QQ_DONE QQ_UNQUOTE: REM [ast[1]] R=Z%(Z%(A+1)+2) GOSUB INC_REF_R GOTO QQ_DONE QQ_LIST: CALL QQ_FOLDR QQ_DONE: END SUB REM Quasiquote right fold (A) -> R. REM Used for unquoted lists (GOTO), vectors (GOSUB), REM and recursively (GOSUB). SUB QQ_FOLDR IF A=0 THEN GOTO QQ_EMPTY IF Z%(A+1)=0 THEN GOTO QQ_EMPTY GOTO QQ_NOTEMPTY QQ_EMPTY: REM empty list/vector -> empty list R=6 GOSUB INC_REF_R GOTO QQ_FOLDR_DONE QQ_NOTEMPTY: REM Execute QQ_FOLDR recursively with (rest A) GOSUB PUSH_A A=Z%(A+1):CALL QQ_FOLDR GOSUB POP_A REM Set A to elt = (first A) A=Z%(A+2) REM Quasiquote transition function: REM A: current element, R: accumulator -> R: new accumulator REM check if A is a list starting with splice-unquote GOSUB TYPE_A IF T<>6 THEN GOTO QQ_DEFAULT IF (Z%(A+1)=0) THEN GOTO QQ_DEFAULT B=Z%(A+2) IF (Z%(B)AND 31)<>5 THEN GOTO QQ_DEFAULT IF S$(Z%(B+1))<>"splice-unquote" THEN GOTO QQ_DEFAULT REM ('concat, A[1], R) B=Z%(Z%(A+1)+2) A=R B$="concat":T=5:GOSUB STRING:C=R GOSUB LIST3 REM release inner quasiquoted since outer list takes ownership AY=A:GOSUB RELEASE AY=C:GOSUB RELEASE GOTO QQ_FOLDR_DONE QQ_DEFAULT: REM ('cons, quasiquote(A), R) GOSUB PUSH_R CALL QUASIQUOTE B=R B$="cons":T=5:GOSUB STRING:C=R GOSUB POP_A GOSUB LIST3 REM release inner quasiquoted since outer list takes ownership AY=A:GOSUB RELEASE AY=B:GOSUB RELEASE AY=C:GOSUB RELEASE QQ_FOLDR_DONE: END SUB REM MACROEXPAND(A, E) -> A: SUB MACROEXPAND GOSUB PUSH_A MACROEXPAND_LOOP: REM list? GOSUB TYPE_A IF T<>6 THEN GOTO MACROEXPAND_DONE REM non-empty? IF Z%(A+1)=0 THEN GOTO MACROEXPAND_DONE B=Z%(A+2) REM symbol? in first position IF (Z%(B)AND 31)<>5 THEN GOTO MACROEXPAND_DONE REM defined in environment? K=B:CALL ENV_FIND IF R=-1 THEN GOTO MACROEXPAND_DONE B=R4 REM macro? IF (Z%(B)AND 31)<>11 THEN GOTO MACROEXPAND_DONE F=B:AR=Z%(A+1):CALL APPLY A=R GOSUB PEEK_Q:AY=Q REM if previous A was not the first A into macroexpand (i.e. an REM intermediate form) then free it IF A<>AY THEN GOSUB PEND_A_LV IF ER<>-2 THEN GOTO MACROEXPAND_DONE GOTO MACROEXPAND_LOOP MACROEXPAND_DONE: GOSUB POP_Q: REM pop original A END SUB REM EVAL_AST(A, E) -> R SUB EVAL_AST REM push A and E on the stack Q=E:GOSUB PUSH_Q GOSUB PUSH_A IF ER<>-2 THEN GOTO EVAL_AST_RETURN GOSUB TYPE_A IF T=5 THEN GOTO EVAL_AST_SYMBOL IF T>5 AND T<9 THEN GOTO EVAL_AST_SEQ REM scalar: deref to actual value and inc ref cnt R=A GOSUB INC_REF_R GOTO EVAL_AST_RETURN EVAL_AST_SYMBOL: K=A:GOTO ENV_GET ENV_GET_RETURN: GOTO EVAL_AST_RETURN EVAL_AST_SEQ: REM setup the stack for the loop GOSUB MAP_LOOP_START EVAL_AST_SEQ_LOOP: REM check if we are done evaluating the source sequence IF Z%(A+1)=0 THEN GOTO EVAL_AST_SEQ_LOOP_DONE REM if we are returning to DO, then skip last element REM The EVAL_DO call to EVAL_AST must be call #2 for EVAL_AST to REM return early and for TCO to work Q=5:GOSUB PEEK_Q_Q IF Q=2 AND Z%(Z%(A+1)+1)=0 THEN GOTO EVAL_AST_SEQ_LOOP_DONE REM call EVAL for each entry GOSUB PUSH_A IF T<>8 THEN A=Z%(A+2) IF T=8 THEN A=Z%(A+3) Q=T:GOSUB PUSH_Q: REM push/save type CALL EVAL GOSUB POP_Q:T=Q: REM pop/restore type GOSUB POP_A M=R REM if error, release the unattached element REM TODO: is R=0 correct? IF ER<>-2 THEN AY=R:GOSUB RELEASE:R=0:GOTO EVAL_AST_SEQ_LOOP_DONE REM for hash-maps, copy the key (inc ref since we are going to REM release it below) IF T=8 THEN N=M:M=Z%(A+2):Z%(M)=Z%(M)+32 REM update the return sequence structure REM release N (and M if T=8) since seq takes full ownership C=1:GOSUB MAP_LOOP_UPDATE REM process the next sequence entry from source list A=Z%(A+1) GOTO EVAL_AST_SEQ_LOOP EVAL_AST_SEQ_LOOP_DONE: REM cleanup stack and get return value GOSUB MAP_LOOP_DONE GOTO EVAL_AST_RETURN EVAL_AST_RETURN: REM pop A and E off the stack GOSUB POP_A GOSUB POP_Q:E=Q END SUB REM EVAL(A, E) -> R SUB EVAL LV=LV+1: REM track basic return stack level REM push A and E on the stack Q=E:GOSUB PUSH_Q GOSUB PUSH_A REM PRINT "EVAL A:"+STR$(A)+",X:"+STR$(X)+",LV:"+STR$(LV)+",FRE:"+STR$(FRE(0)) EVAL_TCO_RECUR: IF ER<>-2 THEN GOTO EVAL_RETURN REM AZ=A:B=1:GOSUB PR_STR REM PRINT "EVAL: "+R$+" [A:"+STR$(A)+", LV:"+STR$(LV)+"]" GOSUB LIST_Q IF R THEN GOTO APPLY_LIST EVAL_NOT_LIST: REM ELSE CALL EVAL_AST GOTO EVAL_RETURN APPLY_LIST: CALL MACROEXPAND GOSUB LIST_Q IF R<>1 THEN GOTO EVAL_NOT_LIST GOSUB EMPTY_Q IF R THEN R=A:GOSUB INC_REF_R:GOTO EVAL_RETURN A0=Z%(A+2) REM get symbol in A$ IF (Z%(A0)AND 31)<>5 THEN A$="" IF (Z%(A0)AND 31)=5 THEN A$=S$(Z%(A0+1)) IF A$="def!" THEN GOTO EVAL_DEF IF A$="let*" THEN GOTO EVAL_LET IF A$="quote" THEN GOTO EVAL_QUOTE IF A$="quasiquoteexpand" THEN GOTO EVAL_QUASIQUOTEEXPAND IF A$="quasiquote" THEN GOTO EVAL_QUASIQUOTE IF A$="defmacro!" THEN GOTO EVAL_DEFMACRO IF A$="macroexpand" THEN GOTO EVAL_MACROEXPAND IF A$="try*" THEN GOTO EVAL_TRY IF A$="do" THEN GOTO EVAL_DO IF A$="if" THEN GOTO EVAL_IF IF A$="fn*" THEN GOTO EVAL_FN GOTO EVAL_INVOKE EVAL_GET_A3: A3=Z%(Z%(Z%(Z%(A+1)+1)+1)+2) EVAL_GET_A2: A2=Z%(Z%(Z%(A+1)+1)+2) EVAL_GET_A1: A1=Z%(Z%(A+1)+2) RETURN EVAL_DEF: REM PRINT "def!" GOSUB EVAL_GET_A2: REM set A1 and A2 Q=A1:GOSUB PUSH_Q A=A2:CALL EVAL: REM eval a2 GOSUB POP_Q:A1=Q IF ER<>-2 THEN GOTO EVAL_RETURN REM set a1 in env to a2 K=A1:C=R:GOSUB ENV_SET GOTO EVAL_RETURN EVAL_LET: REM PRINT "let*" GOSUB EVAL_GET_A2: REM set A1 and A2 Q=A2:GOSUB PUSH_Q: REM push/save A2 Q=E:GOSUB PUSH_Q: REM push env for for later release REM create new environment with outer as current environment C=E:GOSUB ENV_NEW E=R EVAL_LET_LOOP: IF Z%(A1+1)=0 THEN GOTO EVAL_LET_LOOP_DONE Q=A1:GOSUB PUSH_Q: REM push A1 REM eval current A1 odd element A=Z%(Z%(A1+1)+2):CALL EVAL GOSUB POP_Q:A1=Q: REM pop A1 IF ER<>-2 THEN GOTO EVAL_LET_LOOP_DONE REM set key/value in the environment K=Z%(A1+2):C=R:GOSUB ENV_SET AY=R:GOSUB RELEASE: REM release our use, ENV_SET took ownership REM skip to the next pair of A1 elements A1=Z%(Z%(A1+1)+1) GOTO EVAL_LET_LOOP EVAL_LET_LOOP_DONE: GOSUB POP_Q:AY=Q: REM pop previous env REM release previous environment if not the current EVAL env GOSUB PEEK_Q_2 IF AY<>Q THEN GOSUB RELEASE GOSUB POP_Q:A2=Q: REM pop A2 A=A2:GOTO EVAL_TCO_RECUR: REM TCO loop EVAL_DO: A=Z%(A+1): REM rest GOSUB PUSH_A: REM push/save A REM this must be EVAL_AST call #2 for EVAL_AST to return early REM and for TCO to work CALL EVAL_AST REM cleanup AY=R: REM get eval'd list for release GOSUB POP_A: REM pop/restore original A for LAST GOSUB LAST: REM get last element for return A=R: REM new recur AST REM cleanup GOSUB RELEASE: REM release eval'd list AY=A:GOSUB RELEASE: REM release LAST value (not sure why) GOTO EVAL_TCO_RECUR: REM TCO loop EVAL_QUOTE: R=Z%(Z%(A+1)+2) GOSUB INC_REF_R GOTO EVAL_RETURN EVAL_QUASIQUOTEEXPAND: R=Z%(Z%(A+1)+2) A=R:CALL QUASIQUOTE GOTO EVAL_RETURN EVAL_QUASIQUOTE: R=Z%(Z%(A+1)+2) A=R:CALL QUASIQUOTE A=R REM add quasiquote result to pending release queue to free when REM next lower EVAL level returns (LV) GOSUB PEND_A_LV GOTO EVAL_TCO_RECUR: REM TCO loop EVAL_DEFMACRO: REM PRINT "defmacro!" GOSUB EVAL_GET_A2: REM set A1 and A2 Q=A1:GOSUB PUSH_Q: REM push A1 A=A2:CALL EVAL: REM eval A2 GOSUB POP_Q:A1=Q: REM pop A1 REM change function to macro Z%(R)=Z%(R)+1 REM set A1 in env to A2 K=A1:C=R:GOSUB ENV_SET GOTO EVAL_RETURN EVAL_MACROEXPAND: REM PRINT "macroexpand" R=Z%(Z%(A+1)+2) A=R:CALL MACROEXPAND R=A REM since we are returning it unevaluated, inc the ref cnt GOSUB INC_REF_R GOTO EVAL_RETURN EVAL_TRY: REM PRINT "try*" GOSUB EVAL_GET_A1: REM set A1 GOSUB PUSH_A: REM push/save A A=A1:CALL EVAL: REM eval A1 GOSUB POP_A: REM pop/restore A GOSUB EVAL_GET_A2: REM set A1 and A2 REM if there is no error or catch block then return IF ER=-2 OR A2=0 THEN GOTO EVAL_RETURN REM create environment for the catch block eval C=E:GOSUB ENV_NEW:E=R A=A2:GOSUB EVAL_GET_A2: REM set A1 and A2 from catch block REM create object for ER=-1 type raw string errors IF ER=-1 THEN B$=E$:T=4:GOSUB STRING:ER=R:GOSUB INC_REF_R REM bind the catch symbol to the error object K=A1:C=ER:GOSUB ENV_SET AY=R:GOSUB RELEASE: REM release our use, env took ownership REM unset error for catch eval ER=-2:E$="" A=A2:CALL EVAL GOTO EVAL_RETURN EVAL_IF: GOSUB EVAL_GET_A1: REM set A1 GOSUB PUSH_A: REM push/save A A=A1:CALL EVAL GOSUB POP_A: REM pop/restore A IF (R=0) OR (R=2) THEN GOTO EVAL_IF_FALSE EVAL_IF_TRUE: AY=R:GOSUB RELEASE GOSUB EVAL_GET_A2: REM set A1 and A2 after EVAL A=A2:GOTO EVAL_TCO_RECUR: REM TCO loop EVAL_IF_FALSE: AY=R:GOSUB RELEASE REM if no false case (A3), return nil GOSUB COUNT IF R<4 THEN R=0:GOSUB INC_REF_R:GOTO EVAL_RETURN GOSUB EVAL_GET_A3: REM set A1 - A3 after EVAL A=A3:GOTO EVAL_TCO_RECUR: REM TCO loop EVAL_FN: GOSUB EVAL_GET_A2: REM set A1 and A2 T=10:L=A2:M=A1:N=E:GOSUB ALLOC: REM mal function GOTO EVAL_RETURN EVAL_INVOKE: CALL EVAL_AST REM if error, return f/args for release by caller IF ER<>-2 THEN GOTO EVAL_RETURN REM push f/args for release after call GOSUB PUSH_R AR=Z%(R+1): REM rest F=Z%(R+2) REM if metadata, get the actual object GOSUB TYPE_F IF T=14 THEN F=Z%(F+1):GOSUB TYPE_F ON T-8 GOTO EVAL_DO_FUNCTION,EVAL_DO_MAL_FUNCTION,EVAL_DO_MAL_FUNCTION REM if error, pop and return f/args for release by caller GOSUB POP_R ER=-1:E$="apply of non-function":GOTO EVAL_RETURN EVAL_DO_FUNCTION: REM regular function IF Z%(F+1)<65 THEN GOSUB DO_FUNCTION:GOTO EVAL_DO_FUNCTION_SKIP REM for recur functions (apply, map, swap!), use GOTO IF Z%(F+1)>64 THEN CALL DO_TCO_FUNCTION EVAL_DO_FUNCTION_SKIP: REM pop and release f/args GOSUB POP_Q:AY=Q GOSUB RELEASE GOTO EVAL_RETURN EVAL_DO_MAL_FUNCTION: Q=E:GOSUB PUSH_Q: REM save the current environment for release REM create new environ using env and params stored in function C=Z%(F+3):A=Z%(F+2):B=AR:GOSUB ENV_NEW_BINDS REM release previous env if it is not the top one on the REM stack (X%(X-2)) because our new env refers to it and REM we no longer need to track it (since we are TCO recurring) GOSUB POP_Q:AY=Q GOSUB PEEK_Q_2 IF AY<>Q THEN GOSUB RELEASE REM claim the AST before releasing the list containing it A=Z%(F+1):Z%(A)=Z%(A)+32 REM add AST to pending release queue to free as soon as EVAL REM actually returns (LV+1) LV=LV+1:GOSUB PEND_A_LV:LV=LV-1 REM pop and release f/args GOSUB POP_Q:AY=Q GOSUB RELEASE REM A set above E=R:GOTO EVAL_TCO_RECUR: REM TCO loop EVAL_RETURN: REM AZ=R: B=1: GOSUB PR_STR REM PRINT "EVAL_RETURN R: ["+R$+"] ("+STR$(R)+"), LV:"+STR$(LV)+",ER:"+STR$(ER) REM release environment if not the top one on the stack GOSUB PEEK_Q_1 IF E<>Q THEN AY=E:GOSUB RELEASE LV=LV-1: REM track basic return stack level REM release everything we couldn't release earlier GOSUB RELEASE_PEND REM trigger GC #cbm T=FRE(0) #qbasic T=0 REM pop A and E off the stack GOSUB POP_A GOSUB POP_Q:E=Q END SUB REM PRINT is inlined in REP REM RE(A$) -> R REM Assume D has repl_env REM caller must release result RE: R1=-1 GOSUB READ_STR: REM inlined MAL_READ R1=R IF ER<>-2 THEN GOTO RE_DONE A=R:E=D:CALL EVAL RE_DONE: REM Release memory from MAL_READ AY=R1:GOSUB RELEASE RETURN: REM caller must release result of EVAL REM REP(A$) -> R$ REM Assume D has repl_env SUB REP R2=-1 GOSUB RE R2=R IF ER<>-2 THEN GOTO REP_DONE AZ=R:B=1:GOSUB PR_STR: REM MAL_PRINT REP_DONE: REM Release memory from MAL_READ and EVAL AY=R2:GOSUB RELEASE END SUB REM MAIN program MAIN: GOSUB INIT_MEMORY LV=0 REM create repl_env C=0:GOSUB ENV_NEW:D=R REM core.EXT: defined in Basic E=D:GOSUB INIT_CORE_NS: REM set core functions in repl_env ZT=ZI: REM top of memory after base repl_env REM core.mal: defined using the language itself #cbm A$="(def! *host-language* "+CHR$(34)+"C64 BASIC"+CHR$(34)+")" #qbasic A$="(def! *host-language* "+CHR$(34)+"QBasic"+CHR$(34)+")" GOSUB RE:AY=R:GOSUB RELEASE A$="(def! not (fn* (a) (if a false true)))" GOSUB RE:AY=R:GOSUB RELEASE A$="(def! load-file (fn* (f) (do (eval (read-file f)) nil)))" GOSUB RE:AY=R:GOSUB RELEASE A$="(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs)" A$=A$+" (if (> (count xs) 1) (nth xs 1) (throw "+CHR$(34)+"odd number of" A$=A$+" forms to cond"+CHR$(34)+")) (cons 'cond (rest (rest xs)))))))" GOSUB RE:AY=R:GOSUB RELEASE REM load the args file A$="(load-file "+CHR$(34)+".args.mal"+CHR$(34)+")" GOSUB RE:AY=R:GOSUB RELEASE IF ER>-2 THEN GOSUB PRINT_ERROR:END REM set the argument list A$="(def! *ARGV* (rest -*ARGS*-))" GOSUB RE:AY=R:GOSUB RELEASE REM get the first argument A$="(first -*ARGS*-)" GOSUB RE REM no arguments, start REPL loop IF R<16 THEN GOTO REPL REM if there is an argument, then run it as a program RUN_PROG: REM free up first arg because we get it again AY=R:GOSUB RELEASE REM run a single mal program and exit A$="(load-file (first -*ARGS*-))" GOSUB RE IF ER<>-2 THEN GOSUB PRINT_ERROR GOTO QUIT REPL: REM print the REPL startup header REM save memory by printing this directly #cbm PRINT "Mal [C64 BASIC]" #qbasic PRINT "Mal [QBasic]" REPL_LOOP: A$="user> ":GOSUB READLINE: REM call input parser IF EZ=1 THEN GOTO QUIT IF R$="" THEN GOTO REPL_LOOP A$=R$:CALL REP: REM call REP IF ER<>-2 THEN GOSUB PRINT_ERROR:GOTO REPL_LOOP PRINT R$ GOTO REPL_LOOP QUIT: REM GOSUB PR_MEMORY_SUMMARY_SMALL REM GOSUB PR_MEMORY_MAP REM P1=0:P2=ZI:GOSUB PR_MEMORY REM P1=D:GOSUB PR_OBJECT REM P1=ZK:GOSUB PR_OBJECT #cbm END #qbasic SYSTEM PRINT_ERROR: REM if the error is an object, then print and free it IF ER>=0 THEN AZ=ER:B=0:GOSUB PR_STR:E$=R$:AY=ER:GOSUB RELEASE PRINT "Error: "+E$ ER=-2:E$="" RETURN
{ "pile_set_name": "Github" }
// // ______ ______ ______ // /\ __ \ /\ ___\ /\ ___\ // \ \ __< \ \ __\_ \ \ __\_ // \ \_____\ \ \_____\ \ \_____\ // \/_____/ \/_____/ \/_____/ // // // Copyright (c) 2014-2015, Geek Zoo Studio // http://www.bee-framework.com // // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // #import "Bee_HTTPRequest2.h" #import "Bee_HTTPResponse2.h" #pragma mark - @interface BeeHTTPRequest2() - (BOOL)checkIntegrity:(NSData *)data; @end #pragma mark - @implementation BeeHTTPRequest2 @synthesize version = _version; @synthesize method = _method; @synthesize resource = _resource; @synthesize params = _params; @synthesize files = _files; DEF_HTTP_HEADER( Accept, @"Accept" ) // Accept: text/plain, text/html DEF_HTTP_HEADER( AcceptCharset, @"Accept-Charset" ) // Accept-Charset: iso-8859-5 DEF_HTTP_HEADER( AcceptEncoding, @"Accept-Encoding" ) // Accept-Encoding: compress, gzip DEF_HTTP_HEADER( AcceptLanguage, @"Accept-Language" ) // Accept-Language: en,zh DEF_HTTP_HEADER( AcceptRanges, @"Accept-Ranges" ) // Accept-Ranges: bytes DEF_HTTP_HEADER( Authorization, @"Authorization" ) // Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== DEF_HTTP_HEADER( CacheControl, @"Cache-Control" ) // Cache-Control: no-cache DEF_HTTP_HEADER( Connection, @"Connection" ) // Connection: close DEF_HTTP_HEADER( Cookie, @"Cookie" ) // Cookie: $Version=1; Skin=new; DEF_HTTP_HEADER( ContentLength, @"Content-Length" ) // Content-Length: 348 DEF_HTTP_HEADER( ContentType, @"Content-Type" ) // Content-Type: application/x-www-form-urlencoded DEF_HTTP_HEADER( Date, @"Date" ) // Date: Tue, 15 Nov 2010 08:12:31 GMT DEF_HTTP_HEADER( Expect, @"Expect" ) // Expect: 100-continue DEF_HTTP_HEADER( From, @"From" ) // From: [email protected] DEF_HTTP_HEADER( Host, @"Host" ) // Host: www.zcmhi.com DEF_HTTP_HEADER( IfMatch, @"If-Match" ) // If-Match: “737060cd8c284d8af7ad3082f209582d” DEF_HTTP_HEADER( IfModifiedSince, @"If-Modified-Since" ) // If-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT DEF_HTTP_HEADER( IfNoneMatch, @"If-None-Match" ) // If-None-Match: “737060cd8c284d8af7ad3082f209582d” DEF_HTTP_HEADER( IfRange, @"If-Range" ) // If-Range: “737060cd8c284d8af7ad3082f209582d” DEF_HTTP_HEADER( IfUnmodifiedSince, @"If-Unmodified-Since" ) // If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT DEF_HTTP_HEADER( MaxForwards, @"Max-Forwards" ) // Max-Forwards: 10 DEF_HTTP_HEADER( Pragma, @"Pragma" ) // Pragma: no-cache DEF_HTTP_HEADER( ProxyAuthorization, @"Proxy-Authorization" ) // Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== DEF_HTTP_HEADER( Range, @"Range" ) // Range: bytes=500-999 DEF_HTTP_HEADER( Referer, @"Referer" ) // Referer: http://www.zcmhi.com/archives/71.html DEF_HTTP_HEADER( TE, @"TE" ) // TE: trailers,deflate;q=0.5 DEF_HTTP_HEADER( Upgrade, @"Upgrade" ) // Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11 DEF_HTTP_HEADER( UserAgent, @"User-Agent" ) // User-Agent: Mozilla/5.0 (Linux; X11) DEF_HTTP_HEADER( Via, @"Via" ) // Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1) DEF_HTTP_HEADER( Warning, @"Warning" ) // Warn: 199 Miscellaneous warning + (BeeHTTPRequest2 *)request { return [[[BeeHTTPRequest2 alloc] init] autorelease]; } + (BeeHTTPRequest2 *)request:(NSData *)data { BeeHTTPRequest2 * req = [[[BeeHTTPRequest2 alloc] init] autorelease]; if ( req ) { BOOL succeed = [req checkIntegrity:data]; if ( succeed ) { return req; } } return nil; } - (BeeHTTPResponse2 *)response { BeeHTTPResponse2 * response = [BeeHTTPResponse2 response]; if ( response ) { response.version = self.version; response.eol = self.eol; response.eol2 = self.eol2; response.eolValid = self.eolValid; } return response; } - (void)load { self.params = [NSMutableDictionary dictionary]; self.files = [NSMutableDictionary dictionary]; } - (void)unload { self.params = nil; self.files = nil; } - (NSString *)packHead { NSMutableString * headLine = [NSMutableString string]; if ( BeeHTTPMethod_GET == self.method ) { [headLine appendString:@"GET"]; } else if ( BeeHTTPMethod_HEAD == self.method ) { [headLine appendString:@"HEAD"]; } else if ( BeeHTTPMethod_POST == self.method ) { [headLine appendString:@"POST"]; } else if ( BeeHTTPMethod_PUT == self.method ) { [headLine appendString:@"PUT"]; } else if ( BeeHTTPMethod_DELETE == self.method ) { [headLine appendString:@"DELETE"]; } else { return nil; } [headLine appendString:@" "]; [headLine appendString:self.resource]; [headLine appendString:@" "]; if ( BeeHTTPVersion_11 == self.version ) { [headLine appendString:@"HTTP/1.1"]; } else if ( BeeHTTPVersion_10 == self.version ) { [headLine appendString:@"HTTP/1.0"]; } else if ( BeeHTTPVersion_9 == self.version ) { [headLine appendString:@"HTTP/0.9"]; } else { return nil; } return headLine; } - (NSData *)packBody { return self.bodyData; } - (BOOL)unpackHead:(NSString *)text { if ( nil == text || 0 == text.length ) return NO; NSArray * components = [text componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; if ( nil == components || 3 != components.count ) return NO; NSString * method = [components objectAtIndex:0]; NSString * resource = [components objectAtIndex:1]; NSString * version = [components objectAtIndex:2]; if ( NSOrderedSame == [method compare:@"GET" options:NSCaseInsensitiveSearch] ) { self.method = BeeHTTPMethod_GET; } else if ( NSOrderedSame == [method compare:@"HEAD" options:NSCaseInsensitiveSearch] ) { self.method = BeeHTTPMethod_HEAD; } else if ( NSOrderedSame == [method compare:@"POST" options:NSCaseInsensitiveSearch] ) { self.method = BeeHTTPMethod_POST; } else if ( NSOrderedSame == [method compare:@"PUT" options:NSCaseInsensitiveSearch] ) { self.method = BeeHTTPMethod_PUT; } else if ( NSOrderedSame == [method compare:@"DELETE" options:NSCaseInsensitiveSearch] ) { self.method = BeeHTTPMethod_DELETE; } else { self.method = BeeHTTPMethod_UNKNOWN; } self.resource = resource; if ( NSOrderedSame == [version compare:@"HTTP/1.1" options:NSCaseInsensitiveSearch] ) { self.version = BeeHTTPVersion_11; } else if ( NSOrderedSame == [version compare:@"HTTP/1.0" options:NSCaseInsensitiveSearch] ) { self.version = BeeHTTPVersion_10; } else if ( NSOrderedSame == [version compare:@"HTTP/0.9" options:NSCaseInsensitiveSearch] ) { self.version = BeeHTTPVersion_9; } else { self.version = BeeHTTPVersion_UNKNOWN; } return YES; } - (BOOL)unpackBody:(NSData *)data { return YES; } - (BOOL)checkIntegrity:(NSData *)data { if ( nil == data || 0 == data.length ) return NO; if ( NO == self.headValid ) { BOOL flag = [self unpack:data includeBody:YES]; if ( NO == flag ) { return NO; } } if ( NO == self.headValid ) { return NO; } if ( BeeHTTPMethod_GET == self.method ) { return YES; } else if ( BeeHTTPMethod_HEAD == self.method ) { return YES; } else if ( BeeHTTPMethod_POST == self.method ) { if ( self.ContentLength ) { NSUInteger remainLength = data.length - self.headLength; if ( remainLength >= self.ContentLength.integerValue ) { return YES; } else { return NO; } } else { return YES; } } else if ( BeeHTTPMethod_PUT == self.method ) { return YES; } else if ( BeeHTTPMethod_DELETE == self.method ) { return YES; } return YES; } @end
{ "pile_set_name": "Github" }
# VpcAttributesType {#VpcAttributesType .reference} ECS 实例的专有网络相关属性。 ## 节点名 {#section_ajc_1tp_ydb .section} 接口决定 ## 子节点 {#ResponseParameter .section} |名称|类型|描述| |:-|:-|:-| |VpcId|String|虚拟专有网络 ID| |VSwitchId|String|交换机 ID| |PrivateIpAddress|[IpAddressSetType](cn.zh-CN/API 参考/数据类型/IpAddressSetType.md#)|IpAddressSetType类型| |NatIpAddress|String|云产品 IP,用于云产品之间的网络互通|
{ "pile_set_name": "Github" }
<!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.14"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>VSTS DemoGenerator: VstsRestAPI.Viewmodel.WorkItem.SetEpicSettings.Epiclist Class Reference</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> <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 id="projectlogo"><img alt="Logo" src="logo.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">VSTS DemoGenerator </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.14 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></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="namespace_vsts_rest_a_p_i.html">VstsRestAPI</a></li><li class="navelem"><a class="el" href="namespace_vsts_rest_a_p_i_1_1_viewmodel.html">Viewmodel</a></li><li class="navelem"><a class="el" href="namespace_vsts_rest_a_p_i_1_1_viewmodel_1_1_work_item.html">WorkItem</a></li><li class="navelem"><a class="el" href="class_vsts_rest_a_p_i_1_1_viewmodel_1_1_work_item_1_1_set_epic_settings.html">SetEpicSettings</a></li><li class="navelem"><a class="el" href="class_vsts_rest_a_p_i_1_1_viewmodel_1_1_work_item_1_1_set_epic_settings_1_1_epiclist.html">Epiclist</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#properties">Properties</a> &#124; <a href="class_vsts_rest_a_p_i_1_1_viewmodel_1_1_work_item_1_1_set_epic_settings_1_1_epiclist-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">VstsRestAPI.Viewmodel.WorkItem.SetEpicSettings.Epiclist Class Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="properties"></a> Properties</h2></td></tr> <tr class="memitem:a3645bd8639271372fe3c003c98cf46f4"><td class="memItemLeft" align="right" valign="top"><a id="a3645bd8639271372fe3c003c98cf46f4"></a> <a class="el" href="class_vsts_rest_a_p_i_1_1_viewmodel_1_1_work_item_1_1_set_epic_settings_1_1_backlog_visibilities.html">BacklogVisibilities</a>&#160;</td><td class="memItemRight" valign="bottom"><b>backlogVisibilities</b><code> [get, set]</code></td></tr> <tr class="separator:a3645bd8639271372fe3c003c98cf46f4"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <hr/>The documentation for this class was generated from the following file:<ul> <li>D:/Canarys/Projects/DemoGeneratorOauth/VstsRestAPI/Viewmodel/WorkItem/SetEpicSettings.cs</li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.14 </small></address> </body> </html>
{ "pile_set_name": "Github" }
/* * Copyright 2015 Midokura SARL * * 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.midonet.midolman.topology import java.util.UUID import scala.concurrent.Future import scala.concurrent.duration._ import org.junit.runner.RunWith import org.scalatest.concurrent.Eventually._ import org.scalatest.junit.JUnitRunner import org.scalatest.time.{Seconds, Span} import org.midonet.cluster.data.storage._ import org.midonet.cluster.models.Topology.{L2Insertion, Network, Port} import org.midonet.cluster.services.MidonetBackend import org.midonet.cluster.services.MidonetBackend._ import org.midonet.cluster.services.c3po.translators.L2InsertionTranslation._ import org.midonet.cluster.topology.TopologyBuilder import org.midonet.cluster.util.UUIDUtil._ import org.midonet.midolman.rules.L2TransformRule import org.midonet.midolman.simulation.{Chain => SimChain, Port => SimPort} import org.midonet.midolman.util.MidolmanSpec import org.midonet.packets.Ethernet import org.midonet.util.concurrent.FutureOps import org.midonet.util.reactivex._ @RunWith(classOf[JUnitRunner]) class L2InsertionSimulationTest extends MidolmanSpec with TopologyBuilder { private var vt: VirtualTopology = _ private var store: Storage = _ private var stateStore: StateStorage = _ protected override def beforeTest(): Unit = { vt = injector.getInstance(classOf[VirtualTopology]) store = injector.getInstance(classOf[MidonetBackend]).store stateStore = injector.getInstance(classOf[MidonetBackend]).stateStore } implicit def toFutureOps[U](future: Future[U]): FutureOps[U] = { new FutureOps(future) } def packet(srcMac: String, dstMac: String, vlan: Option[Short] = None) = { import org.midonet.packets.util.PacketBuilder._ vlan match { case None => { eth addr srcMac -> dstMac } << { ip4 addr "10.0.0.10" --> "10.0.0.11" } << { udp ports 53 ---> 54 } << payload(UUID.randomUUID().toString) case Some(v) => { eth addr srcMac -> dstMac vlan v } << { ip4 addr "10.0.0.10" --> "10.0.0.11" } << { udp ports 53 ---> 54 } << payload(UUID.randomUUID().toString) } } def checkPacket(when: String, `then`: String, frame: Ethernet, srcPortId: UUID, dstPortId: UUID, expectedVlan: Option[Short] = None) = { When(when) val packetContext = packetContextFor(frame, srcPortId) val result = simulate(packetContext) Then(`then`) result should be(toPort(dstPortId)()) expectedVlan match { case None => result._2.wcmatch.getVlanIds.size() should be(0) case Some(vlan) => result._2.wcmatch.getVlanIds.get(0) should be(vlan) } } def checkInsertionPath(srcPortId: UUID, dstPortId: UUID, srcMac: String, dstMac: String, srcInsertions: Seq[L2Insertion], dstInsertions: Seq[L2Insertion]) = { var prevPortId: UUID = srcPortId var prevVlan: Option[Short] = None var nextVlan: Option[Short] = None var i: Int = 0 def checkInsertions(insertions: Seq[L2Insertion], inbound: Boolean) = { insertions.foreach( x => { inbound match { case true => x.getMac should be(srcMac) x.getPortId should be(srcPortId.asProto) case false => x.getMac should be(dstMac) x.getPortId should be(dstPortId.asProto) } nextVlan = x.getVlan match { case 0 => None case v => inbound match { case true => Some((v | 1 << 13).toShort) case false => Some((v | 2 << 13).toShort) } } checkPacket("The packet ingresses the previous port", "It's redirected out srv port-" + i, packet(srcMac, dstMac, prevVlan), prevPortId, x.getSrvPortId, nextVlan) i = i+1 prevVlan = nextVlan prevPortId = x.getSrvPortId }) } checkInsertions(srcInsertions, inbound = true) checkInsertions(dstInsertions, inbound = false) checkPacket("The packet ingresses the last srv port", "It finally makes its way out the destination port", packet(srcMac, dstMac, prevVlan), prevPortId, dstPortId) } def checkRoundTrip(srcPortId: UUID, dstPortId: UUID, srcMac: String, dstMac: String, srcInsertions: Seq[L2Insertion], dstInsertions: Seq[L2Insertion] = Seq.empty[L2Insertion] ) = { // First we check the forward path log.info("Checking forward path") checkInsertionPath(srcPortId, dstPortId, srcMac, dstMac, srcInsertions, dstInsertions) // Then we check the return path log.info("Checking return path") checkInsertionPath(dstPortId, srcPortId, dstMac, srcMac, dstInsertions, srcInsertions) } def commitTx(f: (Transaction) => Unit): Unit = { val tx = store.transaction() f(tx) tx.commit() } feature("Test redirect without vlans") { scenario("Test") { val mac1 = "02:00:00:00:ee:00" val mac2 = "02:00:00:00:ee:11" val mac3 = "02:00:00:00:ee:22" val mac4 = "02:00:00:00:ee:33" val vmBridge1 = createBridge(name = Some("vmBridge1"), adminStateUp = true) store.create(vmBridge1) val vmBridge2 = createBridge(name = Some("vmBridge2"), adminStateUp = true) store.create(vmBridge2) val srvBridge = createBridge(name = Some("srvBridge"), adminStateUp = true) store.create(srvBridge) def bridgePort(id: UUID, interface: String, bridge: Network) = { val port = createBridgePort( id=id, hostId = Some(hostId), interfaceName = Some(interface), adminStateUp = true, bridgeId = Some(bridge.getId)) store.create(port) port } // Two VMs on bridge1 val vm1Port = bridgePort(new UUID(0, 1), "vm1_if", vmBridge1) val vm2Port = bridgePort(new UUID(0, 2), "vm2_if", vmBridge1) // Two VMs on bridge2 val vm3Port = bridgePort(new UUID(0, 3), "vm3_if", vmBridge2) val vm4Port = bridgePort(new UUID(0, 4), "vm4_if", vmBridge2) // Two services on the service bridge val srv1Port = bridgePort(new UUID(1, 1), "srv1_if", srvBridge) val srv2Port = bridgePort(new UUID(1, 2), "srv2_if", srvBridge) // Load the cache to avoid NotYetException at simulation time fetchPorts(vm1Port.getId, vm2Port.getId, vm3Port.getId, vm4Port.getId, srv1Port.getId, srv2Port.getId) fetchBridges(vmBridge1.getId, vmBridge2.getId, srvBridge.getId) // Set all the ports to "Active" val hostIdString = fromProto(hostId).toString for (port <- List(vm1Port, vm2Port, vm3Port, vm4Port, srv1Port, srv2Port)) { stateStore.addValue(classOf[Port], port.getId, ActiveKey, hostIdString).await(3 seconds) } // Before adding insertions, send forward and return packets to // seed the MAC tables. This avoids bridge flood actions and // allows 'checkPacket' to always check for a single output port. simulate(packetContextFor(packet(mac1, mac2), vm1Port.getId)) simulate(packetContextFor(packet(mac2, mac1), vm2Port.getId)) simulate(packetContextFor(packet(mac3, mac4), vm3Port.getId)) simulate(packetContextFor(packet(mac4, mac3), vm4Port.getId)) // Now add an insertion vm1 -> srv1 var vm1ins1 = L2Insertion.newBuilder .setId(UUID.randomUUID().asProto) .setMac(mac1) .setPortId(vm1Port.getId) .setSrvPortId(srv1Port.getId) .setPosition(1) .setVlan(10) .build commitTx(translateInsertionCreate(_, vm1ins1)) fetchPorts(srv1Port.getId) // Now check the insertion on vm1 checkRoundTrip(vm1Port.getId, vm2Port.getId, mac1, mac2, Seq(vm1ins1)) // Now add another insertion vm1 -> srv2 val vm1ins2 = L2Insertion.newBuilder .setId(UUID.randomUUID().asProto) .setMac(mac1) .setPortId(vm1Port.getId) .setSrvPortId(srv2Port.getId) .setPosition(2) .setVlan(20) .build commitTx(translateInsertionCreate(_, vm1ins2)) fetchPorts(srv2Port.getId) // Now check the two insertions on vm1 checkRoundTrip(vm1Port.getId, vm2Port.getId, mac1, mac2, Seq(vm1ins1, vm1ins2)) // Now add an insertion on vm2 (same bridge as vm1) val vm2ins1 = L2Insertion.newBuilder .setId(UUID.randomUUID().asProto) .setMac(mac2) .setPortId(vm2Port.getId) .setSrvPortId(srv1Port.getId) .setPosition(1) .setVlan(10) .build commitTx(translateInsertionCreate(_, vm2ins1)) // Now check the concurrent insertions on vm1 and vm2 (same bridge) checkRoundTrip(vm1Port.getId, vm2Port.getId, mac1, mac2, Seq(vm1ins1, vm1ins2), Seq(vm2ins1)) // Now delete the insertion on vm2 commitTx(translateInsertionDelete(_, vm2ins1.getId)) // Now modify the insertion vm1->srv1 to use vlan 30. vm1ins1 = vm1ins1.toBuilder.setVlan(30).build commitTx(translateInsertionUpdate(_, vm1ins1)) eventually (timeout(Span(2, Seconds))) { val port = VirtualTopology.tryGet(classOf[SimPort], vm1ins1.getPortId) val chain = VirtualTopology .tryGet(classOf[SimChain], port.inboundFilters.get(0)) chain.rules.get(3) match { case r: L2TransformRule => r.pushVlan should be(30 | 1 << 13) case _ => fail("wrong rule type") } } // Now check the two insertions on vm1 checkRoundTrip(vm1Port.getId, vm2Port.getId, mac1, mac2, Seq(vm1ins1, vm1ins2)) // Now modify the insertion vm1->srv1 to NOT use vlan tags. vm1ins1 = vm1ins1.toBuilder.setVlan(0).build commitTx(translateInsertionUpdate(_, vm1ins1)) eventually (timeout(Span(2, Seconds))) { val port = VirtualTopology.tryGet(classOf[SimPort], vm1ins1.getPortId) val chain = VirtualTopology .tryGet(classOf[SimChain], port.inboundFilters.get(0)) chain.rules.get(3) match { case r: L2TransformRule => r.pushVlan shouldBe 0 case _ => fail("wrong rule type") } } // Now check the two insertions on vm1 checkRoundTrip(vm1Port.getId, vm2Port.getId, mac1, mac2, Seq(vm1ins1, vm1ins2)) // Now add an insertion vm3 -> srv1, using fail_open=true val vm3ins1 = L2Insertion.newBuilder .setId(UUID.randomUUID().asProto) .setMac(mac3) .setPortId(vm3Port.getId) .setSrvPortId(srv1Port.getId) .setPosition(1) .setVlan(10) .setFailOpen(true) .build commitTx(translateInsertionCreate(_, vm3ins1)) // Now check the insertion on vm3 checkRoundTrip(vm3Port.getId, vm4Port.getId, mac3, mac4, Seq(vm3ins1)) // Now set srv1Port to down. Verify traffic still flows thanks to // fail_open=true. stateStore.removeValue(classOf[Port], srv1Port.getId, ActiveKey, hostIdString).await(3 seconds) checkRoundTrip(vm3Port.getId, vm4Port.getId, mac3, mac4, Seq.empty[L2Insertion]) // Now delete the insertion vm1 -> srv1 (keep vm1 -> srv2) commitTx(translateInsertionDelete(_, vm1ins1.getId)) // Now check the remaining insertion on vm1 checkRoundTrip(vm1Port.getId, vm2Port.getId, mac1, mac2, Seq(vm1ins2)) // Finally, delete the 2 remaining insertions. commitTx(translateInsertionDelete(_, vm1ins2.getId)) commitTx(translateInsertionDelete(_, vm3ins1.getId)) } } }
{ "pile_set_name": "Github" }
/*! * Bootstrap Responsive v2.1.1 * * Copyright 2012 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world @twitter by @mdo and @fat. */ .clearfix { *zoom: 1; } .clearfix:before, .clearfix:after { display: table; line-height: 0; content: ""; } .clearfix:after { clear: both; } .hide-text { font: 0/0 a; color: transparent; text-shadow: none; background-color: transparent; border: 0; } .input-block-level { display: block; width: 100%; min-height: 30px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .hidden { display: none; visibility: hidden; } .visible-phone { display: none !important; } .visible-tablet { display: none !important; } .hidden-desktop { display: none !important; } .visible-desktop { display: inherit !important; } @media (min-width: 768px) and (max-width: 979px) { .hidden-desktop { display: inherit !important; } .visible-desktop { display: none !important ; } .visible-tablet { display: inherit !important; } .hidden-tablet { display: none !important; } } @media (max-width: 767px) { .hidden-desktop { display: inherit !important; } .visible-desktop { display: none !important; } .visible-phone { display: inherit !important; } .hidden-phone { display: none !important; } } @media (min-width: 1200px) { .row { margin-left: -30px; *zoom: 1; } .row:before, .row:after { display: table; line-height: 0; content: ""; } .row:after { clear: both; } [class*="span"] { float: left; min-height: 1px; margin-left: 30px; } .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { width: 1170px; } .span12 { width: 1170px; } .span11 { width: 1070px; } .span10 { width: 970px; } .span9 { width: 870px; } .span8 { width: 770px; } .span7 { width: 670px; } .span6 { width: 570px; } .span5 { width: 470px; } .span4 { width: 370px; } .span3 { width: 270px; } .span2 { width: 170px; } .span1 { width: 70px; } .offset12 { margin-left: 1230px; } .offset11 { margin-left: 1130px; } .offset10 { margin-left: 1030px; } .offset9 { margin-left: 930px; } .offset8 { margin-left: 830px; } .offset7 { margin-left: 730px; } .offset6 { margin-left: 630px; } .offset5 { margin-left: 530px; } .offset4 { margin-left: 430px; } .offset3 { margin-left: 330px; } .offset2 { margin-left: 230px; } .offset1 { margin-left: 130px; } .row-fluid { width: 100%; *zoom: 1; } .row-fluid:before, .row-fluid:after { display: table; line-height: 0; content: ""; } .row-fluid:after { clear: both; } .row-fluid [class*="span"] { display: block; float: left; width: 100%; min-height: 30px; margin-left: 2.564102564102564%; *margin-left: 2.5109110747408616%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .row-fluid [class*="span"]:first-child { margin-left: 0; } .row-fluid .span12 { width: 100%; *width: 99.94680851063829%; } .row-fluid .span11 { width: 91.45299145299145%; *width: 91.39979996362975%; } .row-fluid .span10 { width: 82.90598290598291%; *width: 82.8527914166212%; } .row-fluid .span9 { width: 74.35897435897436%; *width: 74.30578286961266%; } .row-fluid .span8 { width: 65.81196581196582%; *width: 65.75877432260411%; } .row-fluid .span7 { width: 57.26495726495726%; *width: 57.21176577559556%; } .row-fluid .span6 { width: 48.717948717948715%; *width: 48.664757228587014%; } .row-fluid .span5 { width: 40.17094017094017%; *width: 40.11774868157847%; } .row-fluid .span4 { width: 31.623931623931625%; *width: 31.570740134569924%; } .row-fluid .span3 { width: 23.076923076923077%; *width: 23.023731587561375%; } .row-fluid .span2 { width: 14.52991452991453%; *width: 14.476723040552828%; } .row-fluid .span1 { width: 5.982905982905983%; *width: 5.929714493544281%; } .row-fluid .offset12 { margin-left: 105.12820512820512%; *margin-left: 105.02182214948171%; } .row-fluid .offset12:first-child { margin-left: 102.56410256410257%; *margin-left: 102.45771958537915%; } .row-fluid .offset11 { margin-left: 96.58119658119658%; *margin-left: 96.47481360247316%; } .row-fluid .offset11:first-child { margin-left: 94.01709401709402%; *margin-left: 93.91071103837061%; } .row-fluid .offset10 { margin-left: 88.03418803418803%; *margin-left: 87.92780505546462%; } .row-fluid .offset10:first-child { margin-left: 85.47008547008548%; *margin-left: 85.36370249136206%; } .row-fluid .offset9 { margin-left: 79.48717948717949%; *margin-left: 79.38079650845607%; } .row-fluid .offset9:first-child { margin-left: 76.92307692307693%; *margin-left: 76.81669394435352%; } .row-fluid .offset8 { margin-left: 70.94017094017094%; *margin-left: 70.83378796144753%; } .row-fluid .offset8:first-child { margin-left: 68.37606837606839%; *margin-left: 68.26968539734497%; } .row-fluid .offset7 { margin-left: 62.393162393162385%; *margin-left: 62.28677941443899%; } .row-fluid .offset7:first-child { margin-left: 59.82905982905982%; *margin-left: 59.72267685033642%; } .row-fluid .offset6 { margin-left: 53.84615384615384%; *margin-left: 53.739770867430444%; } .row-fluid .offset6:first-child { margin-left: 51.28205128205128%; *margin-left: 51.175668303327875%; } .row-fluid .offset5 { margin-left: 45.299145299145295%; *margin-left: 45.1927623204219%; } .row-fluid .offset5:first-child { margin-left: 42.73504273504273%; *margin-left: 42.62865975631933%; } .row-fluid .offset4 { margin-left: 36.75213675213675%; *margin-left: 36.645753773413354%; } .row-fluid .offset4:first-child { margin-left: 34.18803418803419%; *margin-left: 34.081651209310785%; } .row-fluid .offset3 { margin-left: 28.205128205128204%; *margin-left: 28.0987452264048%; } .row-fluid .offset3:first-child { margin-left: 25.641025641025642%; *margin-left: 25.53464266230224%; } .row-fluid .offset2 { margin-left: 19.65811965811966%; *margin-left: 19.551736679396257%; } .row-fluid .offset2:first-child { margin-left: 17.094017094017094%; *margin-left: 16.98763411529369%; } .row-fluid .offset1 { margin-left: 11.11111111111111%; *margin-left: 11.004728132387708%; } .row-fluid .offset1:first-child { margin-left: 8.547008547008547%; *margin-left: 8.440625568285142%; } input, textarea, .uneditable-input { margin-left: 0; } .controls-row [class*="span"] + [class*="span"] { margin-left: 30px; } input.span12, textarea.span12, .uneditable-input.span12 { width: 1156px; } input.span11, textarea.span11, .uneditable-input.span11 { width: 1056px; } input.span10, textarea.span10, .uneditable-input.span10 { width: 956px; } input.span9, textarea.span9, .uneditable-input.span9 { width: 856px; } input.span8, textarea.span8, .uneditable-input.span8 { width: 756px; } input.span7, textarea.span7, .uneditable-input.span7 { width: 656px; } input.span6, textarea.span6, .uneditable-input.span6 { width: 556px; } input.span5, textarea.span5, .uneditable-input.span5 { width: 456px; } input.span4, textarea.span4, .uneditable-input.span4 { width: 356px; } input.span3, textarea.span3, .uneditable-input.span3 { width: 256px; } input.span2, textarea.span2, .uneditable-input.span2 { width: 156px; } input.span1, textarea.span1, .uneditable-input.span1 { width: 56px; } .thumbnails { margin-left: -30px; } .thumbnails > li { margin-left: 30px; } .row-fluid .thumbnails { margin-left: 0; } } @media (min-width: 768px) and (max-width: 979px) { .row { margin-left: -20px; *zoom: 1; } .row:before, .row:after { display: table; line-height: 0; content: ""; } .row:after { clear: both; } [class*="span"] { float: left; min-height: 1px; margin-left: 20px; } .container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container { width: 724px; } .span12 { width: 724px; } .span11 { width: 662px; } .span10 { width: 600px; } .span9 { width: 538px; } .span8 { width: 476px; } .span7 { width: 414px; } .span6 { width: 352px; } .span5 { width: 290px; } .span4 { width: 228px; } .span3 { width: 166px; } .span2 { width: 104px; } .span1 { width: 42px; } .offset12 { margin-left: 764px; } .offset11 { margin-left: 702px; } .offset10 { margin-left: 640px; } .offset9 { margin-left: 578px; } .offset8 { margin-left: 516px; } .offset7 { margin-left: 454px; } .offset6 { margin-left: 392px; } .offset5 { margin-left: 330px; } .offset4 { margin-left: 268px; } .offset3 { margin-left: 206px; } .offset2 { margin-left: 144px; } .offset1 { margin-left: 82px; } .row-fluid { width: 100%; *zoom: 1; } .row-fluid:before, .row-fluid:after { display: table; line-height: 0; content: ""; } .row-fluid:after { clear: both; } .row-fluid [class*="span"] { display: block; float: left; width: 100%; min-height: 30px; margin-left: 2.7624309392265194%; *margin-left: 2.709239449864817%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .row-fluid [class*="span"]:first-child { margin-left: 0; } .row-fluid .span12 { width: 100%; *width: 99.94680851063829%; } .row-fluid .span11 { width: 91.43646408839778%; *width: 91.38327259903608%; } .row-fluid .span10 { width: 82.87292817679558%; *width: 82.81973668743387%; } .row-fluid .span9 { width: 74.30939226519337%; *width: 74.25620077583166%; } .row-fluid .span8 { width: 65.74585635359117%; *width: 65.69266486422946%; } .row-fluid .span7 { width: 57.18232044198895%; *width: 57.12912895262725%; } .row-fluid .span6 { width: 48.61878453038674%; *width: 48.56559304102504%; } .row-fluid .span5 { width: 40.05524861878453%; *width: 40.00205712942283%; } .row-fluid .span4 { width: 31.491712707182323%; *width: 31.43852121782062%; } .row-fluid .span3 { width: 22.92817679558011%; *width: 22.87498530621841%; } .row-fluid .span2 { width: 14.3646408839779%; *width: 14.311449394616199%; } .row-fluid .span1 { width: 5.801104972375691%; *width: 5.747913483013988%; } .row-fluid .offset12 { margin-left: 105.52486187845304%; *margin-left: 105.41847889972962%; } .row-fluid .offset12:first-child { margin-left: 102.76243093922652%; *margin-left: 102.6560479605031%; } .row-fluid .offset11 { margin-left: 96.96132596685082%; *margin-left: 96.8549429881274%; } .row-fluid .offset11:first-child { margin-left: 94.1988950276243%; *margin-left: 94.09251204890089%; } .row-fluid .offset10 { margin-left: 88.39779005524862%; *margin-left: 88.2914070765252%; } .row-fluid .offset10:first-child { margin-left: 85.6353591160221%; *margin-left: 85.52897613729868%; } .row-fluid .offset9 { margin-left: 79.8342541436464%; *margin-left: 79.72787116492299%; } .row-fluid .offset9:first-child { margin-left: 77.07182320441989%; *margin-left: 76.96544022569647%; } .row-fluid .offset8 { margin-left: 71.2707182320442%; *margin-left: 71.16433525332079%; } .row-fluid .offset8:first-child { margin-left: 68.50828729281768%; *margin-left: 68.40190431409427%; } .row-fluid .offset7 { margin-left: 62.70718232044199%; *margin-left: 62.600799341718584%; } .row-fluid .offset7:first-child { margin-left: 59.94475138121547%; *margin-left: 59.838368402492065%; } .row-fluid .offset6 { margin-left: 54.14364640883978%; *margin-left: 54.037263430116376%; } .row-fluid .offset6:first-child { margin-left: 51.38121546961326%; *margin-left: 51.27483249088986%; } .row-fluid .offset5 { margin-left: 45.58011049723757%; *margin-left: 45.47372751851417%; } .row-fluid .offset5:first-child { margin-left: 42.81767955801105%; *margin-left: 42.71129657928765%; } .row-fluid .offset4 { margin-left: 37.01657458563536%; *margin-left: 36.91019160691196%; } .row-fluid .offset4:first-child { margin-left: 34.25414364640884%; *margin-left: 34.14776066768544%; } .row-fluid .offset3 { margin-left: 28.45303867403315%; *margin-left: 28.346655695309746%; } .row-fluid .offset3:first-child { margin-left: 25.69060773480663%; *margin-left: 25.584224756083227%; } .row-fluid .offset2 { margin-left: 19.88950276243094%; *margin-left: 19.783119783707537%; } .row-fluid .offset2:first-child { margin-left: 17.12707182320442%; *margin-left: 17.02068884448102%; } .row-fluid .offset1 { margin-left: 11.32596685082873%; *margin-left: 11.219583872105325%; } .row-fluid .offset1:first-child { margin-left: 8.56353591160221%; *margin-left: 8.457152932878806%; } input, textarea, .uneditable-input { margin-left: 0; } .controls-row [class*="span"] + [class*="span"] { margin-left: 20px; } input.span12, textarea.span12, .uneditable-input.span12 { width: 710px; } input.span11, textarea.span11, .uneditable-input.span11 { width: 648px; } input.span10, textarea.span10, .uneditable-input.span10 { width: 586px; } input.span9, textarea.span9, .uneditable-input.span9 { width: 524px; } input.span8, textarea.span8, .uneditable-input.span8 { width: 462px; } input.span7, textarea.span7, .uneditable-input.span7 { width: 400px; } input.span6, textarea.span6, .uneditable-input.span6 { width: 338px; } input.span5, textarea.span5, .uneditable-input.span5 { width: 276px; } input.span4, textarea.span4, .uneditable-input.span4 { width: 214px; } input.span3, textarea.span3, .uneditable-input.span3 { width: 152px; } input.span2, textarea.span2, .uneditable-input.span2 { width: 90px; } input.span1, textarea.span1, .uneditable-input.span1 { width: 28px; } } @media (max-width: 767px) { body { padding-right: 20px; padding-left: 20px; } .navbar-fixed-top, .navbar-fixed-bottom, .navbar-static-top { margin-right: -20px; margin-left: -20px; } .container-fluid { padding: 0; } .dl-horizontal dt { float: none; width: auto; clear: none; text-align: left; } .dl-horizontal dd { margin-left: 0; } .container { width: auto; } .row-fluid { width: 100%; } .row, .thumbnails { margin-left: 0; } .thumbnails > li { float: none; margin-left: 0; } [class*="span"], .row-fluid [class*="span"] { display: block; float: none; width: 100%; margin-left: 0; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .span12, .row-fluid .span12 { width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .input-large, .input-xlarge, .input-xxlarge, input[class*="span"], select[class*="span"], textarea[class*="span"], .uneditable-input { display: block; width: 100%; min-height: 30px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .input-prepend input, .input-append input, .input-prepend input[class*="span"], .input-append input[class*="span"] { display: inline-block; width: auto; } .controls-row [class*="span"] + [class*="span"] { margin-left: 0; } .modal { position: fixed; top: 20px; right: 20px; left: 20px; width: auto; margin: 0; } .modal.fade.in { top: auto; } } @media (max-width: 480px) { .nav-collapse { -webkit-transform: translate3d(0, 0, 0); } .page-header h1 small { display: block; line-height: 20px; } input[type="checkbox"], input[type="radio"] { border: 1px solid #ccc; } .form-horizontal .control-label { float: none; width: auto; padding-top: 0; text-align: left; } .form-horizontal .controls { margin-left: 0; } .form-horizontal .control-list { padding-top: 0; } .form-horizontal .form-actions { padding-right: 10px; padding-left: 10px; } .modal { top: 10px; right: 10px; left: 10px; } .modal-header .close { padding: 10px; margin: -10px; } .carousel-caption { position: static; } } @media (max-width: 979px) { body { padding-top: 0; } .navbar-fixed-top, .navbar-fixed-bottom { position: static; } .navbar-fixed-top { margin-bottom: 20px; } .navbar-fixed-bottom { margin-top: 20px; } .navbar-fixed-top .navbar-inner, .navbar-fixed-bottom .navbar-inner { padding: 5px; } .navbar .container { width: auto; padding: 0; } .navbar .brand { padding-right: 10px; padding-left: 10px; margin: 0 0 0 -5px; } .nav-collapse { clear: both; } .nav-collapse .nav { float: none; margin: 0 0 10px; } .nav-collapse .nav > li { float: none; } .nav-collapse .nav > li > a { margin-bottom: 2px; } .nav-collapse .nav > .divider-vertical { display: none; } .nav-collapse .nav .nav-header { color: #777777; text-shadow: none; } .nav-collapse .nav > li > a, .nav-collapse .dropdown-menu a { padding: 9px 15px; font-weight: bold; color: #777777; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; } .nav-collapse .btn { padding: 4px 10px 4px; font-weight: normal; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; } .nav-collapse .dropdown-menu li + li a { margin-bottom: 2px; } .nav-collapse .nav > li > a:hover, .nav-collapse .dropdown-menu a:hover { background-color: #f2f2f2; } .navbar-inverse .nav-collapse .nav > li > a:hover, .navbar-inverse .nav-collapse .dropdown-menu a:hover { background-color: #111111; } .nav-collapse.in .btn-group { padding: 0; margin-top: 5px; } .nav-collapse .dropdown-menu { position: static; top: auto; left: auto; display: block; float: none; max-width: none; padding: 0; margin: 0 15px; background-color: transparent; border: none; -webkit-border-radius: 0; -moz-border-radius: 0; border-radius: 0; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } .nav-collapse .dropdown-menu:before, .nav-collapse .dropdown-menu:after { display: none; } .nav-collapse .dropdown-menu .divider { display: none; } .nav-collapse .nav > li > .dropdown-menu:before, .nav-collapse .nav > li > .dropdown-menu:after { display: none; } .nav-collapse .navbar-form, .nav-collapse .navbar-search { float: none; padding: 10px 15px; margin: 10px 0; border-top: 1px solid #f2f2f2; border-bottom: 1px solid #f2f2f2; -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1); } .navbar-inverse .nav-collapse .navbar-form, .navbar-inverse .nav-collapse .navbar-search { border-top-color: #111111; border-bottom-color: #111111; } .navbar .nav-collapse .nav.pull-right { float: none; margin-left: 0; } .nav-collapse, .nav-collapse.collapse { height: 0; overflow: hidden; } .navbar .btn-navbar { display: block; } .navbar-static .navbar-inner { padding-right: 10px; padding-left: 10px; } } @media (min-width: 980px) { .nav-collapse.collapse { height: auto !important; overflow: visible !important; } }
{ "pile_set_name": "Github" }
<meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../../assets/img/favicon-144.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../../assets/img/favicon-144.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../../assets/img/favicon-72.png"> <link rel="apple-touch-icon-precomposed" href="../../assets/img/favicon-32.png"> <link rel="shortcut icon" href="../../assets/img/favicon-32.png"> <link rel="stylesheet" href="../../assets/css/vk.css"/> <link rel="stylesheet" href="../../assets/css/prism.css"/> <vk-title>VkPhysicalDeviceShaderDrawParametersFeatures | NVK</vk-title> <vk-centered> <vk-navigation> <vk-search-title>Search</vk-search-title> <vk-search> <input type="text" id="search" autocomplete="off" /> <vk-search-results> <ol id="search-list"> <li id="no-search-results">No Results</li> </ol> </vk-search-results> </vk-search> <vk-section-title style="margin-top: 1em;">Categories</vk-section-title> <vk-categories></vk-categories> </vk-navigation> <vk-struct> <vk-name>VkPhysicalDeviceShaderDrawParametersFeatures</vk-name> <vk-description>Structure describing shader draw parameter features that can be supported by an implementation</vk-description> <vk-section-title>Syntax</vk-section-title> <vk-syntax> <pre><code class="language-js">physicalDeviceShaderDrawParametersFeatures = VkPhysicalDeviceShaderDrawParametersFeatures(); physicalDeviceShaderDrawParametersFeatures = new VkPhysicalDeviceShaderDrawParametersFeatures(); physicalDeviceShaderDrawParametersFeatures = new VkPhysicalDeviceShaderDrawParametersFeatures(object);</code></pre> </vk-syntax> <vk-section-title>Stub</vk-section-title> <vk-property-prototype id="expand-code" class="expand-btn"></vk-property-prototype> <vk-stub id="code-no-expand" style="display:none;"> <pre><code class="language-js">let physicalDeviceShaderDrawParametersFeatures = new VkPhysicalDeviceShaderDrawParametersFeatures(); physicalDeviceShaderDrawParametersFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES; physicalDeviceShaderDrawParametersFeatures.pNext = ; physicalDeviceShaderDrawParametersFeatures.shaderDrawParameters = ; </code></pre> </vk-stub> <vk-stub id="code-expanded" style="display:none;"> <pre><code class="language-js">let physicalDeviceShaderDrawParametersFeatures = new VkPhysicalDeviceShaderDrawParametersFeatures(); physicalDeviceShaderDrawParametersFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES; physicalDeviceShaderDrawParametersFeatures.pNext = ; physicalDeviceShaderDrawParametersFeatures.shaderDrawParameters = ; </code></pre> </vk-stub><vk-section-title>Parameters</vk-section-title> <vk-properties> <vk-property-entry> <vk-property-prototype class="no-float">object</vk-property-prototype> <vk-property-description>When instantiated with an object, members can be filled directly.</vk-property-description> </vk-property-entry> </vk-properties><vk-section-title>Properties</vk-section-title> <vk-properties> <vk-property-entry> <vk-property-prototype>VkPhysicalDeviceShaderDrawParametersFeatures.prototype.<vk-prototype-name>sType</vk-prototype-name></vk-property-prototype> <vk-property-type type="number"><a href="../enums/VkStructureType.html">VkStructureType</a></vk-property-type> <vk-property-description></vk-property-description> </vk-property-entry> <vk-property-entry> <vk-property-prototype>VkPhysicalDeviceShaderDrawParametersFeatures.prototype.<vk-prototype-name>pNext</vk-prototype-name></vk-property-prototype> <vk-property-type type="null">null</vk-property-type> <vk-property-description></vk-property-description> </vk-property-entry> <vk-property-entry> <vk-property-prototype>VkPhysicalDeviceShaderDrawParametersFeatures.prototype.<vk-prototype-name>shaderDrawParameters</vk-prototype-name></vk-property-prototype> <vk-property-type type="boolean">Boolean</vk-property-type> <vk-property-description></vk-property-description> </vk-property-entry> </vk-properties> <vk-section-title>Default Properties</vk-section-title> <vk-properties> <vk-property-entry> <vk-property-prototype>VkPhysicalDeviceShaderDrawParametersFeatures.prototype.<vk-prototype-name>memoryBuffer</vk-prototype-name></vk-property-prototype> <vk-property-type type="arraybuffer"><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer">ArrayBuffer</a></vk-property-type> <vk-property-description>Native memory reference of the structure.</vk-property-description> </vk-property-entry> <vk-property-entry> <vk-property-prototype>VkPhysicalDeviceShaderDrawParametersFeatures.<vk-prototype-name>memoryLayout</vk-prototype-name></vk-property-prototype> <vk-property-type type="object">Object</vk-property-type> <vk-property-description>Object describing the structure's memory layout.</vk-property-description> </vk-property-entry> <vk-property-entry> <vk-property-prototype>VkPhysicalDeviceShaderDrawParametersFeatures.<vk-prototype-name>byteLength</vk-prototype-name></vk-property-prototype> <vk-property-type type="number">Number</vk-property-type> <vk-property-description>Total native byte length of the structure.</vk-property-description> </vk-property-entry> </vk-properties> <vk-section-title>Internal Properties</vk-section-title> <vk-description>These properties are mainly used by <i>nvk</i> internally.</vk-description> <vk-properties> <vk-property-entry> <vk-property-prototype>VkPhysicalDeviceShaderDrawParametersFeatures.<vk-prototype-name>reset</vk-prototype-name></vk-property-prototype> <vk-property-description>Resets the native memory of the structure.</vk-property-description> </vk-property-entry> <vk-property-entry> <vk-property-prototype>VkPhysicalDeviceShaderDrawParametersFeatures.<vk-prototype-name>flush</vk-prototype-name></vk-property-prototype> <vk-property-description>Writes the structure's data into the native memory.</vk-property-description> </vk-property-entry> <vk-property-entry> <vk-property-prototype>VkPhysicalDeviceShaderDrawParametersFeatures.<vk-prototype-name>reflect</vk-prototype-name></vk-property-prototype> <vk-property-description>Synchronizes the structure's data with the native memory.</vk-property-description> </vk-property-entry> </vk-properties> </vk-struct> </vk-centered> <script> const IS_ROOT = false; </script> <script type="text/javascript" src="../../assets/js/prism.min.js"></script> <script type="text/javascript" src="../../assets/js/index.js"></script>
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <style xmlns="http://purl.org/net/xbiblio/csl" version="1.0" default-locale="en-US"> <!-- Generated with https://github.com/citation-style-language/utilities/tree/master/generate_dependent_styles/data/springer --> <info> <title>Geometriae Dedicata</title> <title-short>Geom Dedicata</title-short> <id>http://www.zotero.org/styles/geometriae-dedicata</id> <link href="http://www.zotero.org/styles/geometriae-dedicata" rel="self"/> <link href="http://www.zotero.org/styles/springer-mathphys-brackets" rel="independent-parent"/> <link href="http://www.springer.com/cda/content/document/cda_downloaddocument/Key_Style_Points_1.0.pdf" rel="documentation"/> <link href="http://www.springer.com/cda/content/document/cda_downloaddocument/manuscript-guidelines-1.0.pdf" rel="documentation"/> <category citation-format="numeric"/> <category field="science"/> <issn>0046-5755</issn> <eissn>1572-9168</eissn> <updated>2014-05-15T12:00:00+00:00</updated> <rights license="http://creativecommons.org/licenses/by-sa/3.0/">This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License</rights> </info> </style>
{ "pile_set_name": "Github" }
/* * * Copyright (c) 2013,2019 AT&T Knowledge Ventures * SPDX-License-Identifier: MIT */ package com.att.research.xacml.api; /** * Defines the API for objects that represent XACML StatusCode values. * * @author Christopher A. Rath * @version $Revision: 1.1 $ */ public interface StatusCode { /** * Retrieves the major status {@link com.att.research.xacml.api.Identifier} for this <code>StatusCode</code>. * * @return the major status <code>Identifier</code> for this <code>StatusCode</code> */ public Identifier getStatusCodeValue(); /** * Gets a child <code>StatusCode</code> of this <code>StatusCode</code> if there is one. * * @return the child <code>StatusCode</code> of this <code>StatusCode</code> or null if there is none */ public StatusCode getChild(); /** * {@inheritDoc} * * Implementations of the <code>StatusCode</code> interface must override the <code>equals</code> method as follows: * * Two <code>StatusCode</code>s (<code>s1</code> and <code>s2</code>) are equal if: * {@code s1.getIdentifer().equals(s2.getIdentifier()} AND * {@code s1.getChild() == null && s2.getChild() == null} OR {@code s1.getChild().equals(s2.getChild())} */ @Override public boolean equals(Object obj); }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.facebook.react" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="16" android:targetSdkVersion="22" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <application /> </manifest>
{ "pile_set_name": "Github" }
import React, { Component } from 'react'; import HomeHeader from './components/HomeHeader'; import {connect} from 'react-redux'; import actions from '@/store/actions/home'; import HomeSwiper from './components/HomeSwiper'; import HomeLesson from './components/HomeLesson'; import './index.less'; import { loadMore, downRefresh } from '@/utils'; @connect( state => state.home, actions ) export default class Home extends Component { componentDidMount() { console.log(actions); const {getLessons, getSliders, refreshLessons} = this.props; getSliders(); getLessons(); loadMore(this.mainContent, getLessons); downRefresh(this.mainContent, refreshLessons); } render() { const { category, changeCategory, sliders, lessons, refreshLessons } = this.props; return (<React.Fragment> <HomeHeader category={category} changeCategory={changeCategory} refreshLessons={refreshLessons} /> <div className="main-content" ref={ref => this.mainContent = ref}> <HomeSwiper sliders={sliders}/> <HomeLesson lessons={lessons}/> </div> </React.Fragment>) } }
{ "pile_set_name": "Github" }
/* Mr Smith problem in B-Prolog. From an IF Prolog example (http://www.ifcomputer.de/) """ The Smith family and their three children want to pay a visit but they do not all have the time to do so. Following are few hints who will go and who will not: o If Mr Smith comes, his wife will come too. o At least one of their two sons Matt and John will come. o Either Mrs Smith or Tim will come, but not both. o Either Tim and John will come, or neither will come. o If Matt comes, then John and his father will also come. """ The answer should be: Mr_Smith_comes = 0 Mrs_Smith_comes = 0 Matt_comes = 0 John_comes = 1 Tim_comes = 1 Model created by Hakan Kjellerstrand, [email protected] See also my B-Prolog page: http://www.hakank.org/bprolog/ */ go:- findall(L,mr_smith(L),Res), write(Res),nl. mr_smith(L) :- L = [Mr_Smith,Mrs_Smith,Matt, John,Tim], L :: 0..1, % If Mr Smith comes, his wife will come too. Mr_Smith #=> Mrs_Smith, % At least one of their two sons Matt and John will come. Matt #\/ John, % Either Mrs Smith or Tim will come, but not both. % Mrs_Smith + Tim #= 1, Mrs_Smith #\ Tim, % Either Tim and John will come, or neither will come. Tim #= John, % If Matt comes, then John and his father will also come. Matt #=> (John #/\ Mr_Smith), labeling([],L).
{ "pile_set_name": "Github" }
#include <stdio.h> #include <stdlib.h> #include <time.h> #include "item.h" #include "queue.h" #define M 10 int main(int argc, char *argv[]) { int i, j, N = atoi(argv[1]); Q queues[M]; srand(time(NULL)); for (i = 0; i < M; i++) queues[i] = QUEUEinit(N); for (j = 0; j < N; j++) QUEUEput(queues[rand() % M], j); for (i = 0; i < M; i++, printf("\n")) for (j = 0; !QUEUEempty(queues[i]); j++) printf("%3d ", QUEUEget(queues[i])); return 0; }
{ "pile_set_name": "Github" }
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], "MONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "SHORTDAY": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "SHORTMONTH": [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], "fullDate": "EEEE dd MMMM y", "longDate": "dd MMMM y", "medium": "MMM d, y h:mm:ss a", "mediumDate": "MMM d, y", "mediumTime": "h:mm:ss a", "short": "dd/MM/yy h:mm a", "shortDate": "dd/MM/yy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "$", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "macFrac": 0, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "(\u00a4", "negSuf": ")", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "en-bw", "pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
{ "pile_set_name": "Github" }
BDEPEND=python_targets_python3_6? ( dev-lang/python:3.6 ) python_targets_python3_7? ( dev-lang/python:3.7 ) python_targets_python3_8? ( dev-lang/python:3.8 ) >=dev-lang/python-exec-2:=[python_targets_python3_6(-)?,python_targets_python3_7(-)?,python_targets_python3_8(-)?,-python_single_target_python3_6(-),-python_single_target_python3_7(-),-python_single_target_python3_8(-)] >=dev-python/setuptools-42.0.2[python_targets_python3_6(-)?,python_targets_python3_7(-)?,python_targets_python3_8(-)?,-python_single_target_python3_6(-),-python_single_target_python3_7(-),-python_single_target_python3_8(-)] DEFINED_PHASES=compile configure install prepare test DEPEND=python? ( python_targets_python3_6? ( dev-lang/python:3.6 ) python_targets_python3_7? ( dev-lang/python:3.7 ) python_targets_python3_8? ( dev-lang/python:3.8 ) >=dev-lang/python-exec-2:=[python_targets_python3_6(-)?,python_targets_python3_7(-)?,python_targets_python3_8(-)?,-python_single_target_python3_6(-),-python_single_target_python3_7(-),-python_single_target_python3_8(-)] dev-lang/swig ) DESCRIPTION=Routing application based on openstreetmap data EAPI=7 HOMEPAGE=http://www.routino.org/ IUSE=python test python_targets_python3_6 python_targets_python3_7 python_targets_python3_8 KEYWORDS=~amd64 ~x86 LICENSE=AGPL-3+ RDEPEND=python? ( python_targets_python3_6? ( dev-lang/python:3.6 ) python_targets_python3_7? ( dev-lang/python:3.7 ) python_targets_python3_8? ( dev-lang/python:3.8 ) >=dev-lang/python-exec-2:=[python_targets_python3_6(-)?,python_targets_python3_7(-)?,python_targets_python3_8(-)?,-python_single_target_python3_6(-),-python_single_target_python3_7(-),-python_single_target_python3_8(-)] ) python_targets_python3_6? ( dev-lang/python:3.6 ) python_targets_python3_7? ( dev-lang/python:3.7 ) python_targets_python3_8? ( dev-lang/python:3.8 ) >=dev-lang/python-exec-2:=[python_targets_python3_6(-)?,python_targets_python3_7(-)?,python_targets_python3_8(-)?,-python_single_target_python3_6(-),-python_single_target_python3_7(-),-python_single_target_python3_8(-)] REQUIRED_USE=|| ( python_targets_python3_6 python_targets_python3_7 python_targets_python3_8 ) || ( python_targets_python3_6 python_targets_python3_7 python_targets_python3_8 ) RESTRICT=!test? ( test ) SLOT=0 SRC_URI=http://www.routino.org/download/routino-3.3.2.tgz _eclasses_=distutils-r1 409cd1220f9f980d21980293a50e2a8e multibuild b2c915190b051f55a23b9354b9849847 multilib 98584e405e2b0264d37e8f728327fed1 multiprocessing cac3169468f893670dac3e7cb940e045 python-r1 8d03325e7e3cf3e1465d9c32031e2517 python-utils-r1 e41e32d357e5bdd388b5be2ce24f3883 toolchain-funcs 605c126bed8d87e4378d5ff1645330cb _md5_=e769c15001430ee3d002fe6bcfc4aeb1
{ "pile_set_name": "Github" }
package com.pan.simplepicture.view.holder; import android.content.Intent; import android.text.Html; import android.text.TextUtils; import android.view.View; import android.widget.RelativeLayout; import android.widget.TextView; import com.pan.simplepicture.R; import com.pan.simplepicture.bean.Lz13; import com.pan.simplepicture.view.activity.ArticleActivity; import butterknife.Bind; /** * Created by sysadminl on 2015/12/11. */ public class ArticleHolder extends BaseHolder<Lz13> { public ArticleHolder(View view) { super(view); } @Bind(R.id.rl_auth) RelativeLayout rl_auth; @Bind(R.id.tv_auth) TextView tv_auth; @Bind(R.id.title) public TextView title; @Bind(R.id.des) TextView des; @Override public void init() { super.init(); mView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent=new Intent(mContext, ArticleActivity.class); intent.putExtra("article", mData); mContext.startActivity(intent); } }); } @Override public void setData(Lz13 mData) { super.setData(mData); title.setText(mData.title); des.setText(Html.fromHtml(mData.text)); if (TextUtils.isEmpty(mData.auth)) { rl_auth.setVisibility(View.GONE); } else { rl_auth.setVisibility(View.VISIBLE); tv_auth.setText(mData.auth); } } }
{ "pile_set_name": "Github" }
// Copyright (c) 2012 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #ifndef MKVPARSER_HPP #define MKVPARSER_HPP #include <cstdlib> #include <cstdio> #include <cstddef> namespace mkvparser { const int E_FILE_FORMAT_INVALID = -2; const int E_BUFFER_NOT_FULL = -3; class IMkvReader { public: virtual int Read(long long pos, long len, unsigned char* buf) = 0; virtual int Length(long long* total, long long* available) = 0; protected: virtual ~IMkvReader(); }; long long GetUIntLength(IMkvReader*, long long, long&); long long ReadUInt(IMkvReader*, long long, long&); long long UnserializeUInt(IMkvReader*, long long pos, long long size); long UnserializeFloat(IMkvReader*, long long pos, long long size, double&); long UnserializeInt(IMkvReader*, long long pos, long len, long long& result); long UnserializeString( IMkvReader*, long long pos, long long size, char*& str); long ParseElementHeader( IMkvReader* pReader, long long& pos, //consume id and size fields long long stop, //if you know size of element's parent long long& id, long long& size); bool Match(IMkvReader*, long long&, unsigned long, long long&); bool Match(IMkvReader*, long long&, unsigned long, unsigned char*&, size_t&); void GetVersion(int& major, int& minor, int& build, int& revision); struct EBMLHeader { EBMLHeader(); ~EBMLHeader(); long long m_version; long long m_readVersion; long long m_maxIdLength; long long m_maxSizeLength; char* m_docType; long long m_docTypeVersion; long long m_docTypeReadVersion; long long Parse(IMkvReader*, long long&); void Init(); }; class Segment; class Track; class Cluster; class Block { Block(const Block&); Block& operator=(const Block&); public: const long long m_start; const long long m_size; Block(long long start, long long size, long long discard_padding); ~Block(); long Parse(const Cluster*); long long GetTrackNumber() const; long long GetTimeCode(const Cluster*) const; //absolute, but not scaled long long GetTime(const Cluster*) const; //absolute, and scaled (ns) bool IsKey() const; void SetKey(bool); bool IsInvisible() const; enum Lacing { kLacingNone, kLacingXiph, kLacingFixed, kLacingEbml }; Lacing GetLacing() const; int GetFrameCount() const; //to index frames: [0, count) struct Frame { long long pos; //absolute offset long len; long Read(IMkvReader*, unsigned char*) const; }; const Frame& GetFrame(int frame_index) const; long long GetDiscardPadding() const; private: long long m_track; //Track::Number() short m_timecode; //relative to cluster unsigned char m_flags; Frame* m_frames; int m_frame_count; protected: const long long m_discard_padding; }; class BlockEntry { BlockEntry(const BlockEntry&); BlockEntry& operator=(const BlockEntry&); protected: BlockEntry(Cluster*, long index); public: virtual ~BlockEntry(); bool EOS() const; const Cluster* GetCluster() const; long GetIndex() const; virtual const Block* GetBlock() const = 0; enum Kind { kBlockEOS, kBlockSimple, kBlockGroup }; virtual Kind GetKind() const = 0; protected: Cluster* const m_pCluster; const long m_index; }; class SimpleBlock : public BlockEntry { SimpleBlock(const SimpleBlock&); SimpleBlock& operator=(const SimpleBlock&); public: SimpleBlock(Cluster*, long index, long long start, long long size); long Parse(); Kind GetKind() const; const Block* GetBlock() const; protected: Block m_block; }; class BlockGroup : public BlockEntry { BlockGroup(const BlockGroup&); BlockGroup& operator=(const BlockGroup&); public: BlockGroup( Cluster*, long index, long long block_start, //absolute pos of block's payload long long block_size, //size of block's payload long long prev, long long next, long long duration, long long discard_padding); long Parse(); Kind GetKind() const; const Block* GetBlock() const; long long GetPrevTimeCode() const; //relative to block's time long long GetNextTimeCode() const; //as above long long GetDurationTimeCode() const; private: Block m_block; const long long m_prev; const long long m_next; const long long m_duration; }; /////////////////////////////////////////////////////////////// // ContentEncoding element // Elements used to describe if the track data has been encrypted or // compressed with zlib or header stripping. class ContentEncoding { public: enum { kCTR = 1 }; ContentEncoding(); ~ContentEncoding(); // ContentCompression element names struct ContentCompression { ContentCompression(); ~ContentCompression(); unsigned long long algo; unsigned char* settings; long long settings_len; }; // ContentEncAESSettings element names struct ContentEncAESSettings { ContentEncAESSettings() : cipher_mode(kCTR) {} ~ContentEncAESSettings() {} unsigned long long cipher_mode; }; // ContentEncryption element names struct ContentEncryption { ContentEncryption(); ~ContentEncryption(); unsigned long long algo; unsigned char* key_id; long long key_id_len; unsigned char* signature; long long signature_len; unsigned char* sig_key_id; long long sig_key_id_len; unsigned long long sig_algo; unsigned long long sig_hash_algo; ContentEncAESSettings aes_settings; }; // Returns ContentCompression represented by |idx|. Returns NULL if |idx| // is out of bounds. const ContentCompression* GetCompressionByIndex(unsigned long idx) const; // Returns number of ContentCompression elements in this ContentEncoding // element. unsigned long GetCompressionCount() const; // Parses the ContentCompression element from |pReader|. |start| is the // starting offset of the ContentCompression payload. |size| is the size in // bytes of the ContentCompression payload. |compression| is where the parsed // values will be stored. long ParseCompressionEntry(long long start, long long size, IMkvReader* pReader, ContentCompression* compression); // Returns ContentEncryption represented by |idx|. Returns NULL if |idx| // is out of bounds. const ContentEncryption* GetEncryptionByIndex(unsigned long idx) const; // Returns number of ContentEncryption elements in this ContentEncoding // element. unsigned long GetEncryptionCount() const; // Parses the ContentEncAESSettings element from |pReader|. |start| is the // starting offset of the ContentEncAESSettings payload. |size| is the // size in bytes of the ContentEncAESSettings payload. |encryption| is // where the parsed values will be stored. long ParseContentEncAESSettingsEntry(long long start, long long size, IMkvReader* pReader, ContentEncAESSettings* aes); // Parses the ContentEncoding element from |pReader|. |start| is the // starting offset of the ContentEncoding payload. |size| is the size in // bytes of the ContentEncoding payload. Returns true on success. long ParseContentEncodingEntry(long long start, long long size, IMkvReader* pReader); // Parses the ContentEncryption element from |pReader|. |start| is the // starting offset of the ContentEncryption payload. |size| is the size in // bytes of the ContentEncryption payload. |encryption| is where the parsed // values will be stored. long ParseEncryptionEntry(long long start, long long size, IMkvReader* pReader, ContentEncryption* encryption); unsigned long long encoding_order() const { return encoding_order_; } unsigned long long encoding_scope() const { return encoding_scope_; } unsigned long long encoding_type() const { return encoding_type_; } private: // Member variables for list of ContentCompression elements. ContentCompression** compression_entries_; ContentCompression** compression_entries_end_; // Member variables for list of ContentEncryption elements. ContentEncryption** encryption_entries_; ContentEncryption** encryption_entries_end_; // ContentEncoding element names unsigned long long encoding_order_; unsigned long long encoding_scope_; unsigned long long encoding_type_; // LIBWEBM_DISALLOW_COPY_AND_ASSIGN(ContentEncoding); ContentEncoding(const ContentEncoding&); ContentEncoding& operator=(const ContentEncoding&); }; class Track { Track(const Track&); Track& operator=(const Track&); public: class Info; static long Create( Segment*, const Info&, long long element_start, long long element_size, Track*&); enum Type { kVideo = 1, kAudio = 2, kSubtitle = 0x11, kMetadata = 0x21 }; Segment* const m_pSegment; const long long m_element_start; const long long m_element_size; virtual ~Track(); long GetType() const; long GetNumber() const; unsigned long long GetUid() const; const char* GetNameAsUTF8() const; const char* GetLanguage() const; const char* GetCodecNameAsUTF8() const; const char* GetCodecId() const; const unsigned char* GetCodecPrivate(size_t&) const; bool GetLacing() const; unsigned long long GetDefaultDuration() const; unsigned long long GetCodecDelay() const; unsigned long long GetSeekPreRoll() const; const BlockEntry* GetEOS() const; struct Settings { long long start; long long size; }; class Info { public: Info(); ~Info(); int Copy(Info&) const; void Clear(); long type; long number; unsigned long long uid; unsigned long long defaultDuration; unsigned long long codecDelay; unsigned long long seekPreRoll; char* nameAsUTF8; char* language; char* codecId; char* codecNameAsUTF8; unsigned char* codecPrivate; size_t codecPrivateSize; bool lacing; Settings settings; private: Info(const Info&); Info& operator=(const Info&); int CopyStr(char* Info::*str, Info&) const; }; long GetFirst(const BlockEntry*&) const; long GetNext(const BlockEntry* pCurr, const BlockEntry*& pNext) const; virtual bool VetEntry(const BlockEntry*) const; virtual long Seek(long long time_ns, const BlockEntry*&) const; const ContentEncoding* GetContentEncodingByIndex(unsigned long idx) const; unsigned long GetContentEncodingCount() const; long ParseContentEncodingsEntry(long long start, long long size); protected: Track( Segment*, long long element_start, long long element_size); Info m_info; class EOSBlock : public BlockEntry { public: EOSBlock(); Kind GetKind() const; const Block* GetBlock() const; }; EOSBlock m_eos; private: ContentEncoding** content_encoding_entries_; ContentEncoding** content_encoding_entries_end_; }; class VideoTrack : public Track { VideoTrack(const VideoTrack&); VideoTrack& operator=(const VideoTrack&); VideoTrack( Segment*, long long element_start, long long element_size); public: static long Parse( Segment*, const Info&, long long element_start, long long element_size, VideoTrack*&); long long GetWidth() const; long long GetHeight() const; double GetFrameRate() const; bool VetEntry(const BlockEntry*) const; long Seek(long long time_ns, const BlockEntry*&) const; private: long long m_width; long long m_height; double m_rate; }; class AudioTrack : public Track { AudioTrack(const AudioTrack&); AudioTrack& operator=(const AudioTrack&); AudioTrack( Segment*, long long element_start, long long element_size); public: static long Parse( Segment*, const Info&, long long element_start, long long element_size, AudioTrack*&); double GetSamplingRate() const; long long GetChannels() const; long long GetBitDepth() const; private: double m_rate; long long m_channels; long long m_bitDepth; }; class Tracks { Tracks(const Tracks&); Tracks& operator=(const Tracks&); public: Segment* const m_pSegment; const long long m_start; const long long m_size; const long long m_element_start; const long long m_element_size; Tracks( Segment*, long long start, long long size, long long element_start, long long element_size); ~Tracks(); long Parse(); unsigned long GetTracksCount() const; const Track* GetTrackByNumber(long tn) const; const Track* GetTrackByIndex(unsigned long idx) const; private: Track** m_trackEntries; Track** m_trackEntriesEnd; long ParseTrackEntry( long long payload_start, long long payload_size, long long element_start, long long element_size, Track*&) const; }; class Chapters { Chapters(const Chapters&); Chapters& operator=(const Chapters&); public: Segment* const m_pSegment; const long long m_start; const long long m_size; const long long m_element_start; const long long m_element_size; Chapters( Segment*, long long payload_start, long long payload_size, long long element_start, long long element_size); ~Chapters(); long Parse(); class Atom; class Edition; class Display { friend class Atom; Display(); Display(const Display&); ~Display(); Display& operator=(const Display&); public: const char* GetString() const; const char* GetLanguage() const; const char* GetCountry() const; private: void Init(); void ShallowCopy(Display&) const; void Clear(); long Parse(IMkvReader*, long long pos, long long size); char* m_string; char* m_language; char* m_country; }; class Atom { friend class Edition; Atom(); Atom(const Atom&); ~Atom(); Atom& operator=(const Atom&); public: unsigned long long GetUID() const; const char* GetStringUID() const; long long GetStartTimecode() const; long long GetStopTimecode() const; long long GetStartTime(const Chapters*) const; long long GetStopTime(const Chapters*) const; int GetDisplayCount() const; const Display* GetDisplay(int index) const; private: void Init(); void ShallowCopy(Atom&) const; void Clear(); long Parse(IMkvReader*, long long pos, long long size); static long long GetTime(const Chapters*, long long timecode); long ParseDisplay(IMkvReader*, long long pos, long long size); bool ExpandDisplaysArray(); char* m_string_uid; unsigned long long m_uid; long long m_start_timecode; long long m_stop_timecode; Display* m_displays; int m_displays_size; int m_displays_count; }; class Edition { friend class Chapters; Edition(); Edition(const Edition&); ~Edition(); Edition& operator=(const Edition&); public: int GetAtomCount() const; const Atom* GetAtom(int index) const; private: void Init(); void ShallowCopy(Edition&) const; void Clear(); long Parse(IMkvReader*, long long pos, long long size); long ParseAtom(IMkvReader*, long long pos, long long size); bool ExpandAtomsArray(); Atom* m_atoms; int m_atoms_size; int m_atoms_count; }; int GetEditionCount() const; const Edition* GetEdition(int index) const; private: long ParseEdition(long long pos, long long size); bool ExpandEditionsArray(); Edition* m_editions; int m_editions_size; int m_editions_count; }; class SegmentInfo { SegmentInfo(const SegmentInfo&); SegmentInfo& operator=(const SegmentInfo&); public: Segment* const m_pSegment; const long long m_start; const long long m_size; const long long m_element_start; const long long m_element_size; SegmentInfo( Segment*, long long start, long long size, long long element_start, long long element_size); ~SegmentInfo(); long Parse(); long long GetTimeCodeScale() const; long long GetDuration() const; //scaled const char* GetMuxingAppAsUTF8() const; const char* GetWritingAppAsUTF8() const; const char* GetTitleAsUTF8() const; private: long long m_timecodeScale; double m_duration; char* m_pMuxingAppAsUTF8; char* m_pWritingAppAsUTF8; char* m_pTitleAsUTF8; }; class SeekHead { SeekHead(const SeekHead&); SeekHead& operator=(const SeekHead&); public: Segment* const m_pSegment; const long long m_start; const long long m_size; const long long m_element_start; const long long m_element_size; SeekHead( Segment*, long long start, long long size, long long element_start, long long element_size); ~SeekHead(); long Parse(); struct Entry { //the SeekHead entry payload long long id; long long pos; //absolute pos of SeekEntry ID long long element_start; //SeekEntry ID size + size size + payload long long element_size; }; int GetCount() const; const Entry* GetEntry(int idx) const; struct VoidElement { //absolute pos of Void ID long long element_start; //ID size + size size + payload size long long element_size; }; int GetVoidElementCount() const; const VoidElement* GetVoidElement(int idx) const; private: Entry* m_entries; int m_entry_count; VoidElement* m_void_elements; int m_void_element_count; static bool ParseEntry( IMkvReader*, long long pos, //payload long long size, Entry*); }; class Cues; class CuePoint { friend class Cues; CuePoint(long, long long); ~CuePoint(); CuePoint(const CuePoint&); CuePoint& operator=(const CuePoint&); public: long long m_element_start; long long m_element_size; void Load(IMkvReader*); long long GetTimeCode() const; //absolute but unscaled long long GetTime(const Segment*) const; //absolute and scaled (ns units) struct TrackPosition { long long m_track; long long m_pos; //of cluster long long m_block; //codec_state //defaults to 0 //reference = clusters containing req'd referenced blocks // reftime = timecode of the referenced block void Parse(IMkvReader*, long long, long long); }; const TrackPosition* Find(const Track*) const; private: const long m_index; long long m_timecode; TrackPosition* m_track_positions; size_t m_track_positions_count; }; class Cues { friend class Segment; Cues( Segment*, long long start, long long size, long long element_start, long long element_size); ~Cues(); Cues(const Cues&); Cues& operator=(const Cues&); public: Segment* const m_pSegment; const long long m_start; const long long m_size; const long long m_element_start; const long long m_element_size; bool Find( //lower bound of time_ns long long time_ns, const Track*, const CuePoint*&, const CuePoint::TrackPosition*&) const; #if 0 bool FindNext( //upper_bound of time_ns long long time_ns, const Track*, const CuePoint*&, const CuePoint::TrackPosition*&) const; #endif const CuePoint* GetFirst() const; const CuePoint* GetLast() const; const CuePoint* GetNext(const CuePoint*) const; const BlockEntry* GetBlock( const CuePoint*, const CuePoint::TrackPosition*) const; bool LoadCuePoint() const; long GetCount() const; //loaded only //long GetTotal() const; //loaded + preloaded bool DoneParsing() const; private: void Init() const; void PreloadCuePoint(long&, long long) const; mutable CuePoint** m_cue_points; mutable long m_count; mutable long m_preload_count; mutable long long m_pos; }; class Cluster { friend class Segment; Cluster(const Cluster&); Cluster& operator=(const Cluster&); public: Segment* const m_pSegment; public: static Cluster* Create( Segment*, long index, //index in segment long long off); //offset relative to segment //long long element_size); Cluster(); //EndOfStream ~Cluster(); bool EOS() const; long long GetTimeCode() const; //absolute, but not scaled long long GetTime() const; //absolute, and scaled (nanosecond units) long long GetFirstTime() const; //time (ns) of first (earliest) block long long GetLastTime() const; //time (ns) of last (latest) block long GetFirst(const BlockEntry*&) const; long GetLast(const BlockEntry*&) const; long GetNext(const BlockEntry* curr, const BlockEntry*& next) const; const BlockEntry* GetEntry(const Track*, long long ns = -1) const; const BlockEntry* GetEntry( const CuePoint&, const CuePoint::TrackPosition&) const; //const BlockEntry* GetMaxKey(const VideoTrack*) const; // static bool HasBlockEntries(const Segment*, long long); static long HasBlockEntries( const Segment*, long long idoff, long long& pos, long& size); long GetEntryCount() const; long Load(long long& pos, long& size) const; long Parse(long long& pos, long& size) const; long GetEntry(long index, const mkvparser::BlockEntry*&) const; protected: Cluster( Segment*, long index, long long element_start); //long long element_size); public: const long long m_element_start; long long GetPosition() const; //offset relative to segment long GetIndex() const; long long GetElementSize() const; //long long GetPayloadSize() const; //long long Unparsed() const; private: long m_index; mutable long long m_pos; //mutable long long m_size; mutable long long m_element_size; mutable long long m_timecode; mutable BlockEntry** m_entries; mutable long m_entries_size; mutable long m_entries_count; long ParseSimpleBlock(long long, long long&, long&); long ParseBlockGroup(long long, long long&, long&); long CreateBlock(long long id, long long pos, long long size, long long discard_padding); long CreateBlockGroup(long long start_offset, long long size, long long discard_padding); long CreateSimpleBlock(long long, long long); }; class Segment { friend class Cues; friend class Track; friend class VideoTrack; Segment(const Segment&); Segment& operator=(const Segment&); private: Segment( IMkvReader*, long long elem_start, //long long elem_size, long long pos, long long size); public: IMkvReader* const m_pReader; const long long m_element_start; //const long long m_element_size; const long long m_start; //posn of segment payload const long long m_size; //size of segment payload Cluster m_eos; //TODO: make private? static long long CreateInstance(IMkvReader*, long long, Segment*&); ~Segment(); long Load(); //loads headers and all clusters //for incremental loading //long long Unparsed() const; bool DoneParsing() const; long long ParseHeaders(); //stops when first cluster is found //long FindNextCluster(long long& pos, long& size) const; long LoadCluster(long long& pos, long& size); //load one cluster long LoadCluster(); long ParseNext( const Cluster* pCurr, const Cluster*& pNext, long long& pos, long& size); #if 0 //This pair parses one cluster, but only changes the state of the //segment object when the cluster is actually added to the index. long ParseCluster(long long& cluster_pos, long long& new_pos) const; bool AddCluster(long long cluster_pos, long long new_pos); #endif const SeekHead* GetSeekHead() const; const Tracks* GetTracks() const; const SegmentInfo* GetInfo() const; const Cues* GetCues() const; const Chapters* GetChapters() const; long long GetDuration() const; unsigned long GetCount() const; const Cluster* GetFirst() const; const Cluster* GetLast() const; const Cluster* GetNext(const Cluster*); const Cluster* FindCluster(long long time_nanoseconds) const; //const BlockEntry* Seek(long long time_nanoseconds, const Track*) const; const Cluster* FindOrPreloadCluster(long long pos); long ParseCues( long long cues_off, //offset relative to start of segment long long& parse_pos, long& parse_len); private: long long m_pos; //absolute file posn; what has been consumed so far Cluster* m_pUnknownSize; SeekHead* m_pSeekHead; SegmentInfo* m_pInfo; Tracks* m_pTracks; Cues* m_pCues; Chapters* m_pChapters; Cluster** m_clusters; long m_clusterCount; //number of entries for which m_index >= 0 long m_clusterPreloadCount; //number of entries for which m_index < 0 long m_clusterSize; //array size long DoLoadCluster(long long&, long&); long DoLoadClusterUnknownSize(long long&, long&); long DoParseNext(const Cluster*&, long long&, long&); void AppendCluster(Cluster*); void PreloadCluster(Cluster*, ptrdiff_t); //void ParseSeekHead(long long pos, long long size); //void ParseSeekEntry(long long pos, long long size); //void ParseCues(long long); const BlockEntry* GetBlock( const CuePoint&, const CuePoint::TrackPosition&); }; } //end namespace mkvparser inline long mkvparser::Segment::LoadCluster() { long long pos; long size; return LoadCluster(pos, size); } #endif //MKVPARSER_HPP
{ "pile_set_name": "Github" }
// RUN: %clang_cc1 -S -O3 -fno-builtin -o - %s | FileCheck %s // rdar://10551066 typedef __SIZE_TYPE__ size_t; double ceil(double x); double copysign(double,double); double cos(double x); double fabs(double x); double floor(double x); char *strcat(char *s1, const char *s2); char *strncat(char *s1, const char *s2, size_t n); char *strchr(const char *s, int c); char *strrchr(const char *s, int c); int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n); char *strcpy(char *s1, const char *s2); char *stpcpy(char *s1, const char *s2); char *strncpy(char *s1, const char *s2, size_t n); size_t strlen(const char *s); char *strpbrk(const char *s1, const char *s2); size_t strspn(const char *s1, const char *s2); double strtod(const char *nptr, char **endptr); float strtof(const char *nptr, char **endptr); long double strtold(const char *nptr, char **endptr); long int strtol(const char *nptr, char **endptr, int base); long long int strtoll(const char *nptr, char **endptr, int base); unsigned long int strtoul(const char *nptr, char **endptr, int base); unsigned long long int strtoull(const char *nptr, char **endptr, int base); double t1(double x) { return ceil(x); } // CHECK: t1 // CHECK: ceil double t2(double x, double y) { return copysign(x,y); } // CHECK: t2 // CHECK: copysign double t3(double x) { return cos(x); } // CHECK: t3 // CHECK: cos double t4(double x) { return fabs(x); } // CHECK: t4 // CHECK: fabs double t5(double x) { return floor(x); } // CHECK: t5 // CHECK: floor char *t6(char *x) { return strcat(x, ""); } // CHECK: t6 // CHECK: strcat char *t7(char *x) { return strncat(x, "", 1); } // CHECK: t7 // CHECK: strncat char *t8(void) { return strchr("hello, world", 'w'); } // CHECK: t8 // CHECK: strchr char *t9(void) { return strrchr("hello, world", 'w'); } // CHECK: t9 // CHECK: strrchr int t10(void) { return strcmp("foo", "bar"); } // CHECK: t10 // CHECK: strcmp int t11(void) { return strncmp("foo", "bar", 3); } // CHECK: t11 // CHECK: strncmp char *t12(char *x) { return strcpy(x, "foo"); } // CHECK: t12 // CHECK: strcpy char *t13(char *x) { return stpcpy(x, "foo"); } // CHECK: t13 // CHECK: stpcpy char *t14(char *x) { return strncpy(x, "foo", 3); } // CHECK: t14 // CHECK: strncpy size_t t15(void) { return strlen("foo"); } // CHECK: t15 // CHECK: strlen char *t16(char *x) { return strpbrk(x, ""); } // CHECK: t16 // CHECK: strpbrk size_t t17(char *x) { return strspn(x, ""); } // CHECK: t17 // CHECK: strspn double t18(char **x) { return strtod("123.4", x); } // CHECK: t18 // CHECK: strtod float t19(char **x) { return strtof("123.4", x); } // CHECK: t19 // CHECK: strtof long double t20(char **x) { return strtold("123.4", x); } // CHECK: t20 // CHECK: strtold long int t21(char **x) { return strtol("1234", x, 10); } // CHECK: t21 // CHECK: strtol long int t22(char **x) { return strtoll("1234", x, 10); } // CHECK: t22 // CHECK: strtoll long int t23(char **x) { return strtoul("1234", x, 10); } // CHECK: t23 // CHECK: strtoul long int t24(char **x) { return strtoull("1234", x, 10); } // CHECK: t24 // CHECK: strtoull
{ "pile_set_name": "Github" }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\IEntityRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The interface IItemAttachmentRequestBuilder. /// </summary> public partial interface IItemAttachmentRequestBuilder : IAttachmentRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> new IItemAttachmentRequest Request(); /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> new IItemAttachmentRequest Request(IEnumerable<Option> options); /// <summary> /// Gets the request builder for Item. /// </summary> /// <returns>The <see cref="IOutlookItemRequestBuilder"/>.</returns> IOutlookItemRequestBuilder Item { get; } } }
{ "pile_set_name": "Github" }
package extra import ( "github.com/json-iterator/go" "github.com/modern-go/reflect2" "unicode/utf8" "unsafe" ) // safeSet holds the value true if the ASCII character with the given array // position can be represented inside a JSON string without any further // escaping. // // All values are true except for the ASCII control characters (0-31), the // double quote ("), and the backslash character ("\"). var safeSet = [utf8.RuneSelf]bool{ ' ': true, '!': true, '"': false, '#': true, '$': true, '%': true, '&': true, '\'': true, '(': true, ')': true, '*': true, '+': true, ',': true, '-': true, '.': true, '/': true, '0': true, '1': true, '2': true, '3': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true, ':': true, ';': true, '<': true, '=': true, '>': true, '?': true, '@': true, 'A': true, 'B': true, 'C': true, 'D': true, 'E': true, 'F': true, 'G': true, 'H': true, 'I': true, 'J': true, 'K': true, 'L': true, 'M': true, 'N': true, 'O': true, 'P': true, 'Q': true, 'R': true, 'S': true, 'T': true, 'U': true, 'V': true, 'W': true, 'X': true, 'Y': true, 'Z': true, '[': true, '\\': false, ']': true, '^': true, '_': true, '`': true, 'a': true, 'b': true, 'c': true, 'd': true, 'e': true, 'f': true, 'g': true, 'h': true, 'i': true, 'j': true, 'k': true, 'l': true, 'm': true, 'n': true, 'o': true, 'p': true, 'q': true, 'r': true, 's': true, 't': true, 'u': true, 'v': true, 'w': true, 'x': true, 'y': true, 'z': true, '{': true, '|': true, '}': true, '~': true, '\u007f': true, } var binaryType = reflect2.TypeOfPtr((*[]byte)(nil)).Elem() type BinaryAsStringExtension struct { jsoniter.DummyExtension } func (extension *BinaryAsStringExtension) CreateEncoder(typ reflect2.Type) jsoniter.ValEncoder { if typ == binaryType { return &binaryAsStringCodec{} } return nil } func (extension *BinaryAsStringExtension) CreateDecoder(typ reflect2.Type) jsoniter.ValDecoder { if typ == binaryType { return &binaryAsStringCodec{} } return nil } type binaryAsStringCodec struct { } func (codec *binaryAsStringCodec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { rawBytes := iter.ReadStringAsSlice() bytes := make([]byte, 0, len(rawBytes)) for i := 0; i < len(rawBytes); i++ { b := rawBytes[i] if b == '\\' { b2 := rawBytes[i+1] if b2 != '\\' { iter.ReportError("decode binary as string", `\\x is only supported escape`) return } b3 := rawBytes[i+2] if b3 != 'x' { iter.ReportError("decode binary as string", `\\x is only supported escape`) return } b4 := rawBytes[i+3] b5 := rawBytes[i+4] i += 4 b = readHex(iter, b4, b5) } bytes = append(bytes, b) } *(*[]byte)(ptr) = bytes } func (codec *binaryAsStringCodec) IsEmpty(ptr unsafe.Pointer) bool { return len(*((*[]byte)(ptr))) == 0 } func (codec *binaryAsStringCodec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) { newBuffer := writeBytes(stream.Buffer(), *(*[]byte)(ptr)) stream.SetBuffer(newBuffer) } func readHex(iter *jsoniter.Iterator, b1, b2 byte) byte { var ret byte if b1 >= '0' && b1 <= '9' { ret = b1 - '0' } else if b1 >= 'a' && b1 <= 'f' { ret = b1 - 'a' + 10 } else { iter.ReportError("read hex", "expects 0~9 or a~f, but found "+string([]byte{b1})) return 0 } ret *= 16 if b2 >= '0' && b2 <= '9' { ret = b2 - '0' } else if b2 >= 'a' && b2 <= 'f' { ret = b2 - 'a' + 10 } else { iter.ReportError("read hex", "expects 0~9 or a~f, but found "+string([]byte{b2})) return 0 } return ret } var hex = "0123456789abcdef" func writeBytes(space []byte, s []byte) []byte { space = append(space, '"') // write string, the fast path, without utf8 and escape support var i int var c byte for i, c = range s { if c < utf8.RuneSelf && safeSet[c] { space = append(space, c) } else { break } } if i == len(s)-1 { space = append(space, '"') return space } return writeBytesSlowPath(space, s[i:]) } func writeBytesSlowPath(space []byte, s []byte) []byte { start := 0 // for the remaining parts, we process them char by char var i int var b byte for i, b = range s { if b >= utf8.RuneSelf { space = append(space, '\\', '\\', 'x', hex[b>>4], hex[b&0xF]) start = i + 1 continue } if safeSet[b] { continue } if start < i { space = append(space, s[start:i]...) } space = append(space, '\\', '\\', 'x', hex[b>>4], hex[b&0xF]) start = i + 1 } if start < len(s) { space = append(space, s[start:]...) } return append(space, '"') }
{ "pile_set_name": "Github" }
/* Small tests for r2pipe */ // return true; var r2pipe = require('./../'); var r2 = r2pipe.pipeSync('/bin/ls'); var res = r2.cmd('pd 4'); var resj = r2.cmdj('pdj 4'); var sys = r2.syscmd('rabin2 -zz /bin/ls'); var sysj = r2.syscmdj('rabin2 -j -zz /bin/ls'); console.log('Normal output'); console.log(res); console.log('JSON output'); console.log(resj); console.log('\nSyscmd normal output'); console.log(sys); console.log('Syscmd JSON output'); console.log(sysj); r2.quit();
{ "pile_set_name": "Github" }