repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
betajs/betajs-dynamics
src/partials/inner_template_partial.js
<filename>src/partials/inner_template_partial.js Scoped.define("module:Partials.InnerTemplatePartial", ["module:Handlers.Partial"], function(Partial, scoped) { var Cls = Partial.extend({ scoped: scoped }, function(inherited) { return { constructor: function(node, args, value) { inherited.constructor.apply(this, arguments); node._element.innerHTML = value; } }; }, { meta: { value_hidden: true } }); Cls.register("ba-inner-template"); return Cls; });
wokalski/Distraction-Free-Xcode-plugin
Archived/v1/WCDistractionFreeXcodePlugin/Headers/PlugIns/Xcode3UI/IDEAppIDFeatureDelegate-Protocol.h
<gh_stars>10-100 // // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by <NAME>. // @class DVTAppIDFeatures, DVTFuture; @protocol IDEAppIDFeatureDelegate @property(readonly) DVTAppIDFeatures *appIDFeatures; - (DVTFuture *)setAppIDFeatures:(DVTAppIDFeatures *)arg1; @end
LaudateCorpus1/llvm-project
utils/bazel/llvm-project-overlay/mlir/build_defs.bzl
<filename>utils/bazel/llvm-project-overlay/mlir/build_defs.bzl # This file is licensed under the Apache License v2.0 with LLVM Exceptions. # See https://llvm.org/LICENSE.txt for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception """Rules and macros for MLIR""" def if_cuda_available(if_true, if_false = []): return select({ # CUDA is not yet supported. "//conditions:default": if_false, }) def _cc_headers_only_impl(ctx): return CcInfo(compilation_context = ctx.attr.src[CcInfo].compilation_context) cc_headers_only = rule( implementation = _cc_headers_only_impl, attrs = { "src": attr.label( mandatory = True, providers = [CcInfo], ), }, doc = "Provides the headers from 'src' without linking anything.", provides = [CcInfo], ) def mlir_c_api_cc_library( name, srcs = [], hdrs = [], deps = [], header_deps = [], capi_deps = [], **kwargs): """Macro that generates three targets for MLIR C API libraries. * A standard cc_library target ("Name"), * A header-only cc_library target ("NameHeaders") * An implementation cc_library target tagged `alwayslink` suitable for inclusion in a shared library built with cc_binary() ("NameObjects"). In order to avoid duplicate symbols, it is important that mlir_c_api_cc_library targets only depend on other mlir_c_api_cc_library targets via the "capi_deps" parameter. This makes it so that "FooObjects" depend on "BarObjects" targets and "Foo" targets depend on "Bar" targets. Don't cross the streams. """ capi_header_deps = ["%sHeaders" % d for d in capi_deps] capi_object_deps = ["%sObjects" % d for d in capi_deps] native.cc_library( name = name, srcs = srcs, hdrs = hdrs, deps = deps + capi_deps + header_deps, **kwargs ) native.cc_library( name = name + "Headers", hdrs = hdrs, deps = header_deps + capi_header_deps, **kwargs ) native.cc_library( name = name + "Objects", srcs = srcs, hdrs = hdrs, deps = deps + capi_object_deps + capi_header_deps + header_deps, alwayslink = True, **kwargs )
lguohan/SDKLT
src/sal/libc/libc_vsnprintf.c
/*! \file libc_vsnprintf.c * * SDK implementation of vsnprintf. */ /* * Copyright: (c) 2018 Broadcom. All Rights Reserved. "Broadcom" refers to * Broadcom Limited and/or its subsidiaries. * * Broadcom Switch Software License * * This license governs the use of the accompanying Broadcom software. Your * use of the software indicates your acceptance of the terms and conditions * of this license. If you do not agree to the terms and conditions of this * license, do not use the software. * 1. Definitions * "Licensor" means any person or entity that distributes its Work. * "Software" means the original work of authorship made available under * this license. * "Work" means the Software and any additions to or derivative works of * the Software that are made available under this license. * The terms "reproduce," "reproduction," "derivative works," and * "distribution" have the meaning as provided under U.S. copyright law. * Works, including the Software, are "made available" under this license * by including in or with the Work either (a) a copyright notice * referencing the applicability of this license to the Work, or (b) a copy * of this license. * 2. Grant of Copyright License * Subject to the terms and conditions of this license, each Licensor * grants to you a perpetual, worldwide, non-exclusive, and royalty-free * copyright license to reproduce, prepare derivative works of, publicly * display, publicly perform, sublicense and distribute its Work and any * resulting derivative works in any form. * 3. Grant of Patent License * Subject to the terms and conditions of this license, each Licensor * grants to you a perpetual, worldwide, non-exclusive, and royalty-free * patent license to make, have made, use, offer to sell, sell, import, and * otherwise transfer its Work, in whole or in part. This patent license * applies only to the patent claims licensable by Licensor that would be * infringed by Licensor's Work (or portion thereof) individually and * excluding any combinations with any other materials or technology. * If you institute patent litigation against any Licensor (including a * cross-claim or counterclaim in a lawsuit) to enforce any patents that * you allege are infringed by any Work, then your patent license from such * Licensor to the Work shall terminate as of the date such litigation is * filed. * 4. Redistribution * You may reproduce or distribute the Work only if (a) you do so under * this License, (b) you include a complete copy of this License with your * distribution, and (c) you retain without modification any copyright, * patent, trademark, or attribution notices that are present in the Work. * 5. Derivative Works * You may specify that additional or different terms apply to the use, * reproduction, and distribution of your derivative works of the Work * ("Your Terms") only if (a) Your Terms provide that the limitations of * Section 7 apply to your derivative works, and (b) you identify the * specific derivative works that are subject to Your Terms. * Notwithstanding Your Terms, this license (including the redistribution * requirements in Section 4) will continue to apply to the Work itself. * 6. Trademarks * This license does not grant any rights to use any Licensor's or its * affiliates' names, logos, or trademarks, except as necessary to * reproduce the notices described in this license. * 7. Limitations * Platform. The Work and any derivative works thereof may only be used, or * intended for use, with a Broadcom switch integrated circuit. * No Reverse Engineering. You will not use the Work to disassemble, * reverse engineer, decompile, or attempt to ascertain the underlying * technology of a Broadcom switch integrated circuit. * 8. Termination * If you violate any term of this license, then your rights under this * license (including the license grants of Sections 2 and 3) will * terminate immediately. * 9. Disclaimer of Warranty * THE WORK IS PROVIDED "AS IS" WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WARRANTIES OR CONDITIONS OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR * NON-INFRINGEMENT. YOU BEAR THE RISK OF UNDERTAKING ANY ACTIVITIES UNDER * THIS LICENSE. SOME STATES' CONSUMER LAWS DO NOT ALLOW EXCLUSION OF AN * IMPLIED WARRANTY, SO THIS DISCLAIMER MAY NOT APPLY TO YOU. * 10. Limitation of Liability * EXCEPT AS PROHIBITED BY APPLICABLE LAW, IN NO EVENT AND UNDER NO LEGAL * THEORY, WHETHER IN TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE * SHALL ANY LICENSOR BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF * OR RELATED TO THIS LICENSE, THE USE OR INABILITY TO USE THE WORK * (INCLUDING BUT NOT LIMITED TO LOSS OF GOODWILL, BUSINESS INTERRUPTION, * LOST PROFITS OR DATA, COMPUTER FAILURE OR MALFUNCTION, OR ANY OTHER * COMMERCIAL DAMAGES OR LOSSES), EVEN IF THE LICENSOR HAS BEEN ADVISED OF * THE POSSIBILITY OF SUCH DAMAGES. */ #include <sal/sal_libc.h> #ifndef sal_vsnprintf /* * Reasonably complete subset of ANSI-style printf routines. * Needs only strlen and stdarg. * Behavior was regressed against Solaris printf(3s) routines (below). * * Supported format controls: * * %% percent sign * %c character * %d integer * %hd short integer * %ld long integer * %u unsigned integer * %o unsigned octal integer * %x unsigned hexadecimal integer (lowercase) * %X unsigned hexadecimal integer (uppercase) * %s string * %p pointer * %n store number of characters output so far * * Flag modifiers supported: * Field width, argument field width (*), left justify (-), * zero-fill (0), alternate form (#), always include sign (+), * space before positive numbers (space). * * Functions implemented: * * int vsnprintf(char *buf, size_t bufsz, const char *fmt, va_list ap); * int vsprintf(char *buf, const char *fmt, va_list ap); * int snprintf(char *buf, size_t bufsz, const char *fmt, ...); * int sprintf(char *buf, const char *fmt, ...); * * Note that some functions are implemented in separate source files. */ static void _itoa(char *buf, /* Large enough result buffer */ uint32_t num, /* Number to convert */ int base, /* Conversion base (2 to 16) */ int caps, /* Capitalize letter digits */ int prec) /* Precision (minimum digits) */ { char tmp[36], *s, *digits; digits = (caps ? "0123456789ABCDEF" : "0123456789abcdef"); s = &tmp[sizeof(tmp) - 1]; for (*s = 0; num || s == &tmp[sizeof(tmp) - 1]; num /= base, prec--) { *--s = digits[num % base]; } while (prec-- > 0) { *--s = '0'; } sal_strcpy(buf, s); } #define X_STORE(c) { \ if (bp < be) { \ *bp = (c); \ } \ bp++; \ } #define X_INF SAL_VSNPRINTF_X_INF int sal_vsnprintf(char *buf, size_t bufsz, const char *fmt, va_list ap) { char c, *bp, *be; char *p_null = NULL; char *b_inf = p_null - 1; bp = buf; be = (bufsz == X_INF) ? b_inf : &buf[bufsz - 1]; while ((c = *fmt++) != 0) { int width = 0, ljust = 0, plus = 0, space = 0; int altform = 0, prec = 0, half = 0, base = 0; int tlong = 0, fillz = 0, plen, pad; long num = 0; char tmp[36], *p = tmp; if (c != '%') { X_STORE(c); continue; } for (c = *fmt++; ; c = *fmt++) switch (c) { case 'h': half = 1; break; case 'l': tlong = 1; break; case '-': ljust = 1; break; case '+': plus = 1; break; case ' ': space = 1; break; case '0': fillz = 1; break; case '#': altform = 1; break; case '*': /* Mark as need-to-fetch */ width = -1; break; case '.': if ((c = *fmt++) == '*') { /* Mark as need-to-fetch */ prec = -1; } else { for (prec = 0; c >= '0' && c <= '9'; c = *fmt++) { prec = prec * 10 + (c - '0'); } fmt--; } break; default: if (c >= '1' && c <= '9') { for (width = 0; c >= '0' && c <= '9'; c = *fmt++) { width = width * 10 + (c - '0'); } fmt--; } else { goto break_for; } break; } break_for: if (width == -1) { width = va_arg(ap, int); } if (prec == -1) { prec = va_arg(ap, int); } if (c == 0) { break; } switch (c) { case 'd': case 'i': num = tlong ? va_arg(ap, long) : va_arg(ap, int); if (half) { num = (int)(short)num; } /* For zero-fill, the sign must be to the left of the zeroes */ if (fillz && (num < 0 || plus || space)) { X_STORE(num < 0 ? '-' : space ? ' ' : '+'); if (width > 0) { width--; } if (num < 0) { num = -num; } } if (!fillz) { if (num < 0) { *p++ = '-'; num = -num; } else if (plus) { *p++ = '+'; } else if (space) { *p++ = ' '; } } base = 10; break; case 'u': num = tlong ? va_arg(ap, long) : va_arg(ap, int); if (half) { num = (int)(short)num; } base = 10; break; case 'p': altform = 0; /* Fall through */ case 'x': case 'X': num = tlong ? va_arg(ap, long) : va_arg(ap, int); if (half) { num = (int)(unsigned short)num; } if (altform) { prec += 2; *p++ = '0'; *p++ = c; } base = 16; break; case 'o': case 'O': num = tlong ? va_arg(ap, long) : va_arg(ap, int); if (half) { num = (int)(unsigned short)num; } if (altform) { prec++; *p++ = '0'; } base = 8; break; case 's': p = va_arg(ap, char *); if (prec == 0) { prec = X_INF; } break; case 'c': p[0] = va_arg(ap, int); p[1] = 0; prec = 1; break; case 'n': *va_arg(ap, int *) = bp - buf; p[0] = 0; break; case '%': p[0] = '%'; p[1] = 0; prec = 1; break; default: X_STORE(c); continue; } if (base != 0) { _itoa(p, (unsigned int)num, base, (c == 'X'), prec); if (prec) { fillz = 0; } p = tmp; prec = X_INF; } if ((plen = sal_strlen(p)) > prec) { plen = prec; } if (width < plen) { width = plen; } pad = width - plen; while (!ljust && pad-- > 0) { X_STORE(fillz ? '0' : ' '); } for (; plen-- > 0 && width-- > 0; p++) { X_STORE(*p); } while (pad-- > 0) { X_STORE(' '); } } if ((be == b_inf) || (bp < be)) { *bp = 0; } else { /* coverity[var_deref_op] */ *be = 0; } return (bp - buf); } #endif
Pokecube-Development/Pokecube-Core
src/main/java/pokecube/core/interfaces/entity/impl/PersistantStatusEffect.java
<reponame>Pokecube-Development/Pokecube-Core package pokecube.core.interfaces.entity.impl; import java.util.Map; import java.util.Random; import java.util.logging.Level; import com.google.common.collect.Maps; import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.INpc; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.DamageSource; import net.minecraft.util.ResourceLocation; import pokecube.core.events.pokemob.combat.StatusEvent; import pokecube.core.interfaces.IMoveConstants; import pokecube.core.interfaces.IPokemob; import pokecube.core.interfaces.PokecubeMod; import pokecube.core.interfaces.capabilities.CapabilityPokemob; import pokecube.core.interfaces.entity.IOngoingAffected; import pokecube.core.interfaces.entity.IOngoingAffected.IOngoingEffect; import thut.api.maths.Vector3; public class PersistantStatusEffect extends BaseEffect { public static final ResourceLocation ID = new ResourceLocation(PokecubeMod.ID, "persistant_status"); public static final Map<Status, IStatusEffect> EFFECTMAP = Maps.newHashMap(); private static final Int2ObjectArrayMap<Status> MASKMAP = new Int2ObjectArrayMap<>(); public static enum Status implements IMoveConstants { SLEEP(STATUS_SLP), FREEZE(STATUS_FRZ), PARALYSIS(STATUS_PAR), BURN(STATUS_BRN), POISON(STATUS_PSN), BADPOISON( STATUS_PSN2); final byte mask; private Status(byte mask) { this.mask = mask; MASKMAP.put(mask, this); } public byte getMask() { return mask; } public static Status getStatus(byte mask) { return MASKMAP.get(mask); } public static void initDefaults() { for (Status stat : values()) { EFFECTMAP.put(stat, new DefaultEffects(stat)); } } } public static interface IStatusEffect { void affectTarget(IOngoingAffected target, IOngoingEffect effect); void setTick(int tick); } public static class DefaultEffects implements IStatusEffect { final Status status; int tick; public DefaultEffects(Status status) { this.status = status; } @Override public void affectTarget(IOngoingAffected target, IOngoingEffect effect) { EntityLivingBase entity = target.getEntity(); IPokemob pokemob = CapabilityPokemob.getPokemobFor(entity); if (pokemob != null && status != Status.BADPOISON) { pokemob.getMoveStats().TOXIC_COUNTER = 0; } boolean toRemove = pokemob != null ? false : Math.random() > 0.8; if (effect.getDuration() == 0) toRemove = true; int duration = PokecubeMod.core.getConfig().attackCooldown + 10; EntityLivingBase targetM = entity.getAttackingEntity(); if (targetM == null) targetM = entity.getRevengeTarget(); if (targetM == null) targetM = entity.getLastAttackedEntity(); if (targetM == null) targetM = entity; float scale = 1; IPokemob user = CapabilityPokemob.getPokemobFor(targetM); DamageSource source = user != null && user.getPokemonOwner() != null ? DamageSource.causeIndirectDamage(targetM, user.getPokemonOwner()) : targetM != null ? DamageSource.causeMobDamage(targetM) : new DamageSource("generic"); if (pokemob != null) { source.setDamageIsAbsolute(); source.setDamageBypassesArmor(); } else { if (entity instanceof EntityPlayer) { scale = (float) (user != null && user.isPlayerOwned() ? PokecubeMod.core.getConfig().ownedPlayerDamageRatio : PokecubeMod.core.getConfig().wildPlayerDamageRatio); } else { scale = (float) (entity instanceof INpc ? PokecubeMod.core.getConfig().pokemobToNPCDamageRatio : PokecubeMod.core.getConfig().pokemobToOtherMobDamageRatio); } } if (scale <= 0) toRemove = true; switch (status) { case BADPOISON: if (pokemob != null) { entity.attackEntityFrom(source, scale * (pokemob.getMoveStats().TOXIC_COUNTER + 1) * entity.getMaxHealth() / 16f); spawnPoisonParticle(entity); spawnPoisonParticle(entity); pokemob.getMoveStats().TOXIC_COUNTER++; } else { entity.attackEntityFrom(source, scale * entity.getMaxHealth() / 8f); spawnPoisonParticle(entity); } break; case BURN: if (scale > 0) entity.setFire(duration); entity.attackEntityFrom(source, scale * entity.getMaxHealth() / 16f); break; case FREEZE: if (Math.random() > 0.9) { toRemove = true; } entity.addPotionEffect( new PotionEffect(Potion.getPotionFromResourceLocation("slowness"), duration, 100)); entity.addPotionEffect( new PotionEffect(Potion.getPotionFromResourceLocation("weakness"), duration, 100)); break; case PARALYSIS: break; case POISON: entity.attackEntityFrom(source, scale * entity.getMaxHealth() / 8f); spawnPoisonParticle(entity); break; case SLEEP: if (Math.random() > 0.9) { toRemove = true; } else { entity.addPotionEffect( new PotionEffect(Potion.getPotionFromResourceLocation("blindness"), duration, 100)); entity.addPotionEffect( new PotionEffect(Potion.getPotionFromResourceLocation("slowness"), duration, 100)); entity.addPotionEffect( new PotionEffect(Potion.getPotionFromResourceLocation("weakness"), duration, 100)); spawnSleepParticle(entity); } break; default: toRemove = true; break; } if (toRemove) { if (pokemob != null) pokemob.healStatus(); effect.setDuration(0); } } @Override public void setTick(int tick) { this.tick = tick; } protected void spawnSleepParticle(Entity entity) { Random rand = new Random(); Vector3 particleLoc = Vector3.getNewVector(); Vector3 vel = Vector3.getNewVector(); for (int i = 0; i < 3; ++i) { particleLoc.set(entity.posX, entity.posY + 0.5D + rand.nextFloat() * entity.height, entity.posZ); PokecubeMod.core.spawnParticle(entity.getEntityWorld(), "mobSpell", particleLoc, vel); } } protected void spawnPoisonParticle(Entity entity) { Random rand = new Random(); Vector3 particleLoc = Vector3.getNewVector(); int i = 0xFFFF00FF; double d0 = (i >> 16 & 255) / 255.0D; double d1 = (i >> 8 & 255) / 255.0D; double d2 = (i >> 0 & 255) / 255.0D; Vector3 vel = Vector3.getNewVector().set(d0, d1, d2); for (i = 0; i < 3; ++i) { particleLoc.set(entity.posX, entity.posY + 0.5D + rand.nextFloat() * entity.height, entity.posZ); PokecubeMod.core.spawnParticle(entity.getEntityWorld(), "mobSpell", particleLoc, vel); } } } private Status status; public PersistantStatusEffect() { super(ID); } public PersistantStatusEffect(byte status, int timer) { super(ID); this.status = Status.getStatus(status); if (this.status == null) { PokecubeMod.log(Level.WARNING, "Error setting of status. " + status, new IllegalArgumentException()); } this.setDuration(timer); } @Override public void affectTarget(IOngoingAffected target) { if (status == null) { IPokemob pokemob = CapabilityPokemob.getPokemobFor(target.getEntity()); if (pokemob == null || pokemob.getStatus() == IMoveConstants.STATUS_NON) { setDuration(0); } else if (pokemob != null) { status = Status.getStatus(pokemob.getStatus()); } } IStatusEffect effect = EFFECTMAP.get(status); if (effect != null) { StatusEvent event = new StatusEvent(target.getEntity(), status); if (!PokecubeMod.MOVE_BUS.post(event)) { effect.setTick(getDuration()); effect.affectTarget(target, this); } } } @Override public void deserializeNBT(NBTTagCompound nbt) { super.deserializeNBT(nbt); if (nbt.hasKey("S")) this.status = Status.values()[nbt.getByte("S")]; else this.setDuration(0); } @Override public NBTTagCompound serializeNBT() { NBTTagCompound tag = super.serializeNBT(); if (status != null) tag.setByte("S", (byte) status.ordinal()); return tag; } }
juniorsgithub/demboyz
demboyz/netmessages/svc_bspdecal.cpp
#include "svc_bspdecal.h" #include "base/bitfile.h" #include "base/jsonfile.h" #include "demofile/demojson.h" #include "netcontants.h" namespace NetHandlers { bool SVC_BSPDecal_BitRead_Internal(BitRead& bitbuf, SourceGameContext& context, NetMsg::SVC_BSPDecal* data) { bitbuf.ReadBitVec3Coord(data->position); data->decalTextureIndex = bitbuf.ReadUBitLong(MAX_DECAL_INDEX_BITS); if (bitbuf.ReadOneBit() != 0) { data->entIndex = bitbuf.ReadUBitLong(MAX_EDICT_BITS); data->modelIndex = bitbuf.ReadUBitLong(SP_MODEL_INDEX_BITS); } else { data->entIndex = 0; data->modelIndex = 0; } data->lowPriority = bitbuf.ReadOneBit() != 0; return !bitbuf.IsOverflowed(); } bool SVC_BSPDecal_BitWrite_Internal(BitWrite& bitbuf, const SourceGameContext& context, NetMsg::SVC_BSPDecal* data) { bitbuf.WriteBitVec3Coord(data->position); bitbuf.WriteUBitLong(data->decalTextureIndex, MAX_DECAL_INDEX_BITS); if (data->entIndex != 0) { bitbuf.WriteOneBit(1); bitbuf.WriteUBitLong(data->entIndex, MAX_EDICT_BITS); bitbuf.WriteUBitLong(data->modelIndex, SP_MODEL_INDEX_BITS); } else { bitbuf.WriteOneBit(0); } bitbuf.WriteOneBit(data->lowPriority); return !bitbuf.IsOverflowed(); } bool SVC_BSPDecal_JsonRead_Internal(JsonRead& jsonbuf, SourceGameContext& context, NetMsg::SVC_BSPDecal* data) { base::JsonReaderObject reader = jsonbuf.ParseObject(); assert(!reader.HasReadError()); DemoJsonReader::ReadVector(reader, "position", data->position); data->decalTextureIndex = reader.ReadUInt32("decalTextureIndex"); data->entIndex = reader.ReadUInt32("entIndex"); data->modelIndex = reader.ReadUInt32("modelIndex"); data->lowPriority = reader.ReadBool("lowPriority"); return !reader.HasReadError(); } bool SVC_BSPDecal_JsonWrite_Internal(JsonWrite& jsonbuf, const SourceGameContext& context, NetMsg::SVC_BSPDecal* data) { jsonbuf.Reset(); jsonbuf.StartObject(); DemoJsonWriter::WriteVector(jsonbuf, "position", data->position); jsonbuf.WriteUInt32("decalTextureIndex", data->decalTextureIndex); jsonbuf.WriteUInt32("entIndex", data->entIndex); jsonbuf.WriteUInt32("modelIndex", data->modelIndex); jsonbuf.WriteBool("lowPriority", data->lowPriority); jsonbuf.EndObject(); return jsonbuf.IsComplete(); } void SVC_BSPDecal_ToString_Internal(std::ostringstream& out, NetMsg::SVC_BSPDecal* data) { out << "svc_BSPDecal: tex " << data->decalTextureIndex << ", ent " << data->entIndex << ", mod " << data->modelIndex << " lowpriority " << data->lowPriority; } }
janniklaskeck/FlatWaveNew
Source/FlatWave/Characters/FWFloatingDamageComponent.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/WidgetComponent.h" #include "FWFloatingDamageComponent.generated.h" UCLASS() class FLATWAVE_API UFWFloatingDamageComponent : public UWidgetComponent { GENERATED_BODY() protected: void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) override; UPROPERTY(EditDefaultsOnly) float TimeToDestroy = 1.f; UPROPERTY(EditDefaultsOnly) float MoveSpeed = 100.f; public: void SetDamageValue(float DamageValue); private: float DestroyCounter; };
rgolangh/cloud-credential-operator
vendor/google.golang.org/genproto/googleapis/ads/googleads/v1/resources/carrier_constant.pb.go
<reponame>rgolangh/cloud-credential-operator<filename>vendor/google.golang.org/genproto/googleapis/ads/googleads/v1/resources/carrier_constant.pb.go // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/ads/googleads/v1/resources/carrier_constant.proto package resources import ( fmt "fmt" math "math" proto "github.com/golang/protobuf/proto" wrappers "github.com/golang/protobuf/ptypes/wrappers" _ "google.golang.org/genproto/googleapis/api/annotations" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package // A carrier criterion that can be used in campaign targeting. type CarrierConstant struct { // The resource name of the carrier criterion. // Carrier criterion resource names have the form: // // `carrierConstants/{criterion_id}` ResourceName string `protobuf:"bytes,1,opt,name=resource_name,json=resourceName,proto3" json:"resource_name,omitempty"` // The ID of the carrier criterion. Id *wrappers.Int64Value `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` // The full name of the carrier in English. Name *wrappers.StringValue `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` // The country code of the country where the carrier is located, e.g., "AR", // "FR", etc. CountryCode *wrappers.StringValue `protobuf:"bytes,4,opt,name=country_code,json=countryCode,proto3" json:"country_code,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *CarrierConstant) Reset() { *m = CarrierConstant{} } func (m *CarrierConstant) String() string { return proto.CompactTextString(m) } func (*CarrierConstant) ProtoMessage() {} func (*CarrierConstant) Descriptor() ([]byte, []int) { return fileDescriptor_6b8b1da6512447a4, []int{0} } func (m *CarrierConstant) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_CarrierConstant.Unmarshal(m, b) } func (m *CarrierConstant) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_CarrierConstant.Marshal(b, m, deterministic) } func (m *CarrierConstant) XXX_Merge(src proto.Message) { xxx_messageInfo_CarrierConstant.Merge(m, src) } func (m *CarrierConstant) XXX_Size() int { return xxx_messageInfo_CarrierConstant.Size(m) } func (m *CarrierConstant) XXX_DiscardUnknown() { xxx_messageInfo_CarrierConstant.DiscardUnknown(m) } var xxx_messageInfo_CarrierConstant proto.InternalMessageInfo func (m *CarrierConstant) GetResourceName() string { if m != nil { return m.ResourceName } return "" } func (m *CarrierConstant) GetId() *wrappers.Int64Value { if m != nil { return m.Id } return nil } func (m *CarrierConstant) GetName() *wrappers.StringValue { if m != nil { return m.Name } return nil } func (m *CarrierConstant) GetCountryCode() *wrappers.StringValue { if m != nil { return m.CountryCode } return nil } func init() { proto.RegisterType((*CarrierConstant)(nil), "google.ads.googleads.v1.resources.CarrierConstant") } func init() { proto.RegisterFile("google/ads/googleads/v1/resources/carrier_constant.proto", fileDescriptor_6b8b1da6512447a4) } var fileDescriptor_6b8b1da6512447a4 = []byte{ // 363 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x8c, 0x91, 0xc1, 0x4a, 0xeb, 0x40, 0x14, 0x86, 0x49, 0x5a, 0x2e, 0xdc, 0xb4, 0x97, 0x0b, 0xc1, 0x45, 0xa9, 0x45, 0x5a, 0xa5, 0x50, 0x10, 0x26, 0x46, 0x45, 0x64, 0x5c, 0x48, 0xda, 0x45, 0xd1, 0x85, 0x94, 0x0a, 0x59, 0x48, 0xa0, 0x4c, 0x33, 0x63, 0x08, 0xb4, 0x73, 0xc2, 0xcc, 0xa4, 0xe2, 0xd2, 0x57, 0x71, 0xe9, 0xa3, 0xf8, 0x00, 0x3e, 0x84, 0x4f, 0x21, 0xcd, 0x64, 0x66, 0xa1, 0xa0, 0xee, 0xfe, 0xe4, 0x7c, 0xff, 0xff, 0x9f, 0xe4, 0x78, 0xe7, 0x19, 0x40, 0xb6, 0x62, 0x01, 0xa1, 0x32, 0xd0, 0x72, 0xab, 0x36, 0x61, 0x20, 0x98, 0x84, 0x52, 0xa4, 0x4c, 0x06, 0x29, 0x11, 0x22, 0x67, 0x62, 0x91, 0x02, 0x97, 0x8a, 0x70, 0x85, 0x0a, 0x01, 0x0a, 0xfc, 0x81, 0xc6, 0x11, 0xa1, 0x12, 0x59, 0x27, 0xda, 0x84, 0xc8, 0x3a, 0xbb, 0x3d, 0x13, 0x5e, 0xe4, 0x01, 0xe1, 0x1c, 0x14, 0x51, 0x39, 0x70, 0xa9, 0x03, 0xba, 0x7b, 0xf5, 0xb4, 0x7a, 0x5a, 0x96, 0xf7, 0xc1, 0x83, 0x20, 0x45, 0xc1, 0x44, 0x3d, 0xdf, 0x7f, 0x73, 0xbc, 0xff, 0x13, 0xdd, 0x3d, 0xa9, 0xab, 0xfd, 0x03, 0xef, 0x9f, 0x89, 0x5f, 0x70, 0xb2, 0x66, 0x1d, 0xa7, 0xef, 0x8c, 0xfe, 0xce, 0xdb, 0xe6, 0xe5, 0x0d, 0x59, 0x33, 0xff, 0xd0, 0x73, 0x73, 0xda, 0x71, 0xfb, 0xce, 0xa8, 0x75, 0xbc, 0x5b, 0xef, 0x86, 0x4c, 0x0b, 0xba, 0xe2, 0xea, 0xec, 0x34, 0x26, 0xab, 0x92, 0xcd, 0xdd, 0x9c, 0xfa, 0x47, 0x5e, 0xb3, 0x0a, 0x6a, 0x54, 0x78, 0xef, 0x0b, 0x7e, 0xab, 0x44, 0xce, 0x33, 0xcd, 0x57, 0xa4, 0x7f, 0xe9, 0xb5, 0x53, 0x28, 0xb9, 0x12, 0x8f, 0x8b, 0x14, 0x28, 0xeb, 0x34, 0x7f, 0xe1, 0x6c, 0xd5, 0x8e, 0x09, 0x50, 0x36, 0x7e, 0x72, 0xbd, 0x61, 0x0a, 0x6b, 0xf4, 0xe3, 0x0f, 0x1c, 0xef, 0x7c, 0xfa, 0xfe, 0xd9, 0x36, 0x7b, 0xe6, 0xdc, 0x5d, 0xd7, 0xd6, 0x0c, 0x56, 0x84, 0x67, 0x08, 0x44, 0x16, 0x64, 0x8c, 0x57, 0xcd, 0xe6, 0x8a, 0x45, 0x2e, 0xbf, 0x39, 0xea, 0x85, 0x55, 0xcf, 0x6e, 0x63, 0x1a, 0x45, 0x2f, 0xee, 0x60, 0xaa, 0x23, 0x23, 0x2a, 0x91, 0x96, 0x5b, 0x15, 0x87, 0x68, 0x6e, 0xc8, 0x57, 0xc3, 0x24, 0x11, 0x95, 0x89, 0x65, 0x92, 0x38, 0x4c, 0x2c, 0xf3, 0xee, 0x0e, 0xf5, 0x00, 0xe3, 0x88, 0x4a, 0x8c, 0x2d, 0x85, 0x71, 0x1c, 0x62, 0x6c, 0xb9, 0xe5, 0x9f, 0x6a, 0xd9, 0x93, 0x8f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x23, 0x97, 0x74, 0xab, 0x80, 0x02, 0x00, 0x00, }
wubo0067/calmwu-go
example/time_test/test.go
package main import ( "fmt" "reflect" "time" "github.com/wubo0067/calmwu-go/utils" ) // https://stackoverflow.com/questions/48422482/how-to-convert-utc-to-india-local-time-using-golang // https://stackoverflow.com/questions/37237223/access-current-system-time-zone func greet() { defer utils.MeasureFunc()() fmt.Println("greet") time.Sleep(time.Second) } func foo() { greet() } func main() { now := time.Now() // 得到时区 tzName, tzOffset := now.Zone() fmt.Printf("TZName:%s TZOffset:%d\n", tzName, tzOffset) location, err := time.LoadLocation("Asia/Kolkata") if err != nil { fmt.Printf("LoadLocation failed! reason:%s\n", err.Error()) } else { fmt.Println("---------Location:", location.String()) } location = time.FixedZone(tzName, tzOffset) fmt.Println("---------Location:", location.String()) //Time time.Time struct fmt.Printf("%s %s %s\n", reflect.TypeOf(now).Name(), reflect.TypeOf(now).String(), reflect.ValueOf(now).Kind().String()) fmt.Println(now, now.Unix()) fmt.Println(now.UTC(), now.UTC().Unix()) // 计算当前时间在指定时区的时间 location, _ = time.LoadLocation("UTC") fmt.Println(now.In(location)) fmt.Println("--------------------------------") fmt.Println(now.UnixNano()) fmt.Println(now.UnixNano()/int64(time.Millisecond), time.Millisecond, int64(time.Millisecond)) fmt.Println("--------------------------------") fmt.Println(now.UTC().Format(time.RFC3339)) fmt.Println(now) fmt.Println(time.Now().Format("2006-01-02T15:04:05-0700")) fmt.Println(time.Now().Format("2006-01-02 15:04:05+0800")) year, month, day := now.Date() date := fmt.Sprintf("%d%02d%02d%02d", year, month, day, now.Hour()) fmt.Println(date) location, _ = time.LoadLocation("Local") fmt.Println("Location:", location.String()) t := time.Date(year, month, day+20, 23, 59, 59, 0, location) fmt.Println(t.Local()) t = time.Date(year, month, day+1, 0, 0, 0, 0, time.UTC) fmt.Println(t.Local()) fmt.Println(t.UTC()) var index = 1 for index <= 7 { nTime := time.Now() nextDay := nTime.AddDate(0, 0, index) year, month, day := nextDay.Date() fmt.Printf("nextDay [%v] %d%02d%02d\n", nextDay, year, month, day) //fmt.Println(nextDay.Format("20060101")) index++ } endTime := time.Now().Sub(now).Seconds() t = time.Unix(int64(endTime), 0) fmt.Println(t.String()) fmt.Println(endTime) // now, _ = time.Parse("20060102 15:04:05", "20170703 00:00:00") // index = 0 // for index < 30 { // future := now.AddDate(0, 0, index) // year, month, day := future.Date() // fmt.Printf("future [%v] %d%02d%02d\n", future, year, month, day) // index++ // } nAry := make([]int, 0) nAry = append(nAry, 1) nAry = append(nAry, 2) fmt.Printf("%+v\n", nAry) //CreateTime:1500019209758 DeadTime:1500027061167 // 1500033649 foo() }
mraitmaier/pyrus
runner.py
<filename>runner.py<gh_stars>0 """ runner.py - NOTE: this module should not be run as a standalone scripts, excepts for built-in tests. """ # HISTORY ##################################################################################################################### # # 1 Jun11 MR Initial version of the file # 2 Jan12 MR Some simplification and bug-fixes (setup & cleanup actions were executed twice!) # 3 Dec14 MR Ported to Py3 # ############################################################################################################################### __description__ = "Pyrus test runner application" __version__ = "3" __author__ = "<NAME>." import sys import os import json import argparse import logging, logging.handlers from datetime import datetime #from time import sleep from pyrus.core.collector import Collector from pyrus.core.testset import TestSetJsonDecoder from pyrus.utils.iputils import check_ip from pyrus.core.teststatus import TestStatus from pyrus.core.testreport import TestReport from pyrus.core.error import Error from pyrus.core.reporter import ReporterFactory, HtmlReporter, XmlReporter from pyrus.db.mongo import MongoDbConn # Where to store results? Normally this is "$HOME/results". # Windows is of course an exception, we use %USERPROFILE% value as a base. if sys.platform == "win32" or sys.platform == "win64": PYRUS_RESULTS_DIR = os.path.join(os.environ["USERPROFILE"], "pyrus") else: PYRUS_RESULTS_DIR = os.path.expanduser(os.path.join("~", "pyrus")) # utility strings are defined START_OUTPUT_STR = "### OUTPUT #{}".format("#"*24) END_OUTPUT_STR = "### OUTPUT END #{}".format("#"*20) def now(): """Generates formatted current timestamp: "YYYY/MM/DD HH:MM:SS""" return "%s" % datetime.now().strftime("%Y/%m/%d %H:%M:%S") def fileStamp(): """Generates the formatted current timestamp for use in filenames""" return datetime.now().strftime("%Y-%m-%d_%H-%M-%S") def _createDefLogName(tsname): """default log name """ return "_".join((tsname, fileStamp())) class Runner(object): """ Runner - a class that executes the test run Well, it actually executes the test set, the TestRun class is just a container for TestSet, adding more information about the test run. Input params: finput - configuration file that defines the set of tests to be executed. Currently, XML and JSON formats are accepted as an input configuration format. The 'collector' module can dynamically determine what kind of file is supplied and can parse both formats. logfile - custom name for the log where all messages are being logged (a default filename is generated if empty) syslog - IP address of the syslog server, if needed (if empty, sending to syslog server is omitted) workdir - custom working directory where logs and other files will be stored. If empty, "$HOME/results" is defined by default. This is also true for Windows platform where %USERPROFILE% is used as a base. debug - enable debug mode (only for testing and debugging purposes) """ def __init__(self, finput, workdir, logfile=None, syslog=None, cssfile=None, xsltfile=None, debug=False): assert finput is not None self._testset = None self._log = None self._debug = debug self._css = cssfile self._xslt = xsltfile self._started = "" # execution started time flag self._finished = "" # execution finished time flag self._init(finput, workdir, logfile, syslog) # initialize data structs @property def log(self): return self._log def __str__(self): s = "\n".join(("The Runner Object instance:", "\ttest set: {}".format(self._testset.name), "\tworking dir: {}".format(self._workdir), "\tlogfile: {}".format(str(self._log)), "\tCSS file: {}". format(str(self._css)), "\tXSLT file: {}".format(str(self._xslt)), "\tdebug: {}".format(self._debug), )) return s def _init(self, finput, workdir, logfile, syslog): """Initialize the data structures""" # if configuration file is specified, parse it; otherwise exit if finput: try: col = Collector(finput) except Error as ex: print(ex) print("Exiting...") raise SystemExit(1) self._testset = col.testset else: print("Input configuration file not defined. Exiting...") raise SystemExit(1) # create default working dir if needed; create it if it does not exist if workdir: self._workdir = workdir else: self._workdir = os.path.join(PYRUS_RESULTS_DIR, "_".join(( self._testset.name.replace(" ", "_"), fileStamp()))) if not os.path.exists(self._workdir): os.makedirs(self._workdir) # define path to logfile and create logfile itself if logfile is not None: logfile = os.path.join(self._workdir, logfile) else: logfile = ".".join((os.path.join(self._workdir, "output"), "log")) self._createLogger(logfile, syslog) def _createLogger(self, filename, syslog=None): """Creates the logger and the appropriate handlers.""" self._log = logging.getLogger("Runner") self._log.setLevel(logging.INFO) timeForm = "%Y-%m-%d %H:%M:%S" f1 = logging.Formatter("%(asctime)s - %(name)s - %(message)s", timeForm) f2 = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s", timeForm) # default handler is sys.stdout sHandler = logging.StreamHandler(sys.stdout) sHandler.setLevel(logging.WARNING) sHandler.setFormatter(f1) self._log.addHandler(sHandler) # we specify logging to file fHandler = logging.FileHandler(filename, mode="a", encoding="utf-8") fHandler.setFormatter(f2) self._log.addHandler(fHandler) self.log.warning("Logger created successfully") self.log.warning("Everything will be logged to '{}'".format(filename)) # syslog logger is added if syslog IP address is specified if syslog is not None and check_ip(syslog): nHandler = logging.handlers.SysLogHandler((syslog, 514)) nHandler.setFormatter(f2) self._log.addHandler(nHandler) self.log.warning("Syslog logger created: '{}".format(syslog)) else: self.log.warning( "Syslog logger will NOT be created.") if self._debug: self._log.setLevel(logging.DEBUG) self.log.warning("Debug mode enabled.") def _runSetup(self, setup, **kwargs): """Run the setup script and check the success.""" assert setup is not None failed = False setup.execute(**kwargs) if setup.returncode != 0: failed = True return failed def _runTestCase(self, tc, **kwargs): """Execute a single test case""" self.log.warning("Starting test case: '{}'". format(tc.name)) # execute a case self.log.warning("Executing test case: {}".format(tc.name)) status, output = tc.execute(**kwargs) self.log.info(START_OUTPUT_STR) self.log.info(output) self.log.info(END_OUTPUT_STR) self.log.warning("Test case status: {}".format(status)) # finish self.log.warning("Test Case '{}' finished.".format(tc.name)) return True def run(self, **kwargs): """Run the tests.""" ts = self._testset # we need a test set to be run start = now() self._started = start self.log.warning("Starting Test Set: '{}'".format(ts.name)) self.log.warning("Execution started at '{}'".format(start)) # execute setup if ts.setup.isAutomated(): self.log.warning("Executing test set setup action") setup_failed = self._runSetup(ts.setup, **kwargs) # if setup script fails, exit immediatelly if setup_failed: self.log.error("Setup action failed.") self.log.error("There's no point to continue. Exiting...") self.__finish() return else: self.log.info(START_OUTPUT_STR) self.log.info(ts.setup.output) self.log.info(END_OUTPUT_STR) self.log.warning("Setup action exited with RC='{}'".format( ts.setup.returncode)) else: self.log.warning("No test set setup action to execute.") # execute testcases for tc in ts.testcases: self._runTestCase(tc, **kwargs) # execute cleanup if ts.cleanup.isAutomated(): self.log.warning("Executing test set cleanup action") ts.cleanup.execute(**kwargs) self.log.info(START_OUTPUT_STR) self.log.info(ts.cleanup.output) self.log.info(END_OUTPUT_STR) self.log.warning("Cleanup action exited with RC='{}'".format( ts.cleanup.returncode)) else: self.log.warning("No test set cleanup action to execute.") # finish self.__finish() def __finish(self): """Aux method that finishes the test set execution.""" stop = now() self.log.warning("Test Set '{}' finished.".format( self._testset.name)) self.log.warning("Execution finished at {}.".format(stop)) self._finished = stop def _saveReport2Db(self): """ """ conn = MongoDbConn("pyrus") db = conn.open() if db is None: self.log.warning("MongoDB connecton cannot be opened.") return self.log.warning("MongoDB connecton opened: {}".format(conn.dbName)) # create a test report #tr = TestReport(self._testset, self._started, self._finished) tr = {"testset": self._testset.toJson(), "started": self._started, "finished": self._finished} id = db.testreports.insert(tr) if id is None: self.log.warning("Report was NOT inserted into DB.") self.log.warning("Report inserted into DB.") conn.close() self.log.warning("MongoDB connection closed.") def createReport(self, name=None, include=None): """Create and write a test run report. If name is empty (None), methot creates the default report name. In this case, report is fixed to HTML. Otherwise, method tries to automagically determine the file type and to create an appropriate reporter class instance. Currently only XML and HTML reports are supported. """ # if name is empty, create default (type is HTML) if not name: name = "report.html" # HTML report by default fullname = os.path.join(self._workdir, name) self.log.warning("Trying to create report: '{}'".format(fullname)) # now create it rep = None try: rep = ReporterFactory(fullname, self._started, self._finished) except Error as ex: self.log.error("Cannot write report file '{}'".format(fullname)) self.log.error(ex) return # check for file to include (CSS or XSLT); local include has precedence if not include: if isinstance(rep, HtmlReporter): include = self._css elif isinstance(rep, XmlReporter): include = self._xslt # and write it try: rep.write(self._testset, include) self.log.warning("Report created.") except (Error, IOError) as ex: self.log.warning("Report NOT created.") self.log.error(ex) self._saveReport2Db() # XXX save the report into DB def parseArgs(): """Parse command-line arguments""" p = argparse.ArgumentParser() p.add_argument("-i", metavar="FILE", dest="input", help="Name of the input (JSON) file; [REQUIRED]", required=True) p.add_argument("-l", metavar="LOGFILE", dest="logfile", default=None, help="Name of the logfile") p.add_argument("-s", metavar="SYSLOG-IP-ADDR", dest="syslog", default=None, help="IP address of the syslog file") p.add_argument("-d", dest="debug", action="store_true", default=False, help="enable debug mode (for testing purposes only)") p.add_argument("-w", metavar="WORKDIR", dest="workdir", default=None, help="Specify working directory (default is '$HOME/results')") p.add_argument("-r", metavar="REPORTNAME", dest="report", default=None, help="set custom report name (default is ....)") p.add_argument("-c", metavar="CSS-FILE", dest="cssfile", default=None, help="a path to CSS file that will included in HTML report") p.add_argument("-x", metavar="XSLT-FILE", dest="xsltfile", default=None, help="a XSLT file that will included into XML report""") return p.parse_args() if __name__ == '__main__': args = parseArgs() r = Runner(args.input, args.workdir, args.logfile, args.syslog, args.cssfile, args.xsltfile, args.debug) r.run() r.createReport(args.report)
james-curtis/whalefallcms
public/templates/assets/modules/default/book.js
<gh_stars>0 define(["jquery", "layer", "mescroll"], function ($, layer, MeScroll, undefined, undefined) { let Controller = { detail: function (type = "cartoon") { $("#cate").addClass("selected"); Date.prototype.format = function (fmt) { var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小时 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), //季度 "S": this.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); } for (var k in o) { if (new RegExp("(" + k + ")").test(fmt)) { fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); } } return fmt; }; //章节列表 let mescroll = new MeScroll("mescroll", { down: { auto: false, callback: downCallback }, up: { callback: getListData, isBounce: false, clearEmptyId: "dataList", toTop: { src: "/templates/assets/modules/default/static/mescroll-option/mescroll-totop.png", offset: 1000 }, lazyLoad: { use: true } } }); /*下拉刷新页面*/ function downCallback() { setTimeout(function () { window.location.reload(); }, 300) } /*切换排序*/ var order = 'asc'; $(".navorder a").click(function () { var i = $(this).attr("id"); if (order != i) { order = i; $(".navorder a.active").removeClass("active"); $(this).addClass("active"); mescroll.resetUpScroll(); mescroll.hideTopBtn(); $(".qhlist").addClass("animation"); setTimeout(function () { $(".qhlist").removeClass("animation") }, 300) } }); /*获取数据*/ function getListData(page) { // var pageNum = page.num - 1; // var pageSize = page.size; // var zpid = $("#snovelId").val(); $.ajax({ type: 'GET', url: '/api/' + module + '.book/getChapterList/id/' + book_info.id + '/page/' + page.num + '/size/' + page.size + '/orderby/' + order, dataType: 'json', success: function (res) { $(".data-list").html(); // var curPageData = b.length; //内容列表 // var totalPage = b.totalPage; //总页码 mescroll.endByPage(res.data.data.length, res.data.last_page); setListData(res.data.data); //打印内容 }, error: function (e) { mescroll.endErr(); } }); } /*设置列表数据*/ function setListData(curPageData) { let listDom = document.getElementById("dataList"); for (let i = 0; i < curPageData.length; i++) { let pd = curPageData[i]; // let gold = $("#gold").val(); console.log(pd); let t = "免费", s = "free"; // 1 == pd.price ? s = "free" : // 2 == pd.price ? s = "toll" : // 3 == pd.price ? s = "vip" : // 4 == pd.price ? s = "bought" : // 5 == pd.price ? s = "read" : // 6 == pd.price ? s = "his" : // 7 == pd.price && (s = "free"); // 1 == pd.price ? t = "免费" : // 2 == pd.price ? t = gold + "阅币" : // 3 == pd.price ? t = "VIP免费" : // 4 == pd.price ? t = "已购买" : // 5 == pd.price ? t = "已看过" : // 6 == pd.price ? t = "上次看到这里" : // 7 == pd.price && (t = "限免中"); if (pd.money != 0) { s = 'vip'; t = pd.money.toString() + Config.site.score_name + ' | VIP免费'; } if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) { $(".data-list a,#startUrl").attr("target", "_self") } let str = '<a href="/index/' + module + '.chapter/show/id/' + pd.id + '" target="_blank">' + '<span class="imgs fl">' + '<img src="/templates/assets/modules/default/static/images/cover.jpg" imgurl="' + pd.image + '">' + '</span>' + '<span class="w50">' + pd.name + '<p>' + new Date(parseInt(pd.log_time != null ? pd.log_time.toString() + '000' : pd.updatetime.toString() + '000')).format('yyyy-MM-dd') + '</p></span>' + '<b class="' + s + '">' + t + '</b>' + '</a>'; let liDom = document.createElement("li"); liDom.innerHTML = str; listDom.appendChild(liDom); } } if ($("#collection_btn").hasClass('collected')) { $("#collection_btn").on('click', cancel_collection); } else { $("#collection_btn").on('click', add_collection); } function add_collection() { $.ajax({ url: "/api/user/addCollection/book_id/" + book_info.id + "/type/" + type, complete: function (xhr, statusCode) { let res = xhr.responseJSON; console.log(xhr); console.log(res); if (res.code === 1)//code=1为成功 { layer.msg(res.msg); $("#collect-name").text('已收藏'); $("#collect-num").text(parseInt($("#collect-num").text()) + 1); } else { // $(showCollectionListSelector).html(notCollectionHtml); layer.msg(res.msg); } }, }); $("#collection_btn").unbind('click',add_collection).bind('click',cancel_collection); } function cancel_collection() { $.ajax({ url: "/api/user/cancelCollection/book_id/" + book_info.id + "/type/" + type, complete: function (xhr, statusCode) { let res = xhr.responseJSON; console.log(xhr); console.log(res); if (res.code === 1)//code=1为成功 { layer.msg(res.msg); $("#collect-name").text('收藏'); $("#collect-num").text(parseInt($("#collect-num").text()) - 1); } else { layer.msg(res.msg); } }, }); $("#collection_btn").unbind('click',cancel_collection).bind('click',add_collection); } /*点赞收藏**/ // user = { // vote: function(a, b, c, e, d) { // $.ajax({ // type: "get", // url: "/json/fav/add/?btn=yes&type=" + c + "&id=" + a + "&classid=" + b, // success: function(a) { // "yes" == a ? (myTips("已加入书架"), $("#add").hide(), $("#del").show()) : "on" == a ? (myTips("删除成功"), $("#add").show(), $("#del").hide()) : myTips("请先登陆会员") // } // }) // } // }; // SQ = { // thispostion: function(a) { // var b = $(a).offset().left; // a = $(a).offset().top + $(a).height(); // return { // x: b, // y: a // } // }, // windowpostion: function(a) { // a = $(window).width() / 2 + $(window).scrollLeft(); // var b = $(window).height() / 2 + $(window).scrollTop(); // return { // x: a, // y: b // } // }, // mouseposition: function(a) { // var b = 0, // c = 0; // a = a || window.event; // if (a.pageX || a.pageY) b = a.pageX, c = a.pageY; // else if (a.clientX || a.clientY) b = a.clientX + document.body.scrollLeft + document.documentElement.scrollLeft, c = a.clientY + document.body.scrollTop + document.documentElement.scrollTop; // return { // x: b, // y: c // } // }, // Ajax: function(a) { // a = $.extend({ // type: "post", // data: "", // dataType: "jsonp", // before: function() {} // }, a); // burl = (-1 == a.request.indexOf("?") ? "?" : "&") + "_rnd=" + (new Date).getTime(); // $.ajax({ // type: a.type, // url: a.request + burl, // data: a.data, // dataType: a.dataType, // beforeSend: a.before, // success: a.respon // }) // }, // Ajax_async: function(a) { // a = $.extend({ // type: "post", // data: "", // dataType: "jsonp", // before: function() {} // }, a); // burl = (-1 == a.request.indexOf("?") ? "?" : "&") + "_rnd=" + (new Date).getTime(); // $.ajax({ // type: a.type, // url: a.request + burl, // async: !1, // data: a.data, // dataType: a.dataType, // beforeSend: a.before, // success: a.respon // }) // }, // ajaxLoginCheck: function(a) { // return "0" == a.is_login ? (SQ.Adiv(a), !1) : !0 // }, // boolIe: function() { // return $.browser.msie && "6.0" == $.browser.version ? !0 : !1 // } // }; // Digg = { // vote: function(a, b, c, e, d) { // $(".act-msg").remove(); // SQ.Ajax({ // request: "/e/extend/digg.php?id=" + a + "&classid=" + b + "&type=" + c, // data: "", // respon: function(b) { // if (!1 !== SQ.ajaxLoginCheck(b)) { // if (403 == b.status) return myTips(b.msg, "error"), !1; // var c = $(d).offset().left + 50, // f = $(d).offset().top - 20, // g = f - 30; // $("body").append("<div id='act-msg-" + a + "' class='act-msg " + b.code + "'><div class='layer-inner'>" + b.msg + "</div><em></em></div>"); // $("#act-msg-" + a).css({ // position: "absolute", // left: c, // top: f, // "z-index": "99999999" // }).animate({ // top: g // }, 300); // setTimeout(function() { // $("#act-msg-" + a).fadeOut("200") // }, 1E3); // $("#" + e).html(b.count) // } // } // }) // } // }; /*COOKIES浏览记录* $(document).ready(function() { if (localStorage.getItem(CartoonId)) { var a = localStorage.getItem(CartoonId).split(","); $("#startUrl").attr("href", a[0]); $("#startUrl").html("继续阅读 <em>(第" + a[1] + "话)</em>"); $("#history").html('<li style="background:#fafafa;"><a href="' + a[0] + '"><span class="imgs fl"><img src="' + a[3] + '"></span><span class="w50 red"><p class="timeIcon">上次浏览到</p>&nbsp;&nbsp;&nbsp;' + a[2] + "</a><b class='his'>继续阅读</b></a></li>") } else $("#startUrl").html("开始阅读 <em>(第1话)</em>"), $("#history").hide() }); */ } }; return Controller; });
tdiprima/code
recipes/Python/335029_Indent_text_like_email_clients/recipe-335029.py
<gh_stars>1000+ def LineIndent(text, indent, maxwidth=None): """ indent each new line with 'indent' """ if maxwidth: parts = [] for part in text.split('\n'): words = part.split(' ') lines = [] tmpline = '' for word in words: if len(tmpline+' '+word) > maxwidth: lines.append(tmpline.strip()) tmpline = word else: tmpline += ' ' + word lines.append(tmpline.strip()) start = "\n%s"%indent parts.append(indent + start.join(lines)) return "\n".join(parts) else: text = indent+text text = text.replace('\n','\n%s'%indent) return text def test__LineIndent(): t='''There seems to be a problem with paragraphs that are long and on '''\ '''multiple lines. Now there is a simple solution to this. First you go to ASPN and look at this example, then you download it and use '''\ '''it in your own scripts. Let's hope you're lucky.''' print LineIndent(t, '*'*4, maxwidth=50) print "--------------------------------" print LineIndent(t, '> ', maxwidth=35) print "--------------------------------" print LineIndent(t, '*'*4) if __name__=='__main__': test__LineIndent()
codilime/ds-workflow_executor
deeplang/src/main/scala/io/deepsense/deeplang/doperables/spark/wrappers/params/AFTSurvivalRegressionParams.scala
/** * Copyright 2016, deepsense.io * * 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 io.deepsense.deeplang.doperables.spark.wrappers.params import scala.language.reflectiveCalls import org.apache.spark.ml import io.deepsense.deeplang.doperables.spark.wrappers.params.common._ import io.deepsense.deeplang.params.Params import io.deepsense.deeplang.params.validators.{ArrayLengthValidator, ComplexArrayValidator, RangeValidator} import io.deepsense.deeplang.params.wrappers.spark.DoubleArrayParamWrapper trait AFTSurvivalRegressionParams extends Params with PredictorParams with HasOptionalQuantilesColumnParam { val quantileProbabilities = new DoubleArrayParamWrapper[ ml.param.Params { val quantileProbabilities: ml.param.DoubleArrayParam }]( name = "quantile probabilities", description = Some("""Param for quantile probabilities array. |Values of the quantile probabilities array should be in the range (0, 1) |and the array should be non-empty.""".stripMargin), sparkParamGetter = _.quantileProbabilities, validator = ComplexArrayValidator( rangeValidator = RangeValidator(0, 1, beginIncluded = false, endIncluded = false), lengthValidator = ArrayLengthValidator.withAtLeast(1) )) setDefault(quantileProbabilities, Array(0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99)) }
liqiangjava/lq-plat-link-parent
lq-plat-link-web/src/main/java/com/lq/plat/link/repository/InfoAccountRepository.java
<reponame>liqiangjava/lq-plat-link-parent package com.lq.plat.link.repository; import com.lq.plat.link.account.InfoAccount; import com.lq.plat.link.support.PlatFormRepository; import org.springframework.data.jpa.repository.Query; /** * 账户数据访问层 * @author 李强 * @version 1.0.0 * @date 2017/7/20 */ public interface InfoAccountRepository extends PlatFormRepository<InfoAccount> { @Query(value = "select ia.* from info_account ia where ia.info_user_id = ?1",nativeQuery=true) public InfoAccount findByUserId( Long userId); }
richung99/digitizePlots
venv/Lib/site-packages/nibabel/tests/test_nibabel_data.py
""" Tests for ``get_nibabel_data`` """ import os from os.path import dirname, realpath, join as pjoin, isdir from . import nibabel_data as nibd MY_DIR = dirname(__file__) def setup_module(): nibd.environ = {} def teardown_module(): nibd.environ = os.environ def test_get_nibabel_data(): # Test getting directory local_data = realpath(pjoin(MY_DIR, '..', '..', 'nibabel-data')) if isdir(local_data): assert nibd.get_nibabel_data() == local_data else: assert nibd.get_nibabel_data() == '' nibd.environ['NIBABEL_DATA_DIR'] = 'not_a_path' assert nibd.get_nibabel_data() == '' nibd.environ['NIBABEL_DATA_DIR'] = MY_DIR assert nibd.get_nibabel_data() == MY_DIR
zwzhang121/OpenUnReID
openunreid/core/label_generators/kmeans.py
<filename>openunreid/core/label_generators/kmeans.py # Written by <NAME> import warnings import faiss import torch from ...utils.torch_utils import to_numpy, to_torch __all__ = ["label_generator_kmeans"] @torch.no_grad() def label_generator_kmeans(cfg, features, num_classes=500, cuda=True, **kwargs): assert cfg.TRAIN.PSEUDO_LABELS.cluster == "kmeans" assert num_classes, "num_classes for kmeans is null" # num_classes = cfg.TRAIN.PSEUDO_LABELS.cluster_num if not cfg.TRAIN.PSEUDO_LABELS.use_outliers: warnings.warn("there exists no outlier point by kmeans clustering") # k-means cluster by faiss cluster = faiss.Kmeans( features.size(-1), num_classes, niter=300, verbose=True, gpu=cuda ) cluster.train(to_numpy(features)) centers = to_torch(cluster.centroids).float() _, labels = cluster.index.search(to_numpy(features), 1) labels = labels.reshape(-1) labels = to_torch(labels).long() # k-means does not have outlier points assert not (-1 in labels) return labels, centers, num_classes, None
ruby232/web-standard-functions
dist/lib/math/mod.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.mod = void 0; var operation_1 = require("./operation"); /** * Return the result of `operand1` modulo `operand2` operation * @param operand1 First operand * @param operand2 Second operand */ exports.mod = operation_1.defineBinaryOperation("mod"); //# sourceMappingURL=mod.js.map
sourav-majumder/qtlab
scripts/vibhor/making_a_VNA.py
from constants import * from ZurichInstruments_UHFLI import ZurichInstruments_UHFLI import sys import os import shutil import qt import progressbar import numpy as np import time uhf = ZurichInstruments_UHFLI('dev2232')
vbidin/p2p-dns
EagleDNS/src/se/unlogic/eagledns/plugins/zonereplicator/ReplicationClientPlugin.java
package se.unlogic.eagledns.plugins.zonereplicator; import java.rmi.ConnectException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.UnknownHostException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.List; import java.util.Timer; import javax.sql.DataSource; import se.unlogic.eagledns.Status; import se.unlogic.eagledns.plugins.BasePlugin; import se.unlogic.eagledns.zoneproviders.db.beans.DBZone; import se.unlogic.standardutils.dao.AnnotatedDAO; import se.unlogic.standardutils.dao.HighLevelQuery; import se.unlogic.standardutils.dao.RelationQuery; import se.unlogic.standardutils.dao.SimpleAnnotatedDAOFactory; import se.unlogic.standardutils.dao.SimpleDataSource; import se.unlogic.standardutils.dao.TransactionHandler; import se.unlogic.standardutils.numbers.NumberUtils; import se.unlogic.standardutils.rmi.PasswordLogin; import se.unlogic.standardutils.time.MillisecondTimeUnits; import se.unlogic.standardutils.timer.RunnableTimerTask; public class ReplicationClientPlugin extends BasePlugin implements Runnable{ private static final HighLevelQuery<DBZone> ALL_ZONES_QUERY; static{ ALL_ZONES_QUERY = new HighLevelQuery<DBZone>(); ALL_ZONES_QUERY.disableAutoRelations(true); } private static final RelationQuery RELATION_QUERY = new RelationQuery(DBZone.RECORDS_RELATION); private String serverAddress; private String rmiPassword; private Integer rmiPort; private String driver; private String url; private String username; private String password; private AnnotatedDAO<DBZone> zoneDAO; private Timer timer; private int replicationInterval = 60; @Override public void init(String name) throws Exception { super.init(name); DataSource dataSource; try { dataSource = new SimpleDataSource(driver, url, username, password); } catch (ClassNotFoundException e) { log.error("Unable to load JDBC driver " + driver, e); throw e; } SimpleAnnotatedDAOFactory annotatedDAOFactory = new SimpleAnnotatedDAOFactory(); this.zoneDAO = new AnnotatedDAO<DBZone>(dataSource,DBZone.class, annotatedDAOFactory); this.timer = new Timer(name, true); timer.scheduleAtFixedRate(new RunnableTimerTask(this), 0, this.replicationInterval * MillisecondTimeUnits.SECOND); log.info("Plugin " + this.name + " started with replication interval of " + replicationInterval + " seconds."); } @Override public void shutdown() throws Exception { if(timer != null){ timer.cancel(); } super.shutdown(); } public void run() { if(systemInterface.getStatus() != Status.STARTED){ log.debug("Incorrect system status skipping replication"); } log.debug("Replication starting..."); TransactionHandler transactionHandler = null; try{ transactionHandler = zoneDAO.createTransaction(); List<DBZone> zones = zoneDAO.getAll(ALL_ZONES_QUERY, transactionHandler); ReplicationServer server = this.getServer(); ReplicationResponse response = server.replicate(zones); //No changes found if(response == null){ log.debug("Replication completed succesfully, no changes found on server."); return; } log.info("Replication got " + response + " from server " + serverAddress + ":" + rmiPort + ", persisting changes..."); if(response.getNewZones() != null){ zoneDAO.addAll(response.getNewZones(), transactionHandler, RELATION_QUERY); } if(response.getUpdatedZones() != null){ zoneDAO.update(response.getUpdatedZones(), transactionHandler, RELATION_QUERY); } if(response.getDeletedZones() != null){ zoneDAO.delete(response.getDeletedZones(),transactionHandler); } transactionHandler.commit(); log.info("Replication completed succesfully, reloading zones."); systemInterface.reloadZones(); } catch (ConnectException e) { log.warn("Error connecting to server, " + e); } catch (UnknownHostException e) { log.warn("Error connecting to server, " + e); } catch (Exception e) { log.error("Error replicating zones from server", e); }finally{ TransactionHandler.autoClose(transactionHandler); } } @SuppressWarnings("unchecked") private ReplicationServer getServer() throws RemoteException, NotBoundException { Registry registry = LocateRegistry.getRegistry(serverAddress,rmiPort); PasswordLogin<ReplicationServerPlugin> loginHandler = (PasswordLogin<ReplicationServerPlugin>) registry.lookup("replicationLoginHandler"); return loginHandler.login(rmiPassword); } public void setServerAddress(String serverAddress) { this.serverAddress = serverAddress; } public void setRmiPassword(String rmiPassword) { this.rmiPassword = <PASSWORD>; } public void setRmiPort(String rmiPort) { this.rmiPort = NumberUtils.toInt(rmiPort); } public void setDriver(String driver) { this.driver = driver; } public void setUrl(String url) { this.url = url; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public void setReplicationInterval(String replicationInterval) { this.replicationInterval = NumberUtils.toInt(replicationInterval); } }
bobqiu/mpvue-weex
src/elements/x-pay/appPay.js
<filename>src/elements/x-pay/appPay.js export default { async appWxPay (jsThis, paras, orderId) { var response = await jsThis.$api.httpPost('api/pay/WechatAppPay', paras) if (response.status === 1) { var orderInfo = response.result uni.requestPayment({ provider: 'wxpay', orderInfo: orderInfo, // 微信、支付宝订单数据 success: function (res) { jsThis.$api.to('/pages/index?path=order_show&id=' + orderId) }, fail: function (err) { jsThis.$api.toastWarn('用户取消或者订单过期') // jsThis.$api.toastWarn(JSON.stringify(err.errMsg)) console.log(err) } }) } }, async appAliPay (jsThis, data, orderId) { var orderInfo = data.result.message uni.requestPayment({ provider: 'alipay', orderInfo: orderInfo, // 微信、支付宝订单数据 success: function (res) { jsThis.$api.to('/pages/index?path=order_show&id=' + orderId) }, fail: function (err) { jsThis.$api.toastWarn('用户取消或者订单过期') // jsThis.$api.toastWarn(JSON.stringify(err.errMsg)) console.log(err) } }) } }
gravity-addiction/nstack-monorepo
api/config.samples/squareup.js
<reponame>gravity-addiction/nstack-monorepo config = { squareup: { apiSandboxUrl: 'https://connect.squareupsandbox.com/', apiSandboxAppToken: '<PASSWORD>', apiProdUrl: 'https://connect.squareup.com/', apiProdAppToken: '<PASSWORD>', dbTables: { squareupOAuth: 'squareup.oauth_tokens', squareup: 'squareup', squareupItems: 'squareup_items', squareupFlags: 'squareup_flags', squareupOverrides: 'squareup_overrides', }, dbSPs: { procFlagged: 'squareup_flagged', procPayments: 'squareup_payments', }, storeId: 'KG10BD57D65CT', } };
issue9/orm
core/core_test.go
<reponame>issue9/orm // SPDX-License-Identifier: MIT package core import ( "testing" "github.com/issue9/assert/v2" "github.com/issue9/orm/v4/internal/flagtest" ) func TestMain(m *testing.M) { flagtest.Main(m) } func TestPKName(t *testing.T) { a := assert.New(t, false) a.Equal("xx_pk", PKName("xx")) } func TestAIName(t *testing.T) { a := assert.New(t, false) a.Equal("xx_ai", AIName("xx")) }
jiang-ruo/xlo-core
xlo-core-assembly/xlo-core-catcher/src/test/java/xlo/catcher/CatcherTest.java
<reponame>jiang-ruo/xlo-core<gh_stars>0 package xlo.catcher; import lombok.SneakyThrows; import org.junit.Test; import xlo.util.FileUtil; import javax.management.modelmbean.XMLParseException; import java.io.File; /** * @author XiaoLOrange * @time 2021.06.28 * @title */ public class CatcherTest { @Test @SneakyThrows public void ct(){ File root = FileUtil.getRoot(); File file = new File(root.getAbsolutePath() + "/xlo/catcher/catch.xml"); try { Catcher c = new Catcher(file); System.out.println(c.catcher("pass", "/backstage/js/sdf")); } catch (XMLParseException e) { e.printStackTrace(); } } }
wenmagi/StoryReader
app/src/main/java/com/anonymouser/book/view/SearchActivity.java
<reponame>wenmagi/StoryReader package com.anonymouser.book.view; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Toast; import com.aitangba.swipeback.SwipeBackActivity; import com.anonymouser.book.BookApp; import com.anonymouser.book.R; import com.anonymouser.book.adapter.SearchBookAdapter; import com.anonymouser.book.bean.SearchBookInfoBean; import com.anonymouser.book.presenter.HomePresenter; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.util.ArrayList; import java.util.Arrays; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import taobe.tec.jcc.JChineseConvertor; /** * Created by YandZD on 2017/7/24. */ public class SearchActivity extends SwipeBackActivity { @BindView(R.id.searchBookList) RecyclerView mSearchBookList; @BindView(R.id.etSearch) EditText etSearch; @BindView(R.id.ivClear) ImageView ivClear; @BindView(R.id.progressBar) ProgressBar mProgressBar; HomePresenter mPresenter; SearchBookAdapter mAdapter; TextWatcher mSearchTextListener = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (TextUtils.isEmpty(s)) { ivClear.setVisibility(View.INVISIBLE); } else { ivClear.setVisibility(View.VISIBLE); } } @Override public void afterTextChanged(Editable s) { } }; public static Intent getSearchIntent(Context context, String bookName) { Intent intent = new Intent(context, SearchActivity.class); intent.putExtra("bookName", bookName); return intent; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } setContentView(R.layout.activity_search); ButterKnife.bind(this); EventBus.getDefault().register(this); mPresenter = new HomePresenter(); init(); String bookName = getIntent().getStringExtra("bookName"); if (!TextUtils.isEmpty(bookName)) { etSearch.setText(bookName); onSearch(null); } } @Override public void onDestroy() { etSearch.removeTextChangedListener(mSearchTextListener); EventBus.getDefault().unregister(this); super.onDestroy(); } private void init() { etSearch.addTextChangedListener(mSearchTextListener); mAdapter = new SearchBookAdapter(); mSearchBookList.setLayoutManager(new LinearLayoutManager(this)); mSearchBookList.setAdapter(mAdapter); etSearch.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { // TODO Auto-generated method stub // 修改回车键功能 if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) { // 先隐藏键盘 actionSearch(); } return false; } }); } @OnClick(R.id.ivReturn) public void onReturn(View view) { finish(); } @OnClick(R.id.ivSearch) public void onSearch(View view) { actionSearch(); } private void actionSearch() { String word = etSearch.getText().toString(); if (!TextUtils.isEmpty(word)) { try { word = JChineseConvertor.getInstance().t2s(word); } catch (Exception e) { } setRotateLoading(true); mPresenter.searchBook(word); Tracker tracker = ((BookApp) getApplication()).getDefaultTracker(); tracker.send(new HitBuilders.EventBuilder() .setCategory("Action") .setAction("Search_Book") .build()); } } @OnClick(R.id.ivClear) public void onClear(View view) { etSearch.setText(""); } @Subscribe public void searchBookResults(ArrayList<SearchBookInfoBean> beans) { if (beans != null) { mAdapter.setData(beans); } if (beans != null && beans.size() == 0) { Toast.makeText(this, "没有相关小说", Toast.LENGTH_SHORT).show(); } setRotateLoading(false); if (SearchActivity.this .getCurrentFocus() != null) { ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(SearchActivity.this .getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } public void setRotateLoading(boolean isShow) { if (isShow) { mProgressBar.setVisibility(View.VISIBLE); } else { mProgressBar.setVisibility(View.GONE); } } }
ged/treequel
lib/treequel/mixins.rb
<filename>lib/treequel/mixins.rb # -*- ruby -*- #encoding: utf-8 require 'rbconfig' require 'erb' require 'etc' require 'logger' require 'treequel' require 'treequel/constants' module Treequel # A collection of various delegation code-generators that can be used to define # delegation through other methods, to instance variables, etc. module Delegation ############### module_function ############### ### Define the given +delegated_methods+ as delegators to the like-named method ### of the return value of the +delegate_method+. ### ### class MyClass ### extend Treequel::Delegation ### ### # Delegate the #bound?, #err, and #result2error methods to the connection ### # object returned by the #connection method. This allows the connection ### # to still be loaded on demand/overridden/etc. ### def_method_delegators :connection, :bound?, :err, :result2error ### ### def connection ### @connection ||= self.connect ### end ### end ### def def_method_delegators( delegate_method, *delegated_methods ) delegated_methods.each do |name| body = make_method_delegator( delegate_method, name ) define_method( name, &body ) end end ### Define the given +delegated_methods+ as delegators to the like-named method ### of the specified +ivar+. This is pretty much identical with how 'Forwardable' ### from the stdlib does delegation, but it's reimplemented here for consistency. ### ### class MyClass ### extend Treequel::Delegation ### ### # Delegate the #each method to the @collection ivar ### def_ivar_delegators :@collection, :each ### ### end ### def def_ivar_delegators( ivar, *delegated_methods ) delegated_methods.each do |name| body = make_ivar_delegator( ivar, name ) define_method( name, &body ) end end ####### private ####### ### Make the body of a delegator method that will delegate to the +name+ method ### of the object returned by the +delegate+ method. def make_method_delegator( delegate, name ) error_frame = caller(4)[0] file, line = error_frame.split( ':', 2 ) # Ruby can't parse obj.method=(*args), so we have to special-case setters... if name.to_s =~ /(\w+)=$/ name = $1 code = <<-END_CODE lambda {|*args| self.#{delegate}.#{name} = *args } END_CODE else code = <<-END_CODE lambda {|*args,&block| self.#{delegate}.#{name}(*args,&block) } END_CODE end return eval( code, nil, file, line.to_i ) end ### Make the body of a delegator method that will delegate calls to the +name+ ### method to the given +ivar+. def make_ivar_delegator( ivar, name ) error_frame = caller(4)[0] file, line = error_frame.split( ':', 2 ) # Ruby can't parse obj.method=(*args), so we have to special-case setters... if name.to_s =~ /(\w+)=$/ name = $1 code = <<-END_CODE lambda {|*args| #{ivar}.#{name} = *args } END_CODE else code = <<-END_CODE lambda {|*args,&block| #{ivar}.#{name}(*args,&block) } END_CODE end return eval( code, nil, file, line.to_i ) end end # module Delegation # A collection of key-normalization functions for various artifacts in LDAP like # attribute names, objectclass OIDs, etc. module Normalization ############### module_function ############### ### Normalize the given key, returning a downcased Symbol stripped of any invalid ### characters, and with '-' characters converted to '_'. def normalize_key( key ) return key if key.to_s =~ Treequel::Constants::Patterns::NUMERICOID return key.to_s.downcase. gsub( /[^[:alnum:]\-_]/, '' ). gsub( '-', '_' ). to_sym end ### Return a copy of +hash+ with all of its keys normalized by #normalize_key. def normalize_hash( hash ) hash = hash.dup hash.keys.each do |key| nkey = normalize_key( key ) hash[ nkey ] = hash.delete( key ) if key != nkey end return hash end end # Normalization ### Add logging to a Treequel class. Including classes get #log and #log_debug methods. module Loggable ### Inclusion callback -- extend including modules with Loggability instead for ### backward-compatibility. def self::included( mod ) mod.extend( Loggability ) mod.log_to( :treequel ) end end # module Loggable ### A collection of utilities for working with Hashes. module HashUtilities ############### module_function ############### ### Return a version of the given +hash+ with its keys transformed ### into Strings from whatever they were before. def stringify_keys( hash ) newhash = {} hash.each do |key,val| if val.is_a?( Hash ) newhash[ key.to_s ] = stringify_keys( val ) else newhash[ key.to_s ] = val end end return newhash end ### Return a duplicate of the given +hash+ with its identifier-like keys ### transformed into symbols from whatever they were before. def symbolify_keys( hash ) newhash = {} hash.each do |key,val| keysym = key.to_s.dup.untaint.to_sym if val.is_a?( Hash ) newhash[ keysym ] = symbolify_keys( val ) else newhash[ keysym ] = val end end return newhash end alias_method :internify_keys, :symbolify_keys # Recursive hash-merge function def merge_recursively( key, oldval, newval ) case oldval when Hash case newval when Hash oldval.merge( newval, &method(:merge_recursively) ) else newval end when Array case newval when Array oldval | newval else newval end else newval end end ### Normalize the attributes in +hash+ to be of the form expected by the ### LDAP library (i.e., keys as Strings, values as Arrays of Strings) def normalize_attributes( hash ) normhash = {} hash.each do |key,val| val = [ val ] unless val.is_a?( Array ) val.collect! {|obj| obj.to_s } normhash[ key.to_s ] = val end normhash.delete( 'dn' ) return normhash end end # HashUtilities ### A collection of utilities for working with Arrays. module ArrayUtilities ############### module_function ############### ### Return a version of the given +array+ with any Symbols contained in it turned into ### Strings. def stringify_array( array ) return array.collect do |item| case item when Symbol item.to_s when Array stringify_array( item ) else item end end end ### Return a version of the given +array+ with any Strings contained in it turned into ### Symbols. def symbolify_array( array ) return array.collect do |item| case item when String item.to_sym when Array symbolify_array( item ) else item end end end end # module ArrayUtilities ### A collection of attribute declaration functions module AttributeDeclarations ############### module_function ############### ### Declare predicate accessors for the attributes associated with the specified ### +symbols+. def predicate_attr( *symbols ) symbols.each do |attrname| define_method( "#{attrname}?" ) do instance_variable_defined?( "@#{attrname}" ) && instance_variable_get( "@#{attrname}" ) ? true : false end define_method( "#{attrname}=" ) do |newval| instance_variable_set( "@#{attrname}", newval ? true : false ) end alias_method "is_#{attrname}?", "#{attrname}?" end end end # module AttributeDeclarations ### A collection of ANSI color utility functions module ANSIColorUtilities # Set some ANSI escape code constants (Shamelessly stolen from Perl's # Term::ANSIColor by <NAME> <<EMAIL>> and Zenin <<EMAIL>> ANSI_ATTRIBUTES = { 'clear' => 0, 'reset' => 0, 'bold' => 1, 'dark' => 2, 'underline' => 4, 'underscore' => 4, 'blink' => 5, 'reverse' => 7, 'concealed' => 8, 'black' => 30, 'on_black' => 40, 'red' => 31, 'on_red' => 41, 'green' => 32, 'on_green' => 42, 'yellow' => 33, 'on_yellow' => 43, 'blue' => 34, 'on_blue' => 44, 'magenta' => 35, 'on_magenta' => 45, 'cyan' => 36, 'on_cyan' => 46, 'white' => 37, 'on_white' => 47 } ############### module_function ############### ### Create a string that contains the ANSI codes specified and return it def ansi_code( *attributes ) attributes.flatten! attributes.collect! {|at| at.to_s } return '' unless /(?:vt10[03]|xterm(?:-color)?|linux|screen)/i =~ ENV['TERM'] attributes = ANSI_ATTRIBUTES.values_at( *attributes ).compact.join(';') if attributes.empty? return '' else return "\e[%sm" % attributes end end ### Colorize the given +string+ with the specified +attributes+ and return it, handling ### line-endings, color reset, etc. def colorize( *args ) string = '' if block_given? string = yield else string = args.shift end ending = string[/(\s)$/] || '' string = string.rstrip return ansi_code( args.flatten ) + string + ansi_code( 'reset' ) + ending end end # module ANSIColorUtilities end # module Treequel # vim: set nosta noet ts=4 sw=4:
sicelex/EasyWeather
app/src/main/java/com/example/huang/easyweather/About.java
<gh_stars>1-10 package com.example.huang.easyweather; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.support.design.widget.CollapsingToolbarLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.TextView; import android.widget.Toast; import com.example.huang.easyweather.utilities.Utility; import java.net.URL; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class About extends AppCompatActivity { @BindView(R.id.source_code)TextView sourceCode; @BindView(R.id.csdn_blog)TextView csdnBlog; @BindView(R.id.donate)TextView donate; @BindView(R.id.share)TextView share; @BindView(R.id.qq)TextView qq; @BindView(R.id.suggest)TextView suggest; private Toolbar toolbar; private CollapsingToolbarLayout toolbarLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //沉浸式状态栏的兼容性配置 if (Build.VERSION.SDK_INT >= 21) { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); getWindow().setStatusBarColor(Color.TRANSPARENT); } setContentView(R.layout.activity_about); ButterKnife.bind(this); toolbar=(Toolbar)findViewById(R.id.about_toolbar) ; toolbarLayout=(CollapsingToolbarLayout)findViewById(R.id.about_toolbar_layout); toolbarLayout.setTitle("感谢有你"); setSupportActionBar(toolbar); //获取当前标题栏 ActionBar actionBar=this.getSupportActionBar(); //如果标题栏不为空 if(actionBar!=null){ //使左上角图标是否显示,如果设成false,则没有程序图标,仅仅就个标题,否则,显示应用程序图标,对应id actionBar.setDisplayHomeAsUpEnabled(true); } } @OnClick({R.id.source_code,R.id.csdn_blog,R.id.donate,R.id.share,R.id.qq,R.id.suggest}) public void onClick(View view){ switch (view.getId()){ case R.id.source_code:openWebsite("https://github.com/sicelex/EasyWeather");break; case R.id.csdn_blog:openWebsite("http://blog.csdn.net/a1262814100");break; case R.id.donate:openWebsite("http://192.168.3.11/image/Alipay.jpg");break; case R.id.share:openShare();break; case R.id.qq: Utility.copyToClipboard("1262814100",this); Toast.makeText(this, "QQ号已经复制到剪贴板", Toast.LENGTH_SHORT).show(); break; case R.id.suggest:openWebsite("https://www.sojump.hk/jq/15152915.aspx");break; } } private void openWebsite(String url){ Uri uri = Uri.parse(url); //指定网址 Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); //指定Action intent.setData(uri); //设置Uri*/ startActivity(intent); //启动Activity } private void openShare(){ Intent sharingIntent = new Intent(Intent.ACTION_SEND); sharingIntent.setType("text/plain"); sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject Here"); sharingIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.text_share)); startActivity(Intent.createChooser(sharingIntent, getString(R.string.title_share))); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId()==android.R.id.home){ finish(); } return super.onOptionsItemSelected(item); } }
satr/amazon-lex-alexa-getting-started
stage-4/lambda/bookstore-aws-lambda-java/src/main/java/io/github/satr/aws/lambda/bookstore/BookStoreLexLambda.java
package io.github.satr.aws.lambda.bookstore; // Copyright © 2020, github.com/satr, MIT License import com.amazonaws.regions.Regions; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.lambda.runtime.RequestHandler; import io.github.satr.aws.lambda.bookstore.repositories.database.DatabaseRepositoryFactoryImpl; import io.github.satr.aws.lambda.bookstore.request.Request; import io.github.satr.aws.lambda.bookstore.request.RequestFactory; import io.github.satr.aws.lambda.bookstore.services.*; import io.github.satr.aws.lambda.bookstore.strategies.intenthandler.IntentHandlerStrategy; import io.github.satr.aws.lambda.bookstore.strategies.intenthandler.IntentHandlerStrategyFactory; import java.util.Map; //Lambda with POJO as a respond public class BookStoreLexLambda implements RequestHandler<Map<String, Object>, Object> { private IntentHandlerStrategyFactory intentHandlerStrategyFactory; public BookStoreLexLambda() { this(new ServiceFactoryImpl(new DatabaseRepositoryFactoryImpl(getAwsRegionForDynamoDb()))); } public BookStoreLexLambda(ServiceFactory serviceFactory) { intentHandlerStrategyFactory = new IntentHandlerStrategyFactory(serviceFactory.getBookStorageService(), serviceFactory.getSearchBookResultService(), serviceFactory.getBasketService()); } @Override public Object handleRequest(Map<String, Object> input, Context context) { LambdaLogger logger = context.getLogger(); logger.log(input.toString());//Just to show the input in the CloudWatch log Request request = RequestFactory.createFrom(input); logInputProperties(logger, request); //Find intent-handle strategy by IntentName IntentHandlerStrategy intentHandlerStrategy = intentHandlerStrategyFactory.getBy(request.getIntentName()); //Handle the request for the intent return intentHandlerStrategy.handle(request, logger); } private static Regions getAwsRegionForDynamoDb() { return Regions.fromName(System.getenv("AWS_REGION")); } private void logInputProperties(LambdaLogger logger, Request request) { logger.log("UserId:" + request.getUserId()); logger.log("Bot name:" + request.getBotName()); logger.log("Current intent name:" + request.getIntentName()); Map<String, Object> slots = request.getSlots(); logger.log(slots.keySet().isEmpty() ? "No Slots" : "Slots:"); for (String slotName : slots.keySet()) logger.log(" - " + slotName + ":" + slots.get(slotName)); Map<String, Object> sessionAttributes = request.getSessionAttributes(); logger.log(sessionAttributes.keySet().isEmpty() ? "No Session Attributes" : "Session Attributes:"); for (String attr : sessionAttributes.keySet()) logger.log(" - " + attr + ":" + sessionAttributes.get(attr)); } }
kward/venue
vnc/messages/message_string.go
<gh_stars>1-10 // Code generated by "stringer -type=Message"; DO NOT EDIT package messages import "fmt" const _Message_name = "UnknownSetPixelFormatSetEncodingsFramebufferUpdateRequestKeyEventPointerEventClientCutTextFramebufferUpdateSetColorMapEntriesBellServerCutTextSleep" var _Message_index = [...]uint8{0, 7, 21, 33, 57, 65, 77, 90, 107, 125, 129, 142, 147} func (i Message) String() string { if i < 0 || i >= Message(len(_Message_index)-1) { return fmt.Sprintf("Message(%d)", i) } return _Message_name[_Message_index[i]:_Message_index[i+1]] }
hjjohny/editor
src/com.mentor.nucleus.bp.core/src/com/mentor/nucleus/bp/core/Unrelate_c.java
package com.mentor.nucleus.bp.core; //==================================================================== // // File: com.mentor.nucleus.bp.core.Unrelate_c.java // // WARNING: Do not edit this generated file // Generated by ../MC-Java/java.arc, $Revision: 1.111 $ // // (c) Copyright 2005-2014 by Mentor Graphics Corp. All rights reserved. // //==================================================================== // No special imports import java.util.*; import java.lang.reflect.*; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import com.mentor.nucleus.bp.core.util.PersistenceUtil; import org.eclipse.core.runtime.NullProgressMonitor; import com.mentor.nucleus.bp.core.ui.marker.UmlProblem; import com.mentor.nucleus.bp.core.common.*; abstract class EV_UNRELATE extends genericEvent_c { public abstract int getEvtcode(); } public class Unrelate_c extends NonRootModelElement implements IAdaptable, Cloneable { // Public Constructors public Unrelate_c(ModelRoot modelRoot, java.util.UUID p_m_statement_id, java.util.UUID p_m_one_side_var_id, java.util.UUID p_m_other_side_var_id, String p_m_relationship_phrase, java.util.UUID p_m_rel_id, int p_m_associationnumberlinenumber, int p_m_associationnumbercolumn, int p_m_associationphraselinenumber, int p_m_associationphrasecolumn) { super(modelRoot); //pre-process the uuid so that we re-use null uuid instance rather then creating a new one. m_statement_id = IdAssigner.preprocessUUID(p_m_statement_id); //pre-process the uuid so that we re-use null uuid instance rather then creating a new one. m_one_side_var_id = IdAssigner.preprocessUUID(p_m_one_side_var_id); //pre-process the uuid so that we re-use null uuid instance rather then creating a new one. m_other_side_var_id = IdAssigner.preprocessUUID(p_m_other_side_var_id); m_relationship_phrase = p_m_relationship_phrase; m_associationnumberlinenumber = p_m_associationnumberlinenumber; m_associationnumbercolumn = p_m_associationnumbercolumn; m_associationphraselinenumber = p_m_associationphraselinenumber; m_associationphrasecolumn = p_m_associationphrasecolumn; //pre-process the uuid so that we re-use null uuid instance rather then creating a new one. m_rel_id = IdAssigner.preprocessUUID(p_m_rel_id); Object[] key = {m_statement_id}; addInstanceToMap(key); } static public Unrelate_c createProxy(ModelRoot modelRoot, java.util.UUID p_m_statement_id, java.util.UUID p_m_one_side_var_id, java.util.UUID p_m_other_side_var_id, String p_m_relationship_phrase, java.util.UUID p_m_rel_id, int p_m_associationnumberlinenumber, int p_m_associationnumbercolumn, int p_m_associationphraselinenumber, int p_m_associationphrasecolumn, String p_contentPath, IPath p_localPath) { ModelRoot resolvedModelRoot = ModelRoot.findModelRoot(modelRoot, p_contentPath, p_localPath); // if a model root was not resolved it is most likely // due to a missing file of the proxy, defualt back to // the original model root if (resolvedModelRoot != null) modelRoot = resolvedModelRoot; InstanceList instances = modelRoot.getInstanceList(Unrelate_c.class); Unrelate_c new_inst = null; synchronized (instances) { Object[] key = {p_m_statement_id}; new_inst = (Unrelate_c) instances.get(key); } String contentPath = PersistenceUtil.resolveRelativePath(p_localPath, new Path(p_contentPath)); if (modelRoot.isNewCompareRoot()) { // for comparisons we do not want to change // the content path contentPath = p_contentPath; } if (new_inst != null && !modelRoot.isCompareRoot()) { PersistableModelComponent pmc = new_inst.getPersistableComponent(); if (pmc == null) { // dangling reference, redo this instance new_inst.batchUnrelate(); //pre-process the uuid so that we re-use null uuid instance rather then creating a new one. new_inst.m_statement_id = IdAssigner .preprocessUUID(p_m_statement_id); //pre-process the uuid so that we re-use null uuid instance rather then creating a new one. new_inst.m_one_side_var_id = IdAssigner .preprocessUUID(p_m_one_side_var_id); //pre-process the uuid so that we re-use null uuid instance rather then creating a new one. new_inst.m_other_side_var_id = IdAssigner .preprocessUUID(p_m_other_side_var_id); new_inst.m_relationship_phrase = p_m_relationship_phrase; new_inst.m_associationnumberlinenumber = p_m_associationnumberlinenumber; new_inst.m_associationnumbercolumn = p_m_associationnumbercolumn; new_inst.m_associationphraselinenumber = p_m_associationphraselinenumber; new_inst.m_associationphrasecolumn = p_m_associationphrasecolumn; //pre-process the uuid so that we re-use null uuid instance rather then creating a new one. new_inst.m_rel_id = IdAssigner.preprocessUUID(p_m_rel_id); } } if (new_inst == null) { // there is no instance matching the id, create a proxy // if the resource doesn't exist then this will be a dangling reference new_inst = new Unrelate_c(modelRoot, p_m_statement_id, p_m_one_side_var_id, p_m_other_side_var_id, p_m_relationship_phrase, p_m_rel_id, p_m_associationnumberlinenumber, p_m_associationnumbercolumn, p_m_associationphraselinenumber, p_m_associationphrasecolumn); new_inst.m_contentPath = contentPath; } return new_inst; } static public Unrelate_c resolveInstance(ModelRoot modelRoot, java.util.UUID p_m_statement_id, java.util.UUID p_m_one_side_var_id, java.util.UUID p_m_other_side_var_id, String p_m_relationship_phrase, java.util.UUID p_m_rel_id, int p_m_associationnumberlinenumber, int p_m_associationnumbercolumn, int p_m_associationphraselinenumber, int p_m_associationphrasecolumn) { InstanceList instances = modelRoot.getInstanceList(Unrelate_c.class); Unrelate_c source = null; synchronized (instances) { Object[] key = {p_m_statement_id}; source = (Unrelate_c) instances.get(key); if (source != null && !modelRoot.isCompareRoot()) { source.convertFromProxy(); source.batchUnrelate(); //pre-process the uuid so that we re-use null uuid instance rather then creating a new one. source.m_statement_id = IdAssigner .preprocessUUID(p_m_statement_id); //pre-process the uuid so that we re-use null uuid instance rather then creating a new one. source.m_one_side_var_id = IdAssigner .preprocessUUID(p_m_one_side_var_id); //pre-process the uuid so that we re-use null uuid instance rather then creating a new one. source.m_other_side_var_id = IdAssigner .preprocessUUID(p_m_other_side_var_id); source.m_relationship_phrase = p_m_relationship_phrase; source.m_associationnumberlinenumber = p_m_associationnumberlinenumber; source.m_associationnumbercolumn = p_m_associationnumbercolumn; source.m_associationphraselinenumber = p_m_associationphraselinenumber; source.m_associationphrasecolumn = p_m_associationphrasecolumn; //pre-process the uuid so that we re-use null uuid instance rather then creating a new one. source.m_rel_id = IdAssigner.preprocessUUID(p_m_rel_id); return source; } } // there is no instance matching the id Unrelate_c new_inst = new Unrelate_c(modelRoot, p_m_statement_id, p_m_one_side_var_id, p_m_other_side_var_id, p_m_relationship_phrase, p_m_rel_id, p_m_associationnumberlinenumber, p_m_associationnumbercolumn, p_m_associationphraselinenumber, p_m_associationphrasecolumn); return new_inst; } public Unrelate_c(ModelRoot modelRoot) { super(modelRoot); m_statement_id = IdAssigner.NULL_UUID; m_one_side_var_id = IdAssigner.NULL_UUID; m_other_side_var_id = IdAssigner.NULL_UUID; m_relationship_phrase = ""; m_rel_id = IdAssigner.NULL_UUID; Object[] key = {m_statement_id}; addInstanceToMap(key); } public Object getInstanceKey() { Object[] key = {m_statement_id}; return key; } public boolean setInstanceKey(UUID p_newKey) { boolean changed = false; // round p1 // round p2 // round p3 // round p4 // round p5 if (m_statement_id != p_newKey) { m_statement_id = p_newKey; changed = true; } return changed; } public boolean equals(Object elem) { if (!(elem instanceof Unrelate_c)) { return false; } // check that the model-roots are the same if (((NonRootModelElement) elem).getModelRoot() != getModelRoot()) { return false; } return identityEquals(elem); } public boolean identityEquals(Object elem) { if (!(elem instanceof Unrelate_c)) { return false; } Unrelate_c me = (Unrelate_c) elem; // don't allow an empty id-value to produce a false positive result; // in this case, use whether the two instances are actually the same // one in memory, instead if ((IdAssigner.NULL_UUID.equals(getStatement_id()) || IdAssigner.NULL_UUID .equals(((Unrelate_c) elem).getStatement_id())) && this != elem) { return false; } if (!getStatement_id().equals(((Unrelate_c) elem).getStatement_id())) return false; return true; } public boolean cachedIdentityEquals(Object elem) { if (!(elem instanceof Unrelate_c)) { return false; } Unrelate_c me = (Unrelate_c) elem; if (!getStatement_idCachedValue().equals( ((Unrelate_c) elem).getStatement_idCachedValue())) return false; return true; } // Attributes private java.util.UUID m_statement_id; private java.util.UUID m_one_side_var_id; private java.util.UUID m_other_side_var_id; private String m_relationship_phrase; private int m_associationnumberlinenumber; private int m_associationnumbercolumn; private int m_associationphraselinenumber; private int m_associationphrasecolumn; private java.util.UUID m_rel_id; // declare association references from this class // referring navigation Variable_c OneVariable; public void relateAcrossR620To(Variable_c target) { relateAcrossR620To(target, true); } public void relateAcrossR620To(Variable_c target, boolean notifyChanges) { if (target == null) return; if (target == OneVariable) return; // already related if (OneVariable != target) { Object oldKey = getInstanceKey(); if (OneVariable != null) { OneVariable.clearBackPointerR620To(this); if (Boolean.valueOf(System.getenv("PTC_MCC_ENABLED")) == true) { //$NON-NLS-1$ Ooaofooa.log .println( ILogger.CONSISTENCY, "Unrelate_c.relateAcrossR620To(Variable_c target)", "Relate performed across R620 from Unrelate to Variable without unrelate of prior instance."); } } OneVariable = target; m_one_side_var_id = target.getVar_id(); updateInstanceKey(oldKey, getInstanceKey()); target.setBackPointerR620To(this); target.addRef(); } } public void unrelateAcrossR620From(Variable_c target) { unrelateAcrossR620From(target, true); } public void unrelateAcrossR620From(Variable_c target, boolean notifyChanges) { if (target == null) return; if (OneVariable == null) return; // already unrelated if (target != OneVariable) { Exception e = new Exception(); e.fillInStackTrace(); CorePlugin.logError( "Tried to unrelate from non-related instance across R620", e); return; } if (target != null) { target.clearBackPointerR620To(this); } if (OneVariable != null) { m_one_side_var_id = OneVariable.getVar_id(); OneVariable = null; target.removeRef(); } } public static Unrelate_c getOneACT_UNROnR620(Variable_c[] targets) { return getOneACT_UNROnR620(targets, null); } public static Unrelate_c getOneACT_UNROnR620(Variable_c[] targets, ClassQueryInterface_c test) { Unrelate_c ret_val = null; if (targets != null) { for (int i = 0; i < targets.length && ret_val == null; ++i) { ret_val = getOneACT_UNROnR620(targets[i], test); } } return ret_val; } public static Unrelate_c getOneACT_UNROnR620(Variable_c target) { return getOneACT_UNROnR620(target, null); } public static Unrelate_c getOneACT_UNROnR620(Variable_c target, boolean loadComponent) { return getOneACT_UNROnR620(target.getModelRoot(), target, null, loadComponent); } public static Unrelate_c getOneACT_UNROnR620(Variable_c target, ClassQueryInterface_c test) { if (target != null) { return getOneACT_UNROnR620(target.getModelRoot(), target, test); } return null; } public static Unrelate_c getOneACT_UNROnR620(ModelRoot modelRoot, Variable_c target, ClassQueryInterface_c test) { return getOneACT_UNROnR620(modelRoot, target, test, true); } public static Unrelate_c getOneACT_UNROnR620(ModelRoot modelRoot, Variable_c target, ClassQueryInterface_c test, boolean loadComponent) { return find_getOneACT_UNROnR620(modelRoot, target, test); } private static Unrelate_c find_getOneACT_UNROnR620(ModelRoot modelRoot, Variable_c target, ClassQueryInterface_c test) { if (target != null) { synchronized (target.backPointer_IsOneVariableUnrelateIsOneVariable_R620) { for (int i = 0; i < target.backPointer_IsOneVariableUnrelateIsOneVariable_R620 .size(); ++i) { Unrelate_c source = (Unrelate_c) target.backPointer_IsOneVariableUnrelateIsOneVariable_R620 .get(i); if (source != null && (test == null || test.evaluate(source))) { return source; } } } } // not found return null; } public static Unrelate_c[] getManyACT_UNRsOnR620(Variable_c[] targets) { return getManyACT_UNRsOnR620(targets, null); } public static Unrelate_c[] getManyACT_UNRsOnR620(Variable_c[] targets, boolean loadComponent) { return getManyACT_UNRsOnR620(targets, null, loadComponent); } public static Unrelate_c[] getManyACT_UNRsOnR620(Variable_c[] targets, ClassQueryInterface_c test) { return getManyACT_UNRsOnR620(targets, test, true); } public static Unrelate_c[] getManyACT_UNRsOnR620(Variable_c[] targets, ClassQueryInterface_c test, boolean loadComponent) { if (targets == null || targets.length == 0 || targets[0] == null) return new Unrelate_c[0]; ModelRoot modelRoot = targets[0].getModelRoot(); InstanceList instances = modelRoot.getInstanceList(Unrelate_c.class); Vector matches = new Vector(); for (int i = 0; i < targets.length; i++) { synchronized (targets[i].backPointer_IsOneVariableUnrelateIsOneVariable_R620) { for (int j = 0; j < targets[i].backPointer_IsOneVariableUnrelateIsOneVariable_R620 .size(); ++j) { Unrelate_c source = (Unrelate_c) targets[i].backPointer_IsOneVariableUnrelateIsOneVariable_R620 .get(j); if (source != null && (test == null || test.evaluate(source))) { matches.add(source); } } } } if (matches.size() > 0) { Unrelate_c[] ret_set = new Unrelate_c[matches.size()]; matches.copyInto(ret_set); return ret_set; } else { return new Unrelate_c[0]; } } public static Unrelate_c[] getManyACT_UNRsOnR620(Variable_c target) { return getManyACT_UNRsOnR620(target, null); } public static Unrelate_c[] getManyACT_UNRsOnR620(Variable_c target, boolean loadComponent) { return getManyACT_UNRsOnR620(target, null, loadComponent); } public static Unrelate_c[] getManyACT_UNRsOnR620(Variable_c target, ClassQueryInterface_c test) { return getManyACT_UNRsOnR620(target, test, true); } public static Unrelate_c[] getManyACT_UNRsOnR620(Variable_c target, ClassQueryInterface_c test, boolean loadComponent) { if (target == null) return new Unrelate_c[0]; ModelRoot modelRoot = target.getModelRoot(); Vector matches = new Vector(); synchronized (target.backPointer_IsOneVariableUnrelateIsOneVariable_R620) { for (int i = 0; i < target.backPointer_IsOneVariableUnrelateIsOneVariable_R620 .size(); ++i) { Unrelate_c source = (Unrelate_c) target.backPointer_IsOneVariableUnrelateIsOneVariable_R620 .get(i); if (source != null && (test == null || test.evaluate(source))) { matches.add(source); } } } if (matches.size() > 0) { Unrelate_c[] ret_set = new Unrelate_c[matches.size()]; matches.copyInto(ret_set); return ret_set; } else { return new Unrelate_c[0]; } } // referring navigation Variable_c OtherVariable; public void relateAcrossR621To(Variable_c target) { relateAcrossR621To(target, true); } public void relateAcrossR621To(Variable_c target, boolean notifyChanges) { if (target == null) return; if (target == OtherVariable) return; // already related if (OtherVariable != target) { Object oldKey = getInstanceKey(); if (OtherVariable != null) { OtherVariable.clearBackPointerR621To(this); if (Boolean.valueOf(System.getenv("PTC_MCC_ENABLED")) == true) { //$NON-NLS-1$ Ooaofooa.log .println( ILogger.CONSISTENCY, "Unrelate_c.relateAcrossR621To(Variable_c target)", "Relate performed across R621 from Unrelate to Variable without unrelate of prior instance."); } } OtherVariable = target; m_other_side_var_id = target.getVar_id(); updateInstanceKey(oldKey, getInstanceKey()); target.setBackPointerR621To(this); target.addRef(); } } public void unrelateAcrossR621From(Variable_c target) { unrelateAcrossR621From(target, true); } public void unrelateAcrossR621From(Variable_c target, boolean notifyChanges) { if (target == null) return; if (OtherVariable == null) return; // already unrelated if (target != OtherVariable) { Exception e = new Exception(); e.fillInStackTrace(); CorePlugin.logError( "Tried to unrelate from non-related instance across R621", e); return; } if (target != null) { target.clearBackPointerR621To(this); } if (OtherVariable != null) { m_other_side_var_id = OtherVariable.getVar_id(); OtherVariable = null; target.removeRef(); } } public static Unrelate_c getOneACT_UNROnR621(Variable_c[] targets) { return getOneACT_UNROnR621(targets, null); } public static Unrelate_c getOneACT_UNROnR621(Variable_c[] targets, ClassQueryInterface_c test) { Unrelate_c ret_val = null; if (targets != null) { for (int i = 0; i < targets.length && ret_val == null; ++i) { ret_val = getOneACT_UNROnR621(targets[i], test); } } return ret_val; } public static Unrelate_c getOneACT_UNROnR621(Variable_c target) { return getOneACT_UNROnR621(target, null); } public static Unrelate_c getOneACT_UNROnR621(Variable_c target, boolean loadComponent) { return getOneACT_UNROnR621(target.getModelRoot(), target, null, loadComponent); } public static Unrelate_c getOneACT_UNROnR621(Variable_c target, ClassQueryInterface_c test) { if (target != null) { return getOneACT_UNROnR621(target.getModelRoot(), target, test); } return null; } public static Unrelate_c getOneACT_UNROnR621(ModelRoot modelRoot, Variable_c target, ClassQueryInterface_c test) { return getOneACT_UNROnR621(modelRoot, target, test, true); } public static Unrelate_c getOneACT_UNROnR621(ModelRoot modelRoot, Variable_c target, ClassQueryInterface_c test, boolean loadComponent) { return find_getOneACT_UNROnR621(modelRoot, target, test); } private static Unrelate_c find_getOneACT_UNROnR621(ModelRoot modelRoot, Variable_c target, ClassQueryInterface_c test) { if (target != null) { synchronized (target.backPointer_IsOtherVariableUnrelateIsOtherVariable_R621) { for (int i = 0; i < target.backPointer_IsOtherVariableUnrelateIsOtherVariable_R621 .size(); ++i) { Unrelate_c source = (Unrelate_c) target.backPointer_IsOtherVariableUnrelateIsOtherVariable_R621 .get(i); if (source != null && (test == null || test.evaluate(source))) { return source; } } } } // not found return null; } public static Unrelate_c[] getManyACT_UNRsOnR621(Variable_c[] targets) { return getManyACT_UNRsOnR621(targets, null); } public static Unrelate_c[] getManyACT_UNRsOnR621(Variable_c[] targets, boolean loadComponent) { return getManyACT_UNRsOnR621(targets, null, loadComponent); } public static Unrelate_c[] getManyACT_UNRsOnR621(Variable_c[] targets, ClassQueryInterface_c test) { return getManyACT_UNRsOnR621(targets, test, true); } public static Unrelate_c[] getManyACT_UNRsOnR621(Variable_c[] targets, ClassQueryInterface_c test, boolean loadComponent) { if (targets == null || targets.length == 0 || targets[0] == null) return new Unrelate_c[0]; ModelRoot modelRoot = targets[0].getModelRoot(); InstanceList instances = modelRoot.getInstanceList(Unrelate_c.class); Vector matches = new Vector(); for (int i = 0; i < targets.length; i++) { synchronized (targets[i].backPointer_IsOtherVariableUnrelateIsOtherVariable_R621) { for (int j = 0; j < targets[i].backPointer_IsOtherVariableUnrelateIsOtherVariable_R621 .size(); ++j) { Unrelate_c source = (Unrelate_c) targets[i].backPointer_IsOtherVariableUnrelateIsOtherVariable_R621 .get(j); if (source != null && (test == null || test.evaluate(source))) { matches.add(source); } } } } if (matches.size() > 0) { Unrelate_c[] ret_set = new Unrelate_c[matches.size()]; matches.copyInto(ret_set); return ret_set; } else { return new Unrelate_c[0]; } } public static Unrelate_c[] getManyACT_UNRsOnR621(Variable_c target) { return getManyACT_UNRsOnR621(target, null); } public static Unrelate_c[] getManyACT_UNRsOnR621(Variable_c target, boolean loadComponent) { return getManyACT_UNRsOnR621(target, null, loadComponent); } public static Unrelate_c[] getManyACT_UNRsOnR621(Variable_c target, ClassQueryInterface_c test) { return getManyACT_UNRsOnR621(target, test, true); } public static Unrelate_c[] getManyACT_UNRsOnR621(Variable_c target, ClassQueryInterface_c test, boolean loadComponent) { if (target == null) return new Unrelate_c[0]; ModelRoot modelRoot = target.getModelRoot(); Vector matches = new Vector(); synchronized (target.backPointer_IsOtherVariableUnrelateIsOtherVariable_R621) { for (int i = 0; i < target.backPointer_IsOtherVariableUnrelateIsOtherVariable_R621 .size(); ++i) { Unrelate_c source = (Unrelate_c) target.backPointer_IsOtherVariableUnrelateIsOtherVariable_R621 .get(i); if (source != null && (test == null || test.evaluate(source))) { matches.add(source); } } } if (matches.size() > 0) { Unrelate_c[] ret_set = new Unrelate_c[matches.size()]; matches.copyInto(ret_set); return ret_set; } else { return new Unrelate_c[0]; } } // referring navigation Statement_c IsSupertypeStatement; public void relateAcrossR603To(Statement_c target) { relateAcrossR603To(target, true); } public void relateAcrossR603To(Statement_c target, boolean notifyChanges) { if (target == null) return; if (target == IsSupertypeStatement) return; // already related if (IsSupertypeStatement != target) { Object oldKey = getInstanceKey(); if (IsSupertypeStatement != null) { IsSupertypeStatement.clearBackPointerR603To(this); if (Boolean.valueOf(System.getenv("PTC_MCC_ENABLED")) == true) { //$NON-NLS-1$ Ooaofooa.log .println( ILogger.CONSISTENCY, "Unrelate_c.relateAcrossR603To(Statement_c target)", "Relate performed across R603 from Unrelate to Statement without unrelate of prior instance."); } } IsSupertypeStatement = target; m_statement_id = target.getStatement_id(); updateInstanceKey(oldKey, getInstanceKey()); target.setBackPointerR603To(this); target.addRef(); } } public void unrelateAcrossR603From(Statement_c target) { unrelateAcrossR603From(target, true); } public void unrelateAcrossR603From(Statement_c target, boolean notifyChanges) { if (target == null) return; if (IsSupertypeStatement == null) return; // already unrelated if (target != IsSupertypeStatement) { Exception e = new Exception(); e.fillInStackTrace(); CorePlugin.logError( "Tried to unrelate from non-related instance across R603", e); return; } if (target != null) { target.clearBackPointerR603To(this); } if (IsSupertypeStatement != null) { m_statement_id = IsSupertypeStatement.getStatement_id(); IsSupertypeStatement = null; target.removeRef(); } } public static Unrelate_c getOneACT_UNROnR603(Statement_c[] targets) { return getOneACT_UNROnR603(targets, null); } public static Unrelate_c getOneACT_UNROnR603(Statement_c[] targets, ClassQueryInterface_c test) { Unrelate_c ret_val = null; if (targets != null) { for (int i = 0; i < targets.length && ret_val == null; ++i) { ret_val = getOneACT_UNROnR603(targets[i], test); } } return ret_val; } public static Unrelate_c getOneACT_UNROnR603(Statement_c target) { return getOneACT_UNROnR603(target, null); } public static Unrelate_c getOneACT_UNROnR603(Statement_c target, boolean loadComponent) { return getOneACT_UNROnR603(target.getModelRoot(), target, null, loadComponent); } public static Unrelate_c getOneACT_UNROnR603(Statement_c target, ClassQueryInterface_c test) { if (target != null) { return getOneACT_UNROnR603(target.getModelRoot(), target, test); } return null; } public static Unrelate_c getOneACT_UNROnR603(ModelRoot modelRoot, Statement_c target, ClassQueryInterface_c test) { return getOneACT_UNROnR603(modelRoot, target, test, true); } public static Unrelate_c getOneACT_UNROnR603(ModelRoot modelRoot, Statement_c target, ClassQueryInterface_c test, boolean loadComponent) { return find_getOneACT_UNROnR603(modelRoot, target, test); } private static Unrelate_c find_getOneACT_UNROnR603(ModelRoot modelRoot, Statement_c target, ClassQueryInterface_c test) { if (target != null) { Unrelate_c source = (Unrelate_c) target.backPointer_IsSubtypeUnrelateIsSubtype_R603; if (source != null && (test == null || test.evaluate(source))) { return source; } } // not found return null; } public static Unrelate_c[] getManyACT_UNRsOnR603(Statement_c[] targets) { return getManyACT_UNRsOnR603(targets, null); } public static Unrelate_c[] getManyACT_UNRsOnR603(Statement_c[] targets, boolean loadComponent) { return getManyACT_UNRsOnR603(targets, null, loadComponent); } public static Unrelate_c[] getManyACT_UNRsOnR603(Statement_c[] targets, ClassQueryInterface_c test) { return getManyACT_UNRsOnR603(targets, test, true); } public static Unrelate_c[] getManyACT_UNRsOnR603(Statement_c[] targets, ClassQueryInterface_c test, boolean loadComponent) { if (targets == null || targets.length == 0 || targets[0] == null) return new Unrelate_c[0]; ModelRoot modelRoot = targets[0].getModelRoot(); InstanceList instances = modelRoot.getInstanceList(Unrelate_c.class); Vector matches = new Vector(); for (int i = 0; i < targets.length; i++) { Unrelate_c source = (Unrelate_c) targets[i].backPointer_IsSubtypeUnrelateIsSubtype_R603; if (source != null && (test == null || test.evaluate(source))) { matches.add(source); } } if (matches.size() > 0) { Unrelate_c[] ret_set = new Unrelate_c[matches.size()]; matches.copyInto(ret_set); return ret_set; } else { return new Unrelate_c[0]; } } public static Unrelate_c[] getManyACT_UNRsOnR603(Statement_c target) { if (target != null) { Statement_c[] targetArray = new Statement_c[1]; targetArray[0] = target; return getManyACT_UNRsOnR603(targetArray); } else { Unrelate_c[] result = new Unrelate_c[0]; return result; } } public static Unrelate_c[] getManyACT_UNRsOnR603(Statement_c target, boolean loadComponent) { if (target != null) { Statement_c[] targetArray = new Statement_c[1]; targetArray[0] = target; return getManyACT_UNRsOnR603(targetArray, loadComponent); } else { Unrelate_c[] result = new Unrelate_c[0]; return result; } } // referring navigation Association_c DestroysAssociation; public void relateAcrossR655To(Association_c target) { relateAcrossR655To(target, true); } public void relateAcrossR655To(Association_c target, boolean notifyChanges) { if (target == null) return; if (target == DestroysAssociation) return; // already related if (DestroysAssociation != target) { Object oldKey = getInstanceKey(); if (DestroysAssociation != null) { DestroysAssociation.clearBackPointerR655To(this); if (Boolean.valueOf(System.getenv("PTC_MCC_ENABLED")) == true) { //$NON-NLS-1$ Ooaofooa.log .println( ILogger.CONSISTENCY, "Unrelate_c.relateAcrossR655To(Association_c target)", "Relate performed across R655 from Unrelate to Association without unrelate of prior instance."); } } DestroysAssociation = target; if (IdAssigner.NULL_UUID.equals(target.getRel_id())) { // do not update cached value } else { // update cached value m_rel_id = target.getRel_idCachedValue(); } updateInstanceKey(oldKey, getInstanceKey()); target.setBackPointerR655To(this); target.addRef(); } } public void unrelateAcrossR655From(Association_c target) { unrelateAcrossR655From(target, true); } public void unrelateAcrossR655From(Association_c target, boolean notifyChanges) { if (target == null) return; if (DestroysAssociation == null) return; // already unrelated if (target != DestroysAssociation) { Exception e = new Exception(); e.fillInStackTrace(); CorePlugin.logError( "Tried to unrelate from non-related instance across R655", e); return; } if (target != null) { target.clearBackPointerR655To(this); } if (DestroysAssociation != null) { m_rel_id = DestroysAssociation.getRel_id(); if (IdAssigner.NULL_UUID.equals(m_rel_id)) { m_rel_id = DestroysAssociation.getRel_idCachedValue(); } DestroysAssociation = null; target.removeRef(); } } public static Unrelate_c getOneACT_UNROnR655(Association_c[] targets) { return getOneACT_UNROnR655(targets, null); } public static Unrelate_c getOneACT_UNROnR655(Association_c[] targets, ClassQueryInterface_c test) { Unrelate_c ret_val = null; if (targets != null) { for (int i = 0; i < targets.length && ret_val == null; ++i) { ret_val = getOneACT_UNROnR655(targets[i], test); } } return ret_val; } public static Unrelate_c getOneACT_UNROnR655(Association_c target) { return getOneACT_UNROnR655(target, null); } public static Unrelate_c getOneACT_UNROnR655(Association_c target, boolean loadComponent) { return getOneACT_UNROnR655(target.getModelRoot(), target, null, loadComponent); } public static Unrelate_c getOneACT_UNROnR655(Association_c target, ClassQueryInterface_c test) { if (target != null) { return getOneACT_UNROnR655(target.getModelRoot(), target, test); } return null; } public static Unrelate_c getOneACT_UNROnR655(ModelRoot modelRoot, Association_c target, ClassQueryInterface_c test) { return getOneACT_UNROnR655(modelRoot, target, test, true); } public static Unrelate_c getOneACT_UNROnR655(ModelRoot modelRoot, Association_c target, ClassQueryInterface_c test, boolean loadComponent) { return find_getOneACT_UNROnR655(modelRoot, target, test); } private static Unrelate_c find_getOneACT_UNROnR655(ModelRoot modelRoot, Association_c target, ClassQueryInterface_c test) { if (target != null) { synchronized (target.backPointer_Unrelate_R655) { for (int i = 0; i < target.backPointer_Unrelate_R655.size(); ++i) { Unrelate_c source = (Unrelate_c) target.backPointer_Unrelate_R655 .get(i); if (source != null && (test == null || test.evaluate(source))) { return source; } } } } // not found return null; } public static Unrelate_c[] getManyACT_UNRsOnR655(Association_c[] targets) { return getManyACT_UNRsOnR655(targets, null); } public static Unrelate_c[] getManyACT_UNRsOnR655(Association_c[] targets, boolean loadComponent) { return getManyACT_UNRsOnR655(targets, null, loadComponent); } public static Unrelate_c[] getManyACT_UNRsOnR655(Association_c[] targets, ClassQueryInterface_c test) { return getManyACT_UNRsOnR655(targets, test, true); } public static Unrelate_c[] getManyACT_UNRsOnR655(Association_c[] targets, ClassQueryInterface_c test, boolean loadComponent) { if (targets == null || targets.length == 0 || targets[0] == null) return new Unrelate_c[0]; ModelRoot modelRoot = targets[0].getModelRoot(); InstanceList instances = modelRoot.getInstanceList(Unrelate_c.class); Vector matches = new Vector(); for (int i = 0; i < targets.length; i++) { synchronized (targets[i].backPointer_Unrelate_R655) { for (int j = 0; j < targets[i].backPointer_Unrelate_R655.size(); ++j) { Unrelate_c source = (Unrelate_c) targets[i].backPointer_Unrelate_R655 .get(j); if (source != null && (test == null || test.evaluate(source))) { matches.add(source); } } } } if (matches.size() > 0) { Unrelate_c[] ret_set = new Unrelate_c[matches.size()]; matches.copyInto(ret_set); return ret_set; } else { return new Unrelate_c[0]; } } public static Unrelate_c[] getManyACT_UNRsOnR655(Association_c target) { return getManyACT_UNRsOnR655(target, null); } public static Unrelate_c[] getManyACT_UNRsOnR655(Association_c target, boolean loadComponent) { return getManyACT_UNRsOnR655(target, null, loadComponent); } public static Unrelate_c[] getManyACT_UNRsOnR655(Association_c target, ClassQueryInterface_c test) { return getManyACT_UNRsOnR655(target, test, true); } public static Unrelate_c[] getManyACT_UNRsOnR655(Association_c target, ClassQueryInterface_c test, boolean loadComponent) { if (target == null) return new Unrelate_c[0]; ModelRoot modelRoot = target.getModelRoot(); Vector matches = new Vector(); synchronized (target.backPointer_Unrelate_R655) { for (int i = 0; i < target.backPointer_Unrelate_R655.size(); ++i) { Unrelate_c source = (Unrelate_c) target.backPointer_Unrelate_R655 .get(i); if (source != null && (test == null || test.evaluate(source))) { matches.add(source); } } } if (matches.size() > 0) { Unrelate_c[] ret_set = new Unrelate_c[matches.size()]; matches.copyInto(ret_set); return ret_set; } else { return new Unrelate_c[0]; } } public void batchRelate(ModelRoot modelRoot, boolean notifyChanges, boolean searchAllRoots) { batchRelate(modelRoot, false, notifyChanges, searchAllRoots); } public void batchRelate(ModelRoot modelRoot, boolean relateProxies, boolean notifyChanges, boolean searchAllRoots) { InstanceList instances = null; ModelRoot baseRoot = modelRoot; if (OneVariable == null) { // R620 Variable_c relInst39178 = (Variable_c) baseRoot.getInstanceList( Variable_c.class).get(new Object[]{m_one_side_var_id}); // if there was no local element, check for any global elements // failing that proceed to check other model roots if (relInst39178 == null) { relInst39178 = (Variable_c) Ooaofooa.getDefaultInstance() .getInstanceList(Variable_c.class) .get(new Object[]{m_one_side_var_id}); } if (relInst39178 == null && searchAllRoots && !baseRoot.isCompareRoot()) { Ooaofooa[] roots = Ooaofooa.getInstances(); for (int i = 0; i < roots.length; i++) { if (roots[i].isCompareRoot()) { // never use elements from any compare root continue; } relInst39178 = (Variable_c) roots[i].getInstanceList( Variable_c.class).get( new Object[]{m_one_side_var_id}); if (relInst39178 != null) break; } } //synchronized if (relInst39178 != null) { if (relateProxies || !isProxy() || (inSameComponent(this, relInst39178) && !isProxy())) { relInst39178.relateAcrossR620To(this, notifyChanges); } } } if (OtherVariable == null) { // R621 Variable_c relInst39179 = (Variable_c) baseRoot.getInstanceList( Variable_c.class).get(new Object[]{m_other_side_var_id}); // if there was no local element, check for any global elements // failing that proceed to check other model roots if (relInst39179 == null) { relInst39179 = (Variable_c) Ooaofooa.getDefaultInstance() .getInstanceList(Variable_c.class) .get(new Object[]{m_other_side_var_id}); } if (relInst39179 == null && searchAllRoots && !baseRoot.isCompareRoot()) { Ooaofooa[] roots = Ooaofooa.getInstances(); for (int i = 0; i < roots.length; i++) { if (roots[i].isCompareRoot()) { // never use elements from any compare root continue; } relInst39179 = (Variable_c) roots[i].getInstanceList( Variable_c.class).get( new Object[]{m_other_side_var_id}); if (relInst39179 != null) break; } } //synchronized if (relInst39179 != null) { if (relateProxies || !isProxy() || (inSameComponent(this, relInst39179) && !isProxy())) { relInst39179.relateAcrossR621To(this, notifyChanges); } } } // R603 Statement_c relInst39180 = (Statement_c) baseRoot.getInstanceList( Statement_c.class).get(new Object[]{m_statement_id}); // if there was no local element, check for any global elements // failing that proceed to check other model roots if (relInst39180 == null) { relInst39180 = (Statement_c) Ooaofooa.getDefaultInstance() .getInstanceList(Statement_c.class) .get(new Object[]{m_statement_id}); } if (relInst39180 == null && searchAllRoots && !baseRoot.isCompareRoot()) { Ooaofooa[] roots = Ooaofooa.getInstances(); for (int i = 0; i < roots.length; i++) { if (roots[i].isCompareRoot()) { // never use elements from any compare root continue; } relInst39180 = (Statement_c) roots[i].getInstanceList( Statement_c.class).get(new Object[]{m_statement_id}); if (relInst39180 != null) break; } } //synchronized if (relInst39180 != null) { if (relateProxies || !isProxy() || (inSameComponent(this, relInst39180) && !isProxy())) { relInst39180.relateAcrossR603To(this, notifyChanges); } } if (DestroysAssociation == null) { // R655 Association_c relInst39181 = (Association_c) baseRoot .getInstanceList(Association_c.class).get( new Object[]{m_rel_id}); // if there was no local element, check for any global elements // failing that proceed to check other model roots if (relInst39181 == null) { relInst39181 = (Association_c) Ooaofooa.getDefaultInstance() .getInstanceList(Association_c.class) .get(new Object[]{m_rel_id}); } if (relInst39181 == null && searchAllRoots && !baseRoot.isCompareRoot()) { Ooaofooa[] roots = Ooaofooa.getInstances(); for (int i = 0; i < roots.length; i++) { if (roots[i].isCompareRoot()) { // never use elements from any compare root continue; } relInst39181 = (Association_c) roots[i].getInstanceList( Association_c.class).get(new Object[]{m_rel_id}); if (relInst39181 != null) break; } } //synchronized if (relInst39181 != null) { if (relateProxies || !isProxy() || (inSameComponent(this, relInst39181) && !isProxy())) { relInst39181.relateAcrossR655To(this, notifyChanges); } } } } public void batchUnrelate(boolean notifyChanges) { NonRootModelElement inst = null; // R620 // V_VAR inst = OneVariable; unrelateAcrossR620From(OneVariable, notifyChanges); if (inst != null) { inst.removeRef(); } // R621 // V_VAR inst = OtherVariable; unrelateAcrossR621From(OtherVariable, notifyChanges); if (inst != null) { inst.removeRef(); } // R603 // ACT_SMT inst = IsSupertypeStatement; unrelateAcrossR603From(IsSupertypeStatement, notifyChanges); if (inst != null) { inst.removeRef(); } // R655 // R_REL inst = DestroysAssociation; unrelateAcrossR655From(DestroysAssociation, notifyChanges); if (inst != null) { inst.removeRef(); } } public static void batchRelateAll(ModelRoot modelRoot, boolean notifyChanges, boolean searchAllRoots) { batchRelateAll(modelRoot, notifyChanges, searchAllRoots, false); } public static void batchRelateAll(ModelRoot modelRoot, boolean notifyChanges, boolean searchAllRoots, boolean relateProxies) { InstanceList instances = modelRoot.getInstanceList(Unrelate_c.class); synchronized(instances) { Iterator<NonRootModelElement> cursor = instances.iterator() ; while (cursor.hasNext()) { final Unrelate_c inst = (Unrelate_c)cursor.next() ; inst.batchRelate(modelRoot, relateProxies, notifyChanges, searchAllRoots ); } } } public static void clearInstances(ModelRoot modelRoot) { InstanceList instances = modelRoot.getInstanceList(Unrelate_c.class); synchronized (instances) { for (int i = instances.size() - 1; i >= 0; i--) { ((NonRootModelElement) instances.get(i)).delete_unchecked(); } } } public static Unrelate_c UnrelateInstance(ModelRoot modelRoot, ClassQueryInterface_c test, boolean loadComponent) { Unrelate_c result = findUnrelateInstance(modelRoot, test, loadComponent); return result; } private static Unrelate_c findUnrelateInstance(ModelRoot modelRoot, ClassQueryInterface_c test, boolean loadComponent) { InstanceList instances = modelRoot.getInstanceList(Unrelate_c.class); synchronized (instances) { for (int i = 0; i < instances.size(); ++i) { Unrelate_c x = (Unrelate_c) instances.get(i); if (test == null || test.evaluate(x)) { return x; } } } return null; } public static Unrelate_c UnrelateInstance(ModelRoot modelRoot, ClassQueryInterface_c test) { return UnrelateInstance(modelRoot, test, true); } public static Unrelate_c UnrelateInstance(ModelRoot modelRoot) { return UnrelateInstance(modelRoot, null, true); } public static Unrelate_c[] UnrelateInstances(ModelRoot modelRoot, ClassQueryInterface_c test, boolean loadComponent) { InstanceList instances = modelRoot.getInstanceList(Unrelate_c.class); Vector matches = new Vector(); synchronized (instances) { for (int i = 0; i < instances.size(); ++i) { Unrelate_c x = (Unrelate_c) instances.get(i); if (test == null || test.evaluate(x)) { matches.add(x); } } if (matches.size() > 0) { Unrelate_c[] ret_set = new Unrelate_c[matches.size()]; matches.copyInto(ret_set); return ret_set; } else { return new Unrelate_c[0]; } } } public static Unrelate_c[] UnrelateInstances(ModelRoot modelRoot, ClassQueryInterface_c test) { return UnrelateInstances(modelRoot, test, true); } public static Unrelate_c[] UnrelateInstances(ModelRoot modelRoot) { return UnrelateInstances(modelRoot, null, true); } public boolean delete() { boolean result = super.delete(); boolean delete_error = false; String errorMsg = "The following relationships were not torn down by the Unrelate.dispose call: "; Variable_c testR620Inst = Variable_c.getOneV_VAROnR620(this, false); if (testR620Inst != null) { delete_error = true; errorMsg = errorMsg + "620 "; } Variable_c testR621Inst = Variable_c.getOneV_VAROnR621(this, false); if (testR621Inst != null) { delete_error = true; errorMsg = errorMsg + "621 "; } Statement_c testR603Inst18 = Statement_c.getOneACT_SMTOnR603(this, false); if (testR603Inst18 != null) { delete_error = true; errorMsg = errorMsg + "603 "; } Association_c testR655Inst = Association_c.getOneR_RELOnR655(this, false); if (testR655Inst != null) { delete_error = true; errorMsg = errorMsg + "655 "; } if (delete_error == true) { if (CorePlugin.getDefault().isDebugging()) { Ooaofooa.log.println(ILogger.DELETE, "Unrelate", errorMsg); } else { Exception e = new Exception(); e.fillInStackTrace(); CorePlugin.logError(errorMsg, e); } } return result; } // end declare instance pool // declare attribute accessors public boolean isUUID(String attributeName) { if (attributeName.equals("statement_id")) { return true; } if (attributeName.equals("one_side_var_id")) { return true; } if (attributeName.equals("other_side_var_id")) { return true; } if (attributeName.equals("rel_id")) { return true; } return false; } // declare attribute accessors public long getStatement_idLongBased() { if (IsSupertypeStatement != null) { return IsSupertypeStatement.getStatement_idLongBased(); } return 0; } public java.util.UUID getStatement_id() { if (IsSupertypeStatement != null) { return IsSupertypeStatement.getStatement_id(); } return IdAssigner.NULL_UUID; } public boolean hasSuperType() { return (IsSupertypeStatement != null); } public java.util.UUID getStatement_idCachedValue() { if (!IdAssigner.NULL_UUID.equals(m_statement_id)) return m_statement_id; else return getStatement_id(); } public void setStatement_id(java.util.UUID newValue) { m_statement_id = IdAssigner.preprocessUUID(newValue); } public long getOne_side_var_idLongBased() { if (OneVariable != null) { return OneVariable.getVar_idLongBased(); } return 0; } public java.util.UUID getOne_side_var_id() { if (OneVariable != null) { return OneVariable.getVar_id(); } return IdAssigner.NULL_UUID; } public java.util.UUID getOne_side_var_idCachedValue() { if (!IdAssigner.NULL_UUID.equals(m_one_side_var_id)) return m_one_side_var_id; else return getOne_side_var_id(); } public void setOne_side_var_id(java.util.UUID newValue) { m_one_side_var_id = IdAssigner.preprocessUUID(newValue); } public long getOther_side_var_idLongBased() { if (OtherVariable != null) { return OtherVariable.getVar_idLongBased(); } return 0; } public java.util.UUID getOther_side_var_id() { if (OtherVariable != null) { return OtherVariable.getVar_id(); } return IdAssigner.NULL_UUID; } public java.util.UUID getOther_side_var_idCachedValue() { if (!IdAssigner.NULL_UUID.equals(m_other_side_var_id)) return m_other_side_var_id; else return getOther_side_var_id(); } public void setOther_side_var_id(java.util.UUID newValue) { m_other_side_var_id = IdAssigner.preprocessUUID(newValue); } public String getRelationship_phrase() { return m_relationship_phrase; } public void setRelationship_phrase(String newValue) { m_relationship_phrase = newValue; } public int getAssociationnumberlinenumber() { return m_associationnumberlinenumber; } public void setAssociationnumberlinenumber(int newValue) { m_associationnumberlinenumber = newValue; } public int getAssociationnumbercolumn() { return m_associationnumbercolumn; } public void setAssociationnumbercolumn(int newValue) { m_associationnumbercolumn = newValue; } public int getAssociationphraselinenumber() { return m_associationphraselinenumber; } public void setAssociationphraselinenumber(int newValue) { m_associationphraselinenumber = newValue; } public int getAssociationphrasecolumn() { return m_associationphrasecolumn; } public void setAssociationphrasecolumn(int newValue) { m_associationphrasecolumn = newValue; } public long getRel_idLongBased() { if (DestroysAssociation != null) { return DestroysAssociation.getRel_idLongBased(); } return 0; } public java.util.UUID getRel_id() { if (DestroysAssociation != null) { return DestroysAssociation.getRel_id(); } return IdAssigner.NULL_UUID; } public java.util.UUID getRel_idCachedValue() { if (!IdAssigner.NULL_UUID.equals(m_rel_id)) return m_rel_id; else return getRel_id(); } public void setRel_id(java.util.UUID newValue) { m_rel_id = IdAssigner.preprocessUUID(newValue); } // end declare accessors public static void checkClassConsistency(ModelRoot modelRoot) { Ooaofooa.log.println(ILogger.OPERATION, "Unrelate", //$NON-NLS-1$ " Operation entered: Unrelate::checkClassConsistency"); //$NON-NLS-1$ if (Boolean.valueOf(System.getenv("PTC_MCC_ENABLED")) == false) { //$NON-NLS-1$ return; } Unrelate_c[] objs = Unrelate_c .UnrelateInstances(modelRoot, null, false); for (int i = 0; i < objs.length; i++) { objs[i].checkConsistency(); } } public boolean checkConsistency() { Ooaofooa.log.println(ILogger.OPERATION, "Unrelate", //$NON-NLS-1$ " Operation entered: Unrelate::checkConsistency"); //$NON-NLS-1$ if (Boolean.valueOf(System.getenv("PTC_MCC_ENABLED")) == false) { //$NON-NLS-1$ return true; } ModelRoot modelRoot = getModelRoot(); boolean retval = true; class Unrelate_c_test39183_c implements ClassQueryInterface_c { Unrelate_c_test39183_c(java.util.UUID p39184) { m_p39184 = p39184; } private java.util.UUID m_p39184; public boolean evaluate(Object candidate) { Unrelate_c selected = (Unrelate_c) candidate; boolean retval = false; retval = (selected.getStatement_id().equals(m_p39184)); return retval; } } Unrelate_c[] objs39182 = Unrelate_c.UnrelateInstances(modelRoot, new Unrelate_c_test39183_c(getStatement_id())); if (((objs39182.length) == 0)) { if (CorePlugin.getDefault().isDebugging()) { Ooaofooa.log .println(ILogger.CONSISTENCY, "Unrelate", //$NON-NLS-1$ "Consistency: Object: Unrelate: Cardinality of an identifier is zero. " //$NON-NLS-1$ + "Actual Value: " + Integer.toString(objs39182.length)); //$NON-NLS-1$ } else { Exception e = new Exception(); CorePlugin.logError( "Consistency: Object: Unrelate: Cardinality of an identifier is zero. " //$NON-NLS-1$ + "Actual Value: " //$NON-NLS-1$ + Integer.toString(objs39182.length), e); } retval = false; } if (((objs39182.length) > 1)) { if (CorePlugin.getDefault().isDebugging()) { Ooaofooa.log .println(ILogger.CONSISTENCY, "Unrelate", //$NON-NLS-1$ "Consistency: Object: Unrelate: Cardinality of an identifier is greater than 1. " //$NON-NLS-1$ + "Actual Value: " //$NON-NLS-1$ + Integer.toString(objs39182.length) + " Statement_ID: " + "Not Printable"); //$NON-NLS-1$ } else { Exception e = new Exception(); CorePlugin .logError( "Consistency: Object: Unrelate: Cardinality of an identifier is greater than 1. " //$NON-NLS-1$ + "Actual Value: " //$NON-NLS-1$ + Integer.toString(objs39182.length) + " Statement_ID: " + "Not Printable", e); //$NON-NLS-1$ } retval = false; } // Unrelate is a subtype in association: rel.Numb = 603 // The supertype class is: Statement class Statement_c_test39188_c implements ClassQueryInterface_c { Statement_c_test39188_c(java.util.UUID p39189) { m_p39189 = p39189; } private java.util.UUID m_p39189; public boolean evaluate(Object candidate) { Statement_c selected = (Statement_c) candidate; boolean retval = false; retval = (selected.getStatement_id().equals(m_p39189)); return retval; } } Statement_c[] objs39187 = Statement_c.StatementInstances(modelRoot, new Statement_c_test39188_c(getStatement_id())); if (((objs39187.length) != 1)) { if (CorePlugin.getDefault().isDebugging()) { Ooaofooa.log .println(ILogger.CONSISTENCY, "Unrelate", //$NON-NLS-1$ "Consistency: Object: Unrelate: Association: 603: Cardinality of a supertype is not equal to 1. " //$NON-NLS-1$ + "Actual Value: " + Integer.toString(objs39187.length)); //$NON-NLS-1$ } else { Exception e = new Exception(); CorePlugin .logError( "Consistency: Object: Unrelate: Association: 603: Cardinality of a supertype is not equal to 1. " //$NON-NLS-1$ + "Actual Value: " //$NON-NLS-1$ + Integer.toString(objs39187.length), e); } retval = false; } // Unrelate is a referring class in association: rel.Numb = 620 // The participating class is: Variable class Variable_c_test39191_c implements ClassQueryInterface_c { Variable_c_test39191_c(java.util.UUID p39192) { m_p39192 = p39192; } private java.util.UUID m_p39192; public boolean evaluate(Object candidate) { Variable_c selected = (Variable_c) candidate; boolean retval = false; retval = (selected.getVar_id().equals(m_p39192)); return retval; } } Variable_c[] objs39190 = Variable_c.VariableInstances(modelRoot, new Variable_c_test39191_c(getOne_side_var_id())); // The participant is unconditional // The multiplicity of the participant is one if (((objs39190.length) != 1)) { if (CorePlugin.getDefault().isDebugging()) { Ooaofooa.log .println(ILogger.CONSISTENCY, "Unrelate", //$NON-NLS-1$ "Consistency: Object: Unrelate: Association: 620: Cardinality of a participant is not equal to 1. " //$NON-NLS-1$ + "Actual Value: " //$NON-NLS-1$ + Integer.toString(objs39190.length) + " One_Side_Var_ID: " + "Not Printable"); //$NON-NLS-1$ } else { Exception e = new Exception(); CorePlugin .logError( "Consistency: Object: Unrelate: Association: 620: Cardinality of a participant is not equal to 1. " //$NON-NLS-1$ + "Actual Value: " //$NON-NLS-1$ + Integer.toString(objs39190.length) + " One_Side_Var_ID: " + "Not Printable", e); //$NON-NLS-1$ } retval = false; } // Unrelate is a referring class in association: rel.Numb = 621 // The participating class is: Variable class Variable_c_test39194_c implements ClassQueryInterface_c { Variable_c_test39194_c(java.util.UUID p39195) { m_p39195 = p39195; } private java.util.UUID m_p39195; public boolean evaluate(Object candidate) { Variable_c selected = (Variable_c) candidate; boolean retval = false; retval = (selected.getVar_id().equals(m_p39195)); return retval; } } Variable_c[] objs39193 = Variable_c.VariableInstances(modelRoot, new Variable_c_test39194_c(getOther_side_var_id())); // The participant is unconditional // The multiplicity of the participant is one if (((objs39193.length) != 1)) { if (CorePlugin.getDefault().isDebugging()) { Ooaofooa.log .println(ILogger.CONSISTENCY, "Unrelate", //$NON-NLS-1$ "Consistency: Object: Unrelate: Association: 621: Cardinality of a participant is not equal to 1. " //$NON-NLS-1$ + "Actual Value: " //$NON-NLS-1$ + Integer.toString(objs39193.length) + " Other_Side_Var_ID: " + "Not Printable"); //$NON-NLS-1$ } else { Exception e = new Exception(); CorePlugin .logError( "Consistency: Object: Unrelate: Association: 621: Cardinality of a participant is not equal to 1. " //$NON-NLS-1$ + "Actual Value: " //$NON-NLS-1$ + Integer.toString(objs39193.length) + " Other_Side_Var_ID: " + "Not Printable", e); //$NON-NLS-1$ } retval = false; } // Unrelate is a referring class in association: rel.Numb = 655 // The participating class is: Association class Association_c_test39197_c implements ClassQueryInterface_c { Association_c_test39197_c(java.util.UUID p39198) { m_p39198 = p39198; } private java.util.UUID m_p39198; public boolean evaluate(Object candidate) { Association_c selected = (Association_c) candidate; boolean retval = false; retval = (selected.getRel_id().equals(m_p39198)); return retval; } } Association_c[] objs39196 = Association_c.AssociationInstances( modelRoot, new Association_c_test39197_c(getRel_id())); // The participant is unconditional // The multiplicity of the participant is one if (((objs39196.length) != 1)) { if (CorePlugin.getDefault().isDebugging()) { Ooaofooa.log .println(ILogger.CONSISTENCY, "Unrelate", //$NON-NLS-1$ "Consistency: Object: Unrelate: Association: 655: Cardinality of a participant is not equal to 1. " //$NON-NLS-1$ + "Actual Value: " //$NON-NLS-1$ + Integer.toString(objs39196.length) + " Rel_ID: " + "Not Printable"); //$NON-NLS-1$ } else { Exception e = new Exception(); CorePlugin .logError( "Consistency: Object: Unrelate: Association: 655: Cardinality of a participant is not equal to 1. " //$NON-NLS-1$ + "Actual Value: " //$NON-NLS-1$ + Integer.toString(objs39196.length) + " Rel_ID: " + "Not Printable", e); //$NON-NLS-1$ } retval = false; } return retval; } // declare transform functions public void Dispose() { Ooaofooa.log.println(ILogger.OPERATION, "Unrelate", " Operation entered: Unrelate::Dispose"); final ModelRoot modelRoot = getModelRoot(); Variable_c v_one_var = Variable_c.getOneV_VAROnR620(this); if (((v_one_var != null))) { this.unrelateAcrossR620From(v_one_var); } Variable_c v_other_var = Variable_c.getOneV_VAROnR621(this); if (((v_other_var != null))) { this.unrelateAcrossR621From(v_other_var); } Association_c v_rel = Association_c.getOneR_RELOnR655(this); if (((v_rel != null))) { this.unrelateAcrossR655From(v_rel); } delete(); } // End dispose public void Execute(final java.util.UUID p_Stack_frame_id) { Ooaofooa.log.println(ILogger.OPERATION, "Unrelate", " Operation entered: Unrelate::Execute"); final ModelRoot modelRoot = getModelRoot(); } // End execute // end transform functions public Object getAdapter(Class adapter) { Object superAdapter = super.getAdapter(adapter); if (superAdapter != null) { return superAdapter; } return null; } } // end Unrelate
julianfellyco/web-lanjutan
M07-KoneksiDatabase/mobile/controllers/perpus.js
<reponame>julianfellyco/web-lanjutan<filename>M07-KoneksiDatabase/mobile/controllers/perpus.js const conn = require("./db"); const async = require("async"); exports.cariBuku = (req, res, next) => { var id = req.params.id; let query = "select * from tbl_buku where id = ?"; conn.query(query, [id], (err, rows) => { if (err) { return res.status(400).send({ message: "Failed when query data", }); } else { if (rows.length < 1) { return res.status(404).send({ message: "Not Found", }); } else { return res.status(200).send({ data: rows, }); } } }); }; exports.tambahBuku = (req, res, next) => { let nama = req.body.nama; //body.nama; nama sesuai dengan body yang dikirim dari client let deskripsi = req.body.deskripsi; let harga = req.body.harga; var data = { nama: nama, //"nama" : nama, nama dalam kutip disesuaikan dengan nama field (kolom) dari tabel deskripsi: deskripsi, harga: wa, }; let sql = "insert into tbl_buku set ?"; conn.query(sql, data, (err, rows) => { if (err) { return res.status(400).send({ status: 400, }); } else { return res.status(200).send({ status: 200, }); } }); }; exports.updateBuku = (req, res) => { var id = req.body.id; let nama = req.body.nama; let deskripsi = req.body.deskripsi; let harga = req.body.harga; var sql = "UPDATE tbl_buku SET nama=?, deskripsi= ?, harga= ? WHERE id= ?"; // params dalam kurung siku "[]", diurutkan sesuai dengan tanda tanya pada query di atas. conn.query(sql, [nama, deskripsi, harga, id], (err, result) => { if (err) { return res.status(400).send({ status: 400, }); } else { return res.status(200).send({ status: 200, }); } }); };
cyenyxe/eva-pipeline-1
src/main/java/uk/ac/ebi/eva/pipeline/runner/ManageJobsUtils.java
<reponame>cyenyxe/eva-pipeline-1<gh_stars>1-10 /* * Copyright 2015-2017 EMBL - European Bioinformatics Institute * * 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 uk.ac.ebi.eva.pipeline.runner; import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.repository.JobRepository; import uk.ac.ebi.eva.pipeline.runner.exceptions.NoPreviousJobExecutionException; import java.util.Date; /** * Utility class to change job / step status */ public class ManageJobsUtils { public static void markLastJobAsFailed(JobRepository jobRepository, String jobName, JobParameters jobParameters) throws NoPreviousJobExecutionException { JobExecution lastJobExecution = jobRepository.getLastJobExecution(jobName, jobParameters); if (lastJobExecution == null) { throw new NoPreviousJobExecutionException(jobName, jobParameters); } Date currentTime = new Date(); lastJobExecution.setEndTime(currentTime); lastJobExecution.setStatus(BatchStatus.FAILED); lastJobExecution.setExitStatus( lastJobExecution.getExitStatus().replaceExitCode("FAILED").addExitDescription("Manually " + "failed job") ); jobRepository.update(lastJobExecution); for (StepExecution stepExecution : lastJobExecution.getStepExecutions()) { stepExecution.setEndTime(currentTime); stepExecution.setStatus(BatchStatus.FAILED); stepExecution.setExitStatus(lastJobExecution.getExitStatus().replaceExitCode("FAILED")); jobRepository.update(stepExecution); } } }
myzhang1029/WabbitStudio-Old
Shared/wabbitemu core/debugger/dbcommon.h
#ifndef DBCOMMON_H #define DBCOMMON_H #include "calc.h" #include "dbreg.h" const TCHAR * byte_to_binary(int x, BOOL isWord); int xtoi(const TCHAR *xs); #define Debug_UpdateWindow(hwnd) SendMessage(hwnd, WM_USER, DB_UPDATE, 0); #define Debug_CreateWindow(hwnd) SendMessage(hwnd, WM_USER, DB_CREATE, 0); typedef enum { HEX2, HEX4, FLOAT2, FLOAT4, DEC3, DEC5, BIN8, BIN16, CHAR1, } VALUE_FORMAT; typedef enum { HEX, DEC, BIN, } DISPLAY_BASE; typedef enum { REGULAR, //view paged memory FLASH, //view all flash pages RAM, //view all ram pages } ViewType; typedef struct { int total; BOOL state[32]; } ep_state; #ifndef MACVER static const TCHAR* DisplayTypeString = _T("Disp_Type"); #endif #define EN_CANCEL 0x9999 #endif /* DBCOMMON_H */
d-hirano1001/backlog
project.go
package backlog import ( "context" "fmt" "io" ) // Project : project type Project struct { ID *int `json:"id,omitempty"` ProjectKey *string `json:"projectKey,omitempty"` Name *string `json:"name,omitempty"` ChartEnabled *bool `json:"chartEnabled,omitempty"` SubtaskingEnabled *bool `json:"subtaskingEnabled,omitempty"` ProjectLeaderCanEditProjectLeader *bool `json:"projectLeaderCanEditProjectLeader,omitempty"` TextFormattingRule *string `json:"textFormattingRule,omitempty"` Archived *bool `json:"archived,omitempty"` DisplayOrder *int `json:"displayOrder,omitempty"` } // Status : the status of project type Status struct { ID *int `json:"id,omitempty"` ProjectID *int `json:"projectId,omitempty"` Name *string `json:"name,omitempty"` Color *string `json:"color,omitempty"` DisplayOrder *int `json:"displayOrder,omitempty"` } // ProjectDiskUsage : disk usage of project type ProjectDiskUsage struct { ProjectID *int `json:"projectId,omitempty"` Issue *int `json:"issue,omitempty"` Wiki *int `json:"wiki,omitempty"` File *int `json:"file,omitempty"` Subversion *int `json:"subversion,omitempty"` Git *int `json:"git,omitempty"` GitLFS *int `json:"gitLFS,omitempty"` } // RecentlyViewedProject : recently viewed project type RecentlyViewedProject struct { Project *Project `json:"project"` Updated *Timestamp `json:"updated"` } // GetMyRecentlyViewedProjects returns the list of projects I recently viewed func (c *Client) GetMyRecentlyViewedProjects(opts *GetMyRecentlyViewedProjectsOptions) ([]*RecentlyViewedProject, error) { return c.GetMyRecentlyViewedProjectsContext(context.Background(), opts) } // GetMyRecentlyViewedProjectsContext returns the list of projects I recently viewed with context func (c *Client) GetMyRecentlyViewedProjectsContext(ctx context.Context, opts *GetMyRecentlyViewedProjectsOptions) ([]*RecentlyViewedProject, error) { u, err := c.AddOptions("/api/v2/users/myself/recentlyViewedProjects", opts) if err != nil { return nil, err } req, err := c.NewRequest("GET", u, nil) if err != nil { return nil, err } var recentlyViewedProjects []*RecentlyViewedProject if err := c.Do(ctx, req, &recentlyViewedProjects); err != nil { return nil, err } return recentlyViewedProjects, nil } // GetProjects returns the list of projects func (c *Client) GetProjects(opts *GetProjectsOptions) ([]*Project, error) { return c.GetProjectsContext(context.Background(), opts) } // GetProjectsContext returns the list of projects func (c *Client) GetProjectsContext(ctx context.Context, opts *GetProjectsOptions) ([]*Project, error) { u, err := c.AddOptions("/api/v2/projects", opts) if err != nil { return nil, err } req, err := c.NewRequest("GET", u, nil) if err != nil { return nil, err } projects := []*Project{} if err := c.Do(ctx, req, &projects); err != nil { return nil, err } return projects, nil } // GetProject returns a project func (c *Client) GetProject(projectIDOrKey interface{}) (*Project, error) { return c.GetProjectContext(context.Background(), projectIDOrKey) } // GetProjectContext returns a project with context func (c *Client) GetProjectContext(ctx context.Context, projectIDOrKey interface{}) (*Project, error) { u := fmt.Sprintf("/api/v2/projects/%v", projectIDOrKey) req, err := c.NewRequest("GET", u, nil) if err != nil { return nil, err } project := new(Project) if err := c.Do(ctx, req, &project); err != nil { return nil, err } return project, nil } // GetStatuses returns the statuses of a project func (c *Client) GetStatuses(projectIDOrKey interface{}) ([]*Status, error) { return c.GetStatusesContext(context.Background(), projectIDOrKey) } // GetStatusesContext returns the statuses of a project with context func (c *Client) GetStatusesContext(ctx context.Context, projectIDOrKey interface{}) ([]*Status, error) { u := fmt.Sprintf("/api/v2/projects/%v/statuses", projectIDOrKey) req, err := c.NewRequest("GET", u, nil) if err != nil { return nil, err } statuses := []*Status{} if err := c.Do(ctx, req, &statuses); err != nil { return nil, err } return statuses, nil } // CreateProject creates a project func (c *Client) CreateProject(input *CreateProjectInput) (*Project, error) { return c.CreateProjectContext(context.Background(), input) } // CreateProjectContext creates a project with Context func (c *Client) CreateProjectContext(ctx context.Context, input *CreateProjectInput) (*Project, error) { u := "/api/v2/projects" req, err := c.NewRequest("POST", u, input) if err != nil { return nil, err } project := new(Project) if err := c.Do(ctx, req, &project); err != nil { return nil, err } return project, nil } // UpdateProject updates a project func (c *Client) UpdateProject(id int, input *UpdateProjectInput) (*Project, error) { return c.UpdateProjectContext(context.Background(), id, input) } // UpdateProjectContext updates a project with Context func (c *Client) UpdateProjectContext(ctx context.Context, id int, input *UpdateProjectInput) (*Project, error) { u := fmt.Sprintf("/api/v2/projects/%v", id) req, err := c.NewRequest("PATCH", u, input) if err != nil { return nil, err } project := new(Project) if err := c.Do(ctx, req, &project); err != nil { return nil, err } return project, nil } // DeleteProject deletes a project func (c *Client) DeleteProject(projectIDOrKey interface{}) (*Project, error) { return c.DeleteProjectContext(context.Background(), projectIDOrKey) } // DeleteProjectContext deletes a project with Context func (c *Client) DeleteProjectContext(ctx context.Context, projectIDOrKey interface{}) (*Project, error) { u := fmt.Sprintf("/api/v2/projects/%v", projectIDOrKey) req, err := c.NewRequest("DELETE", u, nil) if err != nil { return nil, err } project := new(Project) if err := c.Do(ctx, req, &project); err != nil { return nil, err } return project, nil } // GetProjectIcon downloads project icon func (c *Client) GetProjectIcon(projectIDOrKey interface{}, writer io.Writer) error { return c.GetProjectIconContext(context.Background(), projectIDOrKey, writer) } // GetProjectIconContext downloads project icon with context func (c *Client) GetProjectIconContext(ctx context.Context, projectIDOrKey interface{}, writer io.Writer) error { u := fmt.Sprintf("/api/v2/projects/%v/image", projectIDOrKey) req, err := c.NewRequest("GET", u, nil) if err != nil { return err } if err := c.Do(ctx, req, writer); err != nil { return err } return nil } // AddProjectUser adds a user to a project func (c *Client) AddProjectUser(projectIDOrKey interface{}, input *AddProjectUserInput) (*User, error) { return c.AddProjectUserContext(context.Background(), projectIDOrKey, input) } // AddProjectUserContext adds a user to a project with context func (c *Client) AddProjectUserContext(ctx context.Context, projectIDOrKey interface{}, input *AddProjectUserInput) (*User, error) { u := fmt.Sprintf("/api/v2/projects/%v/users", projectIDOrKey) req, err := c.NewRequest("POST", u, input) if err != nil { return nil, err } var user *User if err := c.Do(ctx, req, &user); err != nil { return nil, err } return user, nil } // GetProjectUsers returns the list of users in a project func (c *Client) GetProjectUsers(projectIDOrKey interface{}, opts *GetProjectUsersOptions) ([]*User, error) { return c.GetProjectUsersContext(context.Background(), projectIDOrKey, opts) } // GetProjectUsersContext returns the list of users in a project with context func (c *Client) GetProjectUsersContext(ctx context.Context, projectIDOrKey interface{}, opts *GetProjectUsersOptions) ([]*User, error) { u := fmt.Sprintf("/api/v2/projects/%v/users", projectIDOrKey) u, err := c.AddOptions(u, opts) if err != nil { return nil, err } req, err := c.NewRequest("GET", u, nil) if err != nil { return nil, err } var users []*User if err := c.Do(ctx, req, &users); err != nil { return nil, err } return users, nil } // DeleteProjectUser deletes a user in a project func (c *Client) DeleteProjectUser(projectIDOrKey interface{}, input *DeleteProjectUserInput) (*User, error) { return c.DeleteProjectUserContext(context.Background(), projectIDOrKey, input) } // DeleteProjectUserContext deletes a user in a project with Context func (c *Client) DeleteProjectUserContext(ctx context.Context, projectIDOrKey interface{}, input *DeleteProjectUserInput) (*User, error) { u := fmt.Sprintf("/api/v2/projects/%v/users", projectIDOrKey) req, err := c.NewRequest("DELETE", u, input) if err != nil { return nil, err } user := new(User) if err := c.Do(ctx, req, &user); err != nil { return nil, err } return user, nil } // AddProjectAdministrator adds an administrator in a project func (c *Client) AddProjectAdministrator(projectIDOrKey interface{}, input *AddProjectAdministratorInput) (*User, error) { return c.AddProjectAdministratorContext(context.Background(), projectIDOrKey, input) } // AddProjectAdministratorContext adds an administrator in a project with context func (c *Client) AddProjectAdministratorContext(ctx context.Context, projectIDOrKey interface{}, input *AddProjectAdministratorInput) (*User, error) { u := fmt.Sprintf("/api/v2/projects/%v/administrators", projectIDOrKey) req, err := c.NewRequest("POST", u, input) if err != nil { return nil, err } user := new(User) if err := c.Do(ctx, req, &user); err != nil { return nil, err } return user, nil } // GetProjectAdministrators returns the list of administrators in a project func (c *Client) GetProjectAdministrators(projectIDOrKey interface{}) ([]*User, error) { return c.GetProjectAdministratorsContext(context.Background(), projectIDOrKey) } // GetProjectAdministratorsContext returns the list of administrators in a project with context func (c *Client) GetProjectAdministratorsContext(ctx context.Context, projectIDOrKey interface{}) ([]*User, error) { u := fmt.Sprintf("/api/v2/projects/%v/administrators", projectIDOrKey) req, err := c.NewRequest("GET", u, nil) if err != nil { return nil, err } var users []*User if err := c.Do(ctx, req, &users); err != nil { return nil, err } return users, nil } // DeleteProjectAdministrator deletes a administrator in a project func (c *Client) DeleteProjectAdministrator(projectIDOrKey interface{}, input *DeleteProjectAdministratorInput) (*User, error) { return c.DeleteProjectAdministratorContext(context.Background(), projectIDOrKey, input) } // DeleteProjectAdministratorContext deletes a administrator in a project with Context func (c *Client) DeleteProjectAdministratorContext(ctx context.Context, projectIDOrKey interface{}, input *DeleteProjectAdministratorInput) (*User, error) { u := fmt.Sprintf("/api/v2/projects/%v/administrators", projectIDOrKey) req, err := c.NewRequest("DELETE", u, input) if err != nil { return nil, err } user := new(User) if err := c.Do(ctx, req, &user); err != nil { return nil, err } return user, nil } // CreateStatus creates a status func (c *Client) CreateStatus(projectIDOrKey interface{}, input *CreateStatusInput) (*Status, error) { return c.CreateStatusContext(context.Background(), projectIDOrKey, input) } // CreateStatusContext creates a status func (c *Client) CreateStatusContext(ctx context.Context, projectIDOrKey interface{}, input *CreateStatusInput) (*Status, error) { u := fmt.Sprintf("/api/v2/projects/%v/statuses", projectIDOrKey) req, err := c.NewRequest("POST", u, input) if err != nil { return nil, err } status := new(Status) if err := c.Do(ctx, req, &status); err != nil { return nil, err } return status, nil } // UpdateStatus updates a status func (c *Client) UpdateStatus(projectIDOrKey interface{}, statusID int, input *UpdateStatusInput) (*Status, error) { return c.UpdateStatusContext(context.Background(), projectIDOrKey, statusID, input) } // UpdateStatusContext updates a status func (c *Client) UpdateStatusContext(ctx context.Context, projectIDOrKey interface{}, statusID int, input *UpdateStatusInput) (*Status, error) { u := fmt.Sprintf("/api/v2/projects/%v/statuses/%v", projectIDOrKey, statusID) req, err := c.NewRequest("PATCH", u, input) if err != nil { return nil, err } status := new(Status) if err := c.Do(ctx, req, &status); err != nil { return nil, err } return status, nil } // DeleteStatus deletes a status func (c *Client) DeleteStatus(projectIDOrKey interface{}, statusID int, input *DeleteStatusInput) (*Status, error) { return c.DeleteStatusContext(context.Background(), projectIDOrKey, statusID, input) } // DeleteStatusContext deletes a status func (c *Client) DeleteStatusContext(ctx context.Context, projectIDOrKey interface{}, statusID int, input *DeleteStatusInput) (*Status, error) { u := fmt.Sprintf("/api/v2/projects/%v/statuses/%v", projectIDOrKey, statusID) req, err := c.NewRequest("DELETE", u, input) if err != nil { return nil, err } status := new(Status) if err := c.Do(ctx, req, &status); err != nil { return nil, err } return status, nil } // SortStatuses sorts the list of statuses func (c *Client) SortStatuses(projectIDOrKey interface{}, input *SortStatusesInput) ([]*Status, error) { return c.SortStatusesContext(context.Background(), projectIDOrKey, input) } // SortStatusesContext sorts the list of statuses with context func (c *Client) SortStatusesContext(ctx context.Context, projectIDOrKey interface{}, input *SortStatusesInput) ([]*Status, error) { u := fmt.Sprintf("/api/v2/projects/%v/statuses/updateDisplayOrder", projectIDOrKey) req, err := c.NewRequest("PATCH", u, input) if err != nil { return nil, err } statuses := []*Status{} if err := c.Do(ctx, req, &statuses); err != nil { return nil, err } return statuses, nil } // GetProjectDiskUsage returns disk usage of a project func (c *Client) GetProjectDiskUsage(projectIDOrKey interface{}) (*ProjectDiskUsage, error) { return c.GetProjectDiskUsageContext(context.Background(), projectIDOrKey) } // GetProjectDiskUsageContext returns the list of administrators in a project with context func (c *Client) GetProjectDiskUsageContext(ctx context.Context, projectIDOrKey interface{}) (*ProjectDiskUsage, error) { u := fmt.Sprintf("/api/v2/projects/%v/diskUsage", projectIDOrKey) req, err := c.NewRequest("GET", u, nil) if err != nil { return nil, err } projectDiskUsage := new(ProjectDiskUsage) if err := c.Do(ctx, req, &projectDiskUsage); err != nil { return nil, err } return projectDiskUsage, nil } // GetMyRecentlyViewedProjectsOptions specifies parameters to the GetMyRecentlyViewedProject method. type GetMyRecentlyViewedProjectsOptions struct { Order Order `url:"order,omitempty"` Offset *int `url:"offset,omitempty"` Count *int `url:"count,omitempty"` } // GetProjectsOptions contains all the parameters necessary (including the optional ones) for a GetProjects() request. type GetProjectsOptions struct { Archived *bool `url:"archived"` All *bool `url:"all"` } // CreateProjectInput contains all the parameters necessary (including the optional ones) for a CreateProject() request. type CreateProjectInput struct { Name *string `json:"name"` Key *string `json:"key"` ChartEnabled *bool `json:"chartEnabled"` ProjectLeaderCanEditProjectLeader *bool `json:"projectLeaderCanEditProjectLeader,omitempty"` SubtaskingEnabled *bool `json:"subtaskingEnabled"` TextFormattingRule *string `json:"textFormattingRule"` } // UpdateProjectInput contains all the parameters necessary (including the optional ones) for a UpdateProject() request. type UpdateProjectInput struct { Name *string `json:"name,omitempty"` Key *string `json:"key,omitempty"` ChartEnabled *bool `json:"chartEnabled,omitempty"` SubtaskingEnabled *bool `json:"subtaskingEnabled,omitempty"` ProjectLeaderCanEditProjectLeader *bool `json:"projectLeaderCanEditProjectLeader,omitempty"` TextFormattingRule *string `json:"textFormattingRule,omitempty"` Archived *bool `json:"archived,omitempty"` } // AddProjectUserInput specifies parameters to the AddProjectUser method. type AddProjectUserInput struct { UserID *int `json:"userId"` } // GetProjectUsersOptions specifies parameters to the GetProjectUsers method. type GetProjectUsersOptions struct { ExcludeGroupMembers *bool `url:"excludeGroupMembers,omitempty"` } // DeleteProjectUserInput specifies parameters to the DeleteProjectUser method. type DeleteProjectUserInput struct { UserID *int `json:"userId"` } // AddProjectAdministratorInput specifies parameters to the AddProjectAdministrator method. type AddProjectAdministratorInput struct { UserID *int `json:"userId"` } // DeleteProjectAdministratorInput specifies parameters to the DeleteProjectAdministrator method. type DeleteProjectAdministratorInput struct { UserID *int `json:"userId"` } // CreateStatusInput specifies parameters to the CreateStatus method. type CreateStatusInput struct { Name *string `json:"name"` Color *string `json:"color"` } // UpdateStatusInput specifies parameters to the UpdateStatus method. type UpdateStatusInput struct { Name *string `json:"name,omitempty"` Color *string `json:"color,omitempty"` } // DeleteStatusInput specifies parameters to the DeleteStatus method. type DeleteStatusInput struct { SubstituteStatusID *int `json:"substituteStatusId"` } // SortStatusesInput specifies parameters to the SortStatuses method. type SortStatusesInput struct { StatusIDs []int `json:"statusId,omitempty"` }
YJBeetle/QtAndroidAPI
android-31/android/media/AudioRecord_MetricsConstants.hpp
#pragma once #include "../../JObject.hpp" class JString; namespace android::media { class AudioRecord_MetricsConstants : public JObject { public: // Fields static JString CHANNELS(); static JString ENCODING(); static JString LATENCY(); static JString SAMPLERATE(); static JString SOURCE(); // QJniObject forward template<typename ...Ts> explicit AudioRecord_MetricsConstants(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} AudioRecord_MetricsConstants(QJniObject obj); // Constructors // Methods }; } // namespace android::media
martmists-gh/BDSP
include/il2cpp/Dpr/UnderGround/UgFieldManager/__c__DisplayClass182_0.h
<filename>include/il2cpp/Dpr/UnderGround/UgFieldManager/__c__DisplayClass182_0.h #pragma once #include "il2cpp.h" void Dpr_UnderGround_UgFieldManager___c__DisplayClass182_0___ctor (Dpr_UnderGround_UgFieldManager___c__DisplayClass182_0_o* __this, const MethodInfo* method_info); bool Dpr_UnderGround_UgFieldManager___c__DisplayClass182_0___CreateNPC_b__0 (Dpr_UnderGround_UgFieldManager___c__DisplayClass182_0_o* __this, XLSXContent_UgNpcList_SheetSheet1_o* x, const MethodInfo* method_info); void Dpr_UnderGround_UgFieldManager___c__DisplayClass182_0___CreateNPC_b__1 (Dpr_UnderGround_UgFieldManager___c__DisplayClass182_0_o* __this, FieldObjectEntity_o* entity, const MethodInfo* method_info);
QinZhen001/template
src/plugins/appReportPlugin.js
<reponame>QinZhen001/template function timeount() { return new Promise((resolve, reject) => { setTimeout(() => { resolve(true) }, 10000) }) } const nativeHook = { onLaunch: async function (option) { console.log("plugin onLaunch", option) await timeount() }, }; export default function appReportPlugin() { return { name: 'launch', nativeHook: nativeHook, custom: { xxx: function () { console.log("xxx", this) }, asd: () => { console.log("asd", this) }, }, }; };
hbatagelo/a_tour_of_cpp
chapter_4/vector.cpp
#include "vector.hpp" #include <algorithm> #include <iostream> Vector::Vector(std::size_t s) { if (s < 0) { throw std::length_error{"Vector constructor: negative size"}; } elem = std::make_unique<double[]>(s); // RAII sz = s; } Vector::Vector(std::initializer_list<double> lst) : elem{std::make_unique<double[]>(lst.size())}, sz{lst.size()} { std::copy(lst.begin(), lst.end(), elem.get()); } Vector::Vector(const Vector &other) : elem{std::make_unique<double[]>(other.size())}, sz{other.sz} { std::copy(other.elem.get(), other.elem.get() + other.size(), elem.get()); } Vector::Vector(Vector &&other) noexcept : elem{std::move(other.elem)}, sz{other.sz} { other.sz = 0; } Vector &Vector::operator=(const Vector &other) { if (&other == this) { return *this; } elem = std::make_unique<double[]>(other.size()); std::copy(other.elem.get(), other.elem.get() + other.size(), elem.get()); sz = other.size(); return *this; } Vector &Vector::operator=(Vector &&other) noexcept { elem = std::move(other.elem); sz = other.size(); return *this; } double &Vector::operator[](std::size_t i) { if (i >= size()) { throw std::out_of_range{"Vector::operator[]: out of range"}; } return elem.get()[i]; } const double &Vector::operator[](std::size_t i) const { if (i >= size()) { throw std::out_of_range{"Vector::operator[]: out of range"}; } return elem.get()[i]; } std::size_t Vector::size() const { return sz; } void Vector::push_back([[maybe_unused]] double x) { // To be implemented }
ideacrew/aca_entities
lib/aca_entities/medicaid/curam/entities/evidences/evidence_command_handler.rb
# frozen_string_literal: true module AcaEntities module Medicaid module Curam module Evidences # CommandHandler Evidence class EvidenceCommandHandler < Sequent::CommandHandler on Commands::CreateIncomeEvidence do |command| repository.add_aggregate IncomeEvidenceAggregate.new(command) end on Commands::UpdateIncomeEvidence do |command| do_with_aggregate(command, IncomeEvidenceAggregate) do |aggregate| aggregate.update(command) end end on Commands::CreateEvidence do |command| repository.add_aggregate EvidenceAggregate.new(command) end on Commands::UpdateEvidence do |command| do_with_aggregate(command, EvidenceAggregate) do |aggregate| aggregate.update(command) end end end end end end end
Erin59/sinsy0.91
doc/html/search/namespaces_73.js
<filename>doc/html/search/namespaces_73.js<gh_stars>1-10 var searchData= [ ['sinsy',['sinsy',['../namespacesinsy.html',1,'']]] ];
SonarSonic/Calculator
src/main/java/sonar/calculator/mod/common/item/calculators/modules/ModuleBase.java
package sonar.calculator.mod.common.item.calculators.modules; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.World; import sonar.calculator.mod.api.modules.IModule; import sonar.calculator.mod.common.item.calculators.ModuleItemRegistry; import sonar.core.api.energy.EnergyType; import sonar.core.api.utils.ActionType; import sonar.core.handlers.energy.EnergyTransferHandler; import sonar.core.helpers.FontHelper; public abstract class ModuleBase implements IModule { @Override public boolean isLoadable() { return true; } @Override public String getClientName(NBTTagCompound tag) { return getItemStack(tag).getDisplayName(); } @Override public ItemStack getItemStack(NBTTagCompound tag){ Item item = ModuleItemRegistry.instance().getValue(getName()); if (item != null) { ItemStack moduleStack = new ItemStack(item, 1); moduleStack.setTagCompound(tag); return moduleStack; } return ItemStack.EMPTY; } protected final boolean isCreativeMode(Entity entity) { return entity instanceof EntityPlayer && ((EntityPlayer) entity).capabilities.isCreativeMode; } protected final boolean isEnergyAvailable(ItemStack container, Entity entity, World world, int required) { boolean toReturn = isCreativeMode(entity) || required <= getEnergyStored(container, entity); if (!toReturn && entity instanceof EntityPlayer) { FontHelper.sendMessage(FontHelper.translate("energy.notEnough"), world, (EntityPlayer) entity); } return toReturn; } protected final long receiveEnergy(ItemStack container, Entity entity, long maxReceive, boolean simulate) { return (int) EnergyTransferHandler.INSTANCE_SC.chargeItem(container, maxReceive, EnergyType.FE, ActionType.getTypeForAction(simulate)); } protected final long extractEnergy(ItemStack container, Entity entity, long maxExtract, boolean simulate) { if (!isCreativeMode(entity)) { return EnergyTransferHandler.INSTANCE_SC.dischargeItem(container, maxExtract, EnergyType.FE, ActionType.getTypeForAction(simulate)); } return 0; } protected final long getEnergyStored(ItemStack container, Entity entity) { return EnergyTransferHandler.INSTANCE_SC.getEnergyStored(container, EnergyType.FE); } protected final long getMaxEnergyStored(ItemStack container, Entity entity) { return EnergyTransferHandler.INSTANCE_SC.getEnergyCapacity(container, EnergyType.FE); } }
eltrufas/Chino
permissions/permissionManager.js
module.exports = { SET_GLOBAL_PERM: { name: 'SET_GLOBAL_PERM', default_value: false, server_overridable: false }, SET_SERVER_PERM: { name: 'SET_SERVER_PERM', default_value: false, server_owner_default_value: true, server_overridable: true } };
zealoussnow/chromium
third_party/blink/web_tests/http/tests/devtools/console/console-preserve-log.js
// Copyright 2017 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. (async function() { TestRunner.addResult(`Tests that the console can preserve log messages across navigations. Bug 53359\n`); await TestRunner.loadLegacyModule('console'); await TestRunner.loadTestModule('console_test_runner'); await TestRunner.showPanel('console'); SDK.consoleModel.addMessage(new SDK.ConsoleMessage( TestRunner.runtimeModel, Protocol.Log.LogEntrySource.Other, Protocol.Log.LogEntryLevel.Info, 'PASS')); Common.settingForTest('preserveConsoleLog').set(true); TestRunner.reloadPage(async function() { await ConsoleTestRunner.dumpConsoleMessages(); Common.settingForTest('preserveConsoleLog').set(false); TestRunner.completeTest(); }); })();
goistjt/CSSE490-Hadoop
ReduceJoin/src/main/java/edu/rosehulman/mohan/JoinRecordMapper.java
package edu.rosehulman.mohan; //cc JoinRecordMapper Mapper for tagging weather records for a reduce-side join import java.io.IOException; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; //vv JoinRecordMapper public class JoinRecordMapper extends Mapper<LongWritable, Text, TextPair, Text> { @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { context.write(new TextPair(getStationID(value.toString()), "1"), value); } private String getStationID(String record){ return record.substring(4, 10) + "-" + record.substring(10, 15); } }
eugeneilyin/mdi-norm
es/RoundAccountCircle.js
<gh_stars>1-10 import { FilledAccountCircle as RoundAccountCircle } from './FilledAccountCircle'; export { RoundAccountCircle };
ferreusveritas/MalisisDoorsLean
src/main/java/net/malisis/doors/block/DoorFactory.java
/* * The MIT License (MIT) * * Copyright (c) 2014 Ordinastie * * 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 net.malisis.doors.block; import net.malisis.doors.MalisisDoors; import net.malisis.doors.block.component.DirectionalComponent; import net.malisis.doors.inventory.MalisisInventory; import net.malisis.doors.renderer.icon.provider.IIconProvider; import net.malisis.doors.tileentity.DoorFactoryTileEntity; import net.malisis.doors.util.TileEntityUtils; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; /** * @author Ordinastie * */ public class DoorFactory extends MalisisBlock implements ITileEntityProvider { public DoorFactory() { super(Material.IRON); setCreativeTab(MalisisDoors.tab); setName("door_factory"); setHardness(3.0F); addComponent(new DirectionalComponent()); if (MalisisDoors.isClient()) addComponent(IIconProvider .create(MalisisDoors.modid + ":blocks/", "door_factory_side") .withSide(EnumFacing.SOUTH, "door_factory") .build()); } @Override public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { if (world.isRemote) return true; if (player.isSneaking()) return false; DoorFactoryTileEntity te = TileEntityUtils.getTileEntity(DoorFactoryTileEntity.class, world, pos); MalisisInventory.open((EntityPlayerMP) player, te); return true; } @Override public void breakBlock(World world, BlockPos pos, IBlockState state) { DoorFactoryTileEntity provider = TileEntityUtils.getTileEntity(DoorFactoryTileEntity.class, world, pos); if (provider != null) provider.breakInventories(world, pos); super.breakBlock(world, pos, state); } @Override public TileEntity createNewTileEntity(World var1, int var2) { return new DoorFactoryTileEntity(); } }
ets-mlb/emissary
src/main/java/emissary/core/Stage.java
package emissary.core; import java.util.ArrayList; import java.util.List; /** * Information class about processing stages in the workflow */ public class Stage { // List of stages to use. Use non-default constructors or extend class to change protected static List<String> stages; // Each stage must be marked parallel or not protected static List<Boolean> parallel; public Stage() {} static { stages = new ArrayList<String>(); parallel = new ArrayList<Boolean>(); stages.add("STUDY"); // prepare, coordinate idents parallel.add(Boolean.FALSE); stages.add("ID"); // identification phase parallel.add(Boolean.FALSE); stages.add("COORDINATE"); // Coordinate processing parallel.add(Boolean.FALSE); stages.add("PRETRANSFORM"); // before transform hook parallel.add(Boolean.TRUE); stages.add("TRANSFORM"); // transformation phase parallel.add(Boolean.FALSE); stages.add("POSTTRANSFORM"); // after transform hook parallel.add(Boolean.TRUE); stages.add("ANALYZE"); // analysis/metadata generation parallel.add(Boolean.TRUE); stages.add("VERIFY"); // verify for output parallel.add(Boolean.FALSE); stages.add("IO"); // output parallel.add(Boolean.FALSE); stages.add("REVIEW"); // finish off parallel.add(Boolean.FALSE); } /** * Indicate if a stage supports parallel processing or not * * @param i the index of the stage */ public boolean isParallelStage(final int i) { if (i >= 0 && i < parallel.size()) { return parallel.get(i).booleanValue(); } return false; } /** * Indicate if named stages supports parallel processing or not * * @param stage the name of the stage */ public boolean isParallelStage(final String stage) { for (int i = 0; i < stages.size(); i++) { if (stages.get(i).equals(stage)) { return parallel.get(i).booleanValue(); } } return false; } /** * Return stage name at index */ public String getStageName(final int i) { if (i >= 0 && i < stages.size()) { return stages.get(i); } else { return "UNDEFINED"; } } /** * Return stage index for name * * @param stage the name of the stage * @return the index of the stage or -1 if no such stage */ public int getStageIndex(final String stage) { for (int i = 0; i < stages.size(); i++) { if (stages.get(i).equals(stage)) { return i; } } return -1; } /** * Return a list of stages */ public List<String> getStages() { return new ArrayList<String>(stages); } /** * Return the stage following the named stage or null if the end of the list * * @param stage the one to find following for */ public String nextStageAfter(final String stage) { for (int i = 0; i < stages.size(); i++) { if (stages.get(i).equals(stage)) { if (i < stages.size() - 1) { return stages.get(i + 1); } } } return null; } /** * Get size of stage list */ public int size() { return stages.size(); } }
Duucking/latke
latke-core/src/main/java/org/b3log/latke/repository/RepositoryException.java
<filename>latke-core/src/main/java/org/b3log/latke/repository/RepositoryException.java /* * Latke - 一款以 JSON 为主的 Java Web 框架 * Copyright (c) 2009-present, b3log.org * * Latke is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ package org.b3log.latke.repository; /** * Repository exception. * * @author <a href="http://88250.b3log.org"><NAME></a> * @version 1.0.0.1, Feb 28, 2012 */ public class RepositoryException extends Exception { /** * Default serial version uid. */ private static final long serialVersionUID = 1L; /** * Public default constructor. */ public RepositoryException() { super("Repository exception!"); } /** * Public constructor with {@link Throwable}. * * @param throwable the specified throwable object */ public RepositoryException(final Throwable throwable) { super(throwable); } /** * Public constructor with message. * * @param msg the specified message */ public RepositoryException(final String msg) { super(msg); } }
dennis-park/slogo
src/backend/command/BracketClose.java
<filename>src/backend/command/BracketClose.java<gh_stars>0 package backend.command; /** * Allows backend to recognize a closing square bracket as the end of a command */ public class BracketClose extends Command { public BracketClose(){ myParameterCount =0; } public boolean equals(Object obj){ return true; } }
maxxcs/swc
crates/swc/tests/tsc-references/parser/ecmascript5/Statements/parserDoStatement2/input.ts/es5.1.normal/output.js
do { }while (false) false;
middware/bekit
service/src/main/java/org/bekit/service/service/ServiceParser.java
/* * 作者:钟勋 (e-mail:<EMAIL>) */ /* * 修订记录: * @author 钟勋 2016-12-16 01:14 创建 */ package org.bekit.service.service; import org.apache.commons.lang3.StringUtils; import org.bekit.common.transaction.TxExecutor; import org.bekit.service.annotation.service.Service; import org.bekit.service.annotation.service.ServiceExecute; import org.bekit.service.engine.ServiceContext; import org.bekit.service.service.ServiceExecutor.ServicePhaseExecutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.support.AopUtils; import org.springframework.core.ResolvableType; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.util.ClassUtils; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** * 服务解析器 */ public class ServiceParser { // 日志记录器 private static final Logger logger = LoggerFactory.getLogger(ServiceParser.class); /** * 解析服务 * * @param service 服务 * @param transactionManager 事务管理器 * @return 服务执行器 */ public static ServiceExecutor parseService(Object service, PlatformTransactionManager transactionManager) { // 获取目标class(应对AOP代理情况) Class<?> serviceClass = AopUtils.getTargetClass(service); logger.debug("解析服务:{}", ClassUtils.getQualifiedName(serviceClass)); Service serviceAnnotation = serviceClass.getAnnotation(Service.class); // 获取服务名称 String serviceName = serviceAnnotation.name(); if (StringUtils.isEmpty(serviceName)) { serviceName = ClassUtils.getShortNameAsProperty(serviceClass); } // 创建服务执行器 ServiceExecutor serviceExecutor = new ServiceExecutor(serviceName, serviceAnnotation.enableTx(), service); if (serviceAnnotation.enableTx()) { if (transactionManager == null) { throw new IllegalArgumentException("服务" + serviceAnnotation.name() + "的enableTx属性为开启状态,但不存在事务管理器(PlatformTransactionManager),请检查是否有配置spring事务管理器"); } serviceExecutor.setTxExecutor(new TxExecutor(transactionManager)); } for (Method method : serviceClass.getDeclaredMethods()) { for (Class clazz : ServiceExecutor.SERVICE_PHASE_ANNOTATIONS) { if (method.isAnnotationPresent(clazz)) { // 设置服务阶段执行器 serviceExecutor.setPhaseExecutor(clazz, parseServicePhase(method)); break; } } } serviceExecutor.validate(); return serviceExecutor; } // 解析服务阶段 private static ServicePhaseExecutor parseServicePhase(Method method) { logger.debug("解析服务方法:{}", method); // 校验方法类型 if (!Modifier.isPublic(method.getModifiers())) { throw new IllegalArgumentException("服务方法" + ClassUtils.getQualifiedMethodName(method) + "必须是public类型"); } // 校验入参 Class[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length != 1 || parameterTypes[0] != ServiceContext.class) { throw new IllegalArgumentException("服务方法" + ClassUtils.getQualifiedMethodName(method) + "的入参必须是(ServiceContext)"); } // 校验返回类型 if (method.getReturnType() != void.class) { throw new IllegalArgumentException("服务方法" + ClassUtils.getQualifiedMethodName(method) + "的返回类型必须是void"); } // 获取ServiceContext中泛型O、R的真实类型 ResolvableType resolvableType = ResolvableType.forMethodParameter(method, 0); Class orderClass = resolvableType.getGeneric(0).resolve(Object.class); Class resultClass = resolvableType.getGeneric(1).resolve(Object.class); // 校验result是否有默认构造函数 if (method.isAnnotationPresent(ServiceExecute.class)) { if (!ClassUtils.hasConstructor(resultClass, new Class[]{})) { throw new IllegalArgumentException("@ServiceExecute服务方法" + ClassUtils.getQualifiedMethodName(method) + "参数ServiceContext的泛型" + ClassUtils.getShortName(resultClass) + "必须得有默认构造函数"); } } return new ServicePhaseExecutor(method, orderClass, resultClass); } }
Minionguyjpro/Ghostly-Skills
sources/com/startapp/a/a/e/d.java
package com.startapp.a.a.e; import com.startapp.a.a.a.c; import java.io.ByteArrayInputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.PrintStream; /* compiled from: StartAppSDK */ public abstract class d { /* renamed from: a reason: collision with root package name */ private final c f16a = new c(); /* access modifiers changed from: protected */ public abstract c a(DataInput dataInput); public c a(String str) { if (str == null) { return null; } try { byte[] a2 = this.f16a.a(str); if (a2 == null) { return null; } return a(a(a2)); } catch (Exception e) { if (e.getMessage() != null && e.getMessage().contains("HighPageCountException")) { PrintStream printStream = System.err; printStream.println("HighPageCountException (PLM-2573) " + e.getMessage() + ", bad bloom token: " + str); } return null; } } /* access modifiers changed from: protected */ public void a(DataInput dataInput, c cVar, long j) { int c = cVar.c(); for (int i = 0; i < c; i++) { long[] a2 = cVar.a(i); int i2 = 0; while (true) { if (i2 >= 4096) { break; } long j2 = j - 1; if (j <= 0) { j = j2; break; } a2[i2] = dataInput.readLong(); i2++; j = j2; } } } /* access modifiers changed from: protected */ public DataInput a(byte[] bArr) { return new DataInputStream(new ByteArrayInputStream(bArr)); } }
sambacha/besu-ltz
packages/system/lib/system.js
"use strict"; module.exports = system; function system() { // TODO }
ayoubbargueoui1996/osm-devops
installers/charm/generate_bundle.py
<filename>installers/charm/generate_bundle.py # Copyright 2020 Canonical 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. import json import argparse CHANNEL_LIST = [ "stable", "candidate", "edge", ] BUNDLE_PREFIX = "cs:~charmed-osm" DEFAULT_BUNDLE = "bundles/osm/bundle.yaml" HA_BUNDLE = "bundles/osm-ha/bundle.yaml" parser = argparse.ArgumentParser(description="Process some arguments.") parser.add_argument("--channel", help="Channel from the Charm Store") parser.add_argument("--destination", help="Destination for the generated bundle") parser.add_argument("--ha", help="Select HA bundle", action="store_true") parser.add_argument("--local", help="Path to the bundle directory", action="store_true") parser.add_argument("--store", help="Path to the bundle directory", action="store_true") args = parser.parse_args() print(args) if not args.local and not args.store: raise Exception("--local or --store must be specified") if args.local and args.store: raise Exception("Both --local and --store cannot be specified. Please choose one.") if not args.destination: raise Exception("--destination must be specified") if args.channel and not args.channel in CHANNEL_LIST: raise Exception( "Channel {} does not exist. Please choose one of these: {}".format( args.channel, CHANNEL_LIST ) ) channel = args.channel if args.channel else "stable" path = HA_BUNDLE if args.ha else DEFAULT_BUNDLE destination = args.destination prefix = "." if args.local else BUNDLE_PREFIX suffix = "/build" if args.local else "" data = { "channel": channel, "prefix": prefix, "suffix": suffix, } with open(path) as template: bundle_template = template.read() template.close() with open("{}".format(destination), "w") as text_file: text_file.write(bundle_template % data) text_file.close()
aisolab/scala102
src/main/scala/scala/learning/nine/example/Example03.scala
<gh_stars>1-10 package scala.learning.nine.example // 09-1. 객체: apply 메소드와 동반객체 예제 // apply 메소드가 클래스의 팩토리 메소드 역할을 하는 경우 object Example03 extends App { val tripler = Multiplier(3) val result = tripler.product(13) println(result) } class Multiplier(val x: Int) { def product(y: Int) = x * y } object Multiplier { def apply(x: Int) = new Multiplier(x) }
ghsecuritylab/tomato_egg
release/src-rt/linux/linux-2.6/include/asm-um/hardirq.h
<filename>release/src-rt/linux/linux-2.6/include/asm-um/hardirq.h /* (c) 2004 <EMAIL>, GPLv2 blah blah */ #ifndef __ASM_UM_HARDIRQ_H #define __ASM_UM_HARDIRQ_H #include <linux/threads.h> #include <linux/irq.h> /* NOTE: When SMP works again we might want to make this * ____cacheline_aligned or maybe use per_cpu state? --cw */ typedef struct { unsigned int __softirq_pending; } irq_cpustat_t; #include <linux/irq_cpustat.h> /* As this would be very strange for UML to get we BUG() after the * printk. */ static inline void ack_bad_irq(unsigned int irq) { printk(KERN_ERR "unexpected IRQ %02x\n", irq); BUG(); } #endif /* __ASM_UM_HARDIRQ_H */
Yannic/chromium
components/cronet/url_request_context_config.h
// Copyright 2014 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 COMPONENTS_CRONET_URL_REQUEST_CONTEXT_CONFIG_H_ #define COMPONENTS_CRONET_URL_REQUEST_CONTEXT_CONFIG_H_ #include <memory> #include <string> #include <vector> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/time/time.h" #include "base/values.h" #include "net/base/hash_value.h" #include "net/cert/cert_verifier.h" #include "net/nqe/effective_connection_type.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "url/origin.h" namespace net { class CertVerifier; struct HttpNetworkSessionParams; struct QuicParams; class URLRequestContextBuilder; } // namespace net namespace cronet { // Common configuration parameters used by Cronet to configure // URLRequestContext. // TODO(mgersh): This shouldn't be a struct, and experimental option parsing // should be kept more separate from applying the configuration. struct URLRequestContextConfig { // Type of HTTP cache. // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.net.impl enum HttpCacheType { // No HTTP cache. DISABLED, // HTTP cache persisted to disk. DISK, // HTTP cache kept in memory. MEMORY, }; // App-provided hint that server supports QUIC. struct QuicHint { QuicHint(const std::string& host, int port, int alternate_port); QuicHint(const QuicHint&) = delete; QuicHint& operator=(const QuicHint&) = delete; ~QuicHint(); // Host name of the server that supports QUIC. const std::string host; // Port of the server that supports QUIC. const int port; // Alternate protocol port. const int alternate_port; }; // Public-Key-Pinning configuration structure. struct Pkp { Pkp(const std::string& host, bool include_subdomains, const base::Time& expiration_date); Pkp(const Pkp&) = delete; Pkp& operator=(const Pkp&) = delete; ~Pkp(); // Host name. const std::string host; // Pin hashes (currently SHA256 only). net::HashValueVector pin_hashes; // Indicates whether the pinning should apply to the pinned host subdomains. const bool include_subdomains; // Expiration date for the pins. const base::Time expiration_date; }; // Simulated headers, used to preconfigure the Reporting API and Network Error // Logging before receiving those actual configuration headers from the // origins. struct PreloadedNelAndReportingHeader { PreloadedNelAndReportingHeader(const url::Origin& origin, std::string value); ~PreloadedNelAndReportingHeader(); // Origin that is "sending" this header. const url::Origin origin; // Value of the header that is "sent". const std::string value; }; URLRequestContextConfig( // Enable QUIC. bool enable_quic, // QUIC User Agent ID. const std::string& quic_user_agent_id, // Enable SPDY. bool enable_spdy, // Enable Brotli. bool enable_brotli, // Type of http cache. HttpCacheType http_cache, // Max size of http cache in bytes. int http_cache_max_size, // Disable caching for HTTP responses. Other information may be stored in // the cache. bool load_disable_cache, // Storage path for http cache and cookie storage. const std::string& storage_path, // Accept-Language request header field. const std::string& accept_language, // User-Agent request header field. const std::string& user_agent, // JSON encoded experimental options. const std::string& experimental_options, // MockCertVerifier to use for testing purposes. std::unique_ptr<net::CertVerifier> mock_cert_verifier, // Enable network quality estimator. bool enable_network_quality_estimator, // Enable bypassing of public key pinning for local trust anchors bool bypass_public_key_pinning_for_local_trust_anchors, // Optional network thread priority. // On Android, corresponds to android.os.Process.setThreadPriority() // values. On iOS, corresponds to NSThread::setThreadPriority values. Do // not specify for other targets. absl::optional<double> network_thread_priority); URLRequestContextConfig(const URLRequestContextConfig&) = delete; URLRequestContextConfig& operator=(const URLRequestContextConfig&) = delete; ~URLRequestContextConfig(); // Configures |context_builder| based on |this|. void ConfigureURLRequestContextBuilder( net::URLRequestContextBuilder* context_builder); // Enable QUIC. const bool enable_quic; // QUIC User Agent ID. const std::string quic_user_agent_id; // Enable SPDY. const bool enable_spdy; // Enable Brotli. const bool enable_brotli; // Type of http cache. const HttpCacheType http_cache; // Max size of http cache in bytes. const int http_cache_max_size; // Disable caching for HTTP responses. Other information may be stored in // the cache. const bool load_disable_cache; // Storage path for http cache and cookie storage. const std::string storage_path; // Accept-Language request header field. const std::string accept_language; // User-Agent request header field. const std::string user_agent; // Certificate verifier for testing. std::unique_ptr<net::CertVerifier> mock_cert_verifier; // Enable Network Quality Estimator (NQE). const bool enable_network_quality_estimator; // Enable public key pinning bypass for local trust anchors. const bool bypass_public_key_pinning_for_local_trust_anchors; // App-provided list of servers that support QUIC. std::vector<std::unique_ptr<QuicHint>> quic_hints; // The list of public key pins. std::vector<std::unique_ptr<Pkp>> pkp_list; // Enable DNS cache persistence. bool enable_host_cache_persistence = false; // Minimum time in milliseconds between writing the HostCache contents to // prefs. Only relevant when |enable_host_cache_persistence| is true. int host_cache_persistence_delay_ms = 60000; // Experimental options that are recognized by the config parser. std::unique_ptr<base::DictionaryValue> effective_experimental_options; // If set, forces NQE to return the set value as the effective connection // type. absl::optional<net::EffectiveConnectionType> nqe_forced_effective_connection_type; // Preloaded Report-To headers, to preconfigure the Reporting API. std::vector<PreloadedNelAndReportingHeader> preloaded_report_to_headers; // Preloaded NEL headers, to preconfigure Network Error Logging. std::vector<PreloadedNelAndReportingHeader> preloaded_nel_headers; // Optional network thread priority. // On Android, corresponds to android.os.Process.setThreadPriority() values. // On iOS, corresponds to NSThread::setThreadPriority values. const absl::optional<double> network_thread_priority; private: // Parses experimental options and makes appropriate changes to settings in // the URLRequestContextConfig and URLRequestContextBuilder. void ParseAndSetExperimentalOptions( net::URLRequestContextBuilder* context_builder, net::HttpNetworkSessionParams* session_params, net::QuicParams* quic_params); // Experimental options encoded as a string in a JSON format containing // experiments and their corresponding configuration options. The format // is a JSON object with the name of the experiment as the key, and the // configuration options as the value. An example: // {"experiment1": {"option1": "option_value1", "option2": // "option_value2", // ...}, "experiment2: {"option3", "option_value3", ...}, ...} const std::string experimental_options; }; // Stores intermediate state for URLRequestContextConfig. Initializes with // (mostly) sane defaults, then the appropriate member variables can be // modified, and it can be finalized with Build(). struct URLRequestContextConfigBuilder { URLRequestContextConfigBuilder(); URLRequestContextConfigBuilder(const URLRequestContextConfigBuilder&) = delete; URLRequestContextConfigBuilder& operator=( const URLRequestContextConfigBuilder&) = delete; ~URLRequestContextConfigBuilder(); // Finalize state into a URLRequestContextConfig. Must only be called once, // as once |mock_cert_verifier| is moved into a URLRequestContextConfig, it // cannot be used again. std::unique_ptr<URLRequestContextConfig> Build(); // Enable QUIC. bool enable_quic = true; // QUIC User Agent ID. std::string quic_user_agent_id = ""; // Enable SPDY. bool enable_spdy = true; // Enable Brotli. bool enable_brotli = false; // Type of http cache. URLRequestContextConfig::HttpCacheType http_cache = URLRequestContextConfig::DISABLED; // Max size of http cache in bytes. int http_cache_max_size = 0; // Disable caching for HTTP responses. Other information may be stored in // the cache. bool load_disable_cache = false; // Storage path for http cache and cookie storage. std::string storage_path = ""; // Accept-Language request header field. std::string accept_language = ""; // User-Agent request header field. std::string user_agent = ""; // Experimental options encoded as a string in a JSON format containing // experiments and their corresponding configuration options. The format // is a JSON object with the name of the experiment as the key, and the // configuration options as the value. An example: // {"experiment1": {"option1": "option_value1", "option2": "option_value2", // ...}, "experiment2: {"option3", "option_value3", ...}, ...} std::string experimental_options = "{}"; // Certificate verifier for testing. std::unique_ptr<net::CertVerifier> mock_cert_verifier; // Enable network quality estimator. bool enable_network_quality_estimator = false; // Enable public key pinning bypass for local trust anchors. bool bypass_public_key_pinning_for_local_trust_anchors = true; // Optional network thread priority. // On Android, corresponds to android.os.Process.setThreadPriority() values. // On iOS, corresponds to NSThread::setThreadPriority values. // Do not specify for other targets. absl::optional<double> network_thread_priority; }; } // namespace cronet #endif // COMPONENTS_CRONET_URL_REQUEST_CONTEXT_CONFIG_H_
srihari-nagaraj/anuvaad
anuvaad-etl/anuvaad-extractor/block-merger/src/utilities/class_2/orientation_correction.py
<filename>anuvaad-etl/anuvaad-extractor/block-merger/src/utilities/class_2/orientation_correction.py class ExtractTextRegions: def __init__(self, image_path, session=sess, conf_threshold=50, lang='eng'): self.image_path = image_path self.image = cv2.imread(image_path)[:, :, ::-1] self.sess = session self.conf_threshold = int(conf_threshold) self.timer = {'net': 0, 'restore': 0, 'nms': 0} self.text = {} self.lang = lang self.extract_text_region() def east_output(self): out_put = [] start = time.time() im_resized, (ratio_h, ratio_w) = postprocess.resize_image(self.image) score, geometry = self.sess.run([f_score, f_geometry], feed_dict={input_images: [im_resized]}) self.timer['net'] = time.time() - start boxes, self.timer = postprocess.detect(score_map=score, geo_map=geometry, timer=self.timer) # #print (' net {:.0f}ms, restore {:.0f}ms, nms {:.0f}ms'.format (self.timer ['net'] * 1000, # self.timer ['restore'] * 1000, # self.timer ['nms'] * 1000)) if boxes is not None: boxes = boxes[:, :8].reshape((-1, 4, 2)) boxes[:, :, 0] /= ratio_w boxes[:, :, 1] /= ratio_h # if boxes is not None: for box in boxes: # to avoid submitting errors box = postprocess.sort_poly(box.astype(np.int32)) # print(box) if np.linalg.norm(box[0] - box[1]) < 5 or np.linalg.norm(box[3] - box[0]) < 5: continue out_put.append( [box[0, 0], box[0, 1], box[1, 0], box[1, 1], box[2, 0], box[2, 1], box[3, 0], box[3, 1]]) return out_put def convert_to_df(self): # dic = [] # for i,box in enumerate(self.bbox): # dic.append({'x1': box[0] ,'y1': box[1] ,'x2': box[2] ,'y2': box[3] ,'x3': box[4] ,'y3': box[5] ,'x4': box[6] ,'y4': box[7]}) df = pd.DataFrame(self.bbox, columns=['x1', 'y1', 'x2', 'y2', 'x3', 'y3', 'x4', 'y4']) df['height'] = df['y4'] - df['y1'] df['width'] = df['x2'] - df['x1'] df['ymid'] = (df['y4'] + df['y3']) * 0.5 df['area'] = df['width'] * df['height'] df = df.sort_values(by=['ymid']) df['group'] = None df['line_change'] = 0 self.df = df def dump_out(self, bbc, rot): im = self.image.copy() for box in bbc: # print(box) cv2.polylines(im, [np.array(box).astype(np.int32).reshape((-1, 1, 2))], True, color=(255, 255, 0), thickness=1) cv2.imwrite('tmp/' + str(rot) + '.png', im) def get_rotaion_angle(self, text_cor_df): bbox_df = text_cor_df.copy() # bboxex = Box_cordinates (east_coordinates) bbox_df['delta_x'] = bbox_df['x2'] - bbox_df['x1'] bboxex.df['delta_y'] = bboxex.df['y2'] - bboxex.df['y1'] box_dir = [bboxex.df['delta_x'].mean(), bboxex.df['delta_y'].mean()] # print(box_dir) x_axis = [1, 0] cosine = np.dot(box_dir, x_axis) / (np.linalg.norm(box_dir) * np.linalg.norm(x_axis)) angle = np.arccos(cosine) * 180 / np.pi avrage_height = bboxex.df['height'].mean() avrage_width = bboxex.df['width'].mean() if avrage_height > avrage_width: angle = 90 - angle return angle * np.sign(box_dir[1]) def check_orientation(self, group_cordinates, margin=5): upside_down = False orientation = [] for index, block in enumerate(group_cordinates): crop = self.image[block[0][1] - margin: block[1][1] + margin, block[0][0] - margin: block[1][0] + margin] try: osd = pytesseract.image_to_osd(crop) angle = osd.split('\nRotate')[0].split(': ')[-1] orientation.append(int(angle)) except: pass orientation = np.array(orientation) chk_orientation = orientation > 170 # Taking vote of regions if chk_orientation.sum() > (len(orientation) * 0.5): # print ('Image is upside down') upside_down = True return upside_down return upside_down def extract_text_region(self): # try : east_cor = self.east_output() angle = self.get_rotaion_angle(east_cor) rotations = 1 # self.dump_out(east_cor,rotations) # Orientation correction while abs(angle) > 2.5: self.image = imutils.rotate_bound(self.image, -angle) if rotations > 1: # Remove rotaion artifacts contours = cv2.findContours(cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) contours = contours[0] if len(contours) == 2 else contours[1] if len(contours) > 0: x, y, w, h = cv2.boundingRect(contours[0]) # print('cropped area reduced ') self.image = self.image[y:y + h, x:x + w, :] east_cor = self.east_output() angle = self.get_rotaion_angle(east_cor) rotations += 1 # self.dump_out(east_cor,rotations) bbox1 = Box_cordinates(east_cor) upside_down = self.check_orientation(bbox1.gr_cordinates) if upside_down: self.image = imutils.rotate_bound(self.image, 180) east_cor = self.east_output() # self.dump_out(east_cor,rotations) bbox2 = Box_cordinates(east_cor, image=self.image, conf_threshold=self.conf_threshold) text_dic, avrage_confidence = bbox2.get_text(lang=self.lang) # added text text_postprocessing self.text = {'metadata': Text_to_json(text_dic).metadata, 'text': [text_dic], 'avrage_confidence': avrage_confidence} # except : # logging.debug('Text extaction failed for {0}'.format(self.image_path))
CrystianPrintes20/ProjetoUri
PythonCode/1146.py
#QUESTÃO: SEQUÊNCIAS CRESCENTES while True: x = int(input()) es = "" if x == 0: break for i in range(1,x+1): es += str(i) + " " print(es[:-1])
catalinboja/cts-2021
course En/Course 11 - Template/src/ro/ase/cts/TestTemplate.java
package ro.ase.cts; public class TestTemplate { public static void main(String[] args) { NUnitTesting nUnit = new NUnitTesting(); JUnitTesting jUnit = new JUnitTesting(); nUnit.test(); jUnit.test(); } }
nikhilsamninan/python-files
day8/listoperations.py
L=[10,5,55,1] #print(L.append(6)) #print(L) print(L.extend([6,4])) print(L) #print(L.reverse()) #print(L) #print(L.sort(reverse=True)) #print(L) #print(L.pop(1)) #print(L) #print(L.remove(55)) #print(L) #del L[0] #print(L)
rudty/nodekell
test/average.spec.js
<reponame>rudty/nodekell "use strict"; const F = require("../index"); const assert = require("assert"); describe('test average', () => { it('num', async () => { const a = [1,2,3,4,5]; const s = await F.average(a); assert.strictEqual(s, 3); }); it('float', async () => { const a = [1.0,2.0,3.0,4.0,5.5]; const s = await F.average(a); assert.strictEqual(s, 3.1); }); it('float2', async () => { const a = [1.0,2.0,3.0,4.0,5.0]; const s = await F.average(a); assert.strictEqual(s, 3); }); // it('string array', async () => { // const a = ["a","b","c","d","e"]; // const s = await F.sum(a); // assert.strictEqual(s, "abcde"); // }); // it('string', async () => { // const a = "abcde"; // const s = await F.sum(a); // assert.strictEqual(s, "abcde"); // }); });
buckelieg/simple-tools
src/main/java/buckelieg/jdbc/ImmutableResultSet.java
<reponame>buckelieg/simple-tools /* * Copyright 2016- <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 buckelieg.jdbc; import javax.annotation.Nonnull; import java.io.InputStream; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.sql.*; import java.util.Calendar; import java.util.Map; import static buckelieg.jdbc.Utils.EXCEPTION_MESSAGE; import static java.util.Objects.requireNonNull; class ImmutableResultSet implements ResultSet { protected final ResultSet delegate; ImmutableResultSet(@Nonnull ResultSet delegate) { this.delegate = requireNonNull(delegate, "ResultSet must be provided"); } @Override public boolean next() throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void close() throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public boolean wasNull() throws SQLException { return delegate.wasNull(); } @Override public String getString(int columnIndex) throws SQLException { return delegate.getString(columnIndex); } @Override public boolean getBoolean(int columnIndex) throws SQLException { return delegate.getBoolean(columnIndex); } @Override public byte getByte(int columnIndex) throws SQLException { return delegate.getByte(columnIndex); } @Override public short getShort(int columnIndex) throws SQLException { return delegate.getShort(columnIndex); } @Override public int getInt(int columnIndex) throws SQLException { return delegate.getInt(columnIndex); } @Override public long getLong(int columnIndex) throws SQLException { return delegate.getLong(columnIndex); } @Override public float getFloat(int columnIndex) throws SQLException { return delegate.getFloat(columnIndex); } @Override public double getDouble(int columnIndex) throws SQLException { return delegate.getDouble(columnIndex); } @Override @Deprecated public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { return delegate.getBigDecimal(columnIndex, scale); } @Override public byte[] getBytes(int columnIndex) throws SQLException { return delegate.getBytes(columnIndex); } @Override public Date getDate(int columnIndex) throws SQLException { return delegate.getDate(columnIndex); } @Override public Time getTime(int columnIndex) throws SQLException { return delegate.getTime(columnIndex); } @Override public Timestamp getTimestamp(int columnIndex) throws SQLException { return delegate.getTimestamp(columnIndex); } @Override public InputStream getAsciiStream(int columnIndex) throws SQLException { return delegate.getAsciiStream(columnIndex); } @Override @Deprecated public InputStream getUnicodeStream(int columnIndex) throws SQLException { return delegate.getUnicodeStream(columnIndex); } @Override public InputStream getBinaryStream(int columnIndex) throws SQLException { return delegate.getBinaryStream(columnIndex); } @Override public String getString(String columnLabel) throws SQLException { return delegate.getString(columnLabel); } @Override public boolean getBoolean(String columnLabel) throws SQLException { return delegate.getBoolean(columnLabel); } @Override public byte getByte(String columnLabel) throws SQLException { return delegate.getByte(columnLabel); } @Override public short getShort(String columnLabel) throws SQLException { return delegate.getShort(columnLabel); } @Override public int getInt(String columnLabel) throws SQLException { return delegate.getInt(columnLabel); } @Override public long getLong(String columnLabel) throws SQLException { return delegate.getLong(columnLabel); } @Override public float getFloat(String columnLabel) throws SQLException { return delegate.getFloat(columnLabel); } @Override public double getDouble(String columnLabel) throws SQLException { return delegate.getDouble(columnLabel); } @Override @Deprecated public BigDecimal getBigDecimal(String columnLabel, int scale) throws SQLException { return delegate.getBigDecimal(columnLabel, scale); } @Override public byte[] getBytes(String columnLabel) throws SQLException { return delegate.getBytes(columnLabel); } @Override public Date getDate(String columnLabel) throws SQLException { return delegate.getDate(columnLabel); } @Override public Time getTime(String columnLabel) throws SQLException { return delegate.getTime(columnLabel); } @Override public Timestamp getTimestamp(String columnLabel) throws SQLException { return delegate.getTimestamp(columnLabel); } @Override public InputStream getAsciiStream(String columnLabel) throws SQLException { return delegate.getAsciiStream(columnLabel); } @Override @Deprecated public InputStream getUnicodeStream(String columnLabel) throws SQLException { return delegate.getUnicodeStream(columnLabel); } @Override public InputStream getBinaryStream(String columnLabel) throws SQLException { return delegate.getBinaryStream(columnLabel); } @Override public SQLWarning getWarnings() throws SQLException { return delegate.getWarnings(); } @Override public void clearWarnings() throws SQLException { delegate.clearWarnings(); } @Override public String getCursorName() throws SQLException { return delegate.getCursorName(); } @Override public ResultSetMetaData getMetaData() throws SQLException { return delegate.getMetaData(); } @Override public Object getObject(int columnIndex) throws SQLException { return delegate.getObject(columnIndex); } @Override public Object getObject(String columnLabel) throws SQLException { return delegate.getObject(columnLabel); } @Override public int findColumn(String columnLabel) throws SQLException { return delegate.findColumn(columnLabel); } @Override public Reader getCharacterStream(int columnIndex) throws SQLException { return delegate.getCharacterStream(columnIndex); } @Override public Reader getCharacterStream(String columnLabel) throws SQLException { return delegate.getCharacterStream(columnLabel); } @Override public BigDecimal getBigDecimal(int columnIndex) throws SQLException { return delegate.getBigDecimal(columnIndex); } @Override public BigDecimal getBigDecimal(String columnLabel) throws SQLException { return delegate.getBigDecimal(columnLabel); } @Override public boolean isBeforeFirst() throws SQLException { return delegate.isBeforeFirst(); } @Override public boolean isAfterLast() throws SQLException { return delegate.isAfterLast(); } @Override public boolean isFirst() throws SQLException { return delegate.isFirst(); } @Override public boolean isLast() throws SQLException { return delegate.isLast(); } @Override public void beforeFirst() throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void afterLast() throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public boolean first() throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public boolean last() throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public int getRow() throws SQLException { return delegate.getRow(); } @Override public boolean absolute(int row) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public boolean relative(int rows) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public boolean previous() throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public int getFetchDirection() throws SQLException { return delegate.getFetchDirection(); } @Override public void setFetchDirection(int direction) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public int getFetchSize() throws SQLException { return delegate.getFetchSize(); } @Override public void setFetchSize(int rows) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public int getType() throws SQLException { return delegate.getType(); } @Override public int getConcurrency() throws SQLException { return delegate.getConcurrency(); } @Override public boolean rowUpdated() throws SQLException { return delegate.rowUpdated(); } @Override public boolean rowInserted() throws SQLException { return delegate.rowInserted(); } @Override public boolean rowDeleted() throws SQLException { return delegate.rowDeleted(); } @Override public void updateNull(int columnIndex) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBoolean(int columnIndex, boolean x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateByte(int columnIndex, byte x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateShort(int columnIndex, short x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateInt(int columnIndex, int x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateLong(int columnIndex, long x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateFloat(int columnIndex, float x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateDouble(int columnIndex, double x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateString(int columnIndex, String x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBytes(int columnIndex, byte[] x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateDate(int columnIndex, Date x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateTime(int columnIndex, Time x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateAsciiStream(int columnIndex, InputStream x, int length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateCharacterStream(int columnIndex, Reader x, int length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateObject(int columnIndex, Object x, int scaleOrLength) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateObject(int columnIndex, Object x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateNull(String columnLabel) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBoolean(String columnLabel, boolean x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateByte(String columnLabel, byte x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateShort(String columnLabel, short x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateInt(String columnLabel, int x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateLong(String columnLabel, long x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateFloat(String columnLabel, float x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateDouble(String columnLabel, double x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBigDecimal(String columnLabel, BigDecimal x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateString(String columnLabel, String x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBytes(String columnLabel, byte[] x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateDate(String columnLabel, Date x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateTime(String columnLabel, Time x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateTimestamp(String columnLabel, Timestamp x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateAsciiStream(String columnLabel, InputStream x, int length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBinaryStream(String columnLabel, InputStream x, int length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateCharacterStream(String columnLabel, Reader reader, int length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateObject(String columnLabel, Object x, int scaleOrLength) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateObject(String columnLabel, Object x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void insertRow() throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateRow() throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void deleteRow() throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void refreshRow() throws SQLException { delegate.refreshRow(); } @Override public void cancelRowUpdates() throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void moveToInsertRow() throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void moveToCurrentRow() throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public Statement getStatement() throws SQLException { return delegate.getStatement(); } @Override public Object getObject(int columnIndex, Map<String, Class<?>> map) throws SQLException { return delegate.getObject(columnIndex, map); } @Override public Ref getRef(int columnIndex) throws SQLException { return delegate.getRef(columnIndex); } @Override public Blob getBlob(int columnIndex) throws SQLException { return delegate.getBlob(columnIndex); } @Override public Clob getClob(int columnIndex) throws SQLException { return delegate.getClob(columnIndex); } @Override public Array getArray(int columnIndex) throws SQLException { return delegate.getArray(columnIndex); } @Override public Object getObject(String columnLabel, Map<String, Class<?>> map) throws SQLException { return delegate.getObject(columnLabel, map); } @Override public Ref getRef(String columnLabel) throws SQLException { return delegate.getRef(columnLabel); } @Override public Blob getBlob(String columnLabel) throws SQLException { return delegate.getBlob(columnLabel); } @Override public Clob getClob(String columnLabel) throws SQLException { return delegate.getClob(columnLabel); } @Override public Array getArray(String columnLabel) throws SQLException { return delegate.getArray(columnLabel); } @Override public Date getDate(int columnIndex, Calendar cal) throws SQLException { return delegate.getDate(columnIndex, cal); } @Override public Date getDate(String columnLabel, Calendar cal) throws SQLException { return delegate.getDate(columnLabel, cal); } @Override public Time getTime(int columnIndex, Calendar cal) throws SQLException { return delegate.getTime(columnIndex, cal); } @Override public Time getTime(String columnLabel, Calendar cal) throws SQLException { return delegate.getTime(columnLabel, cal); } @Override public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { return delegate.getTimestamp(columnIndex, cal); } @Override public Timestamp getTimestamp(String columnLabel, Calendar cal) throws SQLException { return delegate.getTimestamp(columnLabel, cal); } @Override public URL getURL(int columnIndex) throws SQLException { return delegate.getURL(columnIndex); } @Override public URL getURL(String columnLabel) throws SQLException { return delegate.getURL(columnLabel); } @Override public void updateRef(int columnIndex, Ref x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateRef(String columnLabel, Ref x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBlob(int columnIndex, Blob x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBlob(String columnLabel, Blob x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateClob(int columnIndex, Clob x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateClob(String columnLabel, Clob x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateArray(int columnIndex, Array x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateArray(String columnLabel, Array x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public RowId getRowId(int columnIndex) throws SQLException { return delegate.getRowId(columnIndex); } @Override public RowId getRowId(String columnLabel) throws SQLException { return delegate.getRowId(columnLabel); } @Override public void updateRowId(int columnIndex, RowId x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateRowId(String columnLabel, RowId x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public int getHoldability() throws SQLException { return delegate.getHoldability(); } @Override public boolean isClosed() throws SQLException { return delegate.isClosed(); } @Override public void updateNString(int columnIndex, String nString) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateNString(String columnLabel, String nString) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateNClob(int columnIndex, NClob nClob) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateNClob(String columnLabel, NClob nClob) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public NClob getNClob(int columnIndex) throws SQLException { return delegate.getNClob(columnIndex); } @Override public NClob getNClob(String columnLabel) throws SQLException { return delegate.getNClob(columnLabel); } @Override public SQLXML getSQLXML(int columnIndex) throws SQLException { return delegate.getSQLXML(columnIndex); } @Override public SQLXML getSQLXML(String columnLabel) throws SQLException { return delegate.getSQLXML(columnLabel); } @Override public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public String getNString(int columnIndex) throws SQLException { return delegate.getNString(columnIndex); } @Override public String getNString(String columnLabel) throws SQLException { return delegate.getNString(columnLabel); } @Override public Reader getNCharacterStream(int columnIndex) throws SQLException { return delegate.getNCharacterStream(columnIndex); } @Override public Reader getNCharacterStream(String columnLabel) throws SQLException { return delegate.getNCharacterStream(columnLabel); } @Override public void updateNCharacterStream(int columnIndex, Reader x, long length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateNCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateAsciiStream(int columnIndex, InputStream x, long length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBinaryStream(int columnIndex, InputStream x, long length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateAsciiStream(String columnLabel, InputStream x, long length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBinaryStream(String columnLabel, InputStream x, long length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateCharacterStream(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBlob(String columnLabel, InputStream inputStream, long length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateClob(int columnIndex, Reader reader, long length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateClob(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateNCharacterStream(String columnLabel, Reader reader) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateAsciiStream(int columnIndex, InputStream x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBinaryStream(int columnIndex, InputStream x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateCharacterStream(int columnIndex, Reader x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateClob(int columnIndex, Reader reader) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateClob(String columnLabel, Reader reader) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateNClob(int columnIndex, Reader reader) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public void updateNClob(String columnLabel, Reader reader) throws SQLException { throw new SQLException(EXCEPTION_MESSAGE); } @Override public <T> T getObject(int columnIndex, Class<T> type) throws SQLException { return delegate.getObject(columnIndex, type); } @Override public <T> T getObject(String columnLabel, Class<T> type) throws SQLException { return delegate.getObject(columnLabel, type); } @Override public <T> T unwrap(Class<T> iface) throws SQLException { return delegate.unwrap(iface); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return delegate.isWrapperFor(iface); } }
jgraichen/codeocean
test/factories/structured_errors.rb
<filename>test/factories/structured_errors.rb FactoryBot.define do factory :structured_error do error_template nil submission nil end end
molinjc/JCKitDemo
JCKitDemo/JCKitDemo/Class/UIChain/JCChainViewController.h
<gh_stars>1-10 // // JCChainViewController.h // JCKitDemo // // Created by molin.JC on 2017/12/1. // Copyright © 2017年 molin. All rights reserved. // #import "JCViewController.h" @interface JCChainViewController : JCViewController @end
crutchwalkfactory/jaikuengine-mobile-client
ContextCommon/src/errorhandling.cpp
<reponame>crutchwalkfactory/jaikuengine-mobile-client<gh_stars>0 // Copyright (c) 2007-2009 Google Inc. // Copyright (c) 2006-2007 Jaiku Ltd. // Copyright (c) 2002-2006 <NAME> and <NAME> // // This software is licensed at your choice under either 1 or 2 below. // // 1. 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. // // 2. Gnu General Public license 2.0 // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // // This file is part of the JaikuEngine mobile client. #include "errorhandling.h" #include "app_context.h" #include "vararg_impl_macros.h" #include "app_context_impl.h" IMPL_VARARG(MErrorInfoManager, UserMsg, MErrorInfoManager&, const TStringArg&); IMPL_VARARG(MErrorInfoManager, TechMsg, MErrorInfoManager&, const TStringArg&); _LIT(KNoAppContext, "NO_APP_CONTEXT"); MApp_context& Context() { MApp_context* c=GetContext(); if (!c) User::Panic(KNoAppContext, -1); return *c; } EXPORT_C MErrorInfoManager& Bug(const TDesC& aTechMsg) { MErrorInfoManager &m=Context().ErrorInfoMgr(); m.StartErrorWithInfo( KErrorBug, KNullDesC(), aTechMsg, EBug, EError ); return m; } EXPORT_C MErrorInfoManager& Corrupt(const TDesC& aTechMsg) { MErrorInfoManager &m=Context().ErrorInfoMgr(); m.StartErrorWithInfo( KErrorUnknown, KNullDesC(), aTechMsg, EBug, ECorrupt ); return m; } EXPORT_C MErrorInfoManager& InputErr(const TDesC& aUserMsg) { MErrorInfoManager &m=Context().ErrorInfoMgr(); m.StartErrorWithInfo( KErrorUnknown, aUserMsg, KNullDesC(), EInputData, EError ); return m; } EXPORT_C MErrorInfoManager& RemoteErr(const TDesC& aTechMsg) { MErrorInfoManager &m=Context().ErrorInfoMgr(); m.StartErrorWithInfo( KErrorUnknown, KNullDesC(), aTechMsg, ERemote, EError ); return m; } EXPORT_C MErrorInfoManager& EnvErr(const TDesC& aUserMsg) { MErrorInfoManager &m=Context().ErrorInfoMgr(); m.StartErrorWithInfo( KErrorUnknown, aUserMsg, KNullDesC(), ELocalEnvironment, EError ); return m; } EXPORT_C MErrorInfoManager& PlainErr(TInt aError) { MErrorInfoManager &m=Context().ErrorInfoMgr(); TErrorCode e={ 0, aError }; TErrorType t=EBug; if (aError==KErrNoMemory) t=ELocalEnvironment; m.StartErrorWithInfo( e, KNullDesC(), KNullDesC(), t, EError ); return m; }
luhn/AutobahnPython
examples/twisted/websocket/slowsquare/server.py
<gh_stars>0 ############################################################################### ## ## Copyright (C) 2014 Tavendo GmbH ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## ############################################################################### from autobahn.twisted.websocket import WebSocketServerProtocol, \ WebSocketServerFactory import json from twisted.internet.defer import Deferred, \ inlineCallbacks, \ returnValue def sleep(delay): d = Deferred() reactor.callLater(delay, d.callback, None) return d class SlowSquareServerProtocol(WebSocketServerProtocol): @inlineCallbacks def slowsquare(self, x): if x > 5: raise Exception("number too large") else: yield sleep(1) returnValue(x * x) @inlineCallbacks def onMessage(self, payload, isBinary): if not isBinary: x = json.loads(payload.decode('utf8')) try: res = yield self.slowsquare(x) except Exception as e: self.sendClose(1000, "Exception raised: {0}".format(e)) else: self.sendMessage(json.dumps(res).encode('utf8')) if __name__ == '__main__': import sys from twisted.python import log from twisted.internet import reactor log.startLogging(sys.stdout) factory = WebSocketServerFactory("ws://localhost:9000", debug = False) factory.protocol = SlowSquareServerProtocol reactor.listenTCP(9000, factory) reactor.run()
undergrowthlinear/learntest
learncommon/src/main/java/com/learncommon/mapper/GsmsContactMapper.java
<gh_stars>0 package com.learncommon.mapper; import com.learncommon.entity.GsmsContact; public interface GsmsContactMapper { int deleteByPrimaryKey(Integer id); int insert(GsmsContact record); int insertSelective(GsmsContact record); GsmsContact selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(GsmsContact record); int updateByPrimaryKey(GsmsContact record); }
BlackYps/faf-java-commons
faf-commons-api/src/main/java/com/faforever/commons/api/dto/FeaturedMod.java
<reponame>BlackYps/faf-java-commons<gh_stars>0 package com.faforever.commons.api.dto; import com.faforever.commons.api.elide.ElideEntity; import com.github.jasminb.jsonapi.annotations.Id; import com.github.jasminb.jsonapi.annotations.Type; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; @Data @ToString(onlyExplicitlyIncluded = true) @EqualsAndHashCode(onlyExplicitlyIncluded = true) @Type("featuredMod") public class FeaturedMod implements ElideEntity { @Id @ToString.Include @EqualsAndHashCode.Include String id; String description; @ToString.Include String displayName; int order; String gitBranch; String gitUrl; String bireusUrl; @ToString.Include String technicalName; boolean visible; }
SolidRun/edk2-platforms
Silicon/NXP/LX2160A/Include/SocSerDes.h
/** @file The Header file of SerDes Module for LX2160A Copyright 2017 NXP This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #ifndef __SOC_SERDES_H__ #define __SOC_SERDES_H__ #include <SerDes.h> SERDES_CONFIG SerDes1ConfigTbl[] = { /* SerDes 1 */ { 1, { PCIE2, PCIE2, PCIE2, PCIE2, PCIE1, PCIE1, PCIE1, PCIE1 } }, { 2, { PCIE2, PCIE2, PCIE2, PCIE2, SGMII6, SGMII5, SGMII4, SGMII3 } }, { 3, { PCIE2, PCIE2, PCIE2, PCIE2, XFI6, XFI5, XFI4, XFI3 } }, { 4, { SGMII10, SGMII9, SGMII8, SGMII7, SGMII6, SGMII5, SGMII4, SGMII3 } }, { 5, { XFI10, XFI9, XFI8, XFI7, PCIE1, PCIE1, PCIE1, PCIE1} }, { 6, { SGMII10, SGMII9, SGMII8, SGMII7, SGMII6, SGMII5, XFI4, XFI3 } }, { 7, { SGMII10, SGMII9, SGMII8, SGMII7, XFI6, XFI5, XFI4, XFI3 } }, { 8, { XFI10, XFI9, XFI8, XFI7, XFI6, XFI5, XFI4, XFI3 } }, { 9, { SGMII10, SGMII9, SGMII8, PCIE2, SGMII6, SGMII5, SGMII4, PCIE1 } }, { 10, { XFI10, XFI9, XFI8, PCIE2, XFI6, XFI5, XFI4, PCIE1 } }, { 11, { SGMII10, SGMII9, PCIE2, PCIE2, SGMII6, SGMII5, PCIE1, PCIE1 } }, { 12, { SGMII10, SGMII9, PCIE2, PCIE2, PCIE1, PCIE1, PCIE1, PCIE1 } }, { 13, { GE100_2, GE100_2, GE100_2, GE100_2, GE100_1, GE100_1, GE100_1, GE100_1 } }, { 14, { PCIE2, PCIE2, PCIE2, PCIE2, GE100_1, GE100_1, GE100_1, GE100_1 } }, { 15, { PCIE2, PCIE2, PCIE2, PCIE2, GE50_2, GE50_2, GE50_1, GE50_1 } }, { 16, { PCIE2, PCIE2, PCIE2, PCIE2, GE25_6, GE25_5, GE50_1, GE50_1 } }, { 17, { PCIE2, PCIE2, PCIE2, PCIE2, GE25_6, GE25_5, GE25_4, GE25_3 } }, { 18, { XFI10, XFI9, XFI8, XFI7, GE25_6, GE25_5, XFI4, XFI3 } }, { 19, { GE40_2, GE40_2, GE40_2, GE40_2, GE25_6, GE25_5, XFI4, XFI3 } }, { 20, { GE40_2, GE40_2, GE40_2, GE40_2, GE40_1, GE40_1, GE40_1, GE40_1 } }, { 21, { GE25_10, GE25_9, PCIE2, PCIE2, GE25_6, GE25_5, GE25_4, GE25_3 } }, { 22, { XFI10, XFI9, PCIE2, PCIE2, XFI6, XFI5, XFI4, XFI3 } }, {} }; SERDES_CONFIG SerDes2ConfigTbl[] = { /* SerDes 2 */ { 1, { PCIE3, PCIE3, SATA1, SATA2, PCIE4, PCIE4, PCIE4, PCIE4 } }, { 2, { PCIE3, PCIE3, PCIE3, PCIE3, PCIE3, PCIE3, PCIE3, PCIE3 } }, { 3, { PCIE3, PCIE3, PCIE3, PCIE3, PCIE4, PCIE4, PCIE4, PCIE4 } }, { 4, { PCIE3, PCIE3, PCIE3, PCIE3, PCIE4, PCIE4, SATA1, SATA2 } }, { 5, { PCIE3, PCIE3, PCIE3, PCIE3, SATA3, SATA4, SATA1, SATA2 } }, { 6, { PCIE3, PCIE3, PCIE3, PCIE3, SGMII15, SGMII16, XFI13, XFI14} }, { 7, { PCIE3, SGMII12, SGMII17, SGMII18, PCIE4, SGMII16, XFI13, XFI14} }, { 8, { 0, 0, SATA1, SATA2, SATA3, SATA4, XFI13, XFI14} }, { 9, { SGMII11, SGMII12, SGMII17, SGMII18, SGMII15, SGMII16, SGMII13, SGMII14 } }, { 10, { SGMII11, SGMII12, SGMII17, SGMII18, PCIE4, PCIE4, PCIE4, PCIE4 } }, { 11, { PCIE3, SGMII12, SGMII17, SGMII18, PCIE4, SGMII16, SGMII13, SGMII14 } }, { 12, { SGMII11, SGMII12, SGMII17, SGMII18, PCIE4, PCIE4, SATA1, SATA2 } }, { 13, { PCIE3, PCIE3, PCIE3, PCIE3, PCIE4, PCIE4, SGMII13, SGMII14 } }, { 14, { PCIE3, PCIE3, SGMII17, SGMII18, PCIE4, PCIE4, SGMII13, SGMII14 } }, {} }; SERDES_CONFIG SerDes3ConfigTbl[] = { /* SerDes 3 */ { 2, { PCIE5, PCIE5, PCIE5, PCIE5, PCIE5, PCIE5, PCIE5, PCIE5 } }, { 3, { PCIE5, PCIE5, PCIE5, PCIE5, PCIE6, PCIE6, PCIE6, PCIE6 } }, {} }; SERDES_CONFIG *SerDesConfigTbl[] = { SerDes1ConfigTbl, SerDes2ConfigTbl, SerDes3ConfigTbl }; #endif /* __SOC_SERDES_H */
chaitanyks/fuzzy-disco
Linked List Random Node.cpp
// https://leetcode.com/problems/linked-list-random-node/ // 382. Linked List Random Node /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode*Head; Solution(ListNode*head) { Head = head; } int getRandom() { ListNode * temp = Head; int pos; int n = 0; while (temp != NULL) { temp = temp -> next; pos = rand(); if (pos < n) { break; } n++; } if (pos > n) { pos = rand() % n; } temp = Head; while (pos--) { temp = temp -> next; } return temp -> val; } }; /** * Your Solution object will be instantiated and called as such: * Solution* obj = new Solution(head); * int param_1 = obj->getRandom(); */
shuigedeng/taotao-cloud-paren
taotao-cloud-microservice/taotao-cloud-yshop/src/main/java/com/taotao/cloud/yshop/biz/dto/DictQueryCriteria.java
/** * Copyright (C) 2018-2020 * All rights reserved, Designed By www.yixiang.co * 注意: * 本软件为www.yixiang.co开发研制 */ package com.taotao.cloud.system.api.dto; import com.taotao.cloud.system.api.annotation.Query; public class DictQueryCriteria { @Query(blurry = "name,remark") private String blurry; public String getBlurry() { return blurry; } public void setBlurry(String blurry) { this.blurry = blurry; } }
BookAppPA/Dashboard-Admin
src/pages/user/usersList/Users.js
import { useEffect, useContext } from 'react'; import { createUseStyles, useTheme } from 'react-jss'; import { Box } from '@material-ui/core'; import MUIDataTable from "mui-datatables"; import { useHistory } from 'react-router-dom'; import ROUTE from '../../../routes/RoutesNames'; import Chip from '@material-ui/core/Chip'; import { useDispatch, useSelector } from 'react-redux'; import { getAllUsers, getUserById, getUserListBooks } from '../../../redux/actions'; import { AuthContext } from '../../../context/Auth'; import { apiURL } from '../../../utils/constants'; import imageNotFound from '../../../assets/png/imagenotfound.png'; const useStyles = createUseStyles((theme) => ({ tableContainer: { backgroundColor: theme.color.light, padding: 20, }, userImage: { width: 80, height: 80, }, body: { display: 'flex', justifyContent: 'center', alignItems: 'center', } })); const columns = [ { name: "picture", label: "Photo de profil", options: { filter: false, sort: false, customBodyRender: (value) => ( value ? <img src={value} alt='avatar' style={{ width: 90, height: 90, objectFit: 'contain' }} /> : <img src={imageNotFound} alt='avatar' style={{ width: 80, height: 80 }} /> ) }, }, { name: "pseudo", label: "Pseudo", options: { filter: true, sort: true, } }, { name: "email", label: "Mail", options: { filter: true, sort: true, } }, { name: "bio", label: "Bio", options: { filter: false, sort: false, } }, { name: "nbRatings", label: "Nombre d'avis", options: { filter: true, sort: true, } }, { name: 'isBlocked', label: "Statut", options: { filter: true, sort: true, customBodyRender: (value) => ( <Chip label={value ? "Bloqué" : "Autorisé"} color={value ? "secondary" : "primary"} /> ) } }, { name: "uid", options: { display: false } } ]; const Users = ({ ...rest }) => { const theme = useTheme(); const classes = useStyles({ theme }); const { push } = useHistory(); const dispatch = useDispatch(); const { token } = useContext(AuthContext); const allUsers = useSelector((state) => state.allUsers); const redirectTo = async (rowData) => { await dispatch(getUserById(apiURL + `user/getUserById/${rowData[6]}`, token)); await dispatch(getUserListBooks(apiURL + `book/userListBooks/${rowData[6]}`, token)); push({ pathname: ROUTE.USERS_DETAILS, userID: rowData[6] }); } const options = { filterType: 'checkbox', selectableRowsHeader: false, selectableRowsHideCheckboxes: true, selectableRowsOnClick: false, onRowClick: redirectTo, print: false, }; useEffect(() => { dispatch(getAllUsers(apiURL + 'user/getAllUsers', token)) }, []) return ( <Box className={classes.tableContainer} sx={{ minWidth: 1050 }}> <MUIDataTable data={allUsers} columns={columns} options={options} /> </Box> ); }; export default Users;
e-dang/Autogarden
tests/functional/test_watering_station_creation.py
import pytest from django.urls import reverse from garden.utils import build_duration_string from tests.functional.pages.garden_detail_page import GardenDetailPage from .base import Base class TestWateringStationCreation(Base): @pytest.fixture(autouse=True) def setup(self, user_factory, garden_factory, test_password, live_server, use_tmp_static_dir): self.email = '<EMAIL>' self.user = user_factory(email=self.email, password=<PASSWORD>) self.num_watering_stations = 10 self.garden = garden_factory(owner=self.user, watering_stations=self.num_watering_stations, watering_stations__defaults=True) self.url = live_server.url + reverse('garden-detail', kwargs={'pk': self.garden.pk}) self.create_authenticated_session(self.user, live_server) @pytest.mark.django_db def test_user_can_create_watering_station(self): # a logged in user is at the garden detail page self.driver.get(self.url) detail_gpage = GardenDetailPage(self.driver) self.wait_for_page_to_be_loaded(detail_gpage) # they click the add watering station button and see a modal to appear detail_gpage.add_watering_station_button.click() self.wait_for_modal_to_be_visible(detail_gpage.modal_id) # the user then enters invalid information for the new watering station moisture_threshold = -1 watering_duration = -1 detail_gpage.create_watering_station(moisture_threshold=moisture_threshold, watering_duration=watering_duration) # however the user sees errors appear in the form from the invalid inputs self.wait_for_form_error('error_1_id_moisture_threshold') self.wait_for_form_error('error_1_id_watering_duration') # the user then exits out to check if the watering station was added anyway, but finds no extra watering # stations in the table detail_gpage.cancel_button.click() self.wait_for_model_to_disappear(detail_gpage.modal_id) assert detail_gpage.get_number_watering_stations() == self.num_watering_stations # they then click the add watering station button again and try to add valid information. detail_gpage.add_watering_station_button.click() self.wait_for_modal_to_be_visible(detail_gpage.modal_id) moisture_threshold = 1 watering_duration = build_duration_string(minutes=4, seconds=32) plant_type = 'spinach' image = 'test_lettuce_image.png' detail_gpage.enter_form_fields( plant_type=plant_type, moisture_threshold=moisture_threshold, watering_duration=watering_duration, image=image ) self.perform_image_crop(detail_gpage, image) detail_gpage.submit_button.click() # this time it works and the user sees another watering station in the table self.wait_for_model_to_disappear(detail_gpage.modal_id) assert detail_gpage.get_number_watering_stations() == self.num_watering_stations + 1
cyberthinkers/FireDancer3D
firedancer3d_shared/src/main/scala/org/firedancer3d/scenegraph/geometry/Cylinder.scala
package org.firedancer3d.scenegraph.geometry; class Cylinder { }
MilladMuhammadi/Competitive-Programming
UICPC/10/IKE.py
import math from collections import Counter numbers = int(input()) seq = list(map(int, input().split())) MAXN = max(seq)+1 spf = [0 for i in range(MAXN)] def sieve(): spf[1] = 1 for i in range(2, MAXN): spf[i] = i for i in range(4, MAXN, 2): spf[i] = 2 for i in range(3, math.ceil(math.sqrt(MAXN))): if (spf[i] == i): for j in range(i * i, MAXN, i): if (spf[j] == j): spf[j] = i def getFactorization(x): ret = list() while (x != 1): ret.append(spf[x]) x = x // spf[x] return ret def CountFrequency(my_list): freq = {} for item in my_list: if (item in freq): freq[item] += 1 else: freq[item] = 1 return freq sieve() #print(spf) p = [] for i in range(numbers): p.append(CountFrequency(getFactorization(seq[i]))) #print(p[i]) count = Counter() for y in p: count += Counter(y) #print(count) validlist = [] thenum=1 for i in count.items(): if i[1]>=numbers: j = list(i) j[1]=j[1]//numbers thenum*=(j[0]**j[1]) validlist.append(j) print(thenum, end=" ") #print(validlist) steps = 0 for i in validlist: pri = i[0] con = i[1] for j in p: #print("this is j: ",j) #print("this is pri: ",pri) if pri in j: #print("true") dif = con - j[pri] #print(con) #print(dif) if dif > 0: steps+=(dif) else: steps+=con print(steps)
nydevel/qirk
qirk-parent/qirk-main-parent/qirk-repo/src/main/java/org/wrkr/clb/repo/JDBCIdEntityRepo.java
<reponame>nydevel/qirk package org.wrkr.clb.repo; import java.util.List; import org.springframework.jdbc.support.KeyHolder; import org.springframework.stereotype.Repository; import org.wrkr.clb.model.BaseIdEntity; import org.wrkr.clb.model.BaseIdEntityMeta; @Repository public abstract class JDBCIdEntityRepo extends JDBCBaseMainRepo { protected <E extends BaseIdEntity> Long[] buildIdsArray(List<E> entities) { Long[] result = new Long[entities.size()]; for (int i = 0; i < entities.size(); i++) { result[i] = entities.get(i).getId(); } return result; } protected <E extends BaseIdEntity> E setIdAfterSave(E entity, KeyHolder keyHolder) { entity.setId((Long) keyHolder.getKeys().get(BaseIdEntityMeta.id)); return entity; } }
thechurchofcage/Complete-Fire-Red-Upgrade
src/frontier.h
#pragma once #include "defines.h" #define TOTAL_SPREADS 0x4A0 //sizeof(gFrontierSpreads) / sizeof(struct BattleTowerSpreads) #define NUM_MALE_NAMES 0xAA //sizeof(MaleFrontierNamesTable) / sizeof(u8*) #define NUM_FEMALE_NAMES 0xAA //sizeof(FemaleFrontierNamesTable) / sizeof(u8*) #define species_array ((species_t*) 0x203DA00) #define item_array ((item_t*) 0x203DA10) enum { FRONTIER_BEFORE_TEXT, FRONTIER_PLAYER_LOST_TEXT, FRONTIER_PLAYER_WON_TEXT, }; struct BattleTowerTrainer { u16 owNum; u8 trainerClass; u8 trainerSprite; u8 gender; u8* preBattleText; u8* playerWinText; u8* playerLoseText; }; extern const struct BattleTowerTrainer gTowerTrainers[]; struct BattleTowerSpreads { u16 species; u8 nature; u8 hpIv; u8 atkIv; u8 defIv; u8 spdIv; u8 spAtkIv; u8 spDefIv; u8 hpEv; u8 atkEv; u8 defEv; u8 spdEv; u8 spAtkEv; u8 spDefEv; u8 ability; u16 item; u16 moves[4]; u8 ball; u8 _1; // 0x00 u32 _2; // 0x00000000 }; extern const struct BattleTowerSpreads gFrontierSpreads[]; #define gFrontierSpreads ((const struct BattleTowerSpreads*) 0x89DFA00) enum BattleTowerBattleTypes { BATTLE_TOWER_SINGLE, BATTLE_TOWER_DOUBLE, BATTLE_TOWER_MULTI, BATTLE_TOWER_LINK_MULTI, }; enum BattleTowerFormats { BATTLE_TOWER_STANDARD, BATTLE_TOWER_FREE_FOR_ALL, BATTLE_TOWER_OU, BATTLE_TOWER_UBER, BATTLE_TOWER_LITTLE_CUP, BATTLE_TOWER_MIDDLE_CUP, }; enum BattleTowerPartySizes { BATTLE_TOWER_SIZE_STANDARD, BATTLE_TOWER_SIZE_1V1, BATTLE_TOWER_SIZE_2V2, BATTLE_TOWER_SIZE_3V3, BATTLE_TOWER_SIZE_4V4, BATTLE_TOWER_SIZE_5V5, BATTLE_TOWER_SIZE_6V6, }; enum BattleTowerGenders { BATTLE_TOWER_MALE, BATTLE_TOWER_FEMALE }; enum TierBanCheckingType { CHECK_BATTLE_TOWER_SPREADS, CHECK_PARTY_OFFSET, }; extern species_t StandardSpeciesBanList[]; extern species_t OU_SpeciesBanList[]; extern species_t LittleCup_SpeciesList[]; extern ability_t OU_AbilityBanList[]; extern item_t StandardItemBanList[]; extern item_t OU_ItemBanList[]; extern move_t SmogonMoveBanList[]; extern move_t LittleCup_MoveBanList[];
leon9reat/decoding-android
Submission3/app/src/main/java/com/medialink/submission3/model/tv/TvDetailRespon.java
package com.medialink.submission3.model.tv; import com.google.gson.annotations.SerializedName; import java.util.List; public class TvDetailRespon{ @SerializedName("original_language") private String originalLanguage; @SerializedName("number_of_episodes") private int numberOfEpisodes; @SerializedName("networks") private List<NetworksItem> networks; @SerializedName("type") private String type; @SerializedName("backdrop_path") private String backdropPath; @SerializedName("genres") private List<GenresItem> genres; @SerializedName("popularity") private double popularity; @SerializedName("id") private int id; @SerializedName("number_of_seasons") private int numberOfSeasons; @SerializedName("vote_count") private int voteCount; @SerializedName("first_air_date") private String firstAirDate; @SerializedName("overview") private String overview; @SerializedName("seasons") private List<SeasonsItem> seasons; @SerializedName("languages") private List<String> languages; @SerializedName("created_by") private List<CreatedByItem> createdBy; @SerializedName("last_episode_to_air") private LastEpisodeToAir lastEpisodeToAir; @SerializedName("poster_path") private String posterPath; @SerializedName("origin_country") private List<String> originCountry; @SerializedName("production_companies") private List<ProductionCompaniesItem> productionCompanies; @SerializedName("original_name") private String originalName; @SerializedName("vote_average") private double voteAverage; @SerializedName("name") private String name; @SerializedName("episode_run_time") private List<Integer> episodeRunTime; @SerializedName("next_episode_to_air") private Object nextEpisodeToAir; @SerializedName("in_production") private boolean inProduction; @SerializedName("last_air_date") private String lastAirDate; @SerializedName("homepage") private String homepage; @SerializedName("status") private String status; public void setOriginalLanguage(String originalLanguage){ this.originalLanguage = originalLanguage; } public String getOriginalLanguage(){ return originalLanguage; } public void setNumberOfEpisodes(int numberOfEpisodes){ this.numberOfEpisodes = numberOfEpisodes; } public int getNumberOfEpisodes(){ return numberOfEpisodes; } public void setNetworks(List<NetworksItem> networks){ this.networks = networks; } public List<NetworksItem> getNetworks(){ return networks; } public void setType(String type){ this.type = type; } public String getType(){ return type; } public void setBackdropPath(String backdropPath){ this.backdropPath = backdropPath; } public String getBackdropPath(){ return backdropPath; } public void setGenres(List<GenresItem> genres){ this.genres = genres; } public List<GenresItem> getGenres(){ return genres; } public void setPopularity(double popularity){ this.popularity = popularity; } public double getPopularity(){ return popularity; } public void setId(int id){ this.id = id; } public int getId(){ return id; } public void setNumberOfSeasons(int numberOfSeasons){ this.numberOfSeasons = numberOfSeasons; } public int getNumberOfSeasons(){ return numberOfSeasons; } public void setVoteCount(int voteCount){ this.voteCount = voteCount; } public int getVoteCount(){ return voteCount; } public void setFirstAirDate(String firstAirDate){ this.firstAirDate = firstAirDate; } public String getFirstAirDate(){ return firstAirDate; } public void setOverview(String overview){ this.overview = overview; } public String getOverview(){ return overview; } public void setSeasons(List<SeasonsItem> seasons){ this.seasons = seasons; } public List<SeasonsItem> getSeasons(){ return seasons; } public void setLanguages(List<String> languages){ this.languages = languages; } public List<String> getLanguages(){ return languages; } public void setCreatedBy(List<CreatedByItem> createdBy){ this.createdBy = createdBy; } public List<CreatedByItem> getCreatedBy(){ return createdBy; } public void setLastEpisodeToAir(LastEpisodeToAir lastEpisodeToAir){ this.lastEpisodeToAir = lastEpisodeToAir; } public LastEpisodeToAir getLastEpisodeToAir(){ return lastEpisodeToAir; } public void setPosterPath(String posterPath){ this.posterPath = posterPath; } public String getPosterPath(){ return posterPath; } public void setOriginCountry(List<String> originCountry){ this.originCountry = originCountry; } public List<String> getOriginCountry(){ return originCountry; } public void setProductionCompanies(List<ProductionCompaniesItem> productionCompanies){ this.productionCompanies = productionCompanies; } public List<ProductionCompaniesItem> getProductionCompanies(){ return productionCompanies; } public void setOriginalName(String originalName){ this.originalName = originalName; } public String getOriginalName(){ return originalName; } public void setVoteAverage(double voteAverage){ this.voteAverage = voteAverage; } public double getVoteAverage(){ return voteAverage; } public void setName(String name){ this.name = name; } public String getName(){ return name; } public void setEpisodeRunTime(List<Integer> episodeRunTime){ this.episodeRunTime = episodeRunTime; } public List<Integer> getEpisodeRunTime(){ return episodeRunTime; } public void setNextEpisodeToAir(Object nextEpisodeToAir){ this.nextEpisodeToAir = nextEpisodeToAir; } public Object getNextEpisodeToAir(){ return nextEpisodeToAir; } public void setInProduction(boolean inProduction){ this.inProduction = inProduction; } public boolean isInProduction(){ return inProduction; } public void setLastAirDate(String lastAirDate){ this.lastAirDate = lastAirDate; } public String getLastAirDate(){ return lastAirDate; } public void setHomepage(String homepage){ this.homepage = homepage; } public String getHomepage(){ return homepage; } public void setStatus(String status){ this.status = status; } public String getStatus(){ return status; } }
hydthd/games
doudizhu/src/AI/PassiveAI.js
<reponame>hydthd/games<gh_stars>1000+ class PassiveAI { callPoint(args) { return 1; } play(args) { return [args.myCards[0]]; } cover(args) { return []; } } module.exports = PassiveAI;
jmchilton/peptide-shaker
src/main/java/eu/isas/peptideshaker/utils/StarHider.java
package eu.isas.peptideshaker.utils; import com.compomics.util.experiment.biology.Peptide; import com.compomics.util.experiment.identification.Identification; import com.compomics.util.experiment.identification.SequenceFactory; import com.compomics.util.experiment.identification.matches.PeptideMatch; import com.compomics.util.experiment.identification.matches.ProteinMatch; import com.compomics.util.experiment.identification.matches.SpectrumMatch; import com.compomics.util.experiment.massspectrometry.Precursor; import com.compomics.util.experiment.massspectrometry.Spectrum; import com.compomics.util.gui.waiting.waitinghandlers.ProgressDialogX; import eu.isas.peptideshaker.filtering.MatchFilter; import eu.isas.peptideshaker.filtering.PeptideFilter; import eu.isas.peptideshaker.filtering.ProteinFilter; import eu.isas.peptideshaker.filtering.PsmFilter; import eu.isas.peptideshaker.gui.PeptideShakerGUI; import eu.isas.peptideshaker.gui.tabpanels.PtmPanel; import eu.isas.peptideshaker.myparameters.PSParameter; import eu.isas.peptideshaker.preferences.FilterPreferences; import java.awt.Toolkit; import javax.swing.RowFilter.ComparisonType; /** * This class provides information whether a hit should be hidden or starred. * * @author <NAME> * @author <NAME> */ public class StarHider { /** * PeptideShakerGUI instance. */ private PeptideShakerGUI peptideShakerGUI; /** * The sequence factory. */ private SequenceFactory sequenceFactory = SequenceFactory.getInstance(); /** * The progress dialog. */ private ProgressDialogX progressDialog; /** * Constructor. * * @param peptideShakerGUI the peptideShakerGUI main class */ public StarHider(PeptideShakerGUI peptideShakerGUI) { this.peptideShakerGUI = peptideShakerGUI; } /** * Updates the star/hide status of all identification items. */ public void starHide() { progressDialog = new ProgressDialogX(peptideShakerGUI, Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker.gif")), Toolkit.getDefaultToolkit().getImage(getClass().getResource("/icons/peptide-shaker-orange.gif")), true); progressDialog.setIndeterminate(true); progressDialog.setTitle("Hiding/Starring Items. Please Wait..."); new Thread(new Runnable() { public void run() { try { progressDialog.setVisible(true); } catch (IndexOutOfBoundsException e) { // ignore } } }, "ProgressDialog").start(); new Thread("Star/Hide") { @Override public void run() { try { Identification identification = peptideShakerGUI.getIdentification(); progressDialog.setIndeterminate(false); progressDialog.setMaxProgressValue(identification.getProteinIdentification().size()); PSParameter psParameter = new PSParameter(); for (String proteinKey : identification.getProteinIdentification()) { if (progressDialog.isRunCanceled()) { break; } ProteinMatch proteinMatch = identification.getProteinMatch(proteinKey); boolean peptideSurvived = false; for (String peptideKey : proteinMatch.getPeptideMatches()) { if (progressDialog.isRunCanceled()) { break; } PeptideMatch peptideMatch = identification.getPeptideMatch(peptideKey); boolean psmSurvived = false; for (String spectrumKey : peptideMatch.getSpectrumMatches()) { if (progressDialog.isRunCanceled()) { break; } psParameter = (PSParameter) identification.getSpectrumMatchParameter(spectrumKey, psParameter); if (isPsmHidden(spectrumKey)) { psParameter.setHidden(true); } else { psParameter.setHidden(false); psmSurvived = true; } psParameter.setStarred(isPsmStarred(spectrumKey)); identification.updateSpectrumMatchParameter(spectrumKey, psParameter); } psParameter = (PSParameter) identification.getPeptideMatchParameter(peptideKey, psParameter); if (!psmSurvived) { psParameter.setHidden(true); } else if (isPeptideHidden(peptideKey)) { psParameter.setHidden(true); } else { psParameter.setHidden(false); peptideSurvived = true; } psParameter.setStarred(isPeptideStarred(peptideKey)); identification.updatePeptideMatchParameter(peptideKey, psParameter); } psParameter = (PSParameter) identification.getProteinMatchParameter(proteinKey, psParameter); if (!peptideSurvived) { psParameter.setHidden(true); } else { psParameter.setHidden(isProteinHidden(proteinKey)); } psParameter.setStarred(isProteinStarred(proteinKey)); identification.updateProteinMatchParameter(proteinKey, psParameter); progressDialog.increaseProgressValue(); } progressDialog.setRunFinished(); } catch (Exception e) { peptideShakerGUI.catchException(e); } } }.start(); } /** * Stars a protein match. * * @param match the key of the match */ public void starProtein(String match) { try { Identification identification = peptideShakerGUI.getIdentification(); FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); PSParameter psParameter = new PSParameter(); psParameter = (PSParameter) identification.getProteinMatchParameter(match, psParameter); boolean validated = false; for (ProteinFilter matchFilter : filterPreferences.getProteinStarFilters().values()) { if (matchFilter.getExceptions().contains(match)) { matchFilter.removeException(match); } if (isValidated(match, matchFilter)) { validated = true; } } if (!validated) { ProteinFilter proteinFilter; if (!filterPreferences.getProteinStarFilters().containsKey(MatchFilter.MANUAL_SELECTION)) { proteinFilter = new ProteinFilter(MatchFilter.MANUAL_SELECTION); proteinFilter.setDescription("Manual selection via the graphical interface"); filterPreferences.getProteinStarFilters().put(proteinFilter.getName(), proteinFilter); } else { proteinFilter = filterPreferences.getProteinStarFilters().get(MatchFilter.MANUAL_SELECTION); } proteinFilter.addManualValidation(match); } psParameter.setStarred(true); identification.updateProteinMatchParameter(match, psParameter); peptideShakerGUI.setDataSaved(false); } catch (Exception e) { peptideShakerGUI.catchException(e); } } /** * Unstars a protein match. * * @param match the key of the match */ public void unStarProtein(String match) { try { Identification identification = peptideShakerGUI.getIdentification(); FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); PSParameter psParameter = new PSParameter(); psParameter = (PSParameter) identification.getProteinMatchParameter(match, psParameter); for (ProteinFilter matchFilter : filterPreferences.getProteinStarFilters().values()) { if (matchFilter.getManualValidation().contains(match)) { matchFilter.removeManualValidation(match); } if (isValidated(match, matchFilter)) { matchFilter.addException(match); } } psParameter.setStarred(false); identification.updateProteinMatchParameter(match, psParameter); peptideShakerGUI.setDataSaved(false); } catch (Exception e) { peptideShakerGUI.catchException(e); } } /** * Hides a protein match. * * @param match the key of the match */ public void hideProtein(String match) { try { Identification identification = peptideShakerGUI.getIdentification(); FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); PSParameter psParameter = new PSParameter(); psParameter = (PSParameter) identification.getProteinMatchParameter(match, psParameter); boolean validated = false; for (ProteinFilter matchFilter : filterPreferences.getProteinHideFilters().values()) { if (matchFilter.getExceptions().contains(match)) { matchFilter.removeException(match); } if (isValidated(match, matchFilter)) { validated = true; } } if (!validated) { ProteinFilter proteinFilter; if (!filterPreferences.getProteinHideFilters().containsKey(MatchFilter.MANUAL_SELECTION)) { proteinFilter = new ProteinFilter(MatchFilter.MANUAL_SELECTION); proteinFilter.setDescription("Manual selection via the graphical interface"); filterPreferences.getProteinHideFilters().put(proteinFilter.getName(), proteinFilter); } else { proteinFilter = filterPreferences.getProteinHideFilters().get(MatchFilter.MANUAL_SELECTION); } proteinFilter.addManualValidation(match); } psParameter.setHidden(true); identification.updateProteinMatchParameter(match, psParameter); peptideShakerGUI.setDataSaved(false); } catch (Exception e) { peptideShakerGUI.catchException(e); } } /** * Unhides a protein match. * * @param match the key of the match */ public void unHideProtein(String match) { try { Identification identification = peptideShakerGUI.getIdentification(); FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); PSParameter psParameter = new PSParameter(); psParameter = (PSParameter) identification.getProteinMatchParameter(match, psParameter); for (ProteinFilter matchFilter : filterPreferences.getProteinHideFilters().values()) { if (matchFilter.getManualValidation().contains(match)) { matchFilter.removeManualValidation(match); } if (isValidated(match, matchFilter)) { matchFilter.addException(match); } } psParameter.setHidden(true); identification.updateProteinMatchParameter(match, psParameter); peptideShakerGUI.setDataSaved(false); } catch (Exception e) { peptideShakerGUI.catchException(e); } } /** * Stars a peptide match. * * @param match the key of the match */ public void starPeptide(String match) { try { Identification identification = peptideShakerGUI.getIdentification(); FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); PSParameter psParameter = new PSParameter(); psParameter = (PSParameter) identification.getPeptideMatchParameter(match, psParameter); boolean validated = false; for (PeptideFilter matchFilter : filterPreferences.getPeptideStarFilters().values()) { if (matchFilter.getExceptions().contains(match)) { matchFilter.removeException(match); } if (isValidated(match, matchFilter)) { validated = true; } } if (!validated) { PeptideFilter peptideFilter; if (!filterPreferences.getPeptideStarFilters().containsKey(MatchFilter.MANUAL_SELECTION)) { peptideFilter = new PeptideFilter(MatchFilter.MANUAL_SELECTION, peptideShakerGUI.getFoundModifications()); peptideFilter.setDescription("Manual selection via the graphical interface"); filterPreferences.getPeptideStarFilters().put(peptideFilter.getName(), peptideFilter); } else { peptideFilter = filterPreferences.getPeptideStarFilters().get(MatchFilter.MANUAL_SELECTION); } peptideFilter.addManualValidation(match); } psParameter.setStarred(true); identification.updatePeptideMatchParameter(match, psParameter); peptideShakerGUI.setDataSaved(false); } catch (Exception e) { peptideShakerGUI.catchException(e); } } /** * Unstars a peptide match. * * @param match the key of the match */ public void unStarPeptide(String match) { try { Identification identification = peptideShakerGUI.getIdentification(); FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); PSParameter psParameter = new PSParameter(); psParameter = (PSParameter) identification.getPeptideMatchParameter(match, psParameter); for (PeptideFilter matchFilter : filterPreferences.getPeptideStarFilters().values()) { if (matchFilter.getManualValidation().contains(match)) { matchFilter.removeManualValidation(match); } if (isValidated(match, matchFilter)) { matchFilter.addException(match); } } psParameter.setStarred(false); identification.updatePeptideMatchParameter(match, psParameter); peptideShakerGUI.setDataSaved(false); } catch (Exception e) { peptideShakerGUI.catchException(e); } } /** * Hides a peptide match. * * @param match the key of the match */ public void hidePeptide(String match) { try { Identification identification = peptideShakerGUI.getIdentification(); FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); PSParameter psParameter = new PSParameter(); psParameter = (PSParameter) identification.getPeptideMatchParameter(match, psParameter); boolean validated = false; for (PeptideFilter matchFilter : filterPreferences.getPeptideHideFilters().values()) { if (matchFilter.getExceptions().contains(match)) { matchFilter.removeException(match); } if (isValidated(match, matchFilter)) { validated = true; } } if (!validated) { PeptideFilter peptideFilter; if (!filterPreferences.getPeptideHideFilters().containsKey(MatchFilter.MANUAL_SELECTION)) { peptideFilter = new PeptideFilter(MatchFilter.MANUAL_SELECTION, peptideShakerGUI.getFoundModifications()); peptideFilter.setDescription("Manual selection via the graphical interface"); filterPreferences.getPeptideHideFilters().put(peptideFilter.getName(), peptideFilter); } else { peptideFilter = filterPreferences.getPeptideHideFilters().get(MatchFilter.MANUAL_SELECTION); } peptideFilter.addManualValidation(match); } psParameter.setHidden(true); identification.updatePeptideMatchParameter(match, psParameter); peptideShakerGUI.setDataSaved(false); } catch (Exception e) { peptideShakerGUI.catchException(e); } } /** * Unhides a peptide match. * * @param match the key of the match */ public void unHidePeptide(String match) { try { Identification identification = peptideShakerGUI.getIdentification(); FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); PSParameter psParameter = new PSParameter(); psParameter = (PSParameter) identification.getPeptideMatchParameter(match, psParameter); for (PeptideFilter matchFilter : filterPreferences.getPeptideHideFilters().values()) { if (matchFilter.getManualValidation().contains(match)) { matchFilter.removeManualValidation(match); } if (isValidated(match, matchFilter)) { matchFilter.addException(match); } } psParameter.setHidden(false); identification.updatePeptideMatchParameter(match, psParameter); peptideShakerGUI.setDataSaved(false); } catch (Exception e) { peptideShakerGUI.catchException(e); } } /** * Stars a PSM match. * * @param match the key of the match */ public void starPsm(String match) { try { Identification identification = peptideShakerGUI.getIdentification(); FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); PSParameter psParameter = new PSParameter(); psParameter = (PSParameter) identification.getSpectrumMatchParameter(match, psParameter); boolean validated = false; if (!validated) { for (PsmFilter matchFilter : filterPreferences.getPsmStarFilters().values()) { if (matchFilter.getExceptions().contains(match)) { matchFilter.removeException(match); } if (isValidated(match, matchFilter)) { validated = true; } } PsmFilter psmFilter; if (!filterPreferences.getPsmStarFilters().containsKey(MatchFilter.MANUAL_SELECTION)) { psmFilter = new PsmFilter(MatchFilter.MANUAL_SELECTION, peptideShakerGUI.getMetrics().getFoundCharges(), peptideShakerGUI.getSearchParameters().getSpectrumFiles()); psmFilter.setDescription("Manual selection via the graphical interface"); filterPreferences.getPsmStarFilters().put(psmFilter.getName(), psmFilter); } else { psmFilter = filterPreferences.getPsmStarFilters().get(MatchFilter.MANUAL_SELECTION); } psmFilter.addManualValidation(match); } psParameter.setStarred(true); identification.updateSpectrumMatchParameter(match, psParameter); peptideShakerGUI.setDataSaved(false); } catch (Exception e) { peptideShakerGUI.catchException(e); } } /** * Unstars a PSM match. * * @param match the key of the match */ public void unStarPsm(String match) { try { Identification identification = peptideShakerGUI.getIdentification(); FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); PSParameter psParameter = new PSParameter(); psParameter = (PSParameter) identification.getSpectrumMatchParameter(match, psParameter); for (PsmFilter matchFilter : filterPreferences.getPsmStarFilters().values()) { if (matchFilter.getManualValidation().contains(match)) { matchFilter.removeManualValidation(match); } if (isValidated(match, matchFilter)) { matchFilter.addException(match); } } psParameter.setStarred(false); identification.updateSpectrumMatchParameter(match, psParameter); peptideShakerGUI.setDataSaved(false); } catch (Exception e) { peptideShakerGUI.catchException(e); } } /** * Hides a PSM match. * * @param match the key of the match */ public void hidePsm(String match) { try { Identification identification = peptideShakerGUI.getIdentification(); FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); PSParameter psParameter = new PSParameter(); psParameter = (PSParameter) identification.getSpectrumMatchParameter(match, psParameter); boolean validated = false; if (!validated) { for (PsmFilter matchFilter : filterPreferences.getPsmHideFilters().values()) { if (matchFilter.getExceptions().contains(match)) { matchFilter.removeException(match); } if (isValidated(match, matchFilter)) { validated = true; } } PsmFilter psmFilter; if (!filterPreferences.getPsmHideFilters().containsKey(MatchFilter.MANUAL_SELECTION)) { psmFilter = new PsmFilter(MatchFilter.MANUAL_SELECTION, peptideShakerGUI.getMetrics().getFoundCharges(), peptideShakerGUI.getSearchParameters().getSpectrumFiles()); psmFilter.setDescription("Manual selection via the graphical interface"); filterPreferences.getPsmHideFilters().put(psmFilter.getName(), psmFilter); } else { psmFilter = filterPreferences.getPsmHideFilters().get(MatchFilter.MANUAL_SELECTION); } psmFilter.addManualValidation(match); } psParameter.setHidden(true); identification.updateSpectrumMatchParameter(match, psParameter); peptideShakerGUI.setDataSaved(false); } catch (Exception e) { peptideShakerGUI.catchException(e); } } /** * Unhides a psm match. * * @param match the key of the match */ public void unHidePsm(String match) { try { Identification identification = peptideShakerGUI.getIdentification(); FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); PSParameter psParameter = new PSParameter(); psParameter = (PSParameter) identification.getSpectrumMatchParameter(match, psParameter); for (PsmFilter matchFilter : filterPreferences.getPsmHideFilters().values()) { if (matchFilter.getManualValidation().contains(match)) { matchFilter.removeManualValidation(match); } if (isValidated(match, matchFilter)) { matchFilter.addException(match); } } psParameter.setHidden(false); identification.updateSpectrumMatchParameter(match, psParameter); peptideShakerGUI.setDataSaved(false); } catch (Exception e) { peptideShakerGUI.catchException(e); } } /** * Tests whether a protein match should be hidden according to the * implemented filters. * * @param match the key of the match * @return a boolean indicating whether a protein match should be hidden * according to the implemented filters */ public boolean isProteinHidden(String match) { FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); for (ProteinFilter matchFilter : filterPreferences.getProteinHideFilters().values()) { if (matchFilter.isActive() && isValidated(match, matchFilter)) { return true; } } return false; } /** * Tests whether a peptide match should be hidden according to the * implemented filters. * * @param match the key of the match * @return a boolean indicating whether a protein match should be hidden * according to the implemented filters */ public boolean isPeptideHidden(String match) { FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); for (PeptideFilter matchFilter : filterPreferences.getPeptideHideFilters().values()) { if (matchFilter.isActive() && isValidated(match, matchFilter)) { return true; } } return false; } /** * Tests whether a psm match should be hidden according to the implemented * filters. * * @param match the key of the match * @return a boolean indicating whether a protein match should be hidden * according to the implemented filters */ public boolean isPsmHidden(String match) { FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); for (PsmFilter matchFilter : filterPreferences.getPsmHideFilters().values()) { if (matchFilter.isActive() && isValidated(match, matchFilter)) { return true; } } return false; } /** * Tests whether a protein match should be starred according to the * implemented filters. * * @param match the key of the match * @return a boolean indicating whether a protein match should be hidden * according to the implemented filters */ public boolean isProteinStarred(String match) { FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); for (ProteinFilter matchFilter : filterPreferences.getProteinStarFilters().values()) { if (matchFilter.isActive() && isValidated(match, matchFilter)) { return true; } } return false; } /** * Tests whether a peptide match should be starred according to the * implemented filters. * * @param match the key of the match * @return a boolean indicating whether a protein match should be hidden * according to the implemented filters */ public boolean isPeptideStarred(String match) { FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); for (PeptideFilter matchFilter : filterPreferences.getPeptideStarFilters().values()) { if (matchFilter.isActive() && isValidated(match, matchFilter)) { return true; } } return false; } /** * Tests whether a PSM match should be starred according to the implemented * filters. * * @param match the key of the match * @return a boolean indicating whether a protein match should be hidden * according to the implemented filters */ public boolean isPsmStarred(String match) { FilterPreferences filterPreferences = peptideShakerGUI.getFilterPreferences(); for (PsmFilter matchFilter : filterPreferences.getPsmStarFilters().values()) { if (matchFilter.isActive() && isValidated(match, matchFilter)) { return true; } } return false; } /** * Tests whether a protein match is validated by a given filter. * * @param proteinKey the key of the protein match * @param proteinFilter the filter * @return a boolean indicating whether a protein match is validated by a * given filter */ public boolean isValidated(String proteinKey, ProteinFilter proteinFilter) { try { if (proteinFilter.getExceptions().contains(proteinKey)) { return false; } if (proteinFilter.getManualValidation().size() > 0) { if (proteinFilter.getManualValidation().contains(proteinKey)) { return true; } else { return false; } } if (proteinFilter.getIdentifierRegex() != null) { String test = "test_" + proteinKey + "_test"; if (test.split(proteinFilter.getIdentifierRegex()).length == 1) { boolean found = false; for (String accession : ProteinMatch.getAccessions(proteinKey)) { test = "test_" + sequenceFactory.getHeader(accession).getDescription().toLowerCase() + "_test"; if (test.split(proteinFilter.getIdentifierRegex().toLowerCase()).length > 1) { found = true; break; } } if (!found) { return false; } } } PSParameter psParameter = new PSParameter(); Identification identification = peptideShakerGUI.getIdentification(); psParameter = (PSParameter) identification.getProteinMatchParameter(proteinKey, psParameter); if (proteinFilter.getPi() != 5) { if (proteinFilter.getPiComparison() == ComparisonType.NOT_EQUAL && psParameter.getGroupClass() == proteinFilter.getPi()) { return false; } else if (proteinFilter.getPiComparison() == ComparisonType.EQUAL && psParameter.getGroupClass() != proteinFilter.getPi()) { return false; } } if (proteinFilter.getProteinScore() != null) { if (proteinFilter.getProteinScoreComparison() == ComparisonType.AFTER) { if (psParameter.getProteinScore() <= proteinFilter.getProteinScore()) { return false; } } else if (proteinFilter.getProteinScoreComparison() == ComparisonType.BEFORE) { if (psParameter.getProteinScore() >= proteinFilter.getProteinScore()) { return false; } } else if (proteinFilter.getProteinScoreComparison() == ComparisonType.EQUAL) { if (psParameter.getProteinScore() != proteinFilter.getProteinScore()) { return false; } } else if (proteinFilter.getProteinScoreComparison() == ComparisonType.NOT_EQUAL) { if (psParameter.getProteinScore() == proteinFilter.getProteinScore()) { return false; } } } if (proteinFilter.getProteinConfidence() != null) { if (proteinFilter.getProteinConfidenceComparison() == ComparisonType.AFTER) { if (psParameter.getProteinConfidence() <= proteinFilter.getProteinConfidence()) { return false; } } else if (proteinFilter.getProteinConfidenceComparison() == ComparisonType.BEFORE) { if (psParameter.getProteinConfidence() >= proteinFilter.getProteinConfidence()) { return false; } } else if (proteinFilter.getProteinConfidenceComparison() == ComparisonType.EQUAL) { if (psParameter.getProteinConfidence() != proteinFilter.getProteinConfidence()) { return false; } } else if (proteinFilter.getProteinConfidenceComparison() == ComparisonType.NOT_EQUAL) { if (psParameter.getProteinConfidence() == proteinFilter.getProteinConfidence()) { return false; } } } if (proteinFilter.getnPeptides() != null || proteinFilter.getProteinNSpectra() != null || proteinFilter.getProteinCoverage() != null || proteinFilter.getSpectrumCounting() != null) { ProteinMatch proteinMatch = identification.getProteinMatch(proteinKey); if (proteinFilter.getnPeptides() != null) { if (proteinFilter.getnPeptidesComparison() == ComparisonType.AFTER) { if (proteinMatch.getPeptideMatches().size() <= proteinFilter.getnPeptides()) { return false; } } else if (proteinFilter.getnPeptidesComparison() == ComparisonType.BEFORE) { if (proteinMatch.getPeptideMatches().size() >= proteinFilter.getnPeptides()) { return false; } } else if (proteinFilter.getnPeptidesComparison() == ComparisonType.EQUAL) { if (proteinMatch.getPeptideMatches().size() != proteinFilter.getnPeptides()) { return false; } } else if (proteinFilter.getnPeptidesComparison() == ComparisonType.NOT_EQUAL) { if (proteinMatch.getPeptideMatches().size() == proteinFilter.getnPeptides()) { return false; } } } IdentificationFeaturesGenerator identificationFeaturesGenerator = peptideShakerGUI.getIdentificationFeaturesGenerator(); if (proteinFilter.getProteinNSpectra() != null) { if (proteinFilter.getnSpectraComparison() == ComparisonType.AFTER) { if (identificationFeaturesGenerator.getNSpectra(proteinKey) <= proteinFilter.getProteinNSpectra()) { return false; } } else if (proteinFilter.getnSpectraComparison() == ComparisonType.BEFORE) { if (identificationFeaturesGenerator.getNSpectra(proteinKey) >= proteinFilter.getProteinNSpectra()) { return false; } } else if (proteinFilter.getnSpectraComparison() == ComparisonType.EQUAL) { if (identificationFeaturesGenerator.getNSpectra(proteinKey) != proteinFilter.getProteinNSpectra()) { return false; } } else if (proteinFilter.getnSpectraComparison() == ComparisonType.NOT_EQUAL) { if (identificationFeaturesGenerator.getNSpectra(proteinKey) == proteinFilter.getProteinNSpectra()) { return false; } } } if (proteinFilter.getProteinCoverage() != null) { double sequenceCoverage = 100 * identificationFeaturesGenerator.getSequenceCoverage(proteinKey); if (proteinFilter.getProteinCoverageComparison() == ComparisonType.AFTER) { if (sequenceCoverage <= proteinFilter.getProteinCoverage()) { return false; } } else if (proteinFilter.getProteinCoverageComparison() == ComparisonType.BEFORE) { if (sequenceCoverage >= proteinFilter.getProteinCoverage()) { return false; } } else if (proteinFilter.getProteinCoverageComparison() == ComparisonType.EQUAL) { if (sequenceCoverage != proteinFilter.getProteinCoverage()) { return false; } } else if (proteinFilter.getProteinCoverageComparison() == ComparisonType.NOT_EQUAL) { if (sequenceCoverage == proteinFilter.getProteinCoverage()) { return false; } } } if (proteinFilter.getSpectrumCounting() != null) { double spectrumCounting = identificationFeaturesGenerator.getSpectrumCounting(proteinKey); if (proteinFilter.getSpectrumCountingComparison() == ComparisonType.AFTER) { if (spectrumCounting <= proteinFilter.getSpectrumCounting()) { return false; } } else if (proteinFilter.getSpectrumCountingComparison() == ComparisonType.BEFORE) { if (spectrumCounting >= proteinFilter.getSpectrumCounting()) { return false; } } else if (proteinFilter.getSpectrumCountingComparison() == ComparisonType.EQUAL) { if (spectrumCounting != proteinFilter.getSpectrumCounting()) { return false; } } else if (proteinFilter.getSpectrumCountingComparison() == ComparisonType.NOT_EQUAL) { if (spectrumCounting == proteinFilter.getSpectrumCounting()) { return false; } } } } return true; } catch (Exception e) { e.printStackTrace(); peptideShakerGUI.catchException(e); return false; } } /** * Tests whether a peptide match is validated by a given filter. * * @param peptideKey the key of the peptide match * @param peptideFilter the filter * @return a boolean indicating whether a peptide match is validated by a * given filter */ public boolean isValidated(String peptideKey, PeptideFilter peptideFilter) { try { if (peptideFilter.getExceptions().contains(peptideKey)) { return false; } if (peptideFilter.getManualValidation().size() > 0) { if (peptideFilter.getManualValidation().contains(peptideKey)) { return true; } else { return false; } } PSParameter psParameter = new PSParameter(); boolean found = false; for (String ptm : peptideFilter.getModificationStatus()) { if (ptm.equals(PtmPanel.NO_MODIFICATION)) { if (!Peptide.isModified(peptideKey)) { found = true; break; } } else { if (Peptide.isModified(peptideKey, ptm)) { found = true; break; } } } if (!found) { return false; } Identification identification = peptideShakerGUI.getIdentification(); psParameter = (PSParameter) identification.getPeptideMatchParameter(peptideKey, psParameter); if (peptideFilter.getPi() != 5) { if (peptideFilter.getPiComparison() == ComparisonType.NOT_EQUAL && psParameter.getGroupClass() == peptideFilter.getPi()) { return false; } else if (peptideFilter.getPiComparison() == ComparisonType.EQUAL && psParameter.getGroupClass() != peptideFilter.getPi()) { return false; } } if (peptideFilter.getPeptideScore() != null) { if (peptideFilter.getPeptideScoreComparison() == ComparisonType.AFTER) { if (psParameter.getPeptideScore() <= peptideFilter.getPeptideScore()) { return false; } } else if (peptideFilter.getPeptideScoreComparison() == ComparisonType.BEFORE) { if (psParameter.getPeptideScore() >= peptideFilter.getPeptideScore()) { return false; } } else if (peptideFilter.getPeptideScoreComparison() == ComparisonType.EQUAL) { if (psParameter.getPeptideScore() != peptideFilter.getPeptideScore()) { return false; } } else if (peptideFilter.getPeptideScoreComparison() == ComparisonType.NOT_EQUAL) { if (psParameter.getPeptideScore() == peptideFilter.getPeptideScore()) { return false; } } } if (peptideFilter.getPeptideConfidence() != null) { if (peptideFilter.getPeptideConfidenceComparison() == ComparisonType.AFTER) { if (psParameter.getPeptideConfidence() <= peptideFilter.getPeptideConfidence()) { return false; } } else if (peptideFilter.getPeptideConfidenceComparison() == ComparisonType.BEFORE) { if (psParameter.getPeptideConfidence() >= peptideFilter.getPeptideConfidence()) { return false; } } else if (peptideFilter.getPeptideConfidenceComparison() == ComparisonType.EQUAL) { if (psParameter.getPeptideConfidence() != peptideFilter.getPeptideConfidence()) { return false; } } else if (peptideFilter.getPeptideConfidenceComparison() == ComparisonType.NOT_EQUAL) { if (psParameter.getPeptideConfidence() == peptideFilter.getPeptideConfidence()) { return false; } } } if (peptideFilter.getNSpectra() != null || peptideFilter.getProtein() != null) { PeptideMatch peptideMatch = identification.getPeptideMatch(peptideKey); if (peptideFilter.getNSpectra() != null) { if (peptideFilter.getnSpectraComparison() == ComparisonType.AFTER) { if (peptideMatch.getSpectrumCount() <= peptideFilter.getNSpectra()) { return false; } } else if (peptideFilter.getnSpectraComparison() == ComparisonType.BEFORE) { if (peptideMatch.getSpectrumCount() >= peptideFilter.getNSpectra()) { return false; } } else if (peptideFilter.getnSpectraComparison() == ComparisonType.EQUAL) { if (peptideMatch.getSpectrumCount() != peptideFilter.getNSpectra()) { return false; } } else if (peptideFilter.getnSpectraComparison() == ComparisonType.NOT_EQUAL) { if (peptideMatch.getSpectrumCount() != peptideFilter.getNSpectra()) { return false; } } } if (peptideFilter.getProtein() != null) { found = false; for (String accession : peptideMatch.getTheoreticPeptide().getParentProteins()) { if (accession.split(peptideFilter.getProtein()).length > 1) { found = true; break; } if (sequenceFactory.getHeader(accession).getDescription() != null && sequenceFactory.getHeader(accession).getDescription().split(peptideFilter.getProtein()).length > 1) { found = true; break; } } if (!found) { return false; } } } return true; } catch (Exception e) { e.printStackTrace(); peptideShakerGUI.catchException(e); return false; } } /** * Tests whether a spectrum match is validated by a given filter. * * @param spectrumKey the key of the spectrum match * @param psmFilter the filter * @return a boolean indicating whether a spectrum match is validated by a * given filter */ public boolean isValidated(String spectrumKey, PsmFilter psmFilter) { try { if (psmFilter.getExceptions().contains(spectrumKey)) { return false; } if (psmFilter.getManualValidation().size() > 0) { if (psmFilter.getManualValidation().contains(spectrumKey)) { return true; } else { return false; } } Identification identification = peptideShakerGUI.getIdentification(); PSParameter psParameter = new PSParameter(); if (psmFilter.getPsmScore() != null || psmFilter.getPsmConfidence() != null) { psParameter = (PSParameter) identification.getSpectrumMatchParameter(spectrumKey, psParameter); if (psmFilter.getPsmScore() != null) { if (psmFilter.getPsmScoreComparison() == ComparisonType.AFTER) { if (psParameter.getPsmScore() <= psmFilter.getPsmScore()) { return false; } } else if (psmFilter.getPsmScoreComparison() == ComparisonType.BEFORE) { if (psParameter.getPsmScore() >= psmFilter.getPsmScore()) { return false; } } else if (psmFilter.getPsmScoreComparison() == ComparisonType.EQUAL) { if (psParameter.getPsmScore() != psmFilter.getPsmScore()) { return false; } } else if (psmFilter.getPsmScoreComparison() == ComparisonType.NOT_EQUAL) { if (psParameter.getPsmScore() == psmFilter.getPsmScore()) { return false; } } } if (psmFilter.getPsmConfidence() != null) { if (psmFilter.getPsmConfidenceComparison() == ComparisonType.AFTER) { if (psParameter.getPsmConfidence() <= psmFilter.getPsmConfidence()) { return false; } } else if (psmFilter.getPsmConfidenceComparison() == ComparisonType.BEFORE) { if (psParameter.getPsmConfidence() >= psmFilter.getPsmConfidence()) { return false; } } else if (psmFilter.getPsmConfidenceComparison() == ComparisonType.EQUAL) { if (psParameter.getPsmConfidence() != psmFilter.getPsmConfidence()) { return false; } } else if (psmFilter.getPsmConfidenceComparison() == ComparisonType.NOT_EQUAL) { if (psParameter.getPsmConfidence() == psmFilter.getPsmConfidence()) { return false; } } } } if (psmFilter.getPrecursorMz() != null || psmFilter.getPrecursorRT() != null || psmFilter.getPrecursorMzError() != null) { Precursor precursor = peptideShakerGUI.getPrecursor(spectrumKey); if (psmFilter.getPrecursorMz() != null) { if (psmFilter.getPrecursorMzComparison() == ComparisonType.AFTER) { if (precursor.getMz() <= psmFilter.getPrecursorMz()) { return false; } } else if (psmFilter.getPrecursorMzComparison() == ComparisonType.BEFORE) { if (precursor.getMz() >= psmFilter.getPrecursorMz()) { return false; } } else if (psmFilter.getPrecursorMzComparison() == ComparisonType.EQUAL) { if (precursor.getMz() != psmFilter.getPrecursorMz()) { return false; } } else if (psmFilter.getPrecursorMzComparison() == ComparisonType.NOT_EQUAL) { if (precursor.getMz() == psmFilter.getPrecursorMz()) { return false; } } } if (psmFilter.getPrecursorRT() != null) { if (psmFilter.getPrecursorRTComparison() == ComparisonType.AFTER) { if (precursor.getRt() <= psmFilter.getPrecursorRT()) { return false; } } else if (psmFilter.getPrecursorRTComparison() == ComparisonType.BEFORE) { if (precursor.getRt() >= psmFilter.getPrecursorRT()) { return false; } } else if (psmFilter.getPrecursorRTComparison() == ComparisonType.EQUAL) { if (precursor.getRt() != psmFilter.getPrecursorRT()) { return false; } } else if (psmFilter.getPrecursorRTComparison() == ComparisonType.NOT_EQUAL) { if (precursor.getRt() == psmFilter.getPrecursorRT()) { return false; } } } if (psmFilter.getPrecursorMzError() != null) { SpectrumMatch spectrumMatch = identification.getSpectrumMatch(spectrumKey); double error = Math.abs(spectrumMatch.getBestAssumption().getDeltaMass(precursor.getMz(), peptideShakerGUI.getSearchParameters().isPrecursorAccuracyTypePpm())); if (psmFilter.getPrecursorMzErrorComparison() == ComparisonType.AFTER) { if (error <= psmFilter.getPrecursorMzError()) { return false; } } else if (psmFilter.getPrecursorMzErrorComparison() == ComparisonType.BEFORE) { if (error >= psmFilter.getPrecursorMzError()) { return false; } } else if (psmFilter.getPrecursorMzErrorComparison() == ComparisonType.EQUAL) { if (error != psmFilter.getPrecursorMzError()) { return false; } } else if (psmFilter.getPrecursorMzErrorComparison() == ComparisonType.NOT_EQUAL) { if (error == psmFilter.getPrecursorMzError()) { return false; } } } } if (psmFilter.getCharges().size() != peptideShakerGUI.getMetrics().getFoundCharges().size()) { SpectrumMatch spectrumMatch = identification.getSpectrumMatch(spectrumKey); int charge = spectrumMatch.getBestAssumption().getIdentificationCharge().value; if (!psmFilter.getCharges().contains(charge)) { return false; } } if (!psmFilter.getFileNames().contains(Spectrum.getSpectrumFile(spectrumKey))) { return false; } return true; } catch (Exception e) { e.printStackTrace(); peptideShakerGUI.catchException(e); return false; } } }
cr88192/bgbtech_engine
include/bgbdy_vfzip.h
<reponame>cr88192/bgbtech_engine #define VFZIP_CACHE_MAX (1<<24) #define VFZIP_CACHE_MAXCACHE (1<<20) #define FCC_PK_FILE 0x04034B50 #define FCC_PK_DIRFILE 0x02014B50 #define FCC_PK_DIREND 0x06054B50 typedef struct VFZIP_Entry_s VFZIP_Entry; typedef struct VFZIP_Context_s VFZIP_Context; typedef struct VFZIP_FileCtx_s VFZIP_FileCtx; typedef struct VFZIP_Entry_s VFBUF_Entry; typedef struct VFZIP_FileCtx_s VFBUF_FileCtx; struct VFZIP_Entry_s { VFZIP_Entry *next; //next in file VFZIP_Entry *hnext; //next in hash VFZIP_Entry *dnext; //next in dir VFZIP_Entry *dfirst; //first in sub dir VFZIP_Entry *cnext; //next in cache char *name; //full name char *rname; //rel name int offs, doffs, csize, usize, method, crc; int ucnt; //use count for file int iocnt; //io count for file (detects idle files) byte *buffer; //cached version of file int bsize; //buffer size }; struct VFZIP_Context_s { FILE *fd; //zipfile char *name; VFZIP_Entry *first; //first file VFZIP_Entry *root; //root entry VFZIP_Entry *hash[4096]; //hash chains VFZIP_Entry *croot; //cache root int cache; //amount of cached data int dirty; //RRW: file is dirty }; struct VFZIP_FileCtx_s { VFZIP_Context *ctx; VFZIP_Entry *ent; int offs; };
odbozhou/rocketmq-connect
connectors/rocketmq-connect-jdbc/src/main/java/org/apache/rocketmq/connect/jdbc/connector/JdbcSourceConfig.java
<reponame>odbozhou/rocketmq-connect<filename>connectors/rocketmq-connect-jdbc/src/main/java/org/apache/rocketmq/connect/jdbc/connector/JdbcSourceConfig.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.rocketmq.connect.jdbc.connector; import io.openmessaging.KeyValue; import org.apache.rocketmq.connect.jdbc.config.AbstractConfig; import org.apache.rocketmq.connect.jdbc.util.NumericMapping; import org.apache.rocketmq.connect.jdbc.util.TableType; import java.time.ZoneId; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TimeZone; /** * jdbc source config */ public class JdbcSourceConfig extends AbstractConfig { /** * table load mode */ public enum TableLoadMode { MODE_BULK("bulk"), MODE_TIMESTAMP("timestamp"), MODE_INCREMENTING("incrementing"), MODE_TIMESTAMP_INCREMENTING("timestamp+incrementing"); private String name; TableLoadMode(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static TableLoadMode findTableLoadModeByName(String name) { for (TableLoadMode mode : TableLoadMode.values()) { if (mode.getName().equals(name)) { return mode; } } throw new IllegalArgumentException("Unsupports mode " + name); } } //source poll interval ms public static final String POLL_INTERVAL_MS_CONFIG = "poll.interval.ms"; private static final String POLL_INTERVAL_MS_DOC = "Frequency in ms to poll for new data in each table."; public static final int POLL_INTERVAL_MS_DEFAULT = 5000; // batch max rows public static final String BATCH_MAX_ROWS_CONFIG = "batch.max.rows"; public static final int BATCH_MAX_ROWS_DEFAULT = 100; // numeric precision mapping public static final String NUMERIC_PRECISION_MAPPING_CONFIG = "numeric.precision.mapping"; public static final boolean NUMERIC_PRECISION_MAPPING_DEFAULT = false; // numeric mapping public static final String NUMERIC_MAPPING_CONFIG = "numeric.mapping"; public static final String NUMERIC_MAPPING_DEFAULT = null; // dialect name public static final String DIALECT_NAME_CONFIG = "dialect.name"; public static final String DIALECT_NAME_DEFAULT = ""; // table load mode public static final String MODE_CONFIG = "mode"; // incrementing column name public static final String INCREMENTING_COLUMN_NAME_CONFIG = "incrementing.column.name"; public static final String INCREMENTING_COLUMN_NAME_DEFAULT = ""; // timestamp column name public static final String TIMESTAMP_COLUMN_NAME_CONFIG = "timestamp.column.name"; public static final String TIMESTAMP_COLUMN_NAME_DEFAULT = ""; // timestamp initial public static final String TIMESTAMP_INITIAL_CONFIG = "timestamp.initial"; public static final Long TIMESTAMP_INITIAL_DEFAULT = null; public static final long TIMESTAMP_INITIAL_CURRENT = Long.valueOf(-1); // Metadata Change Monitoring Interval (ms) public static final String TABLE_POLL_INTERVAL_MS_CONFIG = "table.poll.interval.ms"; public static final long TABLE_POLL_INTERVAL_MS_DEFAULT = 60 * 1000; // table white list public static final String TABLE_WHITELIST_CONFIG = "table.whitelist"; public static final String TABLE_WHITELIST_DEFAULT = ""; // table black list public static final String TABLE_BLACKLIST_CONFIG = "table.blacklist"; public static final String TABLE_BLACKLIST_DEFAULT = ""; public static final String SCHEMA_PATTERN_CONFIG = "schema.pattern"; private static final String SCHEMA_PATTERN_DOC = "Schema pattern to fetch table metadata from the database.\n" + " * ``\"\"`` retrieves those without a schema.\n" + " * null (default) indicates that the schema name is not used to narrow the search and " + "that all table metadata is fetched, regardless of the schema."; private static final String SCHEMA_PATTERN_DISPLAY = "Schema pattern"; public static final String SCHEMA_PATTERN_DEFAULT = null; public static final String CATALOG_PATTERN_CONFIG = "catalog.pattern"; private static final String CATALOG_PATTERN_DOC = "Catalog pattern to fetch table metadata from the database.\n" + " * ``\"\"`` retrieves those without a catalog \n" + " * null (default) indicates that the schema name is not used to narrow the search and " + "that all table metadata is fetched, regardless of the catalog."; private static final String CATALOG_PATTERN_DISPLAY = "Schema pattern"; public static final String CATALOG_PATTERN_DEFAULT = null; public static final String QUERY_CONFIG = "query"; public static final String QUERY_DEFAULT = ""; public static final String TOPIC_PREFIX_CONFIG = "topic.prefix"; private static final String TOPIC_PREFIX_DOC = "Prefix to prepend to table names to generate the name of the Kafka topic to publish data " + "to, or in the case of a custom query, the full name of the topic to publish to."; private static final String TOPIC_PREFIX_DISPLAY = "Topic Prefix"; /** * validate non null */ public static final String VALIDATE_NON_NULL_CONFIG = "validate.non.null"; private static final String VALIDATE_NON_NULL_DOC = "By default, the JDBC connector will validate that all incrementing and timestamp tables " + "have NOT NULL set for the columns being used as their ID/timestamp. If the tables don't," + " JDBC connector will fail to start. Setting this to false will disable these checks."; public static final boolean VALIDATE_NON_NULL_DEFAULT = true; private static final String VALIDATE_NON_NULL_DISPLAY = "Validate Non Null"; public static final String TIMESTAMP_DELAY_INTERVAL_MS_CONFIG = "timestamp.delay.interval.ms"; private static final String TIMESTAMP_DELAY_INTERVAL_MS_DOC = "How long to wait after a row with certain timestamp appears before we include it in the " + "result. You may choose to add some delay to allow transactions with earlier timestamp to" + " complete. The first execution will fetch all available records (i.e. starting at " + "timestamp 0) until current time minus the delay. Every following execution will get data" + " from the last time we fetched until current time minus the delay."; public static final long TIMESTAMP_DELAY_INTERVAL_MS_DEFAULT = 0; private static final String TIMESTAMP_DELAY_INTERVAL_MS_DISPLAY = "Delay Interval (ms)"; public static final String DB_TIMEZONE_CONFIG = "db.timezone"; public static final String DB_TIMEZONE_DEFAULT = "UTC"; private static final String DB_TIMEZONE_CONFIG_DOC = "Name of the JDBC timezone used in the connector when " + "querying with time-based criteria. Defaults to UTC."; private static final String DB_TIMEZONE_CONFIG_DISPLAY = "DB time zone"; public static final String TABLE_TYPE_DEFAULT = "TABLE"; public static final String TABLE_TYPE_CONFIG = "table.types"; private static final String TABLE_TYPE_DOC = "By default, the JDBC connector will only detect tables with type TABLE from the source " + "Database. This config allows a command separated list of table types to extract. Options" + " include:\n" + " * TABLE\n" + " * VIEW\n" + " * SYSTEM TABLE\n" + " * GLOBAL TEMPORARY\n" + " * LOCAL TEMPORARY\n" + " * ALIAS\n" + " * SYNONYM\n" + " In most cases it only makes sense to have either TABLE or VIEW."; // The suffix to add at offset partition's key public static final String OFFSET_SUFFIX_CONFIG = "offset.suffix"; public static final String OFFSET_SUFFIX_DEFAULT = ""; public static final String OFFSET_SUFFIX_DOC = "Add this suffix to offset partition's key. " + "So every time when create connector can use new offset"; // query suffix public static final String QUERY_SUFFIX_CONFIG = "query.suffix"; public static final String QUERY_SUFFIX_DEFAULT = ""; public static final String QUERY_SUFFIX_DOC = "Suffix to append at the end of the generated query."; private int pollIntervalMs; private int batchMaxRows; private Boolean numericPrecisionMapping; private String numericMapping; private String dialectName; private String mode; private String incrementingColumnName; private List<String> timestampColumnNames; private long timestampDelayIntervalMs; private Long timestampInitial = TIMESTAMP_INITIAL_DEFAULT; private Set<String> tableWhitelist; private Set<String> tableBlacklist; private String schemaPattern; private String catalogPattern; private String query; private String topicPrefix; private boolean validateNonNull; private EnumSet<TableType> tableTypes; private TimeZone timeZone; private String offsetSuffix; private String querySuffix; public JdbcSourceConfig(KeyValue config) { super(config); this.pollIntervalMs = config.getInt(POLL_INTERVAL_MS_CONFIG, POLL_INTERVAL_MS_DEFAULT); this.batchMaxRows = config.getInt(BATCH_MAX_ROWS_CONFIG, BATCH_MAX_ROWS_DEFAULT); this.numericPrecisionMapping = getBoolean(config, NUMERIC_PRECISION_MAPPING_CONFIG, NUMERIC_PRECISION_MAPPING_DEFAULT); this.numericMapping = config.getString(NUMERIC_MAPPING_CONFIG, NUMERIC_MAPPING_DEFAULT); this.dialectName = config.getString(DIALECT_NAME_CONFIG, DIALECT_NAME_DEFAULT); this.mode = config.getString(MODE_CONFIG); this.incrementingColumnName = config.getString(INCREMENTING_COLUMN_NAME_CONFIG); this.timestampColumnNames = getList(config, TIMESTAMP_COLUMN_NAME_CONFIG); timestampDelayIntervalMs = config.getLong(TIMESTAMP_DELAY_INTERVAL_MS_CONFIG); // this.timestampInitial=config.getLong(TIMESTAMP_INITIAL_CONFIG,TIMESTAMP_INITIAL_DEFAULT); if (config.containsKey(TIMESTAMP_INITIAL_CONFIG)) { this.timestampInitial = config.getLong(TIMESTAMP_INITIAL_CONFIG); } this.tableWhitelist = new HashSet<>(getList(config, TABLE_WHITELIST_CONFIG)); this.tableBlacklist = new HashSet<>(getList(config, TABLE_BLACKLIST_CONFIG)); this.schemaPattern = config.getString(SCHEMA_PATTERN_CONFIG); this.catalogPattern = config.getString(CATALOG_PATTERN_CONFIG); this.query = config.getString(QUERY_CONFIG); this.topicPrefix = config.getString(TOPIC_PREFIX_CONFIG); this.validateNonNull = getBoolean(config, VALIDATE_NON_NULL_CONFIG, VALIDATE_NON_NULL_DEFAULT); tableTypes = TableType.parse(getList(config, TABLE_TYPE_CONFIG, TABLE_TYPE_DEFAULT)); String dbTimeZone = config.getString(DB_TIMEZONE_CONFIG, DB_TIMEZONE_DEFAULT); this.timeZone = TimeZone.getTimeZone(ZoneId.of(dbTimeZone)); this.querySuffix = config.getString(QUERY_SUFFIX_CONFIG, QUERY_SUFFIX_DEFAULT); this.offsetSuffix = config.getString(OFFSET_SUFFIX_CONFIG, OFFSET_SUFFIX_DEFAULT); } public NumericMapping numericMapping() { return NumericMapping.get(this); } public int getPollIntervalMs() { return pollIntervalMs; } public int getBatchMaxRows() { return batchMaxRows; } public Boolean getNumericPrecisionMapping() { return numericPrecisionMapping; } public String getNumericMapping() { return numericMapping; } public String getDialectName() { return dialectName; } public String getMode() { return mode; } public String getIncrementingColumnName() { return incrementingColumnName; } public List<String> getTimestampColumnNames() { return timestampColumnNames; } public Long getTimestampInitial() { return timestampInitial; } public Set<String> getTableWhitelist() { return tableWhitelist; } public Set<String> getTableBlacklist() { return tableBlacklist; } public String getSchemaPattern() { return schemaPattern; } public String getCatalogPattern() { return catalogPattern; } public String getQuery() { return query; } public String getTopicPrefix() { return topicPrefix; } public boolean isValidateNonNull() { return validateNonNull; } public EnumSet<TableType> getTableTypes() { return tableTypes; } public TimeZone getTimeZone() { return timeZone; } public long getTimestampDelayIntervalMs() { return timestampDelayIntervalMs; } public String getOffsetSuffix() { return offsetSuffix; } public String getQuerySuffix() { return querySuffix; } }
Chrisi816/Azoniq-Discord-Bot-v.1.3
commands/social-media/twitch.js
module.exports = { commands: ['vAzoniq twitch'], description: 'Link von vAzoniq wird gesendet!', callback:(message) => { message.channel.send(` Über diesen Link kommst du ganz einfach zum Twitch Kanal von vAzoniq! https://www.twitch.tv/vazoniq7882`) } }
dhavalocked/openassessment
client/js/_player/components/assessments/universal_input.spec.js
"use strict"; import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import UniversalInput from './universal_input'; import { shallow } from 'enzyme'; describe('Assessment Questions', ()=> { var result; var item; var Content; var selectAnswer = () => {}; it('It Renders the page', ()=>{ expect(ReactDOM.findDOMNode(result)).toBeDefined(); }); describe('Drag and Drop', ()=>{ let props; beforeEach(()=>{ props = { item: { question_type: 'edx_drag_and_drop', answers: [{ id: 0, type: 'key', draggables: [{id:'0', label:'drag1'},{id:'1', label:'drag2'},{id:'2', label:'drag3'}], targets: [{id:'0', height:'100', width:'180', xPos:'10', yPos:'10'}], img: 'http://www.bealecorner.com/trv900/respat/eia1956-small.jpg', }, { id: 0, type: 'value', draggables: [{id:'0', label:'drag1'},{id:'1', label:'drag2'},{id:'2', label:'drag3'}], img: 'http://www.bealecorner.com/trv900/respat/eia1956-small.jpg', }], } }; result = shallow(<UniversalInput {...props} />); }); it('Renders the components', ()=>{ expect(result).toBeDefined(); }); }); describe('Multiple Choice', ()=>{ beforeEach(()=>{ item = { id : 0, question_type: "multiple_choice_question", url : "www.iamcool.com", title : "title", xml : null, standard : 'edX', edXMaterial : "<p>hello world</p>", answers : [{id: "0", material: "test1"}, {id: "1", material: "test2"}], isGraded : true, messages : ["My Message1", "My Message2"], solution : "<p>solution text</p>" }; Content = ( <UniversalInput settings={ {} } item={item} selectAnswer={selectAnswer}/> ); result = TestUtils.renderIntoDocument(Content); }); it('It Renders the radio buttons', ()=>{ expect(TestUtils.scryRenderedComponentsWithType(result, 'radio')).toBeDefined(); }); it('It Renders the option text', ()=>{ expect(ReactDOM.findDOMNode(result).textContent).toContain(item.answers[0].material); expect(ReactDOM.findDOMNode(result).textContent).toContain(item.answers[1].material); }); }); describe('Numerical Input', ()=>{ beforeEach(()=>{ item.question_type = 'edx_numerical_input'; Content = (<UniversalInput settings={ {} } item={item} />); result = TestUtils.renderIntoDocument(Content); }); it('Renders the sub-question text', ()=>{ expect(ReactDOM.findDOMNode(result).textContent).toContain(item.answers[0].material); expect(ReactDOM.findDOMNode(result).textContent).toContain(item.answers[1].material); }); it('Renders the text input', ()=>{ expect(TestUtils.scryRenderedDOMComponentsWithTag(result, 'input')).toBeDefined(); }); }); describe('Text Input', ()=>{ beforeEach(()=>{ item.question_type = 'edx_numerical_input'; Content = ( <UniversalInput settings={ {} } item={item} selectAnswer={selectAnswer} /> ); result = TestUtils.renderIntoDocument(Content); }); it('Renders the sub-question text', ()=>{ expect(ReactDOM.findDOMNode(result).textContent).toContain(item.answers[0].material); expect(ReactDOM.findDOMNode(result).textContent).toContain(item.answers[1].material); }); it('Renders the text input', ()=>{ expect(TestUtils.scryRenderedDOMComponentsWithTag(result, 'input')).toBeDefined(); }); }); describe('Drop Down', ()=>{ beforeEach(()=>{ item.question_type = 'edx_dropdown'; item.answers = [{ id: 0, material: ['option1', 'option2', 'option3']}]; Content = (<UniversalInput settings={ {} } item={item} />); result = TestUtils.renderIntoDocument(Content); }); it('Renders the drop down element', ()=>{ expect(TestUtils.scryRenderedDOMComponentsWithTag(result, 'select')).toBeDefined(); }); it('All the options are in the dropdown', ()=>{ var options = TestUtils.scryRenderedDOMComponentsWithTag(result, 'option'); expect(options[0].textContent).toContain('option1'); expect(options[1].textContent).toEqual('option2'); expect(options[2].textContent).toEqual('option3'); }); }); describe('Image Mapped Input', ()=>{ beforeEach(()=>{ item.question_type = 'edx_image_mapped_input'; item.answers = [{ id: 0, material:['100','100','100','100'], coordinates: ['200','200','200','200'], height: 100, width: 100}]; Content = (<UniversalInput settings={ {} } item={item} />); result = TestUtils.renderIntoDocument(Content); }); it('Renders the image to the page', ()=>{ expect(TestUtils.scryRenderedDOMComponentsWithTag(result, 'img')).toBeDefined(); }); }); // xdescribe('Problem with Adaptive Hint', ()=>{}); describe('Multiple Answer', ()=>{ beforeEach(()=>{ item = { id : 0, question_type: "multiple_answers_question", url : "www.iamcool.com", title : "title", xml : null, standard : 'edX', edXMaterial : "<p>hello world</p>", answers : [{id: "0", material: "test1"}, {id: "1", material: "test2"}], isGraded : true, messages : ["My Message1", "My Message2"], solution : "<p>solution text</p>" }; Content = ( <UniversalInput settings={ {} } item={item} selectAnswer={selectAnswer}/> ); result = TestUtils.renderIntoDocument(Content); }); it('Renders the checkboxes', ()=>{ expect(TestUtils.scryRenderedComponentsWithType(result, 'checkbox')).toBeDefined(); }); it('Checkbox text is rendered', ()=>{ expect(ReactDOM.findDOMNode(result).textContent).toContain(item.answers[0].material); expect(ReactDOM.findDOMNode(result).textContent).toContain(item.answers[1].material); }); }); it('Does not render the solution if the question is not answered', ()=>{ expect(ReactDOM.findDOMNode(result).textContent).toContain( item.answers[0].material + item.answers[1].material ); }); });
dehilsterlexis/eclide-1
eclide/ChildGraphFrame.cpp
<reponame>dehilsterlexis/eclide-1 #include "StdAfx.h" #include "..\en_us\resource.h" #include "ChildGraphFrame.h" #include "WtlMDIChildFrame.h" #include "ChildFrame.h" #include "MainFrm.h" #include "preferencedlg.h" #include "global.h" #include "util.h" #include "GraphView.h" class CGraphFrame : public CChildFrame { typedef CGraphFrame thisClass; typedef CChildFrame baseClass; public: CGraphView m_dlgview; std::_tstring m_path; public: DECLARE_FRAME_WND_CLASS(NULL, IDR_GRAPHWINDOW) CGraphFrame(const CString & filePath, IWorkspaceItem * workspaceItem) : baseClass(m_attrInfo, workspaceItem), m_dlgview(NULL, NULL) { m_path = filePath; m_dlgview.DoFileOpen(filePath); } BOOL PreTranslateMessage(MSG* pMsg) { if ((pMsg->message == WM_KEYDOWN )&& (pMsg->wParam == VK_F4)) { int d = 0; } if (pMsg->message == WM_KEYDOWN && (::GetAsyncKeyState(VK_CONTROL) & 0x8000)) // Let frame handle some messages. { switch (pMsg->wParam) { case VK_F4: return 0; break; case VK_F6: if (::GetAsyncKeyState(VK_SHIFT) & 0x8000) ::GetIMainFrame()->MDIPrev(); else ::GetIMainFrame()->MDINext(); return 1; break; case VK_TAB: return 0; break; } } return m_dlgview.PreTranslateMessage(pMsg); } void OnSize(UINT nType, CSize size) { CRect rectClient; GetClientRect(rectClient); m_dlgview.SetWindowPos(NULL, rectClient.left, rectClient.top, rectClient.Width(), rectClient.Height(), SWP_NOACTIVATE | SWP_NOZORDER); } void OnSetFocus(HWND /*hWndOther*/) { if (m_dlgview.IsWindow() && m_dlgview.IsWindowVisible()) m_dlgview.SetFocus(); } void PostSelectRibbon() { GetIMainFrame()->PostSelectRibbon(RIBBON_GRAPH); } BEGIN_MSG_MAP(thisClass) MSG_WM_CREATE(OnCreate) MSG_WM_SIZE(OnSize) MSG_WM_SETFOCUS(OnSetFocus) MSG_WM_CONTEXTMENU(OnContextMenu) CHAIN_MSG_MAP(baseClass) REFLECT_NOTIFICATIONS() CHAIN_COMMANDS_MEMBER(m_dlgview) END_MSG_MAP() LRESULT OnCreate(LPCREATESTRUCT lParam) { m_dlgview.Create(m_hWnd, rcDefault); baseClass::OnCreate(lParam); return 0; } virtual void UIUpdateTitle() { CString title = _T("XGMML File"); //m_dlgview.GetTitle(title); GetParent().SendMessage(UM_TITLECHANGED, (WPARAM)(const TCHAR *)title); } virtual bool UIUpdateMenuItems(CCmdUI * cui) { if (m_dlgview.UpdateUI(cui)) return true; return false; } const TCHAR * GetPath() { return m_path.c_str(); } const TCHAR * GetTabTip(std::_tstring & tabTip) { tabTip = GetPath(); return tabTip.c_str(); } // File Access --- bool DoFileOpen(const CString & sPathName); virtual void SavePersistInfo(CPersistMap & persistInfo); virtual void RestorePersistInfo(const CPersistMap & persistInfo); LRESULT OnForwardMsg(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/) { LPMSG pMsg = (LPMSG)lParam; //if(baseClass::PreTranslateMessage(pMsg)) // return TRUE; return m_dlgview.PreTranslateMessage(pMsg); } // IResultSlot override --- void PostStatus(const TCHAR *status, PANE pane = PANE_DEFAULT) { ::GetIMainFrame()->PostStatus(status, pane); } public: void OnContextMenu(HWND phWnd, CPoint pt) { ATLASSERT(!"Check This"); m_dlgview.OnContextMenu(phWnd,pt); } }; bool CGraphFrame::DoFileOpen(const CString & sPathNameX) { m_path = sPathNameX; return m_dlgview.DoFileOpen(sPathNameX); } void CGraphFrame::SavePersistInfo(CPersistMap & persistInfo) { baseClass::SavePersistInfo(persistInfo); persistInfo.Set(PERSIST_TYPE, PERSISTVAL_GRAPH); persistInfo.Set(PERSIST_PATH, m_path); } void CGraphFrame::RestorePersistInfo(const CPersistMap & persistInfo) { if (std::_tstring(persistInfo.Get(PERSIST_PATH)).length()) m_dlgview.DoFileOpen(persistInfo.Get(PERSIST_PATH)); } // =========================================================================== class CChildGraphFrm : public CWtlMDIChildFrame<StlLinked<CGraphFrame> > { typedef CChildGraphFrm thisClass; typedef CWtlMDIChildFrame<StlLinked<CGraphFrame> > baseClass; public: CChildGraphFrm(const CString & filePath, IWorkspaceItem * workspaceItem) { m_view = new CGraphFrame(filePath, workspaceItem); } #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif // Generated message map functions protected: DECLARE_MESSAGE_MAP() }; BEGIN_MESSAGE_MAP(CChildGraphFrm, baseClass) END_MESSAGE_MAP() // CChildGraphFrm diagnostics #ifdef _DEBUG void CChildGraphFrm::AssertValid() const { CMDIChildWndEx::AssertValid(); } void CChildGraphFrm::Dump(CDumpContext& dc) const { CMDIChildWndEx::Dump(dc); } #endif //_DEBUG // =========================================================================== HWND OpenGraphMDI(CMainFrame* pFrame, IWorkspaceItem * workspaceItem) { CChildGraphFrm* pChild = new CChildGraphFrm(_T(""), workspaceItem); CMDIChildWnd * retVal = CreateNewChild(pFrame, pChild, IDR_GRAPHWINDOW, _T("todo")); return retVal->GetSafeHwnd(); } bool OpenFileGraphMDI(CMainFrame* pFrame, const CString & filePath, IWorkspaceItem * workspaceItem) { ATLASSERT(!filePath.IsEmpty()); CChildGraphFrm* pChild = new CChildGraphFrm(filePath, workspaceItem); CMDIChildWnd * retVal = CreateNewChild(pFrame, pChild, IDR_GRAPHWINDOW, _T("todo")); return true; }
meodaiduoi/onos
apps/openstackvtap/app/src/test/java/org/onosproject/openstackvtap/codec/OpenstackVtapNetworkCodecTest.java
/* * Copyright 2018-present Open Networking Foundation * * 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.onosproject.openstackvtap.codec; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.Before; import org.junit.Test; import org.onlab.packet.IpAddress; import org.onosproject.codec.CodecContext; import org.onosproject.codec.JsonCodec; import org.onosproject.codec.impl.CodecManager; import org.onosproject.core.CoreService; import org.onosproject.openstackvtap.api.OpenstackVtapNetwork; import org.onosproject.openstackvtap.impl.DefaultOpenstackVtapNetwork; import java.util.HashMap; import java.util.Map; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; import static org.onosproject.net.NetTestTools.APP_ID; import static org.onosproject.openstackvtap.codec.OpenstackVtapNetworkJsonMatcher.matchesVtapNetwork; /** * Unit tests for OpenstackVtapNetwork codec. */ public class OpenstackVtapNetworkCodecTest { MockCodecContext context; JsonCodec<OpenstackVtapNetwork> vtapNetworkCodec; final CoreService mockCoreService = createMock(CoreService.class); private static final String REST_APP_ID = "org.onosproject.rest"; private static final OpenstackVtapNetwork.Mode MODE = OpenstackVtapNetwork.Mode.VXLAN; private static final int VNI = 1; private static final String SERVER_IP_ADDRESS = "10.10.10.1"; /** * Initial setup for this unit test. */ @Before public void setUp() { context = new MockCodecContext(); vtapNetworkCodec = new OpenstackVtapNetworkCodec(); assertThat(vtapNetworkCodec, notNullValue()); expect(mockCoreService.registerApplication(REST_APP_ID)) .andReturn(APP_ID).anyTimes(); replay(mockCoreService); context.registerService(CoreService.class, mockCoreService); } /** * Tests the openstack vtap network encoding. */ @Test public void testEncode() { OpenstackVtapNetwork vtapNetwork = DefaultOpenstackVtapNetwork.builder() .mode(MODE) .networkId(VNI) .serverIp(IpAddress.valueOf(SERVER_IP_ADDRESS)) .build(); ObjectNode nodeJson = vtapNetworkCodec.encode(vtapNetwork, context); assertThat(nodeJson, matchesVtapNetwork(vtapNetwork)); } /** * Mock codec context for use in codec unit tests. */ private class MockCodecContext implements CodecContext { private final ObjectMapper mapper = new ObjectMapper(); private final CodecManager manager = new CodecManager(); private final Map<Class<?>, Object> services = new HashMap<>(); /** * Constructs a new mock codec context. */ public MockCodecContext() { manager.activate(); } @Override public ObjectMapper mapper() { return mapper; } @Override @SuppressWarnings("unchecked") public <T> JsonCodec<T> codec(Class<T> entityClass) { if (entityClass == OpenstackVtapNetwork.class) { return (JsonCodec<T>) vtapNetworkCodec; } return manager.getCodec(entityClass); } @SuppressWarnings("unchecked") @Override public <T> T getService(Class<T> serviceClass) { return (T) services.get(serviceClass); } // for registering mock services public <T> void registerService(Class<T> serviceClass, T impl) { services.put(serviceClass, impl); } } }
ncl427/openair-cn
SRC/NAS/3gpp_24.301_ies_xml.c
<gh_stars>0 /* * Copyright (c) 2015, EURECOM (www.eurecom.fr) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. */ /*! \file 3gpp_24.301_ies_xml.c \brief EMM msg C struct to/from XML functions \author <NAME> \date 2016 \email: <EMAIL> */ #include <stdbool.h> #include <stdint.h> #include <pthread.h> #include <libxml/xmlwriter.h> #include <libxml/xpath.h> #include "bstrlib.h" #include "dynamic_memory_check.h" #include "hashtable.h" #include "obj_hashtable.h" #include "log.h" #include "common_defs.h" #include "assertions.h" #include "3gpp_23.003.h" #include "3gpp_24.008.h" #include "3gpp_33.401.h" #include "3gpp_24.007.h" #include "3gpp_36.401.h" #include "3gpp_36.331.h" #include "xml2_wrapper.h" #include "3gpp_24.301.h" #include "3gpp_24.301_ies_xml.h" NUM_FROM_XML_GENERATE(security_header_type, SECURITY_HEADER_TYPE); //------------------------------------------------------------------------------ void security_header_type_to_xml ( const security_header_type_t * const security_header_type, xmlTextWriterPtr writer) { XML_WRITE_FORMAT_ELEMENT(writer, SECURITY_HEADER_TYPE_XML_STR, SECURITY_HEADER_TYPE_XML_FMT, *security_header_type); } //------------------------------------------------------------------------------ bool mac_from_xml ( xmlDocPtr xml_doc, xmlXPathContextPtr xpath_ctx, uint32_t * const mac) { bstring xpath_expr = bformat("./%s",MAC_XML_STR); bool res = xml_load_leaf_tag(xml_doc, xpath_ctx, xpath_expr, "%"SCNx32, (void*)mac, NULL); bdestroy_wrapper (&xpath_expr); return res; } //------------------------------------------------------------------------------ void mac_to_xml ( const uint32_t * const mac, xmlTextWriterPtr writer) { XML_WRITE_FORMAT_ELEMENT(writer, MAC_XML_STR, MAC_FMT, *mac); } //------------------------------------------------------------------------------ bool message_type_from_xml (xmlDocPtr xml_doc, xmlXPathContextPtr xpath_ctx, message_type_t * const messagetype) { char message_type_str[128] = {0}; bstring xpath_expr = bformat("./%s",MESSAGE_TYPE_XML_STR); bool res = xml_load_leaf_tag(xml_doc, xpath_ctx, xpath_expr, "%s", (void*)message_type_str, NULL); bdestroy_wrapper (&xpath_expr); *messagetype = 0; if (res) { if (!strcasecmp(ATTACH_REQUEST_VAL_XML_STR, message_type_str)) {*messagetype = ATTACH_REQUEST;return res;} if (!strcasecmp(ATTACH_ACCEPT_VAL_XML_STR, message_type_str)) {*messagetype = ATTACH_ACCEPT;return res;} if (!strcasecmp(ATTACH_COMPLETE_VAL_XML_STR, message_type_str)) {*messagetype = ATTACH_COMPLETE;return res;} if (!strcasecmp(ATTACH_REJECT_VAL_XML_STR, message_type_str)) {*messagetype = ATTACH_REJECT;return res;} if (!strcasecmp(DETACH_REQUEST_VAL_XML_STR, message_type_str)) {*messagetype = DETACH_REQUEST;return res;} if (!strcasecmp(DETACH_ACCEPT_VAL_XML_STR, message_type_str)) {*messagetype = DETACH_ACCEPT;return res;} if (!strcasecmp(TRACKING_AREA_UPDATE_REQUEST_VAL_XML_STR, message_type_str)) {*messagetype = TRACKING_AREA_UPDATE_REQUEST;return res;} if (!strcasecmp(TRACKING_AREA_UPDATE_ACCEPT_VAL_XML_STR, message_type_str)) {*messagetype = TRACKING_AREA_UPDATE_ACCEPT;return res;} if (!strcasecmp(TRACKING_AREA_UPDATE_COMPLETE_VAL_XML_STR, message_type_str)) {*messagetype = TRACKING_AREA_UPDATE_COMPLETE;return res;} if (!strcasecmp(TRACKING_AREA_UPDATE_REJECT_VAL_XML_STR, message_type_str)) {*messagetype = TRACKING_AREA_UPDATE_REJECT;return res;} if (!strcasecmp(EXTENDED_SERVICE_REQUEST_VAL_XML_STR, message_type_str)) {*messagetype = EXTENDED_SERVICE_REQUEST;return res;} if (!strcasecmp(SERVICE_REJECT_VAL_XML_STR, message_type_str)) {*messagetype = SERVICE_REJECT;return res;} if (!strcasecmp(GUTI_REALLOCATION_COMMAND_VAL_XML_STR, message_type_str)) {*messagetype = GUTI_REALLOCATION_COMMAND;return res;} if (!strcasecmp(GUTI_REALLOCATION_COMPLETE_VAL_XML_STR, message_type_str)) {*messagetype = GUTI_REALLOCATION_COMPLETE;return res;} if (!strcasecmp(AUTHENTICATION_REQUEST_VAL_XML_STR, message_type_str)) {*messagetype = AUTHENTICATION_REQUEST;return res;} if (!strcasecmp(AUTHENTICATION_RESPONSE_VAL_XML_STR, message_type_str)) {*messagetype = AUTHENTICATION_RESPONSE;return res;} if (!strcasecmp(AUTHENTICATION_REJECT_VAL_XML_STR, message_type_str)) {*messagetype = AUTHENTICATION_REJECT;return res;} if (!strcasecmp(AUTHENTICATION_FAILURE_VAL_XML_STR, message_type_str)) {*messagetype = AUTHENTICATION_FAILURE;return res;} if (!strcasecmp(IDENTITY_REQUEST_VAL_XML_STR, message_type_str)) {*messagetype = IDENTITY_REQUEST;return res;} if (!strcasecmp(IDENTITY_RESPONSE_VAL_XML_STR, message_type_str)) {*messagetype = IDENTITY_RESPONSE;return res;} if (!strcasecmp(SECURITY_MODE_COMMAND_VAL_XML_STR, message_type_str)) {*messagetype = SECURITY_MODE_COMMAND;return res;} if (!strcasecmp(SECURITY_MODE_COMPLETE_VAL_XML_STR, message_type_str)) {*messagetype = SECURITY_MODE_COMPLETE;return res;} if (!strcasecmp(SECURITY_MODE_REJECT_VAL_XML_STR, message_type_str)) {*messagetype = SECURITY_MODE_REJECT;return res;} if (!strcasecmp(EMM_STATUS_VAL_XML_STR, message_type_str)) {*messagetype = EMM_STATUS;return res;} if (!strcasecmp(EMM_INFORMATION_VAL_XML_STR, message_type_str)) {*messagetype = EMM_INFORMATION;return res;} if (!strcasecmp(DOWNLINK_NAS_TRANSPORT_VAL_XML_STR, message_type_str)) {*messagetype = DOWNLINK_NAS_TRANSPORT;return res;} if (!strcasecmp(UPLINK_NAS_TRANSPORT_VAL_XML_STR, message_type_str)) {*messagetype = UPLINK_NAS_TRANSPORT;return res;} if (!strcasecmp(CS_SERVICE_NOTIFICATION_VAL_XML_STR, message_type_str)) {*messagetype = CS_SERVICE_NOTIFICATION;return res;} if (!strcasecmp(DOWNLINK_GENERIC_NAS_TRANSPORT_VAL_XML_STR, message_type_str)) {*messagetype = DOWNLINK_GENERIC_NAS_TRANSPORT;return res;} if (!strcasecmp(UPLINK_GENERIC_NAS_TRANSPORT_VAL_XML_STR, message_type_str)) {*messagetype = UPLINK_GENERIC_NAS_TRANSPORT;return res;} if (!strcasecmp(ACTIVATE_DEFAULT_EPS_BEARER_CONTEXT_REQUEST_VAL_XML_STR, message_type_str)) {*messagetype = ACTIVATE_DEFAULT_EPS_BEARER_CONTEXT_REQUEST;return res;} if (!strcasecmp(ACTIVATE_DEFAULT_EPS_BEARER_CONTEXT_ACCEPT_VAL_XML_STR, message_type_str)) {*messagetype = ACTIVATE_DEFAULT_EPS_BEARER_CONTEXT_ACCEPT;return res;} if (!strcasecmp(ACTIVATE_DEFAULT_EPS_BEARER_CONTEXT_REJECT_VAL_XML_STR, message_type_str)) {*messagetype = ACTIVATE_DEFAULT_EPS_BEARER_CONTEXT_REJECT;return res;} if (!strcasecmp(ACTIVATE_DEDICATED_EPS_BEARER_CONTEXT_REQUEST_VAL_XML_STR, message_type_str)) {*messagetype = ACTIVATE_DEDICATED_EPS_BEARER_CONTEXT_REQUEST;return res;} if (!strcasecmp(ACTIVATE_DEDICATED_EPS_BEARER_CONTEXT_ACCEPT_VAL_XML_STR, message_type_str)) {*messagetype = ACTIVATE_DEDICATED_EPS_BEARER_CONTEXT_ACCEPT;return res;} if (!strcasecmp(ACTIVATE_DEDICATED_EPS_BEARER_CONTEXT_REJECT_VAL_XML_STR, message_type_str)) {*messagetype = ACTIVATE_DEDICATED_EPS_BEARER_CONTEXT_REJECT;return res;} if (!strcasecmp(MODIFY_EPS_BEARER_CONTEXT_REQUEST_VAL_XML_STR, message_type_str)) {*messagetype = MODIFY_EPS_BEARER_CONTEXT_REQUEST;return res;} if (!strcasecmp(MODIFY_EPS_BEARER_CONTEXT_ACCEPT_VAL_XML_STR, message_type_str)) {*messagetype = MODIFY_EPS_BEARER_CONTEXT_ACCEPT;return res;} if (!strcasecmp(MODIFY_EPS_BEARER_CONTEXT_REJECT_VAL_XML_STR, message_type_str)) {*messagetype = MODIFY_EPS_BEARER_CONTEXT_REJECT;return res;} if (!strcasecmp(DEACTIVATE_EPS_BEARER_CONTEXT_REQUEST_VAL_XML_STR, message_type_str)) {*messagetype = DEACTIVATE_EPS_BEARER_CONTEXT_REQUEST;return res;} if (!strcasecmp(DEACTIVATE_EPS_BEARER_CONTEXT_ACCEPT_VAL_XML_STR, message_type_str)) {*messagetype = DEACTIVATE_EPS_BEARER_CONTEXT_ACCEPT;return res;} if (!strcasecmp(PDN_CONNECTIVITY_REQUEST_VAL_XML_STR, message_type_str)) {*messagetype = PDN_CONNECTIVITY_REQUEST;return res;} if (!strcasecmp(PDN_CONNECTIVITY_REJECT_VAL_XML_STR, message_type_str)) {*messagetype = PDN_CONNECTIVITY_REJECT;return res;} if (!strcasecmp(PDN_DISCONNECT_REQUEST_VAL_XML_STR, message_type_str)) {*messagetype = PDN_DISCONNECT_REQUEST;return res;} if (!strcasecmp(PDN_DISCONNECT_REJECT_VAL_XML_STR, message_type_str)) {*messagetype = PDN_DISCONNECT_REJECT;return res;} if (!strcasecmp(BEARER_RESOURCE_ALLOCATION_REQUEST_VAL_XML_STR, message_type_str)) {*messagetype = BEARER_RESOURCE_ALLOCATION_REQUEST;return res;} if (!strcasecmp(BEARER_RESOURCE_ALLOCATION_REJECT_VAL_XML_STR, message_type_str)) {*messagetype = BEARER_RESOURCE_ALLOCATION_REJECT;return res;} if (!strcasecmp(BEARER_RESOURCE_MODIFICATION_REQUEST_VAL_XML_STR, message_type_str)) {*messagetype = BEARER_RESOURCE_MODIFICATION_REQUEST;return res;} if (!strcasecmp(BEARER_RESOURCE_MODIFICATION_REJECT_VAL_XML_STR, message_type_str)) {*messagetype = BEARER_RESOURCE_MODIFICATION_REJECT;return res;} if (!strcasecmp(ESM_INFORMATION_REQUEST_VAL_XML_STR, message_type_str)) {*messagetype = ESM_INFORMATION_REQUEST;return res;} if (!strcasecmp(ESM_INFORMATION_RESPONSE_VAL_XML_STR, message_type_str)) {*messagetype = ESM_INFORMATION_RESPONSE;return res;} if (!strcasecmp(ESM_STATUS_VAL_XML_STR, message_type_str)) {*messagetype = ESM_STATUS;return res;} } return false; } //------------------------------------------------------------------------------ void message_type_to_xml(const message_type_t * const messagetype, xmlTextWriterPtr writer) { // better do an array ? switch (*messagetype) { case ATTACH_REQUEST: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", ATTACH_REQUEST_VAL_XML_STR); break; case ATTACH_ACCEPT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", ATTACH_ACCEPT_VAL_XML_STR); break; case ATTACH_COMPLETE: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", ATTACH_COMPLETE_VAL_XML_STR); break; case ATTACH_REJECT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", ATTACH_REJECT_VAL_XML_STR); break; case DETACH_REQUEST: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", DETACH_REQUEST_VAL_XML_STR); break; case DETACH_ACCEPT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", DETACH_ACCEPT_VAL_XML_STR); break; case TRACKING_AREA_UPDATE_REQUEST: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", TRACKING_AREA_UPDATE_REQUEST_VAL_XML_STR); break; case TRACKING_AREA_UPDATE_ACCEPT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", TRACKING_AREA_UPDATE_ACCEPT_VAL_XML_STR); break; case TRACKING_AREA_UPDATE_COMPLETE: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", TRACKING_AREA_UPDATE_COMPLETE_VAL_XML_STR); break; case TRACKING_AREA_UPDATE_REJECT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", TRACKING_AREA_UPDATE_REJECT_VAL_XML_STR); break; case EXTENDED_SERVICE_REQUEST: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", EXTENDED_SERVICE_REQUEST_VAL_XML_STR); break; case SERVICE_REJECT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", SERVICE_REJECT_VAL_XML_STR); break; case GUTI_REALLOCATION_COMMAND: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", GUTI_REALLOCATION_COMMAND_VAL_XML_STR); break; case GUTI_REALLOCATION_COMPLETE: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", GUTI_REALLOCATION_COMPLETE_VAL_XML_STR); break; case AUTHENTICATION_REQUEST: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", AUTHENTICATION_REQUEST_VAL_XML_STR); break; case AUTHENTICATION_RESPONSE: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", AUTHENTICATION_RESPONSE_VAL_XML_STR); break; case AUTHENTICATION_REJECT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", AUTHENTICATION_REJECT_VAL_XML_STR); break; case AUTHENTICATION_FAILURE: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", AUTHENTICATION_FAILURE_VAL_XML_STR); break; case IDENTITY_REQUEST: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", IDENTITY_REQUEST_VAL_XML_STR); break; case IDENTITY_RESPONSE: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", IDENTITY_RESPONSE_VAL_XML_STR); break; case SECURITY_MODE_COMMAND: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", SECURITY_MODE_COMMAND_VAL_XML_STR); break; case SECURITY_MODE_COMPLETE: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", SECURITY_MODE_COMPLETE_VAL_XML_STR); break; case SECURITY_MODE_REJECT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", SECURITY_MODE_REJECT_VAL_XML_STR); break; case EMM_STATUS: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", EMM_STATUS_VAL_XML_STR); break; case EMM_INFORMATION: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", EMM_INFORMATION_VAL_XML_STR); break; case DOWNLINK_NAS_TRANSPORT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", DOWNLINK_NAS_TRANSPORT_VAL_XML_STR); break; case UPLINK_NAS_TRANSPORT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", UPLINK_NAS_TRANSPORT_VAL_XML_STR); break; case CS_SERVICE_NOTIFICATION: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", CS_SERVICE_NOTIFICATION_VAL_XML_STR); break; case DOWNLINK_GENERIC_NAS_TRANSPORT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", DOWNLINK_GENERIC_NAS_TRANSPORT_VAL_XML_STR); break; case UPLINK_GENERIC_NAS_TRANSPORT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", UPLINK_GENERIC_NAS_TRANSPORT_VAL_XML_STR); break; case ACTIVATE_DEFAULT_EPS_BEARER_CONTEXT_REQUEST: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", ACTIVATE_DEFAULT_EPS_BEARER_CONTEXT_REQUEST_VAL_XML_STR); break; case ACTIVATE_DEFAULT_EPS_BEARER_CONTEXT_ACCEPT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", ACTIVATE_DEFAULT_EPS_BEARER_CONTEXT_ACCEPT_VAL_XML_STR); break; case ACTIVATE_DEFAULT_EPS_BEARER_CONTEXT_REJECT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", ACTIVATE_DEFAULT_EPS_BEARER_CONTEXT_REJECT_VAL_XML_STR); break; case ACTIVATE_DEDICATED_EPS_BEARER_CONTEXT_REQUEST: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", ACTIVATE_DEDICATED_EPS_BEARER_CONTEXT_REQUEST_VAL_XML_STR); break; case ACTIVATE_DEDICATED_EPS_BEARER_CONTEXT_ACCEPT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", ACTIVATE_DEDICATED_EPS_BEARER_CONTEXT_ACCEPT_VAL_XML_STR); break; case ACTIVATE_DEDICATED_EPS_BEARER_CONTEXT_REJECT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", ACTIVATE_DEDICATED_EPS_BEARER_CONTEXT_REJECT_VAL_XML_STR); break; case MODIFY_EPS_BEARER_CONTEXT_REQUEST: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", MODIFY_EPS_BEARER_CONTEXT_REQUEST_VAL_XML_STR); break; case MODIFY_EPS_BEARER_CONTEXT_ACCEPT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", MODIFY_EPS_BEARER_CONTEXT_ACCEPT_VAL_XML_STR); break; case MODIFY_EPS_BEARER_CONTEXT_REJECT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", MODIFY_EPS_BEARER_CONTEXT_REJECT_VAL_XML_STR); break; case DEACTIVATE_EPS_BEARER_CONTEXT_REQUEST: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", DEACTIVATE_EPS_BEARER_CONTEXT_REQUEST_VAL_XML_STR); break; case DEACTIVATE_EPS_BEARER_CONTEXT_ACCEPT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", DEACTIVATE_EPS_BEARER_CONTEXT_ACCEPT_VAL_XML_STR); break; case PDN_CONNECTIVITY_REQUEST: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", PDN_CONNECTIVITY_REQUEST_VAL_XML_STR); break; case PDN_CONNECTIVITY_REJECT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", PDN_CONNECTIVITY_REJECT_VAL_XML_STR); break; case PDN_DISCONNECT_REQUEST: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", PDN_DISCONNECT_REQUEST_VAL_XML_STR); break; case PDN_DISCONNECT_REJECT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", PDN_DISCONNECT_REJECT_VAL_XML_STR); break; case BEARER_RESOURCE_ALLOCATION_REQUEST: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", BEARER_RESOURCE_ALLOCATION_REQUEST_VAL_XML_STR); break; case BEARER_RESOURCE_ALLOCATION_REJECT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s",BEARER_RESOURCE_ALLOCATION_REJECT_VAL_XML_STR); break; case BEARER_RESOURCE_MODIFICATION_REQUEST: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", BEARER_RESOURCE_MODIFICATION_REQUEST_VAL_XML_STR); break; case BEARER_RESOURCE_MODIFICATION_REJECT: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", BEARER_RESOURCE_MODIFICATION_REJECT_VAL_XML_STR); break; case ESM_INFORMATION_REQUEST: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", ESM_INFORMATION_REQUEST_VAL_XML_STR); break; case ESM_INFORMATION_RESPONSE: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", ESM_INFORMATION_RESPONSE_VAL_XML_STR); break; case ESM_STATUS: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "%s", ESM_STATUS_VAL_XML_STR); break; default: XML_WRITE_FORMAT_ELEMENT(writer, MESSAGE_TYPE_XML_STR, "0x%x", *messagetype); } }
maxxcs/swc
crates/swc/tests/tsc-references/expressions/binaryOperators/comparisonOperator/comparisonOperatorWithOneOperandIsNull/input.ts/es5.1.normal/output.js
var E; (function(E) { E[E["a"] = 0] = "a"; E[E["b"] = 1] = "b"; E[E["c"] = 2] = "c"; })(E || (E = { })); function foo(t) { var foo_r1 = t < null; var foo_r2 = t > null; var foo_r3 = t <= null; var foo_r4 = t >= null; var foo_r5 = t == null; var foo_r6 = t != null; var foo_r7 = t === null; var foo_r8 = t !== null; var foo_r1 = null < t; var foo_r2 = null > t; var foo_r3 = null <= t; var foo_r4 = null >= t; var foo_r5 = null == t; var foo_r6 = null != t; var foo_r7 = null === t; var foo_r8 = null !== t; } var a; var b; var c; var d; var e; var f; var g; // operator < var r1a1 = null < a; var r1a2 = null < b; var r1a3 = null < c; var r1a4 = null < d; var r1a5 = null < e; var r1a6 = null < f; var r1a7 = null < g; var r1b1 = a < null; var r1b2 = b < null; var r1b3 = c < null; var r1b4 = d < null; var r1b5 = e < null; var r1b6 = f < null; var r1b7 = g < null; // operator > var r2a1 = null > a; var r2a2 = null > b; var r2a3 = null > c; var r2a4 = null > d; var r2a5 = null > e; var r2a6 = null > f; var r2a7 = null > g; var r2b1 = a > null; var r2b2 = b > null; var r2b3 = c > null; var r2b4 = d > null; var r2b5 = e > null; var r2b6 = f > null; var r2b7 = g > null; // operator <= var r3a1 = null <= a; var r3a2 = null <= b; var r3a3 = null <= c; var r3a4 = null <= d; var r3a5 = null <= e; var r3a6 = null <= f; var r3a7 = null <= g; var r3b1 = a <= null; var r3b2 = b <= null; var r3b3 = c <= null; var r3b4 = d <= null; var r3b5 = e <= null; var r3b6 = f <= null; var r3b7 = g <= null; // operator >= var r4a1 = null >= a; var r4a2 = null >= b; var r4a3 = null >= c; var r4a4 = null >= d; var r4a5 = null >= e; var r4a6 = null >= f; var r4a7 = null >= g; var r4b1 = a >= null; var r4b2 = b >= null; var r4b3 = c >= null; var r4b4 = d >= null; var r4b5 = e >= null; var r4b6 = f >= null; var r4b7 = g >= null; // operator == var r5a1 = null == a; var r5a2 = null == b; var r5a3 = null == c; var r5a4 = null == d; var r5a5 = null == e; var r5a6 = null == f; var r5a7 = null == g; var r5b1 = a == null; var r5b2 = b == null; var r5b3 = c == null; var r5b4 = d == null; var r5b5 = e == null; var r5b6 = f == null; var r5b7 = g == null; // operator != var r6a1 = null != a; var r6a2 = null != b; var r6a3 = null != c; var r6a4 = null != d; var r6a5 = null != e; var r6a6 = null != f; var r6a7 = null != g; var r6b1 = a != null; var r6b2 = b != null; var r6b3 = c != null; var r6b4 = d != null; var r6b5 = e != null; var r6b6 = f != null; var r6b7 = g != null; // operator === var r7a1 = null === a; var r7a2 = null === b; var r7a3 = null === c; var r7a4 = null === d; var r7a5 = null === e; var r7a6 = null === f; var r7a7 = null === g; var r7b1 = a === null; var r7b2 = b === null; var r7b3 = c === null; var r7b4 = d === null; var r7b5 = e === null; var r7b6 = f === null; var r7b7 = g === null; // operator !== var r8a1 = null !== a; var r8a2 = null !== b; var r8a3 = null !== c; var r8a4 = null !== d; var r8a5 = null !== e; var r8a6 = null !== f; var r8a7 = null !== g; var r8b1 = a !== null; var r8b2 = b !== null; var r8b3 = c !== null; var r8b4 = d !== null; var r8b5 = e !== null; var r8b6 = f !== null; var r8b7 = g !== null;
AllaMaevskaya/AliRoot
HLT/TRD/AliHLTTRDUtils.h
// $Id$ #ifndef ALIHLTTRDUTILS_H #define ALIHLTTRDUTILS_H //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* See cxx source for full Copyright notice * //////////////////////////////////////////////////////////////////////////// // // // HLT TRD Utillities Class // // // //////////////////////////////////////////////////////////////////////////// #include "AliHLTDataTypes.h" #include "TObject.h" //#include "AliHLTProcessor.h" class TClonesArray; class AliESDEvent; class AliTRDtransform; class AliHLTTRDUtils { public: virtual ~AliHLTTRDUtils(){} static AliHLTUInt32_t AddClustersToOutput(const TClonesArray *const inClusterArray, AliHLTUInt8_t *const outBlockPtr, Int_t nTimeBins=24); static AliHLTUInt32_t AddTracksToOutput(const TClonesArray *const inTrackArray, AliHLTUInt8_t *const output, Int_t nTimeBins=24); static AliHLTUInt32_t ReadClusters(TClonesArray *const outArray, const void *const inputPtr, AliHLTUInt32_t size, Int_t* nTimeBins=0x0); static AliHLTUInt32_t ReadTracks(TClonesArray *const outArray, const void *const inputPtr, AliHLTUInt32_t size, Int_t* nTimeBins=0x0); static AliHLTUInt32_t AddESDToOutput(const AliESDEvent* const esd, AliHLTUInt8_t* const outBlockPtr); static void EmulateHLTClusters(TClonesArray *clusterArray); static void EmulateHLTTracks(TClonesArray *trackArray); static AliHLTUInt32_t GetSM(AliHLTUInt32_t spec); static AliHLTUInt32_t AddTracksToOutputAlt(const TClonesArray *const inTrackArray, AliHLTUInt8_t *const output, Int_t nTimeBins=24); static AliHLTUInt32_t ReadTracksAlt(TClonesArray *const outArray, const void *const inputPtr, AliHLTUInt32_t size, Int_t* nTimeBins=0x0); ClassDef(AliHLTTRDUtils, 0) }; #endif
uktrade/export-opportunities
lib/modules/devise_user_methods.rb
# To allow us to create and delete users we include these devise methods: # https://github.com/plataformatec/devise/wiki/How-To:-Override-confirmations-so-users-can-pick-their-own-passwords-as-part-of-confirmation-activation # https://github.com/plataformatec/devise/wiki/How-to:-Soft-delete-a-user-when-user-deletes-account module DeviseUserMethods # new function to set the password without knowing the current # password used in our confirmation controller. def attempt_set_password(params) p = {} p[:password] = params[:password] p[:password_confirmation] = params[:password_confirmation] update(p) end # new function to return whether a password has been set def no_password? encrypted_password.blank? end # Devise::Models:unless_confirmed` method doesn't exist in Devise 2.0.0 anymore. # Instead you should use `pending_any_confirmation`. def only_if_unconfirmed pending_any_confirmation { yield } end def password_match? errors[:password] << "<PASSWORD>" if password.blank? errors[:password_confirmation] << "can't be blank" if password_confirmation.blank? errors[:password_confirmation] << 'does not match password' if password != password_confirmation password == password_confirmation && password.present? end # instead of deleting, indicate the user requested a delete & timestamp it def soft_delete update_attribute(:deactivated_at, Time.current) end # ensure user account is active def active_for_authentication? super && !deactivated_at? end # provide a custom message for a deleted account def inactive_message !deactivated_at? ? super : :deleted_account end end
L-Net-1992/Paddle
paddle/infrt/dialect/tensorrt/convert.h
<filename>paddle/infrt/dialect/tensorrt/convert.h<gh_stars>10-100 // 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. #pragma once #include <glog/logging.h> #include <llvm/Support/ErrorHandling.h> #include <mlir/IR/Attributes.h> #include <mlir/IR/Builders.h> #include <mlir/IR/BuiltinAttributes.h> #include <mlir/IR/PatternMatch.h> #include <mlir/Transforms/DialectConversion.h> #include "paddle/infrt/dialect/infrt/common/types.h" #include "paddle/infrt/dialect/infrt/ir/infrt_dialect.h" #include "paddle/infrt/dialect/pd/ir/pd_ops.h" #include "paddle/infrt/dialect/phi/ir/infrt_phi_tensor.h" #include "paddle/infrt/dialect/tensorrt/trt_ops.h" #include "paddle/infrt/kernel/tensorrt/trt_helper.h" namespace infrt { namespace trt { #ifdef INFRT_WITH_TRT #define STRING_TO_ENUM_TYPE(enum_type) enum_type #define STRING_TO_ENUM_VALUE(enum_value) enum_value #include <NvInfer.h> #else // INFRT_WITH_TRT #define STRING_TO_ENUM_TYPE(enum_type) std::string #define STRING_TO_ENUM_VALUE(enum_value) #enum_value #endif // INFRT_WITH_TRT template <typename T> ::mlir::IntegerAttr createNvinferEnumAttr( ::mlir::PatternRewriter &rewriter, // NOLINT T enum_value) { return rewriter.getSI32IntegerAttr((int32_t)enum_value); } template <> ::mlir::IntegerAttr createNvinferEnumAttr<std::string>( ::mlir::PatternRewriter &rewriter, std::string enum_value) { // NOLINT (void)enum_value; return rewriter.getSI32IntegerAttr(-1); } static mlir::Value createTRTConv2dOp(mlir::PatternRewriter &rewriter, // NOLINT mlir::Operation *op, mlir::Value input, mlir::Value filter) { auto conv_op = ::llvm::dyn_cast<infrt::pd::Conv2dOp>(op); ::mlir::SmallVector<::mlir::Value, 4> operands; operands.push_back(input); operands.push_back(filter); ::mlir::SmallVector<::mlir::Type, 4> resultTypes; for (auto v : conv_op.getODSResults(0)) { resultTypes.push_back(v.getType()); } ::mlir::SmallVector<::mlir::NamedAttribute, 8> attributes; auto *filter_producer = filter.getDefiningOp(); auto create_inited_tensor_op = llvm::dyn_cast<::infrt::phi::CreateHostInitedDenseTensorOp>( filter_producer); CHECK_NOTNULL(create_inited_tensor_op); mlir::ArrayAttr dims = create_inited_tensor_op.dims(); CHECK_EQ(dims.size(), 4U); CHECK(dims[0].getType().isIntOrIndex()); const int32_t n_output = dims[0].cast<mlir::IntegerAttr>().getInt(); const int32_t filter_h = dims[2].cast<mlir::IntegerAttr>().getInt(); const int32_t filter_w = dims[3].cast<mlir::IntegerAttr>().getInt(); auto padding_attr = conv_op->getAttrOfType<::mlir::ArrayAttr>("paddings"); llvm::SmallVector<int32_t, 4> paddings(padding_attr.size()); for (size_t i = 0; i < padding_attr.size(); i++) { paddings[i] = padding_attr[i].cast<mlir::IntegerAttr>().getInt(); } auto dilations_attr = conv_op->getAttrOfType<::mlir::ArrayAttr>("dilations"); llvm::SmallVector<int32_t> dilations(dilations_attr.size()); for (size_t i = 0; i < dilations_attr.size(); i++) { dilations[i] = dilations_attr[i].cast<mlir::IntegerAttr>().getInt(); } llvm::SmallVector<int32_t, 2> nv_paddings(2); llvm::SmallVector<int32_t, 4> nv_pre_paddings(2); llvm::SmallVector<int32_t, 4> nv_post_paddings(2); llvm::SmallVector<int32_t, 2> nv_dilations({dilations[0], dilations[1]}); int32_t nv_padding_mode = 0; // nvinfer1::PaddingMode::kEXPLICIT_ROUND_DOWN auto padding_algorithm_attr = conv_op->getAttrOfType<::mlir::StringAttr>("padding_algorithm"); if (padding_algorithm_attr.strref() == "VALID") { for (size_t i = 0; i < paddings.size(); i++) { paddings[i] = 0; } } if (padding_algorithm_attr.strref() == "SAME") { nv_padding_mode = 2; // nvinfer1::PaddingMode::kSAME_UPPER nv_dilations[0] = 1; nv_dilations[1] = 1; } if (paddings.size() == 2) { nv_paddings[0] = paddings[0]; nv_paddings[1] = paddings[1]; } else { CHECK_EQ(paddings.size(), 4U); nv_pre_paddings[0] = paddings[0]; nv_pre_paddings[1] = paddings[2]; nv_post_paddings[0] = paddings[1]; nv_post_paddings[1] = paddings[3]; } attributes.emplace_back(rewriter.getStringAttr("out_channel_num"), rewriter.getSI32IntegerAttr(n_output)); attributes.emplace_back(rewriter.getStringAttr("kernel_size"), rewriter.getI32ArrayAttr({filter_h, filter_w})); attributes.emplace_back( rewriter.getStringAttr("dilations"), rewriter.getI32ArrayAttr({nv_dilations[0], nv_dilations[1]})); attributes.emplace_back(rewriter.getStringAttr("padding_mode"), rewriter.getSI32IntegerAttr(nv_padding_mode)); attributes.emplace_back(rewriter.getStringAttr("paddings"), rewriter.getI32ArrayAttr({paddings[0], paddings[1]})); attributes.emplace_back( rewriter.getStringAttr("pre_paddings"), rewriter.getI32ArrayAttr({nv_pre_paddings[0], nv_pre_paddings[1]})); attributes.emplace_back( rewriter.getStringAttr("post_paddings"), rewriter.getI32ArrayAttr({nv_post_paddings[0], nv_post_paddings[1]})); { auto tblgen_attr = conv_op->getAttrOfType<::mlir::IntegerAttr>("groups"); attributes.emplace_back(rewriter.getStringAttr("groups"), tblgen_attr); } { auto tblgen_attr = conv_op->getAttrOfType<::mlir::ArrayAttr>("strides"); attributes.emplace_back(rewriter.getStringAttr("strides"), tblgen_attr); } return rewriter.create<trt::ConvolutionOp>( conv_op->getLoc(), resultTypes, operands, attributes); } static inline mlir::ArrayAttr TransposeWeight( mlir::PatternRewriter &builder, // NOLINT const mlir::ArrayAttr &weight, const mlir::ArrayAttr &dims) { CHECK_EQ(dims.size(), 2U); CHECK(!dims.empty()); CHECK(dims[0].getType().isInteger(64)); CHECK(!weight.empty()); CHECK(weight[0].getType().isF32()); int row = dims[0].cast<mlir::IntegerAttr>().getInt(); int col = dims[1].cast<mlir::IntegerAttr>().getInt(); std::vector<float> trans_weight(weight.size()); for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { trans_weight[j * row + i] = weight[i * col + j].cast<mlir::FloatAttr>().getValueAsDouble(); } } return builder.getF32ArrayAttr(trans_weight); } // matmul_y and elt_y is weights. inline ::llvm::SmallVector<::mlir::Value, 4> createTrtFcOp( mlir::PatternRewriter &builder, // NOLINT mlir::Value matmul_x, mlir::Value matmul_y, mlir::Value elt_y, mlir::Value elt_out) { ::llvm::SmallVector<::mlir::Operation *, 4> tblgen_ops; auto *y_producer = matmul_y.getDefiningOp(); auto create_inited_tensor_op = llvm::dyn_cast<::infrt::phi::CreateHostInitedDenseTensorOp>(y_producer); CHECK_NOTNULL(create_inited_tensor_op); mlir::ArrayAttr dims = create_inited_tensor_op.dims(); CHECK_EQ(dims.size(), 2U); std::vector<int64_t> new_dims(dims.size()); CHECK(!dims.empty()); CHECK(dims[0].getType().isIntOrIndex()); for (size_t i = 0; i < new_dims.size(); ++i) { new_dims[i] = dims[dims.size() - 1 - i].cast<mlir::IntegerAttr>().getInt(); } auto insert_point = builder.saveInsertionPoint(); builder.setInsertionPoint(create_inited_tensor_op); auto new_inited_op = builder.create<::infrt::phi::CreateHostInitedDenseTensorOp>( create_inited_tensor_op->getLoc(), create_inited_tensor_op.output().getType(), create_inited_tensor_op.context(), builder.getI64ArrayAttr(new_dims), ::infrt::LayoutAttr::get(builder.getContext(), ::infrt::LayoutType::NCHW), create_inited_tensor_op.lod(), TransposeWeight(builder, create_inited_tensor_op.values(), dims)); builder.replaceOp(create_inited_tensor_op, new_inited_op->getResults()); builder.restoreInsertionPoint(insert_point); auto ods_loc = builder.getFusedLoc({y_producer->getLoc()}); ::infrt::trt::FullyConnectedOp fc_op; { ::mlir::SmallVector<::mlir::Type, 4> tblgen_types; fc_op = builder.create<::infrt::trt::FullyConnectedOp>( ods_loc, elt_out.getType(), matmul_x, new_inited_op.output(), elt_y, builder.getSI32IntegerAttr(new_dims[0])); } ::llvm::SmallVector<::mlir::Value, 4> tblgen_repl_values; for (auto v : ::llvm::SmallVector<::mlir::Value, 4>{fc_op.getODSResults(0)}) { tblgen_repl_values.push_back(v); } return tblgen_repl_values; } inline mlir::IntegerAttr CreatePoolingType( mlir::PatternRewriter &builder, // NOLINT mlir::StringAttr pool_type) { // pool_type. auto ptype = pool_type.str(); if (ptype == "max") { return createNvinferEnumAttr(builder, nvinfer1::PoolingType::kMAX); } else if (ptype == "avg") { return createNvinferEnumAttr(builder, nvinfer1::PoolingType::kAVERAGE); } else { llvm_unreachable("unknown pool_type."); return {}; } } inline mlir::IntegerAttr CreatePaddingMode( mlir::PatternRewriter &builder, // NOLINT mlir::StringAttr padding_algorithm, mlir::BoolAttr ceil_mode) { // TODO(Inference): Phi pool kernel seems not process ceil_mode. auto padding_algo = padding_algorithm.str(); if (padding_algo == "SAME") { return createNvinferEnumAttr(builder, nvinfer1::PaddingMode::kSAME_UPPER); } if (ceil_mode.getValue() && padding_algo != "SAME") { return createNvinferEnumAttr(builder, nvinfer1::PaddingMode::kEXPLICIT_ROUND_UP); } else { return createNvinferEnumAttr(builder, nvinfer1::PaddingMode::kEXPLICIT_ROUND_DOWN); } } inline ::llvm::SmallVector<::mlir::Value, 4> CreatePaddleTrtPoolingOp( mlir::PatternRewriter &builder, // NOLINT mlir::Value input, mlir::StringAttr pool_type, mlir::ArrayAttr ksize, mlir::BoolAttr global_pooling, mlir::ArrayAttr strides, mlir::ArrayAttr paddings, mlir::BoolAttr exclusive, mlir::BoolAttr adaptive, mlir::BoolAttr ceil_mode, mlir::StringAttr data_format, mlir::StringAttr padding_algorithm) { ::llvm::SmallVector<::mlir::Value, 4> tblgen_repl_values; // TODO(inference): Support NHWC. if (data_format.str() != "NCHW") { CHECK(false) << "The pool2d converter now only support NCHW."; } // TODO(Wilber): How to support dynamic shape? auto *input_producer = input.getDefiningOp(); // Process pool_type. auto pool_type_attr = CreatePoolingType(builder, pool_type); // Update padding. auto padding_algorithm_str = padding_algorithm.str(); auto paddings_attr = paddings; if (padding_algorithm_str == "EXPLICIT") { // Do nothing on paddings. } else if (padding_algorithm_str == "SAME") { // We should process this case in trt network build phase. } else if (padding_algorithm_str == "VALID") { // Set padding to zero. paddings_attr = builder.getI32ArrayAttr({0, 0}); } else { CHECK(false) << "Unknown padding_algotithm."; } // if global_pooling == true or adaptive == true, padding will be ignored // if (global_pooling.getValue() || adaptive.getValue()) { // paddings_attr = builder.getI32ArrayAttr({0, 0}); // } // if global_pooling == true, then we should update kernel size to input dims. if (global_pooling.getValue() == true) { // Update ksize to input dims. } // The adaptive logic should be processed when we get the context of // INetworkDefinition, so we place the logic in infrt runtime(trt compile // time). // The `exclusive` may be a naive attr, which can be forward to trt. auto padding_mode_attr = CreatePaddingMode(builder, padding_algorithm, ceil_mode); if (global_pooling.getValue() == true) { CHECK(false) << "Temporarily not support global_pool"; return tblgen_repl_values; } PoolingOp pool_op; { auto ods_loc = builder.getFusedLoc({input_producer->getLoc()}); pool_op = builder.create<PoolingOp>(ods_loc, input.getType(), input, pool_type_attr, ksize, strides, paddings_attr, padding_mode_attr, exclusive, adaptive, padding_algorithm); } for (auto v : ::llvm::SmallVector<::mlir::Value, 4>{pool_op.getODSResults(0)}) { tblgen_repl_values.push_back(v); } return tblgen_repl_values; } } // namespace trt } // namespace infrt
qwelao7/afgj
mobile/web/weixin/src/js/lib/library.js
<filename>mobile/web/weixin/src/js/lib/library.js var common = require('../lib/common.js'); $(function () { var content = $('#content'), popup = $('#popup'), classify = $('#classify').html(), tpl = $('#tpl').html(), tabBottom = $('.buttons-tab'); var url = common.getRequest(), searchText = window.localStorage.getItem('library_search_text'), href = window.location.href, category = url.category, sort = ['1', '2', '3'], keywords = url.q, showSort, // 1-评价 2-借阅数 2-距离 issearch, params = {}; var loading = false, num = 2, nums; var lat, long; /** * 点击tag标签 **/ $(document).on('click', '#tag', function () { return false; $('#popup').css('display', 'block'); $('#modal').toggleClass('modal-overlay-visible'); }); $(document).on('click', '#modal', function () { return false; hideModel(); }); /** * 选择图书类型 */ $(document).on('click', '.modal-p-list', function() { var _this = $(this), text = $.trim(_this.text()); category = _this.data('id'); //当前选中 $('.modal-p-list').removeClass('font-green'); _this.addClass('font-green'); //赋值内容 $('.title-search-span').find('span').html(text); hideModel(); }); /*** * 搜索图书 */ $(document).on('click', '#search', function() { searchHandler(); }); /** * 切换tab页 */ $(document).on('click', '.tab-link', function() { var self = $(this), key = self.index(); issearch = tabBottom.data('issearch'); if (!issearch) { window.location.href = 'library-book-list.html?id=' + url.id + '&type=' + key; } else { $('.tab-link').removeClass('active'); self.addClass('active'); num = 2; searchAll(); } }); /** * 无限滚动 */ $(document).on('infinite', '.infinite-scroll', function () { nums = tabBottom.data('nums'); issearch = tabBottom.data('issearch'); showSort = $('.tab-link.active').index(); if (!issearch) { url.id && scrollerLocal(); !url.id && scrollerAll(); } else { url.id && scrollerLocalSearch(); !url.id && scrollerAllSearch(); } }); /** * 所有书架搜索 */ function searchAll() { showSort = $('.tab-link.active').index(); $('.infinite-scroll-preloader').show(); $('#init').addClass('hide'); $('#container').removeClass('hide'); common.ajax('GET', '/library/search-list', { 'book_name': keywords, 'book_type': category, 'sort': sort[showSort], 'longitude': long, 'latitude': lat }, true, function(rsp) { content.empty(); if (rsp.data.code == 0) { var data = rsp.data.info; if (data.list.length < 1) { renderTips();return false; } data.classify = sort[showSort]; var html = juicer(tpl, data); content.append(html); //参数初始 nums = data.pagination.pageCount; if (nums == 1) { // 删除加载提示符 $('.infinite-scroll-preloader').hide(); } tabBottom[0].setAttribute('data-nums', nums); num = 2; loading = false; } else { renderTips(); } }) } /** * 未搜索时的滚动 (本书架) */ function scrollerLocal() { if (loading) return; loading = true; if (num > nums) { // 删除加载提示符 $('.infinite-scroll-preloader').hide(); return; } common.ajax('GET', '/library/book-list', { 'library_id': url.id, 'sort': sort[showSort], 'page': num }, true, function (rsp) { if (rsp.data.code == 0) { loading = false; var data = rsp.data.info; data.classify = sort[showSort]; var htm = juicer(tpl, data); content.append(htm); num++; } }); $.refreshScroller(); } /** * 搜索时 所有书架 列表 */ function scrollerAllSearch() { if (loading) return; loading = true; if (num > nums) { // 删除加载提示符 $('.infinite-scroll-preloader').hide(); return; } common.ajax('GET', '/library/search-list', { 'book_name': keywords, 'book_type': category, 'sort': sort[showSort], 'longitude': long, 'latitude': lat, 'page': num }, true, function (rsp) { if (rsp.data.code == 0) { loading = false; var data = rsp.data.info; data.classify = sort[showSort]; var htm = juicer(tpl, data); content.append(htm); num++; } }); $.refreshScroller(); } /** * render tips */ function renderTips() { var template = "<h3 style='text-align: center;margin-top: 4rem;'>很抱歉,暂无书本信息!</h3>"; content.append(template); $('.infinite-scroll-preloader').hide(); } /** 隐藏弹出层 **/ function hideModel() { $('#popup').css('display', 'none'); $('#modal').toggleClass('modal-overlay-visible'); $('.actions-modal').addClass('modal-out'); setTimeout(function() { $('.actions-modal').remove(); }, 200) } /** * 搜索事件 */ function searchHandler() { var _this = $('input[name=search]'); keywords = $.trim(_this.val()); if (keywords == '') { $.alert('请输入您要搜索的书籍名!', '搜索失败'); return false; } //保存搜索历史 common.saveStorageLimit('library_search_log', 10, keywords); //保存当前搜索的图书分类和关键词 params.category = category; params.keywords = keywords; localStorage.setItem('curBookSearch', JSON.stringify(params)); $('.buttons-tab')[0].setAttribute('data-issearch', true); searchAll(); } /** 获取微信配置 **/ function getConfig() { common.ajax('POST', '/wechat/config', {href: href}, true, function (rsp) { if (rsp.data.code == 0) { var data = rsp.data.info; data = JSON.parse(data); wx.config({ debug: false, appId: data.appId, timestamp: data.timestamp, nonceStr: data.nonceStr, signature: data.signature, jsApiList: [ 'getLocation' ] }); wx.ready(function() { getLocation(); }) } else { $.alert('获取配置信息失败!'); } }) } /** * 调用地址接口 */ function getLocation() { wx.getLocation({ type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02' success: function (res) { lat = res.latitude; // 纬度,浮点数,范围为90 ~ -90 long = res.longitude; // 经度,浮点数,范围为180 ~ -180。 !url.id && searchHandler(); }, error: function(error) { $.alert('很抱歉,当前无法获取您的位置信息,请重试!', '获取数据失败', function() { location.reload(); }) } }); } /** * 图书类别 */ function loadData() { common.ajax('GET', '/library/guess-you-search', {}, true, function(rsp) { if (rsp.data.code == 0) { var data = rsp.data.info; var htm = juicer(classify, data); popup.append(htm); if (category == 0) { $('#curCategory').text('所有图书'); } else { $('#curCategory').text(data['book_type'][category]); } } }); } getConfig(); !url.id && loadData(); });
axelav/vx
packages/vx-mock-data/src/index.js
export { default as genDateValue } from './generators/genDateValue'; export { default as genRandomNormalPoints, } from './generators/genRandomNormalPoints'; export { default as genBin } from './generators/genBin'; export { default as genBins } from './generators/genBins'; export { default as genStats } from './generators/genStats'; export { default as appleStock } from './mocks/appleStock'; export { default as letterFrequency } from './mocks/letterFrequency'; export { default as browserUsage } from './mocks/browserUsage'; export { default as groupDateValue } from './mocks/groupDateValue'; export { default as cityTemperature } from './mocks/cityTemperature'; export { default as lesMiserables } from './mocks/lesMiserables'; export { default as exoplanets } from './mocks/exoplanets'; export { default as planets } from './mocks/planets'; export { default as shakespeare } from './mocks/shakespeare';
mizne/meishang_app_shangjia
cordova-plugin-sxb/src/android/suixinbo/adapters/LinkAdapter.java
package com.tencent.qcloud.suixinbo.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.TextView; import com.tencent.ilivesdk.core.ILiveLoginManager; import com.tencent.ilivesdk.core.ILiveRoomManager;; import com.tencent.livesdk.ILVLiveManager; import com.baizhanke.store.R; import com.tencent.qcloud.suixinbo.model.RoomInfoJson; import com.tencent.qcloud.suixinbo.presenters.LiveListViewHelper; import com.tencent.qcloud.suixinbo.presenters.UserServerHelper; import com.tencent.qcloud.suixinbo.presenters.viewinface.LiveListView; import com.tencent.qcloud.suixinbo.utils.SxbLog; import com.tencent.qcloud.suixinbo.utils.UIUtils; import java.util.ArrayList; import java.util.List; /** * 跨房连麦 */ public class LinkAdapter extends BaseAdapter implements LiveListView { public interface OnItemClick{ void onClick(RoomInfoJson info); } private static String TAG = "LinkAdapter"; private Context mContext; private LiveListViewHelper helper; private OnItemClick mItemListener = null; private ArrayList<RoomInfoJson> mRoomList = null; private class ViewHolder{ TextView tvTitle; TextView tvId; Button btnLink; } public LinkAdapter(Context context) { mContext = context; helper = new LiveListViewHelper(this); helper.getPageData(); } @Override public int getCount() { return null!=mRoomList ? mRoomList.size() : 0; } @Override public Object getItem(int i) { return null!=mRoomList&&i<mRoomList.size() ? mRoomList.get(i) : null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView != null) { holder = (ViewHolder)convertView.getTag(); } else { convertView = LayoutInflater.from(mContext).inflate(R.layout.item_link_info, null); holder = new ViewHolder(); holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title); holder.tvId = (TextView) convertView.findViewById(R.id.tv_id); holder.btnLink = (Button) convertView.findViewById(R.id.btn_link); convertView.setTag(holder); } if (null != mRoomList && mRoomList.size() > position) { final RoomInfoJson info = mRoomList.get(position); holder.tvTitle.setText(UIUtils.getLimitString(info.getInfo().getTitle(), 10)); holder.tvId.setText(info.getHostId()+"("+info.getInfo().getRoomnum()+")"); List<String> linkedList = ILVLiveManager.getInstance().getCurrentLinkedUserArray(); if (linkedList.contains(info.getHostId()) || ILiveLoginManager.getInstance().getMyUserId().equals(info.getHostId())){ holder.btnLink.setVisibility(View.INVISIBLE); }else{ holder.btnLink.setVisibility(View.VISIBLE); holder.btnLink.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (null != mItemListener){ mItemListener.onClick(info); } } }); } } if (null != mRoomList){ SxbLog.d(TAG, "position: "+position+"/"+mRoomList.size()); } return convertView; } @Override public void showRoomList(UserServerHelper.RequestBackInfo result, ArrayList<RoomInfoJson> roomlist) { if (0 == result.getErrorCode()){ mRoomList = roomlist; notifyDataSetChanged(); SxbLog.d(TAG, "showRoomList->size::"+roomlist.size()); }else{ SxbLog.d(TAG, "showRoomList->result:"+result.getErrorCode()+"|"+result.getErrorInfo()); } } public void setOnItemClickListenr(OnItemClick listener){ mItemListener = listener; } }
sunyuyangg555/STAX
plugins/xfs/src/main/java/io/jiffy/stax/plugin/xfs/actions/XfsExecuteCommandAction.java
<reponame>sunyuyangg555/STAX package io.jiffy.stax.plugin.xfs.actions; import com.ibm.staf.service.stax.STAXAction; import com.ibm.staf.service.stax.STAXPythonEvaluationException; import com.ibm.staf.service.stax.STAXThread; import org.apache.commons.lang3.StringUtils; import org.pmw.tinylog.Logger; import java.util.List; import java.util.stream.Collectors; public abstract class XfsExecuteCommandAction extends XfsCommandAction { private String events; public abstract String getParameter(); public abstract void setParameter(String param); public abstract String createCommand(); protected String handleEvents(STAXThread thread) throws STAXPythonEvaluationException { Logger.info("events = {}", events); if(StringUtils.isEmpty(events)) { return ""; } List<String> eventList = thread.pyListEval(events); return eventList.size() > 0 ? eventList.stream().map(e -> " events " + e).collect(Collectors.joining()) : ""; } public void setEvents(String events) { this.events = events; } public String getEvents() { return events; } }
lonfall/leetcode_learning
src/main/java/com/lh/learning/leetcode/no71_80/no78/Question78.java
<filename>src/main/java/com/lh/learning/leetcode/no71_80/no78/Question78.java<gh_stars>1-10 package com.lh.learning.leetcode.no71_80.no78; import java.util.ArrayList; import java.util.List; /** * @auther: loneyfall * @date: 2021/9/9 * @description: 子集 */ public class Question78 { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> result = new ArrayList<List<Integer>>(); List<Integer> subsets = new ArrayList<Integer>(); findSubsets(nums, -1, subsets, result); return result; } private void findSubsets(int[] nums, int prev, List<Integer> subsets, List<List<Integer>> result) { List<Integer> subset = new ArrayList<Integer>(subsets); result.add(subset); for (int i = prev + 1; i < nums.length; i++) { subsets.add(nums[i]); findSubsets(nums, i, subsets, result); subsets.remove(subsets.size() - 1); } } }
bobmotor/magento-2-gulp
dev/tools/gulp/tasks/exec.js
<reponame>bobmotor/magento-2-gulp const exec = require('exec-queue'); const args = require('../args'); const loggers = require('../loggers'); const matchTheme = require('../matchTheme'); const paths = require('../paths'); module.exports = async () => { if (!matchTheme.matchTheme) { loggers.matchTheme(args.themeName, matchTheme.avaliablePackages); } else { let task = 'exec'; loggers.task(task, paths.execPaths); paths.execPaths.forEach(execOptions => { exec(`${execOptions}`, (err, stdout, stderr) => { console.log(stdout); console.log(stderr); }); }); } };
GustavoGalo/discord-bot-1
ffmpeg/libavcodec/mips/xvididct_init_mips.c
/* * Copyright (c) 2015 <NAME> <<EMAIL>> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/attributes.h" #include "libavutil/mips/cpu.h" #include "xvididct_mips.h" av_cold void ff_xvid_idct_init_mips(IDCTDSPContext *c, AVCodecContext *avctx, unsigned high_bit_depth) { int cpu_flags = av_get_cpu_flags(); if (have_mmi(cpu_flags)) { if (!high_bit_depth) { if (avctx->idct_algo == FF_IDCT_AUTO || avctx->idct_algo == FF_IDCT_XVID) { c->idct_put = ff_xvid_idct_put_mmi; c->idct_add = ff_xvid_idct_add_mmi; c->idct = ff_xvid_idct_mmi; c->perm_type = FF_IDCT_PERM_NONE; } } } }
chenhaoxiang/superior-java-blogs
src/main/java/com/huijava/superiorjavablogs/dto/UsersDTO.java
<gh_stars>1-10 /** * fshows.com * Copyright (C) 2013-2018 All Rights Reserved. */ package com.huijava.superiorjavablogs.dto; import com.huijava.superiorjavablogs.common.base.BaseEntity; import lombok.Data; /** * @author chenhx * @version UsersDTO.java, v 0.1 2018-09-20 上午 2:14 */ @Data public class UsersDTO extends BaseEntity { /** * 用户名 */ private String username; /** * 电子邮箱 */ private String email; /** * 状态 0-正常 1-逻辑删除 */ private Byte status; /** * 用户的主页url */ private String homeUrl; /** * 个性签名 */ private String sign; /** * 昵称 */ private String nikeName; /** * 头像地址 */ private String headImage; /** * 贡献点 */ private Long contributeCount; /** * 贡献权重 - 贡献度 - 相当于累计的贡献点 */ private Long contributeWeight; /** * 粉丝数 */ private Integer followersCount; }
carolbezerra-dev/bash-exercises
31.Sequelize/2.ORM/models/Product.js
<filename>31.Sequelize/2.ORM/models/Product.js // serve para alimentar com dados a tabela criada const createProduct = (sequelize, DataTypes) => { const Product = sequelize.define('Product', { /* Sequelize, estou definindo um modelo chamado Product (coloca o model no singular, ele busca a tabela no plural na migration) */ name: DataTypes.STRING, description: DataTypes.STRING, price: DataTypes.FLOAT, /* essas são as 2 colunas que são preenchidas manualmente (a outra é 'id' que é autoincremente e 'createdAt' e 'updatedAt' que são datas) */ }); return Product; } module.exports = createProduct;