max_stars_count
int64
301
224k
text
stringlengths
6
1.05M
token_count
int64
3
727k
2,706
<reponame>MatPoliquin/retro // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // 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 ERROR_REPORTER_H_ #define ERROR_REPORTER_H_ #if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) #pragma GCC system_header #endif #include "../common.h" #include <kj/string.h> #include <kj/exception.h> #include <kj/vector.h> namespace capnp { namespace compiler { class ErrorReporter { // Callback for reporting errors within a particular file. public: virtual void addError(uint32_t startByte, uint32_t endByte, kj::StringPtr message) = 0; // Report an error at the given location in the input text. `startByte` and `endByte` indicate // the span of text that is erroneous. They may be equal, in which case the parser was only // able to identify where the error begins, not where it ends. template <typename T> inline void addErrorOn(T&& decl, kj::StringPtr message) { // Works for any `T` that defines `getStartByte()` and `getEndByte()` methods, which many // of the Cap'n Proto types defined in `grammar.capnp` do. addError(decl.getStartByte(), decl.getEndByte(), message); } virtual bool hadErrors() = 0; // Return true if any errors have been reported, globally. The main use case for this callback // is to inhibit the reporting of errors which may have been caused by previous errors, or to // allow the compiler to bail out entirely if it gets confused and thinks this could be because // of previous errors. }; class GlobalErrorReporter { // Callback for reporting errors in any file. public: struct SourcePos { uint byte; uint line; uint column; }; virtual void addError(kj::StringPtr file, SourcePos start, SourcePos end, kj::StringPtr message) = 0; // Report an error at the given location in the given file. virtual bool hadErrors() = 0; // Return true if any errors have been reported, globally. The main use case for this callback // is to inhibit the reporting of errors which may have been caused by previous errors, or to // allow the compiler to bail out entirely if it gets confused and thinks this could be because // of previous errors. }; class LineBreakTable { public: LineBreakTable(kj::ArrayPtr<const char> content); GlobalErrorReporter::SourcePos toSourcePos(uint32_t byteOffset) const; private: kj::Vector<uint> lineBreaks; // Byte offsets of the first byte in each source line. The first element is always zero. // Initialized the first time the module is loaded. }; } // namespace compiler } // namespace capnp #endif // ERROR_REPORTER_H_
1,072
1,047
<filename>Sources/DarkModeCore/DMNamespace.h // // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // #import <Foundation/Foundation.h> typedef NS_ENUM(NSInteger, DMNamespace) { DMNamespaceDM NS_SWIFT_NAME(dm), };
90
3,402
/* * 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.spark.dict; import java.io.Serializable; public class NGlobalDictMetaInfo implements Serializable { private int bucketSize; private long dictCount; private long[] bucketOffsets; private long[] bucketCount; NGlobalDictMetaInfo(int bucketSize, long[] bucketOffsets, long dictCount, long[] bucketCount) { this.bucketSize = bucketSize; this.dictCount = dictCount; this.bucketOffsets = bucketOffsets; this.bucketCount = bucketCount; } long getOffset(int point) { return bucketOffsets[point]; } public int getBucketSize() { return bucketSize; } public void setBucketSize(int bucketSize) { this.bucketSize = bucketSize; } public long getDictCount() { return this.dictCount; } public long[] getBucketOffsets() { return this.bucketOffsets; } public long[] getBucketCount() { return this.bucketCount; } public void setDictCount(long dictCount) { this.dictCount = dictCount; } public void setBucketOffsets(long[] bucketOffsets) { this.bucketOffsets = bucketOffsets; } public void setBucketCount(long[] bucketCount) { this.bucketCount = bucketCount; } public boolean equals(final Object o) { if (o == this) return true; if (!(o instanceof NGlobalDictMetaInfo)) return false; final NGlobalDictMetaInfo other = (NGlobalDictMetaInfo) o; if (!other.canEqual((Object) this)) return false; if (this.getBucketSize() != other.getBucketSize()) return false; if (this.getDictCount() != other.getDictCount()) return false; if (!java.util.Arrays.equals(this.getBucketOffsets(), other.getBucketOffsets())) return false; if (!java.util.Arrays.equals(this.getBucketCount(), other.getBucketCount())) return false; return true; } protected boolean canEqual(final Object other) { return other instanceof NGlobalDictMetaInfo; } public int hashCode() { final int PRIME = 59; int result = 1; result = result * PRIME + this.getBucketSize(); final long $dictCount = this.getDictCount(); result = result * PRIME + (int) ($dictCount >>> 32 ^ $dictCount); result = result * PRIME + java.util.Arrays.hashCode(this.getBucketOffsets()); result = result * PRIME + java.util.Arrays.hashCode(this.getBucketCount()); return result; } }
1,175
348
{"nom":"<NAME>","circ":"9ème circonscription","dpt":"Bas-Rhin","inscrits":4817,"abs":2746,"votants":2071,"blancs":65,"nuls":26,"exp":1980,"res":[{"nuance":"REM","nom":"<NAME>","voix":1118},{"nuance":"LR","nom":"<NAME>","voix":862}]}
95
513
# -*- coding: utf-8 -*- import argparse import logging import sys from docker_squash import squash from docker_squash.errors import SquashError from docker_squash.version import version # Source: http://stackoverflow.com/questions/1383254/logging-streamhandler-and-standard-streams class SingleLevelFilter(logging.Filter): def __init__(self, passlevel, reject): self.passlevel = passlevel self.reject = reject def filter(self, record): if self.reject: return (record.levelno != self.passlevel) else: return (record.levelno == self.passlevel) class MyParser(argparse.ArgumentParser): def error(self, message): self.print_help() sys.stderr.write('\nError: %s\n' % message) sys.exit(2) class CLI(object): def __init__(self): handler_out = logging.StreamHandler(sys.stdout) handler_err = logging.StreamHandler(sys.stderr) handler_out.addFilter(SingleLevelFilter(logging.INFO, False)) handler_err.addFilter(SingleLevelFilter(logging.INFO, True)) self.log = logging.getLogger() formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler_out.setFormatter(formatter) handler_err.setFormatter(formatter) self.log.addHandler(handler_out) self.log.addHandler(handler_err) def run(self): parser = MyParser( description='Docker layer squashing tool') parser.add_argument( '-v', '--verbose', action='store_true', help='Verbose output') parser.add_argument( '--version', action='version', help='Show version and exit', version=version) parser.add_argument('image', help='Image to be squashed') parser.add_argument( '-d', '--development', action='store_true', help='Does not clean up after failure for easier debugging') parser.add_argument( '-f', '--from-layer', help='Number of layers to squash or ID of the layer (or image ID or image name) to squash from. In case the provided value is an integer, specified number of layers will be squashed. Every layer in the image will be squashed if the parameter is not provided.') parser.add_argument( '-t', '--tag', help="Specify the tag to be used for the new image. If not specified no tag will be applied") parser.add_argument( '-m', '--message', help="Specify a commit message (comment) for the new image.") parser.add_argument( '-c', '--cleanup', action='store_true', help="Remove source image from Docker after squashing") parser.add_argument( '--tmp-dir', help='Temporary directory to be created and used') parser.add_argument( '--output-path', help='Path where the image should be stored after squashing. If not provided, image will be loaded into Docker daemon') args = parser.parse_args() if args.verbose: self.log.setLevel(logging.DEBUG) else: self.log.setLevel(logging.INFO) self.log.debug("Running version %s", version) try: squash.Squash(log=self.log, image=args.image, from_layer=args.from_layer, tag=args.tag, comment=args.message, output_path=args.output_path, tmp_dir=args.tmp_dir, development=args.development, cleanup=args.cleanup).run() except KeyboardInterrupt: self.log.error("Program interrupted by user, exiting...") sys.exit(1) except: e = sys.exc_info()[1] if args.development or args.verbose: self.log.exception(e) else: self.log.error(str(e)) self.log.error( "Execution failed, consult logs above. If you think this is our fault, please file an issue: https://github.com/goldmann/docker-squash/issues, thanks!") if isinstance(e, SquashError): sys.exit(e.code) sys.exit(1) def run(): cli = CLI() cli.run() if __name__ == "__main__": run()
1,724
307
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on the * source. * */ #include <algorithm> #include "asteroid/asteroid.h" #include "cmdline/cmdline.h" #include "debris/debris.h" #include "debugconsole/console.h" #include "freespace.h" #include "gamesnd/gamesnd.h" #include "globalincs/linklist.h" #include "hud/hudets.h" #include "hud/hudmessage.h" #include "hud/hudshield.h" #include "iff_defs/iff_defs.h" #include "io/timer.h" #include "lighting/lighting.h" #include "math/fvi.h" #include "math/staticrand.h" #include "nebula/neb.h" #include "mod_table/mod_table.h" #include "network/multi.h" #include "network/multimsgs.h" #include "object/objcollide.h" #include "object/object.h" #include "object/objectshield.h" #include "parse/parselo.h" #include "scripting/scripting.h" #include "scripting/api/objs/vecmath.h" #include "particle/particle.h" #include "playerman/player.h" #include "render/3d.h" #include "ship/ship.h" #include "ship/shipfx.h" #include "ship/shiphit.h" #include "weapon/beam.h" #include "weapon/weapon.h" #include "globalincs/globals.h" #include "tracing/tracing.h" // ------------------------------------------------------------------------------------------------ // BEAM WEAPON DEFINES/VARS // // this is the constant which defines when a beam is an "area" beam. meaning, when we switch on sphereline checking and when // a beam gets "stopped" by an object. It is a percentage of the object radius which the beam must be wider than #define BEAM_AREA_PERCENT 0.4f // randomness factor - all beam weapon aiming is adjusted by +/- some factor within this range #define BEAM_RANDOM_FACTOR 0.4f #define MAX_SHOT_POINTS 30 #define SHOT_POINT_TIME 200 // 5 arcs a second #define TOOLTIME 1500.0f std::array<beam, MAX_BEAMS> Beams; // all beams beam Beam_free_list; // free beams beam Beam_used_list; // used beams int Beam_count = 0; // how many beams are in use // octant indices. These are "good" pairs of octants to use for beam target #define BEAM_NUM_GOOD_OCTANTS 8 int Beam_good_slash_octants[BEAM_NUM_GOOD_OCTANTS][4] = { { 2, 5, 1, 0 }, // octant, octant, min/max pt, min/max pt { 7, 0, 1, 0 }, { 1, 6, 1, 0 }, { 6, 1, 0, 1 }, { 5, 2, 0, 1 }, { 0, 7, 0, 1 }, { 7, 1, 1, 0 }, { 6, 0, 1, 0 }, }; int Beam_good_shot_octants[BEAM_NUM_GOOD_OCTANTS][4] = { { 5, 0, 1, 0 }, // octant, octant, min/max pt, min/max pt { 7, 2, 1, 0 }, { 7, 1, 1, 0 }, { 6, 0, 1, 0 }, { 7, 3, 1, 0 }, { 6, 2, 1, 0 }, { 5, 1, 1, 0 }, { 4, 0, 1, 0 }, }; // debug stuff - keep track of how many collision tests we perform a second and how many we toss a second #define BEAM_TEST_STAMP_TIME 4000 // every 4 seconds int Beam_test_stamp = -1; int Beam_test_ints = 0; int Beam_test_ship = 0; int Beam_test_ast = 0; int Beam_test_framecount = 0; // beam warmup completion % #define BEAM_WARMUP_PCT(b) ( ((float)Weapon_info[b->weapon_info_index].b_info.beam_warmup - (float)timestamp_until(b->warmup_stamp)) / (float)Weapon_info[b->weapon_info_index].b_info.beam_warmup ) // beam warmdown completion % #define BEAM_WARMDOWN_PCT(b) ( ((float)Weapon_info[b->weapon_info_index].b_info.beam_warmdown - (float)timestamp_until(b->warmdown_stamp)) / (float)Weapon_info[b->weapon_info_index].b_info.beam_warmdown ) // link into the physics paused system extern int physics_paused; // beam lighting info #define MAX_BEAM_LIGHT_INFO 100 typedef struct beam_light_info { beam *bm; // beam casting the light int objnum; // object getting light cast on it ubyte source; // 0 to light the shooter, 1 for lighting any ship the beam passes, 2 to light the collision ship vec3d c_point; // collision point for type 2 lights } beam_light_info; beam_light_info Beam_lights[MAX_BEAM_LIGHT_INFO]; int Beam_light_count = 0; float b_whack_small = 2000.0f; // used to be 500.0f with the retail whack bug float b_whack_big = 10000.0f; // used to be 1500.0f with the retail whack bug float b_whack_damage = 150.0f; DCF(b_whack_small, "Sets the whack factor for small whacks (Default is 2000f)") { dc_stuff_float(&b_whack_small); } DCF(b_whack_big, "Sets the whack factor for big whacks (Default is 10000f)") { dc_stuff_float(&b_whack_big); } DCF(b_whack_damage, "Sets the whack damage threshold (Default is 150f)") { if (dc_optional_string_either("help", "--help")) { dc_printf("Sets the threshold to determine whether a big whack or a small whack should be applied. Values equal or greater than this threshold will trigger a big whack, while smaller values will trigger a small whack\n"); return; } dc_stuff_float(&b_whack_damage); } // ------------------------------------------------------------------------------------------------ // BEAM WEAPON FORWARD DECLARATIONS // // delete a beam void beam_delete(beam *b); // handle a hit on a specific object void beam_handle_collisions(beam *b); // fills in binfo void beam_get_binfo(beam* b, float accuracy, int num_shots, int burst_seed, float burst_shot_rotation, float per_burst_shot_rotation); // aim the beam (setup last_start and last_shot - the endpoints). also recalculates object collision info void beam_aim(beam *b); // direct fire type functions void beam_type_direct_fire_move(beam *b); // slashing type functions void beam_type_slashing_move(beam *b); // targeting type functions void beam_type_targeting_move(beam *b); // antifighter type functions void beam_type_antifighter_move(beam *b); // stuffs the index of the current pulse in shot_index // stuffs 0 in fire_wait if the beam is active, 1 if it is between pulses void beam_type_antifighter_get_status(beam *b, int *shot_index, int *fire_wait); // normal firing type functions void beam_type_normal_move(beam *b); // given a model #, and an object, stuff 2 good world coord points void beam_get_octant_points(int modelnum, object *objp, int oct_index, int oct_array[BEAM_NUM_GOOD_OCTANTS][4], vec3d *v1, vec3d *v2); // given an object, return its model num int beam_get_model(object *objp); // for rendering the beam effect // output top and bottom vectors // fvec == forward vector (eye viewpoint basically. in world coords) // pos == world coordinate of the point we're calculating "around" // w == width of the diff between top and bottom around pos void beam_calc_facing_pts(vec3d *top, vec3d *bot, vec3d *fvec, vec3d *pos, float w, float z_add); // render the muzzle glow for a beam weapon void beam_render_muzzle_glow(beam *b); // generate particles for the muzzle glow void beam_generate_muzzle_particles(beam *b); // throw some jitter into the aim - based upon shot_aim void beam_jitter_aim(beam *b, float aim); // if it is legal for the beam to continue firing // returns -1 if the beam should stop firing immediately // returns 0 if the beam should go to warmdown // returns 1 if the beam can continue along its way int beam_ok_to_fire(beam *b); // start the warmup phase for the beam void beam_start_warmup(beam *b); // start the firing phase for the beam, return 0 if the beam failed to start, and should be deleted altogether int beam_start_firing(beam *b); // start the warmdown phase for the beam void beam_start_warmdown(beam *b); // add a collision to the beam for this frame (to be evaluated later) void beam_add_collision(beam *b, object *hit_object, mc_info *cinfo, int quad = -1, bool exit_flag = false); // mark an object as being lit void beam_add_light(beam *b, int objnum, int source, vec3d *c_point); // apply lighting from any beams void beam_apply_lighting(); // recalculate beam sounds (looping sounds relative to the player) void beam_recalc_sounds(beam *b); // apply a whack to a ship void beam_apply_whack(beam *b, object *objp, vec3d *hit_point); // if the beam is likely to tool a given target before its lifetime expires int beam_will_tool_target(beam *b, object *objp); // ------------------------------------------------------------------------------------------------ // BEAM WEAPON FUNCTIONS // // init at game startup void beam_init() { beam_level_close(); } // initialize beam weapons for this level void beam_level_init() { // intialize beams int idx; Beam_count = 0; list_init( &Beam_free_list ); list_init( &Beam_used_list ); Beams.fill({}); // Link all object slots into the free list for (idx=0; idx<MAX_BEAMS; idx++) { Beams[idx].objnum = -1; list_append(&Beam_free_list, &Beams[idx] ); } // reset muzzle particle spew timestamp } // shutdown beam weapons for this level void beam_level_close() { // clear the beams list_init( &Beam_free_list ); list_init( &Beam_used_list ); } // get the width of the widest section of the beam float beam_get_widest(beam* b) { int idx; float widest = -1.0f; // sanity Assert(b->weapon_info_index >= 0); if (b->weapon_info_index < 0) { return -1.0f; } // lookup for (idx = 0; idx < Weapon_info[b->weapon_info_index].b_info.beam_num_sections; idx++) { if (Weapon_info[b->weapon_info_index].b_info.sections[idx].width > widest) { widest = Weapon_info[b->weapon_info_index].b_info.sections[idx].width; } } // return return widest; } // return false if the particular beam fire method doesn't have all the required, and specific to its fire method, info bool beam_has_valid_params(beam_fire_info* fire_info) { switch (fire_info->fire_method) { case BFM_TURRET_FIRED: if (fire_info->shooter == nullptr || fire_info->turret == nullptr || fire_info->target == nullptr) return false; break; case BFM_TURRET_FORCE_FIRED: if (fire_info->shooter == nullptr || fire_info->turret == nullptr || (fire_info->target == nullptr && !(fire_info->bfi_flags & BFIF_TARGETING_COORDS))) return false; break; case BFM_FIGHTER_FIRED: if (fire_info->shooter == nullptr || fire_info->turret == nullptr) return false; break; case BFM_SPAWNED: case BFM_SEXP_FLOATING_FIRED: if (!(fire_info->bfi_flags & BFIF_FLOATING_BEAM) || (fire_info->target == nullptr && !(fire_info->bfi_flags & BFIF_TARGETING_COORDS))) return false; break; case BFM_SUBSPACE_STRIKE: if (!(fire_info->bfi_flags & BFIF_FLOATING_BEAM) || (fire_info->target == nullptr)) return false; break; default: Assertion(false, "Unrecognized beam fire method in beam_has_valid_params"); return false; } // let's also validate the type of target, if applicable if (fire_info->target != nullptr) { if ((fire_info->target->type != OBJ_SHIP) && (fire_info->target->type != OBJ_ASTEROID) && (fire_info->target->type != OBJ_DEBRIS) && (fire_info->target->type != OBJ_WEAPON)) return false; } return true; } // fire a beam, returns nonzero on success. the innards of the code handle all the rest, foo int beam_fire(beam_fire_info *fire_info) { beam *new_item; weapon_info *wip; ship *firing_ship = NULL; int objnum; // sanity check if(fire_info == NULL){ Int3(); return -1; } // if we're out of beams, bail if(Beam_count >= MAX_BEAMS){ return -1; } // make sure the beam_info_index is valid if ((fire_info->beam_info_index < 0) || (fire_info->beam_info_index >= weapon_info_size()) || !(Weapon_info[fire_info->beam_info_index].wi_flags[Weapon::Info_Flags::Beam])) { UNREACHABLE("beam_info_index (%d) invalid (either <0, >= %d, or not actually a beam)!\n", fire_info->beam_info_index, weapon_info_size()); return -1; } wip = &Weapon_info[fire_info->beam_info_index]; // copied from weapon_create() if ((wip->num_substitution_patterns > 0) && (fire_info->shooter != nullptr)) { // using substitution // get to the instance of the gun Assertion(fire_info->shooter->type == OBJ_SHIP, "Expected type OBJ_SHIP, got %d", fire_info->shooter->type); Assertion((fire_info->shooter->instance < MAX_SHIPS) && (fire_info->shooter->instance >= 0), "Ship index is %d, which is out of range [%d,%d)", fire_info->shooter->instance, 0, MAX_SHIPS); ship* parent_shipp = &(Ships[fire_info->shooter->instance]); Assert(parent_shipp != nullptr); size_t* position = get_pointer_to_weapon_fire_pattern_index(fire_info->beam_info_index, fire_info->shooter->instance, fire_info->turret); Assertion(position != nullptr, "'%s' is trying to fire a weapon that is not selected", Ships[fire_info->shooter->instance].ship_name); size_t curr_pos = *position; if ((parent_shipp->flags[Ship::Ship_Flags::Primary_linked]) && curr_pos > 0) { curr_pos--; } ++(*position); *position = (*position) % wip->num_substitution_patterns; if (wip->weapon_substitution_pattern[curr_pos] == -1) { // weapon doesn't want any sub return -1; } else if (wip->weapon_substitution_pattern[curr_pos] != fire_info->beam_info_index) { fire_info->beam_info_index = wip->weapon_substitution_pattern[curr_pos]; // weapon wants to sub with weapon other than me return beam_fire(fire_info); } } if (!beam_has_valid_params(fire_info)) return -1; if (fire_info->shooter != NULL) { firing_ship = &Ships[fire_info->shooter->instance]; } // get a free beam new_item = GET_FIRST(&Beam_free_list); Assert( new_item != &Beam_free_list ); // shouldn't have the dummy element if(new_item == &Beam_free_list){ return -1; } // make sure that our textures are loaded as well extern bool weapon_is_used(int weapon_index); extern void weapon_load_bitmaps(int weapon_index); if ( !weapon_is_used(fire_info->beam_info_index) ) { weapon_load_bitmaps(fire_info->beam_info_index); } // remove from the free list list_remove( &Beam_free_list, new_item ); // insert onto the end of used list list_append( &Beam_used_list, new_item ); // increment counter Beam_count++; // fill in some values new_item->warmup_stamp = -1; new_item->warmdown_stamp = -1; new_item->weapon_info_index = fire_info->beam_info_index; new_item->objp = fire_info->shooter; new_item->sig = (fire_info->shooter != NULL) ? fire_info->shooter->signature : 0; new_item->subsys = fire_info->turret; new_item->life_left = wip->b_info.beam_life; new_item->life_total = wip->b_info.beam_life; new_item->r_collision_count = 0; new_item->f_collision_count = 0; new_item->target = fire_info->target; new_item->target_subsys = fire_info->target_subsys; new_item->target_sig = (fire_info->target != NULL) ? fire_info->target->signature : 0; new_item->beam_sound_loop = sound_handle::invalid(); new_item->type = wip->b_info.beam_type; new_item->local_fire_postion = fire_info->local_fire_postion; new_item->framecount = 0; new_item->flags = 0; new_item->shot_index = 0; new_item->current_width_factor = wip->b_info.beam_initial_width < 0.1f ? 0.1f : wip->b_info.beam_initial_width; new_item->team = (firing_ship == NULL) ? fire_info->team : static_cast<char>(firing_ship->team); new_item->range = wip->b_info.range; new_item->damage_threshold = wip->b_info.damage_threshold; new_item->bank = fire_info->bank; new_item->Beam_muzzle_stamp = -1; new_item->beam_glow_frame = 0.0f; new_item->firingpoint = (fire_info->bfi_flags & BFIF_FLOATING_BEAM) ? -1 : fire_info->turret->turret_next_fire_pos; new_item->last_start = fire_info->starting_pos; new_item->type5_rot_speed = wip->b_info.t5info.continuous_rot; new_item->rotates = wip->b_info.beam_type == BeamType::OMNI && wip->b_info.t5info.continuous_rot_axis != Type5BeamRotAxis::UNSPECIFIED; if (fire_info->bfi_flags & BFIF_FORCE_FIRING) new_item->flags |= BF_FORCE_FIRING; if (fire_info->bfi_flags & BFIF_IS_FIGHTER_BEAM) new_item->flags |= BF_IS_FIGHTER_BEAM; if (fire_info->bfi_flags & BFIF_FLOATING_BEAM) new_item->flags |= BF_FLOATING_BEAM; if (fire_info->bfi_flags & BFIF_TARGETING_COORDS) { new_item->flags |= BF_TARGETING_COORDS; new_item->target_pos1 = fire_info->target_pos1; new_item->target_pos2 = fire_info->target_pos2; } else { vm_vec_zero(&new_item->target_pos1); vm_vec_zero(&new_item->target_pos2); } for (float &frame : new_item->beam_section_frame) frame = 0.0f; // beam collision and light width if (wip->b_info.beam_width > 0.0f) { new_item->beam_collide_width = wip->b_info.beam_width; new_item->beam_light_width = wip->b_info.beam_width; } else { float widest = beam_get_widest(new_item); new_item->beam_collide_width = wip->collision_radius_override > 0.0f ? wip->collision_radius_override : widest; new_item->beam_light_width = widest; } if (fire_info->bfi_flags & BFIF_IS_FIGHTER_BEAM && new_item->type != BeamType::OMNI) { new_item->type = BeamType::TARGETING; } // if the targeted subsystem is not NULL, force it to be a direct fire beam if(new_item->target_subsys != nullptr && new_item->type != BeamType::TARGETING && new_item->type != BeamType::OMNI){ new_item->type = BeamType::DIRECT_FIRE; } // antifighter beam weapons can only fire at small ships and missiles if(new_item->type == BeamType::ANTIFIGHTER){ // if its a targeted ship, get the target ship if((fire_info->target != NULL) && (fire_info->target->type == OBJ_SHIP) && (fire_info->target->instance >= 0)){ ship *target_ship = &Ships[fire_info->target->instance]; // maybe force to be direct fire if(Ship_info[target_ship->ship_info_index].class_type > -1 && (Ship_types[Ship_info[target_ship->ship_info_index].class_type].flags[Ship::Type_Info_Flags::Beams_easily_hit])){ new_item->type = BeamType::DIRECT_FIRE; } } } // ---------------------------------------------------------------------- // THIS IS THE CRITICAL POINT FOR MULTIPLAYER // beam_get_binfo(...) determines exactly how the beam will behave over the course of its life // it fills in binfo, which we can pass to clients in multiplayer if(fire_info->beam_info_override != NULL){ new_item->binfo = *fire_info->beam_info_override; } else { float burst_rot = 0.0f; if (new_item->type == BeamType::OMNI && !wip->b_info.t5info.burst_rot_pattern.empty()) { burst_rot = wip->b_info.t5info.burst_rot_pattern[fire_info->burst_index]; } beam_get_binfo(new_item, fire_info->accuracy, wip->b_info.beam_shots,fire_info->burst_seed, burst_rot, fire_info->per_burst_rotation); // to fill in b_info - the set of directional aim vectors } flagset<Object::Object_Flags> default_flags; if (!wip->wi_flags[Weapon::Info_Flags::No_collide]) default_flags.set(Object::Object_Flags::Collides); // create the associated object objnum = obj_create(OBJ_BEAM, ((fire_info->shooter != NULL) ? OBJ_INDEX(fire_info->shooter) : -1), BEAM_INDEX(new_item), &vmd_identity_matrix, &vmd_zero_vector, 1.0f, default_flags); if(objnum < 0){ beam_delete(new_item); mprintf(("obj_create() failed for a beam weapon because you are running out of object slots!\n")); return -1; } new_item->objnum = objnum; if (new_item->objp != nullptr && Weapons_inherit_parent_collision_group) { Objects[objnum].collision_group_id = new_item->objp->collision_group_id; } // this sets up all info for the first frame the beam fires beam_aim(new_item); // to fill in shot_point, etc. // check to see if its legal to fire at this guy if (beam_ok_to_fire(new_item) != 1) { beam_delete(new_item); mprintf(("Killing beam at initial fire because of illegal targeting!!!\n")); return -1; } // if we're a multiplayer master - send a packet if (MULTIPLAYER_MASTER) { send_beam_fired_packet(fire_info, &new_item->binfo); } // start the warmup phase beam_start_warmup(new_item); return objnum; } // fire a targeting beam, returns objnum on success. a much much simplified version of a beam weapon // targeting lasers last _one_ frame. For a continuous stream - they must be created every frame. // this allows it to work smoothly in multiplayer (detect "trigger down". every frame just create a targeting laser firing straight out of the // object. this way you get all the advantages of nice rendering and collisions). // NOTE : only references beam_info_index and shooter int beam_fire_targeting(fighter_beam_fire_info *fire_info) { beam *new_item; weapon_info *wip; int objnum; ship *firing_ship; // sanity check if(fire_info == NULL){ Int3(); return -1; } // if we're out of beams, bail if(Beam_count >= MAX_BEAMS){ return -1; } // make sure the beam_info_index is valid Assert((fire_info->beam_info_index >= 0) && (fire_info->beam_info_index < weapon_info_size()) && (Weapon_info[fire_info->beam_info_index].wi_flags[Weapon::Info_Flags::Beam])); if((fire_info->beam_info_index < 0) || (fire_info->beam_info_index >= weapon_info_size()) || !(Weapon_info[fire_info->beam_info_index].wi_flags[Weapon::Info_Flags::Beam])){ return -1; } wip = &Weapon_info[fire_info->beam_info_index]; // make sure a ship is firing this Assert((fire_info->shooter->type == OBJ_SHIP) && (fire_info->shooter->instance >= 0) && (fire_info->shooter->instance < MAX_SHIPS)); if ( (fire_info->shooter->type != OBJ_SHIP) || (fire_info->shooter->instance < 0) || (fire_info->shooter->instance >= MAX_SHIPS) ) { return -1; } firing_ship = &Ships[fire_info->shooter->instance]; // get a free beam new_item = GET_FIRST(&Beam_free_list); Assert( new_item != &Beam_free_list ); // shouldn't have the dummy element // remove from the free list list_remove( &Beam_free_list, new_item ); // insert onto the end of used list list_append( &Beam_used_list, new_item ); // increment counter Beam_count++; // maybe allocate some extra data based on the beam type Assert(wip->b_info.beam_type == BeamType::TARGETING); if(wip->b_info.beam_type != BeamType::TARGETING){ return -1; } // fill in some values new_item->warmup_stamp = fire_info->warmup_stamp; new_item->warmdown_stamp = fire_info->warmdown_stamp; new_item->weapon_info_index = fire_info->beam_info_index; new_item->objp = fire_info->shooter; new_item->sig = fire_info->shooter->signature; new_item->subsys = NULL; new_item->life_left = fire_info->life_left; new_item->life_total = fire_info->life_total; new_item->r_collision_count = 0; new_item->f_collision_count = 0; new_item->target = NULL; new_item->target_subsys = NULL; new_item->target_sig = 0; new_item->beam_sound_loop = sound_handle::invalid(); new_item->type = BeamType::TARGETING; new_item->local_fire_postion = fire_info->local_fire_postion; new_item->framecount = 0; new_item->flags = 0; new_item->shot_index = 0; new_item->current_width_factor = wip->b_info.beam_initial_width < 0.1f ? 0.1f : wip->b_info.beam_initial_width; new_item->team = (char)firing_ship->team; new_item->range = wip->b_info.range; new_item->damage_threshold = wip->b_info.damage_threshold; // beam collision and light width if (wip->b_info.beam_width > 0.0f) { new_item->beam_collide_width = wip->b_info.beam_width; new_item->beam_light_width = wip->b_info.beam_width; } else { float widest = beam_get_widest(new_item); new_item->beam_collide_width = wip->collision_radius_override > 0.0f ? wip->collision_radius_override : widest; new_item->beam_light_width = widest; } // targeting type beams are a very special weapon type - binfo has no meaning flagset<Object::Object_Flags> initial_flags; if (!wip->wi_flags[Weapon::Info_Flags::No_collide]) initial_flags.set(Object::Object_Flags::Collides); // create the associated object objnum = obj_create(OBJ_BEAM, OBJ_INDEX(fire_info->shooter), BEAM_INDEX(new_item), &vmd_identity_matrix, &vmd_zero_vector, 1.0f, initial_flags); if(objnum < 0){ beam_delete(new_item); nprintf(("General", "obj_create() failed for beam weapon! bah!\n")); Int3(); return -1; } new_item->objnum = objnum; // this sets up all info for the first frame the beam fires beam_aim(new_item); // to fill in shot_point, etc. if(Beams[Objects[objnum].instance].objnum != objnum){ Int3(); return -1; } return objnum; } // return an object index of the guy who's firing this beam int beam_get_parent(object *bm) { beam *b; // get a handle to the beam Assert(bm->type == OBJ_BEAM); Assert(bm->instance >= 0); if(bm->type != OBJ_BEAM){ return -1; } if(bm->instance < 0){ return -1; } b = &Beams[bm->instance]; if(b->objp == NULL){ return -1; } // if the object handle is invalid if(b->objp->signature != b->sig){ return -1; } // return the handle return OBJ_INDEX(b->objp); } // return weapon_info_index of beam int beam_get_weapon_info_index(object *bm) { Assert(bm->type == OBJ_BEAM); if (bm->type != OBJ_BEAM) { return -1; } Assert(bm->instance >= 0 && bm->instance < MAX_BEAMS); if (bm->instance < 0) { return -1; } //make sure it's returning a valid info index Assert((Beams[bm->instance].weapon_info_index > -1) && (Beams[bm->instance].weapon_info_index < weapon_info_size())); // return weapon_info_index return Beams[bm->instance].weapon_info_index; } // given a beam object, get the # of collisions which happened during the last collision check (typically, last frame) int beam_get_num_collisions(int objnum) { // sanity checks if((objnum < 0) || (objnum >= MAX_OBJECTS)){ Int3(); return -1; } if((Objects[objnum].instance < 0) || (Objects[objnum].instance >= MAX_BEAMS)){ Int3(); return -1; } if(Beams[Objects[objnum].instance].objnum != objnum){ Int3(); return -1; } if(Beams[Objects[objnum].instance].objnum < 0){ Int3(); return -1; } // return the # of recent collisions return Beams[Objects[objnum].instance].r_collision_count; } // stuff collision info, returns 1 on success int beam_get_collision(int objnum, int num, int *collision_objnum, mc_info **cinfo) { // sanity checks if((objnum < 0) || (objnum >= MAX_OBJECTS)){ Int3(); return 0; } if((Objects[objnum].instance < 0) || (Objects[objnum].instance >= MAX_BEAMS)){ Int3(); return 0; } if((Beams[Objects[objnum].instance].objnum != objnum) || (Beams[Objects[objnum].instance].objnum < 0)){ Int3(); return 0; } if(num >= Beams[Objects[objnum].instance].r_collision_count){ Int3(); return 0; } // return - success *cinfo = &Beams[Objects[objnum].instance].r_collisions[num].cinfo; *collision_objnum = Beams[Objects[objnum].instance].r_collisions[num].c_objnum; return 1; } // pause all looping beam sounds void beam_pause_sounds() { beam *moveup = NULL; // set all beam volumes to 0 moveup = GET_FIRST(&Beam_used_list); if(moveup == NULL){ return; } while(moveup != END_OF_LIST(&Beam_used_list)){ // set the volume to 0, if he has a looping beam sound if (moveup->beam_sound_loop.isValid()) { snd_set_volume(moveup->beam_sound_loop, 0.0f); } // next beam moveup = GET_NEXT(moveup); } } // unpause looping beam sounds void beam_unpause_sounds() { beam *moveup = NULL; // recalc all beam sounds moveup = GET_FIRST(&Beam_used_list); if(moveup == NULL){ return; } while(moveup != END_OF_LIST(&Beam_used_list)){ if (Cmdline_no_3d_sound) { beam_recalc_sounds(moveup); } else { if (moveup->beam_sound_loop.isValid()) { snd_set_volume(moveup->beam_sound_loop, 1.0f); } } // next beam moveup = GET_NEXT(moveup); } } void beam_get_global_turret_gun_info(object *objp, ship_subsys *ssp, vec3d *gpos, vec3d *gvec, int use_angles, vec3d *targetp, bool fighter_beam) { ship_get_global_turret_gun_info(objp, ssp, gpos, gvec, use_angles, targetp); if (fighter_beam) *gvec = objp->orient.vec.fvec; } // -----------------------------===========================------------------------------ // BEAM MOVEMENT FUNCTIONS // -----------------------------===========================------------------------------ // move a direct fire type beam weapon void beam_type_direct_fire_move(beam *b) { vec3d dir; vec3d temp, temp2; // LEAVE THIS HERE OTHERWISE MUZZLE GLOWS DRAW INCORRECTLY WHEN WARMING UP OR DOWN // get the "originating point" of the beam for this frame. essentially bashes last_start if (b->subsys != NULL) beam_get_global_turret_gun_info(b->objp, b->subsys, &b->last_start, &temp, 1, &temp2, (b->flags & BF_IS_FIGHTER_BEAM) > 0); // if the "warming up" timestamp has not expired if((b->warmup_stamp != -1) || (b->warmdown_stamp != -1)){ return; } // put the "last_shot" point arbitrarily far away vm_vec_sub(&dir, &b->last_shot, &b->last_start); vm_vec_normalize_quick(&dir); vm_vec_scale_add(&b->last_shot, &b->last_start, &dir, b->range); Assert(is_valid_vec(&b->last_shot)); } // move a slashing type beam weapon #define BEAM_T(b) ((b->life_total - b->life_left) / b->life_total) void beam_type_slashing_move(beam *b) { vec3d actual_dir; vec3d temp, temp2; float dot_save; // LEAVE THIS HERE OTHERWISE MUZZLE GLOWS DRAW INCORRECTLY WHEN WARMING UP OR DOWN // get the "originating point" of the beam for this frame. essentially bashes last_start if (b->subsys != NULL) beam_get_global_turret_gun_info(b->objp, b->subsys, &b->last_start, &temp, 1, &temp2, (b->flags & BF_IS_FIGHTER_BEAM) > 0); // if the "warming up" timestamp has not expired if((b->warmup_stamp != -1) || (b->warmdown_stamp != -1)){ return; } // if the two direction vectors are _really_ close together, just use the original direction dot_save = vm_vec_dot(&b->binfo.dir_a, &b->binfo.dir_b); if((double)dot_save >= 0.999999999){ actual_dir = b->binfo.dir_a; } // otherwise move towards the dir we calculated when firing this beam else { vm_vec_interp_constant(&actual_dir, &b->binfo.dir_a, &b->binfo.dir_b, BEAM_T(b)); } // now recalculate shot_point to be shooting through our new point vm_vec_scale_add(&b->last_shot, &b->last_start, &actual_dir, b->range); bool is_valid = is_valid_vec(&b->last_shot); Assert(is_valid); if(!is_valid){ actual_dir = b->binfo.dir_a; vm_vec_scale_add(&b->last_shot, &b->last_start, &actual_dir, b->range); } } // targeting type beams functions void beam_type_targeting_move(beam *b) { vec3d temp; // ugh if ( (b->objp == NULL) || (b->objp->instance < 0) ) { Int3(); return; } // targeting type beams only last one frame so we never have to "move" them. temp = b->local_fire_postion; vm_vec_unrotate(&b->last_start, &temp, &b->objp->orient); vm_vec_add2(&b->last_start, &b->objp->pos); vm_vec_scale_add(&b->last_shot, &b->last_start, &b->objp->orient.vec.fvec, b->range); } // antifighter type beam functions void beam_type_antifighter_move(beam *b) { int shot_index, fire_wait; vec3d temp, temp2, dir; // LEAVE THIS HERE OTHERWISE MUZZLE GLOWS DRAW INCORRECTLY WHEN WARMING UP OR DOWN // get the "originating point" of the beam for this frame. essentially bashes last_start if (b->subsys != NULL) beam_get_global_turret_gun_info(b->objp, b->subsys, &b->last_start, &temp, 1, &temp2, (b->flags & BF_IS_FIGHTER_BEAM) > 0); // if the "warming up" timestamp has not expired if((b->warmup_stamp != -1) || (b->warmdown_stamp != -1)){ return; } // determine what stage of the beam we're in beam_type_antifighter_get_status(b, &shot_index, &fire_wait); // if we've changed shot index if(shot_index != b->shot_index){ // set the new index b->shot_index = shot_index; // re-aim beam_aim(b); } // if we're in the fire wait stage b->flags &= ~BF_SAFETY; if(fire_wait){ b->flags |= BF_SAFETY; } // put the "last_shot" point arbitrarily far away vm_vec_sub(&dir, &b->last_shot, &b->last_start); vm_vec_normalize_quick(&dir); vm_vec_scale_add(&b->last_shot, &b->last_start, &dir, b->range); Assert(is_valid_vec(&b->last_shot)); } void beam_type_antifighter_get_status(beam *b, int *shot_index, int *fire_wait) { float shot_time = b->life_total / (float)b->binfo.shot_count; float beam_time = b->life_total - b->life_left; // determine what "shot" we're on *shot_index = (int)(beam_time / shot_time); if(*shot_index >= b->binfo.shot_count){ nprintf(("Beam","Shot of antifighter beam had bad shot_index value\n")); *shot_index = b->binfo.shot_count - 1; } // determine if its the firing or waiting section of the shot (fire happens first, THEN wait) *fire_wait = 0; if(beam_time > ((shot_time * (*shot_index)) + (shot_time * 0.5f))){ *fire_wait = 1; } } // down-the-normal type beam functions void beam_type_normal_move(beam *b) { vec3d temp, turret_norm; if (b->subsys == NULL) { // If we're a free-floating beam, there's nothing to calculate here. return; } // LEAVE THIS HERE OTHERWISE MUZZLE GLOWS DRAW INCORRECTLY WHEN WARMING UP OR DOWN // get the "originating point" of the beam for this frame. essentially bashes last_start beam_get_global_turret_gun_info(b->objp, b->subsys, &b->last_start, &turret_norm, 1, &temp, (b->flags & BF_IS_FIGHTER_BEAM) > 0); // if the "warming up" timestamp has not expired if((b->warmup_stamp != -1) || (b->warmdown_stamp != -1)){ return; } // put the "last_shot" point arbitrarily far away vm_vec_scale_add(&b->last_shot, &b->last_start, &turret_norm, b->range); Assert(is_valid_vec(&b->last_shot)); } void beam_type_omni_move(beam* b) { // keep this updated even if still warming up if (b->flags & BF_IS_FIGHTER_BEAM) { vm_vec_unrotate(&b->last_start, &b->local_fire_postion, &b->objp->orient); vm_vec_add2(&b->last_start, &b->objp->pos); // compute the change in orientation the fighter went through matrix inv_new_orient, transform_matrix; vm_copy_transpose(&inv_new_orient, &b->objp->orient); vm_matrix_x_matrix(&transform_matrix, &b->objp->last_orient, &inv_new_orient); // and put the beam vectors through the same change vec3d old_dirA = b->binfo.dir_a; vec3d old_dirB = b->binfo.dir_b; vec3d old_rot_axis = b->binfo.rot_axis; vm_vec_rotate(&b->binfo.dir_a, &old_dirA, &transform_matrix); vm_vec_rotate(&b->binfo.dir_b, &old_dirB, &transform_matrix); vm_vec_rotate(&b->binfo.rot_axis, &old_rot_axis, &transform_matrix); } else if (b->subsys != nullptr) { vec3d temp, temp2; beam_get_global_turret_gun_info(b->objp, b->subsys, &b->last_start, &temp, 1, &temp2, false); } // if the "warming up" timestamp has not expired if ((b->warmup_stamp != -1) || (b->warmdown_stamp != -1)) { return; } vec3d newdir_a = b->binfo.dir_a; vec3d newdir_b = b->binfo.dir_b; vec3d zero_vec = vmd_zero_vector; vec3d actual_dir; bool no_sweep = vm_vec_dot(&b->binfo.dir_a, &b->binfo.dir_b) > 0.9999f; if (b->rotates) { vm_rot_point_around_line(&newdir_a, &b->binfo.dir_a, (b->life_total - b->life_left) * b->type5_rot_speed, &zero_vec, &b->binfo.rot_axis); if (no_sweep) actual_dir = newdir_a; else vm_rot_point_around_line(&newdir_b, &b->binfo.dir_b, (b->life_total - b->life_left) * b->type5_rot_speed, &zero_vec, &b->binfo.rot_axis); } if (no_sweep) actual_dir = newdir_a; else vm_vec_interp_constant(&actual_dir, &newdir_a, &newdir_b, BEAM_T(b)); // now recalculate shot_point to be shooting through our new point vm_vec_scale_add(&b->last_shot, &b->last_start, &actual_dir, b->range); } // pre-move (before collision checking - but AFTER ALL OTHER OBJECTS HAVE BEEN MOVED) void beam_move_all_pre() { beam *b; beam *moveup; // zero lights for this frame yet Beam_light_count = 0; // traverse through all active beams moveup = GET_FIRST(&Beam_used_list); while (moveup != END_OF_LIST(&Beam_used_list)) { // get the beam b = moveup; // check if parent object has died, if so then delete beam if (b->objp != NULL && b->objp->type == OBJ_NONE) { // set next beam moveup = GET_NEXT(moveup); // delete current beam beam_delete(b); continue; } // unset collision info b->f_collision_count = 0; if ( !physics_paused ) { // make sure to check that firingpoint is still properly set int temp = -1; if (b->subsys != NULL) { temp = b->subsys->turret_next_fire_pos; if (!(b->flags & BF_IS_FIGHTER_BEAM)) b->subsys->turret_next_fire_pos = b->firingpoint; } // move the beam switch (b->type) { // direct fire type beam weapons don't move case BeamType::DIRECT_FIRE : beam_type_direct_fire_move(b); break; // slashing type beam weapons move across the target somewhat randomly case BeamType::SLASHING: beam_type_slashing_move(b); break; // targeting type beam weapons are attached to a fighter - pointing forward case BeamType::TARGETING: beam_type_targeting_move(b); break; // antifighter type case BeamType::ANTIFIGHTER: beam_type_antifighter_move(b); break; // down-the-normal type beams case BeamType::NORMAL_FIRE: beam_type_normal_move(b); break; case BeamType::OMNI: beam_type_omni_move(b); break; // illegal beam type default : Int3(); } if (b->subsys != NULL) { b->subsys->turret_next_fire_pos = temp; } } // next moveup = GET_NEXT(moveup); } } // post-collision time processing for beams void beam_move_all_post() { beam *moveup; beam *next_one; int bf_status; beam_weapon_info *bwi; // traverse through all active beams moveup = GET_FIRST(&Beam_used_list); while(moveup != END_OF_LIST(&Beam_used_list)){ bwi = &Weapon_info[moveup->weapon_info_index].b_info; // check the status of the beam bf_status = beam_ok_to_fire(moveup); // if we're warming up if(moveup->warmup_stamp != -1){ next_one = GET_NEXT(moveup); // should we be stopping? if(bf_status < 0){ beam_delete(moveup); } else { if (moveup->objp != NULL) { // add a muzzle light for the shooter beam_add_light(moveup, OBJ_INDEX(moveup->objp), 0, NULL); } // if the warming up timestamp has expired, start firing if(timestamp_elapsed(moveup->warmup_stamp)){ // start firing if(!beam_start_firing(moveup)){ beam_delete(moveup); } } } // next moveup = next_one; continue; } // if we're warming down else if(moveup->warmdown_stamp != -1){ next_one = GET_NEXT(moveup); // should we be stopping? if(bf_status < 0){ beam_delete(moveup); } else { if (moveup->objp != NULL) { // add a muzzle light for the shooter beam_add_light(moveup, OBJ_INDEX(moveup->objp), 0, NULL); } // if we're done warming down, the beam is finished if(timestamp_elapsed(moveup->warmdown_stamp)){ beam_delete(moveup); } } // next moveup = next_one; continue; } // otherwise, we're firing away......... if (moveup->objp != NULL) { // add a muzzle light for the shooter beam_add_light(moveup, OBJ_INDEX(moveup->objp), 0, NULL); } // subtract out the life left for the beam if(!physics_paused){ moveup->life_left -= flFrametime; } // if we're past the shrink point, start shrinking the beam if(moveup->life_left <= (moveup->life_total * bwi->beam_shrink_factor)){ moveup->flags |= BF_SHRINK; } // if we're shrinking the beam if(moveup->flags & BF_SHRINK){ moveup->current_width_factor -= bwi->beam_shrink_pct * flFrametime; if(moveup->current_width_factor < 0.1f){ moveup->current_width_factor = 0.1f; } } // if we're past the grow point and haven't already finished growing, start growing the beam if (moveup->life_left <= (moveup->life_total * bwi->beam_grow_factor) && !(moveup->flags & BF_FINISHED_GROWING)) { moveup->flags |= BF_GROW; } // if we're growing the beam (but not shrinking yet) if ((moveup->flags & BF_GROW) && !(moveup->flags & BF_SHRINK)) { moveup->current_width_factor += bwi->beam_grow_pct * flFrametime; if (moveup->current_width_factor > 1.0f) { // We've finished growing! moveup->current_width_factor = 1.0f; moveup->flags &= ~BF_GROW; moveup->flags |= BF_FINISHED_GROWING; } } // add tube light for the beam if (moveup->objp != nullptr) { if (moveup->type == BeamType::ANTIFIGHTER) { //we only use the second variable but we need two pointers to pass. int beam_index, beam_waiting = 0; beam_type_antifighter_get_status(moveup, &beam_index, &beam_waiting); //create a tube light only if we are not waiting between shots if (beam_waiting == 0) { beam_add_light(moveup, OBJ_INDEX(moveup->objp), 1, nullptr); } } else { beam_add_light(moveup, OBJ_INDEX(moveup->objp), 1, nullptr); } } // deal with ammo/energy for fighter beams bool multi_ai = MULTIPLAYER_CLIENT && (moveup->objp != Player_obj); bool cheating_player = Weapon_energy_cheat && (moveup->objp == Player_obj); if (moveup->flags & BF_IS_FIGHTER_BEAM && !multi_ai && !cheating_player) { ship* shipp = &Ships[moveup->objp->instance]; weapon_info* wip = &Weapon_info[moveup->weapon_info_index]; shipp->weapon_energy -= wip->energy_consumed * flFrametime; if (shipp->weapon_energy < 0.0f) shipp->weapon_energy = 0.0f; } // stop shooting? if(bf_status <= 0){ next_one = GET_NEXT(moveup); // if beam should abruptly stop if(bf_status == -1){ beam_delete(moveup); } // if the beam should just power down else { beam_start_warmdown(moveup); } // next beam moveup = next_one; continue; } // increment framecount moveup->framecount++; // targetin type weapons live for one frame only // done firing, so go into the warmdown phase { if((moveup->life_left <= 0.0f) && (moveup->warmdown_stamp == -1) && (moveup->framecount > 1)) { beam_start_warmdown(moveup); moveup = GET_NEXT(moveup); continue; } } // handle any collisions which occured collision (will take care of applying damage to all objects which got hit) beam_handle_collisions(moveup); // recalculate beam sounds beam_recalc_sounds(moveup); // next item moveup = GET_NEXT(moveup); } // apply all beam lighting beam_apply_lighting(); } // -----------------------------===========================------------------------------ // BEAM RENDERING FUNCTIONS // -----------------------------===========================------------------------------ // render a beam weapon #define STUFF_VERTICES() do {\ verts[0]->texture_position.u = 0.0f;\ verts[0]->texture_position.v = 0.0f;\ verts[1]->texture_position.u = 1.0f;\ verts[1]->texture_position.v = 0.0f;\ verts[2]->texture_position.u = 1.0f;\ verts[2]->texture_position.v = 1.0f;\ verts[3]->texture_position.u = 0.0f;\ verts[3]->texture_position.v = 1.0f;\ } while(false); #define P_VERTICES() do {\ for(idx=0; idx<4; idx++){\ g3_project_vertex(verts[idx]);\ }\ } while(false); void beam_render(beam *b, float u_offset) { int idx, s_idx; vertex h1[4]; // halves of a beam section vertex *verts[4] = { &h1[0], &h1[1], &h1[2], &h1[3] }; vec3d fvec, top1, bottom1, top2, bottom2; float scale; float u_scale; // beam tileing -Bobboau float length; // beam tileing -Bobboau beam_weapon_section_info *bwsi; beam_weapon_info *bwi; memset( h1, 0, sizeof(vertex) * 4 ); // bogus weapon info index if ( (b == NULL) || (b->weapon_info_index < 0) ) return; // if the beam start and endpoints are the same if ( vm_vec_same(&b->last_start, &b->last_shot) ) return; // get beam direction vm_vec_sub(&fvec, &b->last_shot, &b->last_start); vm_vec_normalize_quick(&fvec); // turn off backface culling //int cull = gr_set_cull(0); length = vm_vec_dist(&b->last_start, &b->last_shot); // beam tileing -Bobboau bwi = &Weapon_info[b->weapon_info_index].b_info; // if this beam tracks its own u_offset, use that instead if (bwi->flags[Weapon::Beam_Info_Flags::Track_own_texture_tiling]) { u_offset = b->u_offset_local; // the parameter is passed by value so this won't interfere with the u_offset in the calling function b->u_offset_local += flFrametime; // increment *after* we grab the offset so that the first frame will always be at offset=0 } // draw all sections for (s_idx = 0; s_idx < bwi->beam_num_sections; s_idx++) { bwsi = &bwi->sections[s_idx]; if ( (bwsi->texture.first_frame < 0) || (bwsi->width <= 0.0f) ) continue; // calculate the beam points scale = frand_range(1.0f - bwsi->flicker, 1.0f + bwsi->flicker); beam_calc_facing_pts(&top1, &bottom1, &fvec, &b->last_start, bwsi->width * scale * b->current_width_factor, bwsi->z_add); beam_calc_facing_pts(&top2, &bottom2, &fvec, &b->last_shot, bwsi->width * scale * scale * b->current_width_factor, bwsi->z_add); g3_transfer_vertex(verts[0], &bottom1); g3_transfer_vertex(verts[1], &bottom2); g3_transfer_vertex(verts[2], &top2); g3_transfer_vertex(verts[3], &top1); P_VERTICES(); STUFF_VERTICES(); // stuff the beam with creamy goodness (texture coords) if (bwsi->tile_type == 1) u_scale = length / (bwsi->width * 0.5f) / bwsi->tile_factor; // beam tileing, might make a tileing factor in beam index later -Bobboau else u_scale = bwsi->tile_factor; verts[1]->texture_position.u = (u_scale + (u_offset * bwsi->translation)); // beam tileing -Bobboau verts[2]->texture_position.u = (u_scale + (u_offset * bwsi->translation)); // beam tileing -Bobboau verts[3]->texture_position.u = (0 + (u_offset * bwsi->translation)); verts[0]->texture_position.u = (0 + (u_offset * bwsi->translation)); float per = 1.0f; if (bwi->range) per -= length / bwi->range; //this should never happen but, just to be safe CLAMP(per, 0.0f, 1.0f); ubyte alpha = (ubyte)(255.0f * per); verts[1]->r = alpha; verts[2]->r = alpha; verts[1]->g = alpha; verts[2]->g = alpha; verts[1]->b = alpha; verts[2]->b = alpha; verts[1]->a = alpha; verts[2]->a = alpha; verts[0]->r = 255; verts[3]->r = 255; verts[0]->g = 255; verts[3]->g = 255; verts[0]->b = 255; verts[3]->b = 255; verts[0]->a = 255; verts[3]->a = 255; // set the right texture with additive alpha, and draw the poly int framenum = 0; if (bwsi->texture.num_frames > 1) { b->beam_section_frame[s_idx] += flFrametime; framenum = bm_get_anim_frame(bwsi->texture.first_frame, b->beam_section_frame[s_idx], bwsi->texture.total_time, true); } float fade = 0.9999f; if (The_mission.flags[Mission::Mission_Flags::Fullneb] && Neb_affects_beams) { vec3d nearest; int result = vm_vec_dist_to_line(&Eye_position, &b->last_start, &b->last_shot, &nearest, nullptr); if (result == 1) nearest = b->last_shot; if (result == -1) nearest = b->last_start; fade *= neb2_get_fog_visibility(&nearest, NEB_FOG_VISIBILITY_MULT_BEAM(b->beam_light_width)); } material material_params; material_set_unlit_emissive(&material_params, bwsi->texture.first_frame + framenum, fade, 2.0f); g3_render_primitives_colored_textured(&material_params, h1, 4, PRIM_TYPE_TRIFAN, false); } // turn backface culling back on //gr_set_cull(cull); } // generate particles for the muzzle glow int hack_time = 100; DCF(h_time, "Sets the hack time for beam muzzle glow (Default is 100)") { dc_stuff_int(&hack_time); } void beam_generate_muzzle_particles(beam *b) { int particle_count; int idx; weapon_info *wip; vec3d turret_norm, turret_pos, particle_pos, particle_dir; matrix m; // if our hack stamp has expired if(!((b->Beam_muzzle_stamp == -1) || timestamp_elapsed(b->Beam_muzzle_stamp))){ return; } // never generate anything past about 1/5 of the beam fire time if(b->warmup_stamp == -1){ return; } // get weapon info wip = &Weapon_info[b->weapon_info_index]; // no specified particle for this beam weapon if (wip->b_info.beam_particle_ani.first_frame < 0) return; // reset the hack stamp b->Beam_muzzle_stamp = timestamp(hack_time); // randomly generate 10 to 20 particles particle_count = (int)frand_range(0.0f, (float)wip->b_info.beam_particle_count); // get turret info - position and normal turret_pos = b->last_start; if (b->subsys != NULL) { turret_norm = b->subsys->system_info->turret_norm; } else { vm_vec_normalized_dir(&turret_norm, &b->last_shot, &b->last_start); } // randomly perturb a vector within a cone around the normal vm_vector_2_matrix(&m, &turret_norm, NULL, NULL); for(idx=0; idx<particle_count; idx++){ // get a random point in the cone vm_vec_random_cone(&particle_dir, &turret_norm, wip->b_info.beam_particle_angle, &m); vm_vec_scale_add(&particle_pos, &turret_pos, &particle_dir, wip->b_info.beam_muzzle_radius * frand_range(0.75f, 0.9f)); // now generate some interesting values for the particle float p_time_ref = wip->b_info.beam_life + ((float)wip->b_info.beam_warmup / 1000.0f); float p_life = frand_range(p_time_ref * 0.5f, p_time_ref * 0.7f); float p_vel = (wip->b_info.beam_muzzle_radius / p_life) * frand_range(0.85f, 1.2f); vm_vec_scale(&particle_dir, -p_vel); if (b->objp != NULL) { vm_vec_add2(&particle_dir, &b->objp->phys_info.vel); //move along with our parent } particle::particle_info pinfo; pinfo.pos = particle_pos; pinfo.vel = particle_dir; pinfo.lifetime = p_life; pinfo.attached_objnum = -1; pinfo.attached_sig = 0; pinfo.rad = wip->b_info.beam_particle_radius; pinfo.reverse = 1; pinfo.type = particle::PARTICLE_BITMAP; pinfo.optional_data = wip->b_info.beam_particle_ani.first_frame; particle::create(&pinfo); } } static float get_muzzle_glow_alpha(beam* b) { float dist; float alpha = 0.8f; const float inner_radius = 15.0f; const float magic_num = 2.75f; // determine what alpha to draw this bitmap with // higher alpha the closer the bitmap gets to the eye dist = vm_vec_dist_quick(&Eye_position, &b->last_start); // if the point is inside the inner radius, alpha is based on distance to the player's eye, // becoming more transparent as it gets close if (dist <= inner_radius) { // alpha per meter between the magic # and the inner radius alpha /= (inner_radius - magic_num); // above value times the # of meters away we are alpha *= (dist - magic_num); if (alpha < 0.005f) return 0.0f; } if (The_mission.flags[Mission::Mission_Flags::Fullneb] && Neb_affects_beams) { alpha *= neb2_get_fog_visibility(&b->last_start, NEB_FOG_VISIBILITY_MULT_B_MUZZLE(b->beam_light_width)); } return alpha; } // render the muzzle glow for a beam weapon void beam_render_muzzle_glow(beam *b) { vertex pt; weapon_info *wip = &Weapon_info[b->weapon_info_index]; beam_weapon_info *bwi = &wip->b_info; float rad, pct, rand_val; pt.flags = 0; // avoid potential read of uninit var // if we don't have a glow bitmap if (bwi->beam_glow.first_frame < 0) return; // don't show the muzzle glow for players in the cockpit unless show_ship_model is on, provided Render_player_mflash isn't on bool in_cockpit_view = (Viewer_mode & (VM_EXTERNAL | VM_CHASE | VM_OTHER_SHIP | VM_WARP_CHASE)) == 0; bool player_show_ship_model = b->objp == Player_obj && Ship_info[Ships[b->objp->instance].ship_info_index].flags[Ship::Info_Flags::Show_ship_model]; if ((b->flags & BF_IS_FIGHTER_BEAM) && (b->objp == Player_obj && !Render_player_mflash && in_cockpit_view && !player_show_ship_model)) { return; } // if the beam is warming up, scale the glow if (b->warmup_stamp != -1) { // get warmup pct pct = BEAM_WARMUP_PCT(b); rand_val = 1.0f; } else // if the beam is warming down if (b->warmdown_stamp != -1) { // get warmup pct pct = 1.0f - BEAM_WARMDOWN_PCT(b); rand_val = 1.0f; } // otherwise the beam is really firing else { pct = 1.0f; rand_val = frand_range(0.90f, 1.0f); } rad = wip->b_info.beam_muzzle_radius * pct * rand_val; // don't bother trying to draw if there is no radius if (rad <= 0.0f) return; float alpha = get_muzzle_glow_alpha(b); if (alpha <= 0.0f) return; if (bwi->directional_glow == true){ vertex h1[4]; vertex *verts[4] = { &h1[0], &h1[1], &h1[2], &h1[3] }; vec3d fvec, top1, top2, bottom1, bottom2, sub1, sub2, start, end; int idx; float g_length = bwi->glow_length * pct * rand_val; vm_vec_sub(&fvec, &b->last_shot, &b->last_start); vm_vec_normalize_quick(&fvec); /* (DahBlount) If the glow_length is less than the diameter of the muzzle glow we need to account for that by placing the start and end distances such that the glow is centered on the firing point of the turret. There was actually some oversight here when developing the directional glow feature and any refactoring of it will require some more complex parameters for glow placement. */ if (bwi->glow_length >= 2.0f*rad) { vm_vec_copy_scale(&sub1, &fvec, rad); vm_vec_sub(&start, &b->last_start, &sub1); vm_vec_copy_scale(&sub2, &fvec, g_length); vm_vec_add(&end, &start, &sub2); } else { vm_vec_copy_scale(&sub1, &fvec, 0.5f*g_length); vm_vec_sub(&start, &b->last_start, &sub1); vm_vec_add(&end, &b->last_start, &sub1); } beam_calc_facing_pts(&top1, &bottom1, &fvec, &start, rad, 1.0f); beam_calc_facing_pts(&top2, &bottom2, &fvec, &end, rad, 1.0f); g3_transfer_vertex(verts[0], &bottom1); g3_transfer_vertex(verts[1], &bottom2); g3_transfer_vertex(verts[2], &top2); g3_transfer_vertex(verts[3], &top1); P_VERTICES(); STUFF_VERTICES(); verts[0]->r = 255; verts[1]->r = 255; verts[2]->r = 255; verts[3]->r = 255; verts[0]->g = 255; verts[1]->g = 255; verts[2]->g = 255; verts[3]->g = 255; verts[0]->b = 255; verts[1]->b = 255; verts[2]->b = 255; verts[3]->b = 255; verts[0]->a = 255; verts[1]->a = 255; verts[2]->a = 255; verts[3]->a = 255; int framenum = 0; if ( bwi->beam_glow.num_frames > 1 ) { b->beam_glow_frame += flFrametime; framenum = bm_get_anim_frame(bwi->beam_glow.first_frame, b->beam_glow_frame, bwi->beam_glow.total_time, true); } //gr_set_bitmap(bwi->beam_glow.first_frame + framenum, GR_ALPHABLEND_FILTER, GR_BITBLT_MODE_NORMAL, alpha * pct); // draw a poly //g3_draw_poly(4, verts, TMAP_FLAG_TEXTURED | TMAP_FLAG_CORRECT | TMAP_HTL_3D_UNLIT); material material_info; material_set_unlit_emissive(&material_info, bwi->beam_glow.first_frame + framenum, alpha * pct, 2.0f); g3_render_primitives_textured(&material_info, h1, 4, PRIM_TYPE_TRIFAN, false); } else { // draw the bitmap g3_transfer_vertex(&pt, &b->last_start); int framenum = 0; if ( bwi->beam_glow.num_frames > 1 ) { b->beam_glow_frame += flFrametime; framenum = bm_get_anim_frame(bwi->beam_glow.first_frame, b->beam_glow_frame, bwi->beam_glow.total_time, true); } //gr_set_bitmap(bwi->beam_glow.first_frame + framenum, GR_ALPHABLEND_FILTER, GR_BITBLT_MODE_NORMAL, alpha * pct); // draw 1 bitmap //g3_draw_bitmap(&pt, 0, rad, tmap_flags); material mat_params; material_set_unlit_emissive(&mat_params, bwi->beam_glow.first_frame + framenum, alpha * pct, 2.0f); g3_render_rect_screen_aligned(&mat_params, &pt, 0, rad, 0.0f); // maybe draw more if ( pct > 0.3f ) { //g3_draw_bitmap(&pt, 0, rad * 0.75f, tmap_flags, rad * 0.25f); g3_render_rect_screen_aligned(&mat_params, &pt, 0, rad * 0.75f, rad * 0.25f); } if ( pct > 0.5f ) { //g3_draw_bitmap(&pt, 0, rad * 0.45f, tmap_flags, rad * 0.55f); g3_render_rect_screen_aligned(&mat_params, &pt, 0, rad * 0.45f, rad * 0.55f); } if ( pct > 0.7f ) { //g3_draw_bitmap(&pt, 0, rad * 0.25f, tmap_flags, rad * 0.75f); g3_render_rect_screen_aligned(&mat_params, &pt, 0, rad * 0.25f, rad * 0.75f); } } } // render all beam weapons void beam_render_all() { GR_DEBUG_SCOPE("Render Beams"); TRACE_SCOPE(tracing::DrawBeams); beam *moveup; // moves the U value of texture coods in beams if desired-Bobboau static float u_offset = 0.0f; u_offset += flFrametime; // traverse through all active beams moveup = GET_FIRST(&Beam_used_list); while ( moveup != END_OF_LIST(&Beam_used_list) ) { // each beam type renders a little bit differently if ( (moveup->warmup_stamp == -1) && (moveup->warmdown_stamp == -1) && !(moveup->flags & BF_SAFETY) ) { // HACK - if this is the first frame the beam is firing, don't render it if (moveup->framecount <= 0) { moveup->u_offset_local = 0; moveup = GET_NEXT(moveup); continue; } // render the beam itself Assert(moveup->weapon_info_index >= 0); if (moveup->weapon_info_index < 0) { moveup = GET_NEXT(moveup); continue; } beam_render(moveup, u_offset); } // render the muzzle glow beam_render_muzzle_glow(moveup); // maybe generate some muzzle particles beam_generate_muzzle_particles(moveup); // next item moveup = GET_NEXT(moveup); } } // output top and bottom vectors // fvec == forward vector (eye viewpoint basically. in world coords) // pos == world coordinate of the point we're calculating "around" // w == width of the diff between top and bottom around pos void beam_calc_facing_pts( vec3d *top, vec3d *bot, vec3d *fvec, vec3d *pos, float w, float /*z_add*/ ) { vec3d uvec, rvec; vec3d temp; temp = *pos; vm_vec_sub( &rvec, &Eye_position, &temp ); vm_vec_normalize( &rvec ); vm_vec_cross(&uvec,fvec,&rvec); // VECMAT-ERROR: NULL VEC3D (value of, fvec == rvec) vm_vec_normalize_safe(&uvec); // Scale the beam width so that they always appear at least some configured amount of pixels wide. float scaled_w = model_render_get_diameter_clamped_to_min_pixel_size(pos, w, Min_pixel_size_beam); vm_vec_scale_add( top, &temp, &uvec, scaled_w * 0.5f ); vm_vec_scale_add( bot, &temp, &uvec, -scaled_w * 0.5f ); } // light scale factor float blight = 25.5f; DCF(blight, "Sets the beam light scale factor (Default is 25.5f)") { dc_stuff_float(&blight); } // call to add a light source to a small object void beam_add_light_small(beam *bm, object *objp, vec3d *pt_override = NULL) { weapon_info *wip; beam_weapon_info *bwi; float noise; // no lighting if(Detail.lighting < 2){ return; } // sanity Assert(bm != nullptr); if(bm == nullptr){ return; } Assert(objp != nullptr); if(objp == nullptr){ return; } Assert(bm->weapon_info_index >= 0); wip = &Weapon_info[bm->weapon_info_index]; bwi = &wip->b_info; // some noise if ( (bm->warmup_stamp < 0) && (bm->warmdown_stamp < 0) ) // disable noise when warming up or down noise = frand_range(1.0f - bwi->sections[0].flicker, 1.0f + bwi->sections[0].flicker); else noise = 1.0f; // get the width of the beam float light_rad = bm->beam_light_width * bm->current_width_factor * blight * noise; // nearest point on the beam, and its distance to the ship vec3d near_pt; if(pt_override == NULL){ float dist; vm_vec_dist_to_line(&objp->pos, &bm->last_start, &bm->last_shot, &near_pt, &dist); if(dist > light_rad){ return; } } else { near_pt = *pt_override; } // average rgb of the beam float fr = (float)wip->laser_color_1.red / 255.0f; float fg = (float)wip->laser_color_1.green / 255.0f; float fb = (float)wip->laser_color_1.blue / 255.0f; float pct = 0.0f; if (bm->warmup_stamp != -1) { // calculate muzzle light intensity // get warmup pct pct = BEAM_WARMUP_PCT(bm)*0.5f; } else // if the beam is warming down if (bm->warmdown_stamp != -1) { // get warmup pct pct = MAX(1.0f - BEAM_WARMDOWN_PCT(bm)*1.3f,0.0f)*0.5f; } // otherwise the beam is really firing else { pct = 1.0f; } // add a unique light light_add_point_unique(&near_pt, light_rad * 0.0001f, light_rad, pct, fr, fg, fb, OBJ_INDEX(objp)); } // call to add a light source to a large object void beam_add_light_large(beam *bm, object *objp, vec3d *pt0, vec3d *pt1) { weapon_info *wip; beam_weapon_info *bwi; float noise; // no lighting if(Detail.lighting < 2){ return; } // sanity Assert(bm != NULL); if(bm == NULL){ return; } Assert(objp != NULL); if(objp == NULL){ return; } Assert(bm->weapon_info_index >= 0); wip = &Weapon_info[bm->weapon_info_index]; bwi = &wip->b_info; // some noise noise = frand_range(1.0f - bwi->sections[0].flicker, 1.0f + bwi->sections[0].flicker); // width of the beam float light_rad = bm->beam_light_width * bm->current_width_factor * blight * noise; // average rgb of the beam float fr = (float)wip->laser_color_1.red / 255.0f; float fg = (float)wip->laser_color_1.green / 255.0f; float fb = (float)wip->laser_color_1.blue / 255.0f; light_add_tube(pt0, pt1, 1.0f, light_rad, 1.0f * noise, fr, fg, fb, OBJ_INDEX(objp)); } // mark an object as being lit void beam_add_light(beam *b, int objnum, int source, vec3d *c_point) { beam_light_info *l; // if we're out of light slots! if(Beam_light_count >= MAX_BEAM_LIGHT_INFO){ return; } // otherwise add it l = &Beam_lights[Beam_light_count++]; l->bm = b; l->objnum = objnum; l->source = (ubyte)source; // only type 2 lights (from collisions) need a collision point if(c_point != NULL){ l->c_point = *c_point; } else { Assert(source != 2); if(source == 2){ Beam_light_count--; } } } // apply lighting from any beams void beam_apply_lighting() { int idx; beam_light_info *l; vec3d pt, dir; beam_weapon_info *bwi; // convert all beam lights into real lights for(idx=0; idx<Beam_light_count; idx++){ // get the light l = &Beam_lights[idx]; // bad object if((l->objnum < 0) || (l->objnum >= MAX_OBJECTS) || (l->bm == NULL)){ continue; } bwi = &Weapon_info[l->bm->weapon_info_index].b_info; // different light types switch(l->source){ // from the muzzle of the gun case 0: // a few meters in from the of muzzle vm_vec_sub(&dir, &l->bm->last_start, &l->bm->last_shot); vm_vec_normalize_quick(&dir); vm_vec_scale(&dir, -0.8f); // TODO: This probably needs to *not* be stupid. -taylor vm_vec_scale_add(&pt, &l->bm->last_start, &dir, bwi->beam_muzzle_radius * 5.0f); beam_add_light_small(l->bm, &Objects[l->objnum], &pt); break; // from the beam passing by case 1: Assert( Objects[l->objnum].instance >= 0 ); // Valathil: Everyone gets tube lights now beam_add_light_large(l->bm, &Objects[l->objnum], &l->bm->last_start, &l->bm->last_shot); break; // from a collision case 2: // Valathil: Dont render impact lights for shaders, handled by tube lighting break; } } } // -----------------------------===========================------------------------------ // BEAM BOOKKEEPING FUNCTIONS // -----------------------------===========================------------------------------ // delete a beam void beam_delete(beam *b) { // remove from active list and put on free list list_remove(&Beam_used_list, b); list_append(&Beam_free_list, b); // delete our associated object if(b->objnum >= 0){ obj_delete(b->objnum); } b->objnum = -1; // kill the beam looping sound if (b->beam_sound_loop.isValid()) { snd_stop(b->beam_sound_loop); b->beam_sound_loop = sound_handle::invalid(); } // handle model animation reversal (closing) // (beam animations should end pretty much immediately - taylor) if ((b->subsys) && (b->subsys->turret_animation_position == MA_POS_READY)) { b->subsys->turret_animation_done_time = timestamp(50); } // subtract one Beam_count--; Assert(Beam_count >= 0); nprintf(("Beam", "Recycled beam (%d beams remaining)\n", Beam_count)); } // given an object, return its model num int beam_get_model(object *objp) { int pof; if (objp == NULL) { return -1; } Assert(objp->instance >= 0); if(objp->instance < 0){ return -1; } switch(objp->type){ case OBJ_SHIP: return Ship_info[Ships[objp->instance].ship_info_index].model_num; case OBJ_WEAPON: Assert(Weapons[objp->instance].weapon_info_index >= 0); if(Weapons[objp->instance].weapon_info_index < 0){ return -1; } return Weapon_info[Weapons[objp->instance].weapon_info_index].model_num; case OBJ_DEBRIS: Assert(Debris[objp->instance].is_hull); if(!Debris[objp->instance].is_hull){ return -1; } return Debris[objp->instance].model_num; case OBJ_ASTEROID: pof = Asteroids[objp->instance].asteroid_subtype; Assert(Asteroids[objp->instance].asteroid_type >= 0); if(Asteroids[objp->instance].asteroid_type < 0){ return -1; } return Asteroid_info[Asteroids[objp->instance].asteroid_type].model_num[pof]; default: // this shouldn't happen too often mprintf(("Beam couldn't find a good object model/type!! (%d)\n", objp->type)); return -1; } } // start the warmup phase for the beam void beam_start_warmup(beam *b) { // set the warmup stamp b->warmup_stamp = timestamp(Weapon_info[b->weapon_info_index].b_info.beam_warmup); // start playing warmup sound if(!(Game_mode & GM_STANDALONE_SERVER) && (Weapon_info[b->weapon_info_index].b_info.beam_warmup_sound.isValid())){ snd_play_3d(gamesnd_get_game_sound(Weapon_info[b->weapon_info_index].b_info.beam_warmup_sound), &b->last_start, &View_position); } } // start the firing phase for the beam, return 0 if the beam failed to start, and should be deleted altogether int beam_start_firing(beam *b) { // kill the warmup stamp so the rest of the code knows its firing b->warmup_stamp = -1; // any special stuff for each weapon type switch(b->type){ // re-aim direct fire and antifighter beam weapons here, otherwise they tend to miss case BeamType::DIRECT_FIRE: case BeamType::ANTIFIGHTER: beam_aim(b); break; case BeamType::SLASHING: break; case BeamType::TARGETING: break; case BeamType::NORMAL_FIRE: break; case BeamType::OMNI: break; default: Int3(); } // determine if we can legitimately start firing, or if we need to take other action switch(beam_ok_to_fire(b)){ case -1 : return 0; case 0 : beam_start_warmdown(b); return 1; } weapon_info* wip = &Weapon_info[b->weapon_info_index]; // start the beam firing sound now, if we haven't already if ((!b->beam_sound_loop.isValid()) && (Weapon_info[b->weapon_info_index].b_info.beam_loop_sound.isValid())) { b->beam_sound_loop = snd_play_3d(gamesnd_get_game_sound(Weapon_info[b->weapon_info_index].b_info.beam_loop_sound), &b->last_start, &View_position, 0.0f, NULL, 1, 1.0, SND_PRIORITY_SINGLE_INSTANCE, NULL, 1.0f, 1); } // "shot" sound if (Weapon_info[b->weapon_info_index].launch_snd.isValid()) snd_play_3d(gamesnd_get_game_sound(Weapon_info[b->weapon_info_index].launch_snd), &b->last_start, &View_position); // if this is a fighter ballistic beam, always take at least one ammo to start with if (b->flags & BF_IS_FIGHTER_BEAM && wip->wi_flags[Weapon::Info_Flags::Ballistic]) Ships[b->objp->instance].weapons.primary_bank_ammo[b->bank]--; if (Script_system.IsActiveAction(CHA_BEAMFIRE)) { Script_system.SetHookObjects(3, "Beam", &Objects[b->objnum], "User", b->objp, "Target", b->target); Script_system.RunCondition(CHA_BEAMFIRE, &Objects[b->objnum], b->weapon_info_index); Script_system.RemHookVars({"Beam", "User", "Target"}); } // success return 1; } // start the warmdown phase for the beam void beam_start_warmdown(beam *b) { // timestamp b->warmdown_stamp = timestamp(Weapon_info[b->weapon_info_index].b_info.beam_warmdown); // start the warmdown sound if(Weapon_info[b->weapon_info_index].b_info.beam_warmdown_sound.isValid()){ snd_play_3d(gamesnd_get_game_sound(Weapon_info[b->weapon_info_index].b_info.beam_warmdown_sound), &b->last_start, &View_position); } // kill the beam looping sound if (b->beam_sound_loop.isValid()) { snd_stop(b->beam_sound_loop); b->beam_sound_loop = sound_handle::invalid(); } if (b->subsys != nullptr) { // Starts the warmdown program if it exists b->subsys->system_info->beam_warmdown_program.start(b->objp, &vmd_zero_vector, &vmd_identity_matrix, b->subsys->system_info->subobj_num); } } // recalculate beam sounds (looping sounds relative to the player) void beam_recalc_sounds(beam *b) { beam_weapon_info *bwi; vec3d pos; Assert(b->weapon_info_index >= 0); if(b->weapon_info_index < 0){ return; } bwi = &Weapon_info[b->weapon_info_index].b_info; // update the sound position relative to the player if (b->beam_sound_loop.isValid()) { // get the point closest to the player's viewing position switch(vm_vec_dist_to_line(&View_position, &b->last_start, &b->last_shot, &pos, NULL)){ // behind the beam, so use the start pos case -1: pos = b->last_start; break; // use the closest point case 0: // already calculated in vm_vec_dist_to_line(...) break; // past the beam, so use the shot pos case 1: pos = b->last_shot; break; } snd_update_3d_pos(b->beam_sound_loop, gamesnd_get_game_sound(bwi->beam_loop_sound), &pos); } } // -----------------------------===========================------------------------------ // BEAM AIMING FUNCTIONS // -----------------------------===========================------------------------------ // fills in binfo void beam_get_binfo(beam *b, float accuracy, int num_shots, int burst_seed, float burst_shot_rotation, float per_burst_shot_rotation) { vec3d p2; int model_num, idx; vec3d pos1, pos2; vec3d turret_point, turret_norm; beam_weapon_info *bwi; float miss_factor; if (b->flags & BF_IS_FIGHTER_BEAM) { vm_vec_unrotate(&turret_point, &b->local_fire_postion, &b->objp->orient); turret_point += b->objp->pos; turret_norm = b->objp->orient.vec.fvec; } else if (b->subsys != nullptr) { int temp = b->subsys->turret_next_fire_pos; b->subsys->turret_next_fire_pos = b->firingpoint; // where the shot is originating from (b->last_start gets filled in) beam_get_global_turret_gun_info(b->objp, b->subsys, &turret_point, &turret_norm, 1, &p2, (b->flags & BF_IS_FIGHTER_BEAM) > 0); b->subsys->turret_next_fire_pos = temp; } else { turret_point = b->last_start; if (b->flags & BF_TARGETING_COORDS) { p2 = b->target_pos1; } else { p2 = b->target->pos; } vm_vec_normalized_dir(&turret_norm, &p2, &turret_point); } // get a model # to work with model_num = beam_get_model(b->target); if ((model_num < 0) && !(b->flags & BF_TARGETING_COORDS)) { return; } // get beam weapon info Assert(b->weapon_info_index >= 0); if(b->weapon_info_index < 0){ return; } bwi = &Weapon_info[b->weapon_info_index].b_info; // stuff num shots even though its only used for antifighter beam weapons b->binfo.shot_count = (ubyte)num_shots; if(b->binfo.shot_count > MAX_BEAM_SHOTS){ b->binfo.shot_count = MAX_BEAM_SHOTS; } int seed = bwi->flags[Weapon::Beam_Info_Flags::Burst_share_random] ? burst_seed : Random::next(); // generate the proper amount of directional vectors switch(b->type){ // pick an accuracy. beam will be properly aimed at actual fire time case BeamType::DIRECT_FIRE: // determine the miss factor Assert(Game_skill_level >= 0 && Game_skill_level < NUM_SKILL_LEVELS); Assert(b->team >= 0 && b->team < (int)Iff_info.size()); miss_factor = bwi->beam_iff_miss_factor[b->team][Game_skill_level]; // all we will do is decide whether or not we will hit - direct fire beam weapons are re-aimed immediately before firing b->binfo.shot_aim[0] = frand_range(0.0f, 1.0f + miss_factor * accuracy); b->binfo.shot_count = 1; if (b->flags & BF_TARGETING_COORDS) { // these aren't used for direct fire beams, so zero them out vm_vec_zero(&b->binfo.dir_a); vm_vec_zero(&b->binfo.dir_b); } else { // get random model points, this is useful for big ships, because we never miss when shooting at them submodel_get_two_random_points_better(model_num, 0, &b->binfo.dir_a, &b->binfo.dir_b, seed); } break; // just 2 points in the "slash" case BeamType::SLASHING: if (b->flags & BF_TARGETING_COORDS) { // slash between the two pos1 = b->target_pos1; pos2 = b->target_pos2; } else { beam_get_octant_points(model_num, b->target, seed % BEAM_NUM_GOOD_OCTANTS, Beam_good_slash_octants, &pos1, &pos2); } // point 1 vm_vec_sub(&b->binfo.dir_a, &pos1, &turret_point); vm_vec_normalize(&b->binfo.dir_a); // point 2 vm_vec_sub(&b->binfo.dir_b, &pos2, &turret_point); vm_vec_normalize(&b->binfo.dir_b); break; // nothing for this beam - its very special case case BeamType::TARGETING: break; // antifighter beams fire at small ship multiple times case BeamType::ANTIFIGHTER: // determine the miss factor Assert(Game_skill_level >= 0 && Game_skill_level < NUM_SKILL_LEVELS); Assert(b->team >= 0 && b->team < (int)Iff_info.size()); miss_factor = bwi->beam_iff_miss_factor[b->team][Game_skill_level]; // get a bunch of shot aims for(idx=0; idx<b->binfo.shot_count; idx++){ // MK, 9/3/99: Added pow() function to make increasingly likely to miss with subsequent shots. 30% more likely with each shot. float r = ((float) pow(1.3f, (float) idx)) * miss_factor * accuracy; b->binfo.shot_aim[idx] = frand_range(0.0f, 1.0f + r); } break; // normal-fire beams just fire straight case BeamType::NORMAL_FIRE: b->binfo.shot_aim[0] = 0.0000001f; b->binfo.shot_count = 1; b->binfo.dir_a = turret_norm; b->binfo.dir_b = turret_norm; break; case BeamType::OMNI: { vm_vec_zero(&pos1); vm_vec_zero(&pos2); vec3d rot_axis, burst_rot_axis, per_burst_rot_axis; object* usable_target = nullptr; // don't use the target if this is a fighter beam if (!(b->flags & BF_IS_FIGHTER_BEAM) && b->target) usable_target = b->target; // set up shooter orient now matrix orient = vmd_identity_matrix; if (b->flags & BF_IS_FIGHTER_BEAM) { orient = b->objp->orient; } else if (b->subsys) { vec3d fvec, uvec, target_pos; if (b->target) target_pos = b->target->pos; else if (b->flags & BF_TARGETING_COORDS) target_pos = b->target_pos1; else UNREACHABLE("Turret beam fired without a target or target coordinates?"); vm_vec_sub(&fvec, &target_pos, &turret_point); vm_vec_unrotate(&uvec, &b->subsys->system_info->turret_norm, &b->objp->orient); vm_vector_2_matrix(&orient, &fvec, &uvec); } else if (b->flags & BF_TARGETING_COORDS) { // targeting coords already set up turret_norm with target_pos above vm_vector_2_matrix(&orient, &turret_norm); } vec3d rand1_on = vm_vec_new(0.f, 0.f, 0.f); vec3d rand2_on = vm_vec_new(0.f, 0.f, 0.f); vec3d rand1_off = vm_vec_new(0.f, 0.f, 0.f); vec3d rand2_off = vm_vec_new(0.f, 0.f, 0.f); // Get our two starting points if (usable_target) { // set up our two kinds of random points if needed if (bwi->t5info.start_pos == Type5BeamPos::RANDOM_INSIDE || bwi->t5info.end_pos == Type5BeamPos::RANDOM_INSIDE) { vec3d temp1, temp2; submodel_get_two_random_points_better(model_num, 0, &temp1, &temp2, seed); vm_vec_rotate(&rand1_on, &temp1, &b->target->orient); vm_vec_rotate(&rand2_on, &temp2, &b->target->orient); rand1_on += b->target->pos; rand2_on += b->target->pos; } if (bwi->t5info.start_pos == Type5BeamPos::RANDOM_OUTSIDE || bwi->t5info.end_pos == Type5BeamPos::RANDOM_OUTSIDE) beam_get_octant_points(model_num, usable_target, seed % BEAM_NUM_GOOD_OCTANTS, Beam_good_slash_octants, &rand1_off, &rand2_off); // get start and end points switch (bwi->t5info.start_pos) { case Type5BeamPos::CENTER: pos1 = b->target->pos; break; case Type5BeamPos::RANDOM_INSIDE: pos1 = rand1_on; break; case Type5BeamPos::RANDOM_OUTSIDE: pos1 = rand1_off; break; default:; // the other cases dont matter } if (bwi->t5info.no_translate || bwi->t5info.end_pos == Type5BeamPos::SAME_RANDOM) pos2 = pos1; else { switch (bwi->t5info.end_pos) { case Type5BeamPos::CENTER: pos2 = b->target->pos; break; case Type5BeamPos::RANDOM_INSIDE: pos2 = rand2_on; break; case Type5BeamPos::RANDOM_OUTSIDE: pos2 = rand2_off; break; default:; // the other cases dont matter } } // set rot_axis if its center if (bwi->t5info.continuous_rot_axis == Type5BeamRotAxis::CENTER) rot_axis = b->target->pos; if (bwi->t5info.per_burst_rot_axis == Type5BeamRotAxis::CENTER) per_burst_rot_axis = b->target->pos; if (bwi->t5info.burst_rot_axis == Type5BeamRotAxis::CENTER) burst_rot_axis = b->target->pos; } else { // No usable target vec3d center = vm_vec_new(0.f, 0.f, 0.f); // if we have no target let's act as though we're shooting at something with a 300m radius 300m away // randomize the start and end points if not center aiming // aim on the edge for random outside if (bwi->t5info.start_pos != Type5BeamPos::CENTER) vm_vec_random_in_circle(&pos1, &center, &orient, 1.f, bwi->t5info.start_pos == Type5BeamPos::RANDOM_OUTSIDE); if (bwi->t5info.end_pos != Type5BeamPos::CENTER) vm_vec_random_in_circle(&pos2, &center, &orient, 1.f, bwi->t5info.start_pos == Type5BeamPos::RANDOM_OUTSIDE); if (bwi->t5info.no_translate || bwi->t5info.end_pos == Type5BeamPos::SAME_RANDOM) pos2 = pos1; pos1 *= 300.f; pos2 *= 300.f; vec3d move_forward = vm_vec_new(0.f, 0.f, 300.f); center += move_forward; pos1 += move_forward; pos2 += move_forward; // unrotate the points to get world positions vec3d temp = pos1; vm_vec_unrotate(&pos1, &temp, &orient); temp = pos2; vm_vec_unrotate(&pos2, &temp, &orient); temp = center; vm_vec_unrotate(&center, &temp, &orient); pos1 += turret_point; pos2 += turret_point; center += turret_point; // set rot_axis if its center if (bwi->t5info.continuous_rot_axis == Type5BeamRotAxis::CENTER) rot_axis = center; if (bwi->t5info.per_burst_rot_axis == Type5BeamRotAxis::CENTER) per_burst_rot_axis = center; if (bwi->t5info.burst_rot_axis == Type5BeamRotAxis::CENTER) burst_rot_axis = center; } // OKAY DONE WITH THE INITIAL SET UP // set rot_axis if its one of the before offset points if (bwi->t5info.continuous_rot_axis == Type5BeamRotAxis::STARTPOS_NO_OFFSET || bwi->t5info.continuous_rot_axis == Type5BeamRotAxis::ENDPOS_NO_OFFSET) rot_axis = bwi->t5info.continuous_rot_axis == Type5BeamRotAxis::STARTPOS_NO_OFFSET ? pos1 : pos2; if (bwi->t5info.per_burst_rot_axis == Type5BeamRotAxis::STARTPOS_NO_OFFSET || bwi->t5info.per_burst_rot_axis == Type5BeamRotAxis::ENDPOS_NO_OFFSET) per_burst_rot_axis = bwi->t5info.per_burst_rot_axis == Type5BeamRotAxis::STARTPOS_NO_OFFSET ? pos1 : pos2; if (bwi->t5info.burst_rot_axis == Type5BeamRotAxis::STARTPOS_NO_OFFSET || bwi->t5info.burst_rot_axis == Type5BeamRotAxis::ENDPOS_NO_OFFSET) burst_rot_axis = bwi->t5info.burst_rot_axis == Type5BeamRotAxis::STARTPOS_NO_OFFSET ? pos1 : pos2; // now the offsets float scale_factor; if (b->target != nullptr) { if (bwi->t5info.target_scale_positions) scale_factor = b->target->radius; else scale_factor = vm_vec_dist(&b->target->pos, &turret_point); // using dist here means we have a constant angular width } else scale_factor = 300.f; // no target, just use 300m like the notarget scenario above vec3d offset = bwi->t5info.start_pos_offset; offset *= scale_factor; // switch to the target's orient if applicable if (bwi->t5info.target_orient_positions && b->target != nullptr) orient = b->target->orient; // maybe add some random vec3d random_offset; vm_vec_random_in_sphere(&random_offset, &vmd_zero_vector, 1.f, false, true); random_offset *= scale_factor; random_offset.xyz.x *= bwi->t5info.start_pos_rand.xyz.x; random_offset.xyz.y *= bwi->t5info.start_pos_rand.xyz.y; random_offset.xyz.z *= bwi->t5info.start_pos_rand.xyz.z; offset += random_offset; // then unrotate by it to get the world orientation vec3d rotated_offset; vm_vec_unrotate(&rotated_offset, &offset, &orient); pos1 += rotated_offset; // end pos offset if (bwi->t5info.no_translate) pos2 = pos1; else { offset = bwi->t5info.end_pos_offset; offset *= scale_factor; // randomness vm_vec_random_in_sphere(&random_offset, &vmd_zero_vector, 1.f, false, true); random_offset *= scale_factor; random_offset.xyz.x *= bwi->t5info.start_pos_rand.xyz.x; random_offset.xyz.y *= bwi->t5info.start_pos_rand.xyz.y; random_offset.xyz.z *= bwi->t5info.start_pos_rand.xyz.z; offset += random_offset; // rotate vm_vec_unrotate(&rotated_offset, &offset, &orient); pos2 += rotated_offset; } // finally grab the last cases for rot_axis if (bwi->t5info.continuous_rot_axis == Type5BeamRotAxis::STARTPOS_OFFSET || bwi->t5info.continuous_rot_axis == Type5BeamRotAxis::ENDPOS_OFFSET) rot_axis = bwi->t5info.continuous_rot_axis == Type5BeamRotAxis::STARTPOS_OFFSET ? pos1 : pos2; if (bwi->t5info.per_burst_rot_axis == Type5BeamRotAxis::STARTPOS_OFFSET || bwi->t5info.per_burst_rot_axis == Type5BeamRotAxis::ENDPOS_OFFSET) per_burst_rot_axis = bwi->t5info.per_burst_rot_axis == Type5BeamRotAxis::STARTPOS_OFFSET ? pos1 : pos2; if (bwi->t5info.burst_rot_axis == Type5BeamRotAxis::STARTPOS_OFFSET || bwi->t5info.burst_rot_axis == Type5BeamRotAxis::ENDPOS_OFFSET) burst_rot_axis = bwi->t5info.burst_rot_axis == Type5BeamRotAxis::STARTPOS_OFFSET ? pos1 : pos2; // normalize the vectors vec3d per_burst_rot_axis_direction, burst_rot_axis_direction; vm_vec_sub(&per_burst_rot_axis_direction, &per_burst_rot_axis, &turret_point); vm_vec_normalize(&per_burst_rot_axis_direction); vm_vec_sub(&burst_rot_axis_direction, &burst_rot_axis, &turret_point); vm_vec_normalize(&burst_rot_axis_direction); if (bwi->t5info.continuous_rot_axis != Type5BeamRotAxis::UNSPECIFIED) { vm_vec_sub(&b->binfo.rot_axis, &rot_axis, &turret_point); vm_vec_normalize(&b->binfo.rot_axis); } vm_vec_sub(&b->binfo.dir_a, &pos1, &turret_point); vm_vec_normalize(&b->binfo.dir_a); vm_vec_sub(&b->binfo.dir_b, &pos2, &turret_point); vm_vec_normalize(&b->binfo.dir_b); vec3d zero_vec = vmd_zero_vector; // and finally rotate around the per_burst and burst rot_axes if (bwi->t5info.per_burst_rot_axis != Type5BeamRotAxis::UNSPECIFIED) { // negative means random float per_burst_rot = per_burst_shot_rotation; if (per_burst_rot < 0.0f) per_burst_rot = static_randf_range(seed, 0.f, PI2); vm_rot_point_around_line(&b->binfo.dir_a, &b->binfo.dir_a, per_burst_rot, &zero_vec, &per_burst_rot_axis_direction); vm_rot_point_around_line(&b->binfo.dir_b, &b->binfo.dir_b, per_burst_rot, &zero_vec, &per_burst_rot_axis_direction); vm_rot_point_around_line(&b->binfo.rot_axis, &b->binfo.rot_axis, per_burst_rot, &zero_vec, &per_burst_rot_axis_direction); } if (bwi->t5info.burst_rot_axis != Type5BeamRotAxis::UNSPECIFIED) { // negative means random float burst_rot = burst_shot_rotation; if (burst_rot < 0.0f) burst_rot = frand_range(0.f, PI2); vm_rot_point_around_line(&b->binfo.dir_a, &b->binfo.dir_a, burst_rot, &zero_vec, &burst_rot_axis_direction); vm_rot_point_around_line(&b->binfo.dir_b, &b->binfo.dir_b, burst_rot, &zero_vec, &burst_rot_axis_direction); vm_rot_point_around_line(&b->binfo.rot_axis, &b->binfo.rot_axis, burst_rot, &zero_vec, &burst_rot_axis_direction); } break; } default: break; } } // aim the beam (setup last_start and last_shot - the endpoints). also recalculates collision pairs void beam_aim(beam *b) { vec3d temp, p2; if (!(b->flags & BF_TARGETING_COORDS)) { // targeting type beam weapons have no target if (b->target == NULL) { Assert(b->type == BeamType::TARGETING); if(b->type != BeamType::TARGETING){ return; } } // get a model # to work with else { // this can happen if we fire at a target that was just destroyed if (beam_get_model(b->target) < 0) { return; } } } if (b->subsys != nullptr && b->type != BeamType::TARGETING) { // targeting type beams don't use this information. int temp_int = b->subsys->turret_next_fire_pos; if (!(b->flags & BF_IS_FIGHTER_BEAM)) b->subsys->turret_next_fire_pos = b->firingpoint; if (b->subsys->system_info->flags[Model::Subsystem_Flags::Share_fire_direction]) { beam_get_global_turret_gun_info(b->objp, b->subsys, &b->last_start, &temp, 0, nullptr, (b->flags & BF_IS_FIGHTER_BEAM) != 0); } else { // where the shot is originating from (b->last_start gets filled in) beam_get_global_turret_gun_info(b->objp, b->subsys, &b->last_start, &temp, 1, &p2, (b->flags & BF_IS_FIGHTER_BEAM) != 0); } b->subsys->turret_next_fire_pos = temp_int; } // setup our initial shot point and aim direction switch(b->type){ case BeamType::DIRECT_FIRE: // if we're targeting a subsystem - shoot directly at it if(b->target_subsys != nullptr){ vm_vec_unrotate(&b->last_shot, &b->target_subsys->system_info->pnt, &b->target->orient); vm_vec_add2(&b->last_shot, &b->target->pos); if ((b->subsys != nullptr) && (b->subsys->system_info->flags[Model::Subsystem_Flags::Share_fire_direction])) { float dist = vm_vec_dist(&b->last_shot,&b->last_start); vm_vec_scale(&temp, dist); } else { vm_vec_sub(&temp, &b->last_shot, &b->last_start); } vm_vec_scale_add(&b->last_shot, &b->last_start, &temp, 2.0f); break; } // if we're shooting at a big ship - shoot directly at the model if((b->target != nullptr) && (b->target->type == OBJ_SHIP) && (Ship_info[Ships[b->target->instance].ship_info_index].is_big_or_huge())){ if ((b->subsys != nullptr) && (b->subsys->system_info->flags[Model::Subsystem_Flags::Share_fire_direction])) { vec3d pnt; vm_vec_unrotate(&pnt, &b->binfo.dir_a, &b->target->orient); vm_vec_add2(&pnt, &b->target->pos); float dist = vm_vec_dist(&pnt, &b->last_start); vm_vec_scale(&temp, dist); p2 = temp; } else { // rotate into world coords vm_vec_unrotate(&temp, &b->binfo.dir_a, &b->target->orient); vm_vec_add2(&temp, &b->target->pos); // get the shot point vm_vec_sub(&p2, &temp, &b->last_start); } vm_vec_scale_add(&b->last_shot, &b->last_start, &p2, 2.0f); break; } // point at the center of the target... if (b->flags & BF_TARGETING_COORDS) { if ((b->subsys != nullptr) && (b->subsys->system_info->flags[Model::Subsystem_Flags::Share_fire_direction])) { beam_get_global_turret_gun_info(b->objp, b->subsys, &b->last_start, &temp, 0, &b->target_pos1, (b->flags & BF_IS_FIGHTER_BEAM) != 0); float dist = vm_vec_dist(&b->target_pos1, &b->last_start); vm_vec_scale_add(&b->last_shot, &b->last_start, &temp, dist); } else { b->last_shot = b->target_pos1; } } else { if ((b->subsys != nullptr) && (b->subsys->system_info->flags[Model::Subsystem_Flags::Share_fire_direction])) { beam_get_global_turret_gun_info(b->objp, b->subsys, &b->last_start, &temp, 0, &b->target->pos, (b->flags & BF_IS_FIGHTER_BEAM) != 0); float dist = vm_vec_dist(&b->target->pos, &b->last_start); vm_vec_scale_add(&b->last_shot, &b->last_start, &temp, dist); } else { b->last_shot = b->target->pos; } // ...then jitter based on shot_aim (requires target) beam_jitter_aim(b, b->binfo.shot_aim[0]); } break; case BeamType::SLASHING: if ((b->subsys != nullptr) && (b->subsys->system_info->flags[Model::Subsystem_Flags::Share_fire_direction])) { vm_vec_scale(&b->binfo.dir_a, b->range); beam_get_global_turret_gun_info(b->objp, b->subsys, &b->last_start, &temp, 0, &b->binfo.dir_a, (b->flags & BF_IS_FIGHTER_BEAM) != 0); vm_vec_add(&b->last_shot, &b->last_start, &temp); } else { // set the shot point vm_vec_scale_add(&b->last_shot, &b->last_start, &b->binfo.dir_a, b->range); } Assert(is_valid_vec(&b->last_shot)); break; case BeamType::TARGETING: // start point temp = b->local_fire_postion; vm_vec_unrotate(&b->last_start, &temp, &b->objp->orient); vm_vec_add2(&b->last_start, &b->objp->pos); vm_vec_scale_add(&b->last_shot, &b->last_start, &b->objp->orient.vec.fvec, b->range); break; case BeamType::ANTIFIGHTER: // point at the center of the target... if (b->flags & BF_TARGETING_COORDS) { if ((b->subsys != nullptr) && (b->subsys->system_info->flags[Model::Subsystem_Flags::Share_fire_direction])) { beam_get_global_turret_gun_info(b->objp, b->subsys, &b->last_start, &temp, 0, &b->target_pos1, (b->flags & BF_IS_FIGHTER_BEAM) != 0); float dist = vm_vec_dist(&b->target_pos1, &b->last_start); vm_vec_scale_add(&b->last_shot, &b->last_start, &temp, dist); } else { b->last_shot = b->target_pos1; } } else { if ((b->subsys != nullptr) && (b->subsys->system_info->flags[Model::Subsystem_Flags::Share_fire_direction])) { beam_get_global_turret_gun_info(b->objp, b->subsys, &b->last_start, &temp, 0, &b->target->pos, (b->flags & BF_IS_FIGHTER_BEAM) != 0); float dist = vm_vec_dist(&b->target->pos, &b->last_start); vm_vec_scale_add(&b->last_shot, &b->last_start, &temp, dist); } else { b->last_shot = b->target->pos; } // ...then jitter based on shot_aim (requires target) beam_jitter_aim(b, b->binfo.shot_aim[b->shot_index]); } nprintf(("AI", "Frame %i: FIRING\n", Framecount)); break; case BeamType::NORMAL_FIRE: // point directly in the direction of the turret vm_vec_scale_add(&b->last_shot, &b->last_start, &temp, b->range); break; case BeamType::OMNI: if ((b->subsys != nullptr) && (b->subsys->system_info->flags[Model::Subsystem_Flags::Share_fire_direction])) { vm_vec_scale(&b->binfo.dir_a, b->range); beam_get_global_turret_gun_info(b->objp, b->subsys, &b->last_start, &temp, 0, &b->binfo.dir_a, (b->flags & BF_IS_FIGHTER_BEAM) != 0); vm_vec_add(&b->last_shot, &b->last_start, &temp); } else { // set the shot point vm_vec_scale_add(&b->last_shot, &b->last_start, &b->binfo.dir_a, b->range); } Assert(is_valid_vec(&b->last_shot)); break; default: UNREACHABLE("Impossible beam type (%d); get a coder!\n", (int)b->type); } if (!Weapon_info[b->weapon_info_index].wi_flags[Weapon::Info_Flags::No_collide]) // recalculate object pairs OBJ_RECALC_PAIRS((&Objects[b->objnum])); } // given a model #, and an object, stuff 2 good world coord points void beam_get_octant_points(int modelnum, object *objp, int oct_index, int oct_array[BEAM_NUM_GOOD_OCTANTS][4], vec3d *v1, vec3d *v2) { vec3d t1, t2, temp; polymodel *m = model_get(modelnum); // bad bad bad bad bad bad if(m == NULL){ Int3(); return; } Assert((oct_index >= 0) && (oct_index < BEAM_NUM_GOOD_OCTANTS)); // randomly pick octants t1 = oct_array[oct_index][2] ? m->octants[oct_array[oct_index][0]].max : m->octants[oct_array[oct_index][0]].min; t2 = oct_array[oct_index][3] ? m->octants[oct_array[oct_index][1]].max : m->octants[oct_array[oct_index][1]].min; Assert(!vm_vec_same(&t1, &t2)); // get them in world coords vm_vec_unrotate(&temp, &t1, &objp->orient); vm_vec_add(v1, &temp, &objp->pos); vm_vec_unrotate(&temp, &t2, &objp->orient); vm_vec_add(v2, &temp, &objp->pos); } // throw some jitter into the aim - based upon shot_aim void beam_jitter_aim(beam *b, float aim) { Assert(b->target != NULL); vec3d forward, circle; matrix m; float subsys_strength; // if the weapons subsystem is damaged or destroyed if((b->objp != NULL) && (b->objp->signature == b->sig) && (b->objp->type == OBJ_SHIP) && (b->objp->instance >= 0) && (b->objp->instance < MAX_SHIPS)){ // get subsytem strength subsys_strength = ship_get_subsystem_strength(&Ships[b->objp->instance], SUBSYSTEM_WEAPONS); // when subsytem strength is 0, double the aim error factor aim += aim * (1.0f - subsys_strength); } // shot aim is a direct linear factor of the target model's radius. // so, pick a random point on the circle vm_vec_sub(&forward, &b->last_shot, &b->last_start); vm_vec_normalize_quick(&forward); // vector vm_vector_2_matrix(&m, &forward, NULL, NULL); // get a random vector on the circle, but somewhat biased towards the center vm_vec_random_in_circle(&circle, &b->last_shot, &m, aim * b->target->radius, false, true); // get the vector pointing to the circle point vm_vec_sub(&forward, &circle, &b->last_start); vm_vec_scale_add(&b->last_shot, &b->last_start, &forward, 2.0f); } // -----------------------------===========================------------------------------ // BEAM COLLISION FUNCTIONS // -----------------------------===========================------------------------------ // collide a beam with a ship, returns 1 if we can ignore all future collisions between the 2 objects int beam_collide_ship(obj_pair *pair) { beam * a_beam; object *weapon_objp; object *ship_objp; ship *shipp; ship_info *sip; weapon_info *bwi; mc_info mc, mc_shield, mc_hull_enter, mc_hull_exit; int model_num; float width; // bogus if (pair == NULL) { return 0; } if (reject_due_collision_groups(pair->a, pair->b)) return 0; // get the beam Assert(pair->a->instance >= 0); Assert(pair->a->type == OBJ_BEAM); Assert(Beams[pair->a->instance].objnum == OBJ_INDEX(pair->a)); weapon_objp = pair->a; a_beam = &Beams[pair->a->instance]; // Don't check collisions for warping out player if past stage 1. if (Player->control_mode >= PCM_WARPOUT_STAGE1) { if ( pair->a == Player_obj ) return 0; if ( pair->b == Player_obj ) return 0; } // if the "warming up" timestamp has not expired if ((a_beam->warmup_stamp != -1) || (a_beam->warmdown_stamp != -1)) { return 0; } // if the beam is on "safety", don't collide with anything if (a_beam->flags & BF_SAFETY) { return 0; } // if the colliding object is the shooting object, return 1 so this is culled if (pair->b == a_beam->objp) { return 1; } // try and get a model model_num = beam_get_model(pair->b); if (model_num < 0) { return 1; } #ifndef NDEBUG Beam_test_ints++; Beam_test_ship++; #endif // get the ship Assert(pair->b->instance >= 0); Assert(pair->b->type == OBJ_SHIP); Assert(Ships[pair->b->instance].objnum == OBJ_INDEX(pair->b)); if ((pair->b->type != OBJ_SHIP) || (pair->b->instance < 0)) return 1; ship_objp = pair->b; shipp = &Ships[ship_objp->instance]; if (shipp->flags[Ship::Ship_Flags::Arriving_stage_1]) return 0; int quadrant_num = -1; bool valid_hit_occurred = false; sip = &Ship_info[shipp->ship_info_index]; bwi = &Weapon_info[a_beam->weapon_info_index]; polymodel *pm = model_get(model_num); // get the width of the beam width = a_beam->beam_collide_width * a_beam->current_width_factor; // Goober5000 - I tried to make collision code much saner... here begin the (major) changes mc_info_init(&mc); // set up collision structs, part 1 mc.model_instance_num = shipp->model_instance_num; mc.model_num = model_num; mc.submodel_num = -1; mc.orient = &ship_objp->orient; mc.pos = &ship_objp->pos; mc.p0 = &a_beam->last_start; mc.p1 = &a_beam->last_shot; // maybe do a sphereline if (width > ship_objp->radius * BEAM_AREA_PERCENT) { mc.radius = width * 0.5f; mc.flags = MC_CHECK_SPHERELINE; } else { mc.flags = MC_CHECK_RAY; } // set up collision structs, part 2 memcpy(&mc_shield, &mc, sizeof(mc_info)); memcpy(&mc_hull_enter, &mc, sizeof(mc_info)); memcpy(&mc_hull_exit, &mc, sizeof(mc_info)); // reverse this vector so that we check for exit holes as opposed to entrance holes mc_hull_exit.p1 = &a_beam->last_start; mc_hull_exit.p0 = &a_beam->last_shot; // set flags mc_shield.flags |= MC_CHECK_SHIELD; mc_hull_enter.flags |= MC_CHECK_MODEL; mc_hull_exit.flags |= MC_CHECK_MODEL; // check all three kinds of collisions int shield_collision = (pm->shield.ntris > 0) ? model_collide(&mc_shield) : 0; int hull_enter_collision = model_collide(&mc_hull_enter); int hull_exit_collision = (beam_will_tool_target(a_beam, ship_objp)) ? model_collide(&mc_hull_exit) : 0; // If we have a range less than the "far" range, check if the ray actually hit within the range if (a_beam->range < BEAM_FAR_LENGTH && (shield_collision || hull_enter_collision || hull_exit_collision)) { // We can't use hit_dist as "1" is the distance between p0 and p1 float rangeSq = a_beam->range * a_beam->range; // actually make sure that the collision points are within range of our beam if (shield_collision && vm_vec_dist_squared(&a_beam->last_start, &mc_shield.hit_point_world) > rangeSq) { shield_collision = 0; } if (hull_enter_collision && vm_vec_dist_squared(&a_beam->last_start, &mc_hull_enter.hit_point_world) > rangeSq) { hull_enter_collision = 0; } if (hull_exit_collision && vm_vec_dist_squared(&mc_hull_exit.hit_point_world, &a_beam->last_start) > rangeSq) { hull_exit_collision = 0; } } if (hull_enter_collision || hull_exit_collision || shield_collision) { WarpEffect* warp_effect = nullptr; if (shipp->flags[Ship::Ship_Flags::Depart_warp] && shipp->warpout_effect != nullptr) warp_effect = shipp->warpout_effect; else if (shipp->flags[Ship::Ship_Flags::Arriving_stage_2] && shipp->warpin_effect != nullptr) warp_effect = shipp->warpin_effect; bool hull_no_collide, shield_no_collide; hull_no_collide = shield_no_collide = false; if (warp_effect != nullptr) { hull_no_collide = point_is_clipped_by_warp(&mc_hull_enter.hit_point_world, warp_effect); shield_no_collide = point_is_clipped_by_warp(&mc_shield.hit_point_world, warp_effect); } if (hull_no_collide) hull_enter_collision = hull_exit_collision = 0; if (shield_no_collide) shield_collision = 0; } // check shields for impact // (tooled ships are probably not going to be maintaining a shield over their exit hole, // therefore we need only check the entrance, just as with conventional weapons) if (!(ship_objp->flags[Object::Object_Flags::No_shields])) { // pick out the shield quadrant if (shield_collision) quadrant_num = get_quadrant(&mc_shield.hit_point, ship_objp); else if (hull_enter_collision && (sip->flags[Ship::Info_Flags::Surface_shields])) quadrant_num = get_quadrant(&mc_hull_enter.hit_point, ship_objp); // make sure that the shield is active in that quadrant if ((quadrant_num >= 0) && ((shipp->flags[Ship::Ship_Flags::Dying]) || !ship_is_shield_up(ship_objp, quadrant_num))) quadrant_num = -1; // see if we hit the shield if (quadrant_num >= 0) { // do the hit effect if (shield_collision) { if (mc_shield.shield_hit_tri != -1) { add_shield_point(OBJ_INDEX(ship_objp), mc_shield.shield_hit_tri, &mc_shield.hit_point); } } else { /* TODO */; } // if this weapon pierces the shield, then do the hit effect, but act like a shield collision never occurred; // otherwise, we have a valid hit on this shield if (bwi->wi_flags[Weapon::Info_Flags::Pierce_shields]) quadrant_num = -1; else valid_hit_occurred = 1; } } // see which impact we use if (shield_collision && valid_hit_occurred) { memcpy(&mc, &mc_shield, sizeof(mc_info)); Assert(quadrant_num >= 0); } else if (hull_enter_collision) { memcpy(&mc, &mc_hull_enter, sizeof(mc_info)); valid_hit_occurred = 1; } // if we got a hit if (valid_hit_occurred) { // since we might have two collisions handled the same way, let's loop over both of them mc_info *mc_array[2]; int mc_size = 1; mc_array[0] = &mc; if (hull_exit_collision) { mc_array[1] = &mc_hull_exit; ++mc_size; } for (int i = 0; i < mc_size; ++i) { bool ship_override = false, weapon_override = false; if (Script_system.IsActiveAction(CHA_COLLIDEBEAM)) { Script_system.SetHookObjects(4, "Self", ship_objp, "Object", weapon_objp, "Ship", ship_objp, "Beam", weapon_objp); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(mc_array[i]->hit_point_world)); ship_override = Script_system.IsConditionOverride(CHA_COLLIDEBEAM, ship_objp); Script_system.RemHookVars({ "Self", "Object", "Ship", "Beam", "Hitpos" }); } if (Script_system.IsActiveAction(CHA_COLLIDESHIP)) { Script_system.SetHookObjects(4, "Self", weapon_objp, "Object", ship_objp, "Ship", ship_objp, "Beam", weapon_objp); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(mc_array[i]->hit_point_world)); weapon_override = Script_system.IsConditionOverride(CHA_COLLIDESHIP, weapon_objp); Script_system.RemHookVars({ "Self", "Object", "Ship", "Beam", "Hitpos" }); } if (!ship_override && !weapon_override) { // add to the collision_list // if we got "tooled", add an exit hole too beam_add_collision(a_beam, ship_objp, mc_array[i], quadrant_num, i != 0); } if (Script_system.IsActiveAction(CHA_COLLIDEBEAM) && !(weapon_override && !ship_override)) { Script_system.SetHookObjects(4, "Self", ship_objp, "Object", weapon_objp, "Ship", ship_objp, "Beam", weapon_objp); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(mc_array[i]->hit_point_world)); Script_system.RunCondition(CHA_COLLIDEBEAM, ship_objp); Script_system.RemHookVars({ "Self", "Object", "Ship", "Beam", "Hitpos" }); } if (Script_system.IsActiveAction(CHA_COLLIDESHIP) && ((weapon_override && !ship_override) || (!weapon_override && !ship_override))) { Script_system.SetHookObjects(4, "Self", weapon_objp, "Object", ship_objp, "Ship", ship_objp, "Beam", weapon_objp); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(mc_array[i]->hit_point_world)); Script_system.RunCondition(CHA_COLLIDESHIP, weapon_objp); Script_system.RemHookVars({ "Self", "Object", "Ship", "Beam", "Hitpos" }); } } } // reset timestamp to timeout immediately pair->next_check_time = timestamp(0); return 0; } // collide a beam with an asteroid, returns 1 if we can ignore all future collisions between the 2 objects int beam_collide_asteroid(obj_pair *pair) { beam * a_beam; mc_info test_collide; int model_num; // bogus if(pair == NULL){ return 0; } // get the beam Assert(pair->a->instance >= 0); Assert(pair->a->type == OBJ_BEAM); Assert(Beams[pair->a->instance].objnum == OBJ_INDEX(pair->a)); a_beam = &Beams[pair->a->instance]; // if the "warming up" timestamp has not expired if((a_beam->warmup_stamp != -1) || (a_beam->warmdown_stamp != -1)){ return 0; } // if the beam is on "safety", don't collide with anything if(a_beam->flags & BF_SAFETY){ return 0; } // if the colliding object is the shooting object, return 1 so this is culled if(pair->b == a_beam->objp){ return 1; } // try and get a model model_num = beam_get_model(pair->b); if(model_num < 0){ Int3(); return 1; } #ifndef NDEBUG Beam_test_ints++; Beam_test_ast++; #endif // do the collision mc_info_init(&test_collide); test_collide.model_instance_num = -1; test_collide.model_num = model_num; test_collide.submodel_num = -1; test_collide.orient = &pair->b->orient; test_collide.pos = &pair->b->pos; test_collide.p0 = &a_beam->last_start; test_collide.p1 = &a_beam->last_shot; test_collide.flags = MC_CHECK_MODEL | MC_CHECK_RAY; model_collide(&test_collide); // if we got a hit if (test_collide.num_hits) { // add to the collision list bool weapon_override = false, asteroid_override = false; if (Script_system.IsActiveAction(CHA_COLLIDEASTEROID)) { Script_system.SetHookObjects(4, "Self", pair->a, "Object", pair->b, "Beam", pair->a, "Asteroid", pair->b); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(test_collide.hit_point_world)); weapon_override = Script_system.IsConditionOverride(CHA_COLLIDEASTEROID, pair->a); Script_system.RemHookVars({ "Self", "Object", "Beam", "Asteroid", "Hitpos" }); } if (Script_system.IsActiveAction(CHA_COLLIDEBEAM)) { Script_system.SetHookObjects(4, "Self", pair->b, "Object", pair->a, "Beam", pair->a, "Asteroid", pair->b); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(test_collide.hit_point_world)); asteroid_override = Script_system.IsConditionOverride(CHA_COLLIDEBEAM, pair->b); Script_system.RemHookVars({ "Self", "Object", "Beam", "Asteroid", "Hitpos" }); } if (!weapon_override && !asteroid_override) { beam_add_collision(a_beam, pair->b, &test_collide); } if (Script_system.IsActiveAction(CHA_COLLIDEASTEROID) && !(asteroid_override && !weapon_override)) { Script_system.SetHookObjects(4, "Self", pair->a, "Object", pair->b, "Beam", pair->a, "Asteroid", pair->b); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(test_collide.hit_point_world)); Script_system.RunCondition(CHA_COLLIDEASTEROID, pair->a); Script_system.RemHookVars({ "Self", "Object", "Beam", "Asteroid", "Hitpos" }); } if (Script_system.IsActiveAction(CHA_COLLIDEBEAM) && ((asteroid_override && !weapon_override) || (!asteroid_override && !weapon_override))) { Script_system.SetHookObjects(4, "Self", pair->b, "Object", pair->a, "Beam", pair->a, "Asteroid", pair->b); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(test_collide.hit_point_world)); Script_system.RunCondition(CHA_COLLIDEBEAM, pair->b); Script_system.RemHookVars({ "Self", "Object", "Beam", "Asteroid", "Hitpos" }); } return 0; } // reset timestamp to timeout immediately pair->next_check_time = timestamp(0); return 0; } // collide a beam with a missile, returns 1 if we can ignore all future collisions between the 2 objects int beam_collide_missile(obj_pair *pair) { beam *a_beam; mc_info test_collide; int model_num; // bogus if(pair == NULL){ return 0; } // get the beam Assert(pair->a->instance >= 0); Assert(pair->a->type == OBJ_BEAM); Assert(Beams[pair->a->instance].objnum == OBJ_INDEX(pair->a)); a_beam = &Beams[pair->a->instance]; // if the "warming up" timestamp has not expired if((a_beam->warmup_stamp != -1) || (a_beam->warmdown_stamp != -1)){ return 0; } // if the beam is on "safety", don't collide with anything if(a_beam->flags & BF_SAFETY){ return 0; } // don't collide if the beam and missile share their parent if (pair->b->parent_sig >= 0 && a_beam->objp && pair->b->parent_sig == a_beam->objp->signature) { return 1; } // try and get a model model_num = beam_get_model(pair->b); if(model_num < 0){ return 1; } #ifndef NDEBUG Beam_test_ints++; #endif // do the collision mc_info_init(&test_collide); test_collide.model_instance_num = -1; test_collide.model_num = model_num; test_collide.submodel_num = -1; test_collide.orient = &pair->b->orient; test_collide.pos = &pair->b->pos; test_collide.p0 = &a_beam->last_start; test_collide.p1 = &a_beam->last_shot; test_collide.flags = MC_CHECK_MODEL | MC_CHECK_RAY; model_collide(&test_collide); // if we got a hit if(test_collide.num_hits) { // add to the collision list bool a_override = false, b_override = false; if (Script_system.IsActiveAction(CHA_COLLIDEWEAPON)) { Script_system.SetHookObjects(4, "Self", pair->a, "Object", pair->b, "Beam", pair->a, "Weapon", pair->b); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(test_collide.hit_point_world)); a_override = Script_system.IsConditionOverride(CHA_COLLIDEWEAPON, pair->a); Script_system.RemHookVars({ "Self", "Object", "Beam", "Weapon", "Hitpos" }); } //Should be reversed if (Script_system.IsActiveAction(CHA_COLLIDEBEAM)) { Script_system.SetHookObjects(4, "Self", pair->b, "Object", pair->a, "Beam", pair->a, "Weapon", pair->b); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(test_collide.hit_point_world)); b_override = Script_system.IsConditionOverride(CHA_COLLIDEBEAM, pair->b); Script_system.RemHookVars({ "Self", "Object", "Beam", "Weapon", "Hitpos" }); } if(!a_override && !b_override) { beam_add_collision(a_beam, pair->b, &test_collide); } if(Script_system.IsActiveAction(CHA_COLLIDEWEAPON) && !(b_override && !a_override)) { Script_system.SetHookObjects(4, "Self", pair->a, "Object", pair->b, "Beam", pair->a, "Weapon", pair->b); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(test_collide.hit_point_world)); Script_system.RunCondition(CHA_COLLIDEWEAPON, pair->a); Script_system.RemHookVars({ "Self", "Object", "Beam", "Weapon", "Hitpos" }); } if(Script_system.IsActiveAction(CHA_COLLIDEBEAM) && ((b_override && !a_override) || (!b_override && !a_override))) { //Should be reversed Script_system.SetHookObjects(4, "Self", pair->b, "Object", pair->a, "Beam", pair->a, "Weapon", pair->b); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(test_collide.hit_point_world)); Script_system.RunCondition(CHA_COLLIDEBEAM, pair->b); Script_system.RemHookVars({ "Self", "Object", "Beam", "Weapon", "Hitpos" }); } } // reset timestamp to timeout immediately pair->next_check_time = timestamp(0); return 0; } // collide a beam with debris, returns 1 if we can ignore all future collisions between the 2 objects int beam_collide_debris(obj_pair *pair) { beam * a_beam; mc_info test_collide; int model_num; // bogus if(pair == NULL){ return 0; } if (reject_due_collision_groups(pair->a, pair->b)) return 0; // get the beam Assert(pair->a->instance >= 0); Assert(pair->a->type == OBJ_BEAM); Assert(Beams[pair->a->instance].objnum == OBJ_INDEX(pair->a)); a_beam = &Beams[pair->a->instance]; // if the "warming up" timestamp has not expired if((a_beam->warmup_stamp != -1) || (a_beam->warmdown_stamp != -1)){ return 0; } // if the beam is on "safety", don't collide with anything if(a_beam->flags & BF_SAFETY){ return 0; } // if the colliding object is the shooting object, return 1 so this is culled if(pair->b == a_beam->objp){ return 1; } // try and get a model model_num = beam_get_model(pair->b); if(model_num < 0){ return 1; } #ifndef NDEBUG Beam_test_ints++; #endif // do the collision mc_info_init(&test_collide); test_collide.model_instance_num = -1; test_collide.model_num = model_num; test_collide.submodel_num = -1; test_collide.orient = &pair->b->orient; test_collide.pos = &pair->b->pos; test_collide.p0 = &a_beam->last_start; test_collide.p1 = &a_beam->last_shot; test_collide.flags = MC_CHECK_MODEL | MC_CHECK_RAY; model_collide(&test_collide); // if we got a hit if(test_collide.num_hits) { bool weapon_override = false, debris_override = false; if (Script_system.IsActiveAction(CHA_COLLIDEDEBRIS)) { Script_system.SetHookObjects(4, "Self", pair->a, "Object", pair->b, "Beam", pair->a, "Debris", pair->b); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(test_collide.hit_point_world)); weapon_override = Script_system.IsConditionOverride(CHA_COLLIDEDEBRIS, pair->a); Script_system.RemHookVars({ "Self", "Object", "Beam", "Debris", "Hitpos" }); } if (Script_system.IsActiveAction(CHA_COLLIDEBEAM)) { Script_system.SetHookObjects(4, "Self", pair->b, "Object", pair->a, "Beam", pair->a, "Debris", pair->b); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(test_collide.hit_point_world)); debris_override = Script_system.IsConditionOverride(CHA_COLLIDEBEAM, pair->b); Script_system.RemHookVars({ "Self", "Object", "Beam", "Debris", "Hitpos" }); } if(!weapon_override && !debris_override) { // add to the collision list beam_add_collision(a_beam, pair->b, &test_collide); } if (Script_system.IsActiveAction(CHA_COLLIDEDEBRIS) && !(debris_override && !weapon_override)) { Script_system.SetHookObjects(4, "Self", pair->a, "Object", pair->b, "Beam", pair->a, "Debris", pair->b); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(test_collide.hit_point_world)); Script_system.RunCondition(CHA_COLLIDEDEBRIS, pair->a); Script_system.RemHookVars({ "Self", "Object", "Beam", "Debris", "Hitpos" }); } if (Script_system.IsActiveAction(CHA_COLLIDEBEAM) && ((debris_override && !weapon_override) || (!debris_override && !weapon_override))) { Script_system.SetHookObjects(4, "Self", pair->b, "Object", pair->a, "Beam", pair->a, "Debris", pair->b); Script_system.SetHookVar("Hitpos", 'o', scripting::api::l_Vector.Set(test_collide.hit_point_world)); Script_system.RunCondition(CHA_COLLIDEBEAM, pair->b); Script_system.RemHookVars({ "Self", "Object", "Beam", "Debris", "Hitpos" }); } } // reset timestamp to timeout immediately pair->next_check_time = timestamp(0); return 0; } // early-out function for when adding object collision pairs, return 1 if the pair should be ignored int beam_collide_early_out(object *a, object *b) { beam *bm; weapon_info *bwi; // get the beam Assert(a->instance >= 0); if(a->instance < 0){ return 1; } Assert(a->type == OBJ_BEAM); if(a->type != OBJ_BEAM){ return 1; } Assert(Beams[a->instance].objnum == OBJ_INDEX(a)); if(Beams[a->instance].objnum != OBJ_INDEX(a)){ return 1; } bm = &Beams[a->instance]; Assert(bm->weapon_info_index >= 0); if(bm->weapon_info_index < 0){ return 1; } bwi = &Weapon_info[bm->weapon_info_index]; // if the second object has an invalid instance, bail if(b->instance < 0){ return 1; } if((vm_vec_dist(&bm->last_start, &b->pos)-b->radius) > bwi->b_info.range){ return 1; }//if the object is too far away, don't bother trying to colide with it-Bobboau // baseline bails switch(b->type){ case OBJ_SHIP: break; case OBJ_ASTEROID: // targeting lasers only hit ships /* if(bwi->b_info.beam_type == BEAM_TYPE_C){ return 1; }*/ break; case OBJ_DEBRIS: // targeting lasers only hit ships /* if(bwi->b_info.beam_type == BEAM_TYPE_C){ return 1; }*/ // don't ever collide with non hull pieces if(!Debris[b->instance].is_hull){ return 1; } break; case OBJ_WEAPON: // targeting lasers only hit ships /* if(bwi->b_info.beam_type == BEAM_TYPE_C){ return 1; }*/ if(The_mission.ai_profile->flags[AI::Profile_Flags::Beams_damage_weapons]) { if((Weapon_info[Weapons[b->instance].weapon_info_index].weapon_hitpoints <= 0) && (Weapon_info[Weapons[b->instance].weapon_info_index].subtype == WP_LASER)) { return 1; } } else { // don't ever collide against laser weapons - duh if(Weapon_info[Weapons[b->instance].weapon_info_index].subtype == WP_LASER){ return 1; } } break; } float beam_radius = bm->beam_collide_width * bm->current_width_factor * 0.5f; // do a cylinder-sphere collision test if (!fvi_cylinder_sphere_may_collide(&bm->last_start, &bm->last_shot, beam_radius, &b->pos, b->radius * 1.2f)) { return 1; } // don't cull return 0; } // add a collision to the beam for this frame (to be evaluated later) // Goober5000 - erg. Rearranged for clarity, and also to fix a bug that caused is_exit_collision to hardly ever be assigned, // resulting in "tooled" ships taking twice as much damage (in a later function) as they should. void beam_add_collision(beam *b, object *hit_object, mc_info *cinfo, int quadrant_num, bool exit_flag) { beam_collision *bc = nullptr; int idx; // if we haven't reached the limit for beam collisions, just add it if (b->f_collision_count < MAX_FRAME_COLLISIONS) { bc = &b->f_collisions[b->f_collision_count++]; } // otherwise, we've got to do some checking, ick. // I guess we can always just remove the farthest item else { for (idx = 0; idx < MAX_FRAME_COLLISIONS; idx++) { if ((bc == nullptr) || (b->f_collisions[idx].cinfo.hit_dist > bc->cinfo.hit_dist)) bc = &b->f_collisions[idx]; } } if (bc == nullptr) { Int3(); return; } // copy in bc->c_objnum = OBJ_INDEX(hit_object); bc->cinfo = *cinfo; bc->quadrant = quadrant_num; bc->is_exit_collision = exit_flag; // let the hud shield gauge know when Player or Player target is hit if (quadrant_num >= 0) hud_shield_quadrant_hit(hit_object, quadrant_num); } // sort collisions for the frame bool beam_sort_collisions_func(const beam_collision &b1, const beam_collision &b2) { return (b1.cinfo.hit_dist < b2.cinfo.hit_dist); } // handle a hit on a specific object void beam_handle_collisions(beam *b) { int idx, s_idx; beam_collision r_coll[MAX_FRAME_COLLISIONS]; int r_coll_count = 0; weapon_info *wi; float width; // early out if we had no collisions if(b->f_collision_count <= 0){ return; } // get beam weapon info if((b->weapon_info_index < 0) || (b->weapon_info_index >= weapon_info_size())){ Int3(); return; } wi = &Weapon_info[b->weapon_info_index]; // get the width of the beam width = b->beam_collide_width * b->current_width_factor; // the first thing we need to do is sort the collisions, from closest to farthest std::sort(b->f_collisions, b->f_collisions + b->f_collision_count, beam_sort_collisions_func); float damage_time_mod = (flFrametime * 1000.0f) / i2fl(BEAM_DAMAGE_TIME); float real_damage = wi->damage * damage_time_mod; // now apply all collisions until we reach a ship which "stops" the beam or we reach the end of the list for(idx=0; idx<b->f_collision_count; idx++){ int model_num = -1; int apply_beam_physics = 0; int draw_effects = 1; int first_hit = 1; int target = b->f_collisions[idx].c_objnum; // if we have an invalid object if((target < 0) || (target >= MAX_OBJECTS)){ continue; } // try and get a model to deal with model_num = beam_get_model(&Objects[target]); if(model_num < 0){ continue; } if (wi->wi_flags[Weapon::Info_Flags::Huge]) { if (Objects[target].type == OBJ_SHIP) { ship_type_info *sti; sti = ship_get_type_info(&Objects[target]); if (sti->flags[Ship::Type_Info_Flags::No_huge_impact_eff]) draw_effects = 0; } } //Don't draw effects if we're in the cockpit of the hit ship if (Viewer_obj == &Objects[target]) draw_effects = 0; // add to the recent collision list r_coll[r_coll_count].c_objnum = target; r_coll[r_coll_count].c_sig = Objects[target].signature; r_coll[r_coll_count].c_stamp = -1; r_coll[r_coll_count].cinfo = b->f_collisions[idx].cinfo; r_coll[r_coll_count].quadrant = -1; r_coll[r_coll_count].is_exit_collision = false; // if he was already on the recent collision list, copy his timestamp // also, be sure not to play the impact sound again. for(s_idx=0; s_idx<b->r_collision_count; s_idx++){ if((r_coll[r_coll_count].c_objnum == b->r_collisions[s_idx].c_objnum) && (r_coll[r_coll_count].c_sig == b->r_collisions[s_idx].c_sig)){ // timestamp r_coll[r_coll_count].c_stamp = b->r_collisions[s_idx].c_stamp; // don't play the impact sound again first_hit = 0; } } // if the physics timestamp has expired or is not set yet, apply physics if((r_coll[r_coll_count].c_stamp == -1) || timestamp_elapsed(r_coll[r_coll_count].c_stamp)) { float time_compression = f2fl(Game_time_compression); float delay_time = i2fl(BEAM_DAMAGE_TIME) / time_compression; apply_beam_physics = 1; r_coll[r_coll_count].c_stamp = timestamp(fl2i(delay_time)); } // increment collision count r_coll_count++; // play the impact sound if ( first_hit && (wi->impact_snd.isValid()) ) { snd_play_3d( gamesnd_get_game_sound(wi->impact_snd), &b->f_collisions[idx].cinfo.hit_point_world, &Eye_position ); } // KOMET_EXT --> // draw flash, explosion if (draw_effects && ((wi->piercing_impact_effect.isValid()) || (wi->flash_impact_weapon_expl_effect.isValid()))) { float rnd = frand(); int do_expl = 0; if ((rnd < 0.2f || apply_beam_physics) && wi->impact_weapon_expl_effect.isValid()) { do_expl = 1; } vec3d temp_pos, temp_local_pos; vm_vec_sub(&temp_pos, &b->f_collisions[idx].cinfo.hit_point_world, &Objects[target].pos); vm_vec_rotate(&temp_local_pos, &temp_pos, &Objects[target].orient); vec3d worldNormal; if (Objects[target].type == OBJ_SHIP) { auto shipp = &Ships[Objects[target].instance]; model_instance_find_world_dir(&worldNormal, &b->f_collisions[idx].cinfo.hit_normal, shipp->model_instance_num, b->f_collisions[idx].cinfo.submodel_num, &Objects[target].orient); } else { // Just assume that we don't need to handle model subobjects here vm_vec_unrotate(&worldNormal, &b->f_collisions[idx].cinfo.hit_normal, &Objects[target].orient); } if (wi->flash_impact_weapon_expl_effect.isValid()) { auto particleSource = particle::ParticleManager::get()->createSource(wi->flash_impact_weapon_expl_effect); particleSource.moveToObject(&Objects[target], &temp_local_pos); particleSource.setOrientationNormal(&worldNormal); vec3d fvec; vm_vec_sub(&fvec, &b->last_shot, &b->last_start); if (!IS_VEC_NULL(&fvec)) { particleSource.setOrientationFromVec(&fvec); } particleSource.finish(); } if(do_expl){ auto particleSource = particle::ParticleManager::get()->createSource(wi->impact_weapon_expl_effect); particleSource.moveToObject(&Objects[target], &temp_local_pos); particleSource.setOrientationNormal(&worldNormal); vec3d fvec; vm_vec_sub(&fvec, &b->last_shot, &b->last_start); if (!IS_VEC_NULL(&fvec)) { particleSource.setOrientationFromVec(&fvec); } particleSource.finish(); } if (wi->piercing_impact_effect.isValid()) { vec3d fvec; vm_vec_sub(&fvec, &b->last_shot, &b->last_start); if(!IS_VEC_NULL(&fvec)){ // get beam direction int ok_to_draw = 0; if (beam_will_tool_target(b, &Objects[target])) { ok_to_draw = 1; if (Objects[target].type == OBJ_SHIP) { ship *shipp = &Ships[Objects[target].instance]; if (shipp->armor_type_idx != -1) { if (Armor_types[shipp->armor_type_idx].GetPiercingType(wi->damage_type_idx) == SADTF_PIERCING_RETAIL) { ok_to_draw = 0; } } } } else { ok_to_draw = 0; if (Objects[target].type == OBJ_SHIP) { float draw_limit, hull_pct; int dmg_type_idx, piercing_type; ship *shipp = &Ships[Objects[target].instance]; hull_pct = Objects[target].hull_strength / shipp->ship_max_hull_strength; dmg_type_idx = wi->damage_type_idx; draw_limit = Ship_info[shipp->ship_info_index].piercing_damage_draw_limit; if (shipp->armor_type_idx != -1) { piercing_type = Armor_types[shipp->armor_type_idx].GetPiercingType(dmg_type_idx); if (piercing_type == SADTF_PIERCING_DEFAULT) { draw_limit = Armor_types[shipp->armor_type_idx].GetPiercingLimit(dmg_type_idx); } else if ((piercing_type == SADTF_PIERCING_NONE) || (piercing_type == SADTF_PIERCING_RETAIL)) { draw_limit = -1.0f; } } if ((draw_limit != -1.0f) && (hull_pct <= draw_limit)) ok_to_draw = 1; } } if (ok_to_draw){ vm_vec_normalize_quick(&fvec); // stream of fire for big ships if (width <= Objects[target].radius * BEAM_AREA_PERCENT) { auto particleSource = particle::ParticleManager::get()->createSource(wi->piercing_impact_effect); particleSource.moveTo(&b->f_collisions[idx].cinfo.hit_point_world); particleSource.setOrientationFromNormalizedVec(&fvec); particleSource.setOrientationNormal(&worldNormal); particleSource.finish(); } } } } // <-- KOMET_EXT } else { if(draw_effects && apply_beam_physics && !physics_paused){ // maybe draw an explosion, if we aren't hitting shields if ((wi->impact_weapon_expl_effect.isValid()) && (b->f_collisions[idx].quadrant < 0)) { vec3d worldNormal; if (Objects[target].type == OBJ_SHIP) { auto shipp = &Ships[Objects[target].instance]; model_instance_find_world_dir(&worldNormal, &b->f_collisions[idx].cinfo.hit_normal, shipp->model_instance_num, b->f_collisions[idx].cinfo.submodel_num, &Objects[target].orient); } else { // Just assume that we don't need to handle model subobjects here vm_vec_unrotate(&worldNormal, &b->f_collisions[idx].cinfo.hit_normal, &Objects[target].orient); } auto particleSource = particle::ParticleManager::get()->createSource(wi->impact_weapon_expl_effect); particleSource.moveTo(&b->f_collisions[idx].cinfo.hit_point_world); particleSource.setOrientationNormal(&worldNormal); vec3d fvec; vm_vec_sub(&fvec, &b->last_shot, &b->last_start); if (!IS_VEC_NULL(&fvec)) { particleSource.setOrientationFromVec(&fvec); } particleSource.finish(); } } } if(!physics_paused){ switch(Objects[target].type){ case OBJ_DEBRIS: // hit the debris - the debris hit code takes care of checking for MULTIPLAYER_CLIENT, etc debris_hit(&Objects[target], &Objects[b->objnum], &b->f_collisions[idx].cinfo.hit_point_world, wi->damage); break; case OBJ_WEAPON: if (The_mission.ai_profile->flags[AI::Profile_Flags::Beams_damage_weapons]) { if (!(Game_mode & GM_MULTIPLAYER) || MULTIPLAYER_MASTER) { object *trgt = &Objects[target]; if (trgt->hull_strength > 0) { float attenuation = 1.0f; if ((b->damage_threshold >= 0.0f) && (b->damage_threshold < 1.0f)) { float dist = vm_vec_dist(&b->f_collisions[idx].cinfo.hit_point_world, &b->last_start); float range = b->range; float atten_dist = range * b->damage_threshold; if ((range > dist) && (atten_dist < dist)) { attenuation = 1 - ((dist - atten_dist) / (range - atten_dist)); } } float damage = real_damage * attenuation; int dmg_type_idx = wi->damage_type_idx; weapon_info* trgt_wip = &Weapon_info[Weapons[trgt->instance].weapon_info_index]; if (trgt_wip->armor_type_idx != -1) damage = Armor_types[trgt_wip->armor_type_idx].GetDamage(damage, dmg_type_idx, 1.0f, true); trgt->hull_strength -= damage; if (trgt->hull_strength < 0) { Weapons[trgt->instance].weapon_flags.set(Weapon::Weapon_Flags::Destroyed_by_weapon); weapon_hit(trgt, NULL, &trgt->pos); } } else { if (!(Game_mode & GM_MULTIPLAYER) || MULTIPLAYER_MASTER) { Weapons[trgt->instance].weapon_flags.set(Weapon::Weapon_Flags::Destroyed_by_weapon); weapon_hit(&Objects[target], NULL, &Objects[target].pos); } } } } else { // detonate the missile Assert(Weapon_info[Weapons[Objects[target].instance].weapon_info_index].subtype == WP_MISSILE); if (!(Game_mode & GM_MULTIPLAYER) || MULTIPLAYER_MASTER) { Weapons[Objects[target].instance].weapon_flags.set(Weapon::Weapon_Flags::Destroyed_by_weapon); weapon_hit(&Objects[target], NULL, &Objects[target].pos); } } break; case OBJ_ASTEROID: // hit the asteroid if (!(Game_mode & GM_MULTIPLAYER) || MULTIPLAYER_MASTER) { asteroid_hit(&Objects[target], &Objects[b->objnum], &b->f_collisions[idx].cinfo.hit_point_world, wi->damage); } break; case OBJ_SHIP: // hit the ship - again, the innards of this code handle multiplayer cases // maybe vaporize ship. //only apply damage if the collision is not an exit collision. this prevents twice the damage from being done, although it probably be more realistic since two holes are being punched in the ship instead of one. if (!b->f_collisions[idx].is_exit_collision) { real_damage = beam_get_ship_damage(b, &Objects[target], &b->f_collisions[idx].cinfo.hit_point_world) * damage_time_mod; ship_apply_local_damage(&Objects[target], &Objects[b->objnum], &b->f_collisions[idx].cinfo.hit_point_world, real_damage, wi->damage_type_idx, b->f_collisions[idx].quadrant); } // if this is the first hit on the player ship. whack him if(apply_beam_physics) { beam_apply_whack(b, &Objects[target], &b->f_collisions[idx].cinfo.hit_point_world); } break; } } // if the radius of the target is somewhat close to the radius of the beam, "stop" the beam here // for now : if its smaller than about 1/3 the radius of the ship if(width <= (Objects[target].radius * BEAM_AREA_PERCENT) && !beam_will_tool_target(b, &Objects[target])){ // set last_shot so we know where to properly draw the beam b->last_shot = b->f_collisions[idx].cinfo.hit_point_world; Assert(is_valid_vec(&b->last_shot)); // done wif the beam break; } } // store the new recent collisions for(idx=0; idx<r_coll_count; idx++){ b->r_collisions[idx] = r_coll[idx]; } b->r_collision_count = r_coll_count; } // if it is legal for the beam to fire, or continue firing int beam_ok_to_fire(beam *b) { if (b->objp == NULL) { // If we don't have a firing object, none of these checks make sense. return 1; } // if my own object is invalid, stop firing if (b->objp->signature != b->sig) { mprintf(("BEAM : killing beam because of invalid parent object SIGNATURE!\n")); return -1; } // if my own object is a ghost if (b->objp->type != OBJ_SHIP) { mprintf(("BEAM : killing beam because of invalid parent object TYPE!\n")); return -1; } // targeting type beams are ok to fire all the time if (b->type == BeamType::TARGETING) { ship *shipp = &Ships[b->objp->instance]; if (shipp->weapon_energy <= 0.0f ) { if ( OBJ_INDEX(Player_obj) == shipp->objnum && !(b->life_left>0.0f)) { extern void ship_maybe_play_primary_fail_sound(); ship_maybe_play_primary_fail_sound(); } return 0; } else { return 1; } } if (b->subsys == NULL) { // IF we don't have a firing turret, none of these checks make sense. return 1; } if (!(b->flags & BF_FORCE_FIRING)) { // if the shooting turret is destroyed if (b->subsys->current_hits <= 0.0f) { mprintf(("BEAM : killing beam because turret has been destroyed!\n")); return -1; } // kill it if its disrupted if (ship_subsys_disrupted(b->subsys)) { return -1; } // if the beam will be firing out of its FOV, power it down vec3d aim_dir; vm_vec_sub(&aim_dir, &b->last_shot, &b->last_start); vm_vec_normalize(&aim_dir); if (The_mission.ai_profile->flags[AI::Profile_Flags::Force_beam_turret_fov]) { vec3d turret_normal; if (b->flags & BF_IS_FIGHTER_BEAM) { turret_normal = b->objp->orient.vec.fvec; b->subsys->system_info->flags.remove(Model::Subsystem_Flags::Turret_restricted_fov); } else { model_instance_find_world_dir(&turret_normal, &b->subsys->system_info->turret_norm, Ships[b->objp->instance].model_instance_num, b->subsys->system_info->subobj_num, &b->objp->orient, true); } if (!(turret_fov_test(b->subsys, &turret_normal, &aim_dir))) { nprintf(("BEAM", "BEAM : powering beam down because of FOV condition!\n")); return 0; } } else { vec3d turret_dir, turret_pos, temp; beam_get_global_turret_gun_info(b->objp, b->subsys, &turret_pos, &turret_dir, 1, &temp, (b->flags & BF_IS_FIGHTER_BEAM) > 0); if (vm_vec_dot(&aim_dir, &turret_dir) < b->subsys->system_info->turret_fov) { nprintf(("BEAM", "BEAM : powering beam down because of FOV condition!\n")); return 0; } } } // ok to fire/continue firing return 1; } // apply a whack to a ship void beam_apply_whack(beam *b, object *objp, vec3d *hit_point) { weapon_info *wip; ship *shipp; // sanity Assert((b != NULL) && (objp != NULL) && (hit_point != NULL)); if((b == NULL) || (objp == NULL) || (hit_point == NULL)){ return; } Assert(b->weapon_info_index >= 0); wip = &Weapon_info[b->weapon_info_index]; Assert((objp != NULL) && (objp->type == OBJ_SHIP) && (objp->instance >= 0) && (objp->instance < MAX_SHIPS)); if((objp == NULL) || (objp->type != OBJ_SHIP) || (objp->instance < 0) || (objp->instance >= MAX_SHIPS)){ return; } shipp = &Ships[objp->instance]; if((shipp->ai_index < 0) || (shipp->ai_index >= MAX_AI_INFO)){ return; } // don't whack docked ships // Goober5000 - whacking docked ships should work now, so whack them // Goober5000 - weapons with no mass don't whack (bypass the calculations) if(wip->mass == 0.0f) { return; } // determine how big of a whack to apply float whack; // this if block was added by Bobboau to make beams whack properly while preserving reverse compatibility if(wip->mass == 100.0f){ if(wip->damage < b_whack_damage){ whack = b_whack_small; } else { whack = b_whack_big; } }else{ whack = wip->mass; } // whack direction vec3d whack_dir; vm_vec_sub(&whack_dir, &b->last_shot, &b->last_start); // Valathil - use the beam direction as the force direction (like a high pressure water jet) vm_vec_normalize(&whack_dir); vm_vec_scale(&whack_dir, whack); // apply the whack ship_apply_whack(&whack_dir, hit_point, objp); } // return the amount of damage which should be applied to a ship. basically, filters friendly fire damage float beam_get_ship_damage(beam *b, object *objp, vec3d* hitpos) { // if the beam is on the same team as the object if ( (objp == NULL) || (b == NULL) ) { Int3(); return 0.0f; } if ( (objp->type != OBJ_SHIP) || (objp->instance < 0) || (objp->instance >= MAX_SHIPS) ) { Int3(); return 0.0f; } weapon_info *wip = &Weapon_info[b->weapon_info_index]; if (wip->damage <= 0) return 0.0f; // Not much point in calculating the attenuation if the beam doesn't hurt in the first place. float attenuation = 1.0f; if ((b->damage_threshold >= 0.0f) && (b->damage_threshold < 1.0f)) { float dist = hitpos ? vm_vec_dist(hitpos, &b->last_start) : 0.0f; float range = b->range; float atten_dist = range * b->damage_threshold; if ((range > dist) && (atten_dist < dist)) { attenuation = 1 - ((dist - atten_dist) / (range - atten_dist)); } } float damage = 0.0f; // same team. yikes if ( (b->team == Ships[objp->instance].team) && (wip->damage > The_mission.ai_profile->beam_friendly_damage_cap[Game_skill_level]) ) { damage = The_mission.ai_profile->beam_friendly_damage_cap[Game_skill_level] * attenuation; } else { // normal damage damage = wip->damage * attenuation; } return damage; } // if the beam is likely to tool a given target before its lifetime expires int beam_will_tool_target(beam *b, object *objp) { weapon_info *wip = &Weapon_info[b->weapon_info_index]; float total_strength, damage_in_a_few_seconds, hp_limit, hp_pct; // sanity if(objp == NULL){ return 0; } // if the object is not a ship, bail if(objp->type != OBJ_SHIP){ return 0; } if((objp->instance < 0) || (objp->instance >= MAX_SHIPS)){ return 0; } ship *shipp = &Ships[objp->instance]; total_strength = objp->hull_strength; if (shipp->armor_type_idx != -1) { if (Armor_types[shipp->armor_type_idx].GetPiercingType(wip->damage_type_idx) == SADTF_PIERCING_NONE) { return 0; } hp_limit = Armor_types[shipp->armor_type_idx].GetPiercingLimit(wip->damage_type_idx); if (hp_limit > 0.0f) { hp_pct = total_strength / shipp->ship_max_hull_strength; if (hp_limit >= hp_pct) return 1; } } // calculate total strength, factoring in shield if (!(wip->wi_flags[Weapon::Info_Flags::Pierce_shields])) total_strength += shield_get_strength(objp); // if the beam is going to apply more damage in about 1 and a half than the ship can take damage_in_a_few_seconds = (TOOLTIME / (float)BEAM_DAMAGE_TIME) * wip->damage; return (damage_in_a_few_seconds > total_strength); } float beam_accuracy = 1.0f; DCF(b_aim, "Adjusts the beam accuracy factor (Default is 1.0f)") { dc_stuff_float(&beam_accuracy); } DCF(beam_list, "Lists all beams") { int b_count = 0; for (auto &wi : Weapon_info) { if (wi.wi_flags[Weapon::Info_Flags::Beam]) { ++b_count; dc_printf("Beam %d : %s\n", b_count, wi.name); } } }
55,602
703
<reponame>Tekh-ops/ezEngine #include <RendererCore/RendererCorePCH.h> #include <Core/WorldSerializer/WorldReader.h> #include <Core/WorldSerializer/WorldWriter.h> #include <RendererCore/Components/RenderTargetActivatorComponent.h> #include <RendererCore/Pipeline/ExtractedRenderData.h> #include <RendererCore/Pipeline/View.h> #include <RendererCore/RenderWorld/RenderWorld.h> // clang-format off EZ_BEGIN_COMPONENT_TYPE(ezRenderTargetActivatorComponent, 1, ezComponentMode::Static) { EZ_BEGIN_PROPERTIES { EZ_ACCESSOR_PROPERTY("RenderTarget", GetRenderTargetFile, SetRenderTargetFile)->AddAttributes(new ezAssetBrowserAttribute("Render Target")), } EZ_END_PROPERTIES; EZ_BEGIN_ATTRIBUTES { new ezCategoryAttribute("Rendering"), } EZ_END_ATTRIBUTES; EZ_BEGIN_MESSAGEHANDLERS { EZ_MESSAGE_HANDLER(ezMsgExtractRenderData, OnMsgExtractRenderData), } EZ_END_MESSAGEHANDLERS; } EZ_END_COMPONENT_TYPE; // clang-format on ezRenderTargetActivatorComponent::ezRenderTargetActivatorComponent() = default; ezRenderTargetActivatorComponent::~ezRenderTargetActivatorComponent() = default; void ezRenderTargetActivatorComponent::SerializeComponent(ezWorldWriter& stream) const { SUPER::SerializeComponent(stream); ezStreamWriter& s = stream.GetStream(); s << m_hRenderTarget; } void ezRenderTargetActivatorComponent::DeserializeComponent(ezWorldReader& stream) { SUPER::DeserializeComponent(stream); // const ezUInt32 uiVersion = stream.GetComponentTypeVersion(GetStaticRTTI()); ezStreamReader& s = stream.GetStream(); s >> m_hRenderTarget; } ezResult ezRenderTargetActivatorComponent::GetLocalBounds(ezBoundingBoxSphere& bounds, bool& bAlwaysVisible) { if (m_hRenderTarget.IsValid()) { bounds = ezBoundingSphere(ezVec3::ZeroVector(), 0.1f); return EZ_SUCCESS; } return EZ_FAILURE; } void ezRenderTargetActivatorComponent::OnMsgExtractRenderData(ezMsgExtractRenderData& msg) const { // only add render target views from main views // otherwise every shadow casting light source would activate a render target if (msg.m_pView->GetCameraUsageHint() != ezCameraUsageHint::MainView && msg.m_pView->GetCameraUsageHint() != ezCameraUsageHint::EditorView) return; if (!m_hRenderTarget.IsValid()) return; ezResourceLock<ezRenderToTexture2DResource> pRenderTarget(m_hRenderTarget, ezResourceAcquireMode::BlockTillLoaded); for (auto hView : pRenderTarget->GetAllRenderViews()) { ezRenderWorld::AddViewToRender(hView); } } void ezRenderTargetActivatorComponent::SetRenderTarget(const ezRenderToTexture2DResourceHandle& hResource) { m_hRenderTarget = hResource; TriggerLocalBoundsUpdate(); } void ezRenderTargetActivatorComponent::SetRenderTargetFile(const char* szFile) { ezRenderToTexture2DResourceHandle hResource; if (!ezStringUtils::IsNullOrEmpty(szFile)) { hResource = ezResourceManager::LoadResource<ezRenderToTexture2DResource>(szFile); } SetRenderTarget(hResource); } const char* ezRenderTargetActivatorComponent::GetRenderTargetFile() const { if (!m_hRenderTarget.IsValid()) return ""; return m_hRenderTarget.GetResourceID(); } EZ_STATICLINK_FILE(RendererCore, RendererCore_Components_Implementation_RenderTargetActivatorComponent);
1,128
1,851
// Copyright © 2016 <NAME>. All rights reserved. // // 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. package com.viromedia.bridge.component.node; import android.provider.MediaStore; import com.facebook.react.bridge.Dynamic; import com.facebook.react.bridge.DynamicFromMap; import com.facebook.react.bridge.JavaOnlyMap; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableType; import com.facebook.react.uimanager.LayoutShadowNode; import com.facebook.react.uimanager.ViewProps; import com.facebook.react.common.MapBuilder; import com.facebook.react.uimanager.annotations.ReactProp; import com.facebook.react.uimanager.annotations.ReactPropGroup; import com.facebook.yoga.YogaConstants; import com.viro.core.Material; import com.viro.core.VideoTexture; import com.viromedia.bridge.component.VRTViroViewGroupManager; import com.viromedia.bridge.module.MaterialManager; import com.viromedia.bridge.module.MaterialManager.MaterialWrapper; import com.viromedia.bridge.utility.Helper; import com.viromedia.bridge.utility.ViroEvents; import com.viromedia.bridge.utility.ViroLog; import java.util.ArrayList; import java.util.Map; import javax.annotation.Nullable; /** * Abstract NodeManager for setting {@link VRTNode} Control properties. * NOTE: Always extend from this class for all Node Viro controls. */ public abstract class VRTNodeManager<T extends VRTNode> extends VRTViroViewGroupManager<T> { public static final float s2DUnitPer3DUnit = 1000; private static final String WIDTH_NAME = "width"; private static final String HEIGHT_NAME = "height"; private static final String PADDING_NAME = "padding"; private static final float[] DEFAULT_ZERO_VEC = new float[]{0,0,0}; public VRTNodeManager(ReactApplicationContext context) { super(context); } @ReactProp(name = "position") public void setPosition(T view, ReadableArray position) { view.setPosition(Helper.toFloatArray(position, DEFAULT_ZERO_VEC)); } @ReactProp(name = "rotation") public void setRotation(VRTNode view, ReadableArray rotation) { view.setRotation(Helper.toFloatArray(rotation, DEFAULT_ZERO_VEC)); } @ReactProp(name = "scale") public void setScale(VRTNode view, ReadableArray scale) { view.setScale(Helper.toFloatArray(scale, new float[]{1,1,1})); } @ReactProp(name = "rotationPivot") public void setRotationPivot(VRTNode view, ReadableArray scale) { view.setRotationPivot(Helper.toFloatArray(scale, DEFAULT_ZERO_VEC)); } @ReactProp(name = "scalePivot") public void setScalePivot(VRTNode view, ReadableArray scale) { view.setScalePivot(Helper.toFloatArray(scale, DEFAULT_ZERO_VEC)); } @ReactProp(name = "opacity", defaultFloat = 1f) public void setOpacity(VRTNode view, float opacity) { view.setOpacity(opacity); } @ReactProp(name = "visible", defaultBoolean = true) public void setVisible(VRTNode view, boolean visibility) { view.setVisible(visibility); } @ReactProp(name = "renderingOrder", defaultInt = 0) public void setRenderingOrder(VRTNode view, int renderingOrder) { view.setRenderingOrder(renderingOrder); } @ReactProp(name = "canHover", defaultBoolean = VRTNode.DEFAULT_CAN_HOVER) public void setCanHover(VRTNode view, boolean canHover) { view.setCanHover(canHover); } @ReactProp(name = "canClick", defaultBoolean = VRTNode.DEFAULT_CAN_CLICK) public void setCanClick(VRTNode view, boolean canClick) { view.setCanClick(canClick); } @ReactProp(name = "canTouch", defaultBoolean = VRTNode.DEFAULT_CAN_TOUCH) public void setCanTouch(VRTNode view, boolean canTouch) { view.setCanTouch(canTouch); } @ReactProp(name = "canScroll", defaultBoolean = VRTNode.DEFAULT_CAN_SCROLL) public void setCanScroll(VRTNode view, boolean canScroll) { view.setCanScroll(canScroll); } @ReactProp(name = "canSwipe", defaultBoolean = VRTNode.DEFAULT_CAN_SWIPE) public void setCanSwipe(VRTNode view, boolean canSwipe) { view.setCanSwipe(canSwipe); } @ReactProp(name = "canDrag", defaultBoolean = VRTNode.DEFAULT_CAN_DRAG) public void setCanDrag(VRTNode view, boolean canDrag) { view.setCanDrag(canDrag); } @ReactProp(name = "canFuse", defaultBoolean = VRTNode.DEFAULT_CAN_FUSE) public void setCanFuse(VRTNode view, boolean canFuse) { view.setCanFuse(canFuse); } @ReactProp(name = "canPinch", defaultBoolean = VRTNode.DEFAULT_CAN_PINCH) public void setCanPinch(VRTNode view, boolean canPinch) { view.setCanPinch(canPinch); } @ReactProp(name = "canRotate", defaultBoolean = VRTNode.DEFAULT_CAN_ROTATE) public void setCanRotate(VRTNode view, boolean canRotate) { view.setCanRotate(canRotate); } @ReactProp(name = "timeToFuse", defaultFloat = VRTNode.DEFAULT_TIME_TO_FUSE_MILLIS) public void setTimeToFuse(VRTNode view, float durationMillis) { view.setTimeToFuse(durationMillis); } @ReactProp(name = "dragType") public void setDragType(VRTNode view, String dragType) { view.setDragType(dragType); } @ReactProp(name = "dragPlane") public void setDragPlane(VRTNode view, ReadableMap dragPlane) { view.setDragPlane(dragPlane); } @ReactProp(name = "animation") public void setAnimation(VRTNode view, @androidx.annotation.Nullable ReadableMap map) { view.setAnimation(map); } @ReactProp(name = "ignoreEventHandling", defaultBoolean = VRTNode.DEFAULT_IGNORE_EVENT_HANDLING) public void setIgnoreEventHandling(VRTNode view, boolean ignore) { view.setIgnoreEventHandling(ignore); } @ReactProp(name = "materials") public void setMaterials(VRTNode view, @Nullable ReadableArray materials) { // get material manager MaterialManager materialManager = getContext().getNativeModule(MaterialManager.class); ArrayList<Material> nativeMaterials = new ArrayList<>(); if (materials != null) { for (int i = 0; i < materials.size(); i++) { Material nativeMaterial = materialManager.getMaterial(materials.getString(i)); if (materialManager.isVideoMaterial(materials.getString(i))) { if (!(nativeMaterial.getDiffuseTexture() instanceof VideoTexture)) { // Recreate the material with the proper context. if (view.getViroContext() != null) { MaterialWrapper materialWrapper = materialManager.getMaterialWrapper(materials.getString(i)); VideoTexture videoTexture = new VideoTexture(view.getViroContext(), materialWrapper.getVideoTextureURI()); materialWrapper.recreate(videoTexture); nativeMaterial = materialWrapper.getNativeMaterial(); } } } if (nativeMaterial == null) { throw new IllegalArgumentException("Material [" + materials.getString(i) + "] not found. Did you create it?"); } nativeMaterials.add(nativeMaterial); } } view.setMaterials(nativeMaterials); } @ReactProp(name = "transformBehaviors") public void setTransformBehaviors(VRTNode view, @Nullable ReadableArray transformBehaviors) { String[] behaviors = new String[0]; if (transformBehaviors != null) { behaviors = new String[transformBehaviors.size()]; for (int i = 0; i < transformBehaviors.size(); i++) { behaviors[i] = transformBehaviors.getString(i); } } view.setTransformBehaviors(behaviors); } @Override public LayoutShadowNode createShadowNodeInstance() { return new FlexEnabledShadowNode(); } @Override public Class<? extends LayoutShadowNode> getShadowNodeClass() { return FlexEnabledShadowNode.class; } /** * This shadow node is so that views associated with FlexViews (and FlexViews themselves) have * their properties properly converted from 3D to 2D units. It's easiest if we just make all Nodes * have FlexEnabledShadowNodes, and the components can choose whether or not */ protected class FlexEnabledShadowNode extends ViroLayoutShadowNode { private final String TAG = ViroLog.getTag(VRTNodeManager.class); @ReactProp(name = "width", defaultFloat = 1) public void setWidth(Dynamic width) { if (width.getType() == ReadableType.String) { super.setWidth(width); } else if (width.getType() == ReadableType.Number){ JavaOnlyMap map = JavaOnlyMap.of(WIDTH_NAME, width.asDouble() * s2DUnitPer3DUnit); Dynamic newWidth = DynamicFromMap.create(map, WIDTH_NAME); super.setWidth(newWidth); } else { ViroLog.warn(TAG, "Width is not of type Number or String. Doing nothing."); } } @ReactProp(name = "height", defaultFloat = 1) public void setHeight(Dynamic height) { if (height.getType() == ReadableType.String) { super.setHeight(height); } else if (height.getType() == ReadableType.Number) { JavaOnlyMap map = JavaOnlyMap.of(HEIGHT_NAME, height.asDouble() * s2DUnitPer3DUnit); Dynamic newHeight = DynamicFromMap.create(map, HEIGHT_NAME); super.setHeight(newHeight); } else { ViroLog.warn(TAG, "Height is not of type Number or String. Doing nothing."); } } @ReactPropGroup(names = { ViewProps.PADDING, ViewProps.PADDING_VERTICAL, ViewProps.PADDING_HORIZONTAL, ViewProps.PADDING_LEFT, ViewProps.PADDING_RIGHT, ViewProps.PADDING_TOP, ViewProps.PADDING_BOTTOM, }, defaultFloat = YogaConstants.UNDEFINED) public void setPaddings(int index, Dynamic padding) { if (padding.getType() == ReadableType.String) { super.setPaddings(index, padding); } else if (padding.getType() == ReadableType.Number) { JavaOnlyMap map = JavaOnlyMap.of(PADDING_NAME, padding.asDouble() * s2DUnitPer3DUnit); Dynamic newPadding = DynamicFromMap.create(map, PADDING_NAME); super.setPaddings(index, newPadding); } else { ViroLog.warn(TAG, "Padding is not of type Number of String. Doing nothing."); } } @ReactPropGroup(names = { ViewProps.BORDER_WIDTH, ViewProps.BORDER_LEFT_WIDTH, ViewProps.BORDER_RIGHT_WIDTH, ViewProps.BORDER_TOP_WIDTH, ViewProps.BORDER_BOTTOM_WIDTH, }, defaultFloat = YogaConstants.UNDEFINED) public void setBorderWidths(int index, float borderWidth) { super.setBorderWidths(index, borderWidth * s2DUnitPer3DUnit); } } /* The only evnets that should be defined in here are input/touch events that bubble up, that way we don't have to "nativePropOnly" a ton of events... */ @Override public Map getExportedCustomDirectEventTypeConstants() { Map events = super.getExportedCustomDirectEventTypeConstants(); events.put(ViroEvents.ON_HOVER, MapBuilder.of("registrationName", ViroEvents.ON_HOVER)); events.put(ViroEvents.ON_CLICK, MapBuilder.of("registrationName", ViroEvents.ON_CLICK)); events.put(ViroEvents.ON_TOUCH, MapBuilder.of("registrationName", ViroEvents.ON_TOUCH)); events.put(ViroEvents.ON_SWIPE, MapBuilder.of("registrationName", ViroEvents.ON_SWIPE)); events.put(ViroEvents.ON_SCROLL, MapBuilder.of("registrationName", ViroEvents.ON_SCROLL)); events.put(ViroEvents.ON_FUSE, MapBuilder.of("registrationName", ViroEvents.ON_FUSE)); events.put(ViroEvents.ON_PINCH, MapBuilder.of("registrationName", ViroEvents.ON_PINCH)); events.put(ViroEvents.ON_ROTATE, MapBuilder.of("registrationName", ViroEvents.ON_ROTATE)); events.put(ViroEvents.ON_DRAG, MapBuilder.of("registrationName", ViroEvents.ON_DRAG)); events.put(ViroEvents.ON_COLLIDED, MapBuilder.of("registrationName", ViroEvents.ON_COLLIDED)); events.put(ViroEvents.ON_TRANSFORM_DELEGATE, MapBuilder.of("registrationName", ViroEvents.ON_TRANSFORM_DELEGATE)); events.put(ViroEvents.ON_ANIMATION_START, MapBuilder.of("registrationName", ViroEvents.ON_ANIMATION_START)); events.put(ViroEvents.ON_ANIMATION_FINISH, MapBuilder.of("registrationName", ViroEvents.ON_ANIMATION_FINISH)); return events; } @ReactProp(name = "physicsBody") public void setPhysicsBody(VRTNode view, ReadableMap map) { view.setPhysicsBody(map); } @ReactProp(name = "canCollide", defaultBoolean = VRTNode.DEFAULT_CAN_FUSE) public void setCanCollide(VRTNode view, boolean canCollide) { view.setCanCollide(canCollide); } @ReactProp(name = "viroTag") public void setViroTag(VRTNode view, String tag) { view.setViroTag(tag); } @ReactProp(name = "hasTransformDelegate", defaultBoolean = false) public void setViroTag(VRTNode view, boolean hasDelegate) { view.setOnNativeTransformDelegate(hasDelegate); } }
5,938
1,338
// TranslatorTestAddOn.h #ifndef TRANSLATOR_TEST_ADD_ON_H #define TRANSLATOR_TEST_ADD_ON_H #include <TestCase.h> #include <TestSuite.h> #include <TestSuiteAddon.h> #include <DataIO.h> #include <TranslationDefs.h> bool CompareStreams(BPositionIO &a, BPositionIO &b); void CheckTranslatorInfo(translator_info *pti, uint32 type, uint32 group, float quality, float capability, const char *name, const char *mime); void TranslatorLoadAddOnTest(const char *path, BTestCase *ptest, const translation_format *pExpectedIns, uint32 nExpectedIns, const translation_format *pExpectedOuts, uint32 nExpectedOuts, int32 expectedVer); #endif // #ifndef TRANSLATOR_TEST_ADD_ON_H
248
1,168
#ifndef BASIC_H #define BASIC_H void foo(); #endif
25
400
package org.ofdrw.gm.ses.v1; import org.bouncycastle.asn1.*; import java.util.Enumeration; /** * 电子印章数据 * * @author 权观宇 * @since 2020-04-19 15:33:55 */ public class SESeal extends ASN1Object { /** * 印章信息 */ private SES_SealInfo esealInfo; /** * 制章人对印章签名的信息 */ private SES_SignInfo signInfo; public SESeal() { super(); } public SESeal(SES_SealInfo esealInfo, SES_SignInfo signInfo) { this.esealInfo = esealInfo; this.signInfo = signInfo; } public SESeal(ASN1Sequence seq) { Enumeration<?> e = seq.getObjects(); esealInfo = SES_SealInfo.getInstance(e.nextElement()); signInfo = SES_SignInfo.getInstance(e.nextElement()); } public static SESeal getInstance(Object o) { if (o instanceof SESeal) { return (SESeal) o; } else if (o != null) { return new SESeal(ASN1Sequence.getInstance(o)); } return null; } public SES_SealInfo getEsealInfo() { return esealInfo; } public SESeal setEsealInfo(SES_SealInfo esealInfo) { this.esealInfo = esealInfo; return this; } public SES_SignInfo getSignInfo() { return signInfo; } public SESeal setSignInfo(SES_SignInfo signInfo) { this.signInfo = signInfo; return this; } @Override public ASN1Primitive toASN1Primitive() { ASN1EncodableVector v = new ASN1EncodableVector(3); v.add(esealInfo); v.add(signInfo); return new DERSequence(v); } }
795
487
// Copyright 2017-2020 The Verible 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. #ifndef VERIBLE_VERILOG_TOOLS_KYTHE_INDEXING_FACTS_TREE_EXTRACTOR_H_ #define VERIBLE_VERILOG_TOOLS_KYTHE_INDEXING_FACTS_TREE_EXTRACTOR_H_ #include <string> #include <vector> #include "absl/strings/string_view.h" #include "verilog/analysis/verilog_project.h" #include "verilog/tools/kythe/indexing_facts_tree.h" namespace verilog { namespace kythe { // Given a SystemVerilog project (set of files), extract and return the // IndexingFactsTree for the given files. // The returned tree will have the files as children and they will retain their // original ordering from the file list. IndexingFactNode ExtractFiles(absl::string_view file_list_path, VerilogProject* project, const std::vector<std::string>& file_names); } // namespace kythe } // namespace verilog #endif // VERIBLE_VERILOG_TOOLS_KYTHE_INDEXING_FACTS_TREE_EXTRACTOR_H_
523
360
<reponame>opengauss-mirror/openGauss-graph /* ------------------------------------------------------------------------- * * pg_amop.h * definition of the system "amop" relation (pg_amop) * along with the relation's initial contents. * * The amop table identifies the operators associated with each index operator * family and operator class (classes are subsets of families). An associated * operator can be either a search operator or an ordering operator, as * identified by amoppurpose. * * The primary key for this table is <amopfamily, amoplefttype, amoprighttype, * amopstrategy>. amoplefttype and amoprighttype are just copies of the * operator's oprleft/oprright, ie its declared input data types. The * "default" operators for a particular opclass within the family are those * with amoplefttype = amoprighttype = opclass's opcintype. An opfamily may * also contain other operators, typically cross-data-type operators. All the * operators within a family are supposed to be compatible, in a way that is * defined by each individual index AM. * * We also keep a unique index on <amopopr, amoppurpose, amopfamily>, so that * we can use a syscache to quickly answer questions of the form "is this * operator in this opfamily, and if so what are its semantics with respect to * the family?" This implies that the same operator cannot be listed for * multiple strategy numbers within a single opfamily, with the exception that * it's possible to list it for both search and ordering purposes (with * different strategy numbers for the two purposes). * * amopmethod is a copy of the owning opfamily's opfmethod field. This is an * intentional denormalization of the catalogs to buy lookup speed. * * * Portions Copyright (c) 1996-2012, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/include/catalog/pg_amop.h * * NOTES * the genbki.pl script reads this file and generates .bki * information from the DATA() statements. * * ------------------------------------------------------------------------- */ #ifndef PG_AMOP_H #define PG_AMOP_H #include "catalog/genbki.h" /* ---------------- * pg_amop definition. cpp turns this into * typedef struct FormData_pg_amop * ---------------- */ #define AccessMethodOperatorRelationId 2602 #define AccessMethodOperatorRelation_Rowtype_Id 10165 CATALOG(pg_amop,2602) BKI_SCHEMA_MACRO { Oid amopfamily; /* the index opfamily this entry is for */ Oid amoplefttype; /* operator's left input data type */ Oid amoprighttype; /* operator's right input data type */ int2 amopstrategy; /* operator strategy number */ char amoppurpose; /* is operator for 's'earch or 'o'rdering? */ Oid amopopr; /* the operator's pg_operator OID */ Oid amopmethod; /* the index access method this entry is for */ Oid amopsortfamily; /* ordering opfamily OID, or 0 if search op */ } FormData_pg_amop; /* allowed values of amoppurpose: */ #define AMOP_SEARCH 's' /* operator is for search */ #define AMOP_ORDER 'o' /* operator is for ordering */ /* ---------------- * Form_pg_amop corresponds to a pointer to a tuple with * the format of pg_amop relation. * ---------------- */ typedef FormData_pg_amop *Form_pg_amop; /* ---------------- * compiler constants for pg_amop * ---------------- */ #define Natts_pg_amop 8 #define Anum_pg_amop_amopfamily 1 #define Anum_pg_amop_amoplefttype 2 #define Anum_pg_amop_amoprighttype 3 #define Anum_pg_amop_amopstrategy 4 #define Anum_pg_amop_amoppurpose 5 #define Anum_pg_amop_amopopr 6 #define Anum_pg_amop_amopmethod 7 #define Anum_pg_amop_amopsortfamily 8 #endif /* PG_AMOP_H */
1,164
418
<filename>OpenShop/BFUserDetailsViewController.h<gh_stars>100-1000 // // BFUserDetailsViewController.h // OpenShop // // Created by <NAME> // Copyright (c) 2015 Business Factory. All rights reserved. // #import "BFModalViewController.h" #import <RETableViewManager.h> #import <TPKeyboardAvoidingTableView.h> NS_ASSUME_NONNULL_BEGIN /** * `BFUserDetailsViewController` displays user profile details. The details are split into two sections. * First section allows user to change his name, address, phone number and additional info. The second * section represents the password change option. */ @interface BFUserDetailsViewController : BFModalViewController <BFCustomAppearance, RETableViewManagerDelegate> @end NS_ASSUME_NONNULL_END
219
413
<gh_stars>100-1000 /* gdbmgr.h: this header file supports the gdbmgr program * Author: <NAME>, Jr. * Date: Nov 21, 2008 */ /* ===================================================================== * Header Section: {{{1 */ /* ------------------------------------------------------------------------ * Includes: {{{2 */ #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <termios.h> #include <unistd.h> #include <sys/wait.h> #include <sys/shm.h> #include <sys/ipc.h> /* ------------------------------------------------------------------------ * Definitions: {{{2 */ #define BUFSIZE 65536 #define EOA ((char)0xff) #define MAXATTCH 32 #define MEDBUFSIZE 4096 #define SHMKEY ((key_t) 3316) #define SHORTWAITCNTMAX 15 #define SHORTWAIT usleep((useconds_t) 20000) #define SMBUFSIZE 128 /* --------------------------------------------------------------------- * Debugging Support: {{{2 */ #ifdef DEBUG # define Dprintf(x) {FILE *fp; fp= fopen("tmp.gdbmgr","a"); fprintf(fp,"|"); fprintf x; fclose(fp); } # define Edbg(x) {FILE *fp; fp= fopen("tmp.gdbmgr","a"); fprintf x; fprintf(fp," {\n"); fclose(fp); } # define Rdbg(x) {FILE *fp; fp= fopen("tmp.gdbmgr","a"); fprintf(fp,"|return "); fprintf x; fprintf(fp," }\n"); fclose(fp); } #else # define Dprintf(x) # define Edbg(x) # define Initdbg(x) # define Rdbg(x) #endif /* ------------------------------------------------------------------------ * Enumerations: {{{2 */ /* ------------------------------------------------------------------------ * Typedefs: {{{2 */ typedef struct GdbMgr_str GdbMgr; /* ------------------------------------------------------------------------ * Data Structures: {{{2 */ struct GdbMgr_str { char mlbuf[BUFSIZE]; /* multi-line buffer */ char gdbmgrbuf[SMBUFSIZE]; /* small buffer */ char errmsg[MEDBUFSIZE]; /* medium buffer for error messages */ int shmid; /* shared memory id */ int init; /* indicates if its being initialized the first time */ int rwfd; /* master-side read-write file descriptor */ int nbrfd; /* non-blocking read from rwfd file descriptor */ int running; /* indicates if vdlGdb is in run (starting..stopping) mode */ int runstate; /* FSA to determine whether to stop running */ pid_t gdbpid; /* process id of gdb */ }; /* ------------------------------------------------------------------------ * Options: {{{2 */ /* ------------------------------------------------------------------------ * Global Data: {{{2 */ #ifdef MAIN_PROG GdbMgr *gdbmgr= NULL; #endif /* ------------------------------------------------------------------------ * Prototypes: {{{2 */ char *gmInit(char *); /* gdbmgr.c */ char *gmGdb(char *); /* gdbmgr.c */ char *gmPoll(char *); /* gdbmgr.c */ char *gmClose(char *); /* gdbmgr.c */ /* ===================================================================== */ /* Modelines: {{{1 * vim: fdm=marker */
1,357
348
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2021. // // This software is released under a three-clause BSD license: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: <NAME> $ // $Authors: <NAME> $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/String.h> #include <iterator> #include <ostream> #include <vector> // This header collects io relevant parts of ListUtils. Separating the from the // rest avoids inclusion of ostream headers in a lot of classes. namespace OpenMS { /** @brief Output stream operator for std::vectors. @param os The target stream. @param v The vector to write to stream. */ template <typename T> inline std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { os << "["; if (!v.empty()) { for (auto it = v.begin(); it < v.end() - 1; ++it) { // convert to String manually, since this is much faster than ostream build-in conversion; // If T is a String, the compiler will (hopefully) elide the copy os << String(*it) << ", "; } os << String(v.back()); } os << "]"; return os; } template<typename T> struct VecLowPrecision { const std::vector<T>& value; VecLowPrecision(const std::vector<T>& v) : value(v) {} }; /// modified version of the stream operator (works for vectors of float, double, long double) which prints only /// three fractional digits; usage 'os << VecLowPrecision(my_vec);' template <typename T> inline std::ostream& operator<<(std::ostream& os, const VecLowPrecision<T>& val) { os << "["; const auto& v = val.value; if (!v.empty()) { for (auto it = v.begin(); it < v.end() - 1; ++it) { // convert to String manually, since this is much faster than ostreams build-in conversion; os << String(*it, false) << ", "; } os << String(v.back(), false); } os << "]"; return os; } /// Operator for appending entries with less code template <typename TString> inline std::vector<String>& operator<<(std::vector<String>& sl, const TString& string) { sl.push_back(string); return sl; } }
1,245
922
<gh_stars>100-1000 /* * Hibernate Validator, declare and validate application constraints * * License: Apache License, Version 2.0 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>. */ package org.hibernate.validator.cfg.defs; import org.hibernate.validator.cfg.ConstraintDef; import org.hibernate.validator.constraints.LuhnCheck; /** * @author <NAME> */ public class LuhnCheckDef extends ConstraintDef<LuhnCheckDef, LuhnCheck> { public LuhnCheckDef() { super( LuhnCheck.class ); } public LuhnCheckDef startIndex(int index) { addParameter( "startIndex", index ); return this; } public LuhnCheckDef endIndex(int index) { addParameter( "endIndex", index ); return this; } public LuhnCheckDef checkDigitIndex(int index) { addParameter( "checkDigitIndex", index ); return this; } public LuhnCheckDef ignoreNonDigitCharacters(boolean ignore) { addParameter( "ignoreNonDigitCharacters", ignore ); return this; } }
344
343
package com.ejlchina.searcher.param; /** * 分页参数 * @author Troy.Zhou @ 2021-10-31 * @since v3.0.0 */ public class Paging { /** * 分页:最大条数(用于分页) */ private int size; /** * 分页:查询偏移条数(用于分页) */ private long offset; public Paging(int size, long offset) { this.size = size; this.offset = offset; } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public long getOffset() { return offset; } public void setOffset(long offset) { this.offset = offset; } }
349
1,723
<filename>tutorials/scc-inspec/scc/create_source.py import argparse import google.auth import google.auth.impersonated_credentials from google.cloud.securitycenter_v1p1beta1 import SecurityCenterClient parser = argparse.ArgumentParser() parser.add_argument('--org_id', required=True) parser.add_argument('--serviceaccount', required=True) args = parser.parse_args() def print_sources(scc, org_name): for i, source in enumerate(scc.list_sources(request={"parent": org_name}, retry=None)): print(i, source) def create_inspec_source(scc, org_name): new_source = scc.create_source( request={ "parent": org_name, "source": { "display_name": "InSpec", "description": "A new custom source for InSpec findings", }, } ) print('SOURCE_ID: %s' % new_source.name.split('/')[3]) def main(): org_name = "organizations/{org_id}".format(org_id=args.org_id) creds, pid = google.auth.default() impersonated = google.auth.impersonated_credentials.Credentials( source_credentials=creds, target_principal=args.serviceaccount, target_scopes=['https://www.googleapis.com/auth/cloud-platform'], ) scc_client = SecurityCenterClient(credentials=impersonated) # print_sources(scc_client, org_name) create_inspec_source(scc_client, org_name) if __name__ == "__main__": main()
542
395
<reponame>jabader97/backpack<filename>backpack/extensions/curvmatprod/hmp/dropout.py from backpack.core.derivatives.dropout import DropoutDerivatives from backpack.extensions.curvmatprod.hmp.hmpbase import HMPBase class HMPDropout(HMPBase): def __init__(self): super().__init__(derivatives=DropoutDerivatives())
122
2,603
<reponame>JVVJV/FreeRTOS /*********************************************************************************************************************** * DISCLAIMER * This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. * No other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all * applicable laws, including copyright laws. * THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIESREGARDING THIS SOFTWARE, WHETHER EXPRESS, IMPLIED * OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY * LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE FOR ANY DIRECT, * INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR * ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability * of this software. By using this software, you agree to the additional terms and conditions found by accessing the * following link: * http://www.renesas.com/disclaimer * * Copyright (C) 2015 Renesas Electronics Corporation. All rights reserved. ***********************************************************************************************************************/ /*********************************************************************************************************************** * File Name : r_cg_scifa_user.c * Version : Code Generator for RZ/T1 V1.00.00.09 [02 Mar 2015] * Device(s) : R7S910018CBG * Tool-Chain : GCCARM * Description : This file implements device driver for SCIF module. * Creation Date: 19/04/2015 ***********************************************************************************************************************/ /*********************************************************************************************************************** Pragma directive ***********************************************************************************************************************/ /* Start user code for pragma. Do not edit comment generated here */ /* End user code. Do not edit comment generated here */ /*********************************************************************************************************************** Includes ***********************************************************************************************************************/ #include "r_cg_macrodriver.h" #include "r_cg_scifa.h" /* Start user code for include. Do not edit comment generated here */ #include "r_typedefs.h" #include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "serial.h" /* End user code. Do not edit comment generated here */ #include "r_cg_userdefine.h" /*********************************************************************************************************************** Global variables and functions ***********************************************************************************************************************/ extern const uint8_t * gp_scifa2_tx_address; /* SCIFA2 send buffer address */ extern uint16_t g_scifa2_tx_count; /* SCIFA2 send data number */ extern uint8_t * gp_scifa2_rx_address; /* SCIFA2 receive buffer address */ extern uint16_t g_scifa2_rx_count; /* SCIFA2 receive data number */ extern uint16_t g_scifa2_rx_length; /* SCIFA2 receive data length */ /* Start user code for global. Do not edit comment generated here */ /* Characters received from the UART are stored in this queue, ready to be received by the application. ***NOTE*** Using a queue in this way is very convenient, but also very inefficient. It can be used here because characters will only arrive slowly. In a higher bandwidth system a circular RAM buffer or DMA should be used in place of this queue. */ static QueueHandle_t xRxQueue = NULL; /* When a task calls vSerialPutString() its handle is stored in xSendingTask, before being placed into the Blocked state (so does not use any CPU time) to wait for the transmission to end. The task handle is then used from the UART transmit end interrupt to remove the task from the Blocked state. */ static TaskHandle_t xSendingTask = NULL; /* * Entry point for the handlers. These set the pxISRFunction variable to point * to the C handler for each timer, then branch to the FreeRTOS IRQ handler. */ #ifdef __GNUC__ void r_scifa2_txif2_interrupt_entry( void ) __attribute__((naked)); void r_scifa2_rxif2_interrupt_entry( void ) __attribute__((naked)); void r_scifa2_drif2_interrupt_entry( void ) __attribute__((naked)); void r_scifa2_brif2_interrupt_entry( void ) __attribute__((naked)); #endif /* __GNUC__ */ #ifdef __ICCARM__ /* IAR requires the entry point to be in an assembly file. The functions are implemented in $PROJ_DIR$/System/IAR/Interrupt_Entry_Stubs.asm. */ extern void r_scifa2_txif2_interrupt_entry( void ); extern void r_scifa2_rxif2_interrupt_entry( void ); extern void r_scifa2_drif2_interrupt_entry( void ); extern void r_scifa2_brif2_interrupt_entry( void ); #endif /* __ICCARM__ */ /* End user code. Do not edit comment generated here */ /*********************************************************************************************************************** * Function Name: r_scifa2_txif2_interrupt * Description : This function is TXIF2 interrupt service routine. * Arguments : None * Return Value : None ***********************************************************************************************************************/ void r_scifa2_txif2_interrupt(void) { uint16_t count = 0; /* Get the amount of untransmitted data stored in the FRDR register */ uint16_t dummy_fdr = SCIFA2.FDR.BIT.T; /* Write data to the transmit FIFO data register */ while ((g_scifa2_tx_count > 0U) && (count < _SCIF_FIFO_MAX_SIZE - dummy_fdr)) { SCIFA2.FTDR = *gp_scifa2_tx_address; gp_scifa2_tx_address++; g_scifa2_tx_count--; count++; } if (SCIFA2.FSR.BIT.TDFE == 1U) { SCIFA2.FSR.BIT.TDFE = 0U; } if (g_scifa2_tx_count <= 0U) { SCIFA2.SCR.BIT.TIE = 0U; SCIFA2.SCR.BIT.TEIE = 1U; } /* Wait the interrupt signal is disabled */ while (0U != (VIC.IRQS3.LONG & 0x00008000UL)) { VIC.IEC3.LONG = 0x00008000UL; } VIC.IEN3.LONG |= 0x00008000UL; /* Dummy write */ VIC.HVA0.LONG = 0x00000000UL; } /*********************************************************************************************************************** * Function Name: r_scifa2_rxif2_interrupt * Description : This function is RXIF2 interrupt service routine. * Arguments : None * Return Value : None ***********************************************************************************************************************/ void r_scifa2_rxif2_interrupt(void) { uint16_t count = 0; /* Get the amount of receive data stored in FRDR register */ uint16_t dummy_fdr = SCIFA2.FDR.BIT.R; /* Read data from the receive FIFO data register */ while ((g_scifa2_rx_length > g_scifa2_rx_count) && (count < dummy_fdr)) { *gp_scifa2_rx_address = SCIFA2.FRDR; gp_scifa2_rx_address++; g_scifa2_rx_count++; count++; } /* If remaining data is less than the receive trigger number, receive interrupt will not occur. In this case, set trigger number to 1 to force receive interrupt for each one byte of data in FRDR */ if ((g_scifa2_rx_length - g_scifa2_rx_count < _SCIF_RX_TRIG_NUM_2) && (SCIFA2.FTCR.BIT.RFTC != 1U)) { SCIFA2.FTCR.BIT.RFTC = 1U; } /* Clear receive FIFO data full flag */ if (SCIFA2.FSR.BIT.RDF == 1U) { SCIFA2.FSR.BIT.RDF = 0U; } if (g_scifa2_rx_length <= g_scifa2_rx_count) { /* All data received */ SCIFA2.SCR.BIT.RE = 0U; r_scifa2_callback_receiveend(); } /* Wait the interrupt signal is disabled */ while (0U != (VIC.IRQS3.LONG & 0x00004000UL)) { VIC.IEC3.LONG = 0x00004000UL; } VIC.IEN3.LONG |= 0x00004000UL; /* Dummy write */ VIC.HVA0.LONG = 0x00000000UL; } /*********************************************************************************************************************** * Function Name: r_scifa2_drif2_interrupt * Description : This function is TEIF 2 or DRIF2 interrupt service routine. * Arguments : None * Return Value : None ***********************************************************************************************************************/ void r_scifa2_drif2_interrupt(void) { if (1U == SCIFA2.FSR.BIT.TEND) { SCIFA2.SPTR.BIT.SPB2DT = 0U; SCIFA2.SPTR.BIT.SPB2IO = 1U; SCIFA2.SCR.BIT.TE = 0U; SCIFA2.SCR.BIT.TEIE = 0U; } r_scifa2_callback_transmitend(); /* Clear data ready detect flag */ if (1U == SCIFA2.FSR.BIT.DR) { /* Start user code. Do not edit comment generated here */ /* End user code. Do not edit comment generated here */ SCIFA2.FSR.BIT.DR = 0U; } /* Wait the interrupt signal is disabled */ while (0U != (VIC.IRQS3.LONG & 0x00010000UL)) { VIC.IEC3.LONG = 0x00010000UL; } VIC.IEN3.LONG |= 0x00010000UL; /* Dummy write */ VIC.HVA0.LONG = 0x00000000UL; } /*********************************************************************************************************************** * Function Name: r_scifa2_brif2_interrupt * Description : This function is BRIF2 or ERIF2 interrupt service routine. * Arguments : None * Return Value : None ***********************************************************************************************************************/ void r_scifa2_brif2_interrupt(void) { if (1U == SCIFA2.FSR.BIT.BRK) { r_scifa2_callback_error(BREAK_DETECT); /* Clear break detect flag */ SCIFA2.FSR.BIT.BRK = 0U; } if (1U == SCIFA2.FSR.BIT.ER) { r_scifa2_callback_error(RECEIVE_ERROR); /* Clear receive error flag */ SCIFA2.FSR.BIT.ER = 0U; } if (1U == SCIFA2.LSR.BIT.ORER) { r_scifa2_callback_error(OVERRUN_ERROR); /* Clear overrun error flag */ SCIFA2.LSR.BIT.ORER = 0U; } /* Wait the interrupt signal is disabled */ while (0U != (VIC.IRQS3.LONG & 0x00002000UL)) { VIC.IEC3.LONG = 0x00002000UL; } VIC.IEN3.LONG |= 0x00002000UL; /* Dummy write */ VIC.HVA0.LONG = 0x00000000UL; } /*********************************************************************************************************************** * Function Name: r_scifa2_callback_transmitend * Description : This function is a callback function when SCIFA2 finishes transmission. * Arguments : None * Return Value : None ***********************************************************************************************************************/ void r_scifa2_callback_transmitend(void) { /* Start user code. Do not edit comment generated here */ BaseType_t xHigherPriorityTaskWoken = pdFALSE; if( xSendingTask != NULL ) { /* A task is waiting for the end of the Tx, unblock it now. http://www.freertos.org/vTaskNotifyGiveFromISR.html */ vTaskNotifyGiveFromISR( xSendingTask, &xHigherPriorityTaskWoken ); xSendingTask = NULL; portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); } /* End user code. Do not edit comment generated here */ } /*********************************************************************************************************************** * Function Name: r_scifa2_callback_receiveend * Description : This function is a callback function when SCIFA2 finishes reception. * Arguments : None * Return Value : None ***********************************************************************************************************************/ void r_scifa2_callback_receiveend(void) { /* Start user code. Do not edit comment generated here */ uint8_t ucRxedChar = 0; BaseType_t xHigherPriorityTaskWoken = pdFALSE; /* Read the received data */ ucRxedChar = SCIFA2.FRDR; /* Characters received from the UART are stored in this queue, ready to be received by the application. ***NOTE*** Using a queue in this way is very convenient, but also very inefficient. It can be used here because characters will only arrive slowly. In a higher bandwidth system a circular RAM buffer or DMA should be used in place of this queue. */ xQueueSendFromISR( xRxQueue, ( void * ) &ucRxedChar, &xHigherPriorityTaskWoken ); /* Re-enable receptions */ SCIFA2.SCR.BIT.RE = 1U; /* End user code. Do not edit comment generated here */ } /*********************************************************************************************************************** * Function Name: r_scifa2_callback_error * Description : This function is a callback function when SCIFA2 reception encounters error. * Arguments : error_type - * reception error type * Return Value : None ***********************************************************************************************************************/ void r_scifa2_callback_error(scif_error_type_t error_type) { /* Start user code. Do not edit comment generated here */ /* Used to suppress the warning message generated for unused variables */ UNUSED_PARAM(error_type); /* End user code. Do not edit comment generated here */ } /* Start user code for adding. Do not edit comment generated here */ /* Function required in order to link UARTCommandConsole.c - which is used by multiple different demo application. */ xComPortHandle xSerialPortInitMinimal( unsigned long ulWantedBaud, unsigned portBASE_TYPE uxQueueLength ) { ( void ) ulWantedBaud; ( void ) uxQueueLength; /* Characters received from the UART are stored in this queue, ready to be received by the application. ***NOTE*** Using a queue in this way is very convenient, but also very inefficient. It can be used here because characters will only arrive slowly. In a higher bandwidth system a circular RAM buffer or DMA should be used in place of this queue. */ xRxQueue = xQueueCreate( uxQueueLength, sizeof( char ) ); configASSERT( xRxQueue ); /* Enable the receive. */ SCIFA2.FTCR.BIT.RFTC = _SCIF_RX_TRIG_NUM_2; SCIFA2.SCR.BIT.RE = 1U; SCIFA2.SCR.BIT.RIE = 1U; SCIFA2.SCR.BIT.REIE = 1U; /* Enable SCI1 operations */ R_SCIFA2_Start(); /* Only one UART is supported, so it doesn't matter what is returned here. */ return 0; } /* Function required in order to link UARTCommandConsole.c - which is used by multiple different demo application. */ void vSerialPutString( xComPortHandle pxPort, const signed char * const pcString, unsigned short usStringLength ) { const TickType_t xMaxBlockTime = pdMS_TO_TICKS( 5000 ); /* Only one port is supported. */ ( void ) pxPort; /* Don't send the string unless the previous string has been sent. */ if( ( xSendingTask == NULL ) && ( usStringLength > 0 ) ) { /* Ensure the calling task's notification state is not already pending. */ xTaskNotifyStateClear( NULL ); /* Store the handle of the transmitting task. This is used to unblock the task when the transmission has completed. */ xSendingTask = xTaskGetCurrentTaskHandle(); /* Send the string using the auto-generated API. */ R_SCIFA2_Serial_Send( ( uint8_t * ) pcString, usStringLength ); /* Wait in the Blocked state (so not using any CPU time) until the transmission has completed. */ ulTaskNotifyTake( pdTRUE, xMaxBlockTime ); } } /* Function required in order to link UARTCommandConsole.c - which is used by multiple different demo application. */ signed portBASE_TYPE xSerialGetChar( xComPortHandle pxPort, signed char *pcRxedChar, TickType_t xBlockTime ) { /* Only one UART is supported. */ ( void ) pxPort; /* Return a received character, if any are available. Otherwise block to wait for a character. */ return xQueueReceive( xRxQueue, pcRxedChar, xBlockTime ); } /* Function required in order to link UARTCommandConsole.c - which is used by multiple different demo application. */ signed portBASE_TYPE xSerialPutChar( xComPortHandle pxPort, signed char cOutChar, TickType_t xBlockTime ) { /* Just mapped to vSerialPutString() so the block time is not used. */ ( void ) xBlockTime; vSerialPutString( pxPort, &cOutChar, sizeof( cOutChar ) ); return pdPASS; } /* End user code. Do not edit comment generated here */ /* * The RZ/T vectors directly to a peripheral specific interrupt handler, rather * than using the Cortex-R IRQ vector. Therefore each interrupt handler * installed by the application must follow the examples below, which save a * pointer to a standard C function in the pxISRFunction variable, before * branching to the FreeRTOS IRQ handler. The FreeRTOS IRQ handler then manages * interrupt entry (including interrupt nesting), before calling the C function * saved in the pxISRFunction variable. NOTE: The entry points are naked * functions - do not add C code to these functions. */ #ifdef __GNUC__ /* The IAR equivalent is implemented in $PROJ_DIR$/System/IAR/Interrupt_Entry_Stubs.asm */ void r_scifa2_txif2_interrupt_entry( void ) { __asm volatile ( "PUSH {r0-r1} \t\n" "LDR r0, =pxISRFunction \t\n" "LDR r1, =r_scifa2_txif2_interrupt \t\n" "STR r1, [r0] \t\n" "POP {r0-r1} \t\n" "B FreeRTOS_IRQ_Handler " ); } #endif /* __GNUC__ */ /*-----------------------------------------------------------*/ #ifdef __GNUC__ /* The IAR equivalent is implemented in $PROJ_DIR$/System/IAR/Interrupt_Entry_Stubs.asm */ void r_scifa2_rxif2_interrupt_entry( void ) { __asm volatile ( "PUSH {r0-r1} \t\n" "LDR r0, =pxISRFunction \t\n" "LDR r1, =r_scifa2_rxif2_interrupt \t\n" "STR r1, [r0] \t\n" "POP {r0-r1} \t\n" "B FreeRTOS_IRQ_Handler " ); } #endif /* __GNUC__ */ /*-----------------------------------------------------------*/ #ifdef __GNUC__ /* The IAR equivalent is implemented in $PROJ_DIR$/System/IAR/Interrupt_Entry_Stubs.asm */ void r_scifa2_drif2_interrupt_entry( void ) { __asm volatile ( "PUSH {r0-r1} \t\n" "LDR r0, =pxISRFunction \t\n" "LDR r1, =r_scifa2_drif2_interrupt \t\n" "STR r1, [r0] \t\n" "POP {r0-r1} \t\n" "B FreeRTOS_IRQ_Handler " ); } #endif /* __GNUC__ */ /*-----------------------------------------------------------*/ #ifdef __GNUC__ /* The IAR equivalent is implemented in $PROJ_DIR$/System/IAR/Interrupt_Entry_Stubs.asm */ void r_scifa2_brif2_interrupt_entry( void ) { __asm volatile ( "PUSH {r0-r1} \t\n" "LDR r0, =pxISRFunction \t\n" "LDR r1, =r_scifa2_brif2_interrupt \t\n" "STR r1, [r0] \t\n" "POP {r0-r1} \t\n" "B FreeRTOS_IRQ_Handler " ); } #endif /* __GNUC__ */ /*-----------------------------------------------------------*/
6,766
11,877
<gh_stars>1000+ /* * Copyright 2020 <NAME>. 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. */ package com.github.benmanes.caffeine.cache.simulator.parser.snia.parallel; import java.util.stream.LongStream; import com.github.benmanes.caffeine.cache.simulator.parser.TextTraceReader; import com.github.benmanes.caffeine.cache.simulator.parser.TraceReader.KeyOnlyTraceReader; /** * A reader for the Tencent Block Storage trace files provided by * <a href="http://iotta.snia.org/tracetypes/4">SNIA</a>. * * @author <EMAIL> (<NAME>) */ public final class TencentBlockTraceReader extends TextTraceReader implements KeyOnlyTraceReader { static final int BLOCK_SIZE = 512; static final char READ = '0'; public TencentBlockTraceReader(String filePath) { super(filePath); } @Override public LongStream keys() { return lines() .map(line -> line.split(",")) .filter(array -> array[3].charAt(0) == READ) .flatMapToLong(array -> { long offset = Long.parseLong(array[1]); long startBlock = (offset / BLOCK_SIZE); int sequence = Integer.parseInt(array[2]); int volumeId = Integer.parseInt(array[4]); long key = (((long) volumeId) << 31) | Long.hashCode(startBlock); return LongStream.range(key, key + sequence); }); } }
630
383
#include <direct.h> #include "EventTraceHelper.h" #define LOGSESSION_NAME L"winml" struct __declspec(uuid("{BCAD6AEE-C08D-4F66-828C-4C43461A033D}")) WINML_PROVIDER_GUID_HOLDER; static const auto WINML_PROVIDER_GUID = __uuidof(WINML_PROVIDER_GUID_HOLDER); DWORD PointerSize = 0; /*logman update trace winml -p {BCAD6AEE-C08D-4F66-828C-4C43461A033D} <keyword> <level verbosity> -ets To capture only WinML Traces replace <keyword> with 0x1 To capture only Lotus Profiling Traces replace <keyword> with 0x2 Bit 0: WinML Traces Bit 1: Graph profiler Level Verbosity is as follows: - (0x0) LogAlways - (0x1) Critical - (0x2) Error - (0x3) Warning - (0x4) Information - (0x5) Verbose From <https://docs.microsoft.com/en-us/message-analyzer/system-etw-provider-event-keyword-level-settings> */ static void RemoveTrailingSpace(PEVENT_MAP_INFO pMapInfo) { DWORD byteLength = 0; for (DWORD i = 0; i < pMapInfo->EntryCount; i++) { byteLength = (wcslen((LPWSTR)((PBYTE)pMapInfo + pMapInfo->MapEntryArray[i].OutputOffset)) - 1) * 2; *((LPWSTR)((PBYTE)pMapInfo + (pMapInfo->MapEntryArray[i].OutputOffset + byteLength))) = L'\0'; } } static DWORD GetArraySize(PEVENT_RECORD pEvent, PTRACE_EVENT_INFO pInfo, USHORT i, PUSHORT ArraySize) { DWORD status = ERROR_SUCCESS; PROPERTY_DATA_DESCRIPTOR dataDescriptor; DWORD propertySize = 0; if ((pInfo->EventPropertyInfoArray[i].Flags & PropertyParamCount) == PropertyParamCount) { DWORD Count = 0; // Expects the count to be defined by a UINT16 or UINT32 DWORD j = pInfo->EventPropertyInfoArray[i].countPropertyIndex; ZeroMemory(&dataDescriptor, sizeof(PROPERTY_DATA_DESCRIPTOR)); dataDescriptor.PropertyName = (ULONGLONG)((PBYTE)(pInfo) + pInfo->EventPropertyInfoArray[j].NameOffset); dataDescriptor.ArrayIndex = ULONG_MAX; status = TdhGetPropertySize(pEvent, 0, NULL, 1, &dataDescriptor, &propertySize); status = TdhGetProperty(pEvent, 0, NULL, 1, &dataDescriptor, propertySize, (PBYTE)&Count); *ArraySize = (USHORT)Count; } else { *ArraySize = pInfo->EventPropertyInfoArray[i].count; } return status; } // Both MOF-based events and manifest-based events can specify name/value maps. The // map values can be integer values or bit values. If the property specifies a value // map, get the map. static DWORD GetMapInfo(PEVENT_RECORD pEvent, LPWSTR pMapName, DWORD DecodingSource, PEVENT_MAP_INFO& pMapInfo) { DWORD status = ERROR_SUCCESS; DWORD mapSize = 0; // Retrieve the required buffer size for the map info. status = TdhGetEventMapInformation(pEvent, pMapName, pMapInfo, &mapSize); if (ERROR_INSUFFICIENT_BUFFER == status) { pMapInfo = (PEVENT_MAP_INFO)malloc(mapSize); if (pMapInfo == NULL) { printf("Failed to allocate memory for map info (size=%lu).\n", mapSize); status = ERROR_OUTOFMEMORY; return status; } // Retrieve the map info. status = TdhGetEventMapInformation(pEvent, pMapName, pMapInfo, &mapSize); } if (ERROR_SUCCESS == status) { if (DecodingSourceXMLFile == DecodingSource) { RemoveTrailingSpace(pMapInfo); } } else { if (ERROR_NOT_FOUND == status) { status = ERROR_SUCCESS; // This case is okay. } else { printf("TdhGetEventMapInformation failed with 0x%x.\n", status); } } return status; } static DWORD GetPropertyLength(PEVENT_RECORD pEvent, PTRACE_EVENT_INFO pInfo, USHORT i, PUSHORT PropertyLength) { DWORD status = ERROR_SUCCESS; PROPERTY_DATA_DESCRIPTOR dataDescriptor; DWORD propertySize = 0; // If the property is a binary blob and is defined in a manifest, the property can // specify the blob's size or it can point to another property that defines the // blob's size. The PropertyParamLength flag tells you where the blob's size is defined. if ((pInfo->EventPropertyInfoArray[i].Flags & PropertyParamLength) == PropertyParamLength) { DWORD Length = 0; // Expects the length to be defined by a UINT16 or UINT32 DWORD j = pInfo->EventPropertyInfoArray[i].lengthPropertyIndex; ZeroMemory(&dataDescriptor, sizeof(PROPERTY_DATA_DESCRIPTOR)); dataDescriptor.PropertyName = (ULONGLONG)((PBYTE)(pInfo) + pInfo->EventPropertyInfoArray[j].NameOffset); dataDescriptor.ArrayIndex = ULONG_MAX; status = TdhGetPropertySize(pEvent, 0, NULL, 1, &dataDescriptor, &propertySize); status = TdhGetProperty(pEvent, 0, NULL, 1, &dataDescriptor, propertySize, (PBYTE)&Length); *PropertyLength = (USHORT)Length; } else { if (pInfo->EventPropertyInfoArray[i].length > 0) { *PropertyLength = pInfo->EventPropertyInfoArray[i].length; } else { // If the property is a binary blob and is defined in a MOF class, the extension // qualifier is used to determine the size of the blob. However, if the extension // is IPAddrV6, you must set the PropertyLength variable yourself because the // EVENT_PROPERTY_INFO.length field will be zero. if (TDH_INTYPE_BINARY == pInfo->EventPropertyInfoArray[i].nonStructType.InType && TDH_OUTTYPE_IPV6 == pInfo->EventPropertyInfoArray[i].nonStructType.OutType) { *PropertyLength = (USHORT)sizeof(IN6_ADDR); } else if (TDH_INTYPE_UNICODESTRING == pInfo->EventPropertyInfoArray[i].nonStructType.InType || TDH_INTYPE_ANSISTRING == pInfo->EventPropertyInfoArray[i].nonStructType.InType || (pInfo->EventPropertyInfoArray[i].Flags & PropertyStruct) == PropertyStruct) { *PropertyLength = pInfo->EventPropertyInfoArray[i].length; } else { printf("Unexpected length of 0 for intype %d and outtype %d\n", pInfo->EventPropertyInfoArray[i].nonStructType.InType, pInfo->EventPropertyInfoArray[i].nonStructType.OutType); status = ERROR_EVT_INVALID_EVENT_DATA; } } } return status; } static DWORD GetEventInformation(PEVENT_RECORD pEvent, PTRACE_EVENT_INFO& pInfo) { DWORD status = ERROR_SUCCESS; DWORD bufferSize = 0; // Retrieve the required buffer size for the event metadata. status = TdhGetEventInformation(pEvent, 0, NULL, pInfo, &bufferSize); if (ERROR_INSUFFICIENT_BUFFER == status) { pInfo = (TRACE_EVENT_INFO*)malloc(bufferSize); if (pInfo == NULL) { printf("Failed to allocate memory for event info (size=%lu).\n", bufferSize); status = ERROR_OUTOFMEMORY; return status; } // Retrieve the event metadata. status = TdhGetEventInformation(pEvent, 0, NULL, pInfo, &bufferSize); } if (ERROR_SUCCESS != status) { printf("TdhGetEventInformation failed with 0x%x.\n", status); } return status; } static std::wstring TrimOperatorName(std::wstring& s) { wstring substring = L"_kernel_time"; int offset = (int)s.find(substring); if (offset != -1) { s.erase(offset, substring.length()); substring = L"_nchwc"; offset = (int)s.find(substring); if (offset != -1) { s.erase(offset, substring.length()); } } return s; } /// /// Return formated property data /// /// \param EventRecord The event record received by EventRecordCallback /// \param EventInfo A struct with event metadata. /// \param Index The index of the property to read. /// \param pStructureName Used to retrieve the property if it is inside a struct. /// \param StructIndex Used to retrieve the property if it is inside a struct. /// \param Result A wide string stream, where the formatted values are appended. /// /// \return A DWORD with a windows error value. If the function succeded, it returns /// ERROR_SUCCESS. /// static DWORD GetFormatedPropertyData(_In_ const PEVENT_RECORD EventRecord, _In_ const PTRACE_EVENT_INFO EventInfo, _In_ USHORT Index, _Inout_ PBYTE& UserData, _In_ PBYTE EndOfUserData, _Inout_ wstring& propertyValue) { DWORD status = ERROR_SUCCESS; DWORD lastMember = 0; // Last member of a structure USHORT propertyLength = 0; USHORT arraySize = 0; DWORD formattedDataSize = 0; std::vector<BYTE> formattedData; USHORT userDataConsumed = 0; status = GetPropertyLength(EventRecord, EventInfo, Index, &propertyLength); if (ERROR_SUCCESS != status) { printf("Failed to query ETW event propery length. Error: %ul", status); UserData = NULL; return status; } // // Get the size of the array if the property is an array. // status = GetArraySize(EventRecord, EventInfo, Index, &arraySize); for (USHORT k = 0; k < arraySize; k++) { // // If the property is a structure, skip. // if ((EventInfo->EventPropertyInfoArray[Index].Flags & PropertyStruct) == PropertyStruct) { continue; } else if (propertyLength > 0 || (EndOfUserData - UserData) > 0) { PEVENT_MAP_INFO pMapInfo = NULL; // // If the property could be a map, try to get its info. // if (TDH_INTYPE_UINT32 == EventInfo->EventPropertyInfoArray[Index].nonStructType.InType && EventInfo->EventPropertyInfoArray[Index].nonStructType.MapNameOffset != 0) { status = GetMapInfo( EventRecord, (PWCHAR)((PBYTE)(EventInfo) + EventInfo->EventPropertyInfoArray[Index].nonStructType.MapNameOffset), EventInfo->DecodingSource, pMapInfo); if (ERROR_SUCCESS != status) { printf("Failed to query ETW event property of type map. Error: %lu", status); if (pMapInfo) { free(pMapInfo); pMapInfo = NULL; } break; } } // // Get the size of the buffer required for the formatted data. // status = TdhFormatProperty(EventInfo, pMapInfo, PointerSize, EventInfo->EventPropertyInfoArray[Index].nonStructType.InType, EventInfo->EventPropertyInfoArray[Index].nonStructType.OutType, propertyLength, (USHORT)(EndOfUserData - UserData), UserData, &formattedDataSize, (PWCHAR)formattedData.data(), &userDataConsumed); if (ERROR_INSUFFICIENT_BUFFER == status) { formattedData.resize(formattedDataSize); // // Retrieve the formatted data. // status = TdhFormatProperty(EventInfo, pMapInfo, PointerSize, EventInfo->EventPropertyInfoArray[Index].nonStructType.InType, EventInfo->EventPropertyInfoArray[Index].nonStructType.OutType, propertyLength, (USHORT)(EndOfUserData - UserData), UserData, &formattedDataSize, (PWCHAR)formattedData.data(), &userDataConsumed); } if (pMapInfo) { free(pMapInfo); pMapInfo = NULL; } if (ERROR_SUCCESS == status) { propertyValue.assign((PWCHAR)formattedData.data()); UserData += userDataConsumed; } else { printf("Failed to format ETW event property value. Error: %lu", status); UserData = NULL; break; } } } return status; } /// /// Formats the data of an event while searching for CPU fallback related events /// /// \param EventRecord The event record received by EventRecordCallback /// \param EventInfo A struct with event metadata. /// \param Result A string with the formatted data. /// /// \return A DWORD with a windows error value. If the function succeded, it returns /// ERROR_SUCCESS. /// static DWORD FormatDataForCPUFallback(_In_ const PEVENT_RECORD EventRecord, _In_ const PTRACE_EVENT_INFO EventInfo) { DWORD status = ERROR_SUCCESS; if (EVENT_HEADER_FLAG_32_BIT_HEADER == (EventRecord->EventHeader.Flags & EVENT_HEADER_FLAG_32_BIT_HEADER)) { PointerSize = 4; } else { PointerSize = 8; } if (EVENT_HEADER_FLAG_STRING_ONLY == (EventRecord->EventHeader.Flags & EVENT_HEADER_FLAG_STRING_ONLY)) { // Do nothing } else { PBYTE pUserData = (PBYTE)EventRecord->UserData; PBYTE pEndOfUserData = (PBYTE)EventRecord->UserData + EventRecord->UserDataLength; PWCHAR pPropertyName; wstring operatorType; wstring operatorName; wstring duration; wstring propertyValue; wstring executionProvider; for (USHORT i = 0; i < EventInfo->TopLevelPropertyCount; i++) { pPropertyName = (PWCHAR)((PBYTE)(EventInfo) + EventInfo->EventPropertyInfoArray[i].NameOffset); status = GetFormatedPropertyData(EventRecord, EventInfo, i, pUserData, pEndOfUserData, propertyValue); if (wcscmp(pPropertyName, L"Operator Name") == 0) { operatorType = propertyValue; } else if (wcscmp(pPropertyName, L"Event Name") == 0) { operatorName = TrimOperatorName(propertyValue); } else if (wcscmp(pPropertyName, L"Duration (us)") == 0) { duration = propertyValue; } else if (wcscmp(pPropertyName, L"Execution Provider") == 0) { executionProvider = propertyValue; } if (ERROR_SUCCESS != status) { printf("Failed to format ETW event user data.."); return status; } } if (wcscmp(executionProvider.c_str(), L"CPUExecutionProvider") == 0 && !operatorName.empty()) { wprintf(L"WARNING: CPU fallback detected for operator %s(%s), duration: %s\n", operatorName.c_str(), operatorType.c_str(), duration.c_str()); } } return ERROR_SUCCESS; } static VOID WINAPI EventRecordCallback(EVENT_RECORD* pEventRecord) { // This is where you would get the details of ETW event DWORD status = ERROR_SUCCESS; PTRACE_EVENT_INFO pInfo = NULL; LPWSTR pwsEventGuid = NULL; PBYTE pUserData = NULL; PBYTE pEndOfUserData = NULL; ULONGLONG TimeStamp = 0; ULONGLONG Nanoseconds = 0; // Skips the event if it is the event trace header. Log files contain this event // but real-time sessions do not. The event contains the same information as // the EVENT_TRACE_LOGFILE.LogfileHeader member that you can access when you open // the trace. if (IsEqualGUID(pEventRecord->EventHeader.ProviderId, EventTraceGuid) && pEventRecord->EventHeader.EventDescriptor.Opcode == EVENT_TRACE_TYPE_INFO) { // Skip this event. } else { // Process the event. The pEventRecord->UserData member is a pointer to // the event specific data, if it exists. status = GetEventInformation(pEventRecord, pInfo); if (ERROR_SUCCESS != status) { printf("GetEventInformation failed with %lu\n", status); } else { if (DecodingSourceTlg == (pInfo)->DecodingSource) { FormatDataForCPUFallback(pEventRecord, pInfo); } else // Not handling any events other than Tlg type { // Do nothing } } } if (pInfo) { free(pInfo); } } static ULONG WINAPI BufferCallback(PEVENT_TRACE_LOGFILEW pLogFile) { return TRUE; } void EventTraceHelper::ProcessEventTrace(PTRACEHANDLE traceHandle) { try { auto status = ProcessTrace( traceHandle, 1, 0, 0); // this call blocks until either the session is stopped or an exception is occurred in event_callback if (status != ERROR_SUCCESS && status != ERROR_CANCELLED) { printf("ProcessTrace failed with %lu\n", status); } } catch (exception ex) { printf("Exception when processing event trace: %s\n", ex.what()); // catch exceptions occurred in event_callback } } void EventTraceHelper::Start() { if (DontLog()) { return; } // Please refer to this link to understand why buffersize was setup in such a seemingly random manner: // https://docs.microsoft.com/en-us/windows/win32/api/evntrace/ns-evntrace-event_trace_propertiesbuffersize int bufferSize = sizeof(EVENT_TRACE_PROPERTIES) + (sizeof(LOGSESSION_NAME) + 1) * sizeof(wchar_t); m_sessionProperties = static_cast<PEVENT_TRACE_PROPERTIES>(malloc(bufferSize)); ZeroMemory(m_sessionProperties, bufferSize); GUID guid; UuidCreate(&guid); m_sessionProperties->Wnode.BufferSize = static_cast<ULONG>(bufferSize); m_sessionProperties->Wnode.Guid = guid; m_sessionProperties->Wnode.ClientContext = 0; m_sessionProperties->Wnode.Flags = WNODE_FLAG_TRACED_GUID; m_sessionProperties->LogFileMode = EVENT_TRACE_REAL_TIME_MODE; m_sessionProperties->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES); auto hr = StartTrace(static_cast<PTRACEHANDLE>(&m_sessionHandle), LOGSESSION_NAME, m_sessionProperties); if (hr != ERROR_SUCCESS) { printf("Warning starting event trace: Trace already started %d\n", GetLastError()); } else { auto status = EnableTraceEx2(m_sessionHandle, &WINML_PROVIDER_GUID, EVENT_CONTROL_CODE_ENABLE_PROVIDER, TRACE_LEVEL_VERBOSE, 2, 0, 0, nullptr); } EVENT_TRACE_LOGFILE loggerInfo = {}; TRACE_LOGFILE_HEADER* pHeader = &loggerInfo.LogfileHeader; ZeroMemory(&loggerInfo, sizeof(EVENT_TRACE_LOGFILE)); loggerInfo.LogFileMode = EVENT_TRACE_REAL_TIME_MODE; loggerInfo.ProcessTraceMode = PROCESS_TRACE_MODE_REAL_TIME | PROCESS_TRACE_MODE_RAW_TIMESTAMP | PROCESS_TRACE_MODE_EVENT_RECORD; loggerInfo.BufferCallback = BufferCallback; // provide a callback whenever we get an event record loggerInfo.EventRecordCallback = EventRecordCallback; loggerInfo.Context = nullptr; // LoggerName is the sessionName that we had provided in StartTrace // For consuming events from ETL file we will provide path to ETL file. loggerInfo.LoggerName = const_cast<LPWSTR>(LOGSESSION_NAME); m_traceHandle = OpenTrace(&loggerInfo); if (m_traceHandle == INVALID_PROCESSTRACE_HANDLE) { printf("Error opening event trace: OpenTrace failed with %lu\n", GetLastError()); throw std::runtime_error("Unable to open trace"); } PTRACEHANDLE pt = static_cast<PTRACEHANDLE>(&m_traceHandle); m_threadPool.SubmitWork(ProcessEventTrace, pt); } void EventTraceHelper::Stop() { if (DontLog()) { return; } auto status = CloseTrace(m_traceHandle); status = ControlTrace(m_sessionHandle, nullptr, m_sessionProperties, EVENT_TRACE_CONTROL_STOP); status = EnableTraceEx2(m_sessionHandle, &WINML_PROVIDER_GUID, EVENT_CONTROL_CODE_DISABLE_PROVIDER, 0, 0, 0, 0, nullptr); }
9,628
825
<reponame>jiangkang/Hummer<filename>android/hummer-sdk/src/main/java/com/didi/hummer/render/utility/YogaAttrUtils.java package com.didi.hummer.render.utility; import android.graphics.Color; /** * Created by XiaoFeng on 2019-10-20. */ public class YogaAttrUtils { /** * 判断string是否含有数字 * * @param value 字符串 * @return bool */ public static boolean isNumeric(String value) { return value.matches("^-?\\d+(\\.\\d+)?$"); // 耗性能 1ms } /** * 判断string是否带px单位的数字 * * @param value 字符串 * @return bool */ public static boolean isPxNumeric(String value) { return value.matches("^-?\\d+(\\.\\d+)?(px|PX)$"); // 耗性能 1ms } /** * 判断string是否带hm单位的数字 * * @param value 字符串 * @return bool */ public static boolean isHmNumeric(String value) { return value.matches("^-?\\d+(\\.\\d+)?(hm|HM)$"); // 耗性能 1ms } /** * 判断string是否是颜色 * * @param color 颜色值 * @return bool */ public static boolean isColor(String color) { // return color.matches("^#([0-9a-fA-F]{6}|[0-9a-fA-F]{8})$"); // 耗性能 1ms return color.charAt(0) == '#' && (color.length() == 7 || color.length() == 9); } /** * 判断string是否是24位颜色(rgb: #FFFFFF) * * @param color 颜色值 * @return bool */ public static boolean isColor24(String color) { // return color.matches("^#([0-9a-fA-F]{6})$"); // 耗性能 1ms return color.charAt(0) == '#' && color.length() == 7; } /** * 判断string是否是32位颜色(argb #FFFFFFFF)【耗性能 1ms】 * * @param value 颜色值 * @return bool */ public static boolean isColor32(String value) { // return value.matches("^#([0-9a-fA-F]{8})$"); // 耗性能 1ms return value.charAt(0) == '#' && value.length() == 9; } /** * 判断string是否是渐变颜色【耗性能 1ms】 * * @param color 颜色值 * @return bool */ public static boolean isLinearGradientColor(String color) { // return color.matches("^linear-gradient\\(\\d+deg(\\s+#([0-9a-fA-F]{6}|[0-9a-fA-F]{8})){2}\\)$"); return color.startsWith("linear-gradient"); } /** * 解析颜色值(会自动转换24位或者32位的颜色值,32位颜色值最终转成RGBA) * * @param strColor * @return */ public static int parseColor(String strColor) { int color = Color.TRANSPARENT; try { color = Color.parseColor(strColor); } catch (Exception e) {} if (strColor.length() == 9) { color = YogaColorUtils.rgba2argb(color); } return color; } /** * 解析渐变颜色值 * * @param strColor * @return */ public static int[] parseLinearGradientColor(String strColor) { strColor = strColor.replace("linear-gradient(", ""); strColor = strColor.replace("deg", ""); strColor = strColor.replace(")", "").trim(); String[] array = strColor.split("\\s+"); int[] colors = new int[array.length]; colors[0] = Integer.parseInt(array[0]) % 360; for (int i = 1; i < colors.length; i++) { colors[i] = parseColor(array[i]); } return colors; } }
1,779
331
<reponame>janst97/Monal /* This file is a part of JRTPLIB Copyright (c) 1999-2011 <NAME> Contact: <EMAIL> This library was developed at the Expertise Centre for Digital Media (http://www.edm.uhasselt.be), a research center of the Hasselt University (http://www.uhasselt.be). The library is based upon work done for my thesis at the School for Knowledge Technology (Belgium/The Netherlands). 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. */ /** * \file rtptimeutilities.h */ #ifndef RTPTIMEUTILITIES_H #define RTPTIMEUTILITIES_H #include "rtpconfig.hh" #include "rtptypes.hh" #ifndef WIN32 #include <sys/time.h> #include <time.h> #else #ifndef _WIN32_WCE #include <sys/timeb.h> #endif // _WIN32_WINCE #endif // WIN32 #define RTP_NTPTIMEOFFSET 2208988800UL namespace jrtplib { /** * This is a simple wrapper for the most significant word (MSW) and least * significant word (LSW) of an NTP timestamp. */ class RTPNTPTime { public: /** This constructor creates and instance with MSW \c m and LSW \c l. */ RTPNTPTime(uint32_t m,uint32_t l) { msw = m ; lsw = l; } /** Returns the most significant word. */ uint32_t GetMSW() const { return msw; } /** Returns the least significant word. */ uint32_t GetLSW() const { return lsw; } private: uint32_t msw,lsw; }; /** This class is used to specify wallclock time, delay intervals etc. * This class is used to specify wallclock time, delay intervals etc. * It stores a number of seconds and a number of microseconds. */ class RTPTime { public: /** Returns an RTPTime instance representing the current wallclock time. * Returns an RTPTime instance representing the current wallclock time. This is expressed * as a number of seconds since 00:00:00 UTC, January 1, 1970. */ static RTPTime CurrentTime(); /** This function waits the amount of time specified in \c delay. */ static void Wait(const RTPTime &delay); /** Creates an RTPTime instance representing \c t, which is expressed in units of seconds. */ RTPTime(double t); /** Creates an instance that corresponds to \c ntptime. * Creates an instance that corresponds to \c ntptime. If * the conversion cannot be made, both the seconds and the * microseconds are set to zero. */ RTPTime(RTPNTPTime ntptime); /** Creates an instance corresponding to \c seconds and \c microseconds. */ RTPTime(uint32_t seconds, uint32_t microseconds) { sec = seconds; microsec = microseconds; } /** Returns the number of seconds stored in this instance. */ uint32_t GetSeconds() const { return sec; } /** Returns the number of microseconds stored in this instance. */ uint32_t GetMicroSeconds() const { return microsec; } /** Returns the time stored in this instance, expressed in units of seconds. */ double GetDouble() const { return (((double)sec)+(((double)microsec)/1000000.0)); } /** Returns the NTP time corresponding to the time stored in this instance. */ RTPNTPTime GetNTPTime() const; RTPTime &operator-=(const RTPTime &t); RTPTime &operator+=(const RTPTime &t); bool operator<(const RTPTime &t) const; bool operator>(const RTPTime &t) const; bool operator<=(const RTPTime &t) const; bool operator>=(const RTPTime &t) const; private: #if (defined(WIN32) || defined(_WIN32_WCE)) static inline unsigned __int64 CalculateMicroseconds(unsigned __int64 performancecount,unsigned __int64 performancefrequency); #endif // WIN32 || _WIN32_WCE uint32_t sec,microsec; }; inline RTPTime::RTPTime(double t) { sec = (uint32_t)t; double t2 = t-((double)sec); t2 *= 1000000.0; microsec = (uint32_t)t2; } inline RTPTime::RTPTime(RTPNTPTime ntptime) { if (ntptime.GetMSW() < RTP_NTPTIMEOFFSET) { sec = 0; microsec = 0; } else { sec = ntptime.GetMSW() - RTP_NTPTIMEOFFSET; double x = (double)ntptime.GetLSW(); x /= (65536.0*65536.0); x *= 1000000.0; microsec = (uint32_t)x; } } #if (defined(WIN32) || defined(_WIN32_WCE)) inline unsigned __int64 RTPTime::CalculateMicroseconds(unsigned __int64 performancecount,unsigned __int64 performancefrequency) { unsigned __int64 f = performancefrequency; unsigned __int64 a = performancecount; unsigned __int64 b = a/f; unsigned __int64 c = a%f; // a = b*f+c => (a*1000000)/f = b*1000000+(c*1000000)/f return b*1000000ui64+(c*1000000ui64)/f; } inline RTPTime RTPTime::CurrentTime() { static int inited = 0; static unsigned __int64 microseconds, initmicroseconds; static LARGE_INTEGER performancefrequency; unsigned __int64 emulate_microseconds, microdiff; SYSTEMTIME systemtime; FILETIME filetime; LARGE_INTEGER performancecount; QueryPerformanceCounter(&performancecount); if(!inited){ inited = 1; QueryPerformanceFrequency(&performancefrequency); GetSystemTime(&systemtime); SystemTimeToFileTime(&systemtime,&filetime); microseconds = ( ((unsigned __int64)(filetime.dwHighDateTime) << 32) + (unsigned __int64)(filetime.dwLowDateTime) ) / 10ui64; microseconds-= 11644473600000000ui64; // EPOCH initmicroseconds = CalculateMicroseconds(performancecount.QuadPart, performancefrequency.QuadPart); } emulate_microseconds = CalculateMicroseconds(performancecount.QuadPart, performancefrequency.QuadPart); microdiff = emulate_microseconds - initmicroseconds; return RTPTime((uint32_t)((microseconds + microdiff) / 1000000ui64),((uint32_t)((microseconds + microdiff) % 1000000ui64))); } inline void RTPTime::Wait(const RTPTime &delay) { DWORD t; t = ((DWORD)delay.GetSeconds())*1000+(((DWORD)delay.GetMicroSeconds())/1000); Sleep(t); } class RTPTimeInitializer { public: RTPTimeInitializer(); void Dummy() { dummy++; } private: int dummy; }; extern RTPTimeInitializer timeinit; #else // unix style inline RTPTime RTPTime::CurrentTime() { struct timeval tv; gettimeofday(&tv,0); return RTPTime((uint32_t)tv.tv_sec,(uint32_t)tv.tv_usec); } inline void RTPTime::Wait(const RTPTime &delay) { struct timespec req,rem; req.tv_sec = (time_t)delay.sec; req.tv_nsec = ((long)delay.microsec)*1000; nanosleep(&req,&rem); } #endif // WIN32 inline RTPTime &RTPTime::operator-=(const RTPTime &t) { sec -= t.sec; if (t.microsec > microsec) { sec--; microsec += 1000000; } microsec -= t.microsec; return *this; } inline RTPTime &RTPTime::operator+=(const RTPTime &t) { sec += t.sec; microsec += t.microsec; if (microsec >= 1000000) { sec++; microsec -= 1000000; } return *this; } inline RTPNTPTime RTPTime::GetNTPTime() const { uint32_t msw = sec+RTP_NTPTIMEOFFSET; uint32_t lsw; double x; x = microsec/1000000.0; x *= (65536.0*65536.0); lsw = (uint32_t)x; return RTPNTPTime(msw,lsw); } inline bool RTPTime::operator<(const RTPTime &t) const { if (sec < t.sec) return true; if (sec > t.sec) return false; if (microsec < t.microsec) return true; return false; } inline bool RTPTime::operator>(const RTPTime &t) const { if (sec > t.sec) return true; if (sec < t.sec) return false; if (microsec > t.microsec) return true; return false; } inline bool RTPTime::operator<=(const RTPTime &t) const { if (sec < t.sec) return true; if (sec > t.sec) return false; if (microsec <= t.microsec) return true; return false; } inline bool RTPTime::operator>=(const RTPTime &t) const { if (sec > t.sec) return true; if (sec < t.sec) return false; if (microsec >= t.microsec) return true; return false; } } // end namespace #endif // RTPTIMEUTILITIES_H
3,081
8,599
/* * Copyright 2010-2020 Alfresco Software, Ltd. * * 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.activiti.editor.language.xml; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.activiti.bpmn.converter.util.CommaSplitter; import org.junit.jupiter.api.Test; /** */ public class CommaSplitterTest { @Test public void testNoComma() { String testString = "Test String"; List<String> result = CommaSplitter.splitCommas(testString); assertThat(result).isNotNull(); assertThat(result).hasSize(1); assertThat(result.get(0)).isEqualTo(testString); } @Test public void testOneComa() { String testString = "Test,String"; List<String> result = CommaSplitter.splitCommas(testString); assertThat(result).isNotNull(); assertThat(result).hasSize(2); assertThat(result.get(0)).isEqualTo("Test"); assertThat(result.get(1)).isEqualTo("String"); } @Test public void testManyCommas() { String testString = "does,anybody,realy,reads,this,nonsense"; List<String> result = CommaSplitter.splitCommas(testString); assertThat(result).isNotNull(); assertThat(result).hasSize(6); assertThat(result.get(0)).isEqualTo("does"); assertThat(result.get(1)).isEqualTo("anybody"); assertThat(result.get(2)).isEqualTo("realy"); assertThat(result.get(3)).isEqualTo("reads"); assertThat(result.get(4)).isEqualTo("this"); assertThat(result.get(5)).isEqualTo("nonsense"); } @Test public void testCommaAtStart() { String testString = ",first,second"; List<String> result = CommaSplitter.splitCommas(testString); assertThat(result).isNotNull(); assertThat(result).hasSize(2); assertThat(result.get(0)).isEqualTo("first"); assertThat(result.get(1)).isEqualTo("second"); } @Test public void testCommaAtEnd() { String testString = "first,second,"; List<String> result = CommaSplitter.splitCommas(testString); assertThat(result).isNotNull(); assertThat(result).hasSize(2); assertThat(result.get(0)).isEqualTo("first"); assertThat(result.get(1)).isEqualTo("second"); } @Test public void testCommaAtStartAndEnd() { String testString = ",first,second,"; List<String> result = CommaSplitter.splitCommas(testString); assertThat(result).isNotNull(); assertThat(result).hasSize(2); assertThat(result.get(0)).isEqualTo("first"); assertThat(result.get(1)).isEqualTo("second"); } @Test public void testOneComaInExpression() { String testString = "${first,second}"; List<String> result = CommaSplitter.splitCommas(testString); assertThat(result).isNotNull(); assertThat(result).hasSize(1); assertThat(result.get(0)).isEqualTo(testString); } @Test public void testOManyComaInExpression() { String testString = "${Everything,should,be,made,as,simple,as,possible},but,no,simpler"; List<String> result = CommaSplitter.splitCommas(testString); assertThat(result).isNotNull(); assertThat(result).hasSize(4); assertThat(result.get(0)).isEqualTo("${Everything,should,be,made,as,simple,as,possible}"); assertThat(result.get(1)).isEqualTo("but"); assertThat(result.get(2)).isEqualTo("no"); assertThat(result.get(3)).isEqualTo("simpler"); } }
1,357
685
package com.kaichunlin.transition.app; import android.app.Activity; import android.app.AlertDialog; import android.view.View; import com.sothree.slidinguppanel.SlidingUpPanelLayout; import kaichunlin.transition.app.R; /** * Created by Kai on 2015/5/28. */ public class DialogPanelSlideListener implements SlidingUpPanelLayout.PanelSlideListener { private Activity mActivity; public DialogPanelSlideListener(Activity activity) { mActivity = activity; if (mActivity.getPreferences(0).getBoolean("dialog", true)) { new AlertDialog.Builder(mActivity).setMessage(R.string.dialog_slide_up).setNeutralButton(R.string.dialog_ok, null).create().show(); } } @Override public void onPanelSlide(View view, float v) { } @Override public void onPanelStateChanged(View panel, SlidingUpPanelLayout.PanelState previousState, SlidingUpPanelLayout.PanelState newState) { if (newState == SlidingUpPanelLayout.PanelState.EXPANDED) { mActivity.getPreferences(0).edit().putBoolean("dialog", false).commit(); } } }
400
879
package org.zstack.sdk.identity.role.api; public class DeleteRoleResult { }
29
3,326
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for gan.cifar.eval.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import eval # pylint:disable=redefined-builtin FLAGS = tf.flags.FLAGS mock = tf.test.mock class EvalTest(tf.test.TestCase): def _test_build_graph_helper(self, eval_real_images, conditional_eval): FLAGS.eval_real_images = eval_real_images FLAGS.conditional_eval = conditional_eval # Mock `frechet_inception_distance` and `inception_score`, which are # expensive. with mock.patch.object( eval.util, 'get_frechet_inception_distance') as mock_fid: with mock.patch.object(eval.util, 'get_inception_scores') as mock_iscore: mock_fid.return_value = 1.0 mock_iscore.return_value = 1.0 eval.main(None, run_eval_loop=False) def test_build_graph_realdata(self): self._test_build_graph_helper(True, False) def test_build_graph_generateddata(self): self._test_build_graph_helper(False, False) def test_build_graph_generateddataconditional(self): self._test_build_graph_helper(False, True) if __name__ == '__main__': tf.test.main()
608
360
<filename>docs/source/_static/managed-policies/AWSElasticBeanstalkMaintenance.json { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowCloudformationChangeSetOperationsOnElasticBeanstalkStacks", "Effect": "Allow", "Action": [ "cloudformation:CreateChangeSet", "cloudformation:DescribeChangeSet", "cloudformation:ExecuteChangeSet", "cloudformation:DeleteChangeSet", "cloudformation:ListChangeSets", "cloudformation:DescribeStacks" ], "Resource": [ "arn:aws:cloudformation:*:*:stack/awseb-*", "arn:aws:cloudformation:*:*:stack/eb-*" ] }, { "Sid": "AllowElasticBeanstalkStacksUpdateExecuteSuccessfully", "Effect": "Allow", "Action": "elasticloadbalancing:DescribeLoadBalancers", "Resource": "*" }] }
392
971
#pragma once #include "execution/sql/sql.h" namespace noisepage::parser { /** * Stores parameter metadata, e.g. type. */ class Parameter { public: /** Whether a parameter is a constant or a variable. */ enum class Mutability { CONSTANT = 0, VARIABLE = 1 }; /** * Instantiates a new parameter with the given arguments. * @param mutability whether parameter is constant or variable * @param type_id the SQL type ID * @param is_nullable whether this parameter is nullable */ Parameter(Mutability mutability, execution::sql::SqlTypeId type_id, bool is_nullable) : type_(mutability), type_id_(type_id), is_nullable_(is_nullable) {} /** * Creates a new constant parameter. * @param type_id SQL type * @param is_nullable whether the parameter is nullable * @return the new constant parameter */ static Parameter CreateConstantParameter(const execution::sql::SqlTypeId type_id, const bool is_nullable) { return {Mutability::CONSTANT, type_id, is_nullable}; } /** * Creates a new variable parameter. * @param type_id SQL type * @param is_nullable whether the parameter is nullable * @return the new variable parameter */ static Parameter CreateVariableParameter(const execution::sql::SqlTypeId type_id, const bool is_nullable) { return {Mutability::VARIABLE, type_id, is_nullable}; } /** @return parameter type (constant or variable) */ Mutability GetMutability() const { return type_; } /** @return SQL type ID */ execution::sql::SqlTypeId GetTypeId() const { return type_id_; } /** @return true if parameter is nullable, false otherwise */ bool IsNullable() const { return is_nullable_; } private: const Mutability type_; const execution::sql::SqlTypeId type_id_; const bool is_nullable_; }; } // namespace noisepage::parser
580
4,283
/* * Copyright (c) 2008-2021, Hazelcast, 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. */ package com.hazelcast.cp.event; import java.util.EventListener; /** * CPMembershipListener is notified when a CP member is added to * or removed from the CP Subsystem. * * @see com.hazelcast.cp.CPSubsystemManagementService * @see com.hazelcast.cp.CPSubsystem#addMembershipListener(CPMembershipListener) * @since 4.1 */ public interface CPMembershipListener extends EventListener { /** * Called when a new CP member is added to the CP Subsystem. * * @param event membership event */ void memberAdded(CPMembershipEvent event); /** * Called when a CP member is removed from the CP Subsystem. * * @param event membership event */ void memberRemoved(CPMembershipEvent event); }
415
20,995
// Copyright 2014 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. #include "src/base/sys-info.h" #include "testing/gtest/include/gtest/gtest.h" namespace v8 { namespace base { TEST(SysInfoTest, NumberOfProcessors) { EXPECT_LT(0, SysInfo::NumberOfProcessors()); } TEST(SysInfoTest, AmountOfPhysicalMemory) { EXPECT_LT(0, SysInfo::AmountOfPhysicalMemory()); } TEST(SysInfoTest, AmountOfVirtualMemory) { EXPECT_LE(0, SysInfo::AmountOfVirtualMemory()); } } // namespace base } // namespace v8
207
988
//------------------------------------------------------------------------------ // GxB_Vector_export_CSC: export a vector in CSC format //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, <NAME>, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ #include "GB_export.h" #define GB_FREE_ALL ; GrB_Info GxB_Vector_export_CSC // export and free a CSC vector ( GrB_Vector *v, // handle of vector to export and free GrB_Type *type, // type of vector exported GrB_Index *n, // length of the vector GrB_Index **vi, // indices void **vx, // values GrB_Index *vi_size, // size of Ai in bytes GrB_Index *vx_size, // size of Ax in bytes bool *iso, // if true, A is iso GrB_Index *nvals, // # of entries in vector bool *jumbled, // if true, indices may be unsorted const GrB_Descriptor desc ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GB_WHERE1 ("GxB_Vector_export_CSC (&v, &type, &n, " "&vi, &vx, &vi_size, &vx_size, &iso, &nvals, &jumbled, desc)") ; GB_BURBLE_START ("GxB_Vector_export_CSC") ; GB_GET_DESCRIPTOR (info, desc, xx1, xx2, xx3, xx4, xx5, xx6, xx7) ; GB_RETURN_IF_NULL (v) ; GB_RETURN_IF_NULL_OR_FAULTY (*v) ; GB_RETURN_IF_NULL (nvals) ; ASSERT_VECTOR_OK (*v, "v to export", GB0) ; //-------------------------------------------------------------------------- // finish any pending work //-------------------------------------------------------------------------- if (jumbled == NULL) { // the exported vector cannot be jumbled GB_MATRIX_WAIT (*v) ; } else { // the exported vector is allowed to be jumbled GB_MATRIX_WAIT_IF_PENDING_OR_ZOMBIES (*v) ; } //-------------------------------------------------------------------------- // ensure the vector is sparse //-------------------------------------------------------------------------- GB_OK (GB_convert_any_to_sparse ((GrB_Matrix) *v, Context)) ; //-------------------------------------------------------------------------- // export the vector //-------------------------------------------------------------------------- ASSERT (GB_IS_SPARSE (*v)) ; ASSERT ((*v)->is_csc) ; ASSERT (!GB_ZOMBIES (*v)) ; ASSERT (GB_IMPLIES (jumbled == NULL, !GB_JUMBLED (*v))) ; ASSERT (!GB_PENDING (*v)) ; int sparsity ; bool is_csc ; GrB_Index vdim ; info = GB_export (false, (GrB_Matrix *) v, type, n, &vdim, true, NULL, NULL, // Ap NULL, NULL, // Ah NULL, NULL, // Ab vi, vi_size, // Ai vx, vx_size, // Ax nvals, jumbled, NULL, // jumbled or not &sparsity, &is_csc, // sparse by col iso, Context) ; if (info == GrB_SUCCESS) { ASSERT (sparsity == GxB_SPARSE) ; ASSERT (is_csc) ; ASSERT (vdim == 1) ; } GB_BURBLE_END ; return (info) ; }
1,246
460
#include <gsl/gsl_math.h> #include <gsl/gsl_cblas.h> #include "cblas.h" #include "error_cblas_l2.h" void cblas_chemv (const enum CBLAS_ORDER order, const enum CBLAS_UPLO Uplo, const int N, const void *alpha, const void *A, const int lda, const void *X, const int incX, const void *beta, void *Y, const int incY) { #define BASE float #include "source_hemv.h" #undef BASE }
196
568
package com.novoda.pianohero; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.support.annotation.Nullable; class AndroidSynthSpeaker implements Speaker { private static final double durationSeconds = 0.1; private static final int sampleRate = 8000; private static final int numSamples = (int) (durationSeconds * sampleRate); private static final double sample[] = new double[numSamples]; @Nullable private AudioTrack audioTrack; @Override public void start(double frequency) { byte[] sound = generateTone(frequency); audioTrack = new AudioTrack( AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, sound.length, AudioTrack.MODE_STATIC ); audioTrack.setLoopPoints(0, audioTrack.getBufferSizeInFrames(), -1); audioTrack.write(sound, 0, sound.length); audioTrack.play(); } private byte[] generateTone(double freqOfTone) { byte generatedSound[] = new byte[2 * numSamples]; // fill out the array for (int i = 0; i < numSamples; ++i) { sample[i] = Math.sin(2 * Math.PI * i / (sampleRate / freqOfTone)); } // convert to 16 bit pcm sound array // assumes the sample buffer is normalized. int idx = 0; for (double dVal : sample) { // scale to maximum amplitude short val = (short) ((dVal * 32767)); // in 16 bit wav PCM, first byte is the low order byte generatedSound[idx++] = (byte) (val & 0x00ff); generatedSound[idx++] = (byte) ((val & 0xff00) >>> 8); } return generatedSound; } @Override public void stop() { if (audioTrack != null) { audioTrack.release(); audioTrack = null; } } }
855
3,056
/* * Copyright 2021 Google LLC * * 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. */ #ifndef LYRA_CODEC_TESTING_MOCK_SPECTROGRAM_PREDICTOR_H_ #define LYRA_CODEC_TESTING_MOCK_SPECTROGRAM_PREDICTOR_H_ #include <vector> #include "gmock/gmock.h" #include "spectrogram_predictor_interface.h" namespace chromemedia { namespace codec { class MockSpectrogramPredictor : public SpectrogramPredictorInterface { public: ~MockSpectrogramPredictor() override {} MOCK_METHOD(void, FeedFrame, (const std::vector<float>&), (override)); MOCK_METHOD(std::vector<float>, PredictFrame, (), (override)); }; } // namespace codec } // namespace chromemedia #endif // LYRA_CODEC_TESTING_MOCK_SPECTROGRAM_PREDICTOR_H_
395
301
<gh_stars>100-1000 //****************************************************************** // // Copyright 2016 Samsung Electronics 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. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= package org.iotivity.test.re.app; import android.os.Bundle; import android.util.Log; import org.iotivity.service.testapp.framework.Base; import org.iotivity.service.testapp.framework.MenuInfo; import java.util.LinkedHashMap; import java.util.Map; import android.net.ConnectivityManager; import android.app.AlertDialog; import android.content.DialogInterface; import org.iotivity.base.ModeType; import org.iotivity.base.OcPlatform; import org.iotivity.base.PlatformConfig; import org.iotivity.base.QualityOfService; import org.iotivity.base.ServiceType; import static org.iotivity.test.re.app.REUtility.*; public class MainActivity extends Base { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!isWifiConnected()) { showWifiUnavailableDialog(); return; } configurePlatform(); Map<String, MenuInfo> menuMap = new LinkedHashMap<String, MenuInfo>(); menuMap.put("1", new MenuInfo("Create Resource", "createResource")); menuMap.put("2", new MenuInfo("Set Attributes", "setAttributes")); menuMap.put("3", new MenuInfo("Get Attributes", "getAttributes")); menuMap.put("4", new MenuInfo("Discover Resource without query", "discoverResource")); menuMap.put("5", new MenuInfo("Discover Resource with Resource Type", "discoverResourceByType")); menuMap.put("6", new MenuInfo("Discover Non-Discoverable Resource", "discoverNonDiscoverableResource")); menuMap.put("7", new MenuInfo("Start Monitoring", "startMonitoring")); menuMap.put("8", new MenuInfo("Stop Monitoring", "stopMonitoring")); menuMap.put("9", new MenuInfo("Get State", "getState")); menuMap.put("10", new MenuInfo("Set Remote Attributes", "setRemoteAttributes")); menuMap.put("11", new MenuInfo("Get Remote Attributes", "getRemoteAttributes")); menuMap.put("12", new MenuInfo("Start Caching", "startCaching")); menuMap.put("13", new MenuInfo("Stop Caching", "stopCaching")); menuMap.put("14", new MenuInfo("Get Cached Attributes", "getCachedAttributes")); menuMap.put("15", new MenuInfo("Get Cached State", "getCachedState")); menuMap.put("0", new MenuInfo("Exit", "exitApplication")); RegisterApp("Resource Encapsulation", menuMap, new RETestAppAction()); } private boolean isWifiConnected() { ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); return connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) .isConnected(); } private void showWifiUnavailableDialog() { new AlertDialog.Builder(this) .setTitle("Error") .setMessage( "WiFi is not enabled/connected! Please connect the WiFi and start application again...") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }).create().show(); } private void configurePlatform() { OcPlatform.Configure(new PlatformConfig(getApplicationContext(), ServiceType.IN_PROC, ModeType.CLIENT_SERVER, "0.0.0.0", 0, QualityOfService.LOW)); Log.i(TAG, "Configuration done Successfully"); } }
1,777
2,151
/* * Copyright (c) 2012 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "native_client/src/trusted/service_runtime/nacl_config.h" #include "native_client/tests/signal_handler_single_step/step_test_syscalls.h" #define UNTYPED_SYSCALL(s) ((int (*)()) NACL_SYSCALL_ADDR(s)) void _start(void) { while (1) { UNTYPED_SYSCALL(SINGLE_STEP_TEST_SYSCALL)(); } }
183
1,444
<gh_stars>1000+ package mage.cards.o; import java.util.UUID; import mage.abilities.mana.GreenManaAbility; import mage.abilities.mana.RedManaAbility; import mage.abilities.mana.WhiteManaAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; /** * * @author Loki */ public final class ObeliskOfNaya extends CardImpl { public ObeliskOfNaya (UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.ARTIFACT},"{3}"); this.addAbility(new RedManaAbility()); this.addAbility(new GreenManaAbility()); this.addAbility(new WhiteManaAbility()); } public ObeliskOfNaya (final ObeliskOfNaya card) { super(card); } @Override public ObeliskOfNaya copy() { return new ObeliskOfNaya(this); } }
327
442
<filename>SVHN/test_calibration.py<gh_stars>100-1000 import numpy as np import sys import os import pickle import argparse import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torchvision.transforms as trn import torchvision.datasets as dset import torch.nn.functional as F from models.allconv import AllConvNet from models.wrn import WideResNet from skimage.filters import gaussian as gblur from PIL import Image as PILImage # go through rigamaroo to do ...utils.display_results import show_performance if __package__ is None: import sys from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from utils.display_results import show_performance, get_measures, print_measures, print_measures_with_std import utils.svhn_loader as svhn import utils.lsun_loader as lsun_loader from utils.validation_dataset import validation_split from utils.calibration_tools import * parser = argparse.ArgumentParser(description='Evaluates a SVHN OOD Detector', formatter_class=argparse.ArgumentDefaultsHelpFormatter) # Setup parser.add_argument('--test_bs', type=int, default=200) parser.add_argument('--num_to_avg', type=int, default=1, help='Average measures across num_to_avg runs.') parser.add_argument('--validate', '-v', action='store_true', help='Evaluate performance on validation distributions.') parser.add_argument('--method_name', '-m', type=str, default='allconv_calib_baseline', help='Method name.') parser.add_argument('--use_01', '-z', action='store_true', help='Use 0-1 Posterior Rescaling.') # Loading details parser.add_argument('--layers', default=16, type=int, help='total number of layers') parser.add_argument('--widen-factor', default=4, type=int, help='widen factor') parser.add_argument('--droprate', default=0.4, type=float, help='dropout probability') parser.add_argument('--load', '-l', type=str, default='./snapshots', help='Checkpoint path to resume / test.') parser.add_argument('--ngpu', type=int, default=1, help='0 = CPU.') parser.add_argument('--prefetch', type=int, default=2, help='Pre-fetching threads.') args = parser.parse_args() # torch.manual_seed(1) # np.random.seed(1) train_data = svhn.SVHN('/share/data/vision-greg/svhn/', split='train_and_extra', transform=trn.ToTensor(), download=False) test_data = svhn.SVHN('/share/data/vision-greg/svhn/', split='test', transform=trn.ToTensor(), download=False) num_classes = 10 train_data, val_data = validation_split(train_data, val_share=5000/604388.) val_loader = torch.utils.data.DataLoader( val_data, batch_size=args.test_bs, shuffle=False, num_workers=args.prefetch, pin_memory=True) test_loader = torch.utils.data.DataLoader( test_data, batch_size=args.test_bs, shuffle=False, num_workers=args.prefetch, pin_memory=True) # Create model if 'allconv' in args.method_name: net = AllConvNet(num_classes) else: net = WideResNet(args.layers, num_classes, args.widen_factor, dropRate=args.droprate) start_epoch = 0 # Restore model if args.load != '': for i in range(300 - 1, -1, -1): if 'baseline' in args.method_name: subdir = 'baseline' elif 'oe_tune' in args.method_name: subdir = 'oe_tune' else: subdir = 'oe_scratch' model_name = os.path.join(os.path.join(args.load, subdir), args.method_name + '_epoch_' + str(i) + '.pt') if os.path.isfile(model_name): net.load_state_dict(torch.load(model_name)) print('Model restored! Epoch:', i) start_epoch = i + 1 break if start_epoch == 0: assert False, "could not resume" net.eval() if args.ngpu > 1: net = torch.nn.DataParallel(net, device_ids=list(range(args.ngpu))) if args.ngpu > 0: net.cuda() # torch.cuda.manual_seed(1) cudnn.benchmark = True # fire on all cylinders # /////////////// Calibration Prelims /////////////// ood_num_examples = test_data.data.shape[0] // 5 expected_ap = ood_num_examples / (ood_num_examples + test_data.data.shape[0]) concat = lambda x: np.concatenate(x, axis=0) to_np = lambda x: x.data.cpu().numpy() def get_net_results(data_loader, in_dist=False, t=1): logits = [] confidence = [] correct = [] with torch.no_grad(): for batch_idx, (data, target) in enumerate(data_loader): if batch_idx >= ood_num_examples // args.test_bs and in_dist is False: break data, target = data.cuda(), target.cuda().long() output = net(data) logits.extend(to_np(output).squeeze()) if args.use_01: confidence.extend(to_np( (F.softmax(output/t, dim=1).max(1)[0] - 1./num_classes)/(1 - 1./num_classes) ).squeeze().tolist()) else: confidence.extend(to_np(F.softmax(output/t, dim=1).max(1)[0]).squeeze().tolist()) if in_dist: pred = output.data.max(1)[1] correct.extend(pred.eq(target).cpu().numpy().squeeze().tolist()) if in_dist: return logits.copy(), confidence.copy(), correct.copy() else: return logits[:ood_num_examples].copy(), confidence[:ood_num_examples].copy() val_logits, val_confidence, val_correct = get_net_results(val_loader, in_dist=True) print('\nTuning Softmax Temperature') val_labels = val_data.parent_ds.targets[val_data.offset:] t_star = tune_temp(val_logits, val_labels) print('Softmax Temperature Tuned. Temperature is {:.3f}'.format(t_star)) test_logits, test_confidence, test_correct = get_net_results(test_loader, in_dist=True, t=t_star) print('Error Rate {:.2f}'.format(100*(len(test_correct) - sum(test_correct))/len(test_correct))) # /////////////// End Calibration Prelims /////////////// print('\nUsing SVHN as typical data') # /////////////// In-Distribution Calibration /////////////// print('\n\nIn-Distribution Data') show_calibration_results(np.array(test_confidence), np.array(test_correct), method_name=args.method_name) # /////////////// OOD Calibration /////////////// rms_list, mad_list, sf1_list = [], [], [] def get_and_print_results(ood_loader, num_to_avg=args.num_to_avg): rmss, mads, sf1s = [], [], [] for _ in range(num_to_avg): out_logits, out_confidence = get_net_results(ood_loader, t=t_star) measures = get_measures( concat([out_confidence, test_confidence]), concat([np.zeros(len(out_confidence)), test_correct])) rmss.append(measures[0]); mads.append(measures[1]); sf1s.append(measures[2]) rms = np.mean(rmss); mad = np.mean(mads); sf1 = np.mean(sf1s) rms_list.append(rms); mad_list.append(mad); sf1_list.append(sf1) if num_to_avg >= 5: print_measures_with_std(rmss, mads, sf1s, args.method_name) else: print_measures(rms, mad, sf1, args.method_name) # /////////////// Gaussian Noise /////////////// dummy_targets = torch.ones(ood_num_examples * args.num_to_avg) ood_data = torch.from_numpy( np.clip(np.random.normal(size=(ood_num_examples * args.num_to_avg, 3, 32, 32), loc=0.5, scale=0.5).astype(np.float32), 0, 1)) ood_data = torch.utils.data.TensorDataset(ood_data, dummy_targets) ood_loader = torch.utils.data.DataLoader(ood_data, batch_size=args.test_bs, shuffle=True) print('\n\nGaussian Noise (mu = sigma = 0.5) Calibration') get_and_print_results(ood_loader) # /////////////// Bernoulli Noise /////////////// dummy_targets = torch.ones(ood_num_examples * args.num_to_avg) ood_data = torch.from_numpy(np.random.binomial( n=1, p=0.5, size=(ood_num_examples * args.num_to_avg, 3, 32, 32)).astype(np.float32)) ood_data = torch.utils.data.TensorDataset(ood_data, dummy_targets) ood_loader = torch.utils.data.DataLoader(ood_data, batch_size=args.test_bs, shuffle=True) print('\n\nBernoulli Noise Calibration') get_and_print_results(ood_loader) # /////////////// Blob /////////////// ood_data = np.float32(np.random.binomial(n=1, p=0.7, size=(ood_num_examples * args.num_to_avg, 32, 32, 3))) for i in range(ood_num_examples * args.num_to_avg): ood_data[i] = gblur(ood_data[i], sigma=1.5, multichannel=False) ood_data[i][ood_data[i] < 0.75] = 0.0 dummy_targets = torch.ones(ood_num_examples * args.num_to_avg) ood_data = torch.from_numpy(ood_data.transpose((0, 3, 1, 2))) ood_data = torch.utils.data.TensorDataset(ood_data, dummy_targets) ood_loader = torch.utils.data.DataLoader(ood_data, batch_size=args.test_bs, shuffle=True, num_workers=args.prefetch, pin_memory=True) print('\n\nBlob Calibration') get_and_print_results(ood_loader) # /////////////// Icons-50 /////////////// ood_data = dset.ImageFolder('/share/data/vision-greg/DistortedImageNet/Icons-50', transform=trn.Compose([trn.Resize((32, 32)), trn.ToTensor()])) filtered_imgs = [] for img in ood_data.imgs: if 'numbers' not in img[0]: # img[0] is image name filtered_imgs.append(img) ood_data.imgs = filtered_imgs ood_loader = torch.utils.data.DataLoader(ood_data, batch_size=args.test_bs, shuffle=True) print('\n\nIcons-50 Calibration') get_and_print_results(ood_loader) # /////////////// Textures /////////////// ood_data = dset.ImageFolder(root="/share/data/vision-greg2/users/dan/datasets/dtd/images", transform=trn.Compose([trn.Resize(32), trn.CenterCrop(32), trn.ToTensor()])) ood_loader = torch.utils.data.DataLoader(ood_data, batch_size=args.test_bs, shuffle=True, num_workers=args.prefetch, pin_memory=True) print('\n\nTexture Calibration') get_and_print_results(ood_loader) # /////////////// Places365 /////////////// ood_data = dset.ImageFolder(root="/share/data/vision-greg2/places365/test_subset", transform=trn.Compose([trn.Resize(32), trn.CenterCrop(32), trn.ToTensor()])) ood_loader = torch.utils.data.DataLoader(ood_data, batch_size=args.test_bs, shuffle=True, num_workers=args.prefetch, pin_memory=True) print('\n\nPlaces365 Calibration') get_and_print_results(ood_loader) # /////////////// LSUN /////////////// ood_data = lsun_loader.LSUN("/share/data/vision-greg2/users/dan/datasets/LSUN/lsun-master/data", classes='test', transform=trn.Compose([trn.Resize(32), trn.CenterCrop(32), trn.ToTensor()])) ood_loader = torch.utils.data.DataLoader(ood_data, batch_size=args.test_bs, shuffle=True, num_workers=args.prefetch, pin_memory=True) print('\n\nLSUN Calibration') get_and_print_results(ood_loader) # /////////////// CIFAR data /////////////// ood_data = dset.CIFAR10('/share/data/vision-greg/cifarpy', train=False, transform=trn.ToTensor(), download=False) ood_loader = torch.utils.data.DataLoader(ood_data, batch_size=args.test_bs, shuffle=True, num_workers=args.prefetch, pin_memory=True) print('\n\nCIFAR-10 Calibration') get_and_print_results(ood_loader) # /////////////// Street View Characters data /////////////// ood_data = dset.ImageFolder(root="/share/data/vision-greg2/users/dan/datasets/StreetLetters", transform=trn.Compose([trn.Resize(32), trn.CenterCrop(32), trn.ToTensor()])) ood_loader = torch.utils.data.DataLoader(ood_data, batch_size=args.test_bs, shuffle=True, num_workers=args.prefetch, pin_memory=True) print('\n\nStreet View Characters Calibration') get_and_print_results(ood_loader) # /////////////// Mean Results /////////////// print('\n\nMean Test Results') print_measures(np.mean(rms_list), np.mean(mad_list), np.mean(sf1_list), method_name=args.method_name) # /////////////// OOD Detection of Validation Distributions /////////////// if args.validate is False: exit() rms_list, mad_list, sf1_list = [], [], [] # /////////////// Uniform Noise /////////////// dummy_targets = torch.ones(ood_num_examples * args.num_to_avg) ood_data = torch.from_numpy( np.random.uniform(size=(ood_num_examples * args.num_to_avg, 3, 32, 32), low=0.0, high=1.0).astype(np.float32)) ood_data = torch.utils.data.TensorDataset(ood_data, dummy_targets) ood_loader = torch.utils.data.DataLoader(ood_data, batch_size=args.test_bs, shuffle=True) print('\n\nUniform[0,1] Noise Calibration') get_and_print_results(ood_loader) # /////////////// Arithmetic Mean of Images /////////////// class AvgOfPair(torch.utils.data.Dataset): def __init__(self, dataset): self.dataset = dataset self.shuffle_indices = np.arange(len(dataset)) np.random.shuffle(self.shuffle_indices) def __getitem__(self, i): random_idx = np.random.choice(len(self.dataset)) while random_idx == i: random_idx = np.random.choice(len(self.dataset)) return self.dataset[i][0] / 2. + self.dataset[random_idx][0] / 2., 0 def __len__(self): return len(self.dataset) ood_loader = torch.utils.data.DataLoader( AvgOfPair(test_data), batch_size=args.test_bs, shuffle=True, num_workers=args.prefetch, pin_memory=True) print('\n\nArithmetic Mean of Random Image Pair Calibration') get_and_print_results(ood_loader) # /////////////// Geometric Mean of Images /////////////// class GeomMeanOfPair(torch.utils.data.Dataset): def __init__(self, dataset): self.dataset = dataset self.shuffle_indices = np.arange(len(dataset)) np.random.shuffle(self.shuffle_indices) def __getitem__(self, i): random_idx = np.random.choice(len(self.dataset)) while random_idx == i: random_idx = np.random.choice(len(self.dataset)) return torch.sqrt(self.dataset[i][0] * self.dataset[random_idx][0]), 0 def __len__(self): return len(self.dataset) ood_loader = torch.utils.data.DataLoader( GeomMeanOfPair(test_data), batch_size=args.test_bs, shuffle=True, num_workers=args.prefetch, pin_memory=True) print('\n\nGeometric Mean of Random Image Pair Calibration') get_and_print_results(ood_loader) # /////////////// Jigsaw Images /////////////// ood_loader = torch.utils.data.DataLoader(test_data, batch_size=args.test_bs, shuffle=True, num_workers=args.prefetch, pin_memory=True) jigsaw = lambda x: torch.cat(( torch.cat((torch.cat((x[:, 8:16, :16], x[:, :8, :16]), 1), x[:, 16:, :16]), 2), torch.cat((x[:, 16:, 16:], torch.cat((x[:, :16, 24:], x[:, :16, 16:24]), 2)), 2), ), 1) ood_loader.dataset.transform = trn.Compose([trn.ToTensor(), jigsaw]) print('\n\nJigsawed Images Calibration') get_and_print_results(ood_loader) # /////////////// Speckled Images /////////////// speckle = lambda x: torch.clamp(x + x * torch.randn_like(x), 0, 1) ood_loader.dataset.transform = trn.Compose([trn.ToTensor(), speckle]) print('\n\nSpeckle Noised Images Calibration') get_and_print_results(ood_loader) # /////////////// Pixelated Images /////////////// pixelate = lambda x: x.resize((int(32 * 0.2), int(32 * 0.2)), PILImage.BOX).resize((32, 32), PILImage.BOX) ood_loader.dataset.transform = trn.Compose([pixelate, trn.ToTensor()]) print('\n\nPixelate Calibration') get_and_print_results(ood_loader) # /////////////// Mirrored SVHN digits /////////////// idxs = test_data.targets vert_idxs = np.squeeze(np.logical_and(idxs != 3, np.logical_and(idxs != 0, np.logical_and(idxs != 1, idxs != 8)))) vert_digits = test_data.data[vert_idxs][:, :, ::-1, :] horiz_idxs = np.squeeze(np.logical_and(idxs != 0, np.logical_and(idxs != 1, idxs != 8))) horiz_digits = test_data.data[horiz_idxs][:, :, :, ::-1] flipped_digits = concat((vert_digits, horiz_digits)) dummy_targets = torch.ones(flipped_digits.shape[0]) ood_data = torch.from_numpy(flipped_digits.astype(np.float32) / 255) ood_data = torch.utils.data.TensorDataset(ood_data, dummy_targets) ood_loader = torch.utils.data.DataLoader(ood_data, batch_size=args.test_bs, shuffle=True, num_workers=args.prefetch) print('\n\nMirrored SVHN Digit Calibration') get_and_print_results(ood_loader) # /////////////// Mean Results /////////////// print('\n\nMean Validation Results') print_measures(np.mean(rms_list), np.mean(mad_list), np.mean(sf1_list), method_name=args.method_name)
7,059
722
<filename>model_tools/src/caffe/caffe_adaptee.h<gh_stars>100-1000 // Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved. // 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 _H_CAFFEADAPTEE #define _H_CAFFEADAPTEE #include <string> #include <fstream> #include <map> #include <vector> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl.h> #include <google/protobuf/text_format.h> #include <google/protobuf/message.h> #include "caffe.pb.h" #include "model_adaptee.h" class CaffeAdaptee : public ModelAdaptee { public: CaffeAdaptee() {} ~CaffeAdaptee() {} protected: // read prototxt EE read_from_prototxt(const char *path, google::protobuf::Message *message) { std::ifstream fs(path, std::ifstream::in); if (!fs.is_open()) { UNI_ERROR_LOG("can not open caffe model file %s.\n", path); } google::protobuf::io::IstreamInputStream input(&fs); bool ret = google::protobuf::TextFormat::Parse(&input, message); fs.close(); return (ret) ? SUCCESS : NOT_SUPPORTED; } // read caffemodel(bin) EE read_from_caffemodel(const char *path, google::protobuf::Message *message) { std::ifstream fs(path, std::ifstream::in | std::ifstream::binary); if (!fs.is_open()) { UNI_ERROR_LOG("can not open caffe prototxt file %s.\n", path); } google::protobuf::io::IstreamInputStream input(&fs); google::protobuf::io::CodedInputStream codedstr(&input); codedstr.SetTotalBytesLimit(INT_MAX, INT_MAX / 2); bool ret = message->ParseFromCodedStream(&codedstr); fs.close(); return (ret) ? SUCCESS : NOT_SUPPORTED; } OperatorType convert_caffe_type(std::string inputType) { if (inputType == "Convolution") { return OT_Conv; } else if (inputType == "Deconvolution") { return OT_Deconvolution; } else if (inputType == "L2Norm") { return OT_L2Normalization; } else if (inputType == "BatchNorm") { return OT_BatchNorm; } else if (inputType == "Scale") { return OT_Scale; } else if (inputType == "Eltwise") { return OT_Eltwise; } else if (inputType == "InnerProduct") { return OT_FC; } else if (inputType == "Pooling") { return OT_Pooling; } else if (inputType == "ReLU") { return OT_Relu; } else if (inputType == "ReLU6") { return OT_Relu6; } else if (inputType == "HSwish") { return OT_HSwish; } else if (inputType == "Sigmoid") { return OT_Sigmoid; } else if (inputType == "HSigmoid") { return OT_HSigmoid; } else if (inputType == "Softmax") { return OT_Softmax; } else if (inputType == "Concat") { return OT_Concat; } else if (inputType == "Embed") { return OT_Embedding; } else if (inputType == "Gelu") { return OT_Gelu; } else if (inputType == "LayerNorm") { return OT_LayerNorm; } else if (inputType == "MatMul") { return OT_MatMul; } else if (inputType == "Power") { return OT_Power; } else if (inputType == "Reshape") { return OT_Reshape; } else if (inputType == "Slice") { return OT_Slice; } else if (inputType == "Attention") { return OT_Attention; } else if (inputType == "Input") { return OT_Input; } else if (inputType == "LSTM") { return OT_RNN; } else if (inputType == "TanH") { return OT_TanH; } else if (inputType == "SoftmaxWithLoss") { return OT_SoftmaxWithLoss; } else if (inputType == "Squeeze") { return OT_Squeeze; } else if (inputType == "Unsqueeze") { return OT_Unsqueeze; } else if (inputType == "Reduction") { return OT_Reduction; } else if (inputType == "ArgMax") { return OT_ArgMax; } else if (inputType == "PreAllocatedMemory") { return OT_PreAllocatedMemory; } else if (inputType == "SharedWeight") { return OT_SharedWeight; } else if (inputType == "Copy") { return OT_Copy; } else if (inputType == "Check") { return OT_Check; } else if (inputType == "Repeat") { return OT_Repeat; } else if (inputType == "Interp") { return OT_Resize; } else if (inputType == "Jump") { return OT_Jump; } else if (inputType == "AttentionMask") { return OT_AttentionMask; } else if (inputType == "RelativePositionEmbed") { return OT_RelativePositionEmbedding; } else if (inputType == "RelativeShift") { return OT_RelativeShift; } else if (inputType == "Dropout") { return OT_Dropout; } else if (inputType == "Flatten") { return OT_Reshape; } else if (inputType == "Permute") { return OT_Transpose; } else if (inputType == "Clip") { return OT_Clip; } else if (inputType == "PriorBox") { return OT_PriorBox; } else if (inputType == "DetectionOutput") { return OT_DetectionOutput; } else if (inputType == "Yolov3DetectionOutput") { return OT_Yolov3DetectionOutput; } else if (inputType == "Mish") { return OT_Mish; } else if (inputType == "PReLU") { return OT_PRelu; } else if (inputType == "Tile") { return OT_Tile; } else if (inputType == "Pad") { return OT_Pad; } else if (inputType == "SoftPlus") { return OT_SoftPlus; } else if (inputType == "Exp") { return OT_Exp; } else if (inputType == "AbsVal") { return OT_Abs; } else if (inputType == "Silence") { return OT_None; } else { UNI_ERROR_LOG("operator name:%s type:%s not supported.\n", this->layer.name().c_str(), inputType.c_str()); } return OT_None; } int net_search_layerId(caffe::NetParameter &netParams, std::string &layerName) { int i = 0; if (netParams.layer_size() > 0) { for (i = 0; i < netParams.layer_size(); i++) { if (netParams.layer(i).name() == layerName) { return i; } } } else { for (i = 0; i < netParams.layers_size(); i++) { if (netParams.layers(i).name() == layerName) { return i; } } } return -1; } caffe::BlobProto net_get_blob(caffe::NetParameter &netParams, int layerId, int blobId) { if (netParams.layer_size() > 0) { return netParams.layer(layerId).blobs(blobId); } else { return netParams.layers(layerId).blobs(blobId); } } int net_get_blobs_size(caffe::NetParameter &netParams, int layerId) { if (netParams.layer_size() > 0) { return netParams.layer(layerId).blobs_size(); } else { return netParams.layers(layerId).blobs_size(); } } void net_copy_blob(WeightSpec *wsPtr, int weightIndex, caffe::NetParameter &netParams, int netLayerId, int blobNum, OperatorType operatorType) { wsPtr[weightIndex].mdt = DT_F32; wsPtr[weightIndex].bytes_of_weight = 0; wsPtr[weightIndex].weight = nullptr; wsPtr[weightIndex].bytes_of_vec = 0; wsPtr[weightIndex].vec = nullptr; std::vector<std::pair<caffe::BlobProto, U32>> weights; std::vector<std::pair<caffe::BlobProto, U32>> biases; // Batchnorm may have 3 blobs, but the third blob can be ignored if (operatorType == OT_BatchNorm) { if (blobNum >= 3) { blobNum = 2; } } if (blobNum >= 1) { caffe::BlobProto blob0 = net_get_blob(netParams, netLayerId, 0); U32 elemSize = sizeof(*(blob0.data().data())); CHECK_REQUIREMENT(elemSize == bytesOf(wsPtr[weightIndex].mdt)); U32 blobSize = elemSize * blob0.data_size(); wsPtr[weightIndex].bytes_of_weight += blobSize; weights.push_back(std::make_pair(blob0, blobSize)); } if (blobNum >= 2) { caffe::BlobProto blob1 = net_get_blob(netParams, netLayerId, 1); U32 elemSize = sizeof(*(blob1.data().data())); CHECK_REQUIREMENT(sizeof(*(blob1.data().data())) == bytesOf(wsPtr[weightIndex].mdt)); U32 blobSize = elemSize * blob1.data_size(); wsPtr[weightIndex].bytes_of_vec += blobSize; biases.push_back(std::make_pair(blob1, blobSize)); } if (blobNum >= 3) { caffe::BlobProto blob2 = net_get_blob(netParams, netLayerId, 2); U32 elemSize = sizeof(*(blob2.data().data())); CHECK_REQUIREMENT(elemSize == bytesOf(wsPtr[weightIndex].mdt)); U32 blobSize = elemSize * blob2.data_size(); wsPtr[weightIndex].bytes_of_weight += blobSize; weights.push_back(std::make_pair(blob2, blobSize)); } if (weights.size() > 0) { wsPtr[weightIndex].weight = (U8 *)mt_new_storage(wsPtr[weightIndex].bytes_of_weight); U8 *ptr = wsPtr[weightIndex].weight; for (U32 i = 0; i < weights.size(); i++) { memcpy(ptr, weights[i].first.data().data(), weights[i].second); ptr += weights[i].second; } } if (biases.size() > 0) { wsPtr[weightIndex].vec = (U8 *)mt_new_storage(wsPtr[weightIndex].bytes_of_vec); U8 *ptr = wsPtr[weightIndex].vec; for (U32 i = 0; i < biases.size(); i++) { memcpy(ptr, biases[i].first.data().data(), biases[i].second); ptr += biases[i].second; } } } EE parse_file(std::string dir, std::string mfn) override { EE ret = SUCCESS; std::string prototxtSuffix = ".prototxt"; std::string caffeModelSuffix = ".caffemodel"; std::string prototxtPath = dir + "/" + mfn + prototxtSuffix; std::string caffeModelPath = dir + "/" + mfn + caffeModelSuffix; // load prototxt ret = read_from_prototxt(prototxtPath.c_str(), (google::protobuf::Message *)(&proto)); if (proto.layer_size() <= 0 || ret != SUCCESS) { UNI_ERROR_LOG("can not read caffe prototxt file %s.\n", prototxtPath.c_str()); } // load model bin. ret = read_from_caffemodel(caffeModelPath.c_str(), (google::protobuf::Message *)(&net)); if (ret != SUCCESS) { UNI_ERROR_LOG("can not read caffe model file %s.\n", caffeModelPath.c_str()); } return ret; } // the first loop can specify the input info and output info EE adapt_operators(ModelSpec *ms) override { EE ret = SUCCESS; // model_name str_copy(ms->model_name, proto.name().c_str(), proto.name().length()); ms->dt = DT_F32; // set default value ms->num_operator_specs = proto.layer_size(); OperatorSpec *opsPtr = (OperatorSpec *)mt_new_storage(sizeof(OperatorSpec) * ms->num_operator_specs); ms->ops = opsPtr; for (I32 i = 0; i < ms->num_operator_specs; i++) { ms->ops[i].tensor_positions = nullptr; ms->ops[i].num_quant_feature = 0; ms->ops[i].feature_scale = nullptr; } int inputsNumber = 0; weightNumber = 0; // set global variable initial value std::map<std::string, int> outputCounts; std::set<std::string> sharedWeightCounts; for (int i = 0; i < proto.input_size(); i++) { outputCounts[proto.input(i).c_str()] = 1; } for (int i = 0; i < proto.layer_size(); i++) { if (proto.layer(i).type() == "SharedWeight") { sharedWeightCounts.insert(proto.layer(i).top(0)); } } for (int i = 0; i < proto.layer_size(); i++) { const caffe::LayerParameter curLayer = proto.layer(i); this->layer = curLayer; UNI_DEBUG_LOG("process operator name:%s parameter.\n", this->layer.name().c_str()); if (layer.type() == "Input") { // layer,the global variable inputsNumber++; } str_copy(opsPtr[i].name, layer.name().c_str(), layer.name().length()); this->op = layer.type(); opsPtr[i].type = convert_caffe_type(layer.type()); int bottomSize = layer.bottom_size(); opsPtr[i].num_inputs = bottomSize; opsPtr[i].input_tensors_name = (I8 **)mt_new_storage(bottomSize * sizeof(I8 *)); for (int j = 0; j < bottomSize; j++) { opsPtr[i].input_tensors_name[j] = (I8 *)mt_new_storage(NAME_LEN * sizeof(I8)); str_copy(opsPtr[i].input_tensors_name[j], layer.bottom(j).c_str(), layer.bottom(j).length()); if (outputCounts.find(layer.bottom(j)) == outputCounts.end()) { if (opsPtr[i].type != OT_Jump) { UNI_ERROR_LOG("no tensor is operator name:%s input %s.\n", layer.name().c_str(), layer.bottom(j).c_str()); } } else { outputCounts[layer.bottom(j)]--; } } int topSize = layer.top_size(); opsPtr[i].num_outputs = topSize; opsPtr[i].output_tensors_name = (I8 **)mt_new_storage(topSize * sizeof(I8 *)); for (int j = 0; j < topSize; j++) { opsPtr[i].output_tensors_name[j] = (I8 *)mt_new_storage(NAME_LEN * sizeof(I8)); str_copy( opsPtr[i].output_tensors_name[j], layer.top(j).c_str(), layer.top(j).length()); if (outputCounts.find(layer.top(j)) == outputCounts.end()) { outputCounts[layer.top(j)] = 1; } else { outputCounts[layer.top(j)]++; } } CHECK_STATUS(adapt_operator(opsPtr[i].type, &(ms->ops[i].ps))); if (opsPtr[i].type == OT_MatMul && sharedWeightCounts.count(layer.bottom(1))) { weightNumber += 1; } } inputsNumber = (inputsNumber > proto.input_size()) ? inputsNumber : proto.input_size(); ms->num_inputs = inputsNumber; ms->input_names = (I8 **)mt_new_storage(inputsNumber * sizeof(I8 *)); ms->input_dims = (TensorDesc *)mt_new_storage(sizeof(TensorDesc) * inputsNumber); for (int i = 0; i < inputsNumber; i++) { ms->input_names[i] = (I8 *)mt_new_storage(NAME_LEN * sizeof(I8)); ms->input_dims[i] = tensor0d(); if (proto.input_size() > 0) { str_copy(ms->input_names[i], proto.input(i).c_str(), proto.input(i).length()); ms->input_dims[i].nDims = proto.input_dim_size(); for (U32 j = 0; j < ms->input_dims[i].nDims; j++) { ms->input_dims[i].dims[ms->input_dims[i].nDims - 1 - j] = proto.input_dim(j); } } if (i < proto.input_shape_size()) { str_copy(ms->input_names[i], proto.input(i).c_str(), proto.input(i).length()); ms->input_dims[i].nDims = proto.input_shape(i).dim_size(); for (U32 j = 0; j < ms->input_dims[i].nDims; j++) { ms->input_dims[i].dims[ms->input_dims[i].nDims - 1 - j] = proto.input_shape(i).dim(j); } } ms->input_dims[i].dt = DT_F32; ms->input_dims[i].df = getTensorDefaultDataFormat(ms->input_dims[i].nDims); } for (int i = 0; i < proto.output_size(); i++) { std::string name = proto.output(i); if (outputCounts.find(name) == outputCounts.end()) { UNI_ERROR_LOG("can not find model output %s in tensors.\n", name.c_str()); } else { outputCounts[name] = (outputCounts[name] > 0) ? outputCounts[name] : 1; } } int outputsNumber = 0; for (auto iter : outputCounts) { if (iter.second > 0) { outputsNumber++; } } ms->num_outputs = outputsNumber; ms->output_names = (I8 **)mt_new_storage(outputsNumber * sizeof(I8 *)); outputsNumber = 0; for (auto iter : outputCounts) { if (iter.second > 0) { ms->output_names[outputsNumber] = (I8 *)mt_new_storage(NAME_LEN * sizeof(I8)); str_copy(ms->output_names[outputsNumber], iter.first.c_str(), iter.first.length()); outputsNumber++; } } ms->num_weight_specs = this->weightNumber; return ret; } EE adapt_weights(ModelSpec *ms) override { EE ret = SUCCESS; WeightSpec *wsPtr = (WeightSpec *)mt_new_storage(sizeof(WeightSpec) * ms->num_weight_specs); for (int j = 0; j < ms->num_weight_specs; j++) { wsPtr[j].num_quant_scale = 0; wsPtr[j].weight_scale = nullptr; } ms->ws = wsPtr; int inNamesIndex = 0; int weightIndex = 0; std::set<std::string> sharedWeightCounts; for (int i = 0; i < proto.layer_size(); i++) { if (proto.layer(i).type() == "SharedWeight") { sharedWeightCounts.insert(proto.layer(i).top(0)); } } for (int i = 0; i < proto.layer_size(); i++) { this->layer = proto.layer(i); std::string layerName = layer.name(); UNI_DEBUG_LOG("process operator name:%s weight.\n", layerName.c_str()); std::string layerType = layer.type(); if (layerType == "Input") { std::string dataName = layerName; if (layer.top_size() > 0) { dataName = layer.top(0); } str_copy(ms->input_names[inNamesIndex], dataName.c_str(), dataName.length()); ms->input_dims[inNamesIndex].nDims = layer.input_param().shape(0).dim_size(); ms->input_dims[inNamesIndex].dt = DT_F32; ms->input_dims[inNamesIndex].df = getTensorDefaultDataFormat(ms->input_dims[inNamesIndex].nDims); for (U32 j = 0; j < ms->input_dims[inNamesIndex].nDims; j++) { ms->input_dims[inNamesIndex].dims[ms->input_dims[inNamesIndex].nDims - 1 - j] = layer.input_param().shape(0).dim(j); } inNamesIndex++; } else if (layerType == "Convolution" || layerType == "InnerProduct" || layerType == "BatchNorm" || layerType == "Embed" || layerType == "LSTM" || layerType == "SharedWeight" || layerType == "RelativePositionEmbed" || layerType == "Deconvolution" || layerType == "PReLU") { int netLayerId = net_search_layerId(net, layerName); CHECK_REQUIREMENT(netLayerId >= 0); str_copy(wsPtr[weightIndex].op_name, layerName.c_str(), layerName.length()); U32 blobNum = net_get_blobs_size(net, netLayerId); net_copy_blob( wsPtr, weightIndex, net, netLayerId, blobNum, convert_caffe_type(layerType)); if (layerType == "BatchNorm" && blobNum > 2) { caffe::BlobProto blob2 = net_get_blob(net, netLayerId, 2); float cur_gama = blob2.data().data()[0] == 0 ? 1.0 : 1.0 / blob2.data().data()[0]; ms->ops[i].ps.bn_spec.gama = cur_gama; } weightIndex++; } else if (layerType == "Scale" || layerType == "LayerNorm") { int netLayerId = net_search_layerId(net, layerName); CHECK_REQUIREMENT(netLayerId >= 0); str_copy(wsPtr[weightIndex].op_name, layerName.c_str(), layerName.length()); U32 blobNum = net_get_blobs_size(net, netLayerId); if (layer.bottom_size() == 1) { CHECK_REQUIREMENT(blobNum >= 1); } else { CHECK_REQUIREMENT(blobNum == 0); } net_copy_blob( wsPtr, weightIndex, net, netLayerId, blobNum, convert_caffe_type(layerType)); weightIndex++; } else if (layerType == "MatMul" && sharedWeightCounts.count(layer.bottom(1))) { int netLayerId = net_search_layerId(net, layerName); CHECK_REQUIREMENT(netLayerId >= 0); str_copy(wsPtr[weightIndex].op_name, layerName.c_str(), layerName.length()); net_copy_blob(wsPtr, weightIndex, net, netLayerId, 0, convert_caffe_type(layerType)); weightIndex++; } } CHECK_REQUIREMENT(weightIndex == weightNumber); // relationship init null ms->num_op_tensor_entries = 0; ms->op_relationship_entries = nullptr; return ret; } ParameterSpec adapt_Resize() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); ResizeParamSpec resizePs; memset(&resizePs, 0, sizeof(resizePs)); auto caffeInterpParam = layer.interp_param(); resizePs.sizes[0] = caffeInterpParam.height(); resizePs.sizes[1] = caffeInterpParam.width(); resizePs.num_sizes = 2; resizePs.num_scales = 0; curPs.resize_spec = resizePs; return curPs; } ParameterSpec adapt_Conv() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); weightNumber = weightNumber + 1; ConvolutionParamSpec cps; memset(&cps, 0, sizeof(cps)); cps.num_outputs = layer.convolution_param().num_output(); cps.num_outputs_origin = cps.num_outputs; cps.kernel_t = 1; cps.stride_t = 1; cps.padding_before = 0; cps.padding_after = 0; cps.dilatedRate_t = 1; if (layer.convolution_param().has_kernel_w() && layer.convolution_param().has_kernel_h()) { cps.kernel_w = layer.convolution_param().kernel_w(); cps.kernel_h = layer.convolution_param().kernel_h(); } else { cps.kernel_h = (layer.convolution_param().kernel_size_size() > 0) ? layer.convolution_param().kernel_size(0) : 1; cps.kernel_w = (layer.convolution_param().kernel_size_size() > 1) ? layer.convolution_param().kernel_size(1) : cps.kernel_h; } cps.group = (layer.convolution_param().has_group()) ? layer.convolution_param().group() : 1; // group[default=1] cps.dilatedRate_h = (layer.convolution_param().dilation_size() != 0) ? layer.convolution_param().dilation(0) : 1; cps.dilatedRate_w = cps.dilatedRate_h; if (cps.group != 1 && cps.group == cps.num_outputs) { cps.convolution_type = Convolution_Depthwise; } else { if (cps.dilatedRate_h > 1 || cps.dilatedRate_w > 1) { cps.convolution_type = Convolution_Dilation; } else { cps.convolution_type = Convolution_Pointwise; } } cps.dw_activation_type = ACTIVATION_NULL; cps.pw_activation_type = ACTIVATION_NULL; if (layer.convolution_param().has_stride_w() && layer.convolution_param().has_stride_h()) { cps.stride_w = layer.convolution_param().stride_w(); cps.stride_h = layer.convolution_param().stride_h(); } else { cps.stride_h = (layer.convolution_param().stride_size() != 0) ? layer.convolution_param().stride(0) : 1; // stride[default=1] cps.stride_w = (layer.convolution_param().stride_size() > 1) ? layer.convolution_param().stride(1) : cps.stride_h; } if (layer.convolution_param().has_pad_w() && layer.convolution_param().has_pad_h()) { cps.padding_left = layer.convolution_param().pad_w(); cps.padding_right = cps.padding_left; cps.padding_top = layer.convolution_param().pad_h(); cps.padding_bottom = cps.padding_top; } else { cps.padding_top = (layer.convolution_param().pad_size() > 0) ? layer.convolution_param().pad(0) : 0; cps.padding_bottom = (layer.convolution_param().pad_size() > 1) ? layer.convolution_param().pad(1) : cps.padding_top; cps.padding_left = (layer.convolution_param().pad_size() > 2) ? layer.convolution_param().pad(2) : cps.padding_top; cps.padding_right = (layer.convolution_param().pad_size() > 3) ? layer.convolution_param().pad(3) : cps.padding_top; } curPs.conv_spec = cps; return curPs; } ParameterSpec adapt_Deconvolution() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); weightNumber = weightNumber + 1; ConvolutionParamSpec cps; memset(&cps, 0, sizeof(cps)); cps.num_outputs = layer.convolution_param().num_output(); cps.num_outputs_origin = cps.num_outputs; cps.kernel_t = 1; cps.stride_t = 1; cps.padding_before = 0; cps.padding_after = 0; cps.dilatedRate_t = 1; if (layer.convolution_param().has_kernel_w() && layer.convolution_param().has_kernel_h()) { cps.kernel_w = layer.convolution_param().kernel_w(); cps.kernel_h = layer.convolution_param().kernel_h(); } else { cps.kernel_h = layer.convolution_param().kernel_size(0); cps.kernel_w = cps.kernel_h; } cps.group = (layer.convolution_param().has_group()) ? layer.convolution_param().group() : 1; if (1 != cps.group) { UNI_ERROR_LOG( "can not process operator name:%s group != 1.", this->layer.name().c_str()); } cps.dilatedRate_h = 1; cps.dilatedRate_w = 1; cps.convolution_type = Convolution_Deconvolution; cps.dw_activation_type = ACTIVATION_NULL; cps.pw_activation_type = ACTIVATION_NULL; if (layer.convolution_param().has_stride_w() && layer.convolution_param().has_stride_h()) { cps.stride_w = layer.convolution_param().stride_w(); cps.stride_h = layer.convolution_param().stride_h(); } else { cps.stride_h = (layer.convolution_param().stride_size() != 0) ? layer.convolution_param().stride(0) : 1; // stride[default=1] cps.stride_w = cps.stride_h; } cps.rm = CEIL; if (layer.convolution_param().has_pad_w() && layer.convolution_param().has_pad_h()) { cps.padding_left = layer.convolution_param().pad_w(); cps.padding_right = cps.padding_left; cps.padding_top = layer.convolution_param().pad_h(); cps.padding_bottom = cps.padding_top; } else { cps.padding_top = (layer.convolution_param().pad_size() != 0) ? layer.convolution_param().pad(0) : 0; // pad[default=0] cps.padding_bottom = cps.padding_top; cps.padding_left = cps.padding_top; cps.padding_right = cps.padding_top; } curPs.conv_spec = cps; return curPs; } ParameterSpec adapt_Pooling() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); PoolingParamSpec pps; memset(&pps, 0, sizeof(pps)); pps.kernel_t = 1; pps.stride_t = 1; pps.padding_before = 0; pps.padding_after = 0; if (layer.pooling_param().has_kernel_w() && layer.pooling_param().has_kernel_h()) { pps.kernel_w = layer.pooling_param().kernel_w(); pps.kernel_h = layer.pooling_param().kernel_h(); } else { pps.kernel_h = layer.pooling_param().kernel_size(); pps.kernel_w = pps.kernel_h; } if (layer.pooling_param().has_stride_w() && layer.pooling_param().has_stride_h()) { pps.stride_w = layer.pooling_param().stride_w(); pps.stride_h = layer.pooling_param().stride_h(); } else { pps.stride_h = layer.pooling_param().stride(); pps.stride_w = pps.stride_h; } bool global_pooling = layer.pooling_param().global_pooling(); if (global_pooling) { pps.kernel_h = 0; pps.kernel_w = 0; pps.stride_h = 1; pps.stride_w = 1; } else { CHECK_REQUIREMENT(pps.kernel_h > 0); } if (layer.pooling_param().has_pad_w() && layer.pooling_param().has_pad_h()) { pps.padding_left = layer.pooling_param().pad_w(); pps.padding_right = pps.padding_left; pps.padding_top = layer.pooling_param().pad_h(); pps.padding_bottom = pps.padding_top; } else { pps.padding_top = layer.pooling_param().has_pad() ? layer.pooling_param().pad() : 0; pps.padding_bottom = pps.padding_top; pps.padding_left = pps.padding_top; pps.padding_right = pps.padding_top; } if (layer.pooling_param().has_round_mode() && layer.pooling_param().round_mode() == 1) { pps.rm = FLOOR; } else { pps.rm = CEIL; } auto op = layer.pooling_param().pool(); switch (op) { case caffe::PoolingParameter_PoolMethod_MAX: { pps.mode = POOLING_MAX; break; } case caffe::PoolingParameter_PoolMethod_AVE: { pps.mode = POOLING_MEAN; break; } default: { const google::protobuf::EnumDescriptor *descriptor = caffe::PoolingParameter::PoolMethod_descriptor(); UNI_ERROR_LOG("can not map operator name:%s %s to Pooling.\n", this->layer.name().c_str(), descriptor->FindValueByNumber(op)->name().c_str()); } } curPs.pooling_spec = pps; return curPs; } ParameterSpec adapt_Fc() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); weightNumber = weightNumber + 1; FullyConnectedParamSpec ips; memset(&ips, 0, sizeof(ips)); ips.num_outputs = layer.inner_product_param().num_output(); ips.num_slices = 1; ips.slice_point[0] = ips.num_outputs; curPs.fc_spec = ips; return curPs; } ParameterSpec adapt_BatchNorm() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); weightNumber = weightNumber + 1; BatchNormParamSpec bnps; memset(&bnps, 0, sizeof(bnps)); bnps.axis = layer.batch_norm_param().axis(); bnps.eps = layer.batch_norm_param().eps(); bnps.gama = 1; bnps.momentum = layer.batch_norm_param().moving_average_fraction(); curPs.bn_spec = bnps; return curPs; } ParameterSpec adapt_LayerNorm() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); weightNumber = weightNumber + 1; return curPs; } ParameterSpec adapt_Eltwise() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); EltwiseParamSpec eps; memset(&eps, 0, sizeof(eps)); EltwiseSumSpec ess; memset(&ess, 0, sizeof(ess)); auto caffeEltwiseParam = layer.eltwise_param(); auto op = caffeEltwiseParam.operation(); switch (op) { case caffe::EltwiseParameter_EltwiseOp_PROD: eps.elt_mode = ELTWISE_PROD; break; case caffe::EltwiseParameter_EltwiseOp_SUM: eps.elt_mode = ELTWISE_SUM; break; case caffe::EltwiseParameter_EltwiseOp_MAX: eps.elt_mode = ELTWISE_MAX; break; case caffe::EltwiseParameter_EltwiseOp_DIV: eps.elt_mode = ELTWISE_DIV; break; default: { const google::protobuf::EnumDescriptor *descriptor = caffe::EltwiseParameter::EltwiseOp_descriptor(); UNI_ERROR_LOG("can not map operator name:%s %s to Eltwise.\n", this->layer.name().c_str(), descriptor->FindValueByNumber(op)->name().c_str()); } } U32 bytes = caffeEltwiseParam.coeff_size() * sizeof(F32); ess.coeff_size = caffeEltwiseParam.coeff_size(); memcpy(ess.coeff_values, caffeEltwiseParam.coeff().data(), bytes); for (int j = 0; j < caffeEltwiseParam.coeff_size(); j++) { CHECK_REQUIREMENT(ess.coeff_values[j] == 1); } eps.elt_sum_spec = ess; eps.activation_type = ACTIVATION_NULL; curPs.eltwise_spec = eps; return curPs; } ParameterSpec adapt_Embedding() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); weightNumber = weightNumber + 1; EmbedParamSpec embedPs; memset(&embedPs, 0, sizeof(embedPs)); auto caffeEmbedParam = layer.embed_param(); embedPs.input_dim = caffeEmbedParam.input_dim(); embedPs.num_output = caffeEmbedParam.num_output(); embedPs.bias_term = caffeEmbedParam.bias_term() == 0 ? false : true; embedPs.transpose = caffeEmbedParam.transpose() == 0 ? false : true; curPs.embed_spec = embedPs; return curPs; } ParameterSpec adapt_Power() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); PowerParamSpec powerPs; memset(&powerPs, 0, sizeof(powerPs)); auto caffePowerParam = layer.power_param(); powerPs.scale = caffePowerParam.scale(); powerPs.shift = caffePowerParam.shift(); powerPs.power = caffePowerParam.power(); curPs.power_spec = powerPs; return curPs; } ParameterSpec adapt_Reshape() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); ReshapeParamSpec reshapePs; memset(&reshapePs, 0, sizeof(reshapePs)); if (this->op == "Flatten") { auto caffeFlattenParam = layer.flatten_param(); CHECK_REQUIREMENT( -1 == caffeFlattenParam.end_axis()); // Currently compute as reshape layer reshapePs.shape_size = caffeFlattenParam.axis() + 1; for (I32 iter = 0; iter < reshapePs.shape_size - 1; iter++) { reshapePs.shape_dims[iter] = 0; } reshapePs.shape_dims[reshapePs.shape_size - 1] = -1; reshapePs.axis = 0; reshapePs.num_axes = -1; } else { auto caffeReshapeParam = layer.reshape_param(); reshapePs.shape_size = caffeReshapeParam.shape().dim_size(); for (I32 iter = 0; iter < caffeReshapeParam.shape().dim_size(); iter++) { reshapePs.shape_dims[iter] = caffeReshapeParam.shape().dim(iter); } reshapePs.axis = caffeReshapeParam.axis(); reshapePs.num_axes = caffeReshapeParam.num_axes(); } curPs.reshape_spec = reshapePs; return curPs; } ParameterSpec adapt_Slice() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); SliceParamSpec slicePs; memset(&slicePs, 0, sizeof(slicePs)); auto caffeSliceParam = layer.slice_param(); for (I32 iter = 0; iter < caffeSliceParam.slice_point().size(); iter++) { slicePs.slice_points[iter] = caffeSliceParam.slice_point(iter); } slicePs.slice_size = caffeSliceParam.slice_point().size(); slicePs.axis = caffeSliceParam.axis(); curPs.slice_spec = slicePs; return curPs; } ParameterSpec adapt_Transpose() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); TransposeParamSpec transPs; memset(&transPs, 0, sizeof(transPs)); auto caffePermuteParam = layer.permute_param(); for (I32 iter = 0; iter < caffePermuteParam.order().size(); iter++) { transPs.trans_dims[iter] = caffePermuteParam.order(iter); } transPs.trans_size = caffePermuteParam.order().size(); curPs.transpose_spec = transPs; return curPs; } ParameterSpec adapt_Tile() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); TileParamSpec tilePS; auto caffeTileParam = layer.tile_param(); for (int i = 0; i < 8; ++i) { tilePS.repeatsInfo[i] = 1; } tilePS.dimsSize = 1; tilePS.axis = caffeTileParam.axis(); tilePS.repeatsInfo[0] = caffeTileParam.tiles(); curPs.tile_spec = tilePS; return curPs; } ParameterSpec adapt_Pad() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); PadParamSpec padPs; auto caffePadParam = layer.padding_param(); padPs.before = 0; padPs.after = 0; padPs.top = caffePadParam.shape(0); padPs.bottom = caffePadParam.shape(1); padPs.left = caffePadParam.shape(2); padPs.right = caffePadParam.shape(3); padPs.constant_value = 0; padPs.pad_mode = Pad_Constant; curPs.pad_spec = padPs; return curPs; } ParameterSpec adapt_Attention() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); AttentionParamSpec attentionPs; memset(&attentionPs, 0, sizeof(attentionPs)); auto caffe_attention_param = layer.attention_param(); attentionPs.num_heads = caffe_attention_param.num_heads(); attentionPs.from_sequence_length = caffe_attention_param.from_sequence_length(); attentionPs.to_sequence_length = caffe_attention_param.to_sequence_length(); curPs.attention_spec = attentionPs; return curPs; } ParameterSpec adapt_RNN() override { weightNumber = weightNumber + 1; ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); RNNParamSpec rnnPs; memset(&rnnPs, 0, sizeof(rnnPs)); auto caffeLSTMParam = layer.lstm_param(); rnnPs.mode = RNN_LSTM; rnnPs.numOutput = caffeLSTMParam.num_output(); rnnPs.steps = caffeLSTMParam.steps(); if (rnnPs.steps == -2) { rnnPs.steps = 0; rnnPs.biDirection = true; } else { rnnPs.biDirection = false; } rnnPs.numProjection = caffeLSTMParam.num_proj(); rnnPs.zoneoutCell = caffeLSTMParam.zoneout_cell(); rnnPs.zoneoutOutput = caffeLSTMParam.zoneout_output(); rnnPs.forgetBias = 1.0; rnnPs.activationMode = ACTIVATION_TANH; curPs.rnn_spec = rnnPs; return curPs; } ParameterSpec adapt_Scale() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); weightNumber = weightNumber + 1; ScaleParamSpec scalePs; memset(&scalePs, 0, sizeof(scalePs)); auto caffeScaleParam = layer.scale_param(); scalePs.axis = caffeScaleParam.axis(); curPs.scale_spec = scalePs; return curPs; } ParameterSpec adapt_Reduction() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); ReductionParamSpec reductionPs; memset(&reductionPs, 0, sizeof(reductionPs)); auto caffeReductionParam = layer.reduction_param(); reductionPs.axes[0] = caffeReductionParam.axis(); reductionPs.axes_num = 1; auto op = caffeReductionParam.operation(); switch (op) { case caffe::ReductionParameter_ReductionOp_SUM: reductionPs.reduction_mode = REDUCTION_SUM; break; case caffe::ReductionParameter_ReductionOp_MEAN: reductionPs.reduction_mode = REDUCTION_MEAN; break; default: { const google::protobuf::EnumDescriptor *descriptor = caffe::ReductionParameter::ReductionOp_descriptor(); UNI_ERROR_LOG("can not map operator name:%s %s to Reduction.\n", this->layer.name().c_str(), descriptor->FindValueByNumber(op)->name().c_str()); } } reductionPs.coeff = caffeReductionParam.coeff(); reductionPs.keep_dim = caffeReductionParam.keep_dim(); curPs.reduction_spec = reductionPs; return curPs; } ParameterSpec adapt_Squeeze() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); SqueezeParamSpec squeezePs; memset(&squeezePs, 0, sizeof(squeezePs)); auto caffeSqueezeParam = layer.squeeze_param(); squeezePs.axes[0] = caffeSqueezeParam.axis(); squeezePs.axes_num = 1; curPs.squeeze_spec = squeezePs; return curPs; } ParameterSpec adapt_Unsqueeze() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); UnsqueezeParamSpec unsqueezePs; memset(&unsqueezePs, 0, sizeof(unsqueezePs)); auto caffeUnsqueezeParam = layer.unsqueeze_param(); unsqueezePs.axes[0] = caffeUnsqueezeParam.axis(); unsqueezePs.axes_num = 1; curPs.unsqueeze_spec = unsqueezePs; return curPs; } ParameterSpec adapt_ArgMax() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); ArgMaxParamSpec argmaxPs; memset(&argmaxPs, 0, sizeof(argmaxPs)); auto caffeArgMaxParam = layer.argmax_param(); argmaxPs.axis = caffeArgMaxParam.axis(); curPs.argmax_spec = argmaxPs; return curPs; } ParameterSpec adapt_Repeat() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); RepeatParamSpec repeatPs; memset(&repeatPs, 0, sizeof(repeatPs)); auto caffeRepeatParam = layer.repeat_param(); repeatPs.loops = caffeRepeatParam.loops(); repeatPs.axis = caffeRepeatParam.axis(); curPs.repeat_spec = repeatPs; return curPs; } ParameterSpec adapt_Check() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); CheckParamSpec checkPs; memset(&checkPs, 0, sizeof(checkPs)); auto caffeCheckParam = layer.check_param(); auto op = caffeCheckParam.operation(); switch (op) { case caffe::CheckParameter_CheckOp_EQUAL: checkPs.check_mode = CHECK_EQUAL; break; case caffe::CheckParameter_CheckOp_GREAT: checkPs.check_mode = CHECK_GREAT; break; case caffe::CheckParameter_CheckOp_GREATEQUAL: checkPs.check_mode = CHECK_GREATEQUAL; break; default: { const google::protobuf::EnumDescriptor *descriptor = caffe::CheckParameter::CheckOp_descriptor(); UNI_ERROR_LOG("can not map operator name:%s %s to Check.\n", this->layer.name().c_str(), descriptor->FindValueByNumber(op)->name().c_str()); } } curPs.check_spec = checkPs; return curPs; } ParameterSpec adapt_PreAllocatedMemory() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); PreAllocatedMemoryParamSpec preAllocatedMemoryPs; memset(&preAllocatedMemoryPs, 0, sizeof(preAllocatedMemoryPs)); auto caffePreAllocatedMemoryParam = layer.preallocated_memory_param(); preAllocatedMemoryPs.desc.nDims = caffePreAllocatedMemoryParam.shape().dim_size(); for (I32 iter = 0; iter < caffePreAllocatedMemoryParam.shape().dim_size(); iter++) { preAllocatedMemoryPs.desc.dims[preAllocatedMemoryPs.desc.nDims - 1 - iter] = caffePreAllocatedMemoryParam.shape().dim(iter); } preAllocatedMemoryPs.desc.df = getTensorDefaultDataFormat(preAllocatedMemoryPs.desc.nDims); auto dt = caffePreAllocatedMemoryParam.data_type(); switch (dt) { case caffe::PreAllocatedMemoryParameter_DataType_FLOAT32: preAllocatedMemoryPs.desc.dt = DT_F32; break; case caffe::PreAllocatedMemoryParameter_DataType_UINT32: preAllocatedMemoryPs.desc.dt = DT_U32; break; case caffe::PreAllocatedMemoryParameter_DataType_INT32: preAllocatedMemoryPs.desc.dt = DT_I32; break; default: { const google::protobuf::EnumDescriptor *descriptor = caffe::PreAllocatedMemoryParameter::DataType_descriptor(); UNI_ERROR_LOG("can not process operator name:%s %s type memory.\n", this->layer.name().c_str(), descriptor->FindValueByNumber(dt)->name().c_str()); } } curPs.preallocated_memory_spec = preAllocatedMemoryPs; return curPs; } ParameterSpec adapt_SharedWeight() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); weightNumber = weightNumber + 1; SharedWeightParamSpec sharedWeightPs; memset(&sharedWeightPs, 0, sizeof(sharedWeightPs)); auto caffeSharedWeightParam = layer.shared_weight_param(); sharedWeightPs.desc.nDims = caffeSharedWeightParam.shape().dim_size(); for (I32 iter = 0; iter < caffeSharedWeightParam.shape().dim_size(); iter++) { sharedWeightPs.desc.dims[sharedWeightPs.desc.nDims - 1 - iter] = caffeSharedWeightParam.shape().dim(iter); } sharedWeightPs.desc.df = getTensorDefaultDataFormat(sharedWeightPs.desc.nDims); auto dt = caffeSharedWeightParam.data_type(); switch (dt) { case caffe::SharedWeightParameter_DataType_FLOAT32: sharedWeightPs.desc.dt = DT_F32; break; case caffe::SharedWeightParameter_DataType_UINT32: sharedWeightPs.desc.dt = DT_U32; break; case caffe::SharedWeightParameter_DataType_INT32: sharedWeightPs.desc.dt = DT_I32; break; default: { const google::protobuf::EnumDescriptor *descriptor = caffe::SharedWeightParameter::DataType_descriptor(); UNI_ERROR_LOG("can not process operator name:%s %s type weight.\n", this->layer.name().c_str(), descriptor->FindValueByNumber(dt)->name().c_str()); } } curPs.shared_weight_spec = sharedWeightPs; return curPs; } ParameterSpec adapt_Copy() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); CopyParamSpec copyPs; memset(&copyPs, 0, sizeof(copyPs)); auto caffeCopyParam = layer.copy_param(); copyPs.src_dims[0] = caffeCopyParam.src_batch_stride(); copyPs.src_dims[1] = caffeCopyParam.src_stride(); copyPs.src_dims[2] = caffeCopyParam.src_offset(); copyPs.dst_dims[0] = caffeCopyParam.dst_batch_stride(); copyPs.dst_dims[1] = caffeCopyParam.dst_stride(); copyPs.dst_dims[2] = caffeCopyParam.dst_offset(); copyPs.length = caffeCopyParam.length(); curPs.copy_spec = copyPs; return curPs; } ParameterSpec adapt_MatMul() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); MatMulParamSpec matmulPs; memset(&matmulPs, 0, sizeof(matmulPs)); auto caffeMatMulParam = layer.matmul_param(); matmulPs.transpose_a = caffeMatMulParam.transpose_a(); matmulPs.transpose_b = caffeMatMulParam.transpose_b(); curPs.matmul_spec = matmulPs; return curPs; } ParameterSpec adapt_AttentionMask() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); AttentionMaskParamSpec attentionMaskPs; memset(&attentionMaskPs, 0, sizeof(attentionMaskPs)); auto caffeAttentionMaskParam = layer.attention_mask_param(); attentionMaskPs.attention_length = caffeAttentionMaskParam.attention_length(); attentionMaskPs.same_length = caffeAttentionMaskParam.same_length(); attentionMaskPs.mask = caffeAttentionMaskParam.mask(); curPs.attention_mask_spec = attentionMaskPs; return curPs; } ParameterSpec adapt_RelativePositionEmbedding() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); weightNumber = weightNumber + 1; EmbedParamSpec p; memset(&p, 0, sizeof(p)); auto caffeRelativePositionEmbedParam = layer.relative_position_embed_param(); p.input_dim = caffeRelativePositionEmbedParam.input_dim(); p.num_output = caffeRelativePositionEmbedParam.num_output(); p.bias_term = caffeRelativePositionEmbedParam.bias_term() == 0 ? false : true; p.transpose = caffeRelativePositionEmbedParam.transpose() == 0 ? false : true; p.axis = caffeRelativePositionEmbedParam.axis(); curPs.embed_spec = p; return curPs; } ParameterSpec adapt_RelativeShift() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); RelativeShiftParamSpec relativeShiftPs; memset(&relativeShiftPs, 0, sizeof(relativeShiftPs)); auto caffeRelativeShiftParam = layer.relative_shift_param(); relativeShiftPs.axis = caffeRelativeShiftParam.axis(); relativeShiftPs.shift_length = caffeRelativeShiftParam.shift_length(); curPs.relative_shift_spec = relativeShiftPs; return curPs; } ParameterSpec adapt_Concat() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); ConcatParamSpec concatPs; memset(&concatPs, 0, sizeof(concatPs)); auto caffeConcatParam = layer.concat_param(); concatPs.axis = caffeConcatParam.axis(); curPs.concat_spec = concatPs; return curPs; } ParameterSpec adapt_Softmax() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); SoftmaxParamSpec softmaxPs; memset(&softmaxPs, 0, sizeof(softmaxPs)); auto caffeSoftmaxParam = layer.softmax_param(); softmaxPs.axis = caffeSoftmaxParam.axis(); curPs.softmax_spec = softmaxPs; return curPs; } ParameterSpec adapt_PriorBox() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); PriorBoxParamSpec priorboxPs; memset(&priorboxPs, 0, sizeof(priorboxPs)); auto caffePriorBoxParam = layer.prior_box_param(); CHECK_REQUIREMENT( caffePriorBoxParam.min_size_size() <= 2 && caffePriorBoxParam.max_size_size() <= 2); for (int i = 0; i < 2; i++) { priorboxPs.min_sizes[i] = 0; if (i < caffePriorBoxParam.min_size_size()) { priorboxPs.min_sizes[i] = caffePriorBoxParam.min_size(i); } } for (int i = 0; i < 2; i++) { priorboxPs.max_sizes[i] = 0; if (i < caffePriorBoxParam.max_size_size()) { priorboxPs.max_sizes[i] = caffePriorBoxParam.max_size(i); } } CHECK_REQUIREMENT(caffePriorBoxParam.aspect_ratio_size() <= 2); for (int i = 0; i < 2; i++) { priorboxPs.aspect_ratios[i] = 0; if (i < caffePriorBoxParam.aspect_ratio_size()) { priorboxPs.aspect_ratios[i] = caffePriorBoxParam.aspect_ratio(i); } } if (caffePriorBoxParam.has_flip()) { if (caffePriorBoxParam.flip()) { priorboxPs.flip = 1; } else { priorboxPs.flip = 0; } } else { priorboxPs.flip = 1; } if (caffePriorBoxParam.has_clip()) { if (caffePriorBoxParam.clip()) { priorboxPs.clip = 1; } else { priorboxPs.clip = 0; } } else { priorboxPs.clip = 0; } if (caffePriorBoxParam.variance_size() == 4) { priorboxPs.variances[0] = caffePriorBoxParam.variance(0); priorboxPs.variances[1] = caffePriorBoxParam.variance(1); priorboxPs.variances[2] = caffePriorBoxParam.variance(2); priorboxPs.variances[3] = caffePriorBoxParam.variance(3); } else if (caffePriorBoxParam.variance_size() == 1) { priorboxPs.variances[0] = caffePriorBoxParam.variance(0); priorboxPs.variances[1] = caffePriorBoxParam.variance(0); priorboxPs.variances[2] = caffePriorBoxParam.variance(0); priorboxPs.variances[3] = caffePriorBoxParam.variance(0); } priorboxPs.image_w = 0; priorboxPs.image_h = 0; if (caffePriorBoxParam.has_img_size()) { priorboxPs.image_w = caffePriorBoxParam.img_size(); priorboxPs.image_h = caffePriorBoxParam.img_size(); } if (caffePriorBoxParam.has_img_w() && caffePriorBoxParam.has_img_h()) { priorboxPs.image_w = caffePriorBoxParam.img_w(); priorboxPs.image_h = caffePriorBoxParam.img_h(); } priorboxPs.step_w = 0; priorboxPs.step_h = 0; if (caffePriorBoxParam.has_step()) { priorboxPs.step_w = caffePriorBoxParam.step(); priorboxPs.step_h = caffePriorBoxParam.step(); } if (caffePriorBoxParam.has_step_w() && caffePriorBoxParam.has_step_h()) { priorboxPs.step_w = caffePriorBoxParam.step_w(); priorboxPs.step_h = caffePriorBoxParam.step_h(); } priorboxPs.offset = caffePriorBoxParam.offset(); curPs.prior_box_spec = priorboxPs; return curPs; } ParameterSpec adapt_DetectionOutput() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); DetectionOutputParamSpec detectionoutputPs; memset(&detectionoutputPs, 0, sizeof(detectionoutputPs)); auto caffeDetectionOutputParam = layer.detection_output_param(); detectionoutputPs.num_class = caffeDetectionOutputParam.num_classes(); CHECK_REQUIREMENT((caffeDetectionOutputParam.background_label_id() == 0) && (caffeDetectionOutputParam.share_location() == true)); detectionoutputPs.nms_threshold = caffeDetectionOutputParam.nms_param().nms_threshold(); detectionoutputPs.nms_top_k = caffeDetectionOutputParam.nms_param().top_k(); detectionoutputPs.keep_top_k = caffeDetectionOutputParam.keep_top_k(); detectionoutputPs.confidence_threshold = caffeDetectionOutputParam.confidence_threshold(); curPs.detection_output_spec = detectionoutputPs; return curPs; } ParameterSpec adapt_Yolov3DetectionOutput() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); Yolov3DetectionOutputParamSpec yolov3detectionoutputPs; memset(&yolov3detectionoutputPs, 0, sizeof(yolov3detectionoutputPs)); auto caffeYolov3DetectionOutputParam = layer.yolov3_detection_output_param(); yolov3detectionoutputPs.num_class = caffeYolov3DetectionOutputParam.num_classes(); yolov3detectionoutputPs.num_box = caffeYolov3DetectionOutputParam.num_box(); yolov3detectionoutputPs.confidence_threshold = caffeYolov3DetectionOutputParam.confidence_threshold(); yolov3detectionoutputPs.nms_threshold = caffeYolov3DetectionOutputParam.nms_threshold(); for (int i = 0; i < 18; i++) { yolov3detectionoutputPs.biases[i] = 0; if (i < caffeYolov3DetectionOutputParam.biases_size()) { yolov3detectionoutputPs.biases[i] = caffeYolov3DetectionOutputParam.biases(i); } } for (int i = 0; i < 3; i++) { yolov3detectionoutputPs.anchors_scale[i] = 0; if (i < caffeYolov3DetectionOutputParam.anchors_scale_size()) { yolov3detectionoutputPs.anchors_scale[i] = caffeYolov3DetectionOutputParam.anchors_scale(i); } } yolov3detectionoutputPs.mask_group_num = caffeYolov3DetectionOutputParam.mask_group_num(); for (int i = 0; i < 9; i++) { yolov3detectionoutputPs.mask[i] = 0; if (i < caffeYolov3DetectionOutputParam.mask_size()) { yolov3detectionoutputPs.mask[i] = caffeYolov3DetectionOutputParam.mask(i); } } curPs.yolov3_detection_output_spec = yolov3detectionoutputPs; return curPs; } ParameterSpec adapt_Clip() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); ClipParamSpec clipParam; memset(&clipParam, 0, sizeof(clipParam)); auto caffeClipParam = layer.clip_param(); clipParam.min = caffeClipParam.min(); clipParam.max = caffeClipParam.max(); curPs.clip_spec = clipParam; return curPs; } ParameterSpec adapt_Relu() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); ReLUParamSpec reluSpec; memset(&reluSpec, 0, sizeof(reluSpec)); reluSpec.neg_slope = layer.relu_param().negative_slope(); curPs.relu_spec = reluSpec; return curPs; } ParameterSpec adapt_PRelu() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); weightNumber = weightNumber + 1; return curPs; } ParameterSpec adapt_Exp() override { ParameterSpec curPs; memset(&curPs, 0, sizeof(curPs)); auto caffeExpParam = layer.exp_param(); if (caffeExpParam.base() != -1 || caffeExpParam.scale() != 1 || caffeExpParam.shift() != 0) { UNI_ERROR_LOG("can not process operator name:%s base!=-1(e), scale!=1, shift!=0.\n", this->layer.name().c_str()); } return curPs; } private: std::string op; caffe::NetParameter proto; caffe::NetParameter net; caffe::LayerParameter layer; int weightNumber; }; #endif
29,510
450
<reponame>Khaos116/PowerTunnel-Android package ru.krlvm.powertunnel.android.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.VpnService; import android.os.Build; import android.preference.PreferenceManager; import android.util.Log; import ru.krlvm.powertunnel.android.managers.PTManager; import ru.krlvm.powertunnel.android.services.ProxyModeService; import tun.proxy.service.Tun2HttpVpnService; public class BootReceiver extends BroadcastReceiver { public static final String PREF_RUNNING = "pref_running"; private static final String LOG_TAG = "PowerTunnel.Boot"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action == null) return; if (!action.equals(Intent.ACTION_BOOT_COMPLETED) && !action.equals(Intent.ACTION_REBOOT) && !action.equals("android.intent.action.QUICKBOOT_POWERON")) { return; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean isRunning = prefs.getBoolean(PREF_RUNNING, false); if (!isRunning) { Log.i(LOG_TAG, "We don't have to start the app on boot"); return; } if (PTManager.isVPN(prefs)) { Intent prepare = VpnService.prepare(context); Log.i(LOG_TAG, "Starting VPN..."); if (prepare == null) { Tun2HttpVpnService.start(context); } else { Log.e(LOG_TAG, "VPN is not prepared"); } } else { Log.i(LOG_TAG, "Starting proxy mode service..."); Intent proxy = new Intent(context, ProxyModeService.class); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(proxy); } else { context.startService(proxy); } } } }
851
1,240
<reponame>raghavpartani/open-event-organizer-android package com.eventyay.organizer.utils; import com.eventyay.organizer.data.event.Event; import com.eventyay.organizer.utils.service.DateService; import org.junit.Test; import org.threeten.bp.LocalDateTime; import java.text.ParseException; import timber.log.Timber; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class DateServiceTest { private static final Event LIVE = new Event(); private static final Event PAST = new Event(); private static final Event UPCOMING = new Event(); static { String max = DateUtils.formatDateToIso(LocalDateTime.MAX); String min = DateUtils.formatDateToIso(LocalDateTime.MIN); LIVE.setStartsAt(min); LIVE.setEndsAt(max); PAST.setStartsAt(min); PAST.setEndsAt(min); UPCOMING.setStartsAt(max); UPCOMING.setEndsAt(max); } private static void testStatus(Event event, String expected) { try { assertEquals(expected, DateService.getEventStatus(event)); } catch (ParseException e) { Timber.e(e); fail("Parse error should not have occurred"); } } @Test public void shouldReturnLiveStatus() { testStatus(LIVE, DateService.LIVE_EVENT); } @Test public void shouldReturnPastStatus() { testStatus(PAST, DateService.PAST_EVENT); } @Test public void shouldReturnUpcomingStatus() { testStatus(UPCOMING, DateService.UPCOMING_EVENT); } @Test public void testNaturalOrderLive() { // Live should appear on top of upcoming and past assertEquals(1, DateService.compareEventDates(LIVE, LIVE)); assertEquals(-1, DateService.compareEventDates(LIVE, PAST)); assertEquals(-1, DateService.compareEventDates(LIVE, UPCOMING)); } @Test public void testNaturalOrderPast() { // Past should always appear in bottom assertEquals(1, DateService.compareEventDates(PAST, LIVE)); assertEquals(1, DateService.compareEventDates(PAST, PAST)); assertEquals(1, DateService.compareEventDates(PAST, UPCOMING)); } @Test public void testNaturalOrderUpcoming() { // Upcoming should appear on top of past assertEquals(1, DateService.compareEventDates(UPCOMING, LIVE)); assertEquals(-1, DateService.compareEventDates(UPCOMING, PAST)); assertEquals(1, DateService.compareEventDates(UPCOMING, UPCOMING)); } @Test public void testClashLive() { Event liveLatest = new Event(); String nowMinus5 = DateUtils.formatDateToIso(LocalDateTime.now().minusDays(5)); String nowPlus5 = DateUtils.formatDateToIso(LocalDateTime.now().plusDays(5)); liveLatest.setStartsAt(nowMinus5); liveLatest.setEndsAt(nowPlus5); assertEquals(1, DateService.compareEventDates(LIVE, liveLatest)); } @Test public void testClashPast() { Event pastLatest = new Event(); String min = DateUtils.formatDateToIso(LocalDateTime.MIN); String minPlus5 = DateUtils.formatDateToIso(LocalDateTime.MIN.plusDays(5)); pastLatest.setStartsAt(min); pastLatest.setEndsAt(minPlus5); assertEquals(1, DateService.compareEventDates(PAST, pastLatest)); } @Test public void testClashUpcoming() { Event upcomingEarliest = new Event(); String max = DateUtils.formatDateToIso(LocalDateTime.MAX); String maxMinus5 = DateUtils.formatDateToIso(LocalDateTime.MAX.minusDays(5)); upcomingEarliest.setStartsAt(maxMinus5); upcomingEarliest.setEndsAt(max); assertEquals(1, DateService.compareEventDates(UPCOMING, upcomingEarliest)); } }
1,547
303
package com.yuyh.bankcardformat; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.TextView; import com.example.library.BandCardEditText; import com.example.library.BankCardListener; public class MainActivity extends AppCompatActivity { BandCardEditText editText; TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); editText = (BandCardEditText) findViewById(R.id.et); editText.setBankCardListener(new BankCardListener() { @Override public void success(String name) { tv.setText("所属银行:" + name); } @Override public void failure() { Log.i("TAG", "failure"); tv.setText("所属银行:"); } }); } }
449
1,853
<gh_stars>1000+ /* * Copyright 2017-2021 Dromara.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dromara.hmily.metrics.spi; /** * Metrics register. */ public interface MetricsRegister { /** * Register gauge. * * @param name name * @param labelNames label names * @param document document for gauge */ void registerGauge(String name, String[] labelNames, String document); /** * Register counter. * * @param name name * @param labelNames label names * @param document document for counter */ void registerCounter(String name, String[] labelNames, String document); /** * Register histogram. * * @param name name * @param labelNames label names * @param document document for histogram */ void registerHistogram(String name, String[] labelNames, String document); /** * Counter increment by count. * * @param name name * @param labelValues label values * @param count count */ void counterIncrement(String name, String[] labelValues, long count); /** * Gauge increment. * * @param name name * @param labelValues label values */ void gaugeIncrement(String name, String[] labelValues); /** * Gauge decrement. * * @param name name * @param labelValues label values */ void gaugeDecrement(String name, String[] labelValues); /** * Record time by duration. * * @param name name * @param labelValues label values * @param duration duration */ void recordTime(String name, String[] labelValues, long duration); }
774
539
<reponame>hoskillua/geometry-central #pragma once // The MeshIO class provides a variety of methods for mesh input/output. #include "geometrycentral/surface/manifold_surface_mesh.h" #include "geometrycentral/surface/vertex_position_geometry.h" #include <fstream> #include <string> namespace geometrycentral { namespace surface { // Loads a halfedge mesh and its geometry from file. // Specify a type like "ply" or "obj", if no type is specified, attempts to infer from extension. // Load a general surface mesh, which might or might not be manifold std::tuple<std::unique_ptr<SurfaceMesh>, std::unique_ptr<VertexPositionGeometry>> readSurfaceMesh(std::string filename, std::string type = ""); std::tuple<std::unique_ptr<SurfaceMesh>, std::unique_ptr<VertexPositionGeometry>> readSurfaceMesh(std::istream& in, std::string type); // Load a manifold surface mesh; an exception will by thrown if the mesh is not manifold. std::tuple<std::unique_ptr<ManifoldSurfaceMesh>, std::unique_ptr<VertexPositionGeometry>> readManifoldSurfaceMesh(std::string filename, std::string type = ""); std::tuple<std::unique_ptr<ManifoldSurfaceMesh>, std::unique_ptr<VertexPositionGeometry>> readManifoldSurfaceMesh(std::istream& in, std::string type); // Load a mesh with UV coordinates, which will be stored as data at triangle // corners (to allow for UVs that are discontinuous across edges, e.g., at cuts) std::tuple<std::unique_ptr<ManifoldSurfaceMesh>, std::unique_ptr<VertexPositionGeometry>, std::unique_ptr<CornerData<Vector2>>> readParameterizedManifoldSurfaceMesh(std::string filename, std::string type = ""); std::tuple<std::unique_ptr<SurfaceMesh>, std::unique_ptr<VertexPositionGeometry>, std::unique_ptr<CornerData<Vector2>>> readParameterizedSurfaceMesh(std::string filename, std::string type = ""); // Legacy method, prefer one of the variants above std::tuple<std::unique_ptr<ManifoldSurfaceMesh>, std::unique_ptr<VertexPositionGeometry>> loadMesh(std::string filename, std::string type = ""); // Write a surface mesh void writeSurfaceMesh(SurfaceMesh& mesh, EmbeddedGeometryInterface& geometry, std::string filename, std::string type = ""); void writeSurfaceMesh(SurfaceMesh& mesh, EmbeddedGeometryInterface& geometry, CornerData<Vector2>& texCoords, std::string filename, std::string type = ""); void writeSurfaceMesh(SurfaceMesh& mesh, EmbeddedGeometryInterface& geometry, std::ostream& out, std::string type); void writeSurfaceMesh(SurfaceMesh& mesh, EmbeddedGeometryInterface& geometry, CornerData<Vector2>& texCoords, std::ostream& out, std::string type); // Helpers to map vertex data CornerData<Vector2> packToParam(SurfaceMesh& mesh, VertexData<double>& vals); // 0 in Y coord CornerData<Vector2> packToParam(SurfaceMesh& mesh, VertexData<double>& valsX, VertexData<double>& valsY); // Legacy writer, prefer on of the variants above class WavefrontOBJ { public: static bool write(std::string filename, EmbeddedGeometryInterface& geometry); static bool write(std::string filename, EmbeddedGeometryInterface& geometry, CornerData<Vector2>& texcoords); static bool write(std::string filename, EmbeddedGeometryInterface& geometry, CornerData<Vector3>& normals); static bool write(std::string filename, EmbeddedGeometryInterface& geometry, CornerData<Vector2>& texcoords, CornerData<Vector3>& normals); protected: static bool openStream(std::ofstream& out, std::string filename); static void writeHeader(std::ofstream& out, EmbeddedGeometryInterface& geometry); static void writeVertices(std::ofstream& out, EmbeddedGeometryInterface& geometry); static void writeTexCoords(std::ofstream& out, EmbeddedGeometryInterface& geometry, CornerData<Vector2>& texcoords); static void writeNormals(std::ofstream& out, EmbeddedGeometryInterface& geometry, CornerData<Vector3>& normals); static void writeFaces(std::ofstream& out, EmbeddedGeometryInterface& geometry, bool useTexCoords = false, bool useNormals = false); }; // TODO write halfedge mesh as a permutation, in binary format (for quicker loading/smaller files) // === Integrations with other libraries and formats // Generate the permutations which map geometry-central's indexing order to the Polyscope indexing order std::array<std::pair<std::vector<size_t>, size_t>, 5> polyscopePermutations(SurfaceMesh& mesh); // Generate booleans to communicate the canonical orientations of edges for 1form-valued data EdgeData<char> polyscopeEdgeOrientations(SurfaceMesh& mesh); } // namespace surface } // namespace geometrycentral
1,536
72,551
<filename>test/Interop/Cxx/implementation-only-imports/Inputs/user-b.h #ifndef TEST_INTEROP_CXX_IMPLEMENTATION_ONLY_IMPORTS_INPUTS_USER_B_H #define TEST_INTEROP_CXX_IMPLEMENTATION_ONLY_IMPORTS_INPUTS_USER_B_H #include "helper.h" #endif // TEST_INTEROP_CXX_IMPLEMENTATION_ONLY_IMPORTS_INPUTS_USER_B_H
138
3,066
/* * Licensed to Crate.io GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package org.elasticsearch.index.translog; import io.crate.integrationtests.SQLIntegrationTestCase; import org.elasticsearch.test.ESIntegTestCase; import static org.hamcrest.Matchers.is; @ESIntegTestCase.ClusterScope(numDataNodes = 2) public class TranslogHistoryTest extends SQLIntegrationTestCase { public void test_translog_is_trimmed_with_soft_deletes_enabled() throws Exception { execute("create table doc.test(x int) clustered into 1 shards with(number_of_replicas=1, \"soft_deletes.enabled\"='true')"); ensureGreen(); int numDocs = randomIntBetween(1, 10); for(int i = 0; i < numDocs; i++) { execute("insert into doc.test(x) values(?)", new Object[]{i}); } execute("refresh table doc.test"); execute("optimize table doc.test"); ensureGreen(); assertBusy(() -> { execute("select translog_stats['number_of_operations'] from sys.shards where table_name='test' and primary=true"); assertThat(response.rows()[0][0], is(0)); }); assertBusy(() -> { execute("select translog_stats['number_of_operations'] from sys.shards where table_name='test' and primary=false"); assertThat(response.rows()[0][0], is(0)); }); } }
747
190,993
<reponame>ashutom/tensorflow-upstream /* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/gpu/horizontal_input_fusion.h" #include <algorithm> #include "absl/container/flat_hash_set.h" #include "absl/strings/str_cat.h" #include "absl/types/span.h" #include "tensorflow/compiler/xla/layout_util.h" #include "tensorflow/compiler/xla/service/gpu/gpu_fusible.h" #include "tensorflow/compiler/xla/service/gpu/ir_emission_utils.h" #include "tensorflow/compiler/xla/service/hlo_creation_utils.h" #include "tensorflow/core/platform/errors.h" namespace xla { namespace gpu { namespace { // Gets the representative input shape of the multi-output fusion. Shape GetInputShapeForMultiOutputFusion(const HloInstruction& instr) { // Get the HLO that determines the emitter used for lowering. const HloInstruction* real_hero = GetRealHeroForMultiOutputFusion(instr); if (real_hero->operands().empty()) { // Simply return an empty shape if the representative node has no input // operands. return Shape(); } else { return real_hero->operand(0)->shape(); } } class HorizontalInputFusionImpl { public: explicit HorizontalInputFusionImpl(HloComputation* computation) : computation_(computation) {} ~HorizontalInputFusionImpl() {} StatusOr<bool> Run(); private: HloComputation* computation_; }; // HorizontalInputFusionImpl // Compares one-by-one the dimensions of `shape_a` and `shape_b` from left to // right. bool CompareShapeDimsFromLeftToRight(const Shape& shape_a, const Shape& shape_b) { if (shape_a.rank() != shape_b.rank()) { return shape_a.rank() < shape_b.rank(); } auto dims_a = shape_a.dimensions(); auto dims_b = shape_b.dimensions(); for (size_t i = 0; i < dims_a.size(); ++i) { if (dims_a[i] != dims_b[i]) { return dims_a[i] < dims_b[i]; } } return true; } std::vector<HloInstruction*> FindAndSortFusionCandidates( HloInstruction* consumer) { absl::flat_hash_set<HloInstruction*> fusion_instr_set; std::vector<HloInstruction*> fusion_instrs; for (HloInstruction* opnd : consumer->operands()) { HloInstruction* predecessor = opnd->LatestNonGteAncestor(); // Find out the input fusion instructions whose only consumer is `consumer`. // This guarantees that fusing these candidates will never create cycles, as // there is no back edge. if (IsInputFusibleReduction(*predecessor) && IsConsumerTheOnlyNonRootUser(*predecessor, *consumer)) { if (fusion_instr_set.insert(predecessor).second) { fusion_instrs.push_back(predecessor); } } } std::sort(fusion_instrs.begin(), fusion_instrs.end(), [&](const HloInstruction* a, const HloInstruction* b) { Shape shape_a = GetInputShapeForMultiOutputFusion(*a); Shape shape_b = GetInputShapeForMultiOutputFusion(*b); if (!ShapeUtil::EqualIgnoringElementType(shape_a, shape_b)) { // Sort shapes according to dimensions, so that the same input // shapes will be placed adjacent each other. return CompareShapeDimsFromLeftToRight(shape_a, shape_b); } // Sort `fusion_instrs` according to instruction counts, because // we'd like to fuse together computations of similar sizes. return GetInstrCountOfFusible(*a) < GetInstrCountOfFusible(*b); }); return fusion_instrs; } StatusOr<bool> HorizontalInputFusionImpl::Run() { bool changed = false; XLA_VLOG_LINES(3, computation_->ToString()); // Using def-to-use order is sound since we do not modify users. std::vector<HloInstruction*> def_to_use_order = computation_->MakeInstructionPostOrder(); for (HloInstruction* consumer : def_to_use_order) { auto candidates = FindAndSortFusionCandidates(consumer); if (candidates.size() <= 1) { continue; } // Convert candidates into fusions if needed. for (size_t j = 0; j < candidates.size(); ++j) { if (candidates[j]->opcode() != HloOpcode::kFusion) { TF_ASSIGN_OR_RETURN( HloInstruction * fusion_instr, MakeFusionInstruction(candidates[j], HloInstruction::FusionKind::kInput)); candidates[j] = fusion_instr; changed = true; } } size_t fusion_anchor_id = 0; for (size_t j = 1; j < candidates.size(); ++j) { HloInstruction* fusion_anchor = candidates[fusion_anchor_id]; HloInstruction* fused = candidates[j]; if (ShapesCompatibleForMultiOutputFusion(*fusion_anchor, *fused) && !FusionWouldBeTooLarge(*fusion_anchor, *fused)) { VLOG(3) << "Fuse " << fused->ToString() << " into " << fusion_anchor->ToString(); fusion_anchor->MergeFusionInstructionIntoMultiOutput(fused); changed = true; } else { // Update the `fusion_anchor_id` since `fused` is either not // compatible or not beneficial to be fused with current fusion anchor. VLOG(3) << j - fusion_anchor_id - 1 << " instructions are fused."; fusion_anchor_id = j; } } } return changed; } } // namespace StatusOr<bool> GpuHorizontalInputFusion::RunOnComputation( HloComputation* computation) { HorizontalInputFusionImpl horizontal_fusion_impl(computation); return horizontal_fusion_impl.Run(); } StatusOr<bool> GpuHorizontalInputFusion::Run(HloModule* module) { bool changed = false; VLOG(2) << "Run horizontal input fusion."; for (HloComputation* comp : module->MakeNonfusionComputations()) { TF_ASSIGN_OR_RETURN(changed, RunOnComputation(comp)); } return changed; } } // namespace gpu } // namespace xla
2,431
1,875
<filename>core/src/main/java/org/teavm/parsing/CompositeClassHolderSource.java /* * Copyright 2017 <NAME>. * * 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.teavm.parsing; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.teavm.model.ClassHolder; import org.teavm.model.ClassHolderSource; public class CompositeClassHolderSource implements ClassHolderSource { private List<ClassHolderSource> innerSources; private Map<String, ClassHolder> cache = new HashMap<>(); public CompositeClassHolderSource(List<ClassHolderSource> innerSources) { this.innerSources = new ArrayList<>(innerSources); } @Override public ClassHolder get(String name) { return cache.computeIfAbsent(name, n -> { for (ClassHolderSource innerSource : innerSources) { ClassHolder cls = innerSource.get(n); if (cls != null) { return cls; } } return null; }); } }
575
439
<reponame>odidev/pyaes # The MIT License (MIT) # # Copyright (c) 2014 <NAME> # # 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 sys sys.path.append('../pyaes') import os import random try: from StringIO import StringIO except: import io StringIO = io.BytesIO import pyaes from pyaes.blockfeeder import Decrypter, Encrypter from pyaes import decrypt_stream, encrypt_stream from pyaes.util import to_bufferable key = os.urandom(32) plaintext = os.urandom(1000) for mode_name in pyaes.AESModesOfOperation: mode = pyaes.AESModesOfOperation[mode_name] print(mode.name) kw = dict(key = key) if mode_name in ('cbc', 'cfb', 'ofb'): kw['iv'] = os.urandom(16) encrypter = Encrypter(mode(**kw)) ciphertext = to_bufferable('') # Feed the encrypter random number of bytes at a time index = 0 while index < len(plaintext): length = random.randint(1, 128) if index + length > len(plaintext): length = len(plaintext) - index ciphertext += encrypter.feed(plaintext[index: index + length]) index += length ciphertext += encrypter.feed(None) decrypter = Decrypter(mode(**kw)) decrypted = to_bufferable('') # Feed the decrypter random number of bytes at a time index = 0 while index < len(ciphertext): length = random.randint(1, 128) if index + length > len(ciphertext): length = len(ciphertext) - index decrypted += decrypter.feed(ciphertext[index: index + length]) index += length decrypted += decrypter.feed(None) passed = decrypted == plaintext cipher_length = len(ciphertext) print(" cipher-length=%(cipher_length)s passed=%(passed)s" % locals()) # Test block modes of operation with no padding plaintext = os.urandom(1024) for mode_name in ['ecb', 'cbc']: mode = pyaes.AESModesOfOperation[mode_name] print(mode.name + ' (no padding)') kw = dict(key = key) if mode_name == 'cbc': kw['iv'] = os.urandom(16) encrypter = Encrypter(mode(**kw), padding = pyaes.PADDING_NONE) ciphertext = to_bufferable('') # Feed the encrypter random number of bytes at a time index = 0 while index < len(plaintext): length = random.randint(1, 128) if index + length > len(plaintext): length = len(plaintext) - index ciphertext += encrypter.feed(plaintext[index: index + length]) index += length ciphertext += encrypter.feed(None) if len(ciphertext) != len(plaintext): print(' failed to encrypt with correct padding') decrypter = Decrypter(mode(**kw), padding = pyaes.PADDING_NONE) decrypted = to_bufferable('') # Feed the decrypter random number of bytes at a time index = 0 while index < len(ciphertext): length = random.randint(1, 128) if index + length > len(ciphertext): length = len(ciphertext) - index decrypted += decrypter.feed(ciphertext[index: index + length]) index += length decrypted += decrypter.feed(None) passed = decrypted == plaintext cipher_length = len(ciphertext) print(" cipher-length=%(cipher_length)s passed=%(passed)s" % locals()) plaintext = os.urandom(1000) for mode_name in pyaes.AESModesOfOperation: mode = pyaes.AESModesOfOperation[mode_name] print(mode.name + ' (stream operations)') kw = dict(key = key) if mode_name in ('cbc', 'cfb', 'ofb'): kw['iv'] = os.urandom(16) moo = mode(**kw) output = StringIO() pyaes.encrypt_stream(moo, StringIO(plaintext), output) output.seek(0) ciphertext = output.read() moo = mode(**kw) output = StringIO() pyaes.decrypt_stream(moo, StringIO(ciphertext), output) output.seek(0) decrypted = output.read() passed = decrypted == plaintext cipher_length = len(ciphertext) print(" cipher-length=%(cipher_length)s passed=%(passed)s" % locals()) # Issue #15 # https://github.com/ricmoo/pyaes/issues/15 # @TODO: These tests need a severe overhaul; they should use deterministic input, keys and IVs... def TestIssue15(): print('Issue #15') key = b"<KEY>" iv = b"0123456789012345" encrypter = pyaes.Encrypter(pyaes.AESModeOfOperationCBC(key, iv)) plaintext = b"Hello World!!!!!" ciphertext = to_bufferable('') ciphertext += encrypter.feed(plaintext) ciphertext += encrypter.feed('') ciphertext += encrypter.feed(plaintext) ciphertext += encrypter.feed(None) expected = b'(Ob\xe5\xae"\xdc\xb0\x84\xc5\x04\x04GQ\xd8.\x0e4\xd2b\xc1\x15\xe5\x11M\xfc\x9a\xd2\xd5\xc8xP\x00[\xd57\x92\x01\xbb\xc42\x18\xbc\xbf\x1ay\x19P' decrypter = pyaes.Decrypter(pyaes.AESModeOfOperationCBC(key, iv)) output = to_bufferable('') output += decrypter.feed('') output += decrypter.feed(ciphertext) output += decrypter.feed('') output += decrypter.feed(None) print(" passed=%(passed)s" % dict(passed = (ciphertext == expected and output == (plaintext + plaintext)))) TestIssue15()
2,292
5,514
package com.u9porn.parser; import android.text.TextUtils; import com.orhanobut.logger.Logger; import com.u9porn.data.model.BaseResult; import com.u9porn.data.model.MeiZiTu; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.ArrayList; import java.util.List; /** * @author flymegoc * @date 2018/1/25 */ public class ParseMeiZiTu { private static final String TAG = ParseMeiZiTu.class.getSimpleName(); public static BaseResult<List<MeiZiTu>> parseMeiZiTuList(String html, int page) { BaseResult<List<MeiZiTu>> baseResult = new BaseResult<>(); baseResult.setTotalPage(1); Document doc = Jsoup.parse(html); Element ulPins = doc.getElementById("pins"); Elements lis = ulPins.select("li"); List<MeiZiTu> meiZiTuList = new ArrayList<>(); for (Element li : lis) { Element contentElement = li.select("a").first(); if (contentElement == null) { continue; } MeiZiTu meiZiTu = new MeiZiTu(); String contentUrl = contentElement.attr("href"); //meiZiTu.setContentUrl(contentUrl); int index = contentUrl.lastIndexOf("/"); if (index >= 0 && index + 1 < contentUrl.length()) { String idStr = contentUrl.substring(index + 1, contentUrl.length()); Logger.t(TAG).d(idStr); if (!TextUtils.isEmpty(idStr) && TextUtils.isDigitsOnly(idStr)) { meiZiTu.setId(Integer.parseInt(idStr)); } } Element imageElement = li.selectFirst("img"); String name = imageElement.attr("alt"); meiZiTu.setName(name); String thumbUrl = imageElement.attr("data-original"); meiZiTu.setThumbUrl(thumbUrl); Logger.t(TAG).d(thumbUrl); int height = Integer.parseInt(imageElement.attr("height")); meiZiTu.setHeight(height); int width = Integer.parseInt(imageElement.attr("width")); meiZiTu.setWidth(width); String date = li.getElementsByClass("time").first().text(); meiZiTu.setDate(date); // String viewCount = li.getElementsByClass("view").first().text(); // meiZiTu.setViewCount(viewCount); meiZiTuList.add(meiZiTu); } Logger.t(TAG).d("size::" + meiZiTuList.size()); if (page == 1) { Elements pageElements = doc.getElementsByClass("page-numbers"); if (pageElements != null && pageElements.size() > 3) { String pageStr = pageElements.get(pageElements.size() - 2).text(); Logger.t(TAG).d("totalPage::" + pageStr); if (!TextUtils.isEmpty(pageStr) && TextUtils.isDigitsOnly(pageStr)) { baseResult.setTotalPage(Integer.parseInt(pageStr)); } } } baseResult.setData(meiZiTuList); return baseResult; } public static BaseResult<List<String>> parsePicturePage(String html) { BaseResult<List<String>> baseResult = new BaseResult<>(); Document doc = Jsoup.parse(html); Element pageElement = doc.getElementsByClass("pagenavi").first(); Elements aElements = pageElement.select("a"); int totalPage = 1; if (aElements != null && aElements.size() > 3) { String pageStr = aElements.get(aElements.size() - 2).text(); if (!TextUtils.isEmpty(pageStr) && TextUtils.isDigitsOnly(pageStr)) { totalPage = Integer.parseInt(pageStr); } } List<String> imageUrlList = new ArrayList<>(); String imageUrl = doc.getElementsByClass("main-image").first().selectFirst("img").attr("src"); if (totalPage == 1) { imageUrlList.add(imageUrl); } for (int i = 1; i < totalPage + 1; i++) { String tmp; if (i < 10) { tmp = imageUrl.replace("01.", "0" + i + "."); } else { tmp = imageUrl.replace("01.", "" + i + "."); } imageUrlList.add(tmp); } baseResult.setData(imageUrlList); return baseResult; } }
2,067
32,544
<filename>spring-cloud/spring-cloud-aws/src/test/java/com/baeldung/spring/cloud/aws/SpringContextLiveTest.java package com.baeldung.spring.cloud.aws; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * * To run this Live Test, we need to have an AWS account and have API keys generated for programmatic access. * * Check the README file in this module for more information. * */ @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringCloudAwsApplication.class) public class SpringContextLiveTest { @Test public void whenSpringContextIsBootstrapped_thenNoExceptions() { } }
230
32,544
<reponame>DBatOWL/tutorials<filename>java-native/src/test/java/com/baeldung/jvmbitversion/JVMBitVersionUnitTest.java<gh_stars>1000+ package com.baeldung.jvmbitversion; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.Before; import org.junit.Test; import com.sun.jna.Platform; public class JVMBitVersionUnitTest { private JVMBitVersion jvmVersion; @Before public void setup() { jvmVersion = new JVMBitVersion(); } @Test public void whenUsingSystemClass_thenOutputIsAsExpected() { if ("64".equals(System.getProperty("sun.arch.data.model"))) { assertEquals("64-bit", jvmVersion.getUsingSystemClass()); } else if ("32".equals(System.getProperty("sun.arch.data.model"))) { assertEquals("32-bit", jvmVersion.getUsingSystemClass()); } } @Test public void whenUsingNativeClass_thenResultIsAsExpected() { if (com.sun.jna.Native.POINTER_SIZE == 8) { assertEquals("64-bit", jvmVersion.getUsingNativeClass()); } else if (com.sun.jna.Native.POINTER_SIZE == 4) { assertEquals("32-bit", jvmVersion.getUsingNativeClass()); } } @Test public void whenUsingPlatformClass_thenResultIsAsExpected() { if (Platform.is64Bit() == Boolean.TRUE) { assertEquals(Boolean.TRUE, jvmVersion.getUsingPlatformClass()); } else if (com.sun.jna.Native.POINTER_SIZE == 4) { assertEquals(Boolean.FALSE, jvmVersion.getUsingPlatformClass()); } } }
660
1,379
<reponame>jerryuhoo/PaddleSpeech # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import traceback from typing import Union from fastapi import APIRouter from paddlespeech.cli.log import logger from paddlespeech.server.engine.engine_pool import get_engine_pool from paddlespeech.server.engine.text.python.text_engine import PaddleTextConnectionHandler from paddlespeech.server.restful.request import TextRequest from paddlespeech.server.restful.response import ErrorResponse from paddlespeech.server.restful.response import TextResponse from paddlespeech.server.utils.errors import ErrorCode from paddlespeech.server.utils.errors import failed_response from paddlespeech.server.utils.exception import ServerBaseException router = APIRouter() @router.get('/paddlespeech/text/help') def help(): """help Returns: json: The /paddlespeech/text api response content """ response = { "success": "True", "code": 200, "message": { "global": "success" }, "result": { "punc_text": "The punctuation text content" } } return response @router.post( "/paddlespeech/text", response_model=Union[TextResponse, ErrorResponse]) def asr(request_body: TextRequest): """asr api Args: request_body (TextRequest): the punctuation request body Returns: json: the punctuation response body """ try: # 1. we get the sentence content from the request text = request_body.text logger.info(f"Text service receive the {text}") # 2. get single engine from engine pool # and each request has its own connection to process the text engine_pool = get_engine_pool() text_engine = engine_pool['text'] connection_handler = PaddleTextConnectionHandler(text_engine) punc_text = connection_handler.run(text) logger.info(f"Get the Text Connection result {punc_text}") # 3. create the response if punc_text is None: punc_text = text response = { "success": True, "code": 200, "message": { "description": "success" }, "result": { "punc_text": punc_text } } logger.info(f"The Text Service final response: {response}") except ServerBaseException as e: response = failed_response(e.error_code, e.msg) except BaseException: response = failed_response(ErrorCode.SERVER_UNKOWN_ERR) traceback.print_exc() return response
1,182
435
<gh_stars>100-1000 { "copyright_text": null, "description": "", "duration": 1425, "language": "eng", "recorded": "2018-10-04", "related_urls": [ { "label": "Conference website", "url": "https://pycon.ee/" } ], "speakers": [ "<NAME>" ], "tags": [], "thumbnail_url": "https://i.ytimg.com/vi/4UMW4UJwu3Y/maxresdefault.jpg", "title": "Predicting prescription drug marketing campaigns based on demographic, weather and", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=4UMW4UJwu3Y" } ] }
254
5,813
/* * 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.druid.tests.indexer; import com.google.inject.Inject; import org.apache.commons.io.IOUtils; import org.apache.druid.java.util.common.ISE; import org.apache.druid.java.util.common.StringUtils; import org.apache.druid.java.util.common.logger.Logger; import org.apache.druid.testing.IntegrationTestingConfig; import org.apache.druid.testing.clients.ClientInfoResourceTestClient; import org.apache.druid.testing.clients.CoordinatorResourceTestClient; import org.apache.druid.testing.guice.DruidTestModuleFactory; import org.apache.druid.testing.utils.ITRetryUtil; import org.apache.druid.testing.utils.TestQueryHelper; import org.apache.druid.tests.TestNGGroup; import org.testng.annotations.BeforeSuite; import org.testng.annotations.Guice; import org.testng.annotations.Test; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; @Test(groups = TestNGGroup.QUERY) @Guice(moduleFactory = DruidTestModuleFactory.class) public class ITNestedQueryPushDownTest extends AbstractIndexerTest { private static final String WIKITICKER_DATA_SOURCE = "wikiticker"; private static final String WIKITICKER_INDEX_TASK = "/indexer/wikiticker_index_task.json"; private static final String WIKITICKER_QUERIES_RESOURCE = "/queries/nestedquerypushdown_queries.json"; @Inject private CoordinatorResourceTestClient coordinatorClient; @Inject private TestQueryHelper queryHelper; private static final Logger LOG = new Logger(ITNestedQueryPushDownTest.class); @Inject private IntegrationTestingConfig config; @Inject ClientInfoResourceTestClient clientInfoResourceTestClient; private String fullDatasourceName; @BeforeSuite public void setFullDatasourceName() { fullDatasourceName = WIKITICKER_DATA_SOURCE + config.getExtraDatasourceNameSuffix(); } @Test public void testIndexData() { try { loadData(); String queryResponseTemplate; try { InputStream is = AbstractITBatchIndexTest.class.getResourceAsStream(WIKITICKER_QUERIES_RESOURCE); queryResponseTemplate = IOUtils.toString(is, StandardCharsets.UTF_8); } catch (IOException e) { throw new ISE(e, "could not read query file: %s", WIKITICKER_QUERIES_RESOURCE); } queryResponseTemplate = StringUtils.replace( queryResponseTemplate, "%%DATASOURCE%%", fullDatasourceName ); queryHelper.testQueriesFromString(queryResponseTemplate); } catch (Exception e) { LOG.error(e, "Error while testing"); throw new RuntimeException(e); } } private void loadData() throws Exception { String taskSpec = getResourceAsString(WIKITICKER_INDEX_TASK); taskSpec = StringUtils.replace(taskSpec, "%%DATASOURCE%%", fullDatasourceName); final String taskID = indexer.submitTask(taskSpec); LOG.info("TaskID for loading index task %s", taskID); indexer.waitUntilTaskCompletes(taskID); ITRetryUtil.retryUntilTrue( () -> coordinator.areSegmentsLoaded(fullDatasourceName), "Segment Load" ); } }
1,296
852
#ifndef CSCWireDigi_CSCWireDigiCollection_h #define CSCWireDigi_CSCWireDigiCollection_h /** \class CSCWireDigiCollection * * Based on DTDigiCollection.h * \author <NAME> - CMU * */ #include "DataFormats/MuonDetId/interface/CSCDetId.h" #include "DataFormats/CSCDigi/interface/CSCWireDigi.h" #include "DataFormats/MuonData/interface/MuonDigiCollection.h" typedef MuonDigiCollection<CSCDetId, CSCWireDigi> CSCWireDigiCollection; #endif
176
2,151
<filename>third_party/blink/renderer/platform/text/capitalize_test.cc // Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/platform/text/capitalize.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/text/character.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { struct CapitalizeTestData { String input; String expected; UChar previous_character = kSpaceCharacter; }; class CapitalizeTest : public testing::Test, public testing::WithParamInterface<CapitalizeTestData> { }; INSTANTIATE_TEST_CASE_P(CapitalizeTest, CapitalizeTest, testing::Values(CapitalizeTestData{String(), String()}, CapitalizeTestData{"", ""}, CapitalizeTestData{"hello, world", "Hello, World"})); TEST_P(CapitalizeTest, Data) { const auto& data = GetParam(); EXPECT_EQ(data.expected, Capitalize(data.input, data.previous_character)); } } // namespace blink
553
2,151
<reponame>ceremetrix/X # Copyright 2008-2009 WebDriver committers # Copyright 2008-2009 Google 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. """Exceptions that may happen in all the webdriver code.""" class WebDriverException(Exception): def __init__(self, msg=None, screen=None, stacktrace=None): self.msg = msg self.screen = screen self.stacktrace = stacktrace def __str__(self): exception_msg = "Message: %s " % repr(self.msg) if self.screen is not None: exception_msg = "%s; Screenshot: available via screen " \ % exception_msg if self.stacktrace is not None: exception_msg = "%s; Stacktrace: %s " \ % (exception_msg, str(self.stacktrace)) return exception_msg class ErrorInResponseException(WebDriverException): """An error has occurred on the server side. This may happen when communicating with the firefox extension or the remote driver server.""" def __init__(self, response, msg): WebDriverException.__init__(self, msg) self.response = response class InvalidSwitchToTargetException(WebDriverException): """The frame or window target to be switched doesn't exist.""" pass class NoSuchFrameException(InvalidSwitchToTargetException): pass class NoSuchWindowException(InvalidSwitchToTargetException): pass class NoSuchElementException(WebDriverException): """find_element_by_* can't find the element.""" pass class NoSuchAttributeException(WebDriverException): """find_element_by_* can't find the element.""" pass class StaleElementReferenceException(WebDriverException): """Indicates that a reference to an element is now "stale" --- the element no longer appears on the DOM of the page.""" pass class InvalidElementStateException(WebDriverException): pass class NoAlertPresentException(WebDriverException): pass class ElementNotVisibleException(InvalidElementStateException): """Thrown to indicate that although an element is present on the DOM, it is not visible, and so is not able to be interacted with.""" pass class ElementNotSelectableException(InvalidElementStateException): pass class InvalidCookieDomainException(WebDriverException): """Thrown when attempting to add a cookie under a different domain than the current URL.""" pass class UnableToSetCookieException(WebDriverException): """Thrown when a driver fails to set a cookie.""" pass class RemoteDriverServerException(WebDriverException): pass class TimeoutException(WebDriverException): """Thrown when a command does not complete in enough time.""" pass class MoveTargetOutOfBoundsException(WebDriverException): """Indicates that the target provided to the actions move() method is invalid""" pass class UnexpectedTagNameException(WebDriverException): """Thrown when a support class did not get an expected web element""" pass class InvalidSelectorException(NoSuchElementException): """ Thrown when the selector which is used to find an element does not return a WebElement. Currently this only happens when the selector is an xpath expression is used which is either syntactically invalid (i.e. it is not a xpath expression) or the expression does not select WebElements (e.g. "count(//input)"). """ pass class ImeNotAvailableException(WebDriverException): """ Indicates that IME support is not available. This exception is thrown for every IME-related method call if IME support is not available on the machine. """ pass class ImeActivationFailedException(WebDriverException): """ Indicates that activating an IME engine has failed. """ pass
1,294
418
#ifndef FFT_H_ #define FFT_H_ typedef float DTYPE; typedef int INTTYPE; #define M 10 /* Number of Stages = Log2N */ #define SIZE 1024 /* SIZE OF FFT */ #define SIZE2 SIZE>>1 /* SIZE/2 */ void fft(DTYPE XX_R[SIZE], DTYPE XX_I[SIZE]); //W_real and W_image are twiddle factors for 1024 size FFT. //WW_R[i]=cos(e*i/SIZE); //WW_I[i]=sin(e*i/SIZE); //where i=[0,512) and DTYPE e = -6.283185307178; #include "tw_r.h" #include "tw_i.h" #endif
208
1,085
[ {"sourceType": "HBASE", "tags": ["community"]}, {"sourceType": "TERADATA", "tags": ["beta"]}, {"sourceType": "CASSANDRA", "disabled": true}, {"sourceType": "SALESFORCE", "disabled": true}, {"sourceType": "NETEZZA", "disabled": true} ]
91
822
package com.zlm.hp.libs.download; import com.zlm.hp.libs.download.utils.TaskThreadUtil; import java.io.Serializable; import java.util.Date; /** * 下载任务 * * @author zhangliangming */ public class DownloadTask implements Serializable { /** * 任务id */ private String taskId; /** * 任务名称 */ private String taskName; /** * 任务文件后缀名 */ private String taskExt; /** * 任务保存路径 */ private String taskPath; /** * 任务hash */ private String taskHash; /** * 任务临时保存路径 */ private String taskTempPath; /** * 任务下载路径 */ private String taskUrl; /** * 添加时间 */ private Date createTime; /** * 任务状态 */ private int status; /** * 线程总数 */ private int threadNum; /** * 任务文件大小 */ private long taskFileSize; /** * 任务线程 */ private TaskThreadUtil taskThreadUtil; public DownloadTask() { } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } public String getTaskExt() { return taskExt; } public void setTaskExt(String taskExt) { this.taskExt = taskExt; } public String getTaskPath() { return taskPath; } public void setTaskPath(String taskPath) { this.taskPath = taskPath; } public String getTaskHash() { return taskHash; } public void setTaskHash(String taskHash) { this.taskHash = taskHash; } public String getTaskTempPath() { return taskTempPath; } public void setTaskTempPath(String taskTempPath) { this.taskTempPath = taskTempPath; } public String getTaskUrl() { return taskUrl; } public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getThreadNum() { return threadNum; } public void setThreadNum(int threadNum) { this.threadNum = threadNum; } public long getTaskFileSize() { return taskFileSize; } public void setTaskFileSize(long taskFileSize) { this.taskFileSize = taskFileSize; } public TaskThreadUtil getTaskThreadUtil() { return taskThreadUtil; } public void setTaskThreadUtil(TaskThreadUtil taskThreadUtil) { this.taskThreadUtil = taskThreadUtil; } @Override public String toString() { return "DownloadTask{" + "taskId='" + taskId + '\'' + ", taskName='" + taskName + '\'' + ", taskExt='" + taskExt + '\'' + ", taskPath='" + taskPath + '\'' + ", taskHash='" + taskHash + '\'' + ", taskTempPath='" + taskTempPath + '\'' + ", taskUrl='" + taskUrl + '\'' + ", createTime=" + createTime + ", status=" + status + ", threadNum=" + threadNum + ", taskFileSize=" + taskFileSize + ", taskThreadUtil=" + taskThreadUtil + '}'; } }
1,737
435
{ "description": "En los \u00faltimos a\u00f1os se ha popularizado la utilizaci\u00f3n de Python en el 'ambiente cient\u00edfico'. Esta tendencia creciente de debe al solapamiento entre las caracter\u00edsticas diferenciales que provee el lenguaje (y las bibliotecas especializadas) y las necesidades del cient\u00edfico en el modelado de sistemas f\u00edsicos, qu\u00edmicos y biol\u00f3gicos, entre otros. El objetivo de esta taller es introducir a los participantes, aquellas herramientas que pueden resolver las 'tareas cient\u00edficas' que se le plantean en el trabajo cient\u00edfico diario. En particular, se presentar\u00e1n las bibliotecas IPython, Numpy, Scipy y Matplotlib, detallando sus principales caracter\u00edsticas, ventajas y desventajas, as\u00ed como la integraci\u00f3n de dichas herramientas para la construcci\u00f3n de un flujo de trabajo que permita desarrollar modelos en m\u00faltiples \u00e1reas del conocimiento. El taller es de modalidad te\u00f3rica-pr\u00e1ctica, por lo que se trabajar\u00e1 con las bibliotecas cient\u00edficas anteriormente mencionadas en la resoluci\u00f3n de problemas simples a medida que se desarrolla el eje te\u00f3rico propuesto. \n\nD\u00eda 1:\n\n1. Python cient\u00edfico.\n\n #. ( T ) Flujo de trabajo de cient\u00edfico.\n #. ( T ) Python vs. Otros. Ventajas y desventajas.\n #. ( T ) El coraz\u00f3n de Python cient\u00edfico.\n #. ( P ) Obtenci\u00f3n de herramientas.\n\n2. IPython.\n\n #. ( T ) Descripci\u00f3n.\n #. ( T ) Clientes: consola, consola Qt, notebook.\n #. ( T ) El notebook de IPython.\n #. ( P ) Exploraci\u00f3n del notebook de IPython.", "recorded": "2013-05-16", "speakers": [ "Dami\u00e1<NAME>" ], "thumbnail_url": "https://i.ytimg.com/vi/x1_LPVFsPIU/hqdefault.jpg", "title": "Python Cient\u00edfico: Episodio I - D\u00eda 1 de 3", "videos": [ { "type": "youtube", "url": "https://www.youtube.com/watch?v=x1_LPVFsPIU" } ] }
856
338
package com.tvd12.ezyfoxserver.testing.socket; import java.net.InetSocketAddress; import java.nio.channels.DatagramChannel; import org.testng.annotations.Test; import com.tvd12.ezyfoxserver.socket.EzySimpleUdpReceivedPacket; public class EzySimpleUdpReceivedPacketTest { @Test public void test() { DatagramChannel channel = null; try { channel = DatagramChannel.open(); } catch (Exception e) { e.printStackTrace(); } InetSocketAddress address = new InetSocketAddress(12345); byte[] bytes = new byte[] {1, 2, 3}; EzySimpleUdpReceivedPacket packet = new EzySimpleUdpReceivedPacket( channel, address, bytes); assert packet.getAddress() != null; assert packet.getBytes() != null; System.out.println(packet.getChannel()); packet.release(); } }
383
380
from .imports import * from .foundation import * from .dispatch import * from .utils import * from .script import * from .transform import *
38
839
/** * 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.cxf.ws.transfer.validationtransformation; import java.util.List; import org.apache.cxf.ws.transfer.Representation; import org.apache.cxf.ws.transfer.shared.faults.InvalidRepresentation; /** * Helper class for validation and transformation. */ public final class ValidAndTransformHelper { private ValidAndTransformHelper() { } /** * Validation and transformation process. * @param resourceTypeIdentifiers List of resourceTypeIdentifiers. * @param newRepresentation Incoming representation. * @param oldRepresentation Representation stored in the ResourceManager. */ public static void validationAndTransformation( List<ResourceTypeIdentifier> resourceTypeIdentifiers, Representation newRepresentation, Representation oldRepresentation) { if (resourceTypeIdentifiers != null && !resourceTypeIdentifiers.isEmpty()) { for (ResourceTypeIdentifier resourceIdentifier : resourceTypeIdentifiers) { ResourceTypeIdentifierResult valResult = resourceIdentifier.identify(newRepresentation); if (valResult.isCorrect()) { if (valResult.getTransformer() != null) { ResourceTransformer transformer = valResult.getTransformer(); ResourceValidator validator = transformer.transform(newRepresentation, oldRepresentation); if (validator != null && !validator.validate(newRepresentation, oldRepresentation)) { throw new InvalidRepresentation(); } } return; } } throw new InvalidRepresentation(); } } }
886
479
<filename>gerrit-server/src/main/java/com/google/gerrit/server/plugins/PluginEntry.java // Copyright (C) 2014 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.google.gerrit.server.plugins; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.Optional; /** * Plugin static resource entry * * <p>Bean representing a static resource inside a plugin. All static resources are available at * {@code <plugin web url>/static} and served by the HttpPluginServlet. */ public class PluginEntry { public static final String ATTR_CHARACTER_ENCODING = "Character-Encoding"; public static final String ATTR_CONTENT_TYPE = "Content-Type"; public static final Comparator<PluginEntry> COMPARATOR_BY_NAME = new Comparator<PluginEntry>() { @Override public int compare(PluginEntry a, PluginEntry b) { return a.getName().compareTo(b.getName()); } }; private static final Map<Object, String> EMPTY_ATTRS = Collections.emptyMap(); private static final Optional<Long> NO_SIZE = Optional.empty(); private final String name; private final long time; private final Optional<Long> size; private final Map<Object, String> attrs; public PluginEntry(String name, long time, Optional<Long> size, Map<Object, String> attrs) { this.name = name; this.time = time; this.size = size; this.attrs = attrs; } public PluginEntry(String name, long time, Optional<Long> size) { this(name, time, size, EMPTY_ATTRS); } public PluginEntry(String name, long time) { this(name, time, NO_SIZE, EMPTY_ATTRS); } public String getName() { return name; } public long getTime() { return time; } public Optional<Long> getSize() { return size; } public Map<Object, String> getAttrs() { return attrs; } }
752
2,607
<filename>Src/PRuntimes/PSymbolicRuntime/src/main/java/psymbolic/runtime/NondetUtil.java package psymbolic.runtime; import psymbolic.valuesummary.Guard; import psymbolic.valuesummary.GuardedValue; import psymbolic.valuesummary.PrimitiveVS; import psymbolic.valuesummary.util.ValueSummaryUnionFind; import java.util.*; import java.util.stream.Collectors; public class NondetUtil { private static int log2(int bits) { if( bits == 0 ) return 0; // or throw exception return 31 - Integer.numberOfLeadingZeros(bits); } private static List<Guard> generateAllCombos(List<Guard> bdds) { Guard thisGuard = bdds.get(0); List<Guard> remaining = bdds.subList(1, bdds.size()); if (remaining.size() == 0) { List<Guard> res = new ArrayList<>(); res.add(thisGuard); res.add(thisGuard.not()); return res; } List<Guard> rec = generateAllCombos(remaining); List<Guard> res = rec.stream().map(x -> x.and(thisGuard)).collect(Collectors.toList()); res.addAll(rec.stream().map(x -> x.and(thisGuard.not())).collect(Collectors.toList())); return res; } public static PrimitiveVS getNondetChoiceAlt(List<PrimitiveVS> choices) { if (choices.size() == 0) return new PrimitiveVS<>(); if (choices.size() == 1) return choices.get(0); List<PrimitiveVS> results = new ArrayList<>(); PrimitiveVS empty = choices.get(0).restrict(Guard.constFalse()); List<Guard> choiceVars = new ArrayList<>(); int numVars = 1; while ((1 << numVars) - choices.size() < 0) { numVars++; } for (int i = 0; i < numVars; i++) { choiceVars.add(Guard.newVar()); } List<Guard> choiceConds = generateAllCombos(choiceVars); Guard accountedPc = Guard.constFalse(); for (int i = 0; i < choices.size(); i++) { PrimitiveVS choice = choices.get(i).restrict(choiceConds.get(i)); results.add(choice); accountedPc = accountedPc.or(choice.getUniverse()); } Guard residualPc = accountedPc.not(); int i = 0; for (PrimitiveVS choice : choices) { if (residualPc.isFalse()) break; Guard enabledCond = choice.getUniverse(); PrimitiveVS guarded = choice.restrict(residualPc); results.add(guarded); residualPc = residualPc.and(enabledCond.not()); } return empty.merge(results); } public static PrimitiveVS getNondetChoice(List<PrimitiveVS> choices) { if (choices.size() == 0) return new PrimitiveVS<>(); if (choices.size() == 1) return choices.get(0); List<PrimitiveVS> results = new ArrayList<>(); PrimitiveVS empty = choices.get(0).restrict(Guard.constFalse()); List<Guard> choiceVars = new ArrayList<>(); ValueSummaryUnionFind uf = new ValueSummaryUnionFind(choices); Collection<Set<PrimitiveVS>> disjoint = uf.getDisjointSets(); // only need to distinguish between things within disjoint sets Map<Set<PrimitiveVS>, Guard> universeMap = uf.getLastUniverseMap(); int maxSize = 0; for (Set<PrimitiveVS> set : disjoint) { int size = set.size(); if (size > maxSize) { maxSize = size; } } int numVars = 1; while ((1 << numVars) - maxSize < 0) { numVars++; } for (int i = 0; i < numVars; i++) { choiceVars.add(Guard.newVar()); } List<Guard> choiceConds = generateAllCombos(choiceVars); for (Set<PrimitiveVS> set : disjoint) { results.addAll(getIntersectingNondetChoice(new ArrayList<>(set), choiceConds, universeMap.get(set))); } return empty.merge(results); } public static List<PrimitiveVS> getIntersectingNondetChoice(List<PrimitiveVS> choices, List<Guard> choiceConds, Guard universe) { List<PrimitiveVS> results = new ArrayList<>(); Guard accountedPc = Guard.constFalse(); for (int i = 0; i < choices.size(); i++) { PrimitiveVS choice = choices.get(i).restrict(choiceConds.get(i)); results.add(choice); accountedPc = accountedPc.or(choice.getUniverse()); } Guard residualPc = accountedPc.not().and(universe); for (PrimitiveVS choice : choices) { if (residualPc.isFalse()) break; Guard enabledCond = choice.getUniverse(); PrimitiveVS guarded = choice.restrict(residualPc); results.add(guarded); residualPc = residualPc.and(enabledCond.not()); } return results; } public static Guard chooseGuard(int n, PrimitiveVS choice) { Guard guard = Guard.constFalse(); if (choice.getGuardedValues().size() <= n) return Guard.constTrue(); for (GuardedValue guardedValue : (List<GuardedValue>) choice.getGuardedValues()) { if (n == 0) break; guard = guard.or(guardedValue.getGuard()); n--; } return guard; } public static PrimitiveVS excludeChoice(Guard guard, PrimitiveVS choice) { PrimitiveVS newChoice = choice.restrict(guard.not()); List<GuardedValue> guardedValues = newChoice.getGuardedValues(); if (guardedValues.size() > 0) { newChoice.merge(new PrimitiveVS(guardedValues.iterator().next().getValue()).restrict(guard)); } return newChoice; } }
2,454
14,668
<filename>chrome/test/data/extensions/crx_installer/v2_no_permission_change/manifest.json { "name": "CRX Installer Test New Title", "version": "2", "manifest_version": 2, "permissions": ["tabs"], "icons": { "16": "icon.png" }, "homepage_url": "http://chrome.google.com" }
117
777
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_DATA_USE_MEASUREMENT_CHROME_DATA_USE_ASCRIBER_SERVICE_H_ #define CHROME_BROWSER_DATA_USE_MEASUREMENT_CHROME_DATA_USE_ASCRIBER_SERVICE_H_ #include <list> #include <unordered_set> #include "base/macros.h" #include "components/keyed_service/core/keyed_service.h" namespace content { class NavigationHandle; class RenderFrameHost; } namespace data_use_measurement { class ChromeDataUseAscriber; // UI thread functionality of ChromeDataUseAscriber. // // Listens to navigation and frame events on the UI thread and propagates them // to ChromeDataUseAscriber on the IO thread. This class depends on external // WebContentsObservers to propagate events to itself because each // WebContents instance requires its own WebContentsObserver instance. // // Created, destroyed, and used only on the UI thread. class ChromeDataUseAscriberService : public KeyedService { public: ChromeDataUseAscriberService(); ~ChromeDataUseAscriberService() override; // Called when a render frame host is created. Propagates this information to // |ascriber_| on the IO thread. |RenderFrameHost| methods cannot be called // on the IO thread, so only routing IDs of |render_frame_host| and its parent // are propagated. void RenderFrameCreated(content::RenderFrameHost* render_frame_host); // Called when a render frame host is deleted. Propagates this information to // |ascriber_| on the IO thread. RenderFrameHost methods cannot be called // on the IO thread, so only routing IDs of |render_frame_host| and its parent // are propagated. void RenderFrameDeleted(content::RenderFrameHost* render_frame_host); // Called when a navigation is started. Propagates main frame navigation // start to the |ascriber_| on the IO thread. NavigationHandle methods // cannot be called on the IO thread, so the pointer is cast to void*. void DidStartNavigation(content::NavigationHandle* navigation_handle); // Called when the navigation is ready to be committed in a renderer. // Propagates the event to the |ascriber_| on the IO thread. NavigationHandle // methods cannot be called on the IO thread, so the pointer is cast to void*. void ReadyToCommitNavigation(content::NavigationHandle* navigation_handle); // Called every time the WebContents changes visibility. Propagates the event // to the |ascriber_| on the IO thread. void WasShownOrHidden(content::RenderFrameHost* main_render_frame_host, bool visible); // Called when one of the render frames of a WebContents is swapped. void RenderFrameHostChanged(content::RenderFrameHost* old_host, content::RenderFrameHost* new_host); private: friend class ChromeDataUseAscriberServiceTest; void SetDataUseAscriber(ChromeDataUseAscriber* ascriber); // |ascriber_| outlives this instance. ChromeDataUseAscriber* ascriber_; // Tracks whether |ascriber_| was set. This field is required because tests // might set |ascriber_| to nullptr. bool is_initialized_; // Frame events might arrive from the UI thread before |ascriber_| is set. A // queue of frame events that arrive before |ascriber_| is set is maintained // in this field so that they can be propagated immediately after |ascriber_| // is set. The RenderFrameHost pointers in the queues are valid for the // duration that they are in the queue. std::list<content::RenderFrameHost*> pending_frames_queue_; // WebContents visibility change events might arrive from the UI thread before // |ascriber_| is set. Sucn pending main render frame visibile events are // maintained in this set and propagated immediately after |ascriber_| is set. std::unordered_set<content::RenderFrameHost*> pending_visible_main_frames_; DISALLOW_COPY_AND_ASSIGN(ChromeDataUseAscriberService); }; } // namespace data_use_measurement #endif // CHROME_BROWSER_DATA_USE_MEASUREMENT_CHROME_DATA_USE_ASCRIBER_SERVICE_H_
1,198
9,402
<reponame>pyracanda/runtime<filename>src/tests/Interop/PInvoke/Generics/GenericsNative.SpanB.cpp // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #include <stdio.h> #include <stdint.h> #include <xplatform.h> #include <platformdefines.h> struct ByReferenceB { intptr_t value; }; struct SpanB { ByReferenceB pointer; int32_t length; }; static SpanB SpanBValue = { }; extern "C" DLL_EXPORT SpanB STDMETHODCALLTYPE GetSpanB(bool e00) { throw "P/Invoke for Span<bool> should be unsupported."; } extern "C" DLL_EXPORT void STDMETHODCALLTYPE GetSpanBOut(bool e00, SpanB* pValue) { throw "P/Invoke for Span<bool> should be unsupported."; } extern "C" DLL_EXPORT const SpanB* STDMETHODCALLTYPE GetSpanBPtr(bool e00) { throw "P/Invoke for Span<bool> should be unsupported."; } extern "C" DLL_EXPORT SpanB STDMETHODCALLTYPE AddSpanB(SpanB lhs, SpanB rhs) { throw "P/Invoke for Span<bool> should be unsupported."; } extern "C" DLL_EXPORT SpanB STDMETHODCALLTYPE AddSpanBs(const SpanB* pValues, uint32_t count) { throw "P/Invoke for Span<bool> should be unsupported."; }
455
1,347
<filename>tests/examples/factory/test_factory.py import pytest from eth_utils import keccak import vyper @pytest.fixture def create_token(get_contract): with open("examples/tokens/ERC20.vy") as f: code = f.read() def create_token(): return get_contract(code, *["VyperCoin", "FANG", 0, 0]) return create_token @pytest.fixture def create_exchange(w3, get_contract): with open("examples/factory/Exchange.vy") as f: code = f.read() def create_exchange(token, factory): exchange = get_contract(code, *[token.address, factory.address]) # NOTE: Must initialize exchange to register it with factory exchange.initialize(transact={"from": w3.eth.accounts[0]}) return exchange return create_exchange @pytest.fixture def factory(get_contract): with open("examples/factory/Exchange.vy") as f: code = f.read() exchange_interface = vyper.compile_code(code, output_formats=["bytecode_runtime"]) exchange_deployed_bytecode = exchange_interface["bytecode_runtime"] with open("examples/factory/Factory.vy") as f: code = f.read() # NOTE: We deploy the factory with the hash of the exchange's expected deployment bytecode return get_contract(code, keccak(hexstr=exchange_deployed_bytecode)) def test_exchange(w3, factory, create_token, create_exchange): a = w3.eth.accounts[0] token1 = create_token() exchange1 = create_exchange(token1, factory) token2 = create_token() exchange2 = create_exchange(token2, factory) # user has token 1 token1.mint(a, 1, transact={"from": a}) # exchange has token 2 token2.mint(exchange2.address, 1, transact={"from": a}) # So approval doesn't fail for transferFrom token1.approve(exchange1.address, 1, transact={"from": a}) # trade token 1 for token 2 assert token1.balanceOf(a) == 1 assert token2.balanceOf(a) == 0 factory.trade(token1.address, token2.address, 1, transact={"from": a}) assert token1.balanceOf(a) == 0 assert token2.balanceOf(a) == 1
783
852
<reponame>ckamtsikis/cmssw #ifndef CASTOR_CALIBRATION_WIDTHS_H #define CASTOR_CALIBRATION_WIDTHS_H /** \class CastorCalibrationWidths Container for retrieving uncertainties of calibration constants for Castor */ class CastorCalibrationWidths { public: CastorCalibrationWidths() : mGain{}, mPedestal{} {}; CastorCalibrationWidths(const float fGain[4], const float fPedestal[4]); /// get gain width for capid=0..3 double gain(int fCapId) const { return mGain[fCapId]; } /// get pedestal width for capid=0..3 double pedestal(int fCapId) const { return mPedestal[fCapId]; } private: double mGain[4]; double mPedestal[4]; }; #endif
255
683
<filename>instrumentation/opentelemetry-api-metrics-1.0/javaagent/src/main/java/io/opentelemetry/javaagent/instrumentation/opentelemetryapi/metrics/bridge/ApplicationBoundDoubleHistogram.java /* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.javaagent.instrumentation.opentelemetryapi.metrics.bridge; import application.io.opentelemetry.api.metrics.BoundDoubleHistogram; import application.io.opentelemetry.context.Context; import io.opentelemetry.javaagent.instrumentation.opentelemetryapi.context.AgentContextStorage; final class ApplicationBoundDoubleHistogram implements BoundDoubleHistogram { private final io.opentelemetry.api.metrics.BoundDoubleHistogram agentHistogram; ApplicationBoundDoubleHistogram( io.opentelemetry.api.metrics.BoundDoubleHistogram agentHistogram) { this.agentHistogram = agentHistogram; } @Override public void record(double value) { agentHistogram.record(value); } @Override public void record(double value, Context context) { agentHistogram.record(value, AgentContextStorage.getAgentContext(context)); } @Override public void unbind() { agentHistogram.unbind(); } }
373
1,448
/*===================================================================*/ /* */ /* Mapper 9 (MMC2) */ /* */ /*===================================================================*/ struct Map9_Latch { BYTE lo_bank; BYTE hi_bank; BYTE state; }; struct Map9_Latch latch1; struct Map9_Latch latch2; /*-------------------------------------------------------------------*/ /* Initialize Mapper 9 */ /*-------------------------------------------------------------------*/ void Map9_Init() { int nPage; /* Initialize Mapper */ MapperInit = Map9_Init; /* Write to Mapper */ MapperWrite = Map9_Write; /* Write to SRAM */ MapperSram = Map0_Sram; /* Write to APU */ MapperApu = Map0_Apu; /* Read from APU */ MapperReadApu = Map0_ReadApu; /* Callback at VSync */ MapperVSync = Map0_VSync; /* Callback at HSync */ MapperHSync = Map0_HSync; /* Callback at PPU */ MapperPPU = Map9_PPU; /* Callback at Rendering Screen ( 1:BG, 0:Sprite ) */ MapperRenderScreen = Map0_RenderScreen; /* Set SRAM Banks */ SRAMBANK = SRAM; /* Set ROM Banks */ ROMBANK0 = ROMPAGE( 0 ); ROMBANK1 = ROMLASTPAGE( 2 ); ROMBANK2 = ROMLASTPAGE( 1 ); ROMBANK3 = ROMLASTPAGE( 0 ); /* Set PPU Banks */ if ( NesHeader.byVRomSize > 0 ) { for ( nPage = 0; nPage < 8; ++nPage ) PPUBANK[ nPage ] = VROMPAGE( nPage ); InfoNES_SetupChr(); } /* Init Latch Selector */ latch1.state = 0xfe; latch1.lo_bank = 0; latch1.hi_bank = 0; latch2.state = 0xfe; latch2.lo_bank = 0; latch2.hi_bank = 0; /* Set up wiring of the interrupt pin */ K6502_Set_Int_Wiring( 1, 1 ); } /*-------------------------------------------------------------------*/ /* Mapper 9 Write Function */ /*-------------------------------------------------------------------*/ void Map9_Write( WORD wAddr, BYTE byData ) { WORD wMapAddr; wMapAddr = wAddr & 0xf000; switch ( wMapAddr ) { case 0xa000: /* Set ROM Banks */ byData %= ( NesHeader.byRomSize << 1 ); ROMBANK0 = ROMPAGE( byData ); break; case 0xb000: /* Number of 4K Banks to Number of 1K Banks */ byData %= ( NesHeader.byVRomSize << 1 ); byData <<= 2; /* Latch Control */ latch1.lo_bank = byData; if (0xfd == latch1.state) { /* Set PPU Banks */ PPUBANK[ 0 ] = VROMPAGE( byData ); PPUBANK[ 1 ] = VROMPAGE( byData + 1 ); PPUBANK[ 2 ] = VROMPAGE( byData + 2 ); PPUBANK[ 3 ] = VROMPAGE( byData + 3 ); InfoNES_SetupChr(); } break; case 0xc000: /* Number of 4K Banks to Number of 1K Banks */ byData %= ( NesHeader.byVRomSize << 1 ); byData <<= 2; /* Latch Control */ latch1.hi_bank = byData; if (0xfe == latch1.state) { /* Set PPU Banks */ PPUBANK[ 0 ] = VROMPAGE( byData ); PPUBANK[ 1 ] = VROMPAGE( byData + 1 ); PPUBANK[ 2 ] = VROMPAGE( byData + 2 ); PPUBANK[ 3 ] = VROMPAGE( byData + 3 ); InfoNES_SetupChr(); } break; case 0xd000: /* Number of 4K Banks to Number of 1K Banks */ byData %= ( NesHeader.byVRomSize << 1 ); byData <<= 2; /* Latch Control */ latch2.lo_bank = byData; if (0xfd == latch2.state) { /* Set PPU Banks */ PPUBANK[ 4 ] = VROMPAGE( byData ); PPUBANK[ 5 ] = VROMPAGE( byData + 1 ); PPUBANK[ 6 ] = VROMPAGE( byData + 2 ); PPUBANK[ 7 ] = VROMPAGE( byData + 3 ); InfoNES_SetupChr(); } break; case 0xe000: /* Number of 4K Banks to Number of 1K Banks */ byData %= ( NesHeader.byVRomSize << 1 ); byData <<= 2; /* Latch Control */ latch2.hi_bank = byData; if (0xfe == latch2.state) { /* Set PPU Banks */ PPUBANK[ 4 ] = VROMPAGE( byData ); PPUBANK[ 5 ] = VROMPAGE( byData + 1 ); PPUBANK[ 6 ] = VROMPAGE( byData + 2 ); PPUBANK[ 7 ] = VROMPAGE( byData + 3 ); InfoNES_SetupChr(); } break; case 0xf000: /* Name Table Mirroring */ InfoNES_Mirroring( byData & 0x01 ? 0 : 1); break; } } /*-------------------------------------------------------------------*/ /* Mapper 9 PPU Function */ /*-------------------------------------------------------------------*/ void Map9_PPU( WORD wAddr ) { /* Control Latch Selector */ switch ( wAddr & 0x3ff0 ) { case 0x0fd0: /* Latch Control */ latch1.state = 0xfd; /* Set PPU Banks */ PPUBANK[ 0 ] = VROMPAGE( latch1.lo_bank ); PPUBANK[ 1 ] = VROMPAGE( latch1.lo_bank + 1 ); PPUBANK[ 2 ] = VROMPAGE( latch1.lo_bank + 2 ); PPUBANK[ 3 ] = VROMPAGE( latch1.lo_bank + 3 ); InfoNES_SetupChr(); break; case 0x0fe0: /* Latch Control */ latch1.state = 0xfe; /* Set PPU Banks */ PPUBANK[ 0 ] = VROMPAGE( latch1.hi_bank ); PPUBANK[ 1 ] = VROMPAGE( latch1.hi_bank + 1 ); PPUBANK[ 2 ] = VROMPAGE( latch1.hi_bank + 2 ); PPUBANK[ 3 ] = VROMPAGE( latch1.hi_bank + 3 ); InfoNES_SetupChr(); break; case 0x1fd0: /* Latch Control */ latch2.state = 0xfd; /* Set PPU Banks */ PPUBANK[ 4 ] = VROMPAGE( latch2.lo_bank ); PPUBANK[ 5 ] = VROMPAGE( latch2.lo_bank + 1 ); PPUBANK[ 6 ] = VROMPAGE( latch2.lo_bank + 2 ); PPUBANK[ 7 ] = VROMPAGE( latch2.lo_bank + 3 ); InfoNES_SetupChr(); break; case 0x1fe0: /* Latch Control */ latch2.state = 0xfe; /* Set PPU Banks */ PPUBANK[ 4 ] = VROMPAGE( latch2.hi_bank ); PPUBANK[ 5 ] = VROMPAGE( latch2.hi_bank + 1 ); PPUBANK[ 6 ] = VROMPAGE( latch2.hi_bank + 2 ); PPUBANK[ 7 ] = VROMPAGE( latch2.hi_bank + 3 ); InfoNES_SetupChr(); break; } }
2,989
2,151
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/metrics/desktop_task_switch_metric_recorder.h" #include "ash/metrics/user_metrics_recorder.h" #include "ash/shell.h" #include "ash/wm/window_util.h" #include "ui/wm/public/activation_client.h" namespace ash { DesktopTaskSwitchMetricRecorder::DesktopTaskSwitchMetricRecorder() : last_active_task_window_(nullptr) { Shell::Get()->activation_client()->AddObserver(this); } DesktopTaskSwitchMetricRecorder::~DesktopTaskSwitchMetricRecorder() { Shell::Get()->activation_client()->RemoveObserver(this); } void DesktopTaskSwitchMetricRecorder::OnWindowActivated( ::wm::ActivationChangeObserver::ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) { if (gained_active && wm::IsWindowUserPositionable(gained_active)) { if (last_active_task_window_ != gained_active && reason == ::wm::ActivationChangeObserver::ActivationReason::INPUT_EVENT) { Shell::Get()->metrics()->RecordUserMetricsAction(UMA_DESKTOP_SWITCH_TASK); } last_active_task_window_ = gained_active; } } } // namespace ash
439
350
/* * Copyright 2020 Google 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. */ package com.google.android.accessibility.brailleime.tutorial; import static android.view.animation.Animation.INFINITE; import static com.google.android.accessibility.brailleime.tutorial.TutorialView.ROTATION_0; import static com.google.android.accessibility.brailleime.tutorial.TutorialView.ROTATION_180; import static com.google.android.accessibility.brailleime.tutorial.TutorialView.ROTATION_270; import static com.google.android.accessibility.brailleime.tutorial.TutorialView.ROTATION_90; import static java.lang.Math.max; import static java.lang.Math.min; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.Configuration; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Point; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.Shader.TileMode; import android.text.Layout.Alignment; import android.text.StaticLayout; import android.text.TextPaint; import android.util.Size; import android.view.View; import androidx.annotation.ColorInt; import com.google.android.accessibility.brailleime.BrailleIme.OrientationSensitive; import com.google.android.accessibility.brailleime.R; import com.google.android.accessibility.brailleime.Utils; import com.google.android.accessibility.brailleime.tutorial.TutorialAnimationView.SwipeAnimation.Direction; import java.util.ArrayList; import java.util.List; /** View that draws instruction text, gesture animation and action result text. */ class TutorialAnimationView extends View implements OrientationSensitive { private final HintToast hintToast; private final ActionResult actionResult; private final SwipeAnimation swipeAnimation; private boolean shouldShowActionResult; private boolean shouldShowSwipeAnimation; private int orientation; private Size screenSize; private final boolean isTabletop; TutorialAnimationView(Context context, int orientation, Size screenSize, boolean isTabletop) { super(context); this.orientation = orientation; this.isTabletop = isTabletop; this.screenSize = getScreenSize(screenSize); hintToast = new HintToast(context, this::invalidate); actionResult = new ActionResult(context, this::invalidate); swipeAnimation = new SwipeAnimation(context, this::invalidate); } @Override public void onOrientationChanged(int orientation, Size screenSize) { this.orientation = orientation; this.screenSize = getScreenSize(screenSize); invalidate(); requestLayout(); } private Size getScreenSize(Size screenSize) { if (Utils.isPhoneSizedDevice(getResources()) && orientation == Configuration.ORIENTATION_PORTRAIT) { screenSize = new Size(/* width= */ screenSize.getHeight(), /* height= */ screenSize.getWidth()); } return screenSize; } @Override public void onDraw(Canvas canvas) { canvas.save(); if (Utils.isPhoneSizedDevice(getResources())) { if (orientation == Configuration.ORIENTATION_PORTRAIT) { canvas.rotate(isTabletop ? ROTATION_90 : ROTATION_270); canvas.translate( /* dx= */ isTabletop ? 0 : -screenSize.getWidth(), /* dy= */ isTabletop ? -screenSize.getHeight() : 0); } else { canvas.rotate(isTabletop ? ROTATION_180 : ROTATION_0); canvas.translate( /* dx= */ isTabletop ? -screenSize.getWidth() : 0, /* dy= */ isTabletop ? -screenSize.getHeight() : 0); } } hintToast.onDraw(canvas, screenSize); if (shouldShowActionResult) { actionResult.onDraw(canvas, screenSize); } if (shouldShowSwipeAnimation) { swipeAnimation.onDraw(canvas); } canvas.restore(); } void startHintToastAnimation(String text) { hintToast.setText(text); hintToast.startAnimation(); } void startActionResultAnimation(String text) { shouldShowActionResult = true; actionResult.setText(text); actionResult.startAnimation(); } void startSwipeAnimation(int fingerCount, Direction swipeDirection) { shouldShowSwipeAnimation = true; swipeAnimation.updatePaint( fingerCount, screenSize, isTabletop ? mirror(swipeDirection) : swipeDirection); swipeAnimation.startAnimation(); } private static Direction mirror(Direction oldDirection) { if (oldDirection == Direction.LEFT_TO_RIGHT) { return Direction.RIGHT_TO_LEFT; } else if (oldDirection == Direction.RIGHT_TO_LEFT) { return Direction.LEFT_TO_RIGHT; } return oldDirection; } void stopSwipeAnimation() { shouldShowSwipeAnimation = false; swipeAnimation.stopAnimation(); } void reset() { shouldShowActionResult = false; shouldShowSwipeAnimation = false; } /** Draws the tutorial instruction of every stage in the top middle of screen. */ static class HintToast { private static final int ANIMATION_DURATION_MS = 200; private static final float HEIGHT_SCALE = 1.5f; private final int top; private final Paint textBackgroundPaint; private final TextPaint textPaint; private final RectF textBackgroundRect; private final ValueAnimator animator; private String text = ""; HintToast(Context context, Runnable invalidate) { top = context.getResources().getDimensionPixelSize(R.dimen.hint_margin); int backgroundColor = context.getColor(R.color.hint_background); textBackgroundPaint = new Paint(); textBackgroundPaint.setColor(backgroundColor); textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); textPaint.setColor(Color.WHITE); textPaint.setTextSize(context.getResources().getDimensionPixelSize(R.dimen.hint_text_size)); textPaint.setTextAlign(Align.CENTER); textBackgroundRect = new RectF(); animator = ValueAnimator.ofInt(0, Color.alpha(backgroundColor)); animator.setDuration(ANIMATION_DURATION_MS); animator.addUpdateListener(animation -> invalidate.run()); } void startAnimation() { animator.start(); } void setText(String text) { this.text = text; } void onDraw(Canvas canvas, Size screenSize) { int alpha = (int) animator.getAnimatedValue(); textBackgroundPaint.setAlpha(alpha); // Append 4 spaces to make text look like it has left/right padding. float measureTextWidth = textPaint.measureText(" " + text); float textLength = min(screenSize.getWidth(), measureTextWidth); StaticLayout staticLayout = buildStaticLayout(text, textPaint, (int) textLength); float left = (screenSize.getWidth() - textLength) / 2f; float top = this.top; float textHeight = staticLayout.getHeight(); textBackgroundRect.set(left, top, left + textLength, top + HEIGHT_SCALE * textHeight); float cornerRadius = (textBackgroundRect.bottom - textBackgroundRect.top) / 2f; canvas.drawRoundRect(textBackgroundRect, cornerRadius, cornerRadius, textBackgroundPaint); canvas.save(); canvas.translate(textBackgroundRect.centerX(), textBackgroundRect.centerY() - textHeight / 2); staticLayout.draw(canvas); canvas.restore(); } } /** Draws the braille output or gesture event in the middle of screen. */ static class ActionResult { private static final int ANIMATION_DURATION_MS = 300; private static final float ROUND_CORNER_RADIUS_DIVISOR = 5f; private final Paint textBackgroundPaint; private final TextPaint textPaint; private final RectF textBackgroundRect; private final ValueAnimator animator; private String text = ""; ActionResult(Context context, Runnable invalidate) { textBackgroundPaint = new Paint(); textBackgroundPaint.setColor(context.getColor(R.color.hint_background)); textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); textPaint.setColor(Color.WHITE); textPaint.setTextSize( context.getResources().getDimensionPixelSize(R.dimen.action_result_text_size)); textPaint.setTextAlign(Align.CENTER); textBackgroundRect = new RectF(); animator = ValueAnimator.ofInt(0, Color.alpha(context.getColor(R.color.hint_background))); animator.setDuration(ANIMATION_DURATION_MS); animator.addUpdateListener(animation -> invalidate.run()); } void startAnimation() { animator.start(); } void setText(String text) { this.text = text; } void onDraw(Canvas canvas, Size screenSize) { int alpha = (int) animator.getAnimatedValue(); textBackgroundPaint.setAlpha(alpha); // Append 4 spaces to make text look like it has left/right padding. float measureTextWidth = (int) textPaint.measureText(" " + text); float textLength = min(screenSize.getWidth(), measureTextWidth); StaticLayout staticLayout = buildStaticLayout(text, textPaint, (int) textLength); float textHeight = staticLayout.getHeight(); float rectHeight = 2f * textHeight; float rectLength = max(textLength, rectHeight); float left = (screenSize.getWidth() - rectLength) / 2f; float top = (screenSize.getHeight() - rectHeight) / 2f; textBackgroundRect.set(left, top, left + rectLength, top + rectHeight); float cornerRadius = textHeight / ROUND_CORNER_RADIUS_DIVISOR; canvas.drawRoundRect(textBackgroundRect, cornerRadius, cornerRadius, textBackgroundPaint); canvas.save(); canvas.translate(textBackgroundRect.centerX(), textBackgroundRect.centerY() - textHeight / 2); staticLayout.draw(canvas); canvas.restore(); } } private static StaticLayout buildStaticLayout( String text, TextPaint textPaint, int desiredLength) { StaticLayout.Builder builder = StaticLayout.Builder.obtain(text, /* start= */ 0, text.length(), textPaint, desiredLength) .setAlignment(Alignment.ALIGN_NORMAL) .setLineSpacing(/* spacingAdd= */ 0, /* spacingMult= */ 1) .setIncludePad(false); return builder.build(); } /** Draws the swipe instruction animation in the middle of screen. */ static class SwipeAnimation { public enum Direction { TOP_TO_BOTTOM, BOTTOM_TO_TOP, LEFT_TO_RIGHT, RIGHT_TO_LEFT, } private static final int DISTANCE_BETWEEN_GESTURES_IN_PIXELS = 75; private static final int ANIMATION_DURATION_MS = 1500; private static final float SCALE_FACTOR = 0.5f; private final Paint circlePaint; private final Paint roundRectPaint; private ValueAnimator animator; private Direction direction = Direction.TOP_TO_BOTTOM; private final int dotRadiusInPixels; @ColorInt private final int gestureGradientColor; private final Runnable invalidate; private final List<Point> gesturesCircleCoordinates = new ArrayList<>(); SwipeAnimation(Context context, Runnable invalidate) { this.invalidate = invalidate; circlePaint = new Paint(); circlePaint.setColor(context.getColor(R.color.gesture_circle)); this.gestureGradientColor = context.getColor(R.color.gesture_circle_gradient); roundRectPaint = new Paint(); roundRectPaint.setColor(gestureGradientColor); dotRadiusInPixels = context.getResources().getDimensionPixelSize(R.dimen.tutorial_gesture_dot_radius); } void updatePaint(int fingerCount, Size screenSize, Direction swipeDirection) { this.direction = swipeDirection; float canvasLength = 0; switch (swipeDirection) { case TOP_TO_BOTTOM: case BOTTOM_TO_TOP: canvasLength = screenSize.getHeight() * SCALE_FACTOR; break; case LEFT_TO_RIGHT: case RIGHT_TO_LEFT: canvasLength = screenSize.getWidth() * SCALE_FACTOR; break; } updateGesturesCoordinates(fingerCount, (int) canvasLength, screenSize, swipeDirection); Rect gradientVariation = determineGradientVariation((int) canvasLength, swipeDirection); Shader shader = new LinearGradient( gradientVariation.left, gradientVariation.top, gradientVariation.right, gradientVariation.bottom, Color.TRANSPARENT, gestureGradientColor, TileMode.CLAMP); roundRectPaint.setShader(shader); animator = ValueAnimator.ofFloat(0, canvasLength, canvasLength); animator.setDuration(ANIMATION_DURATION_MS); animator.setRepeatCount(INFINITE); animator.addUpdateListener(animation -> invalidate.run()); } void startAnimation() { animator.start(); } void stopAnimation() { animator.cancel(); } /** Determines the start coordinates of swipe animation. */ void updateGesturesCoordinates( int fingerCount, int canvasLength, Size screenSize, Direction swipeDirection) { gesturesCircleCoordinates.clear(); int gestureInterval = DISTANCE_BETWEEN_GESTURES_IN_PIXELS + 2 * dotRadiusInPixels; int distanceToStartPoint = (fingerCount - 1) * gestureInterval / 2; for (int i = 0; i < fingerCount; i++) { int x = 0; int y = 0; switch (swipeDirection) { case TOP_TO_BOTTOM: x = screenSize.getWidth() / 2 - distanceToStartPoint + i * gestureInterval; y = (screenSize.getHeight() - canvasLength) / 2; break; case BOTTOM_TO_TOP: x = screenSize.getWidth() / 2 - distanceToStartPoint + i * gestureInterval; y = (screenSize.getHeight() - canvasLength) / 2 + canvasLength; break; case LEFT_TO_RIGHT: x = (screenSize.getWidth() - canvasLength) / 2; y = screenSize.getHeight() / 2 - distanceToStartPoint + i * gestureInterval; break; case RIGHT_TO_LEFT: x = (screenSize.getWidth() - canvasLength) / 2 + canvasLength; y = screenSize.getHeight() / 2 - distanceToStartPoint + i * gestureInterval; break; } gesturesCircleCoordinates.add(new Point(x, y)); } } Rect determineGradientVariation(int canvasLength, Direction swipeDirection) { Rect gradientVariation = new Rect(); gradientVariation.left = gesturesCircleCoordinates.get(0).x - dotRadiusInPixels; gradientVariation.top = gesturesCircleCoordinates.get(0).y - dotRadiusInPixels; switch (swipeDirection) { case TOP_TO_BOTTOM: gradientVariation.right = gradientVariation.left; gradientVariation.bottom = gradientVariation.top + canvasLength; break; case BOTTOM_TO_TOP: gradientVariation.right = gradientVariation.left; gradientVariation.top = gesturesCircleCoordinates.get(0).y + dotRadiusInPixels; gradientVariation.bottom = gradientVariation.top - canvasLength; break; case LEFT_TO_RIGHT: gradientVariation.right = gradientVariation.left + canvasLength; gradientVariation.bottom = gradientVariation.top; break; case RIGHT_TO_LEFT: gradientVariation.left = gesturesCircleCoordinates.get(0).x + dotRadiusInPixels; gradientVariation.right = gradientVariation.left - canvasLength; gradientVariation.bottom = gradientVariation.top; break; } return gradientVariation; } void onDraw(Canvas canvas) { float range = (float) animator.getAnimatedValue(); for (Point point : gesturesCircleCoordinates) { switch (direction) { case TOP_TO_BOTTOM: canvas.drawRoundRect( point.x - dotRadiusInPixels, point.y - dotRadiusInPixels, point.x + dotRadiusInPixels, point.y + dotRadiusInPixels + range, dotRadiusInPixels, dotRadiusInPixels, roundRectPaint); canvas.drawCircle(point.x, point.y + range, dotRadiusInPixels, circlePaint); break; case BOTTOM_TO_TOP: canvas.drawRoundRect( point.x - dotRadiusInPixels, point.y + dotRadiusInPixels, point.x + dotRadiusInPixels, point.y - dotRadiusInPixels - range, dotRadiusInPixels, dotRadiusInPixels, roundRectPaint); canvas.drawCircle(point.x, point.y - range, dotRadiusInPixels, circlePaint); break; case LEFT_TO_RIGHT: canvas.drawRoundRect( point.x - dotRadiusInPixels, point.y - dotRadiusInPixels, point.x + dotRadiusInPixels + range, point.y + dotRadiusInPixels, dotRadiusInPixels, dotRadiusInPixels, roundRectPaint); canvas.drawCircle(point.x + range, point.y, dotRadiusInPixels, circlePaint); break; case RIGHT_TO_LEFT: canvas.drawRoundRect( point.x + dotRadiusInPixels, point.y - dotRadiusInPixels, point.x - dotRadiusInPixels - range, point.y + dotRadiusInPixels, dotRadiusInPixels, dotRadiusInPixels, roundRectPaint); canvas.drawCircle(point.x - range, point.y, dotRadiusInPixels, circlePaint); break; } } } } }
7,015
3,428
<filename>lib/node_modules/@stdlib/datasets/spam-assassin/data/easy-ham-2/00388.06d9471d9bb3270cc5caa33d267a1e9e.json {"id":"00388","group":"easy-ham-2","checksum":{"type":"MD5","value":"06d9471d9bb3270cc5caa33d267a1e9e"},"text":"From <EMAIL> Tue Aug 13 10:30:49 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: y<EMAIL>.netnoteinc.com\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 531344413F\n\tfor <jm@localhost>; Tue, 13 Aug 2002 05:22:24 -0400 (EDT)\nReceived: from phobos [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Tue, 13 Aug 2002 10:22:24 +0100 (IST)\nReceived: from lugh.tuatha.org (<EMAIL> [172.16.58.35]) by\n dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id g7D9K4b25113 for\n <<EMAIL>>; Tue, 13 Aug 2002 10:20:04 +0100\nReceived: from lugh (root@localhost [127.0.0.1]) by lugh.tuatha.org\n (8.9.3/8.9.3) with ESMTP id KAA04754; Tue, 13 Aug 2002 10:19:05 +0100\nX-Authentication-Warning: lugh.tuatha.org: Host root@localhost [127.0.0.1]\n claimed to be lugh\nReceived: from smtp014.mail.yahoo.com (smtp014.mail.yahoo.com\n [216.136.173.58]) by lugh.tuatha.org (8.9.3/8.9.3) with SMTP id KAA04713\n for <<EMAIL>>; Tue, 13 Aug 2002 10:18:56 +0100\nReceived: from unknown (HELO mfrenchw2k) ([email protected] with\n login) by smtp.mail.vip.sc5.yahoo.com with SMTP; 13 Aug 2002 09:18:55\n -0000\nMessage-Id: <<EMAIL>>\nFrom: \"<NAME>\" <<EMAIL>>\nTo: \"<NAME>\" <<EMAIL>>, <<EMAIL>>\nReferences: <<EMAIL>>\nSubject: Re: [ILUG] SUSE 8 disks? (thread changed slightly)\nDate: Tue, 13 Aug 2002 10:15:11 +0100\nMIME-Version: 1.0\nContent-Type: text/plain; charset=\"iso-8859-1\"\nContent-Transfer-Encoding: 7bit\nX-Priority: 3\nX-Msmail-Priority: Normal\nX-Mailer: Microsoft Outlook Express 6.00.2600.0000\nX-Mimeole: Produced By Microsoft MimeOLE V6.00.2600.0000\nSender: [email protected]\nErrors-To: [email protected]\nX-Mailman-Version: 1.1\nPrecedence: bulk\nList-Id: Irish Linux Users' Group <ilug.linux.ie>\nX-Beenthere: [email protected]\n\n<NAME> asked:\n> ...but maybe there is general interest in\n> an Irish distro.\n\nI have my own thoughts on this, and would be very keen to create yet another\nnew (and different) distro.\n\nOf course, it would require a minimum of EUR300,000 in funding, which is the\nreason I have not started this project myself... :(\n\n- Matthew\n\n\n__________________________________________________\nDo You Yahoo!?\nEverything you'll ever need on one web page\nfrom News and Sport to Email and Music Charts\nhttp://uk.my.yahoo.com\n\n\n-- \nIrish Linux Users' Group: [email protected]\nhttp://www.linux.ie/mailman/listinfo/ilug for (un)subscription information.\nList maintainer: listmaster<EMAIL>.ie\n\n\n"}
1,129
2,542
<reponame>AnthonyM/service-fabric // ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace Api; using namespace ServiceModel; // ******************************************************************************************************************** // ComAsyncOperationContext Classes // class ComInfrastructureServiceAgent::ComStartInfrastructureTaskAsyncOperation : public ComAsyncOperationContext { DENY_COPY(ComStartInfrastructureTaskAsyncOperation); public: ComStartInfrastructureTaskAsyncOperation( __in IInfrastructureServiceAgent & impl, FABRIC_INFRASTRUCTURE_TASK_DESCRIPTION * taskDescription) : ComAsyncOperationContext() , impl_(impl) , taskDescription_(taskDescription) , timeout_(TimeSpan::Zero) { } virtual ~ComStartInfrastructureTaskAsyncOperation() { } HRESULT Initialize( __in ComponentRootSPtr const & rootSPtr, __in DWORD timeoutMilliseconds, __in IFabricAsyncOperationCallback * callback) { HRESULT hr = this->ComAsyncOperationContext::Initialize(rootSPtr, callback); if (SUCCEEDED(hr)) { timeout_ = TimeSpan::FromMilliseconds(timeoutMilliseconds); } return hr; } static HRESULT End(__in IFabricAsyncOperationContext * context) { if (context == NULL) { return E_POINTER; } ComPointer<ComAsyncOperationContext> thisCPtr(context, IID_IFabricAsyncOperationContext); return thisCPtr->End(); } protected: virtual void OnStart(AsyncOperationSPtr const & proxySPtr) { auto operation = impl_.BeginStartInfrastructureTask( taskDescription_, timeout_, [this](AsyncOperationSPtr const & operation) { this->OnStartInfrastructureTaskComplete(operation, false); }, proxySPtr); this->OnStartInfrastructureTaskComplete(operation, true); } private: void OnStartInfrastructureTaskComplete(AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously) { if (operation->CompletedSynchronously != expectedCompletedSynchronously) { return; } ErrorCode error = impl_.EndStartInfrastructureTask(operation); this->TryComplete(operation->Parent, error.ToHResult()); } IInfrastructureServiceAgent & impl_; FABRIC_INFRASTRUCTURE_TASK_DESCRIPTION * taskDescription_; TimeSpan timeout_; }; class ComInfrastructureServiceAgent::ComFinishInfrastructureTaskAsyncOperation : public ComAsyncOperationContext { DENY_COPY(ComFinishInfrastructureTaskAsyncOperation); public: ComFinishInfrastructureTaskAsyncOperation( __in IInfrastructureServiceAgent & impl, wstring const & taskId, uint64 instanceId) : ComAsyncOperationContext() , impl_(impl) , taskId_(taskId) , instanceId_(instanceId) , timeout_(TimeSpan::Zero) { } virtual ~ComFinishInfrastructureTaskAsyncOperation() { } HRESULT Initialize( __in ComponentRootSPtr const & rootSPtr, __in DWORD timeoutMilliseconds, __in IFabricAsyncOperationCallback * callback) { HRESULT hr = this->ComAsyncOperationContext::Initialize(rootSPtr, callback); if (SUCCEEDED(hr)) { timeout_ = TimeSpan::FromMilliseconds(timeoutMilliseconds); } return hr; } static HRESULT End(__in IFabricAsyncOperationContext * context) { if (context == NULL) { return E_POINTER; } ComPointer<ComAsyncOperationContext> thisCPtr(context, IID_IFabricAsyncOperationContext); return thisCPtr->End(); } protected: virtual void OnStart(AsyncOperationSPtr const & proxySPtr) { auto operation = impl_.BeginFinishInfrastructureTask( taskId_, instanceId_, timeout_, [this](AsyncOperationSPtr const & operation) { this->OnFinishInfrastructureTaskComplete(operation, false); }, proxySPtr); this->OnFinishInfrastructureTaskComplete(operation, true); } private: void OnFinishInfrastructureTaskComplete(AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously) { if (operation->CompletedSynchronously != expectedCompletedSynchronously) { return; } ErrorCode error = impl_.EndFinishInfrastructureTask(operation); this->TryComplete(operation->Parent, error.ToHResult()); } IInfrastructureServiceAgent & impl_; wstring taskId_; uint64 instanceId_; TimeSpan timeout_; }; // {34a16309-07f5-49c6-bac9-626d181a2e52} static const GUID CLSID_ComQueryInfrastructureTaskAsyncOperation = { 0x34a16309, 0x07f5, 0x49c6, { 0xba, 0xc9, 0x62, 0x6d, 0x18, 0x1a, 0x2e, 0x52 } }; class ComInfrastructureServiceAgent::ComQueryInfrastructureTaskAsyncOperation : public ComAsyncOperationContext { DENY_COPY(ComQueryInfrastructureTaskAsyncOperation); COM_INTERFACE_AND_DELEGATE_LIST( ComQueryInfrastructureTaskAsyncOperation, CLSID_ComQueryInfrastructureTaskAsyncOperation, ComQueryInfrastructureTaskAsyncOperation, ComAsyncOperationContext) public: ComQueryInfrastructureTaskAsyncOperation( __in IInfrastructureServiceAgent & impl) : ComAsyncOperationContext() , impl_(impl) , timeout_(TimeSpan::Zero) { } virtual ~ComQueryInfrastructureTaskAsyncOperation() { } HRESULT Initialize( __in ComponentRootSPtr const & rootSPtr, __in DWORD timeoutMilliseconds, __in IFabricAsyncOperationCallback * callback) { HRESULT hr = this->ComAsyncOperationContext::Initialize(rootSPtr, callback); if (SUCCEEDED(hr)) { timeout_ = TimeSpan::FromMilliseconds(timeoutMilliseconds); } return hr; } static HRESULT End(__in IFabricAsyncOperationContext * context, __out IFabricInfrastructureTaskQueryResult ** result) { if ((context == NULL) || (result == NULL)) { return E_POINTER; } ComPointer<ComQueryInfrastructureTaskAsyncOperation> thisCPtr(context, CLSID_ComQueryInfrastructureTaskAsyncOperation); auto hr = thisCPtr->Result; if (SUCCEEDED(hr)) { vector<InfrastructureTaskQueryResult> resultList; auto error = thisCPtr->nativeResult_.MoveList(resultList); if (error.IsSuccess()) { ComPointer<IFabricInfrastructureTaskQueryResult> cPtr = make_com<ComQueryResult, IFabricInfrastructureTaskQueryResult>(move(resultList)); hr = cPtr->QueryInterface(IID_IFabricInfrastructureTaskQueryResult, reinterpret_cast<void**>(result)); } else { hr = error.ToHResult(); } } return hr; } protected: virtual void OnStart(AsyncOperationSPtr const & proxySPtr) { auto operation = impl_.BeginQueryInfrastructureTask( timeout_, [this](AsyncOperationSPtr const & operation) { this->OnQueryInfrastructureTaskComplete(operation, false); }, proxySPtr); this->OnQueryInfrastructureTaskComplete(operation, true); } private: void OnQueryInfrastructureTaskComplete(AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously) { if (operation->CompletedSynchronously != expectedCompletedSynchronously) { return; } auto error = impl_.EndQueryInfrastructureTask(operation, nativeResult_); this->TryComplete(operation->Parent, error.ToHResult()); } IInfrastructureServiceAgent & impl_; QueryResult nativeResult_; TimeSpan timeout_; }; class ComInfrastructureServiceAgent::ComQueryResult : public IFabricInfrastructureTaskQueryResult , private Common::ComUnknownBase { DENY_COPY_ASSIGNMENT(ComQueryResult) BEGIN_COM_INTERFACE_LIST(ComQueryResult) COM_INTERFACE_ITEM(IID_IUnknown,IFabricInfrastructureTaskQueryResult) COM_INTERFACE_ITEM(IID_IFabricInfrastructureTaskQueryResult,IFabricInfrastructureTaskQueryResult) END_COM_INTERFACE_LIST() public: explicit ComQueryResult(vector<InfrastructureTaskQueryResult> && resultList) { queryResult_ = heap_.AddItem<FABRIC_INFRASTRUCTURE_TASK_QUERY_RESULT_LIST>(); auto array = heap_.AddArray<FABRIC_INFRASTRUCTURE_TASK_QUERY_RESULT_ITEM>(resultList.size()); queryResult_->Count = static_cast<ULONG>(resultList.size()); queryResult_->Items = array.GetRawArray(); for (size_t ix = 0; ix < resultList.size(); ++ix) { FABRIC_INFRASTRUCTURE_TASK_QUERY_RESULT_ITEM * arrayItem = &array[ix]; InfrastructureTaskQueryResult const & listItem = resultList[ix]; arrayItem->Description = heap_.AddItem<FABRIC_INFRASTRUCTURE_TASK_DESCRIPTION>().GetRawPointer(); listItem.Description.ToPublicApi(heap_, *arrayItem->Description); arrayItem->State = Management::ClusterManager::InfrastructureTaskState::ToPublicApi(listItem.State); } } const FABRIC_INFRASTRUCTURE_TASK_QUERY_RESULT_LIST * STDMETHODCALLTYPE get_Result(void) { return queryResult_.GetRawPointer(); } private: Common::ScopedHeap heap_; Common::ReferencePointer<FABRIC_INFRASTRUCTURE_TASK_QUERY_RESULT_LIST> queryResult_; }; // ******************************************************************************************************************** // ComInfrastructureServiceAgent::ComInfrastructureServiceAgent Implementation // ComInfrastructureServiceAgent::ComInfrastructureServiceAgent(IInfrastructureServiceAgentPtr const & impl) : IFabricInfrastructureServiceAgent() , ComUnknownBase() , impl_(impl) { } ComInfrastructureServiceAgent::~ComInfrastructureServiceAgent() { // Break lifetime cycle between ISAgent and ServiceRoutingAgentProxy impl_->Release(); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::RegisterInfrastructureServiceFactory( IFabricStatefulServiceFactory * factory) { return ComUtility::OnPublicApiReturn(impl_->RegisterInfrastructureServiceFactory(factory).ToHResult()); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::RegisterInfrastructureService( FABRIC_PARTITION_ID partitionId, FABRIC_REPLICA_ID replicaId, IFabricInfrastructureService * comInterface, IFabricStringResult ** serviceAddress) { if (serviceAddress == NULL) { return ComUtility::OnPublicApiReturn(E_POINTER); } wstring serviceAddressResult; impl_->RegisterInfrastructureService( partitionId, replicaId, WrapperFactory::create_rooted_com_proxy(comInterface), serviceAddressResult); auto result = make_com<ComStringResult, IFabricStringResult>(serviceAddressResult); *serviceAddress = result.DetachNoRelease(); return ComUtility::OnPublicApiReturn(S_OK); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::UnregisterInfrastructureService( FABRIC_PARTITION_ID partitionId, FABRIC_REPLICA_ID replicaId) { impl_->UnregisterInfrastructureService(partitionId, replicaId); return ComUtility::OnPublicApiReturn(S_OK); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::BeginStartInfrastructureTask( /* [in] */ FABRIC_INFRASTRUCTURE_TASK_DESCRIPTION * taskDescription, /* [in] */ DWORD timeoutMilliseconds, /* [in] */ IFabricAsyncOperationCallback * callback, /* [out, retval] */ IFabricAsyncOperationContext ** context) { auto operation = make_com<ComStartInfrastructureTaskAsyncOperation>(*impl_.get(), taskDescription); HRESULT hr = operation->Initialize( impl_.get_Root(), timeoutMilliseconds, callback); if (FAILED(hr)) { return ComUtility::OnPublicApiReturn(hr); } return ComUtility::OnPublicApiReturn(ComAsyncOperationContext::StartAndDetach(move(operation), context)); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::EndStartInfrastructureTask( /* [in] */ IFabricAsyncOperationContext * context) { return ComUtility::OnPublicApiReturn(ComStartInfrastructureTaskAsyncOperation::End(context)); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::BeginFinishInfrastructureTask( /* [in] */ LPCWSTR taskId, /* [in] */ ULONGLONG instanceId, /* [in] */ DWORD timeoutMilliseconds, /* [in] */ IFabricAsyncOperationCallback * callback, /* [out, retval] */ IFabricAsyncOperationContext ** context) { wstring parsedTaskId; HRESULT hr = StringUtility::LpcwstrToWstring(taskId, false, parsedTaskId); if (FAILED(hr)) { return ComUtility::OnPublicApiReturn(hr); } auto operation = make_com<ComFinishInfrastructureTaskAsyncOperation>(*impl_.get(), parsedTaskId, instanceId); hr = operation->Initialize( impl_.get_Root(), timeoutMilliseconds, callback); if (FAILED(hr)) { return ComUtility::OnPublicApiReturn(hr); } return ComUtility::OnPublicApiReturn(ComAsyncOperationContext::StartAndDetach(move(operation), context)); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::EndFinishInfrastructureTask( /* [in] */ IFabricAsyncOperationContext * context) { return ComUtility::OnPublicApiReturn(ComFinishInfrastructureTaskAsyncOperation::End(context)); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::BeginQueryInfrastructureTask( /* [in] */ DWORD timeoutMilliseconds, /* [in] */ IFabricAsyncOperationCallback * callback, /* [out, retval] */ IFabricAsyncOperationContext ** context) { auto operation = make_com<ComQueryInfrastructureTaskAsyncOperation>(*impl_.get()); auto hr = operation->Initialize( impl_.get_Root(), timeoutMilliseconds, callback); if (FAILED(hr)) { return ComUtility::OnPublicApiReturn(hr); } return ComUtility::OnPublicApiReturn(ComAsyncOperationContext::StartAndDetach(move(operation), context)); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::EndQueryInfrastructureTask( /* [in] */ IFabricAsyncOperationContext * context, /* [out, retval] */ IFabricInfrastructureTaskQueryResult ** result) { return ComUtility::OnPublicApiReturn(ComQueryInfrastructureTaskAsyncOperation::End(context, result)); }
5,284
3,172
<reponame>jkren6/PARL<filename>examples/NeurIPS2018-AI-for-Prosthetics-Challenge/final_submit/test.py # Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import numpy as np import time from env_wrapper import FrameSkip, ActionScale, PelvisBasedObs, ForwardReward from osim.env import ProstheticsEnv from parl.utils import logger from submit_model import SubmitModel def play_multi_episode(submit_model, episode_num=2, vis=False, seed=0): np.random.seed(seed) env = ProstheticsEnv(visualize=vis) env.change_model(model='3D', difficulty=1, prosthetic=True, seed=seed) env = ForwardReward(env) env = FrameSkip(env, 4) env = ActionScale(env) env = PelvisBasedObs(env) all_reward = [] all_shaping_reward = 0 last_frames_count = 0 for e in range(episode_num): t = time.time() episode_reward = 0.0 episode_shaping_reward = 0.0 observation = env.reset(project=False) target_change_times = 0 step = 0 loss = [] while True: step += 1 action = submit_model.pred_batch(observation, target_change_times) observation, reward, done, info = env.step(action, project=False) step_frames = info['frame_count'] - last_frames_count last_frames_count = info['frame_count'] episode_reward += reward # we pacle it here to drop the first step after changing if target_change_times >= 1: loss.append(10 * step_frames - reward) if info['target_changed']: target_change_times = min(target_change_times + 1, 3) logger.info("[step/{}]reward:{} info:{}".format( step, reward, info)) episode_shaping_reward += info['shaping_reward'] if done: break all_reward.append(episode_reward) all_shaping_reward += episode_shaping_reward t = time.time() - t logger.info( "[episode/{}] time: {} episode_reward:{} change_loss:{} after_change_loss:{} mean_reward:{}" .format(e, t, episode_reward, np.sum(loss[:15]), np.sum(loss[15:]), np.mean(all_reward))) logger.info("Mean reward:{}".format(np.mean(all_reward))) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--use_cuda', action="store_true", help='If set, will run in gpu 0') parser.add_argument( '--vis', action="store_true", help='If set, will visualize.') parser.add_argument('--seed', type=int, default=0, help='Random seed.') parser.add_argument( '--episode_num', type=int, default=1, help='Episode number to run.') args = parser.parse_args() submit_model = SubmitModel(use_cuda=args.use_cuda) play_multi_episode( submit_model, episode_num=args.episode_num, vis=args.vis, seed=args.seed)
1,435
1,545
<filename>bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookies/MetaFormatCommand.java /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.bookkeeper.tools.cli.commands.bookies; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; /** * Format the bookkeeper metadata present in zookeeper. */ public class MetaFormatCommand extends BookieCommand<MetaFormatCommand.MetaFormatFlags> { private static final String NAME = "metaformat"; private static final String DESC = "Format bookkeeper metadata in zookeeper."; public MetaFormatCommand() { this(new MetaFormatFlags()); } private MetaFormatCommand(MetaFormatFlags flags) { super(CliSpec.<MetaFormatCommand.MetaFormatFlags>newBuilder() .withName(NAME) .withDescription(DESC) .withFlags(flags) .build()); } /** * Flags for command meta format. */ @Accessors(fluent = true) @Setter public static class MetaFormatFlags extends CliFlags { @Parameter(names = { "-n", "nonInteractive" }, description = "Whether to confirm old data exists..?") private boolean interactive; @Parameter(names = {"-f", "--force"}, description = "If [nonInteractive] is specified, then whether to force delete the old data without prompt.") private boolean force; } @Override public boolean apply(ServerConfiguration conf, MetaFormatFlags flags) { try { return BookKeeperAdmin.format(conf, flags.interactive, flags.force); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } } }
934
1,093
<gh_stars>1000+ /* * Copyright 2002-2021 the original author or 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 * * https://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.springframework.integration.file.filters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; /** * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> */ public class CompositeFileListFilterTests { @SuppressWarnings("unchecked") private final FileListFilter<File> fileFilterMock1 = mock(FileListFilter.class); @SuppressWarnings("unchecked") private final FileListFilter<File> fileFilterMock2 = mock(FileListFilter.class); private final File fileMock = mock(File.class); @Test public void forwardedToFilters() throws Exception { CompositeFileListFilter<File> compositeFileFilter = new CompositeFileListFilter<>(); compositeFileFilter.addFilter(fileFilterMock1); compositeFileFilter.addFilter(fileFilterMock2); List<File> returnedFiles = Collections.singletonList(fileMock); when(fileFilterMock1.filterFiles(isA(File[].class))).thenReturn(returnedFiles); when(fileFilterMock2.filterFiles(isA(File[].class))).thenReturn(returnedFiles); assertThat(compositeFileFilter.filterFiles(new File[]{ fileMock })).isEqualTo(returnedFiles); verify(fileFilterMock1).filterFiles(isA(File[].class)); verify(fileFilterMock2).filterFiles(isA(File[].class)); compositeFileFilter.close(); } @Test public void forwardedToAddedFilters() throws Exception { CompositeFileListFilter<File> compositeFileFilter = new CompositeFileListFilter<>(); compositeFileFilter.addFilter(fileFilterMock1); compositeFileFilter.addFilter(fileFilterMock2); List<File> returnedFiles = Collections.singletonList(fileMock); when(fileFilterMock1.filterFiles(isA(File[].class))).thenReturn(returnedFiles); when(fileFilterMock2.filterFiles(isA(File[].class))).thenReturn(returnedFiles); assertThat(compositeFileFilter.filterFiles(new File[]{ fileMock })).isEqualTo(returnedFiles); verify(fileFilterMock1).filterFiles(isA(File[].class)); verify(fileFilterMock2).filterFiles(isA(File[].class)); compositeFileFilter.close(); } @Test public void negative() throws Exception { CompositeFileListFilter<File> compositeFileFilter = new CompositeFileListFilter<>(); compositeFileFilter.addFilter(fileFilterMock1); compositeFileFilter.addFilter(fileFilterMock2); when(fileFilterMock2.filterFiles(isA(File[].class))).thenReturn(new ArrayList<>()); when(fileFilterMock1.filterFiles(isA(File[].class))).thenReturn(new ArrayList<>()); assertThat(compositeFileFilter.filterFiles(new File[]{ fileMock }).isEmpty()).isTrue(); compositeFileFilter.close(); } @Test public void excludeFromLaterFilters() throws Exception { CompositeFileListFilter<File> compositeFileFilter = new ChainFileListFilter<>(); compositeFileFilter.addFilter(this.fileFilterMock1); compositeFileFilter.addFilter(this.fileFilterMock2); List<File> noFiles = new ArrayList<>(); when(this.fileFilterMock1.filterFiles(isA(File[].class))).thenReturn(noFiles); assertThat(compositeFileFilter.filterFiles(new File[]{ this.fileMock })).isEqualTo(noFiles); verify(fileFilterMock1).filterFiles(isA(File[].class)); verify(fileFilterMock2, never()).filterFiles(isA(File[].class)); compositeFileFilter.close(); } @Test public void singleFileCapableUO() throws IOException { CompositeFileListFilter<String> compo = new CompositeFileListFilter<>(Collections.singletonList(new FileListFilter<String>() { @Override public List<String> filterFiles(String[] files) { return Collections.emptyList(); } @Override public boolean supportsSingleFileFiltering() { return true; } })); assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> compo.accept("foo")); compo.close(); } @Test public void singleFileCapable() throws IOException { CompositeFileListFilter<String> compo = new CompositeFileListFilter<>(Collections.singletonList(new FileListFilter<String>() { @Override public List<String> filterFiles(String[] files) { return Collections.emptyList(); } @Override public boolean supportsSingleFileFiltering() { return true; } @Override public boolean isForRecursion() { return true; } @Override public boolean accept(String file) { return true; } })); assertThat(compo.accept("foo")).isTrue(); compo.addFilter(s -> null); assertThat(compo.supportsSingleFileFiltering()).isFalse(); assertThat(compo.isForRecursion()).isTrue(); compo.close(); } @Test public void notSingleFileCapable() throws IOException { CompositeFileListFilter<String> compo = new CompositeFileListFilter<>(Collections.singletonList(s -> null)); assertThat(compo.supportsSingleFileFiltering()).isFalse(); assertThat(compo.isForRecursion()).isFalse(); compo.close(); } }
2,018
14,668
<filename>third_party/blink/renderer/bindings/scripts/bind_gen/code_node_cxx_test.py # Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from .code_node import SymbolNode from .code_node import SymbolScopeNode from .code_node import TextNode from .code_node import render_code_node from .code_node_cxx import CxxClassDefNode from .code_node_cxx import CxxFuncDefNode from .code_node_cxx import CxxLikelyIfNode from .code_node_cxx import CxxUnlikelyIfNode from .codegen_accumulator import CodeGenAccumulator from .mako_renderer import MakoRenderer class CodeNodeCxxTest(unittest.TestCase): def setUp(self): super(CodeNodeCxxTest, self).setUp() self.addTypeEqualityFunc(str, self.assertMultiLineEqual) def assertRenderResult(self, node, expected): if node.renderer is None: node.set_renderer(MakoRenderer()) if node.accumulator is None: node.set_accumulator(CodeGenAccumulator()) def simplify(text): return "\n".join( [" ".join(line.split()) for line in text.split("\n")]) actual = simplify(render_code_node(node)) expected = simplify(expected) self.assertEqual(actual, expected) def test_symbol_definition_with_branches(self): root = SymbolScopeNode() root.register_code_symbols([ SymbolNode("var1", "int ${var1} = 1;"), SymbolNode("var2", "int ${var2} = 2;"), SymbolNode("var3", "int ${var3} = 3;"), SymbolNode("var4", "int ${var4} = 4;"), SymbolNode("var5", "int ${var5} = 5;"), SymbolNode("var6", "int ${var6} = 6;"), ]) root.extend([ TextNode("${var1};"), CxxUnlikelyIfNode( cond=TextNode("${var2}"), body=[ TextNode("${var3};"), TextNode("return ${var4};"), ]), CxxLikelyIfNode( cond=TextNode("${var5}"), body=[ TextNode("return ${var6};"), ]), TextNode("${var3};"), ]) self.assertRenderResult( root, """\ int var1 = 1; var1; int var2 = 2; int var3 = 3; if (var2) { var3; int var4 = 4; return var4; } int var5 = 5; if (var5) { int var6 = 6; return var6; } var3;\ """) def test_symbol_definition_with_nested_branches(self): root = SymbolScopeNode() root.register_code_symbols([ SymbolNode("var1", "int ${var1} = 1;"), SymbolNode("var2", "int ${var2} = 2;"), SymbolNode("var3", "int ${var3} = 3;"), SymbolNode("var4", "int ${var4} = 4;"), SymbolNode("var5", "int ${var5} = 5;"), SymbolNode("var6", "int ${var6} = 6;"), ]) root.extend([ CxxUnlikelyIfNode( cond=TextNode("false"), body=[ CxxUnlikelyIfNode( cond=TextNode("false"), body=[ TextNode("return ${var1};"), ]), TextNode("return;"), ]), CxxLikelyIfNode( cond=TextNode("true"), body=[ CxxLikelyIfNode( cond=TextNode("true"), body=[ TextNode("return ${var2};"), ]), TextNode("return;"), ]), ]) self.assertRenderResult( root, """\ if (false) { if (false) { int var1 = 1; return var1; } return; } if (true) { if (true) { int var2 = 2; return var2; } return; }\ """) def test_function_definition_minimum(self): root = CxxFuncDefNode( name="blink::bindings::func", arg_decls=[], return_type="void") self.assertRenderResult(root, """\ void blink::bindings::func() { }\ """) def test_function_definition_full(self): root = CxxFuncDefNode( name="blink::bindings::func", arg_decls=["int arg1", "int arg2"], return_type="void", const=True, override=True, member_initializer_list=[ "member1(0)", "member2(\"str\")", ]) root.body.register_code_symbols([ SymbolNode("var1", "int ${var1} = 1;"), SymbolNode("var2", "int ${var2} = 2;"), ]) root.body.extend([ CxxUnlikelyIfNode( cond=TextNode("${var1}"), body=[TextNode("return ${var1};")]), TextNode("return ${var2};"), ]) self.assertRenderResult( root, """\ void blink::bindings::func(int arg1, int arg2) const override\ : member1(0), member2("str") { int var1 = 1; if (var1) { return var1; } int var2 = 2; return var2; }\ """) def test_class_definition(self): root = CxxClassDefNode("X", ["A", "B"], final=True) root.public_section.extend([ TextNode("void m1();"), TextNode("void m2();"), ]) root.private_section.extend([ TextNode("int m1_;"), TextNode("int m2_;"), ]) self.assertRenderResult( root, """\ class X final : public A, public B { public: void m1(); void m2(); private: int m1_; int m2_; };\ """)
2,877
868
<filename>tests/activemq5-unit-tests/src/test/java/org/apache/activemq/load/LoadClient.java<gh_stars>100-1000 /** * 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.activemq.load; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.DeliveryMode; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.Session; import javax.jms.TextMessage; import org.apache.activemq.ActiveMQMessageAudit; import org.apache.activemq.perf.PerfRate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * */ public class LoadClient implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(LoadClient.class); protected static int SLEEP_TIME = 2; protected String name; protected ConnectionFactory factory; protected Connection connection; protected Destination startDestination; protected Destination nextDestination; protected Session session; protected MessageConsumer consumer; protected MessageProducer producer; protected PerfRate rate = new PerfRate(); protected int deliveryMode = DeliveryMode.PERSISTENT; protected ActiveMQMessageAudit audit = new ActiveMQMessageAudit(); protected boolean connectionPerMessage = false; protected boolean running; protected int timeout = 10000; public LoadClient(String name, ConnectionFactory factory) { this.name = name; this.factory = factory; } public synchronized void start() throws JMSException { if (!running) { rate.reset(); running = true; if (!connectionPerMessage) { connection = factory.createConnection(); connection.start(); session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); consumer = session.createConsumer(getConsumeDestination()); producer = session.createProducer(getSendDestination()); producer.setDeliveryMode(this.deliveryMode); } Thread t = new Thread(this); t.setName(name); t.start(); } } public void stop() throws JMSException, InterruptedException { running = false; if (connection != null) { connection.stop(); } } @Override public void run() { try { while (running) { String result = consume(); if (result != null) { send(result); rate.increment(); } else if (running) { LOG.error(name + " Failed to consume!"); } } } catch (Throwable e) { e.printStackTrace(); } } protected String consume() throws Exception { Connection con = null; MessageConsumer c = consumer; if (connectionPerMessage) { con = factory.createConnection(); con.start(); Session s = con.createSession(false, Session.AUTO_ACKNOWLEDGE); c = s.createConsumer(getConsumeDestination()); } TextMessage result = (TextMessage) c.receive(timeout); if (result != null) { if (audit.isDuplicate(result.getJMSMessageID())) { throw new JMSException("Received duplicate " + result.getText()); } if (!audit.isInOrder(result.getJMSMessageID())) { throw new JMSException("Out of order " + result.getText()); } if (connectionPerMessage) { Thread.sleep(SLEEP_TIME);//give the broker a chance con.close(); } } return result != null ? result.getText() : null; } protected void send(String text) throws Exception { Connection con = connection; MessageProducer p = producer; Session s = session; if (connectionPerMessage) { con = factory.createConnection(); con.start(); s = con.createSession(false, Session.AUTO_ACKNOWLEDGE); p = s.createProducer(getSendDestination()); p.setDeliveryMode(deliveryMode); } TextMessage message = s.createTextMessage(text); p.send(message); if (connectionPerMessage) { Thread.sleep(SLEEP_TIME);//give the broker a chance con.close(); } } public String getName() { return name; } public void setName(String name) { this.name = name; } public Destination getStartDestination() { return startDestination; } public void setStartDestination(Destination startDestination) { this.startDestination = startDestination; } public Destination getNextDestination() { return nextDestination; } public void setNextDestination(Destination nextDestination) { this.nextDestination = nextDestination; } public int getDeliveryMode() { return deliveryMode; } public void setDeliveryMode(int deliveryMode) { this.deliveryMode = deliveryMode; } public boolean isConnectionPerMessage() { return connectionPerMessage; } public void setConnectionPerMessage(boolean connectionPerMessage) { this.connectionPerMessage = connectionPerMessage; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } protected Destination getSendDestination() { return nextDestination; } protected Destination getConsumeDestination() { return startDestination; } }
2,264
2,962
<filename>storio-sqlite-annotations-processor-test/src/test/resources/BoxedTypesMethodsFactoryMethodSQLiteTypeMapping.java package com.pushtorefresh.storio3.sqlite.annotations; import com.pushtorefresh.storio3.sqlite.SQLiteTypeMapping; /** * Generated mapping with collection of resolvers. */ public class BoxedTypesMethodsFactoryMethodSQLiteTypeMapping extends SQLiteTypeMapping<BoxedTypesMethodsFactoryMethod> { public BoxedTypesMethodsFactoryMethodSQLiteTypeMapping() { super(new BoxedTypesMethodsFactoryMethodStorIOSQLitePutResolver(), new BoxedTypesMethodsFactoryMethodStorIOSQLiteGetResolver(), new BoxedTypesMethodsFactoryMethodStorIOSQLiteDeleteResolver()); } }
241
974
// Blend2D - 2D Vector Graphics Powered by a JIT Compiler // // * Official Blend2D Home Page: https://blend2d.com // * Official Github Repository: https://github.com/blend2d/blend2d // // Copyright (c) 2017-2020 The Blend2D Authors // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. #ifndef BLEND2D_RASTER_RASTERWORKDATA_P_H_INCLUDED #define BLEND2D_RASTER_RASTERWORKDATA_P_H_INCLUDED #include "../geometry_p.h" #include "../image.h" #include "../path.h" #include "../region.h" #include "../zeroallocator_p.h" #include "../zoneallocator_p.h" #include "../raster/edgebuilder_p.h" #include "../raster/rasterdefs_p.h" //! \cond INTERNAL //! \addtogroup blend2d_internal_raster //! \{ // ============================================================================ // [Forward Declarations] // ============================================================================ class BLRasterContextImpl; class BLRasterWorkBatch; // ============================================================================ // [BLRasterWorkData] // ============================================================================ //! Provides data used by both single-threaded and multi-threaded render command //! processing. Single-threaded rendering context uses this data synchronously //! to process commands that are required before using pipelines. Multi-threaded //! rendering context uses 1 + N WorkData instances, where the first one can be //! used synchronously by the rendering context to perform synchronous tasks //! while the remaining WorkData is used per worker thread. class BLRasterWorkData { public: BL_NONCOPYABLE(BLRasterWorkData) enum : uint32_t { kSyncWorkerId = 0xFFFFFFFFu }; enum : size_t { kEdgeListSize = sizeof(BLEdgeList<int>) }; //! Rendering context impl. BLRasterContextImpl* ctxI; //! Batch data to process in case this data is used in a worker thread. BLRasterWorkBatch* batch; //! Context data used by pipelines (either the destination data or layer). BLPipeContextData ctxData; //! Clip mode. uint8_t clipMode; //! Reserved. uint8_t reserved[3]; //! Id of the worker that uses this WorkData. uint32_t _workerId; //! Band height. uint32_t _bandHeight; //! Accumulated error flags. uint32_t _accumulatedErrorFlags; //! Temporary paths. BLPath tmpPath[4]; //! Temporary glyph buffer used by high-level text rendering calls. BLGlyphBuffer glyphBuffer; //! Zone memory used by the worker context. BLZoneAllocator workZone; //! The last state of the zone to be reverted to in case of failure. BLZoneAllocator::StatePtr workState; //! Zero memory filled by rasterizers and zeroed back by pipelines. BLZeroBuffer zeroBuffer; //! Edge storage. BLEdgeStorage<int> edgeStorage; //! Edge builder. BLEdgeBuilder<int> edgeBuilder; explicit BLRasterWorkData(BLRasterContextImpl* ctxI, uint32_t workerId = kSyncWorkerId) noexcept; ~BLRasterWorkData() noexcept; // NOTE: `initContextData()` is called after `initBandData()` in `blRasterContextImplAttach()`. BL_INLINE void initContextData(const BLImageData& dstData) noexcept { ctxData.dst = dstData; } BLResult initBandData(uint32_t bandHeight, uint32_t bandCount) noexcept; BL_INLINE bool isSync() const noexcept { return _workerId == kSyncWorkerId; } BL_INLINE const BLSizeI& dstSize() const noexcept { return ctxData.dst.size; } BL_INLINE uint32_t workerId() const noexcept { return _workerId; } BL_INLINE uint32_t bandHeight() const noexcept { return _bandHeight; } BL_INLINE uint32_t bandCount() const noexcept { return edgeStorage.bandCount(); } BL_INLINE uint32_t accumulatedErrorFlags() const noexcept { return _accumulatedErrorFlags; } BL_INLINE void cleanAccumulatedErrorFlags() noexcept { _accumulatedErrorFlags = 0; } BL_INLINE void startOver() noexcept { workZone.clear(); } BL_INLINE void saveState() noexcept { workState = workZone.saveState(); } BL_INLINE void revertEdgeBuilder() noexcept { edgeBuilder.mergeBoundingBox(); edgeStorage.clear(); workZone.restoreState(workState); } //! Accumulates the error result into error flags of this work-data. Used by //! both synchronous and asynchronous rendering context to accumulate errors //! that may happen during the rendering. BLResult accumulateError(BLResult error) noexcept; }; //! \} //! \endcond #endif // BLEND2D_RASTER_RASTERWORKDATA_P_H_INCLUDED
1,551
306
from . import data from . import metrics from . import models from . import train from . import util
25
995
package zemberek.morphology.analysis; import static zemberek.core.turkish.PhoneticAttribute.LastLetterVoiceless; import static zemberek.core.turkish.PhoneticAttribute.LastLetterVowel; import static zemberek.core.turkish.PhoneticAttribute.LastVowelBack; import static zemberek.core.turkish.PhoneticAttribute.LastVowelFrontal; import static zemberek.core.turkish.PhoneticAttribute.LastVowelRounded; import static zemberek.core.turkish.PhoneticAttribute.LastVowelUnrounded; import java.util.Iterator; import java.util.NoSuchElementException; import zemberek.core.turkish.PhoneticAttribute; import zemberek.core.turkish.TurkishAlphabet; import zemberek.morphology.morphotactics.AttributeSet; import zemberek.morphology.morphotactics.Morpheme; import zemberek.morphology.morphotactics.MorphemeState; import zemberek.morphology.morphotactics.MorphemeTransition; import zemberek.morphology.morphotactics.SuffixTransition; import zemberek.morphology.morphotactics.TurkishMorphotactics; // TODO: find a better name. Move some methods outside. // not a transition. public class SurfaceTransition { public final String surface; // TODO: this can be removed if SearchPath contains StemTransition. public final MorphemeTransition lexicalTransition; public SurfaceTransition(String surface, MorphemeTransition transition) { this.surface = surface; this.lexicalTransition = transition; } public boolean isDerivative() { return lexicalTransition.to.derivative; } public MorphemeState getState() { return lexicalTransition.to; } public Morpheme getMorpheme() { return lexicalTransition.to.morpheme; } public boolean isDerivationalOrRoot() { return getState().derivative || getState().posRoot; } @Override public String toString() { return surfaceString() + getState().id; } public String toMorphemeString() { return surfaceString() + getState().morpheme.id; } private String surfaceString() { return surface.isEmpty() ? "" : surface + ":"; } static TurkishAlphabet alphabet = TurkishAlphabet.INSTANCE; public static String generateSurface( SuffixTransition transition, AttributeSet<PhoneticAttribute> phoneticAttributes) { String cached = transition.getFromSurfaceCache(phoneticAttributes); if (cached != null) { return cached; } StringBuilder sb = new StringBuilder(); int index = 0; for (SuffixTemplateToken token : transition.getTokenList()) { AttributeSet<PhoneticAttribute> attrs = AttributesHelper.getMorphemicAttributes(sb, phoneticAttributes); switch (token.type) { case LETTER: sb.append(token.letter); break; case A_WOVEL: // TODO: document line below. if (index == 0 && phoneticAttributes.contains(LastLetterVowel)) { break; } if (attrs.contains(LastVowelBack)) { sb.append('a'); } else if (attrs.contains(LastVowelFrontal)) { sb.append('e'); } else { throw new IllegalArgumentException("Cannot generate A form! "); } break; case I_WOVEL: // TODO: document line below. With templates like +Im this would not be necessary if (index == 0 && phoneticAttributes.contains(LastLetterVowel)) { break; } if (attrs.contains(LastVowelFrontal) && attrs.contains(LastVowelUnrounded)) { sb.append('i'); } else if (attrs.contains(LastVowelBack) && attrs.contains(LastVowelUnrounded)) { sb.append('ı'); } else if (attrs.contains(LastVowelBack) && attrs.contains(LastVowelRounded)) { sb.append('u'); } else if (attrs.contains(LastVowelFrontal) && attrs.contains(LastVowelRounded)) { sb.append('ü'); } else { throw new IllegalArgumentException("Cannot generate I form!"); } break; case APPEND: if (attrs.contains(LastLetterVowel)) { sb.append(token.letter); } break; case DEVOICE_FIRST: char ld = token.letter; if (attrs.contains(LastLetterVoiceless)) { ld = alphabet.devoice(ld); } sb.append(ld); break; case LAST_VOICED: case LAST_NOT_VOICED: ld = token.letter; sb.append(ld); break; } index++; } String s = sb.toString(); transition.addToSurfaceCache(phoneticAttributes, s); return s; } public enum TemplateTokenType { I_WOVEL, A_WOVEL, DEVOICE_FIRST, //VOICE_LAST, LAST_VOICED, LAST_NOT_VOICED, APPEND, LETTER } public static class SuffixTemplateToken { TemplateTokenType type; char letter; boolean append = false; private SuffixTemplateToken(TemplateTokenType type, char letter) { this.type = type; this.letter = letter; } private SuffixTemplateToken(TemplateTokenType type, char letter, boolean append) { this.type = type; this.letter = letter; this.append = append; } public TemplateTokenType getType() { return type; } public char getLetter() { return letter; } } // TODO: consider making templates like "+Im" possible. Also change + syntax to () public static class SuffixTemplateTokenizer implements Iterator<SuffixTemplateToken> { private final String generationWord; private int pointer; public SuffixTemplateTokenizer(String generationWord) { this.generationWord = generationWord; } public boolean hasNext() { return generationWord != null && pointer < generationWord.length(); } public SuffixTemplateToken next() { if (!hasNext()) { throw new NoSuchElementException("no elements left!"); } char c = generationWord.charAt(pointer++); char cNext = 0; if (pointer < generationWord.length()) { cNext = generationWord.charAt(pointer); } char undefined = (char) 0; switch (c) { case '+': pointer++; if (cNext == 'I') { return new SuffixTemplateToken(TemplateTokenType.I_WOVEL, undefined, true); } else if (cNext == 'A') { return new SuffixTemplateToken(TemplateTokenType.A_WOVEL, undefined, true); } else { return new SuffixTemplateToken(TemplateTokenType.APPEND, cNext); } case '>': pointer++; return new SuffixTemplateToken(TemplateTokenType.DEVOICE_FIRST, cNext); case '~': pointer++; return new SuffixTemplateToken(TemplateTokenType.LAST_VOICED, cNext); case '!': pointer++; return new SuffixTemplateToken(TemplateTokenType.LAST_NOT_VOICED, cNext); case 'I': return new SuffixTemplateToken(TemplateTokenType.I_WOVEL, undefined); case 'A': return new SuffixTemplateToken(TemplateTokenType.A_WOVEL, undefined); default: return new SuffixTemplateToken(TemplateTokenType.LETTER, c); } } public void remove() { } } }
2,937
930
package com.foxinmy.weixin4j.type.mch; /** * 对账单类型 * * @className BillType * @author jinyu(<EMAIL>) * @date 2014年10月31日 * @since JDK 1.6 * @see * @deprecated 迁移到子模块weixin4j-pay */ @Deprecated public enum BillType { /** * 全部 */ ALL(0), /** * 成功订单 */ SUCCESS(1), /** * 退款订单 */ REFUND(2); private int val; BillType(int val) { this.val = val; } public int getVal() { return val; } }
246
1,308
/* * Copyright 2019 <NAME> * * 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 exchange.core2.core.utils; import exchange.core2.core.common.StateHash; import lombok.extern.slf4j.Slf4j; import org.agrona.collections.MutableLong; import org.eclipse.collections.impl.map.mutable.primitive.IntObjectHashMap; import org.eclipse.collections.impl.map.mutable.primitive.LongObjectHashMap; import java.util.Arrays; import java.util.BitSet; import java.util.Iterator; import java.util.Objects; import java.util.stream.Stream; @Slf4j public final class HashingUtils { public static int stateHash(final BitSet bitSet) { return Arrays.hashCode(bitSet.toLongArray()); } public static <T extends StateHash> int stateHash(final LongObjectHashMap<T> hashMap) { final MutableLong mutableLong = new MutableLong(); hashMap.forEachKeyValue((k, v) -> mutableLong.addAndGet(Objects.hash(k, v.stateHash()))); return Long.hashCode(mutableLong.value); } public static <T extends StateHash> int stateHash(final IntObjectHashMap<T> hashMap) { final MutableLong mutableLong = new MutableLong(); hashMap.forEachKeyValue((k, v) -> mutableLong.addAndGet(Objects.hash(k, v.stateHash()))); return Long.hashCode(mutableLong.value); } public static int stateHashStream(final Stream<? extends StateHash> stream) { int h = 0; final Iterator<? extends StateHash> iterator = stream.iterator(); while (iterator.hasNext()) { h = h * 31 + iterator.next().stateHash(); } return h; } /** * Checks if both streams contain same elements in same order * * @param s1 stream 1 * @param s2 stream 2 * @return true if streams contain same elements in same order */ public static boolean checkStreamsEqual(final Stream<?> s1, final Stream<?> s2) { final Iterator<?> iter1 = s1.iterator(), iter2 = s2.iterator(); while (iter1.hasNext() && iter2.hasNext()) { if (!iter1.next().equals(iter2.next())) { return false; } } return !iter1.hasNext() && !iter2.hasNext(); } }
982
1,131
/* * 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 com.cloud.utils; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.jasypt.encryption.pbe.PBEStringEncryptor; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import com.cloud.utils.exception.CloudRuntimeException; public class EncryptionUtil { public static final Logger s_logger = Logger.getLogger(EncryptionUtil.class.getName()); private static PBEStringEncryptor encryptor; private static void initialize(String key) { StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor(); standardPBEStringEncryptor.setAlgorithm("PBEWITHSHA1ANDDESEDE"); standardPBEStringEncryptor.setPassword(key); encryptor = standardPBEStringEncryptor; } public static String encodeData(String data, String key) { if (encryptor == null) { initialize(key); } return encryptor.encrypt(data); } public static String decodeData(String encodedData, String key) { if (encryptor == null) { initialize(key); } return encryptor.decrypt(encodedData); } public static String generateSignature(String data, String key) { try { final Mac mac = Mac.getInstance("HmacSHA1"); final SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1"); mac.init(keySpec); mac.update(data.getBytes("UTF-8")); final byte[] encryptedBytes = mac.doFinal(); return Base64.encodeBase64String(encryptedBytes); } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) { s_logger.error("exception occurred which encoding the data." + e.getMessage()); throw new CloudRuntimeException("unable to generate signature", e); } } }
987
4,559
<gh_stars>1000+ """ Copyright 2017-2018 Fizyr (https://fizyr.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import csv import pytest try: from io import StringIO except ImportError: from stringio import StringIO from keras_retinanet.preprocessing import csv_generator def csv_str(string): if str == bytes: string = string.decode('utf-8') return csv.reader(StringIO(string)) def annotation(x1, y1, x2, y2, class_name): return {'x1': x1, 'y1': y1, 'x2': x2, 'y2': y2, 'class': class_name} def test_read_classes(): assert csv_generator._read_classes(csv_str('')) == {} assert csv_generator._read_classes(csv_str('a,1')) == {'a': 1} assert csv_generator._read_classes(csv_str('a,1\nb,2')) == {'a': 1, 'b': 2} def test_read_classes_wrong_format(): with pytest.raises(ValueError): try: csv_generator._read_classes(csv_str('a,b,c')) except ValueError as e: assert str(e).startswith('line 1: format should be') raise with pytest.raises(ValueError): try: csv_generator._read_classes(csv_str('a,1\nb,c,d')) except ValueError as e: assert str(e).startswith('line 2: format should be') raise def test_read_classes_malformed_class_id(): with pytest.raises(ValueError): try: csv_generator._read_classes(csv_str('a,b')) except ValueError as e: assert str(e).startswith("line 1: malformed class ID:") raise with pytest.raises(ValueError): try: csv_generator._read_classes(csv_str('a,1\nb,c')) except ValueError as e: assert str(e).startswith('line 2: malformed class ID:') raise def test_read_classes_duplicate_name(): with pytest.raises(ValueError): try: csv_generator._read_classes(csv_str('a,1\nb,2\na,3')) except ValueError as e: assert str(e).startswith('line 3: duplicate class name') raise def test_read_annotations(): classes = {'a': 1, 'b': 2, 'c': 4, 'd': 10} annotations = csv_generator._read_annotations(csv_str( 'a.png,0,1,2,3,a' '\n' 'b.png,4,5,6,7,b' '\n' 'c.png,8,9,10,11,c' '\n' 'd.png,12,13,14,15,d' '\n' ), classes) assert annotations == { 'a.png': [annotation( 0, 1, 2, 3, 'a')], 'b.png': [annotation( 4, 5, 6, 7, 'b')], 'c.png': [annotation( 8, 9, 10, 11, 'c')], 'd.png': [annotation(12, 13, 14, 15, 'd')], } def test_read_annotations_multiple(): classes = {'a': 1, 'b': 2, 'c': 4, 'd': 10} annotations = csv_generator._read_annotations(csv_str( 'a.png,0,1,2,3,a' '\n' 'b.png,4,5,6,7,b' '\n' 'a.png,8,9,10,11,c' '\n' ), classes) assert annotations == { 'a.png': [ annotation(0, 1, 2, 3, 'a'), annotation(8, 9, 10, 11, 'c'), ], 'b.png': [annotation(4, 5, 6, 7, 'b')], } def test_read_annotations_wrong_format(): classes = {'a': 1, 'b': 2, 'c': 4, 'd': 10} with pytest.raises(ValueError): try: csv_generator._read_annotations(csv_str('a.png,1,2,3,a'), classes) except ValueError as e: assert str(e).startswith("line 1: format should be") raise with pytest.raises(ValueError): try: csv_generator._read_annotations(csv_str( 'a.png,0,1,2,3,a' '\n' 'a.png,1,2,3,a' '\n' ), classes) except ValueError as e: assert str(e).startswith("line 2: format should be") raise def test_read_annotations_wrong_x1(): with pytest.raises(ValueError): try: csv_generator._read_annotations(csv_str('a.png,a,0,1,2,a'), {'a': 1}) except ValueError as e: assert str(e).startswith("line 1: malformed x1:") raise def test_read_annotations_wrong_y1(): with pytest.raises(ValueError): try: csv_generator._read_annotations(csv_str('a.png,0,a,1,2,a'), {'a': 1}) except ValueError as e: assert str(e).startswith("line 1: malformed y1:") raise def test_read_annotations_wrong_x2(): with pytest.raises(ValueError): try: csv_generator._read_annotations(csv_str('a.png,0,1,a,2,a'), {'a': 1}) except ValueError as e: assert str(e).startswith("line 1: malformed x2:") raise def test_read_annotations_wrong_y2(): with pytest.raises(ValueError): try: csv_generator._read_annotations(csv_str('a.png,0,1,2,a,a'), {'a': 1}) except ValueError as e: assert str(e).startswith("line 1: malformed y2:") raise def test_read_annotations_wrong_class(): with pytest.raises(ValueError): try: csv_generator._read_annotations(csv_str('a.png,0,1,2,3,g'), {'a': 1}) except ValueError as e: assert str(e).startswith("line 1: unknown class name:") raise def test_read_annotations_invalid_bb_x(): with pytest.raises(ValueError): try: csv_generator._read_annotations(csv_str('a.png,1,2,1,3,g'), {'a': 1}) except ValueError as e: assert str(e).startswith("line 1: x2 (1) must be higher than x1 (1)") raise with pytest.raises(ValueError): try: csv_generator._read_annotations(csv_str('a.png,9,2,5,3,g'), {'a': 1}) except ValueError as e: assert str(e).startswith("line 1: x2 (5) must be higher than x1 (9)") raise def test_read_annotations_invalid_bb_y(): with pytest.raises(ValueError): try: csv_generator._read_annotations(csv_str('a.png,1,2,3,2,a'), {'a': 1}) except ValueError as e: assert str(e).startswith("line 1: y2 (2) must be higher than y1 (2)") raise with pytest.raises(ValueError): try: csv_generator._read_annotations(csv_str('a.png,1,8,3,5,a'), {'a': 1}) except ValueError as e: assert str(e).startswith("line 1: y2 (5) must be higher than y1 (8)") raise def test_read_annotations_empty_image(): # Check that images without annotations are parsed. assert csv_generator._read_annotations(csv_str('a.png,,,,,\nb.png,,,,,'), {'a': 1}) == {'a.png': [], 'b.png': []} # Check that lines without annotations don't clear earlier annotations. assert csv_generator._read_annotations(csv_str('a.png,0,1,2,3,a\na.png,,,,,'), {'a': 1}) == {'a.png': [annotation(0, 1, 2, 3, 'a')]}
3,462
14,668
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_SEARCH_BACKGROUND_NTP_BACKGROUND_DATA_H_ #define CHROME_BROWSER_SEARCH_BACKGROUND_NTP_BACKGROUND_DATA_H_ #include <string> #include "chrome/browser/search/background/ntp_background.pb.h" #include "url/gurl.h" enum class ErrorType { // Data retrieved successfully. NONE, // Network error occurred. NET_ERROR, // Response from backend couldn't be read. SERVICE_ERROR, }; std::string GetThumbnailImageOptionsForTesting(); // Background images are organized into collections, according to a theme. This // struct contains the data required to display information about a collection, // including a representative image. The complete set of CollectionImages must // be requested separately, by referencing the identifier for this collection. struct CollectionInfo { CollectionInfo(); CollectionInfo(const CollectionInfo&); CollectionInfo(CollectionInfo&&); ~CollectionInfo(); CollectionInfo& operator=(const CollectionInfo&); CollectionInfo& operator=(CollectionInfo&&); static CollectionInfo CreateFromProto( const ntp::background::Collection& collection); // A unique identifier for the collection. std::string collection_id; // A human-readable name for the collection. std::string collection_name; // A representative image from the collection. GURL preview_image_url; }; bool operator==(const CollectionInfo& lhs, const CollectionInfo& rhs); bool operator!=(const CollectionInfo& lhs, const CollectionInfo& rhs); // Represents an image within a collection. The associated collection_id may be // used to get CollectionInfo. struct CollectionImage { CollectionImage(); CollectionImage(const CollectionImage&); CollectionImage(CollectionImage&&); ~CollectionImage(); CollectionImage& operator=(const CollectionImage&); CollectionImage& operator=(CollectionImage&&); // default_image_options are applied to the image.image_url() if options // (specifying resolution, cropping, etc) are not already present. static CollectionImage CreateFromProto( const std::string& collection_id, const ntp::background::Image& image, const std::string& default_image_options); // A unique identifier for the collection the image is in. std::string collection_id; // A unique identifier for the image. uint64_t asset_id; // The thumbnail image URL, typically lower resolution than the image_url. GURL thumbnail_image_url; // The image URL. GURL image_url; // The attribution list for the image. std::vector<std::string> attribution; // A URL that can be accessed to find out more information about the image. GURL attribution_action_url; }; bool operator==(const CollectionImage& lhs, const CollectionImage& rhs); bool operator!=(const CollectionImage& lhs, const CollectionImage& rhs); // Represents errors that occur when communicating with the Backdrop service and // Google Photos. struct ErrorInfo { ErrorInfo(); ErrorInfo(const ErrorInfo&); ErrorInfo(ErrorInfo&&); ~ErrorInfo(); ErrorInfo& operator=(const ErrorInfo&); ErrorInfo& operator=(ErrorInfo&&); void ClearError(); // Network error number, listed at chrome://network-errors. int net_error; // Category of error that occured. ErrorType error_type; }; // Represents a custom background on the new tab page. struct CustomBackground { CustomBackground(); CustomBackground(const CustomBackground&); CustomBackground(CustomBackground&&); ~CustomBackground(); CustomBackground& operator=(const CustomBackground&); CustomBackground& operator=(CustomBackground&&); // Url of the custom background selected by the user. GURL custom_background_url; // First attribution string for custom background. std::string custom_background_attribution_line_1; // Second attribution string for custom background. std::string custom_background_attribution_line_2; // Url to learn more info about the custom background. GURL custom_background_attribution_action_url; // Id of the collection being used for "daily refresh". std::string collection_id; }; #endif // CHROME_BROWSER_SEARCH_BACKGROUND_NTP_BACKGROUND_DATA_H_
1,155
5,087
<gh_stars>1000+ import tensorflow as tf sess = tf.Session() a = tf.placeholder("float") b = tf.placeholder("float") c = tf.constant(6.0) d = tf.mul(a, b) y = tf.mul(d, c) print sess.run(y, feed_dict={a: 3, b: 3}) A = [[1.1,2.3],[3.4,4.1]] Y = tf.matrix_inverse(A) print sess.run(Y) sess.close()
151
599
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://opensource.org/licenses/MIT 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. Module for generating kubeconfig file """ import contextlib import logging import tempfile from dataclasses import dataclass from typing import List import yaml logger = logging.getLogger(__name__) @dataclass class Cluster: """Cluster Info :param cert: path of certification :param cert_data: certification in base64 format, will be ignored if cert is provided """ name: str server: str cert: str = "" cert_data: str = "" api_version: str = "v1" @dataclass class User: """Kubernetes user info""" name: str token: str @dataclass class Context: """kube config context""" name: str user: User cluster: Cluster class KubeConfig: """The kubeconfig class""" def __init__(self, contexts: List[Context]): assert contexts, "Must provide at least one context" self.contexts = contexts @staticmethod def format_cluster(cluster): """Format a cluster as kubeconfig format""" cert_info = {"certificate-authority-data": cluster.cert_data} if cluster.cert: cert_info = {"certificate-authority": cluster.cert} # if settings.HELM_INSECURE_SKIP_TLS_VERIFY: cert_info = {"insecure-skip-tls-verify": True} return { "name": cluster.name, "cluster": {"server": cluster.server, "api-version": cluster.api_version, **cert_info}, } @staticmethod def format_user(user): """Format an user as kubeconfig format""" return {"name": user.name, "user": {"token": user.token}} @staticmethod def format_context(context): """Format a context as kubeconfig format""" return { "name": context.name, "context": { "user": context.user.name, "cluster": context.cluster.name, }, } def dumps(self, current_context: str = ""): """Represent current config as a kubeconfig file :returns: kubeconfig file content """ clusters = {} users = {} for context in self.contexts: clusters[context.cluster.name] = self.format_cluster(context.cluster) users[context.user.name] = self.format_user(context.user) current_context = current_context or self.contexts[0].name payload = { "apiVersion": "v1", "kind": "Config", "clusters": list(clusters.values()), "users": list(users.values()), "contexts": [self.format_context(context) for context in self.contexts], "current-context": current_context, } return yaml.dump(payload, default_flow_style=False) @contextlib.contextmanager def as_tempfile(self): """A context manager which dump current config to a temp kubeconfig file""" with tempfile.NamedTemporaryFile() as fp: fp.write(self.dumps().encode()) fp.flush() yield fp.name
1,479
2,199
<gh_stars>1000+ { "Logging": { "LogLevel": { "Default": "Trace", "System": "Information", "Microsoft": "Information" } }, "Kestrel": { "EndpointDefaults": { "Protocols": "Http2" } }, "MagicOnion": { "OpenTelemetry": { "ServiceName": "ChatApp.Server", // "ExposeRpcScope": false, "TracingTags": { "foo": "bar" } } }, "UseExporter": "jaeger", // select "console", "zipkin", "jaeger" "Jaeger": { "AgentHost": "localhost", "AgentPort": 6831 }, "Zipkin": { "Endpoint": "http://localhost:9411/api/v2/spans" }, "AspNetCoreInstrumentation": { "RecordException": "true" } }
324
852
# -*- coding: utf-8 -*- import FWCore.ParameterSet.Config as cms process = cms.Process("L1TMuonEmulation") import optparse process.load("FWCore.MessageLogger.MessageLogger_cfi") process.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32(1) process.options = cms.untracked.PSet(wantSummary = cms.untracked.bool(False)) process.source = cms.Source('PoolSource', fileNames = cms.untracked.vstring('file:/afs/cern.ch/work/g/gkaratha/private/bmtf/gen_samples/Singlemu_oneoverpt_100k.root') ) process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(2000)) # PostLS1 geometry used process.load('Configuration.Geometry.GeometryExtended2015Reco_cff') process.load('Configuration.Geometry.GeometryExtended2015_cff') ############################ process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff') from Configuration.AlCa.GlobalTag import GlobalTag process.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_mc', '') ##ES Producer ####Event Setup Producer process.load('L1Trigger.L1TTwinMux.fakeTwinMuxParams_cff') process.esProd = cms.EDAnalyzer("EventSetupRecordDataGetter", toGet = cms.VPSet( cms.PSet(record = cms.string('L1TTwinMuxParamsRcd'), data = cms.vstring('L1TTwinMuxParams')) ), verbose = cms.untracked.bool(True) ) # process.fakeTwinMuxParams.verbose = cms.bool(True) # process.fakeTwinMuxParams.useOnlyRPC = cms.bool(False) ###TwinMux Emulator process.load('L1Trigger.L1TTwinMux.simTwinMuxDigis_cfi') process.L1TMuonSeq = cms.Sequence( process.esProd +process.simTwinMuxDigis ) process.L1TMuonPath = cms.Path(process.L1TMuonSeq) process.out = cms.OutputModule("PoolOutputModule", outputCommands = cms.untracked.vstring( 'drop *', #'keep *CSC*_*_*_*', 'keep *RPC*_*_*_*', 'keep *DT*_*_*_*', 'keep *L1Mu*_*_*_*', 'keep *_*Muon*_*_*', 'keep *_*gen*_*_*', 'keep *_*TwinMux*_*_*', 'keep *_*Bmtf*_*_*', 'keep GenEventInfoProduct_generator_*_*'), fileName = cms.untracked.string("l1twinmux.root") ) process.output_step = cms.EndPath(process.out) process.schedule = cms.Schedule(process.L1TMuonPath) process.schedule.extend([process.output_step])
1,018
17,809
<reponame>ScriptBox21/winget-cli<filename>src/AppInstallerCommonCore/HttpStream/HttpClientWrapper.h // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once namespace AppInstaller::Utility::HttpStream { // Wrapper around HTTP client. When created, an object of this class will send a HTTP // head request to determine the size of the data source. class HttpClientWrapper { public: static std::future<std::shared_ptr<HttpClientWrapper>> CreateAsync(const winrt::Windows::Foundation::Uri& uri); std::future<winrt::Windows::Storage::Streams::IBuffer> DownloadRangeAsync( const ULONG64 startPosition, const UINT32 requestedSizeInBytes, const winrt::Windows::Storage::Streams::InputStreamOptions& options); unsigned long long GetFullFileSize() { return m_sizeInBytes; } winrt::Windows::Foundation::Uri GetRedirectUri() { return m_redirectUri; } std::wstring GetContentType() { return m_contentType; } private: winrt::Windows::Web::Http::HttpClient m_httpClient; winrt::Windows::Foundation::Uri m_requestUri = nullptr; winrt::Windows::Foundation::Uri m_redirectUri = nullptr; std::wstring m_contentType; unsigned long long m_sizeInBytes = 0; std::wstring m_etagHeader; std::wstring m_lastModifiedHeader; std::future<void> PopulateInfoAsync(); std::future<winrt::Windows::Storage::Streams::IBuffer> SendHttpRequestAsync( _In_ ULONG64 startPosition, _In_ UINT32 requestedSizeInBytes); }; }
756