repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
shoutem/extensions
shoutem.deals/server/src/modules/deals/services/validation.js
<gh_stars>100-1000 import { isURL } from 'validator'; import _ from 'lodash'; import moment from 'moment'; import i18next from 'i18next'; import { DEFAULT_START_TIME } from '../const'; import { isExpirationTimeValid } from './deal'; import LOCALIZATION from './localization'; function validateRequiredField(fieldValue) { if (!fieldValue) { return i18next.t(LOCALIZATION.VALUE_REQUIRED_MESSAGE); } return null; } function validateExpirationTime(expirationTime) { if (!expirationTime) { return i18next.t(LOCALIZATION.VALUE_REQUIRED_MESSAGE); } if (!isExpirationTimeValid(expirationTime)) { return i18next.t(LOCALIZATION.INVALID_VALUE_MESSAGE); } return null; } function validateNumericField(fieldValue) { const numberValue = _.toNumber(fieldValue); if (_.isNaN(numberValue)) { return i18next.t(LOCALIZATION.INVALID_NUMBER_MESSAGE); } return null; } function validateNumericFields(regularPrice, discountPrice) { const validation = {}; if (!!regularPrice) { validation.regularPrice = validateNumericField(regularPrice); } if (!!discountPrice) { validation.discountPrice = validateNumericField(discountPrice); } return validation; } function validateUrl(urlField) { if (urlField && !isURL(urlField)) { return i18next.t(LOCALIZATION.INVALID_URL_MESSAGE); } return null; } function validatePricing(regularPrice, discountPrice, discountType) { const validation = {}; if (discountPrice) { const hasRegularPrice = !!regularPrice; if (!hasRegularPrice) { validation.regularPrice = i18next.t( LOCALIZATION.REGULAR_PRICE_REQUIRED_WHEN_DISCOUNTED, ); } const regularPriceFloat = hasRegularPrice && parseFloat(regularPrice); const discountPriceFloat = parseFloat(discountPrice); if (hasRegularPrice && discountPriceFloat >= regularPriceFloat) { validation.discountPrice = i18next.t( LOCALIZATION.DISCOUNT_PRICE_HIGHER_THAN_REGULAR, ); } if (!discountType) { validation.discountType = i18next.t( LOCALIZATION.DISCOUNT_TYPE_REQUIRED_WHEN_DISCOUNTED, ); } } return validation; } function validateStartEndTime(startTime, endTime) { if (!endTime) { return { endTime: validateRequiredField(endTime), }; } const resolvedStartTime = !!startTime ? startTime : DEFAULT_START_TIME; const momentStartTime = moment(resolvedStartTime); const momentEndTime = moment(endTime); if (!momentStartTime.isBefore(momentEndTime)) { return { startTime: i18next.t(LOCALIZATION.INVALID_START_TIME_MESSAGE), endTime: i18next.t(LOCALIZATION.INVALID_END_TIME_MESSAGE), }; } return {}; } export function validateDeal(deal) { const { title, regularPrice, discountPrice, currency, discountType, startTime, endTime, couponsExpirationTime, couponsEnabled, buyLink, } = deal; return { title: validateRequiredField(title), currency: validateRequiredField(currency), couponsExpirationTime: couponsEnabled && validateExpirationTime(couponsExpirationTime), buyLink: validateUrl(buyLink), ...validateNumericFields(regularPrice, discountPrice), ...validatePricing(regularPrice, discountPrice, discountType), ...validateStartEndTime(startTime, endTime), }; }
nuecho/covidflow
action-server/covidflow/db/reminder.py
import copy from datetime import datetime, timedelta from typing import Any, Dict, Text import pytz import structlog from sqlalchemy import ( Boolean, CheckConstraint, Column, Date, DateTime, Integer, String, Time, case, cast, func, ) from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.ext.hybrid import hybrid_property from covidflow.constants import ( AGE_OVER_65_SLOT, FIRST_NAME_SLOT, HAS_DIALOGUE_SLOT, LANGUAGE_SLOT, METADATA_SLOT, PHONE_NUMBER_SLOT, PRECONDITIONS_SLOT, PROVINCE_SLOT, ) from .base import Base logger = structlog.get_logger() FIRST_NAME_ATTRIBUTE = "first_name" PHONE_NUMBER_ATTRIBUTE = "phone_number" LANGUAGE_ATTRIBUTE = "language" PROVINCE_ATTRIBUTE = "province" AGE_OVER_65_ATTRIBUTE = "age_over_65" PRECONDITIONS_ATTRIBUTE = "preconditions" HAS_DIALOGUE_ATTRIBUTE = "has_dialogue" TIMEZONE_METADATA_PROPERTY = "timezone" SLOT_MAPPING = { FIRST_NAME_SLOT: FIRST_NAME_ATTRIBUTE, PHONE_NUMBER_SLOT: PHONE_NUMBER_ATTRIBUTE, LANGUAGE_SLOT: LANGUAGE_ATTRIBUTE, PROVINCE_SLOT: PROVINCE_ATTRIBUTE, AGE_OVER_65_SLOT: AGE_OVER_65_ATTRIBUTE, PRECONDITIONS_SLOT: PRECONDITIONS_ATTRIBUTE, HAS_DIALOGUE_SLOT: HAS_DIALOGUE_ATTRIBUTE, } REMINDER_FREQUENCY = timedelta(days=1) def _uniformize_timezone(timezone): if timezone is None: return None try: return pytz.timezone(timezone).zone except: logger.warning( "Could not instantiate timezone. Reminder will be created without specifying timezone.", timezone=timezone, exc_info=True, ) return None class Reminder(Base): __tablename__ = "reminder" id = Column("id", Integer, primary_key=True) created_at = Column( "created_at", DateTime(timezone=True), server_default=func.current_timestamp(), nullable=False, ) last_reminded_at = Column("last_reminded_at", DateTime(timezone=True)) timezone = Column("timezone", String(), CheckConstraint("is_timezone(timezone)")) is_canceled = Column( "is_canceled", Boolean(), nullable=False, server_default="false" ) attributes = Column("attributes", JSONB, nullable=False) def __init__( self, timezone=None, id=None, created_at=None, last_reminded_at=None, is_canceled=None, attributes=dict(), ): self.id = id self.created_at = created_at self.last_reminded_at = last_reminded_at self.timezone = _uniformize_timezone(timezone) self.is_canceled = is_canceled self.attributes = copy.deepcopy(attributes) @staticmethod def create_from_slot_values(slot_values: Dict[Text, Any]): metadata = slot_values.get(METADATA_SLOT) or {} timezone = metadata.get(TIMEZONE_METADATA_PROPERTY, None) reminder = Reminder(timezone) for slot_name, attribute_name in SLOT_MAPPING.items(): reminder._set_attribute(attribute_name, slot_values.get(slot_name, None)) return reminder # For Unit tests def __eq__(self, other): if not isinstance(other, Reminder): return False if self.id != other.id: return False if self.created_at != other.created_at: return False if self.last_reminded_at != other.last_reminded_at: return False if self.timezone != other.timezone: return False if self.is_canceled != other.is_canceled: return False if self.attributes != other.attributes: return False return True def _set_attribute(self, attribute, value): if value is not None: self.attributes[attribute] = value @hybrid_property def next_reminder_due_date(self): should_have_been_last_reminded_at = ( self.created_at if self.last_reminded_at is None else datetime.combine(self.last_reminded_at.date(), self.created_at.time()) ) return should_have_been_last_reminded_at + REMINDER_FREQUENCY @next_reminder_due_date.expression # type: ignore def next_reminder_due_date(cls): return ( case( [(cls.last_reminded_at == None, cls.created_at)], else_=cast(cls.last_reminded_at, Date) + cast(cls.created_at, Time(timezone=True)), ) + REMINDER_FREQUENCY ) @property def first_name(self): return self.attributes.get(FIRST_NAME_ATTRIBUTE) @first_name.setter def first_name(self, first_name): self._set_attribute(FIRST_NAME_ATTRIBUTE, first_name) @property def phone_number(self): return self.attributes.get(PHONE_NUMBER_ATTRIBUTE) @phone_number.setter def phone_number(self, phone_number): self._set_attribute(PHONE_NUMBER_ATTRIBUTE, phone_number) @property def language(self): return self.attributes.get(LANGUAGE_ATTRIBUTE) @language.setter def language(self, language): self._set_attribute(LANGUAGE_ATTRIBUTE, language) @property def province(self): return self.attributes.get(PROVINCE_ATTRIBUTE) @province.setter def province(self, province): self._set_attribute(PROVINCE_ATTRIBUTE, province) @property def age_over_65(self): return self.attributes.get(AGE_OVER_65_ATTRIBUTE) @age_over_65.setter def age_over_65(self, age_over_65): self._set_attribute(AGE_OVER_65_ATTRIBUTE, age_over_65) @property def preconditions(self): return self.attributes.get(PRECONDITIONS_ATTRIBUTE) @preconditions.setter def preconditions(self, preconditions): self._set_attribute(PRECONDITIONS_ATTRIBUTE, preconditions) @property def has_dialogue(self): return self.attributes.get(HAS_DIALOGUE_ATTRIBUTE) @has_dialogue.setter def has_dialogue(self, has_dialogue): self._set_attribute(HAS_DIALOGUE_ATTRIBUTE, has_dialogue) def __repr__(self): items = ", ".join( [f"{k}={v}" for k, v in self.__dict__.items() if not k.startswith("_")] ) return f"{self.__class__.__name__}({items})"
efornara/cc65
samples/xv65/sys.c
<gh_stars>1-10 // sys.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "sys.h" /* These are just quick tests. A proper implementation should be written in assembly, hence the non-standard sys_ prefix. REQRES is a return code set at every request. REQERRNO is a "sticky" code that remembers the last failed return code - it can be (re)set by the program. */ sys_pid_t sys_fork(void) { req_put(REQ_FORK); req_end(); if (req_res()) return -1; return *(sys_pid_t *)REQDAT; } int __fastcall__ sys_exit(int status) { req_put(REQ_EXIT); req_put_word(status); req_end(); return req_res() ? -1 : 0; } sys_pid_t sys_wait(void) { req_put(REQ_WAIT); req_end(); if (req_res()) return -1; return *(sys_pid_t *)REQDAT; } int __fastcall__ sys_kill(sys_pid_t pid, byte sig) { req_put(REQ_KILL); req_put(sig); // optional (15 - SIGTERM is the default) *(long *)REQDAT = pid; req_end(); return req_res() ? -1 : 0; } sys_pid_t sys_getpid() { req_put(REQ_GETPID); req_end(); return *(sys_pid_t *)REQDAT; } unsigned __fastcall__ sys_sleep(unsigned seconds) { req_put(REQ_SLEEP); /* Trailing ints can be sent using 0 to 4 bytes. Value is UNSIGNED and default to 0. Example: if (seconds == 0) req_put_word(seconds); else if (seconds > 255) req_put_word(seconds); else req_put_word(seconds); */ req_put_word(seconds); req_end(); return req_res() ? *(unsigned *)REQDAT : 0; } int sys_execvp(const char *filename, char *argv[]) { static int i; req_put(REQ_EXEC); req_put_string(filename); for (i = 0; argv[i]; i++) req_put_string(argv[i]); req_end(); return req_res() ? -1 : 0; } int __fastcall__ sys_fstat(int fd, struct sys_stat *buf) { req_put(REQ_FSTAT); req_put(fd); req_end(); if (req_res()) return -1; buf->type = *(unsigned char *)REQDAT; buf->size = ((unsigned long *)REQDAT2)[0]; buf->size_hi = ((unsigned long *)REQDAT2)[1]; return 0; } int sys_open(const char *filename, int flags, ...) { req_put(REQ_OPEN); req_put_string(filename); req_put(flags); req_end(); if (req_res()) return -1; return *(byte *)REQDAT; } int do_rdwr(int fd, void *buf, int n, int req_id) { req_put(req_id); req_put(fd); req_put_word((unsigned)buf); req_put_word(n); req_end(); if (req_res()) return -1; return *(int *)REQDAT; } int __fastcall__ sys_read(int fd, void *buf, int n) { return do_rdwr(fd, buf, n, REQ_READ); } int __fastcall__ sys_write(int fd, void *buf, int n) { return do_rdwr(fd, buf, n, REQ_WRITE); } int __fastcall__ sys_close(int fd) { req_put(REQ_CLOSE); req_put(fd); req_end(); return req_res() ? -1 : 0; } int __fastcall__ sys_pipe(int *p) { req_put(REQ_PIPE); req_end(); if (req_res()) return -1; p[0] = *(int *)REQDAT; p[1] = *(int *)(REQDAT + 8); return 0; } int __fastcall__ sys_dup(int fd) { req_put(REQ_DUP); req_put(fd); req_end(); if (req_res()) return -1; return *(byte *)REQDAT; } int do_filename(const char *filename, int req_id) { req_put(req_id); req_put_string(filename); req_end(); return req_res() ? -1 : 0; } int __fastcall__ sys_chdir(const char *filename) { return do_filename(filename, REQ_CHDIR); } int __fastcall__ sys_mkdir(const char *filename) { return do_filename(filename, REQ_MKDIR); } int __fastcall__ sys_unlink(const char *filename) { return do_filename(filename, REQ_UNLINK); } int __fastcall__ sys_rmdir(const char *filename) { return do_filename(filename, REQ_RMDIR); } unsigned long __fastcall__ sys_time(unsigned long *t) { req_put(REQ_TIME); req_end(); if (t) *t = *(unsigned long *)REQDAT; return *(unsigned long *)REQDAT; } long __fastcall__ sys_lseek(int fd, long offset, int whence) { int w; switch (whence) { case SEEK_SET: w = XV65_SEEK_SET; break; case SEEK_CUR: w = XV65_SEEK_CUR; break; case SEEK_END: w = XV65_SEEK_END; break; default: return -1; } req_put(REQ_LSEEK); req_put(fd); req_put(w); req_put_word((unsigned)offset); req_end(); if (req_res()) return -1; return *(long *)REQDAT; } unsigned int sys_argc(void) { req_put(REQ_ARGC); req_end(); return *(unsigned int *)REQDAT; } int __fastcall__ sys_argv(unsigned int i, char *buf, unsigned int *size) { req_put(REQ_ARGV); req_put_word((unsigned int)buf); req_put_word(*size); req_put_word(i); req_end(); *size = *(unsigned int *)REQDAT; return req_res() ? -1 : 0; } int __fastcall__ sys_env(const char *name, char *buf, unsigned int *size) { req_put(REQ_ENV); req_put_word((unsigned int)buf); req_put_word(*size); req_put_string(name); req_end(); *size = *(unsigned int *)REQDAT; return req_res() ? -1 : 0; }
steva44/OpenSees
OpenSeesLibs/arpack/Unix/3.7.0_2/libexec/include/arpack/debug_c.h
<filename>OpenSeesLibs/arpack/Unix/3.7.0_2/libexec/include/arpack/debug_c.h #ifndef __DEBUG_C_H__ #define __DEBUG_C_H__ extern void debug_c(int logfil_c, int ndigit_c, int mgetv0_c, int msaupd_c, int msaup2_c, int msaitr_c, int mseigt_c, int msapps_c, int msgets_c, int mseupd_c, int mnaupd_c, int mnaup2_c, int mnaitr_c, int mneigh_c, int mnapps_c, int mngets_c, int mneupd_c, int mcaupd_c, int mcaup2_c, int mcaitr_c, int mceigh_c, int mcapps_c, int mcgets_c, int mceupd_c); #endif
guidocecilio/discover-smarter
app/controllers/Projects.scala
<gh_stars>1-10 package controllers import play.api._ import play.api.mvc._ import play.api.data._ import play.api.data.Forms._ import anorm._ import models._ import views._ import play.api.libs.json._ /** * Manage projects related operations. */ object Projects extends Controller with Secured { implicit val pkWrites = new Writes[Pk[Long]] { def writes(id: Pk[Long]) = JsNumber(id.get) } implicit val pkReads = new Reads[Pk[Long]] { def reads(json: JsValue):JsResult[Pk[Long]] = { JsSuccess(Id(json.as[Long])) } } /** * Display the dashboard. */ def index = IsAuthenticated { username => _ => User.findByEmail(username).map { user => Ok( html.dashboard( Project.findInvolving(username), Task.findTodoInvolving(username), user ) ) }.getOrElse(Forbidden) } def build = IsAuthenticated { username => _ => User.findByEmail(username).map { user => Ok( html.build( Project.findInvolving(username), user ) ) }.getOrElse(Forbidden) } // -- Projects /** * Add a project. */ def add = IsAuthenticated { username => implicit request =>{ Logger.info("I am in project controller") Form("group" -> nonEmptyText).bindFromRequest.fold( errors => BadRequest, folder => { val project = Project.create(Project(NotAssigned, folder, "New project"), Seq(username),Seq.empty) Ok(views.html.items.projectitem(project)) }) } } /** * Delete a project. */ def delete(project: Long) = IsMemberOf(project) { username => _ => Project.delete(project) Ok } /** * Rename a project. */ def rename(project: Long) = IsMemberOf(project) { _ => implicit request => Form("name" -> nonEmptyText).bindFromRequest.fold( errors => BadRequest, newName => { Project.rename(project, newName) Ok(newName) } ) } /** * */ def listProjects = Action { val projects = Project.findAll Ok(Json.toJson(projects)) } // -- Project groups /** * Add a new project group. */ def addGroup = IsAuthenticated { _ => _ => Ok(html.items.projectgroupitem("New group")) } /** * Delete a project group. */ def deleteGroup(folder: String) = IsAuthenticated { _ => _ => Project.deleteInFolder(folder) Ok } /** * Rename a project group. */ def renameGroup(folder: String) = IsAuthenticated { _ => implicit request => Form("name" -> nonEmptyText).bindFromRequest.fold( errors => BadRequest, newName => { Project.renameFolder(folder, newName); Ok(newName) } ) } // -- Members /** * Add a project member. */ def addUser(project: Long) = IsMemberOf(project) { _ => implicit request => Form("user" -> nonEmptyText).bindFromRequest.fold( errors => BadRequest, user => { Project.addMember(project, user); Ok } ) } /** * Remove a project member. */ def removeUser(project: Long) = IsMemberOf(project) { _ => implicit request => Form("user" -> nonEmptyText).bindFromRequest.fold( errors => BadRequest, user => { Project.removeMember(project, user); Ok } ) } implicit val projectWrites = new Writes[Project] { def writes(project: Project) = Json.obj( "id" -> project.id, "folder" -> project.folder, "name" -> project.name ) } }
aquila-zyy/Botania
src/main/java/vazkii/botania/api/subtile/TileEntityGeneratingFlower.java
<reponame>aquila-zyy/Botania /* * This class is distributed as part of the Botania Mod. * Get the Source Code in github: * https://github.com/Vazkii/Botania * * Botania is Open Source and distributed under the * Botania License: http://botaniamod.net/license.php */ package vazkii.botania.api.subtile; import com.mojang.blaze3d.vertex.PoseStack; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.Minecraft; import net.minecraft.client.resources.language.I18n; import net.minecraft.core.BlockPos; import net.minecraft.core.Registry; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.phys.Vec3; import vazkii.botania.api.BotaniaAPI; import vazkii.botania.api.BotaniaAPIClient; import vazkii.botania.api.internal.IManaNetwork; import vazkii.botania.api.mana.IManaCollector; import javax.annotation.Nullable; /** * The basic class for a Generating Flower. */ public class TileEntityGeneratingFlower extends TileEntityBindableSpecialFlower<IManaCollector> { private static final ResourceLocation SPREADER_ID = new ResourceLocation(BotaniaAPI.MODID, "mana_spreader"); public static final int LINK_RANGE = 6; private static final String TAG_MANA = "mana"; public static final String TAG_PASSIVE_DECAY_TICKS = "passiveDecayTicks"; private int mana; public int passiveDecayTicks; public TileEntityGeneratingFlower(BlockEntityType<?> type, BlockPos pos, BlockState state) { super(type, pos, state, IManaCollector.class); } @Override public void tickFlower() { super.tickFlower(); if (!getLevel().isClientSide && canGeneratePassively()) { int delay = getDelayBetweenPassiveGeneration(); if (delay > 0 && ticksExisted % delay == 0) { addMana(getValueForPassiveGeneration()); } } emptyManaIntoCollector(); if (getLevel().isClientSide) { double particleChance = 1F - (double) getMana() / (double) getMaxMana() / 3.5F; int color = getColor(); float red = (color >> 16 & 0xFF) / 255F; float green = (color >> 8 & 0xFF) / 255F; float blue = (color & 0xFF) / 255F; if (Math.random() > particleChance) { Vec3 offset = getLevel().getBlockState(getBlockPos()).getOffset(getLevel(), getBlockPos()); double x = getBlockPos().getX() + offset.x; double y = getBlockPos().getY() + offset.y; double z = getBlockPos().getZ() + offset.z; BotaniaAPI.instance().sparkleFX(getLevel(), x + 0.3 + Math.random() * 0.5, y + 0.5 + Math.random() * 0.5, z + 0.3 + Math.random() * 0.5, red, green, blue, (float) Math.random(), 5); } } else { boolean passive = isPassiveFlower(); int muhBalance = BotaniaAPI.instance().getPassiveFlowerDecay(); if (passive) { passiveDecayTicks++; } if (passive && muhBalance > 0 && passiveDecayTicks > muhBalance) { getLevel().destroyBlock(getBlockPos(), false); if (Blocks.DEAD_BUSH.defaultBlockState().canSurvive(getLevel(), getBlockPos())) { getLevel().setBlockAndUpdate(getBlockPos(), Blocks.DEAD_BUSH.defaultBlockState()); } } } } @Override public int getBindingRadius() { return LINK_RANGE; } @Override public @Nullable BlockPos findClosestTarget() { IManaNetwork network = BotaniaAPI.instance().getManaNetworkInstance(); BlockEntity closestCollector = network.getClosestCollector(getBlockPos(), getLevel(), getBindingRadius()); return closestCollector == null ? null : closestCollector.getBlockPos(); } public void emptyManaIntoCollector() { IManaCollector collector = findBoundTile(); if (collector != null && !collector.isFull() && getMana() > 0) { int manaval = Math.min(getMana(), collector.getMaxMana() - collector.getCurrentMana()); addMana(-manaval); collector.receiveMana(manaval); sync(); } } public void addMana(int mana) { this.mana = Math.min(getMaxMana(), this.getMana() + mana); setChanged(); } public int getMana() { return mana; } public boolean isPassiveFlower() { return false; } public boolean canGeneratePassively() { return false; } public int getDelayBetweenPassiveGeneration() { return 20; } public int getValueForPassiveGeneration() { return 1; } public int getMaxMana() { return 20; } public int getColor() { return 0xFFFFFF; } @Override public void readFromPacketNBT(CompoundTag cmp) { super.readFromPacketNBT(cmp); mana = cmp.getInt(TAG_MANA); passiveDecayTicks = cmp.getInt(TAG_PASSIVE_DECAY_TICKS); } @Override public void writeToPacketNBT(CompoundTag cmp) { super.writeToPacketNBT(cmp); cmp.putInt(TAG_MANA, getMana()); cmp.putInt(TAG_PASSIVE_DECAY_TICKS, passiveDecayTicks); } public ItemStack getHudIcon() { return Registry.ITEM.getOptional(SPREADER_ID).map(ItemStack::new).orElse(ItemStack.EMPTY); } @Environment(EnvType.CLIENT) @Override public void renderHUD(PoseStack ms, Minecraft mc) { String name = I18n.get(getBlockState().getBlock().getDescriptionId()); int color = getColor(); BotaniaAPIClient.instance().drawComplexManaHUD(ms, color, getMana(), getMaxMana(), name, getHudIcon(), isValidBinding()); } @Override public boolean isOvergrowthAffected() { return !isPassiveFlower(); } }
CrowdArt/public-market-storefront
app/models/spree/product_decorator.rb
module Spree module ProductDecorator MISSING_TITLE = '[Missing title]'.freeze def self.included(base) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength class << base prepend ClassMethods end base.prepend InstanceMethods base.belongs_to :best_variant, class_name: 'Spree::Variant' base.has_many :product_collections_products, class_name: 'Spree::ProductCollectionProduct', dependent: :destroy base.has_many :product_collections, through: :product_collections_products, class_name: 'Spree::ProductCollection', source: :product_collection base.include Spree::Core::NumberGenerator.new(prefix: 'PM', letters: true, length: 13) base.include Spree::ProductKind base.before_validation :set_missing_title, if: -> { name.blank? } base.before_create :reset_boost_factor_if_no_images, if: -> { master.images.blank? } base.after_create_commit :notify_missing_title, if: -> { name == MISSING_TITLE } base.scope :in_stock, lambda { joins(variants: :stock_items).where('spree_stock_items.count_on_hand > ? OR spree_variants.track_inventory = ?', 0, false) } base.delegate :variation_module, to: :taxonomy, allow_nil: true base.skip_callback :touch, :after, :touch_taxons if base._touch_callbacks.any? end module InstanceMethods def should_generate_new_friendly_id? name_changed? || super end def update_best_variant # get minimum price of best condition variant best_variant = variants.in_stock .joins(:prices) .joins(%( LEFT JOIN "spree_option_value_variants" ON "spree_option_value_variants"."variant_id" = "spree_variants"."id" LEFT JOIN "spree_option_values" ON "spree_option_values"."id" = "spree_option_value_variants"."option_value_id" LEFT JOIN "spree_option_types" ON "spree_option_types"."id" = "spree_option_values"."option_type_id" and "spree_option_types"."name" = 'condition')) .reorder('spree_option_values.position asc, spree_prices.amount asc') .limit(1) .first update(price: best_variant.price, best_variant: best_variant) if best_variant end # can be false def taxonomy return @taxonomy if defined?(@taxonomy) @taxonomy = taxons.first&.taxonomy end # fields merged to searchkick's search_data def index_data { conversions_month: orders.complete.where('completed_at > ?', 1.month.ago).count, slug: slug, variations: variations, collections: product_collection_ids, in_stock: variants.active.in_stock.count } end def should_index? name != MISSING_TITLE end # variations visible on product page/product card def variations variation_module_properties&.variation_properties(self) || [] end def variation return @variation if defined?(@variation) @variation = variation_module_properties&.variation(self) end def variation_finder return @variation_finder if defined?(@variation_finder) @variation_finder = variation_module&.const_get('VariationFinder') end def rewards best_variant&.final_rewards || Spree::Config.rewards end def rewards_amount PublicMarket::RewardsCalculator.call(price, rewards) end private def variation_module_properties variation_module&.const_get('Properties') end def reset_boost_factor_if_no_images self.boost_factor = 0 end def set_missing_title self.name = MISSING_TITLE end def notify_missing_title PublicMarket::Workers::Slack::DataReconcilationWorker.perform_async(product_id: id, message_type: 'missing-title') rescue => e # rubocop:disable Style/RescueStandardError Rails.env.production? || Rails.env.staging? ? Raven.capture_exception(e) : raise(e) end end module ClassMethods # enable searchkick callbacks in RecalculateVendorVariantPrice # when price is included in searchkick index def search_fields autocomplete_fields + %i[isbn] end def autocomplete_fields %i[name author artist] end end end end Spree::Product.include(Spree::ProductDecorator)
PavelBlend/fluid-engine-dev
src/jet/collocated_vector_grid3.cpp
<filename>src/jet/collocated_vector_grid3.cpp // Copyright (c) 2018 <NAME> // // I am making my contributions/submissions to this project solely in my // personal capacity and am not conveying any rights to any intellectual // property of any third parties. #include <pch.h> #include <jet/collocated_vector_grid3.h> #include <jet/parallel.h> #include <jet/serial.h> #include <algorithm> #include <utility> // just make cpplint happy.. #include <vector> using namespace jet; CollocatedVectorGrid3::CollocatedVectorGrid3() : _linearSampler(_data.constAccessor(), Vector3D(1, 1, 1), Vector3D()) { } CollocatedVectorGrid3::~CollocatedVectorGrid3() { } const Vector3D& CollocatedVectorGrid3::operator()( size_t i, size_t j, size_t k) const { return _data(i, j, k); } Vector3D& CollocatedVectorGrid3::operator()(size_t i, size_t j, size_t k) { return _data(i, j, k); } double CollocatedVectorGrid3::divergenceAtDataPoint( size_t i, size_t j, size_t k) const { const Size3 ds = _data.size(); const Vector3D& gs = gridSpacing(); JET_ASSERT(i < ds.x && j < ds.y && k < ds.z); double left = _data((i > 0) ? i - 1 : i, j, k).x; double right = _data((i + 1 < ds.x) ? i + 1 : i, j, k).x; double down = _data(i, (j > 0) ? j - 1 : j, k).y; double up = _data(i, (j + 1 < ds.y) ? j + 1 : j, k).y; double back = _data(i, j, (k > 0) ? k - 1 : k).z; double front = _data(i, j, (k + 1 < ds.z) ? k + 1 : k).z; return 0.5 * (right - left) / gs.x + 0.5 * (up - down) / gs.y + 0.5 * (front - back) / gs.z; } Vector3D CollocatedVectorGrid3::curlAtDataPoint( size_t i, size_t j, size_t k) const { const Size3 ds = _data.size(); const Vector3D& gs = gridSpacing(); JET_ASSERT(i < ds.x && j < ds.y && k < ds.z); Vector3D left = _data((i > 0) ? i - 1 : i, j, k); Vector3D right = _data((i + 1 < ds.x) ? i + 1 : i, j, k); Vector3D down = _data(i, (j > 0) ? j - 1 : j, k); Vector3D up = _data(i, (j + 1 < ds.y) ? j + 1 : j, k); Vector3D back = _data(i, j, (k > 0) ? k - 1 : k); Vector3D front = _data(i, j, (k + 1 < ds.z) ? k + 1 : k); double Fx_ym = down.x; double Fx_yp = up.x; double Fx_zm = back.x; double Fx_zp = front.x; double Fy_xm = left.y; double Fy_xp = right.y; double Fy_zm = back.y; double Fy_zp = front.y; double Fz_xm = left.z; double Fz_xp = right.z; double Fz_ym = down.z; double Fz_yp = up.z; return Vector3D( 0.5 * (Fz_yp - Fz_ym) / gs.y - 0.5 * (Fy_zp - Fy_zm) / gs.z, 0.5 * (Fx_zp - Fx_zm) / gs.z - 0.5 * (Fz_xp - Fz_xm) / gs.x, 0.5 * (Fy_xp - Fy_xm) / gs.x - 0.5 * (Fx_yp - Fx_ym) / gs.y); } Vector3D CollocatedVectorGrid3::sample(const Vector3D& x) const { return _sampler(x); } double CollocatedVectorGrid3::divergence(const Vector3D& x) const { std::array<Point3UI, 8> indices; std::array<double, 8> weights; _linearSampler.getCoordinatesAndWeights(x, &indices, &weights); double result = 0.0; for (int i = 0; i < 8; ++i) { result += weights[i] * divergenceAtDataPoint( indices[i].x, indices[i].y, indices[i].z); } return result; } Vector3D CollocatedVectorGrid3::curl(const Vector3D& x) const { std::array<Point3UI, 8> indices; std::array<double, 8> weights; _linearSampler.getCoordinatesAndWeights(x, &indices, &weights); Vector3D result; for (int i = 0; i < 8; ++i) { result += weights[i] * curlAtDataPoint( indices[i].x, indices[i].y, indices[i].z); } return result; } std::function<Vector3D(const Vector3D&)> CollocatedVectorGrid3::sampler() const { return _sampler; } VectorGrid3::VectorDataAccessor CollocatedVectorGrid3::dataAccessor() { return _data.accessor(); } VectorGrid3::ConstVectorDataAccessor CollocatedVectorGrid3::constDataAccessor() const { return _data.constAccessor(); } VectorGrid3::DataPositionFunc CollocatedVectorGrid3::dataPosition() const { Vector3D dataOrigin_ = dataOrigin(); return [this, dataOrigin_](size_t i, size_t j, size_t k) -> Vector3D { return dataOrigin_ + gridSpacing() * Vector3D({i, j, k}); }; } void CollocatedVectorGrid3::forEachDataPointIndex( const std::function<void(size_t, size_t, size_t)>& func) const { _data.forEachIndex(func); } void CollocatedVectorGrid3::parallelForEachDataPointIndex( const std::function<void(size_t, size_t, size_t)>& func) const { _data.parallelForEachIndex(func); } void CollocatedVectorGrid3::swapCollocatedVectorGrid( CollocatedVectorGrid3* other) { swapGrid(other); _data.swap(other->_data); std::swap(_linearSampler, other->_linearSampler); std::swap(_sampler, other->_sampler); } void CollocatedVectorGrid3::setCollocatedVectorGrid( const CollocatedVectorGrid3& other) { setGrid(other); _data.set(other._data); resetSampler(); } void CollocatedVectorGrid3::onResize( const Size3& resolution, const Vector3D& gridSpacing, const Vector3D& origin, const Vector3D& initialValue) { UNUSED_VARIABLE(resolution); UNUSED_VARIABLE(gridSpacing); UNUSED_VARIABLE(origin); _data.resize(dataSize(), initialValue); resetSampler(); } void CollocatedVectorGrid3::resetSampler() { _linearSampler = LinearArraySampler3<Vector3D, double>( _data.constAccessor(), gridSpacing(), dataOrigin()); _sampler = _linearSampler.functor(); } void CollocatedVectorGrid3::getData(std::vector<double>* data) const { size_t size = 3 * dataSize().x * dataSize().y * dataSize().z; data->resize(size); size_t cnt = 0; _data.forEach([&] (const Vector3D& value) { (*data)[cnt++] = value.x; (*data)[cnt++] = value.y; (*data)[cnt++] = value.z; }); } void CollocatedVectorGrid3::setData(const std::vector<double>& data) { JET_ASSERT(3 * dataSize().x * dataSize().y * dataSize().z == data.size()); size_t cnt = 0; _data.forEachIndex([&] (size_t i, size_t j, size_t k) { _data(i, j, k).x = data[cnt++]; _data(i, j, k).y = data[cnt++]; _data(i, j, k).z = data[cnt++]; }); }
embeddedartistry/embeddedartistry.github.io
libc/df/da2/abs_8c.js
var abs_8c = [ [ "abs", "df/da2/abs_8c.html#aeb20b44c8437544e571a3cb9bb2cc37d", null ] ];
jasonnam/buck
src/com/facebook/buck/core/rules/tool/RunInfoLegacyTool.java
<filename>src/com/facebook/buck/core/rules/tool/RunInfoLegacyTool.java<gh_stars>0 /* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.buck.core.rules.tool; import com.facebook.buck.core.rulekey.AddToRuleKey; import com.facebook.buck.core.rules.providers.lib.RunInfo; import com.facebook.buck.core.sourcepath.resolver.SourcePathResolverAdapter; import com.facebook.buck.core.toolchain.tool.Tool; import com.facebook.buck.core.util.immutables.BuckStyleValue; import com.facebook.buck.rules.args.ArgFactory; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; /** * A legacy {@link Tool} interface to {@link RunInfo} provider info objects. This ensures that rules * returning {@link RunInfo} can still be executed by legacy style build rules, and also the {@code * buck run} command. */ @BuckStyleValue public abstract class RunInfoLegacyTool implements Tool { @AddToRuleKey public abstract RunInfo getRunInfo(); public static RunInfoLegacyTool of(RunInfo runInfo) { return ImmutableRunInfoLegacyTool.ofImpl(runInfo); } @Override public ImmutableList<String> getCommandPrefix(SourcePathResolverAdapter resolver) { RunInfo runInfo = getRunInfo(); ImmutableList.Builder<String> command = ImmutableList.builderWithExpectedSize(runInfo.args().getEstimatedArgsCount()); runInfo .args() .getArgsAndFormatStrings() .map( argAndFormat -> ArgFactory.from( argAndFormat.getObject(), argAndFormat.getPostStringificationFormatString())) .forEach(arg -> arg.appendToCommandLine(command::add, resolver)); return command.build(); } @Override public ImmutableMap<String, String> getEnvironment(SourcePathResolverAdapter resolver) { return getRunInfo().getEnvironmentVariables(); } }
tenta-browser/go-video-downloader
gen/youtube_dl/extractor/soundcloud/module.go
<gh_stars>10-100 // Code generated by transpiler. DO NOT EDIT. /** * Go Video Downloader * * Copyright 2019 Tenta, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * For any questions, please contact <EMAIL> * * soundcloud/module.go: transpiled from https://github.com/ytdl-org/youtube-dl/blob/master/youtube_dl/extractor/soundcloud.py */ package soundcloud import ( Ωcompat "github.com/tenta-browser/go-video-downloader/gen/youtube_dl/compat" Ωcommon "github.com/tenta-browser/go-video-downloader/gen/youtube_dl/extractor/common" Ωutils "github.com/tenta-browser/go-video-downloader/gen/youtube_dl/utils" λ "github.com/tenta-browser/go-video-downloader/runtime" ) var ( ExtractorError λ.Object HEADRequest λ.Object InfoExtractor λ.Object KNOWN_EXTENSIONS λ.Object SearchInfoExtractor λ.Object SoundcloudEmbedIE λ.Object SoundcloudIE λ.Object SoundcloudPagedPlaylistBaseIE λ.Object SoundcloudPlaylistBaseIE λ.Object SoundcloudPlaylistIE λ.Object SoundcloudSearchIE λ.Object SoundcloudSetIE λ.Object SoundcloudTrackStationIE λ.Object SoundcloudUserIE λ.Object ϒcompat_kwargs λ.Object ϒcompat_str λ.Object ϒerror_to_compat_str λ.Object ϒfloat_or_none λ.Object ϒint_or_none λ.Object ϒmimetype2ext λ.Object ϒstr_or_none λ.Object ϒtry_get λ.Object ϒunified_timestamp λ.Object ϒupdate_url_query λ.Object ϒurl_or_none λ.Object ) func init() { λ.InitModule(func() { InfoExtractor = Ωcommon.InfoExtractor SearchInfoExtractor = Ωcommon.SearchInfoExtractor ϒcompat_kwargs = Ωcompat.ϒcompat_kwargs ϒcompat_str = Ωcompat.ϒcompat_str ϒerror_to_compat_str = Ωutils.ϒerror_to_compat_str ExtractorError = Ωutils.ExtractorError ϒfloat_or_none = Ωutils.ϒfloat_or_none HEADRequest = Ωutils.HEADRequest ϒint_or_none = Ωutils.ϒint_or_none KNOWN_EXTENSIONS = Ωutils.KNOWN_EXTENSIONS ϒmimetype2ext = Ωutils.ϒmimetype2ext ϒstr_or_none = Ωutils.ϒstr_or_none ϒtry_get = Ωutils.ϒtry_get ϒunified_timestamp = Ωutils.ϒunified_timestamp ϒupdate_url_query = Ωutils.ϒupdate_url_query ϒurl_or_none = Ωutils.ϒurl_or_none SoundcloudEmbedIE = λ.Cal(λ.TypeType, λ.StrLiteral("SoundcloudEmbedIE"), λ.NewTuple(InfoExtractor), func() λ.Dict { var ( SoundcloudEmbedIE__VALID_URL λ.Object ) SoundcloudEmbedIE__VALID_URL = λ.StrLiteral("https?://(?:w|player|p)\\.soundcloud\\.com/player/?.*?\\burl=(?P<id>.+)") return λ.ClassDictLiteral(map[string]λ.Object{ "_VALID_URL": SoundcloudEmbedIE__VALID_URL, }) }()) SoundcloudIE = λ.Cal(λ.TypeType, λ.StrLiteral("SoundcloudIE"), λ.NewTuple(InfoExtractor), func() λ.Dict { var ( SoundcloudIE__VALID_URL λ.Object ) SoundcloudIE__VALID_URL = λ.StrLiteral("(?x)^(?:https?://)?\n (?:(?:(?:www\\.|m\\.)?soundcloud\\.com/\n (?!stations/track)\n (?P<uploader>[\\w\\d-]+)/\n (?!(?:tracks|albums|sets(?:/.+?)?|reposts|likes|spotlight)/?(?:$|[?#]))\n (?P<title>[\\w\\d-]+)/?\n (?P<token>[^?]+?)?(?:[?].*)?$)\n |(?:api(?:-v2)?\\.soundcloud\\.com/tracks/(?P<track_id>\\d+)\n (?:/?\\?secret_token=(?P<secret_token>[^&]+))?)\n )\n ") return λ.ClassDictLiteral(map[string]λ.Object{ "_VALID_URL": SoundcloudIE__VALID_URL, }) }()) SoundcloudPlaylistBaseIE = λ.Cal(λ.TypeType, λ.StrLiteral("SoundcloudPlaylistBaseIE"), λ.NewTuple(SoundcloudIE), func() λ.Dict { return λ.ClassDictLiteral(map[λ.Object]λ.Object{}) }()) SoundcloudSetIE = λ.Cal(λ.TypeType, λ.StrLiteral("SoundcloudSetIE"), λ.NewTuple(SoundcloudPlaylistBaseIE), func() λ.Dict { var ( SoundcloudSetIE__VALID_URL λ.Object ) SoundcloudSetIE__VALID_URL = λ.StrLiteral("https?://(?:(?:www|m)\\.)?soundcloud\\.com/(?P<uploader>[\\w\\d-]+)/sets/(?P<slug_title>[\\w\\d-]+)(?:/(?P<token>[^?/]+))?") return λ.ClassDictLiteral(map[string]λ.Object{ "_VALID_URL": SoundcloudSetIE__VALID_URL, }) }()) SoundcloudPagedPlaylistBaseIE = λ.Cal(λ.TypeType, λ.StrLiteral("SoundcloudPagedPlaylistBaseIE"), λ.NewTuple(SoundcloudIE), func() λ.Dict { return λ.ClassDictLiteral(map[λ.Object]λ.Object{}) }()) SoundcloudUserIE = λ.Cal(λ.TypeType, λ.StrLiteral("SoundcloudUserIE"), λ.NewTuple(SoundcloudPagedPlaylistBaseIE), func() λ.Dict { var ( SoundcloudUserIE__VALID_URL λ.Object ) SoundcloudUserIE__VALID_URL = λ.StrLiteral("(?x)\n https?://\n (?:(?:www|m)\\.)?soundcloud\\.com/\n (?P<user>[^/]+)\n (?:/\n (?P<rsrc>tracks|albums|sets|reposts|likes|spotlight)\n )?\n /?(?:[?#].*)?$\n ") return λ.ClassDictLiteral(map[string]λ.Object{ "_VALID_URL": SoundcloudUserIE__VALID_URL, }) }()) SoundcloudTrackStationIE = λ.Cal(λ.TypeType, λ.StrLiteral("SoundcloudTrackStationIE"), λ.NewTuple(SoundcloudPagedPlaylistBaseIE), func() λ.Dict { var ( SoundcloudTrackStationIE__VALID_URL λ.Object ) SoundcloudTrackStationIE__VALID_URL = λ.StrLiteral("https?://(?:(?:www|m)\\.)?soundcloud\\.com/stations/track/[^/]+/(?P<id>[^/?#&]+)") return λ.ClassDictLiteral(map[string]λ.Object{ "_VALID_URL": SoundcloudTrackStationIE__VALID_URL, }) }()) SoundcloudPlaylistIE = λ.Cal(λ.TypeType, λ.StrLiteral("SoundcloudPlaylistIE"), λ.NewTuple(SoundcloudPlaylistBaseIE), func() λ.Dict { var ( SoundcloudPlaylistIE__VALID_URL λ.Object ) SoundcloudPlaylistIE__VALID_URL = λ.StrLiteral("https?://api(?:-v2)?\\.soundcloud\\.com/playlists/(?P<id>[0-9]+)(?:/?\\?secret_token=(?P<token>[^&]+?))?$") return λ.ClassDictLiteral(map[string]λ.Object{ "_VALID_URL": SoundcloudPlaylistIE__VALID_URL, }) }()) SoundcloudSearchIE = λ.Cal(λ.TypeType, λ.StrLiteral("SoundcloudSearchIE"), λ.NewTuple( SearchInfoExtractor, SoundcloudIE, ), func() λ.Dict { var ( SoundcloudSearchIE__SEARCH_KEY λ.Object ) SoundcloudSearchIE__SEARCH_KEY = λ.StrLiteral("scsearch") return λ.ClassDictLiteral(map[string]λ.Object{ "_SEARCH_KEY": SoundcloudSearchIE__SEARCH_KEY, }) }()) }) }
pvanheus/irida
src/main/java/ca/corefacility/bioinformatics/irida/repositories/referencefile/ReferenceFileRepository.java
package ca.corefacility.bioinformatics.irida.repositories.referencefile; import ca.corefacility.bioinformatics.irida.model.project.ReferenceFile; import ca.corefacility.bioinformatics.irida.repositories.IridaJpaRepository; import ca.corefacility.bioinformatics.irida.repositories.filesystem.FilesystemSupplementedRepository; /** * Repository for interacting with {@link ReferenceFile}. * * */ public interface ReferenceFileRepository extends IridaJpaRepository<ReferenceFile, Long>, FilesystemSupplementedRepository<ReferenceFile> { /** * {@inheritDoc} * * Save is overridden here instead of in FilesystemSupplementedRepository as it would throw a * compilation error */ <S extends ReferenceFile> S save(S entity); }
ukane-philemon/dcrdex
client/core/errors_test.go
<filename>client/core/errors_test.go package core import ( "errors" "fmt" "testing" ) type testErr string func (te testErr) Error() string { return string(te) } const ( err0 = testErr("other error") err2 = testErr("Test error 2") ) // TestCoreError tests the error output for the Error type. func TestCoreError(t *testing.T) { tests := []struct { in Error want string }{{ Error{ code: walletErr, err: errors.New("wallet error"), }, "wallet error", }, { Error{ code: walletAuthErr, err: errors.New("wallet auth error"), }, "wallet auth error", }} for i, test := range tests { result := test.in.Error() if result != test.want { t.Errorf("#%d: got: %s want: %s", i, result, test.want) continue } } coreErr := newError(walletErr, "stuff: %w", err0) var err1 *Error if !errors.As(coreErr, &err1) { t.Errorf("it isn't a core.Error type") } if !errors.Is(coreErr, err0) { t.Errorf("it wasn't err0") } if errors.Is(coreErr, err2) { t.Errorf("it was err2") } otherErr := codedError(walletErr, err0) var err3 testErr if !errors.As(otherErr, &err3) { t.Errorf("it wasn't an testErr") } } func TestUnwrapErr(t *testing.T) { err1 := errors.New("Error 1") err2 := fmt.Errorf("Error 2: %w", err1) err3 := fmt.Errorf("Not wrapped: %v, %d", "other string", 20) erra := newError(walletErr, "wraps 2: %w", err2) testCases := []struct { err error want error }{ {erra, err1}, {newError(walletErr, "wraps 2: %w", err2), err1}, {newError(walletErr, "wraps 1: %w", err1), err1}, {newError(walletErr, "Not wrapped: %v, %d", "other string", 20), err3}, } for i, tc := range testCases { if got := UnwrapErr(tc.err); got.Error() != tc.want.Error() { t.Errorf("#%d: UnwrapErr(%v) = %v, want %v", i, tc.err, got.Error(), tc.want.Error()) } } }
BeMyHand/BeMyHand
src/contexts/ThemeContext/ThemeContext.js
<reponame>BeMyHand/BeMyHand import React, {createContext} from "react"; const themes = { red: { hex: '#ED4739', color: '#ED4739', }, blue: { hex: '#458BFF', color: '#458BFF', }, yellow: { hex: '#FFD459', color: '#FFD459', }, green: { hex: '#19C270', color: '#19C270', }, }; const ThemeContext = createContext(themes); export default ThemeContext;
GMAP/NPB-CPP
libs/fastflow/tests/test_dataflow.cpp
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* *************************************************************************** * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * As a special exception, you may use this file as part of a free software * library without restriction. Specifically, if other files instantiate * templates or use macros or inline functions from this file, or you compile * this file and link it with other files to produce an executable, this * file does not by itself cause the resulting executable to be covered by * the GNU General Public License. This exception does not however * invalidate any other reasons why the executable file might be covered by * the GNU General Public License. * **************************************************************************** */ /* * 2-stages pipeline * * -------------------------------- * | | * | ---> FU -->| * v | | * MU ----> Scheduler --- ---> FU -->| * ^ | | * | ---> FU -->| * | | * -------------------------------- * */ #include <vector> #include <iostream> #include <ff/ff.hpp> using namespace ff; /* * NOTE: this is a multi-input node */ class MU: public ff_minode { public: MU(int numtasks): numtasks(numtasks), k(0) {} void* svc(void* task) { if (task==NULL) { printf("MU starting producing tasks\n"); for(long i=1;i<=numtasks;++i) ff_send_out((void*)i); return GO_ON; } long t = (long)task; if (--t > 0) ff_send_out((void*)t); else if (++k == numtasks) return EOS; return GO_ON; } private: long numtasks; long k; }; struct Scheduler: public ff_node { void* svc(void* task) { return task; } }; struct FU: public ff_node { void* svc(void* task) { printf("FU (%ld) got one task (%ld)\n", get_my_id(), (long)task); return task; } }; int main(int argc, char* argv[]) { int nw=3; int numtasks=1000; if (argc>1) { if (argc < 3) { std::cerr << "use:\n" << " " << argv[0] << " numworkers ntasks\n"; return -1; } nw=atoi(argv[1]); numtasks=atoi(argv[2]); } ff_pipeline pipe; ff_farm farm; std::vector<ff_node *> w; for(int i=0;i<nw;++i) w.push_back(new FU); farm.add_emitter(new Scheduler); farm.add_workers(w); pipe.add_stage(new MU(numtasks)); pipe.add_stage(&farm); /* this is needed to allow the creation of output buffer in the * farm workers */ farm.remove_collector(); pipe.wrap_around(); pipe.run_and_wait_end(); return 0; }
eagletmt/procon
aoj/0/0574.cc
<filename>aoj/0/0574.cc #include <cstdio> #include <algorithm> using namespace std; int main() { int N, M; scanf("%d %d", &N, &M); static int a[5001][5001]; for (int i = 0; i < M; i++) { int A, B, X; scanf("%d %d %d", &A, &B, &X); a[A][B] = X+1; } int ans = 0; for (int i = 1; i <= N; i++) { for (int j = 1; j <= i; j++) { a[i][j] = max(a[i][j], a[i-1][j] - 1); a[i][j] = max(a[i][j], a[i-1][j-1] - 1); if (a[i][j] > 0) { ++ans; } } } printf("%d\n", ans); return 0; }
tencentyun/xiaowei-device-sdk
Device/Demo_Android/control/jni/OpusDecoder.cpp
/* * Tencent is pleased to support the open source community by making XiaoweiSDK Demo Codes available. * * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the MIT License (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://opensource.org/licenses/MIT * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. * */ #include <stdlib.h> #include <jni.h> #include <android/log.h> #include "XWeiJNIDef.h" #include "OpusDecoder.h" #include "opus.h" #include <map> #include <string.h> COpusDecoder::COpusDecoder(size_t sample, size_t channel, size_t max_frames) : sample_(sample), channel_(channel), max_frames_(max_frames), decoder_(NULL), opus_buffer_(NULL), pcm_buffer_(NULL) { } COpusDecoder::~COpusDecoder() { if (decoder_) opus_decoder_destroy(decoder_); if (opus_buffer_) delete[] opus_buffer_; if (pcm_buffer_) delete[] pcm_buffer_; } size_t COpusDecoder::Decode(const unsigned char *data, int data_len, char *outPcm) { if (data == NULL) { return -1; } if (outPcm == NULL) { return -1; } int total_frames = 0; if (!decoder_) { int err = 0; decoder_ = opus_decoder_create(sample_, channel_, &err); } if (!opus_buffer_) { opus_buffer_ = new opus_int16[max_frames_ * channel_]; } if (!pcm_buffer_) { pcm_buffer_ = new char[max_frames_ * channel_ * 2]; } int outLength = 0; if (decoder_ && opus_buffer_ && pcm_buffer_) { int frames = 0; do { frames = opus_decode(decoder_, data, data_len, opus_buffer_, max_frames_, 0); if (frames <= 0) { __android_log_print(ANDROID_LOG_ERROR, LOGFILTER, "COpusDecoder::onTTSPush opus decode error=%d, origin len=%d", frames, data_len); break; } for (int i = 0; i < frames; i++) { pcm_buffer_[i * 2] = (char) ((opus_buffer_[i]) & 0xFF); pcm_buffer_[i * 2 + 1] = (char) ((opus_buffer_[i] >> 8) & 0xFF); } total_frames += frames; int length = frames * channel_ * 2; memcpy(outPcm + outLength, pcm_buffer_, length); outLength += length; } while (frames == max_frames_); } return outLength; } class CDecoderMgr { public: bool Start(int id, int sample, int channel, int max_frames); int Decode(int id, const unsigned char *data, int data_length, char *outPcm); bool Stop(int id); private: std::map<int, COpusDecoder *> map_; }; bool CDecoderMgr::Start(int id, int sample, int channel, int max_frames) { std::map<int, COpusDecoder *>::iterator itr = map_.find(id); if (map_.end() != itr) { delete (itr->second); } COpusDecoder *decoder = new COpusDecoder(sample, channel, max_frames); map_[id] = decoder; return true; } int CDecoderMgr::Decode(int id, const unsigned char *data, int data_length, char *outPcm) { int result = 0; std::map<int, COpusDecoder *>::iterator itr = map_.find(id); if (map_.end() != itr) { COpusDecoder *decoder = itr->second; if (decoder) { result = decoder->Decode(data, data_length, outPcm); } } return result; } bool CDecoderMgr::Stop(int id) { bool result = false; std::map<int, COpusDecoder *>::iterator itr = map_.find(id); if (map_.end() != itr) { COpusDecoder *decoder = itr->second; if (decoder) { delete decoder; } map_.erase(itr); result = true; } return result; } CDecoderMgr g_decoderMgr; #ifdef __cplusplus extern "C" { #endif JNIEXPORT void JNICALL Java_com_tencent_xiaowei_control_OpusDecoder_init(JNIEnv *env, jclass service, jint id, jint sample, jint channel) { g_decoderMgr.Start(id, sample, channel, 960 * 6); } JNIEXPORT jbyteArray JNICALL Java_com_tencent_xiaowei_control_OpusDecoder_decoder(JNIEnv *env, jclass service, jint id, jbyteArray data) { int nBufLen = 0; unsigned char *pBuffer = NULL; char *pOutBuffer = NULL; if (NULL != data) { nBufLen = env->GetArrayLength(data); if (nBufLen > 0) { pBuffer = new unsigned char[nBufLen]; memset(pBuffer, 0, nBufLen); env->GetByteArrayRegion(data, 0, nBufLen, (jbyte *) pBuffer); pOutBuffer = new char[960 * 6 * 2]; memset(pOutBuffer, 0, 960 * 6 * 2); int length = g_decoderMgr.Decode(id, reinterpret_cast<const unsigned char *>(pBuffer), nBufLen, pOutBuffer); if(length <=0 ){ delete[]pOutBuffer; delete[]pBuffer; return NULL; } jbyteArray jbuf = env->NewByteArray(length); env->SetByteArrayRegion(jbuf, 0, length, (jbyte *) pOutBuffer); delete[]pOutBuffer; delete[]pBuffer; return jbuf; } } return NULL; } JNIEXPORT void JNICALL Java_com_tencent_xiaowei_control_OpusDecoder_unInit(JNIEnv *env, jclass service, jint id) { g_decoderMgr.Stop(id); } #ifdef __cplusplus } #endif
Rudy02/CPP-Fundementals
templates/templates_multi_parameters/example_1/main.cpp
<gh_stars>0 /************************************************************************* * <NAME> * main.cpp * * This program takes two numbers and displays the smallest of the two. * This is done by creating a function template that takes in two * parameters. Our function is called smaller(), with two parameters * T and U. T and U represent two generic variables to hold the data * type we are going to work with. * * Key note is that the return type may * only be one of the datatypes that we pass in. Since two are being * passed in, the datatype chosen to be returned will by the first * to be passed in; in this case T. * * **********************************************************************/ #include <iostream> using namespace std; template <class T, class U> //Assed another generic data type U T smaller(T &a, U &b) { return (a<b?a:b); //Ternary Operators: (condition) ? (If TRUE) : (If FALSE) } int main() { int x = 89; double y = 20.56; cout << smaller(x,y) << endl; }
frederico-neres/orange-talents-05-template-mercado-livre
src/main/java/br/com/zupacademy/frederico/treinomercadolivre/treinomercadolivre/security/DetailsService.java
package br.com.zupacademy.frederico.treinomercadolivre.treinomercadolivre.security; import br.com.zupacademy.frederico.treinomercadolivre.treinomercadolivre.dominio.usuario.Usuario; import io.jsonwebtoken.Jwts; import net.bytebuddy.implementation.bytecode.Throw; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import java.util.List; @Service public class DetailsService implements UserDetailsService { @PersistenceContext EntityManager entityManager; @Override public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException { String jpql = "SELECT u FROM Usuario u WHERE u.login = :login"; Query query = entityManager.createQuery(jpql); query.setParameter("login", login); try { Usuario usuario = (Usuario) query.getSingleResult(); return usuario; }catch (NoResultException exception) { throw new UsernameNotFoundException("Dados invalidos"); } } }
rixwwd/vaccination-scheduler
vaccination-scheduler-admin/src/main/java/com/github/rixwwd/vaccination_scheduler/admin/service/PublicUserUploadService.java
package com.github.rixwwd.vaccination_scheduler.admin.service; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import javax.validation.groups.Default; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.BeanPropertyBindingResult; import org.springframework.validation.BindException; import org.springframework.validation.SmartValidator; import com.fasterxml.jackson.databind.MappingIterator; import com.fasterxml.jackson.dataformat.csv.CsvMapper; import com.fasterxml.jackson.dataformat.csv.CsvSchema; import com.fasterxml.jackson.dataformat.csv.CsvSchema.ColumnType; import com.github.rixwwd.vaccination_scheduler.admin.entity.PublicUser; import com.github.rixwwd.vaccination_scheduler.admin.repository.PublicUserRepository; @Service public class PublicUserUploadService { private static final Logger logger = LoggerFactory.getLogger(PublicUserUploadService.class); private final PublicUserRepository publicUserRepository; private final SmartValidator smartValidator; private final PasswordEncoder encoder; public PublicUserUploadService(PublicUserRepository publicUserRepository, SmartValidator smartValidator, PasswordEncoder encoder) { this.publicUserRepository = publicUserRepository; this.smartValidator = smartValidator; this.encoder = encoder; } @Transactional(rollbackFor = BindException.class) public void createPublicUserFromCsv(InputStream inputStream) throws BindException { //@formatter:off var schema = CsvSchema.builder() .addColumn("loginName", ColumnType.STRING) .addColumn("plainPassword", ColumnType.STRING) .addColumn("name", ColumnType.STRING) .addColumn("hurigana", ColumnType.STRING) .addColumn("birthday", ColumnType.STRING) .addColumn("address", ColumnType.STRING) .addColumn("telephoneNumber", ColumnType.STRING) .addColumn("email", ColumnType.STRING) .addColumn("sms", ColumnType.STRING) .setUseHeader(false) .build(); //@formatter:on var mapper = new CsvMapper(); try { MappingIterator<PublicUser> mi = mapper.readerFor(PublicUser.class).with(schema).readValues(inputStream); int lineNumber = 0; while (mi.hasNext()) { var publicUser = mi.nextValue(); var result = new BeanPropertyBindingResult(publicUser, "row" + lineNumber); smartValidator.validate(publicUser, result, Default.class, PublicUser.CreateFromCSV.class); if (result.hasErrors()) { if (logger.isDebugEnabled()) { logger.debug("CSV Validation error: " + result.toString()); } throw new BindException(result); } publicUser.setPassword(<PASSWORD>(publicUser.getPlainPassword())); publicUserRepository.save(publicUser); lineNumber++; } } catch (IOException e) { throw new UncheckedIOException(e); } } }
melonwater211/snorkel
test/classification/test_loss.py
<reponame>melonwater211/snorkel<filename>test/classification/test_loss.py import unittest import numpy as np import torch import torch.nn.functional as F from snorkel.classification import cross_entropy_with_probs from snorkel.utils import preds_to_probs class SoftCrossEntropyTest(unittest.TestCase): def test_sce_equals_ce(self): # Does soft ce loss match classic ce loss when labels are one-hot? Y_golds = torch.LongTensor([0, 1, 2]) Y_golds_probs = torch.Tensor(preds_to_probs(Y_golds.numpy(), num_classes=4)) Y_probs = torch.rand_like(Y_golds_probs) Y_probs = Y_probs / Y_probs.sum(dim=1).reshape(-1, 1) ce_loss = F.cross_entropy(Y_probs, Y_golds, reduction="none") ces_loss = cross_entropy_with_probs(Y_probs, Y_golds_probs, reduction="none") np.testing.assert_equal(ce_loss.numpy(), ces_loss.numpy()) ce_loss = F.cross_entropy(Y_probs, Y_golds, reduction="sum") ces_loss = cross_entropy_with_probs(Y_probs, Y_golds_probs, reduction="sum") np.testing.assert_equal(ce_loss.numpy(), ces_loss.numpy()) ce_loss = F.cross_entropy(Y_probs, Y_golds, reduction="mean") ces_loss = cross_entropy_with_probs(Y_probs, Y_golds_probs, reduction="mean") np.testing.assert_equal(ce_loss.numpy(), ces_loss.numpy()) def test_perfect_predictions(self): # Does soft ce loss achieve approx. 0 loss with perfect predictions? Y_golds = torch.LongTensor([0, 1, 2]) Y_golds_probs = torch.Tensor(preds_to_probs(Y_golds.numpy(), num_classes=4)) Y_probs = Y_golds_probs.clone() Y_probs[Y_probs == 1] = 100 Y_probs[Y_probs == 0] = -100 ces_loss = cross_entropy_with_probs(Y_probs, Y_golds_probs) np.testing.assert_equal(ces_loss.numpy(), 0) def test_lower_loss(self): # Is loss lower when it should be? Y_golds_probs = torch.tensor([[0.1, 0.9], [0.5, 0.5]]) Y_probs1 = torch.tensor([[0.1, 0.3], [1.0, 0.0]]) Y_probs2 = torch.tensor([[0.1, 0.2], [1.0, 0.0]]) ces_loss1 = cross_entropy_with_probs(Y_probs1, Y_golds_probs) ces_loss2 = cross_entropy_with_probs(Y_probs2, Y_golds_probs) self.assertLess(ces_loss1, ces_loss2) def test_equal_loss(self): # Is loss equal when it should be? Y_golds_probs = torch.tensor([[0.1, 0.9], [0.5, 0.5]]) Y_probs1 = torch.tensor([[0.1, 0.3], [1.0, 0.0]]) Y_probs2 = torch.tensor([[0.1, 0.3], [0.0, 1.0]]) ces_loss1 = cross_entropy_with_probs(Y_probs1, Y_golds_probs) ces_loss2 = cross_entropy_with_probs(Y_probs2, Y_golds_probs) self.assertEqual(ces_loss1, ces_loss2) def test_invalid_reduction(self): Y_golds = torch.LongTensor([0, 1, 2]) Y_golds_probs = torch.Tensor(preds_to_probs(Y_golds.numpy(), num_classes=4)) Y_probs = torch.rand_like(Y_golds_probs) Y_probs = Y_probs / Y_probs.sum(dim=1).reshape(-1, 1) with self.assertRaisesRegex(ValueError, "Keyword 'reduction' must be"): cross_entropy_with_probs(Y_probs, Y_golds_probs, reduction="bad") def test_loss_weights(self): FACTOR = 10 # Do class weights work as expected? Y_golds = torch.LongTensor([0, 0, 1]) Y_golds_probs = torch.Tensor(preds_to_probs(Y_golds.numpy(), num_classes=3)) # Predict [1, 1, 1] Y_probs = torch.tensor( [[-100.0, 100.0, -100.0], [-100.0, 100.0, -100.0], [-100.0, 100.0, -100.0]] ) ces_loss0 = cross_entropy_with_probs(Y_probs, Y_golds_probs).numpy() weight1 = torch.FloatTensor([1, 1, 1]) ces_loss1 = cross_entropy_with_probs( Y_probs, Y_golds_probs, weight=weight1 ).numpy() # Do weights of 1 match no weights at all? self.assertEqual(ces_loss0, ces_loss1) weight2 = torch.FloatTensor([1, 2, 1]) ces_loss2 = cross_entropy_with_probs( Y_probs, Y_golds_probs, weight=weight2 ).numpy() weight3 = weight2 * FACTOR ces_loss3 = cross_entropy_with_probs( Y_probs, Y_golds_probs, weight=weight3 ).numpy() # If weights are X times larger, is loss X times larger? self.assertAlmostEqual(ces_loss2 * FACTOR, ces_loss3, places=3) # Note that PyTorch's cross-entropy loss has the unusual behavior that weights # behave differently when losses are averaged inside vs. outside the function. # See https://github.com/pytorch/pytorch/issues/8062 for details. ce_loss3 = ( F.cross_entropy(Y_probs, Y_golds, weight=weight3, reduction="none") .mean() .numpy() ) # Do hard and soft ce loss still match when we use class weights? self.assertAlmostEqual(ce_loss3, ces_loss3, places=3) if __name__ == "__main__": unittest.main()
rafamel/rest-api-boilerplate
package-scripts.js
const path = require('path'); const scripts = (x) => ({ scripts: x }); const exit0 = (x) => `${x} || shx echo `; const series = (...x) => `(${x.join(') && (')})`; const dir = (file) => path.join(CONFIG_DIR, file); const ts = (cmd) => (TYPESCRIPT ? cmd : 'shx echo'); const dotted = (ext) => '.' + ext.replace(/,/g, ',.'); const { APP_NAME, DOCS_DIR, CONFIG_DIR, EXTENSIONS, TYPESCRIPT } = require('./project.config'); process.env.LOG_LEVEL = 'disable'; module.exports = scripts({ start: series( exit0(`shx mkdir ${DOCS_DIR} logs`), `cross-env NODE_ENV=production pm2 start index.js --name ${APP_NAME}` ), stop: `pm2 stop ${APP_NAME}`, dev: { default: series( exit0(`shx mkdir ${DOCS_DIR} logs`), 'onchange "./src/**/*" --initial --kill -- nps private.dev' ), db: 'nps private.dev_db' }, spec: series( exit0(`shx mkdir ${DOCS_DIR}`), `jake docs:spec[${DOCS_DIR}/spec.json]`, `speccy lint --skip info-contact ${DOCS_DIR}/spec.json`, `swagger-cli validate ${DOCS_DIR}/spec.json` ), fix: [ 'prettier', `--write "./**/*.{${EXTENSIONS},json,scss}"`, `--config "${dir('.prettierrc.js')}"`, `--ignore-path "${dir('.prettierignore')}"` ].join(' '), lint: { default: [ 'concurrently', '"nps spec"', `"eslint ./src --ext ${dotted(EXTENSIONS)} -c ${dir('.eslintrc.js')}"`, `"${ts(`tslint ./src/**/*.{ts,tsx} -c ${dir('tslint.json')}`)}"`, `"${ts('tsc --noEmit')}"`, '-n spec,eslint,tslint,tsc', '-c gray,yellow,blue,magenta' ].join(' '), test: `eslint ./test --ext ${dotted(EXTENSIONS)} -c ${dir('.eslintrc.js')}`, md: `markdownlint *.md --config ${dir('markdown.json')}`, scripts: 'jake lintscripts[' + __dirname + ']' }, test: { default: series('nps lint.test', `cross-env NODE_ENV=test jest`), watch: 'onchange "./test/**/*" --initial --kill -- nps private.test_watch' }, validate: 'nps lint lint.test lint.md lint.scripts test private.validate_last', update: 'npm update --save/save-dev && npm outdated', clean: series( exit0(`shx rm -r ${DOCS_DIR} coverage logs captain-definition`), 'shx rm -rf node_modules' ), docs: { default: 'nps docs.redoc', redoc: series( 'nps spec', `redoc-cli bundle ${DOCS_DIR}/spec.json --options.pathInMiddlePanel --options.showExtensions --options.requiredPropsFirst --options.hideHostname --options.expandResponses="200,201"`, `shx mv redoc-static.html ${DOCS_DIR}/index.html` ), shins: series( 'nps spec', `api2html -o ${DOCS_DIR}/shins.html -l shell,javascript--nodejs ${DOCS_DIR}/spec.json` ) }, // Private private: { dev: series( 'jake clear', 'shx echo "____________\n"', 'concurrently "cross-env NODE_ENV=development node ./index.js" "nps lint" -n node,+ -c green,gray' ), test_watch: series('jake clear', 'nps test'), validate_last: `npm outdated || jake countdown`, dev_db: 'jake docker:dockerize' + JSON.stringify([ `${APP_NAME}-dev-postgres`, 'postgres:11-alpine', '5432:5432', 'POSTGRES_PASSWORD:<PASSWORD>' ]), add: { docker: series( 'docker version', 'shx cp setup/Dockerfile ./', 'shx cp setup/.dockerignore ./', `docker build --rm -f ./Dockerfile -t ${APP_NAME} ./`, exit0('docker rmi $(docker images -q -f dangling=true)'), 'shx rm Dockerfile .dockerignore' ), captain: 'jake captain' } } });
sylvaindeker/Radium-Engine
src/Core/Animation/HandleWeightOperation.cpp
<reponame>sylvaindeker/Radium-Engine<filename>src/Core/Animation/HandleWeightOperation.cpp #include <Core/Animation/HandleWeightOperation.hpp> #include <Core/Utils/Log.hpp> #include <utility> namespace Ra { namespace Core { namespace Animation { WeightMatrix extractWeightMatrix( const MeshWeight& weight, const uint weight_size ) { WeightMatrix W( weight.size(), weight_size ); W.setZero(); for ( uint i = 0; i < weight.size(); ++i ) { for ( const auto& w : weight[i] ) { W.coeffRef( i, w.first ) = w.second; } } return W; } MeshWeight extractMeshWeight( Eigen::Ref<const WeightMatrix> matrix ) { MeshWeight W( matrix.rows() ); for ( int i = 0; i < matrix.rows(); ++i ) { for ( int j = 0; j < matrix.cols(); ++j ) { if ( matrix.coeff( i, j ) != 0.0 ) { std::pair<uint, Scalar> w( uint( j ), matrix.coeff( i, j ) ); W[i].push_back( w ); } } } return W; } WeightMatrix partitionOfUnity( Eigen::Ref<const WeightMatrix> weights ) { WeightMatrix W = weights; normalizeWeights( W ); return W; } uint getMaxWeightIndex( Eigen::Ref<const WeightMatrix> weights, const uint vertexID ) { uint maxId = uint( -1 ); Math::VectorN row = weights.row( vertexID ); row.maxCoeff( &maxId ); return maxId; } void getMaxWeightIndex( Eigen::Ref<const WeightMatrix> weights, std::vector<uint>& handleID ) { handleID.resize( weights.rows() ); for ( int i = 0; i < weights.rows(); ++i ) { handleID[i] = getMaxWeightIndex( weights, i ); } } bool checkWeightMatrix( Eigen::Ref<const WeightMatrix> matrix, const bool FAIL_ON_ASSERT, const bool MT ) { bool ok = Math::MatrixUtils::checkInvalidNumbers( matrix, FAIL_ON_ASSERT ) && checkNoWeightVertex( matrix, FAIL_ON_ASSERT, MT ); if ( !ok ) { LOG( Utils::logDEBUG ) << "Matrix is not good."; } return ok; } bool checkNoWeightVertex( Eigen::Ref<const WeightMatrix> matrix, const bool FAIL_ON_ASSERT, const bool MT ) { int status = 1; LOG( Utils::logDEBUG ) << "Searching for empty rows in the matrix..."; if ( MT ) { #pragma omp parallel for for ( int i = 0; i < matrix.rows(); ++i ) { Math::Sparse row = matrix.row( i ); const int check = ( row.nonZeros() > 0 ) ? 1 : 0; #pragma omp atomic status &= check; } if ( status == 0 ) { if ( FAIL_ON_ASSERT ) { CORE_ASSERT( false, "At least a vertex as no weights" ); } else { LOG( Utils::logDEBUG ) << "At least a vertex as no weights"; } } } else { for ( int i = 0; i < matrix.rows(); ++i ) { Math::Sparse row = matrix.row( i ); if ( row.nonZeros() == 0 ) { status = 0; const std::string text = "Vertex " + std::to_string( i ) + " has no weights."; if ( FAIL_ON_ASSERT ) { CORE_ASSERT( false, text.c_str() ); } else { LOG( Utils::logDEBUG ) << text; } } } } return status != 0; } bool normalizeWeights( Eigen::Ref<WeightMatrix> matrix, const bool MT ) { CORE_UNUSED( MT ); bool skinningWeightOk = true; #pragma omp parallel for if ( MT ) for ( int k = 0; k < matrix.innerSize(); ++k ) { const Scalar sum = matrix.row( k ).sum(); if ( !Math::areApproxEqual( sum, Scalar( 0 ) ) ) { if ( !Math::areApproxEqual( sum, Scalar( 1 ) ) ) { skinningWeightOk = false; matrix.row( k ) /= sum; } } } return !skinningWeightOk; } } // namespace Animation } // Namespace Core } // Namespace Ra
jerry-sky/academic-notebook
4th-semester/aisd/lab/lista-3/ex-1/shared/algorithms/radix-sort.h
<filename>4th-semester/aisd/lab/lista-3/ex-1/shared/algorithms/radix-sort.h #pragma once #include "sort.h" /** * Sorts an arbitrary array of integers using the RadixSort algorithm. */ class RadixSort : Sort { private: int radix = 10; /** * Elect the biggest number out of the input array. */ int max(); /** * Modified CountSort algorithm for partial sorting numbers by their digits. */ void countingSort(int expOffset); public: using Sort::Sort; int *sort(); };
Magikis/Uniwersity
sztuczna_inteligencja/2-lab/main.py
from komandos import * if __name__ == '__main__': initState = getInitialState() print(shortestPathToGoal((1, 2)))
chrisk1ng/PublicTransportApp.Android
app/src/main/java/com/chrisking/publictransportapp/activities/itinerary/SelectedItineraryListItem.java
<filename>app/src/main/java/com/chrisking/publictransportapp/activities/itinerary/SelectedItineraryListItem.java package com.chrisking.publictransportapp.activities.itinerary; import android.support.constraint.ConstraintLayout; import android.support.constraint.ConstraintSet; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.chrisking.publictransportapp.R; public class SelectedItineraryListItem extends AppCompatActivity { private ConstraintLayout innerCardConstrainLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_selected_itinerary_list_item); innerCardConstrainLayout = (ConstraintLayout) findViewById(R.id.innerCard); innerCardConstrainLayout.getLayoutParams().width = 100; innerCardConstrainLayout.requestLayout(); } }
KingAlone0/Tetris-Clone
src/menu.cpp
#include "menu.hpp" #include "renderWindow.hpp" #include "text.hpp" void func_test(int a) { abort(); } void Menu(RenderWindow &window) { sf::Clock c; sf::Sprite background; sf::Texture bg; bg.loadFromFile("../textures/default-background.png"); background.setTexture(bg); Button start(V2(232.f, 133.f), sf::IntRect(0.f, 26.f, 32.f, 16.f), 4, 0.2f, sf::IntRect(0.f, 222.f, 9.f, 9.f), "Start"); start.setScale(3.f); Button options(V2(232.f, 216.f), sf::IntRect(0.f, 26.f, 32.f, 16.f), 4, 0.2f, sf::IntRect(0.f, 231.f, 9.f, 9.f), "Options"); options.setScale(3.f); Image logo(V2(214.f, 15.f), sf::IntRect(0.f, 0.f, 40.f, 23.f), 8, 0.2f); logo.setScale(3.2f); options.setOnReleasedFunction([&window]() { Options(window); } ); start.setOnReleasedFunction([&window]() { Tetris(window); } ); window.playOST(); Keyboard k; while(window.isOpen()) { if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::T)) { window.clear(); Tetris(window); c.restart(); } // NOTE: When go to the game em press Escape, is getting out of the game directly. // tried to make a static function but still don't work sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.Quit(); } } if (Keyboard::justPressedGlobal(sf::Keyboard::Key::Escape) && c.getElapsedTime().asSeconds() >= 0.2f) { window.Quit(); } // ---------------------- window.draw(background); logo.Update(&window); start.Update(&window); options.Update(&window); // ---------------------- /* // Preserve Aspect ratio if (window.getSize().x != window_size.x || window.getSize().y != window_size.y) { view.setSize((float)window.getSize().x, (float)window.getSize().y); if ((double)window.getSize().x / window.getSize().y == aspect_ratio) { view = window.getDefaultView(); // don't that, need to pick up last aspect useful std::cout << window.getSize().x << " : " << window.getSize().y << std::endl; } window.setView(view); window_size = sf::Vector2f(window.getSize()); */ window.Update(); } }
ilyasku/readdy
include/readdy/common/thread/scoped_async.h
<filename>include/readdy/common/thread/scoped_async.h /******************************************************************** * Copyright © 2018 Computational Molecular Biology Group, * * Freie Universität Berlin (GER) * * * * 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. * * 3. Neither the name of the copyright holder nor the names of * * its contributors may be used to endorse or promote products * * derived from this software without specific * * prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ********************************************************************/ /** * The definition of scoped_async. Behaves the same as scoped_thread, just with std::async as backing call. * * @file scoped_async.h * @brief Contains the definition of `readdy::util::thread::scoped_async` * @author clonker * @date 28.03.17 * @copyright BSD-3 */ #pragma once #include <future> #include <readdy/common/logging.h> namespace readdy::util::thread { class scoped_async { std::future<void> async_; public: /** * Creates a new scoped_async object that will execute a provided function with the respective arguments * asynchronously. * * @tparam Function the function type * @tparam Args the argument types * @param fun the function instance * @param args the arguments */ template<typename Function, typename... Args> explicit scoped_async(Function &&fun, Args &&... args) : async_(std::async(std::launch::async, std::forward<Function>(fun), std::forward<Args>(args)...)) {} /** * wait for the task to finish if valid */ ~scoped_async() { if (async_.valid()) async_.wait(); } /** * no copying */ scoped_async(const scoped_async &) = delete; /** * no copy assign */ scoped_async &operator=(const scoped_async &) = delete; /** * move is permitted */ scoped_async(scoped_async &&) = default; /** * move assign is permitted */ scoped_async &operator=(scoped_async &&) = default; }; }
Bangerok/Ninja
ninja-security/src/main/java/ru/bangerok/enterprise/ninja/util/CookieUtils.java
package ru.bangerok.enterprise.ninja.util; import java.util.Arrays; import java.util.Base64; import java.util.List; import java.util.Optional; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.util.SerializationUtils; /** * <p> Class for working with cookies. Used before sending an authorization request to the provider * and after receiving a response from him. </p> * * @author Vladislav [Bangerok] Kuznetsov. * @since 0.3.0 */ public class CookieUtils { private static final List<String> WHITE_LIST = Arrays.asList("oauth2_auth_request", "redirect_uri"); private CookieUtils() { throw new IllegalStateException("Utility class"); } /** * Static method for getting cookie from request. * * @param request request. * @param name cookie name. * @return optional с cookie. */ public static Optional<Cookie> getCookie(HttpServletRequest request, String name) { var cookies = request.getCookies(); if (cookies != null && cookies.length > 0) { for (var cookie : cookies) { if (cookie.getName().equals(name)) { return Optional.of(cookie); } } } return Optional.empty(); } /** * Static method for adding a new cookie to the request response. * * @param response response. * @param name the name of the new cookie. * @param value the value of the new cookie. */ public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) { var cookie = new Cookie(name, value); cookie.setPath("/"); cookie.setHttpOnly(true); cookie.setMaxAge(maxAge); response.addCookie(cookie); } /** * Static method to remove cookie from request response. * * @param request request. * @param response response. * @param name the name of the old cookie. */ public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String name) { var cookies = request.getCookies(); if (cookies != null && cookies.length > 0 && WHITE_LIST.contains(name)) { Arrays.stream(cookies).filter(cookie -> cookie.getName().equals(name)).forEach(cookie -> { cookie.setValue(""); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie); }); } } /** * Static method for serializing cookie. * * @param object cookie. * @return the string representation of the cookie. */ public static String serialize(Object object) { return Base64.getUrlEncoder().encodeToString(SerializationUtils.serialize(object)); } /** * Static method to deserialize the string representation of the cookie. * * @param cookie cookie. * @param cls the class for the value in the cookie. * @return cookie object representation. */ public static <T> T deserialize(Cookie cookie, Class<T> cls) { return cls .cast(SerializationUtils.deserialize(Base64.getUrlDecoder().decode(cookie.getValue()))); } }
nempyxa17/mathtr
app/src/main/java/com/nempyxa/mathtr/ui/MathtrFragment.java
package com.nempyxa.mathtr.ui; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import com.nempyxa.mathtr.databinding.FragmentMathtrBinding; import com.nempyxa.mathtr.log.Logger; import com.nempyxa.mathtr.viewmodel.MathtrViewModel; public class MathtrFragment extends Fragment implements NumericKeypadView.OnClickListener { private MathtrViewModel mViewModel; private FragmentMathtrBinding mBinding; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mViewModel = new ViewModelProvider(requireActivity()).get(MathtrViewModel.class); mBinding = FragmentMathtrBinding.inflate(inflater, container, false); mBinding.setListener(this); mBinding.numericKeypad.setOnClickListener(this); return mBinding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mViewModel.getQuestionText().observe(getViewLifecycleOwner(), text -> { mBinding.questionView.setText(text); mBinding.setAnswerText(""); }); } @Override public void onResume() { super.onResume(); Logger.d("onResume"); mViewModel.checkSettingsChanged(); } @Override public void onDestroyView() { super.onDestroyView(); mBinding = null; } public void onAnswerTextChanged(CharSequence s, int start, int before, int count) { mViewModel.verify(String.valueOf(s)); } @Override public void onClick(NumericKeypadView.Keys key) { String answerText = mBinding.answerView.getText().toString(); switch (key) { case ZERO: case ONE: case TWO: case THREE: case FOUR: case FIVE: case SIX: case SEVEN: case EIGHT: case NINE: answerText = answerText + key.getStringValue(); break; case BACKSPACE: answerText = answerText.length() > 0 ? answerText.substring(0, answerText.length() - 1) : answerText; break; case NEXT: mViewModel.playNext(); break; default: throw new IllegalArgumentException("Invalid key: " + key); } mBinding.setAnswerText(answerText); } @Override public void onLongClick(NumericKeypadView.Keys key) { if (key == NumericKeypadView.Keys.BACKSPACE) { mBinding.setAnswerText(""); } } }
SergeyZadorozhniy/google-cloud-java
google-cloud-clients/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Transaction.java
<gh_stars>1-10 /* * Copyright 2015 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.datastore; import com.google.protobuf.ByteString; import java.util.Iterator; import java.util.List; /** * A Google cloud datastore transaction. * Similar to {@link Batch} any write operation that is applied on a transaction will only be sent * to the Datastore upon {@link #commit}. A call to {@link #rollback} will invalidate * the transaction and discard the changes. Any read operation that is done by a transaction * will be part of it and therefore a {@code commit} is guaranteed to fail if an entity * was modified outside of the transaction after it was read. Write operation on this * transaction will not be reflected by read operation (as the changes are only sent to * the Datastore upon {@code commit}. * A usage example: * <pre> {@code * Transaction transaction = datastore.newTransaction(); * try { * Entity entity = transaction.get(key); * if (!entity.contains("last_name") || entity.isNull("last_name")) { * String[] name = entity.getString("name").split(" "); * entity = Entity.newBuilder(entity) * .remove("name") * .set("first_name", name[0]) * .set("last_name", name[1]) * .build(); * transaction.update(entity); * transaction.commit(); * } * } finally { * if (transaction.isActive()) { * transaction.rollback(); * } * } * } </pre> * * @see <a href="https://cloud.google.com/datastore/docs/concepts/transactions"> * Google Cloud Datastore transactions</a> * */ public interface Transaction extends DatastoreBatchWriter, DatastoreReaderWriter { interface Response { /** * Returns a list of keys generated by a transaction. */ List<Key> getGeneratedKeys(); } /** * {@inheritDoc} * The requested entity will be part of this Datastore transaction (so a commit is guaranteed * to fail if entity was changed by others after it was seen by this transaction) but any * write changes in this transaction will not be reflected by the returned entity. * * <p>Example of getting an entity for a given key. * <pre> {@code * String keyName = "my_key_name"; * Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); * Entity entity = transaction.get(key); * transaction.commit(); * // Do something with the entity * }</pre> * * @throws DatastoreException upon failure or if no longer active */ @Override Entity get(Key key); /** * {@inheritDoc} * The requested entities will be part of this Datastore transaction (so a commit is guaranteed * to fail if any of the entities was changed by others after they were seen by this transaction) * but any write changes in this transaction will not be reflected by the returned entities. * * <p>Example of getting entities for several keys. * <pre> {@code * String firstKeyName = "my_first_key_name"; * String secondKeyName = "my_second_key_name"; * KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); * Key firstKey = keyFactory.newKey(firstKeyName); * Key secondKey = keyFactory.newKey(secondKeyName); * Iterator<Entity> entitiesIterator = transaction.get(firstKey, secondKey); * List<Entity> entities = Lists.newArrayList(); * while (entitiesIterator.hasNext()) { * Entity entity = entitiesIterator.next(); * // do something with the entity * entities.add(entity); * } * transaction.commit(); * }</pre> * * @throws DatastoreException upon failure or if no longer active */ @Override Iterator<Entity> get(Key... key); /** * {@inheritDoc} * The requested entities will be part of this Datastore transaction (so a commit is guaranteed * to fail if any of the entities was changed by others after they were seen by this transaction) * but any write changes in this transaction will not be reflected by the returned entities. * * <p>Example of fetching a list of entities for several keys. * <pre> {@code * String firstKeyName = "my_first_key_name"; * String secondKeyName = "my_second_key_name"; * KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); * Key firstKey = keyFactory.newKey(firstKeyName); * Key secondKey = keyFactory.newKey(secondKeyName); * List<Entity> entities = transaction.fetch(firstKey, secondKey); * for (Entity entity : entities) { * // do something with the entity * } * transaction.commit(); * }</pre> * * @throws DatastoreException upon failure or if no longer active */ @Override List<Entity> fetch(Key... keys); /** * {@inheritDoc} * The entities returned by the result of this query will be part of this Datastore transaction * (so a commit is guaranteed to fail if any of the entities was changed by others after the * query was performed) but any write changes in this transaction will not be reflected by * the result. * * <p>Example of running a query to find all entities with an ancestor. * <pre> {@code * String parentKeyName = "my_parent_key_name"; * KeyFactory keyFactory = datastore.newKeyFactory().setKind("ParentKind"); * Key parentKey = keyFactory.newKey(parentKeyName); * // Build a query * Query<Entity> query = Query.newEntityQueryBuilder() * .setKind("MyKind") * .setFilter(PropertyFilter.hasAncestor(parentKey)) * .build(); * QueryResults<Entity> results = transaction.run(query); * List<Entity> entities = Lists.newArrayList(); * while (results.hasNext()) { * Entity result = results.next(); * // do something with result * entities.add(result); * } * transaction.commit(); * }</pre> * * @throws DatastoreException upon failure or if no longer active */ @Override <T> QueryResults<T> run(Query<T> query); /** * Datastore add operation. This method will also allocate id for any entity with an incomplete * key. As opposed to {@link #add(FullEntity)} and {@link #add(FullEntity...)}, this method will * defer any necessary id allocation to commit time. * * <p>Example of adding multiple entities with deferred id allocation. * <pre> {@code * IncompleteKey key1 = datastore.newKeyFactory().setKind("MyKind").newKey(); * FullEntity.Builder entityBuilder1 = FullEntity.newBuilder(key1); * entityBuilder1.set("propertyName", "value1"); * FullEntity entity1 = entityBuilder1.build(); * * IncompleteKey key2 = datastore.newKeyFactory().setKind("MyKind").newKey(); * FullEntity.Builder entityBuilder2 = FullEntity.newBuilder(key2); * entityBuilder2.set("propertyName", "value2"); * FullEntity entity2 = entityBuilder2.build(); * * transaction.addWithDeferredIdAllocation(entity1, entity2); * Response response = transaction.commit(); * }</pre> * * @throws DatastoreException if a given entity with a complete key was already added to this * transaction or if the transaction is no longer active */ void addWithDeferredIdAllocation(FullEntity<?>... entities); /** * {@inheritDoc} * * <p>Example of adding a single entity. * <pre> {@code * String keyName = "my_key_name"; * Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); * Entity.Builder entityBuilder = Entity.newBuilder(key); * entityBuilder.set("propertyName", "value"); * Entity entity = entityBuilder.build(); * transaction.add(entity); * transaction.commit(); * }</pre> * * @throws DatastoreException if a given entity with the same complete key was already added to * this writer, if the transaction is no longer active or if id allocation for an entity with * an incomplete key failed */ @Override Entity add(FullEntity<?> entity); /** * {@inheritDoc} * * <p>Example of adding multiple entities. * <pre> {@code * String keyName1 = "my_key_name1"; * String keyName2 = "my_key_name2"; * Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); * Entity.Builder entityBuilder1 = Entity.newBuilder(key1); * entityBuilder1.set("propertyName", "value1"); * Entity entity1 = entityBuilder1.build(); * * Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); * Entity.Builder entityBuilder2 = Entity.newBuilder(key2); * entityBuilder2.set("propertyName", "value2"); * Entity entity2 = entityBuilder2.build(); * * transaction.add(entity1, entity2); * transaction.commit(); * }</pre> * * @throws DatastoreException if a given entity with the same complete key was already added to * this writer, if the transaction is no longer active or if id allocation for an entity with * an incomplete key failed */ @Override List<Entity> add(FullEntity<?>... entities); /** * {@inheritDoc} * This operation will be converted to {@link #put} operation for entities that were already * added or put in this writer. * * <p>Example of updating multiple entities. * <pre> {@code * String keyName1 = "my_key_name1"; * String keyName2 = "my_key_name2"; * Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); * Entity.Builder entityBuilder1 = Entity.newBuilder(key1); * entityBuilder1.set("propertyName", "value3"); * Entity entity1 = entityBuilder1.build(); * * Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); * Entity.Builder entityBuilder2 = Entity.newBuilder(key2); * entityBuilder2.set("propertyName", "value4"); * Entity entity2 = entityBuilder2.build(); * * transaction.update(entity1, entity2); * transaction.commit(); * }</pre> * * @throws DatastoreException if an entity is marked for deletion in this transaction or if the * transaction is no longer active */ @Override void update(Entity... entities); /** * {@inheritDoc} * This operation will also remove from this transaction any prior writes for entities with the * same keys. * * <p>Example of deleting multiple entities. * <pre> {@code * String keyName1 = "my_key_name1"; * String keyName2 = "my_key_name2"; * Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); * Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); * transaction.delete(key1, key2); * transaction.commit(); * }</pre> * * @throws DatastoreException upon failure or if no longer active */ @Override void delete(Key... keys); /** * Datastore put operation. This method will also allocate id for any entity with an incomplete * key. As opposed to {@link #put(FullEntity)} and {@link #put(FullEntity...)}, this method will * defer any necessary id allocation to commit time. * * <p>Example of putting multiple entities with deferred id allocation. * <pre> {@code * IncompleteKey key1 = datastore.newKeyFactory().setKind("MyKind").newKey(); * FullEntity.Builder entityBuilder1 = FullEntity.newBuilder(key1); * entityBuilder1.set("propertyName", "value1"); * FullEntity entity1 = entityBuilder1.build(); * * IncompleteKey key2 = datastore.newKeyFactory().setKind("MyKind").newKey(); * FullEntity.Builder entityBuilder2 = FullEntity.newBuilder(key2); * entityBuilder2.set("propertyName", "value2"); * FullEntity entity2 = entityBuilder2.build(); * * transaction.putWithDeferredIdAllocation(entity1, entity2); * Response response = transaction.commit(); * }</pre> * * @throws IllegalArgumentException if any of the given entities is missing a key * @throws DatastoreException if no longer active */ void putWithDeferredIdAllocation(FullEntity<?>... entities); /** * {@inheritDoc} * This operation will also remove from this transaction any prior writes for the same entity. * * <p>Example of putting a single entity. * <pre> {@code * String keyName = "my_key_name"; * Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); * Entity.Builder entityBuilder = Entity.newBuilder(key); * entityBuilder.set("propertyName", "value"); * Entity entity = entityBuilder.build(); * transaction.put(entity); * transaction.commit(); * }</pre> * * @throws DatastoreException if id allocation for an entity with an incomplete key failed or if * the transaction is no longer active */ @Override Entity put(FullEntity<?> entity); /** * {@inheritDoc} * This operation will also remove from this transaction any prior writes for the same entities. * * <p>Example of putting multiple entities. * <pre> {@code * String keyName1 = "my_key_name1"; * String keyName2 = "my_key_name2"; * Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); * Entity.Builder entityBuilder1 = Entity.newBuilder(key1); * entityBuilder1.set("propertyName", "value1"); * Entity entity1 = entityBuilder1.build(); * * Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); * Entity.Builder entityBuilder2 = Entity.newBuilder(key2); * entityBuilder2.set("propertyName", "value2"); * Entity entity2 = entityBuilder2.build(); * * transaction.put(entity1, entity2); * transaction.commit(); * }</pre> * * @throws DatastoreException if id allocation for an entity with an incomplete key failed or if * the transaction is no longer active */ @Override List<Entity> put(FullEntity<?>... entities); /** * Commit the transaction. * * <p>Example of committing a transaction. * <pre> {@code * // create an entity * KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); * Key key = datastore.allocateId(keyFactory.newKey()); * Entity entity = Entity.newBuilder(key).set("description", "commit()").build(); * * // add the entity and commit * try { * transaction.put(entity); * transaction.commit(); * } catch (DatastoreException ex) { * // handle exception * } * }</pre> * * @throws DatastoreException if could not commit the transaction or if no longer active */ Response commit(); /** * Rollback the transaction. * * <p>Example of rolling back a transaction. * <pre> {@code * // create an entity * KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); * Key key = datastore.allocateId(keyFactory.newKey()); * Entity entity = Entity.newBuilder(key).set("description", "rollback()").build(); * * // add the entity and rollback * transaction.put(entity); * transaction.rollback(); * // calling transaction.commit() now would fail * }</pre> * * @throws DatastoreException if transaction was already committed */ void rollback(); /** * Returns {@code true} if the transaction is still active (was not committed or rolledback). * * <p>Example of verifying if a transaction is active. * <pre> {@code * // create an entity * KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); * Key key = datastore.allocateId(keyFactory.newKey()); * Entity entity = Entity.newBuilder(key).set("description", "active()").build(); * // calling transaction.active() now would return true * try { * // add the entity and commit * transaction.put(entity); * transaction.commit(); * } finally { * // if committing succeeded * // then transaction.active() will be false * if (transaction.isActive()) { * // otherwise it's true and we need to rollback * transaction.rollback(); * } * } * }</pre> * */ @Override boolean isActive(); /** * Returns the transaction associated {@link Datastore}. */ Datastore getDatastore(); ByteString getTransactionId(); }
idmontie/gptp
SCT-Plugin/hooks/unit_speed_inject.cpp
<gh_stars>1-10 #include "unit_speed.h" #include "../hook_tools.h" namespace { //Inject with jmpPatch() void __declspec(naked) getModifiedUnitSpeedWrapper() { static CUnit *unit; static u32 speed; __asm { PUSHAD MOV ebp, esp MOV unit, edx MOV speed, eax } speed = hooks::getModifiedUnitSpeedHook(unit, speed); __asm { POPAD MOV EAX, speed RETN } } //Inject with jmpPatch() void __declspec(naked) getModifiedUnitAccelerationWrapper() { static CUnit *unit; static u32 acceleration; __asm { PUSHAD MOV ebp, esp MOV unit, ecx } acceleration = hooks::getModifiedUnitAccelerationHook(unit); __asm { POPAD MOV EAX, acceleration RETN } } //Inject with jmpPatch() void __declspec(naked) getModifiedUnitTurnSpeedWrapper() { static CUnit *unit; static u32 turnSpeed; __asm { PUSHAD MOV ebp, esp MOV unit, ecx } turnSpeed = hooks::getModifiedUnitTurnSpeedHook(unit); __asm { POPAD MOV EAX, turnSpeed RETN } } } //unnamed namespace namespace hooks { void injectUnitSpeedHooks() { jmpPatch(getModifiedUnitSpeedWrapper, 0x0047B5F0); jmpPatch(getModifiedUnitAccelerationWrapper, 0x0047B8A0); jmpPatch(getModifiedUnitTurnSpeedWrapper, 0x0047B850); } } //hooks
IBMa/AccProbe
org.a11y.utils.accprobe.accservice.win32.ia2-fragment/src/org/a11y/utils/accprobe/accservice/core/win32/ia2/IA2WindowService.java
/******************************************************************************* * Copyright (c) 2004, 2010 IBM Corporation. * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.a11y.utils.accprobe.accservice.core.win32.ia2; import org.a11y.utils.accprobe.accservice.core.win32.msaa.MsaaAccessible; import org.a11y.utils.accprobe.accservice.core.win32.msaa.MsaaWindowService; import org.a11y.utils.accprobe.core.model.InvalidComponentException; /** * @author <a href="mailto:<EMAIL>><NAME></a> * */ public class IA2WindowService extends MsaaWindowService { private static final long serialVersionUID = -4191226662163560401L; /** * not to be used by clients; made public so that native code can reference * * @param hwnd * @throws InvalidComponentException */ protected void windowCallback (int hwnd) throws InvalidComponentException { IA2Accessible ca = new IA2Accessible(hwnd, MsaaAccessible.childId_self); fireTopLevelWindowEvent(ca); } }
rhencke/engine
src/third_party/skia/tests/SrcSrcOverBatchTest.cpp
<gh_stars>1000+ /* * Copyright 2020 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // We want to make sure that if we collapse src-over down to src when blending, that batching still // works correctly with a draw that explicitly requests src. #include "include/core/SkCanvas.h" #include "include/core/SkShader.h" #include "include/core/SkSurface.h" #include "include/gpu/GrDirectContext.h" #include "tests/Test.h" #include "tools/gpu/GrContextFactory.h" DEF_GPUTEST_FOR_RENDERING_CONTEXTS(SrcSrcOverBatchTest, reporter, ctxInfo) { auto ctx = ctxInfo.directContext(); static const int kSize = 8; const SkImageInfo ii = SkImageInfo::Make(kSize, kSize, kRGBA_8888_SkColorType, kPremul_SkAlphaType); sk_sp<SkSurface> surface(SkSurface::MakeRenderTarget(ctx, SkBudgeted::kNo, ii, 0, kTopLeft_GrSurfaceOrigin, nullptr)); auto canvas = surface->getCanvas(); SkPaint paint; // Setting a shader so that we actually build a processor set and don't fallback to all // defaults. paint.setShader(SkShaders::Color(SK_ColorRED)); SkIRect rect = SkIRect::MakeWH(2, 2); canvas->drawIRect(rect, paint); // Now draw a rect with src blend mode. If we collapsed the previous draw to src blend mode (a // setting on caps plus not having any coverage), then we expect this second draw to try to // batch with it. This test is a success if we don't hit any asserts, specifically making sure // that both things we decided can be batched together claim to have the same value for // CompatibleWithCoverageAsAlpha. canvas->translate(3, 0); paint.setBlendMode(SkBlendMode::kSrc); canvas->drawIRect(rect, paint); }
zhangkn/iOS14Header
Applications/SharingViewService/AppleTVSetupHomePickerViewController.h
<filename>Applications/SharingViewService/AppleTVSetupHomePickerViewController.h<gh_stars>1-10 // // Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20). // // Copyright (C) 1997-2019 <NAME>. // #import "SVSBaseViewController.h" @class NSArray, UIActivityIndicatorView, UIButton, UILabel, UIPickerView, UIView; @interface AppleTVSetupHomePickerViewController : SVSBaseViewController { UILabel *_titleLabel; // 32 = 0x20 UIPickerView *_homePickerView; // 40 = 0x28 UIButton *_chooseButton; // 48 = 0x30 _Bool _homeChosen; // 56 = 0x38 UIView *_progressView; // 64 = 0x40 UIActivityIndicatorView *_progressSpinner; // 72 = 0x48 UILabel *_progressLabel; // 80 = 0x50 long long _defaultHomeIndex; // 88 = 0x58 NSArray *_homes; // 96 = 0x60 } - (void).cxx_destruct; // IMP=0x00000001000190c4 @property(retain, nonatomic) NSArray *homes; // @synthesize homes=_homes; @property(nonatomic) long long defaultHomeIndex; // @synthesize defaultHomeIndex=_defaultHomeIndex; - (id)pickerView:(id)arg1 titleForRow:(long long)arg2 forComponent:(long long)arg3; // IMP=0x0000000100018fa4 - (long long)pickerView:(id)arg1 numberOfRowsInComponent:(long long)arg2; // IMP=0x0000000100018f4c - (long long)numberOfComponentsInPickerView:(id)arg1; // IMP=0x0000000100018f44 - (void)handleDismissButton:(id)arg1; // IMP=0x0000000100018eac - (void)handleChooseButton:(id)arg1; // IMP=0x0000000100018c70 - (void)viewDidDisappear:(_Bool)arg1; // IMP=0x0000000100018bd8 - (void)viewWillAppear:(_Bool)arg1; // IMP=0x0000000100018b1c @end
jsmestad/multiple_man
spec/identity_spec.rb
require 'spec_helper' describe MultipleMan::Identity do let(:record) { double(:model, id: 1, foo: 'foo', bar: 'bar' )} context "with identifier" do subject { described_class.build(record, identifier: identifier).value } let(:identifier) { :id } context "proc identifier" do let(:identifier) { lambda{|record| "#{record.foo}-#{record.id}" } } it { should == "foo-1" } end context "symbol identifier" do let(:identifier) { :foo } it { should == "foo" } end context "id identifier" do let(:identifier) { :id } it { should == "1" } end it "should log a deprecation notice" do MultipleMan.logger.should_receive(:warn) subject end end context "with identify_by" do subject { described_class.build(record, identify_by: identify_by).value } context "single field" do let(:identify_by) { :foo } it { should == { foo: 'foo'} } end context "no identify_by" do let(:identify_by) { nil } it { should == { id: 1 } } end context "multiple_fields" do let(:identify_by) { [:foo, :bar] } it { should == { foo: 'foo', bar: 'bar' } } end end end
443070582/lina
soubaoShopMobile/build/generated/source/r/debug/com/handmark/pulltorefresh/library/R.java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.handmark.pulltorefresh.library; public final class R { public static final class anim { public static final int slide_in_from_bottom = 0x7f040011; public static final int slide_in_from_top = 0x7f040012; public static final int slide_out_to_bottom = 0x7f040015; public static final int slide_out_to_top = 0x7f040016; } public static final class attr { public static final int ptrAdapterViewBackground = 0x7f01008f; public static final int ptrAnimationStyle = 0x7f01008b; public static final int ptrDrawable = 0x7f010085; public static final int ptrDrawableBottom = 0x7f010091; public static final int ptrDrawableEnd = 0x7f010087; public static final int ptrDrawableStart = 0x7f010086; public static final int ptrDrawableTop = 0x7f010090; public static final int ptrHeaderBackground = 0x7f010080; public static final int ptrHeaderSubTextColor = 0x7f010082; public static final int ptrHeaderTextAppearance = 0x7f010089; public static final int ptrHeaderTextColor = 0x7f010081; public static final int ptrListViewExtrasEnabled = 0x7f01008d; public static final int ptrMode = 0x7f010083; public static final int ptrOverScroll = 0x7f010088; public static final int ptrRefreshableViewBackground = 0x7f01007f; public static final int ptrRotateDrawableWhilePulling = 0x7f01008e; public static final int ptrScrollingWhileRefreshingEnabled = 0x7f01008c; public static final int ptrShowIndicator = 0x7f010084; public static final int ptrSubHeaderTextAppearance = 0x7f01008a; } public static final class dimen { public static final int header_footer_left_right_padding = 0x7f07006a; public static final int header_footer_top_bottom_padding = 0x7f07006b; public static final int indicator_corner_radius = 0x7f070073; public static final int indicator_internal_padding = 0x7f070074; public static final int indicator_right_padding = 0x7f070075; } public static final class drawable { public static final int default_ptr_flip = 0x7f020067; public static final int default_ptr_rotate = 0x7f020068; public static final int indicator_arrow = 0x7f0200b3; public static final int indicator_bg_bottom = 0x7f0200b4; public static final int indicator_bg_top = 0x7f0200b5; public static final int new_logo = 0x7f0200c4; } public static final class id { public static final int both = 0x7f0c003b; public static final int disabled = 0x7f0c003c; public static final int fl_inner = 0x7f0c0230; public static final int flip = 0x7f0c0042; public static final int gridview = 0x7f0c000d; public static final int manualOnly = 0x7f0c003d; public static final int pullDownFromTop = 0x7f0c003e; public static final int pullFromEnd = 0x7f0c003f; public static final int pullFromStart = 0x7f0c0040; public static final int pullUpFromBottom = 0x7f0c0041; public static final int pull_to_refresh_image = 0x7f0c0231; public static final int pull_to_refresh_progress = 0x7f0c0232; public static final int pull_to_refresh_sub_text = 0x7f0c0234; public static final int pull_to_refresh_text = 0x7f0c0233; public static final int rotate = 0x7f0c0043; public static final int scrollview = 0x7f0c0017; public static final int webview = 0x7f0c001e; } public static final class layout { public static final int pull_to_refresh_header_horizontal = 0x7f030087; public static final int pull_to_refresh_header_vertical = 0x7f030088; } public static final class string { public static final int pull_to_refresh_from_bottom_pull_label = 0x7f060010; public static final int pull_to_refresh_from_bottom_refreshing_label = 0x7f060011; public static final int pull_to_refresh_from_bottom_release_label = 0x7f060012; public static final int pull_to_refresh_pull_label = 0x7f06000d; public static final int pull_to_refresh_refreshing_label = 0x7f06000e; public static final int pull_to_refresh_release_label = 0x7f06000f; } public static final class styleable { public static final int[] PullToRefresh = { 0x7f01007f, 0x7f010080, 0x7f010081, 0x7f010082, 0x7f010083, 0x7f010084, 0x7f010085, 0x7f010086, 0x7f010087, 0x7f010088, 0x7f010089, 0x7f01008a, 0x7f01008b, 0x7f01008c, 0x7f01008d, 0x7f01008e, 0x7f01008f, 0x7f010090, 0x7f010091 }; public static final int PullToRefresh_ptrAdapterViewBackground = 16; public static final int PullToRefresh_ptrAnimationStyle = 12; public static final int PullToRefresh_ptrDrawable = 6; public static final int PullToRefresh_ptrDrawableBottom = 18; public static final int PullToRefresh_ptrDrawableEnd = 8; public static final int PullToRefresh_ptrDrawableStart = 7; public static final int PullToRefresh_ptrDrawableTop = 17; public static final int PullToRefresh_ptrHeaderBackground = 1; public static final int PullToRefresh_ptrHeaderSubTextColor = 3; public static final int PullToRefresh_ptrHeaderTextAppearance = 10; public static final int PullToRefresh_ptrHeaderTextColor = 2; public static final int PullToRefresh_ptrListViewExtrasEnabled = 14; public static final int PullToRefresh_ptrMode = 4; public static final int PullToRefresh_ptrOverScroll = 9; public static final int PullToRefresh_ptrRefreshableViewBackground = 0; public static final int PullToRefresh_ptrRotateDrawableWhilePulling = 15; public static final int PullToRefresh_ptrScrollingWhileRefreshingEnabled = 13; public static final int PullToRefresh_ptrShowIndicator = 5; public static final int PullToRefresh_ptrSubHeaderTextAppearance = 11; } }
nylen/go-compgeo
dcel/pointLoc/bench/trapezoid/trapezoid.go
<filename>dcel/pointLoc/bench/trapezoid/trapezoid.go<gh_stars>0 // trapezoid holds structures and functions for point location through // mapping a dcel to a trapezoidal map. package trapezoid import ( "github.com/oakmound/oak/physics" "github.com/nylen/go-compgeo/dcel" "github.com/nylen/go-compgeo/geom" "github.com/nylen/go-compgeo/printutil" ) // These constants refer to indices // within trapezoids' Edges const ( top = iota bot ) const ( left = iota right ) // These constants refer to indices // within trapezoids' Neighbors const ( upright = iota botright upleft botleft ) // A Trapezoid is used when contstructing a Trapezoid map, // and contains references to its neighbor trapezoids and // the edges that border it. type Trapezoid struct { // See above indices top [2]float64 // y values bot [2]float64 // y values left, right float64 // x values Neighbors [4]*Trapezoid node *Node faces [2]*dcel.Face } func (tr *Trapezoid) GetNeighbors() (*Trapezoid, *Trapezoid, *Trapezoid, *Trapezoid) { return tr.Neighbors[0], tr.Neighbors[1], tr.Neighbors[2], tr.Neighbors[3] } // DCELEdges evaluates and returns the edges of // a trapezoid as DCElEdges with initialized origins, // prevs, and nexts. func (tr *Trapezoid) DCELEdges() []*dcel.Edge { edges := make([]*dcel.Edge, 1) i := 0 edges[i] = dcel.NewEdge() edges[i].Origin = dcel.PointToVertex(geom.NewPoint(tr.left, tr.top[left], 0)) edges[i].Origin.OutEdge = edges[i] p := geom.NewPoint(tr.right, tr.top[right], 0) if !p.Eq(edges[i].Origin) { i++ edges = append(edges, dcel.NewEdge()) edges[i].Origin = dcel.PointToVertex(p) edges[i].Origin.OutEdge = edges[i] edges[i-1].Next = edges[i] edges[i].Prev = edges[i-1] } p = geom.NewPoint(tr.right, tr.bot[right], 0) if !p.Eq(edges[i].Origin) { i++ edges = append(edges, dcel.NewEdge()) edges[i].Origin = dcel.PointToVertex(p) edges[i].Origin.OutEdge = edges[i] edges[i-1].Next = edges[i] edges[i].Prev = edges[i-1] } p = geom.NewPoint(tr.left, tr.bot[left], 0) if !p.Eq(edges[i].Origin) && !p.Eq(edges[0].Origin) { i++ edges = append(edges, dcel.NewEdge()) edges[i].Origin = dcel.PointToVertex(p) edges[i].Origin.OutEdge = edges[i] edges[i-1].Next = edges[i] edges[i].Prev = edges[i-1] } // In the case of a trapezoid which is a point, // this will cause the edge to refer to itself by next // and prev, which is probably not expected by code // which iterates over edges. edges[0].Prev = edges[i] edges[i].Next = edges[0] return edges } // Rights is shorthand for setting both of // tr's right neighbors to the same value func (tr *Trapezoid) Rights(tr2 *Trapezoid) { tr.Neighbors[upright] = tr2 tr.Neighbors[botright] = tr2 } // Lefts is shorthand for setting both of // tr's left neighbors to the same value. func (tr *Trapezoid) Lefts(tr2 *Trapezoid) { tr.Neighbors[upleft] = tr2 tr.Neighbors[botleft] = tr2 } // Copy returns a trapezoid with identical edges // and neighbors. func (tr *Trapezoid) Copy() *Trapezoid { tr2 := new(Trapezoid) tr2.top = tr.top tr2.bot = tr.bot tr2.left = tr.left tr2.right = tr.right tr2.Neighbors = tr.Neighbors tr2.faces = tr.faces return tr2 } // AsPoints converts a trapezoid's internal values // into four points. func (tr *Trapezoid) AsPoints() []geom.D2 { ds := make([]geom.D2, 4) ds[0] = geom.NewPoint(tr.left, tr.top[left], 0) ds[1] = geom.NewPoint(tr.right, tr.top[right], 0) ds[2] = geom.NewPoint(tr.right, tr.bot[right], 0) ds[3] = geom.NewPoint(tr.left, tr.bot[left], 0) return ds } // BotEdge returns a translation of tr's values to // tr's bottom edge as a FullEdge func (tr *Trapezoid) BotEdge() geom.FullEdge { return geom.FullEdge{ geom.NewPoint(tr.right, tr.bot[right], 0), geom.NewPoint(tr.left, tr.bot[left], 0), } } // TopEdge acts as BotEdge for tr's top func (tr *Trapezoid) TopEdge() geom.FullEdge { return geom.FullEdge{ geom.NewPoint(tr.left, tr.top[left], 0), geom.NewPoint(tr.right, tr.top[right], 0), } } // HasDefinedPoint returns for a given Trapezoid // whether or not any of the points on the Trapezoid's // perimeter match the query point. // We make an assumption here that there will be no // edges who have vertices defined on other edges, aka // that all intersections are represented through // vertices. func (tr *Trapezoid) HasDefinedPoint(p geom.D3) bool { for _, p2 := range tr.AsPoints() { if p2.X() == p.X() && p2.Y() == p.Y() { return true } } return false } func (tr *Trapezoid) String() string { s := "" for _, p := range tr.AsPoints() { s += "(" s += printutil.Stringf64(p.X(), p.Y()) s += ")" } return s } func newTrapezoid(sp geom.Span) *Trapezoid { t := new(Trapezoid) min := sp.At(geom.SPAN_MIN).(geom.Point) max := sp.At(geom.SPAN_MAX).(geom.Point) t.top[left] = max.Y() t.top[right] = max.Y() t.bot[left] = min.Y() t.bot[right] = min.Y() t.left = min.X() t.right = max.X() t.Neighbors = [4]*Trapezoid{nil, nil, nil, nil} return t } func (tr *Trapezoid) toPhysics() []physics.Vector { vs := make([]physics.Vector, 4) for i, p := range tr.AsPoints() { vs[i] = physics.NewVector(p.X(), p.Y()) } return vs } // Replace neighbors runs replace neighbor for all directions // off of a trapezoid func (tr *Trapezoid) replaceNeighbors(rep, new *Trapezoid) { if tr == nil { return } for i := range tr.Neighbors { tr.replaceNeighbor(i, rep, new) } } // Replace neighbor checks that the input is not nil, // and if it is not, if it's neighbor in the given direction is the // expected trapezoid to replace, replaces it with the given new trapezoid. func (tr *Trapezoid) replaceNeighbor(dir int, rep, new *Trapezoid) { if tr == nil { return } if tr.Neighbors[dir] == rep { tr.Neighbors[dir] = new } } // Assign the neighbors of the trapezoid tr's upleft and upright // neighbors (if they exist) dependant on tr being replaced by // the two trapezoids u and b split at y value lpy. // // ~ ~ ~ ~ ~ ~ // ul | u // ~ ~ ~ -lpy----- // bl | b // ~ ~ ~ ~ ~ ~ func (tr *Trapezoid) replaceLeftPointers(u, b *Trapezoid, lpy float64) { replaceLeftPointers(tr, tr.Neighbors[upleft], tr.Neighbors[botleft], u, b, lpy) } // Given the trapezoid tr, being replaced by u and b where // u is above b and lpy is the point at which u and be connect // on tr's left edge, assign all pointers from ul and bl where ul // is above bl that previously pointed to tr to the appropriate // trapezoid of u and b. func replaceLeftPointers(tr, ul, bl, u, b *Trapezoid, lpy float64) { if ul != nil && geom.F64eq(ul.bot[right], lpy) { // U matches exactly to ul, // B matches exactly to bl. // // ~ ~ ~ ~ ~ ~ // ul | u // -----lpy----- // bl | b // ~ ~ ~ ~ ~ ~ // ul.replaceNeighbors(tr, u) bl.replaceNeighbors(tr, b) } else if (ul != nil && geom.F64eq(ul.top[right], lpy)) || (ul == nil && bl != nil && geom.F64eq(bl.top[right], lpy)) { // U does not border the left edge // // ~ ~ ~ lpy \ // (ul) \ \ u // ~ ~ ~ ~ \ b \ // (bl) \ \ // ~ ~ ~ ~ ~ ~ ~ ul.replaceNeighbors(tr, b) bl.replaceNeighbors(tr, b) if ul != nil { b.Neighbors[upleft] = ul } else { b.Neighbors[upleft] = bl } if bl != nil { b.Neighbors[botleft] = bl } else { b.Neighbors[botleft] = ul } u.Lefts(b) } else if (bl != nil && geom.F64eq(bl.bot[right], lpy)) || (bl == nil && ul != nil && geom.F64eq(ul.bot[right], lpy)) { // D does not border the left edge // // ~ ~ ~ ~ ~ ~ ~ ~ // (ul) / / // ~ ~ ~ ~ / u / // (bl) / / b // ~ ~ ~ lpy / ~ ~ // ul.replaceNeighbors(tr, u) bl.replaceNeighbors(tr, u) if bl != nil { u.Neighbors[botleft] = bl } else { u.Neighbors[botleft] = ul } if ul != nil { u.Neighbors[upleft] = ul } else { u.Neighbors[upleft] = bl } b.Lefts(u) } else if ul != nil && ul.bot[right] < lpy { // UL expands past FE // // ~ ~ ~ ~ ~ ~ ~ ~ ~ // ul | u // lpy ~ ~ ~ // ~ ~ ~ ~ | b // bl | // ~ ~ ~ ~ ~ ~ ~ ~ ~ // if ul != bl { bl.replaceNeighbors(tr, b) } ul.replaceNeighbor(upright, tr, u) ul.replaceNeighbor(botright, tr, b) u.Lefts(ul) b.Neighbors[upleft] = ul b.Neighbors[botleft] = bl } else if bl != nil && bl.top[right] > lpy { // BL expands past FE // // ~ ~ ~ ~ ~ ~ ~ ~ ~ // ul | u // ~ ~ ~ ~ | // lpy ~ ~ ~ // bl | b // ~ ~ ~ ~ ~ ~ ~ ~ ~ // if ul != bl { ul.replaceNeighbors(tr, u) } bl.replaceNeighbor(upright, tr, u) bl.replaceNeighbor(botright, tr, b) b.Lefts(bl) u.Neighbors[upleft] = ul u.Neighbors[botleft] = bl } } // ~ ~ ~ ~ ~ ~ // u | ur // --rpy ~ ~ ~ // b | br // ~ ~ ~ ~ ~ ~ func (tr *Trapezoid) replaceRightPointers(u, b *Trapezoid, rpy float64) { replaceRightPointers(tr, tr.Neighbors[upright], tr.Neighbors[botright], u, b, rpy) } func replaceRightPointers(tr, ur, br, u, b *Trapezoid, rpy float64) { if ur != nil && geom.F64eq(ur.bot[left], rpy) { // U matches exactly to ur, // B matches exactly to br. // // ~ ~ ~ ~ ~ ~ // u | ur // -----rpy----- // b | br // ~ ~ ~ ~ ~ ~ // ur.replaceNeighbors(tr, u) br.replaceNeighbors(tr, b) } else if (ur != nil && geom.F64eq(ur.top[left], rpy)) || (ur == nil && br != nil && geom.F64eq(br.top[left], rpy)) { // U does not border the right edge // // ~ ~ rpy ~ ~ ~ // u / / (ur) // / b / ~ ~ ~ // / / (br) // ~ ~ ~ ~ ~ ~ // ur.replaceNeighbors(tr, b) br.replaceNeighbors(tr, b) u.Rights(b) if ur != nil { b.Neighbors[upright] = ur } else { b.Neighbors[upright] = br } if br != nil { b.Neighbors[botright] = br } else { b.Neighbors[botright] = ur } } else if (br != nil && geom.F64eq(br.bot[left], rpy)) || (br == nil && ur != nil && geom.F64eq(ur.bot[left], rpy)) { // // ~ ~ rpy ~ ~ ~ // \ \ ur // \ u \ ~ ~ ~ // b \ \ br // ~ ~ rpy ~ ~ ~ // ur.replaceNeighbors(tr, u) br.replaceNeighbors(tr, u) b.Rights(u) if ur != nil { u.Neighbors[upright] = ur } else { u.Neighbors[upright] = br } if br != nil { u.Neighbors[botright] = br } else { u.Neighbors[botright] = ur } } else if ur != nil && ur.bot[left] < rpy { // UR expands past FE // // ~ ~ ~ ~ ~ ~ ~ ~ ~ // u | ur // ~ ~ ~ ~rpy // | ~ ~ ~ ~ // b | br // ~ ~ ~ ~ ~ ~ ~ ~ ~ // if ur != br { br.replaceNeighbors(tr, b) } ur.replaceNeighbor(upleft, tr, u) ur.replaceNeighbor(botleft, tr, b) u.Rights(ur) b.Neighbors[upright] = ur b.Neighbors[botright] = br } else if br != nil && br.top[left] > rpy { // BR expands past FE // // ~ ~ ~ ~ ~ ~ ~ ~ ~ // u | ur // | ~ ~ ~ ~ // ~ ~ ~ ~rpy br // b | // ~ ~ ~ ~ ~ ~ ~ ~ ~ // if ur != br { ur.replaceNeighbors(tr, u) } br.replaceNeighbor(upleft, tr, u) br.replaceNeighbor(botleft, tr, b) b.Rights(br) u.Neighbors[upright] = ur u.Neighbors[botright] = br } } func (tr *Trapezoid) twoRights(u, b *Trapezoid, lpy float64) { tr.Neighbors[upright] = u tr.Neighbors[botright] = b if geom.F64eq(tr.top[right], lpy) { tr.Neighbors[upright] = b } else if geom.F64eq(tr.bot[right], lpy) { tr.Neighbors[botright] = u } u.Lefts(tr) b.Lefts(tr) } func (tr *Trapezoid) twoLefts(u, b *Trapezoid, rpy float64) { tr.Neighbors[upleft] = u tr.Neighbors[botleft] = b if geom.F64eq(tr.top[left], rpy) { tr.Neighbors[upleft] = b } else if geom.F64eq(tr.bot[left], rpy) { tr.Neighbors[botleft] = u } u.Rights(tr) b.Rights(tr) } func splitExactly(u, d *Trapezoid, fe geom.FullEdge) { u.exactly(top, fe) d.exactly(bot, fe) } func (tr *Trapezoid) exactly(d int, fe geom.FullEdge) { lp := fe.Left() rp := fe.Right() tr.left = lp.X() tr.right = rp.X() if d == bot { tr.top[left] = lp.Y() tr.top[right] = rp.Y() } else if d == top { tr.bot[left] = lp.Y() tr.bot[right] = rp.Y() } } func (tr *Trapezoid) setBotleft(fe geom.FullEdge) { r := tr.right if r > fe.Right().X() { r = fe.Right().X() } l := tr.left if l < fe.Left().X() { l = fe.Left().X() } edge, _ := fe.SubEdge(0, l, r) tr.bot[left] = edge.Left().Y() tr.bot[right] = edge.Right().Y() } func (tr *Trapezoid) setTopleft(fe geom.FullEdge) { r := tr.right if r > fe.Right().X() { r = fe.Right().X() } l := tr.left if l < fe.Left().X() { l = fe.Left().X() } edge, _ := fe.SubEdge(0, l, r) tr.top[left] = edge.Left().Y() tr.top[right] = edge.Right().Y() }
cxsper/saleor
saleor/lib/python3.7/site-packages/measurement/measures/__init__.py
<gh_stars>1-10 from measurement.measures.distance import * from measurement.measures.energy import * from measurement.measures.temperature import * from measurement.measures.volume import * from measurement.measures.mass import * from measurement.measures.speed import * from measurement.measures.time import * from measurement.measures.voltage import * from measurement.measures.resistance import * from measurement.measures.capacitance import * from measurement.measures.frequency import * from measurement.measures.current import *
KenMan79/hubble
app/models/prime/accounts/terra.rb
<filename>app/models/prime/accounts/terra.rb class Prime::Accounts::Terra < Prime::Account def details @details ||= ::Terra::AccountDecorator.new(::Terra::Chain.find_by(slug: network.primary.slug), address) end def rewards @rewards ||= network.primary.client.prime_rewards(self) end end
jmcarbo/gomsgraph
msgraph/beta/models/oauth2_permission_grant.go
<reponame>jmcarbo/gomsgraph package models import ( "time" ) type OAuth2PermissionGrant struct { Id *string `json:"id,omitempty"` // The id of the client service principal for the application which is authorized to act on behalf of a signed-in user when accessing an API. Required. Supports $filter (eq only). ClientId *string `json:"clientId,omitempty"` // Indicates if authorization is granted for the client application to impersonate all users or only a specific user. AllPrincipals indicates authorization to impersonate all users. Principal indicates authorization to impersonate a specific user. Consent on behalf of all users can be granted by an administrator. Non-admin users may be authorized to consent on behalf of themselves in some cases, for some delegated permissions. Required. Supports $filter (eq only). ConsentType *string `json:"consentType,omitempty"` // Currently, the end time value is ignored, but a value is required when creating an oAuth2PermissionGrant. Required. ExpiryTime *time.Time `json:"expiryTime,omitempty"` // The id of the user on behalf of whom the client is authorized to access the resource, when consentType is Principal. If consentType is AllPrincipals this value is null. Required when consentType is Principal. PrincipalId *string `json:"principalId,omitempty"` // The id of the resource service principal to which access is authorized. This identifies the API which the client is authorized to attempt to call on behalf of a signed-in user. ResourceId *string `json:"resourceId,omitempty"` // A space-separated list of the claim values for delegated permissions which should be included in access tokens for the resource application (the API). For example, openid User.Read GroupMember.Read.All. Each claim value should match the value field of one of the delegated permissions defined by the API, listed in the publishedPermissionScopes property of the resource service principal. Scope *string `json:"scope,omitempty"` // Currently, the start time value is ignored, but a value is required when creating an oAuth2PermissionGrant. Required. StartTime *time.Time `json:"startTime,omitempty"` }
mhmmdgamal/ecommerce
src/main/java/com/ecommerce/admin/comment/ManageCommentController.java
package com.ecommerce.admin.comment; import com.ecommerce.general.comment.Comment; import com.ecommerce.general.item.Item; import com.ecommerce.general.user.User; import com.ecommerce.general.comment.CommentDaoImpl; import com.ecommerce.general.item.ItemDaoImpl; import com.ecommerce.general.user.UserDaoImpl; import com.ecommerce.general.helper.Helper; import com.ecommerce.general.path.ViewPath; import java.io.IOException; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.annotation.WebServlet; @WebServlet("/admin/manage-comments") public class ManageCommentController extends HttpServlet { ServletContext servletContext = null; @Override public void init() throws ServletException { servletContext = getServletContext(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // set page title Helper.setTitle(request, "Manage Comments"); // get all users with out pendings users List<User> users = new UserDaoImpl(servletContext).getAllUsers(false); // System.out.println(users); // get all items with assending order List<Item> items = new ItemDaoImpl(servletContext).getAllItems("ASC"); // get all comments with assending order List<Comment> comments = new CommentDaoImpl(servletContext).getAllComments("ASC"); // set users to request request.setAttribute("users", users); // set items to request request.setAttribute("items", items); // set comments to request request.setAttribute("comments", comments); // forword request to manage page Helper.forwardRequest(request, response, ViewPath.manage_comment_admin); } }
MotionResearchLabs/pathfinder
vendor/periph.io/x/periph/host/pine64/doc.go
// Copyright 2016 The Periph Authors. All rights reserved. // Use of this source code is governed under the Apache License, Version 2.0 // that can be found in the LICENSE file. // Package pine64 contains Pine64 hardware logic. It is intrinsically // related to package a64. // // Requires Armbian Jessie Server. // // Physical // // http://files.pine64.org/doc/Pine%20A64%20Schematic/Pine%20A64%20Pin%20Assignment%20160119.pdf // // http://wiki.pine64.org/images/2/2e/Pine64_Board_Connector_heatsink.png package pine64
FateRevoked/mage
Mage.Tests/src/test/java/org/mage/test/rollback/ExtraTurnTest.java
<reponame>FateRevoked/mage package org.mage.test.rollback; import mage.constants.PhaseStep; import mage.constants.Zone; import org.junit.Test; import org.mage.test.serverside.base.CardTestPlayerBase; /** * * @author Quercitron */ public class ExtraTurnTest extends CardTestPlayerBase { // Test that rollback works correctly when extra turn is taken during an opponent turn. @Test public void testThatRollbackWorksCorrectlyWithExtraTurn() { addCard(Zone.BATTLEFIELD, playerA, "Island", 3); // The next sorcery card you cast this turn can be cast as though it had flash. addCard(Zone.HAND, playerA, "Quicken"); // Take an extra turn after this one. addCard(Zone.HAND, playerA, "Time Walk"); castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerA, "Quicken"); castSpell(2, PhaseStep.PRECOMBAT_MAIN, playerA, "Time Walk"); rollbackTurns(3, PhaseStep.PRECOMBAT_MAIN, playerA, 0); setStopAt(4, PhaseStep.PRECOMBAT_MAIN); execute(); assertActivePlayer(playerA); } }
EnderNightLord-ChromeBook/fuchsia-pine64-pinephone
tools/check-licenses/traverse.go
<gh_stars>10-100 // Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package checklicenses import ( "fmt" "log" "os" "strings" "sync" "golang.org/x/sync/errgroup" ) // Walk gathers all Licenses then checks for a match within each filtered file func Walk(config *Config) error { var eg errgroup.Group var wg sync.WaitGroup metrics := new(Metrics) metrics.Init() file_tree := NewFileTree(config, metrics) licenses, unlicensedFiles, err := NewLicenses(config.LicensePatternDir, config.ProhibitedLicenseTypes) if err != nil { return err } for _, l := range licenses.licenses { l := l wg.Add(1) go func() { l.MatchChannelWorker() wg.Done() }() } log.Printf("Starting singleLicenseFile walk") for tree := range file_tree.getSingleLicenseFileIterator() { tree := tree for singleLicenseFile := range tree.singleLicenseFiles { singleLicenseFile := singleLicenseFile eg.Go(func() error { if err := processSingleLicenseFile(singleLicenseFile, metrics, licenses, config, tree); err != nil { // error safe to ignore because eg. io.EOF means symlink hasn't been handled yet // TODO(jcecil): Correctly skip symlink. fmt.Printf("warning: %s. Skipping file: %s.\n", err, tree.getPath()) } return nil }) } } eg.Wait() log.Println("Starting regular file walk") for path := range file_tree.getFileIterator() { path := path eg.Go(func() error { if err := processFile(path, metrics, licenses, unlicensedFiles, config, file_tree); err != nil { // error safe to ignore because eg. io.EOF means symlink hasn't been handled yet // TODO(jcecil): Correctly skip symlink. fmt.Printf("warning: %s. Skipping file: %s.\n", err, path) } return nil }) } eg.Wait() log.Println("Done") // Close each licenses's matchChannel goroutine by sending a nil object. for _, l := range licenses.licenses { l.AddMatch(nil) } wg.Wait() if config.ExitOnProhibitedLicenseTypes { filesWithProhibitedLicenses := licenses.GetFilesWithProhibitedLicenses() if len(filesWithProhibitedLicenses) > 0 { files := strings.Join(filesWithProhibitedLicenses, "\n") return fmt.Errorf("Encountered prohibited license types. File paths are:\n%v", files) } } if config.ExitOnUnlicensedFiles && len(unlicensedFiles.files) > 0 { files := strings.Join(unlicensedFiles.files, "\n") return fmt.Errorf("Encountered files that are missing licenses. File paths are:\n%v", files) } if config.OutputLicenseFile { file, err := createOutputFile(config) if err != nil { return err } saveToOutputFile(file, licenses, config, metrics) } metrics.print() return nil } func processSingleLicenseFile(base string, metrics *Metrics, licenses *Licenses, config *Config, file_tree *FileTree) error { path := strings.TrimSpace(file_tree.getPath() + base) // For singe license files, we increase the max read size // to be the size of the file. max_read_size := config.MaxReadSize file_stats, err := os.Stat(path) if err == nil { max_read_size = file_stats.Size() } data, err := readFromFile(path, max_read_size) if err != nil { return err } licenses.MatchSingleLicenseFile(data, base, metrics, file_tree) return nil } func processFile(path string, metrics *Metrics, licenses *Licenses, unlicensedFiles *UnlicensedFiles, config *Config, file_tree *FileTree) error { log.Printf("visited file or dir: %q", path) data, err := readFromFile(path, config.MaxReadSize) if err != nil { return err } is_matched := licenses.MatchFile(data, path, metrics) if !is_matched { project := file_tree.getProjectLicense(path) if project == nil { metrics.increment("num_unlicensed") unlicensedFiles.files = append(unlicensedFiles.files, path) fmt.Printf("File license: missing. Project license: missing. path: %s\n", path) } else { metrics.increment("num_with_project_license") for _, arr_license := range project.singleLicenseFiles { for i, license := range arr_license { license.mu.Lock() for author := range license.matches { license.matches[author].files = append(license.matches[author].files, path) } license.mu.Unlock() if i == 0 { metrics.increment("num_one_file_matched_to_one_single_license") } log.Printf("project license: %s", license.category) metrics.increment("num_one_file_matched_to_multiple_single_licenses") } } log.Printf("File license: missing. Project license: exists. path: %s", path) } } return nil } // TODO(solomonkinard) tools/zedmon/client/pubspec.yaml" error reading: EOF
patte/styleguide
src/templates/EditorialNewsletter/schema.js
<reponame>patte/styleguide import React from 'react' import { Br } from './email/Paragraph' import HR from './email/HR' import Blockquote, { BlockquoteText, BlockquoteSource } from './email/Blockquote' import { matchType, matchZone, matchHeading, matchParagraph } from 'mdast-react-render/lib/utils' import { FigureImage } from '../../components/Figure' import { If, Else, Variable } from '../../components/Variables' import { extractImages, getDatePath, matchFigure, matchImagesParagraph } from '../Article/utils' const matchLast = (node, index, parent) => index === parent.children.length - 1 const createNewsletterSchema = ({ H2, Paragraph, Container, Cover, CoverImage, Center, Figure, Image, Caption, Byline, Sub, Sup, Button, List, ListItem, ListP, variableContext, A } = {}) => { const matchSpan = matchType('span') const globalInlines = [ { matchMdast: matchType('break'), component: Br, isVoid: true }, { matchMdast: matchType('sub'), component: Sub, editorModule: 'mark', editorOptions: { type: 'sub' } }, { matchMdast: matchType('sup'), component: Sup, editorModule: 'mark', editorOptions: { type: 'sup' } }, { matchMdast: node => matchSpan(node) && node.data?.variable, props: node => node.data, component: Variable, editorModule: 'variable', editorOptions: { insertVar: true, insertTypes: ['PARAGRAPH'], fields: [ { key: 'variable', items: [ { value: 'firstName', text: 'Vorname' }, { value: 'lastName', text: 'Nachname' } ] }, { key: 'fallback' } ] } } ] const link = { matchMdast: matchType('link'), component: A, props: node => ({ title: node.title, href: node.url }), editorModule: 'link' } const createParagraphRule = customComponent => { return { matchMdast: matchParagraph, component: customComponent || Paragraph, editorModule: 'paragraph', editorOptions: { formatButtonText: 'Paragraph', type: customComponent ? 'LISTP' : undefined }, rules: [ ...globalInlines, link, { matchMdast: matchType('strong'), component: ({ attributes, children }) => ( <strong {...attributes}>{children}</strong> ), editorModule: 'mark', editorOptions: { type: 'STRONG', mdastType: 'strong' } }, { matchMdast: matchType('emphasis'), component: ({ attributes, children }) => ( <em {...attributes}>{children}</em> ), editorModule: 'mark', editorOptions: { type: 'EMPHASIS', mdastType: 'emphasis' } } ] } } const paragraph = createParagraphRule() const listParagraph = createParagraphRule(ListP) const figureCaption = { matchMdast: matchParagraph, component: Caption, editorModule: 'figureCaption', editorOptions: { isStatic: true, afterType: 'PARAGRAPH', insertAfterType: 'CENTER', placeholder: 'Legende' }, rules: [ { matchMdast: matchType('emphasis'), component: Byline, editorModule: 'paragraph', editorOptions: { type: 'BYLINE', placeholder: 'Credit' } }, link, ...globalInlines ] } const figure = { matchMdast: matchFigure, component: Figure, editorModule: 'figure', editorOptions: { pixelNote: 'Auflösung: min. 1200x (proportionaler Schnitt)', insertButtonText: 'Bild', insertTypes: ['PARAGRAPH'], type: 'CENTERFIGURE', plainOption: true }, props: (node, index, parent) => { return node.data }, rules: [ { matchMdast: matchImagesParagraph, component: Image, props: (node, index, parent) => { const { src, srcDark } = extractImages(node) const displayWidth = 600 const { plain } = parent.data return { ...FigureImage.utils.getResizedSrcs(src, displayWidth), dark: srcDark && FigureImage.utils.getResizedSrcs(srcDark, displayWidth), alt: node.children[0].alt, plain } }, editorModule: 'figureImage', isVoid: true }, figureCaption ] } const cover = { matchMdast: (node, index, parent) => { return matchFigure(node) && index === 0 }, component: Cover, editorModule: 'figure', editorOptions: { type: 'COVERFIGURE', afterType: 'PARAGRAPH', pixelNote: 'Auflösung: min. 2000x (proportionaler Schnitt)' }, rules: [ { matchMdast: matchImagesParagraph, component: CoverImage, props: (node, index, parent) => { const { src, srcDark } = extractImages(node) const displayWidth = 1280 const setMaxWidth = parent.data.size !== undefined return { ...FigureImage.utils.getResizedSrcs(src, displayWidth, setMaxWidth), dark: srcDark && FigureImage.utils.getResizedSrcs(srcDark, displayWidth), alt: node.children[0].alt } }, editorModule: 'figureImage', editorOptions: { type: 'COVERFIGUREIMAGE' }, isVoid: true }, figureCaption ] } return { emailTemplate: 'newsletter-editorial', repoPrefix: 'newsletter-editorial-', getPath: getDatePath, rules: [ { matchMdast: matchType('root'), component: Container, editorModule: 'documentPlain', props: node => ({ meta: node.meta || {}, variableContext }), rules: [ { matchMdast: () => false, editorModule: 'meta', editorOptions: { customFields: [ { label: 'Format', key: 'format', ref: 'repo' } ], additionalFields: ['emailSubject'] } }, cover, { matchMdast: matchZone('CENTER'), component: Center, editorModule: 'center', props: (mdast, index, parent, { ancestors }) => ({ meta: ancestors[ancestors.length - 1].meta || {} }), rules: [ paragraph, figure, { matchMdast: matchHeading(2), component: H2, editorModule: 'headline', editorOptions: { type: 'h2', depth: 2, formatButtonText: 'Zwischentitel' } }, { matchMdast: matchZone('IF'), component: If, props: node => ({ present: node.data.present }), editorModule: 'variableCondition', editorOptions: { type: 'IF', insertBlock: 'greeting', insertTypes: ['PARAGRAPH'], fields: [ { key: 'present', items: [ { value: 'firstName', text: 'Vorname' }, { value: 'lastName', text: 'Nachname' } ] } ] } }, { matchMdast: matchZone('ELSE'), component: Else, editorModule: 'variableCondition', editorOptions: { type: 'ELSE' } }, { matchMdast: matchZone('BUTTON'), component: Button, props: (node, index, parent, { ancestors }) => { const link = (node.children[0] && node.children[0].children[0]) || {} return { ...node.data, title: link.title, href: link.url } }, rules: globalInlines.concat({ matchMdast: matchParagraph, component: ({ children }) => children, rules: [ { matchMdast: matchType('link'), component: ({ children }) => children, rules: globalInlines } ] }), editorModule: 'button' }, { matchMdast: matchZone('QUOTE'), component: Blockquote, editorModule: 'quote', editorOptions: { insertButtonText: 'Zitat' }, rules: [ { matchMdast: (node, index, parent) => matchParagraph(node) && (index === 0 || !matchLast(node, index, parent)), component: BlockquoteText, editorModule: 'paragraph', editorOptions: { type: 'QUOTEP', placeholder: 'Zitat' }, rules: [paragraph] }, { matchMdast: (node, index, parent) => matchParagraph(node) && matchLast(node, index, parent), component: BlockquoteSource, editorModule: 'paragraph', editorOptions: { type: 'QUOTECITE', placeholder: 'Quellenangabe / Autor' }, rules: [paragraph] } ] }, { matchMdast: matchType('list'), component: List, props: node => ({ data: { ordered: node.ordered, start: node.start } }), editorModule: 'list', rules: [ { matchMdast: matchType('listItem'), component: ListItem, editorModule: 'listItem', rules: [listParagraph] } ] }, { matchMdast: matchType('thematicBreak'), component: HR, editorModule: 'line', editorOptions: { insertButtonText: 'Trennlinie', insertTypes: ['PARAGRAPH'] }, isVoid: true } ] }, { matchMdast: () => false, editorModule: 'specialchars' } ] } ] } } export default createNewsletterSchema
degarashi/revenant
src/serialization/uri.hpp
<reponame>degarashi/revenant #pragma once #include "../uri/uri.hpp" #include "serialization/path.hpp" #include <cereal/types/utility.hpp> #include <cereal/types/vector.hpp> namespace rev { template <class Ar> void serialize(Ar& ar, UserURI& uri) { ar(uri._name); } template <class Ar> void serialize(Ar& ar, FileURI& uri) { ar(uri._path); } template <class Ar> void serialize(Ar& ar, DataURI& uri) { ar(uri._mediaType, uri._bBase64, uri._data); } } namespace cereal { template <> struct LoadAndConstruct<::rev::FileURI> { template <class Ar> static void load_and_construct(Ar& ar, cereal::construct<::rev::FileURI>& construct) { ::rev::PathBlock path; ar(path); construct(path.plain_utf8()); } }; template <> struct LoadAndConstruct<::rev::UserURI> { template <class Ar> static void load_and_construct(Ar& ar, cereal::construct<::rev::UserURI>& construct) { std::string name; ar(name); construct(name); } }; } #include <cereal/types/polymorphic.hpp> #include <cereal/archives/binary.hpp> #include <cereal/archives/json.hpp> CEREAL_REGISTER_TYPE(::rev::UserURI); CEREAL_REGISTER_TYPE(::rev::FileURI); CEREAL_REGISTER_TYPE(::rev::DataURI); CEREAL_REGISTER_POLYMORPHIC_RELATION(::rev::URI, ::rev::UserURI); CEREAL_REGISTER_POLYMORPHIC_RELATION(::rev::URI, ::rev::FileURI); CEREAL_REGISTER_POLYMORPHIC_RELATION(::rev::URI, ::rev::DataURI);
NuwanJ/Swarm-Robots-Simulator
Swarm Robots Simulator/src/communication/messageData/general/ColorData.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package communication.messageData.general; import java.awt.Color; import communication.Data; /** * * @author Nadun, Mahendra, Tharuka */ public class ColorData extends Color implements Data { public ColorData(Color c) { super(c.getRed(), c.getGreen(), c.getBlue()); } }
gscept/nebula-trifid
code/tests/testfoundation/messagereaderwritertest.cc
<gh_stars>10-100 //------------------------------------------------------------------------------ // messagereaderwritertest.cc // (C) 2006 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "messagereaderwritertest.h" #include "messaging/messagereader.h" #include "messaging/messagewriter.h" #include "io/memorystream.h" namespace Test { __ImplementClass(Test::MessageReaderWriterTest, 'MRWT', Test::TestCase); __ImplementClass(Test::TestMessage, 'TMSG', Messaging::Message); __ImplementMsgId(Test::TestMessage); using namespace Util; using namespace IO; using namespace Core; using namespace Messaging; using namespace Math; //------------------------------------------------------------------------------ /** Encode method of the test message class. */ void TestMessage::Encode(const Ptr<BinaryWriter>& writer) { Message::Encode(writer); writer->WriteString(this->command); writer->WriteFloat4(this->position); writer->WriteFloat(this->velocity); } //------------------------------------------------------------------------------ /** Decode method of the test message class. */ void TestMessage::Decode(const Ptr<BinaryReader>& reader) { Message::Decode(reader); this->command = reader->ReadString(); this->position = reader->ReadFloat4(); this->velocity = reader->ReadFloat(); } //------------------------------------------------------------------------------ /** */ void MessageReaderWriterTest::Run() { // create a few test messages Ptr<TestMessage> origMsg1 = TestMessage::Create(); origMsg1->SetCommand("Goto"); origMsg1->SetPosition(point(1.0f, 2.0f, 3.0f)); origMsg1->SetVelocity(4.0f); Ptr<TestMessage> origMsg2 = TestMessage::Create(); origMsg2->SetCommand("Flyto"); origMsg2->SetPosition(point(5.0f, 6.0f, 7.0f)); origMsg2->SetVelocity(8.0f); // create a memory stream, and attach a message writer and // message reader to it Ptr<MemoryStream> stream = MemoryStream::Create(); Ptr<MessageWriter> writer = MessageWriter::Create(); Ptr<MessageReader> reader = MessageReader::Create(); // encode the messages into the stream stream->SetAccessMode(Stream::WriteAccess); this->Verify(stream->Open()); writer->SetStream(stream.upcast<Stream>()); this->Verify(writer->Open()); writer->WriteMessage(origMsg1.upcast<Message>()); writer->WriteMessage(origMsg2.upcast<Message>()); writer->Close(); stream->Close(); // open stream for reading and read back messages stream->SetAccessMode(Stream::ReadAccess); this->Verify(stream->Open()); reader->SetStream(stream.upcast<Stream>()); this->Verify(reader->Open()); Ptr<TestMessage> copyMsg1 = (TestMessage*) reader->ReadMessage(); Ptr<TestMessage> copyMsg2 = (TestMessage*) reader->ReadMessage(); reader->Close(); stream->Close(); // verify result this->Verify(copyMsg1->IsA(TestMessage::RTTI)); this->Verify(copyMsg2->IsA(TestMessage::RTTI)); this->Verify(copyMsg1->GetCommand() == "Goto"); this->Verify(copyMsg1->GetPosition() == point(1.0f, 2.0f, 3.0f)); this->Verify(copyMsg1->GetVelocity() == 4.0f); this->Verify(copyMsg2->GetCommand() == "Flyto"); this->Verify(copyMsg2->GetPosition() == point(5.0f, 6.0f, 7.0f)); this->Verify(copyMsg2->GetVelocity() == 8.0f); } }; // namespace Test
redmic-project/device-oag-buoy-modem
test/unit/api/test_is_msg_preview.py
import unittest from vodem.api import is_msg_preview class TestIsMsgPreview(unittest.TestCase): @classmethod def setUpClass(cls): cls.valid_response = { 'is_msg_preview': '1', } def test_call(self): resp = is_msg_preview() self.assertEqual(self.valid_response, resp)
topillar/PuTTY-ng
library/view/controls/menu/menu_separator.cpp
#include "menu_separator.h" #include <windows.h> #include <uxtheme.h> #include <vssym32.h> #include "ui_gfx/canvas_skia.h" #include "ui_gfx/native_theme_win.h" #include "menu_config.h" #include "menu_item_view.h" namespace view { void MenuSeparator::OnPaint(gfx::Canvas* canvas) { const MenuConfig& config = MenuConfig::instance(); // The gutter is rendered before the background. int start_x = 0; const gfx::NativeTheme* theme = gfx::NativeTheme::instance(); if(config.render_gutter) { // If render_gutter is true, we're on Vista and need to render the // gutter, then indent the separator from the gutter. gfx::Rect gutter_bounds(MenuItemView::label_start()- config.gutter_to_label-config.gutter_width, 0, config.gutter_width, height()); gfx::NativeTheme::ExtraParams extra; theme->Paint(canvas->AsCanvasSkia(), gfx::NativeTheme::kMenuPopupGutter, gfx::NativeTheme::kNormal, gutter_bounds, extra); start_x = gutter_bounds.x() + config.gutter_width; } gfx::Rect separator_bounds(start_x, 0, width(), height()); gfx::NativeTheme::ExtraParams extra; extra.menu_separator.has_gutter = config.render_gutter; theme->Paint(canvas->AsCanvasSkia(), gfx::NativeTheme::kMenuPopupSeparator, gfx::NativeTheme::kNormal, separator_bounds, extra); } gfx::Size MenuSeparator::GetPreferredSize() { return gfx::Size(10, // Just in case we're the only item in a menu. MenuConfig::instance().separator_height); } } //namespace view
bzq360/gin
quixbugs/correct_programs/MINIMUM_SPANNING_TREE.java
<reponame>bzq360/gin package correct_programs; import faulty_programs.Node; import faulty_programs.WeightedEdge; import java.util.*; /** * Minimum spanning tree */ public class MINIMUM_SPANNING_TREE { public static Set<WeightedEdge> minimum_spanning_tree(List<WeightedEdge> weightedEdges) { Map<Node,Set<Node>> groupByNode = new HashMap<>(); Set<WeightedEdge> minSpanningTree = new HashSet<>(); Collections.sort(weightedEdges); for (WeightedEdge edge : weightedEdges) { Node vertex_u = edge.node1; Node vertex_v = edge.node2; //System.out.printf("u: %s, v: %s weight: %d\n", vertex_u.getValue(), vertex_v.getValue(), edge.weight); if (!groupByNode.containsKey(vertex_u)){ groupByNode.put(vertex_u, new HashSet<>(Arrays.asList(vertex_u))); } if (!groupByNode.containsKey(vertex_v)){ groupByNode.put(vertex_v, new HashSet<>(Arrays.asList(vertex_v))); } if (groupByNode.get(vertex_u) != groupByNode.get(vertex_v)) { minSpanningTree.add(edge); groupByNode = update(groupByNode, vertex_u, vertex_v); for (Node node : groupByNode.get(vertex_v)) { groupByNode.put(node, groupByNode.get(vertex_u)); } } } return minSpanningTree; } public static Map<Node,Set<Node>> update(Map<Node,Set<Node>> groupByNode, Node vertex_u, Node vertex_v) { Set<Node> vertex_u_span = new HashSet<>(groupByNode.get(vertex_u)); vertex_u_span.addAll(groupByNode.get(vertex_v)); groupByNode.put(vertex_u, vertex_u_span); return groupByNode; } }
PrimozLavric/VulkanRenderer
include/logi/memory/acceleration_structure_nv_impl.hpp
/** * Project Logi source code * Copyright (C) 2019 <NAME> * * 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 3 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, see <http://www.gnu.org/licenses/>. */ #ifndef LOGI_NVIDIA_ACCELERATION_STRUCTURE_NV_IMPL_HPP #define LOGI_NVIDIA_ACCELERATION_STRUCTURE_NV_IMPL_HPP #include "logi/base/common.hpp" #include "logi/base/vulkan_object.hpp" #include "logi/device/logical_device_impl.hpp" #include "logi/structures/extension.hpp" namespace logi { class VulkanInstanceImpl; class PhysicalDeviceImpl; class LogicalDeviceImpl; class AccelerationStructureNVImpl : public VulkanObject, public std::enable_shared_from_this<AccelerationStructureNVImpl> { public: AccelerationStructureNVImpl(LogicalDeviceImpl& logicalDevice, const vk::AccelerationStructureCreateInfoNV& createInfo, const std::optional<vk::AllocationCallbacks>& allocator = {}); // region Vulkan Declarations template <typename T> vk::ResultValueType<void>::type getHandleNV(vk::ArrayProxy<T> data) const; vk::MemoryRequirements2KHR getMemoryRequirementsNV(vk::AccelerationStructureMemoryRequirementsTypeNV type, const ConstVkNextProxy<vk::AccelerationStructureMemoryRequirementsInfoNV>& next = {}) const; vk::ResultValueType<void>::type bindMemory(vk::DeviceMemory memory, vk::DeviceSize memoryOffset, const vk::ArrayProxy<uint32_t>& deviceIndices = nullptr, const ConstVkNextProxy<vk::BindAccelerationStructureMemoryInfoNV>& next = {}) const; // endregion // region Logi Declarations VulkanInstanceImpl& getInstance() const; PhysicalDeviceImpl& getPhysicalDevice() const; LogicalDeviceImpl& getLogicalDevice() const; const vk::DispatchLoaderDynamic& getDispatcher() const; virtual void destroy() const; operator const vk::AccelerationStructureNV&() const; protected: void free() override; // endregion private: LogicalDeviceImpl& logicalDevice_; std::optional<vk::AllocationCallbacks> allocator_; vk::AccelerationStructureNV vkAccelerationStructureNV_; }; template <typename T> vk::ResultValueType<void>::type AccelerationStructureNVImpl::getHandleNV(vk::ArrayProxy<T> data) const { auto vkDevice = static_cast<vk::Device>(logicalDevice_); return vkDevice.getAccelerationStructureHandleNV(vkAccelerationStructureNV_, data, getDispatcher()); } } // namespace logi #endif // LOGI_NVIDIA_ACCELERATION_STRUCTURE_NV_IMPL_HPP
greck2908/dawnengine
src/dawn/renderer/Texture.cpp
/* * Dawn Engine * Written by <NAME> (c) 2012-2019 (<EMAIL>) */ #include "Base.h" #include "renderer/StbImage.h" #include "renderer/Texture.h" #include "renderer/Renderer.h" namespace dw { // Internal. namespace { int imageCallbackRead(void* user, char* data, int size) { InputStream& stream = *reinterpret_cast<InputStream*>(user); // If we want to read past the end of the buffer, clamp the size to prevent an error occurring, // as the stream API will read either the entire block or nothing at all. if ((stream.position() + size) > stream.size()) { size = static_cast<int>(stream.size() - stream.position()); } return static_cast<int>(stream.readData(data, static_cast<u32>(size))); } void imageCallbackSkip(void* user, int n) { InputStream& stream = *reinterpret_cast<InputStream*>(user); stream.seek(stream.position() + n); } int imageCallbackEof(void* user) { InputStream& stream = *reinterpret_cast<InputStream*>(user); return stream.eof() ? 1 : 0; } } // namespace Texture::Texture(Context* ctx) : Resource(ctx) { } Texture::~Texture() { if (handle_.isValid()) { module<Renderer>()->rhi()->deleteTexture(handle_); } } SharedPtr<Texture> Texture::createTexture2D(Context* ctx, const Vec2i& size, gfx::TextureFormat format, gfx::Memory data) { auto texture = makeShared<Texture>(ctx); texture->handle_ = ctx->module<Renderer>()->rhi()->createTexture2D(size.x, size.y, format, std::move(data)); return texture; } Result<void> Texture::beginLoad(const String&, InputStream& src) { stbi_io_callbacks callbacks = { &imageCallbackRead, &imageCallbackSkip, &imageCallbackEof, }; int width, height, bpp; byte* buffer = stbi_load_from_callbacks(&callbacks, reinterpret_cast<void*>(&src), &width, &height, &bpp, 4); gfx::Memory data(buffer, static_cast<usize>(width * height * 4), [](byte* buffer) { stbi_image_free(buffer); }); handle_ = module<Renderer>()->rhi()->createTexture2D( static_cast<u16>(width), static_cast<u16>(height), gfx::TextureFormat::RGBA8, std::move(data)); return Result<void>(); } gfx::TextureHandle Texture::internalHandle() const { return handle_; } } // namespace dw
dkun7944/mxml
src/mxml/dom/Identification.h
<reponame>dkun7944/mxml // Copyright © 2016 <NAME>. // // This file is part of mxml. The full mxml copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #pragma once #include "Node.h" #include <string> #include <vector> namespace mxml { namespace dom { class TypedValue { public: TypedValue() : _type(), _value() {} const std::string& type() const { return _type; } void setType(const std::string& type) { _type = type; } void setType(std::string&& type) { _type = type; } const std::string& value() const { return _value; } void setValue(const std::string& value) { _value = value; } void setName(std::string&& value) { _value = value; } private: std::string _type; std::string _value; }; class Identification : public Node { public: public: Identification() {} const std::vector<std::unique_ptr<TypedValue>>& creators() const { return _creators; } const std::string& creator(const std::string& type) const; void addCreator(std::unique_ptr<TypedValue> creator); const std::vector<std::unique_ptr<TypedValue>>& rights() const { return _rights; } const std::string& rights(const std::string& type) const; void addRights(std::unique_ptr<TypedValue> rights); const std::string& source() const { return _source; } void setSource(const std::string& source) { _source = source; } private: std::vector<std::unique_ptr<TypedValue>> _creators; std::vector<std::unique_ptr<TypedValue>> _rights; std::string _source; }; } // namespace dom } // namespace mxml
mrzhuzhe/mmdetection
mmdet/core/anchor/builder.py
# Copyright (c) OpenMMLab. All rights reserved. import warnings from mmcv.utils import Registry, build_from_cfg PRIOR_GENERATORS = Registry('Generator for anchors and points') ANCHOR_GENERATORS = PRIOR_GENERATORS def build_prior_generator(cfg, default_args=None): return build_from_cfg(cfg, PRIOR_GENERATORS, default_args) def build_anchor_generator(cfg, default_args=None): warnings.warn( '``build_anchor_generator`` would be deprecated soon, please use ' '``build_prior_generator`` ') return build_prior_generator(cfg, default_args=default_args)
nhirakawa/swarm
swarm-protocol/src/main/java/com/github/nhirakawa/swarm/protocol/protocol/MemberStatus.java
package com.github.nhirakawa.swarm.protocol.protocol; public enum MemberStatus { ALIVE, SUSPECTED, FAILED }
roroclaw/wyedu
src/main/java/com/cloud9/biz/models/SysDictItemKey.java
<gh_stars>0 package com.cloud9.biz.models; public class SysDictItemKey { private String code; private String dictType; public String getCode() { return code; } public void setCode(String code) { this.code = code == null ? null : code.trim(); } public String getDictType() { return dictType; } public void setDictType(String dictType) { this.dictType = dictType == null ? null : dictType.trim(); } }
taerok/nongbunae
back/IoTBackend/src/main/java/com/ssafy/IoTBackend/service/ChoiceService.java
package com.ssafy.IoTBackend.service; import com.ssafy.IoTBackend.model.Choice; public interface ChoiceService { public String insertChoice(Choice choice) throws Exception; public int stopChoice(String choice_id) throws Exception; public Choice selectChoice(String user_id) throws Exception; }
kolegm/simple-api-number
src/app/services/multiple.js
export default () => async (num: number|string) => { if (typeof num === 'string') { const parsed = parseInt(num); // Be attentive. The comparison must be non-strict cause string and number if (num != parsed) throw new TypeError('Incorrect number (mix of digits and alphabetic chars)'); num = parsed; } if (!Number.isInteger(num)) throw new TypeError('Number is not integer'); const result = []; if (!(num % 3)) result.push('P'); if (!(num % 5)) result.push('E'); return result.length ? result.join('') : num; };
cqcallaw/shootergame
Source/ShooterGame/Public/Online/ShooterGame_Menu.h
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "ShooterGame_Menu.generated.h" UCLASS() class AShooterGame_Menu : public AGameModeBase { GENERATED_UCLASS_BODY() public: // Begin AGameModeBase interface /** skip it, menu doesn't require player start or pawn */ virtual void RestartPlayer(class AController* NewPlayer) override; /** Returns game session class to use */ virtual TSubclassOf<AGameSession> GetGameSessionClass() const override; // End AGameModeBase interface protected: /** Perform some final tasks before hosting/joining a session. Remove menus, set king state etc */ void BeginSession(); /** Display a loading screen */ void ShowLoadingScreen(); };
daumann/ghost
core/client/controllers/reset.js
/*global console*/ /* jshint unused: false */ import ajax from 'ghost/utils/ajax'; import ValidationEngine from 'ghost/mixins/validation-engine'; var ResetController = Ember.Controller.extend(ValidationEngine, { passwords: { newPassword: '', ne2Password: '' }, token: '', submitButtonDisabled: false, validationType: 'reset', actions: { submit: function () { var self = this, data = self.getProperties('passwords', 'token'); this.toggleProperty('submitting'); this.validate({format: false}).then(function () { ajax({ url: self.get('ghostPaths.url').api('authentication', 'passwordreset'), type: 'PUT', data: { passwordreset: [{ newPassword: <PASSWORD>, ne2Password: data.<PASSWORD>, token: data.token }] } }).then(function (resp) { self.toggleProperty('submitting'); console.log('success'); self.transitionToRoute('signin'); }).catch(function (errors) { self.toggleProperty('submitting'); console.log('error'); }); }).catch(function (error) { self.toggleProperty('submitting'); // @TODO: notifications here for validation errors console.log('validation error', error); }); } } }); export default ResetController;
IFWallet/wallet-core
src/Seele/Signer.cpp
// Copyright © 2017-2019 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "Signer.h" #include "Serialization.h" #include "../Hash.h" #include "../HexCoding.h" #include "../PrivateKey.h" #include "../Data.h" #include <boost/multiprecision/cpp_int.hpp> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include <string> using namespace TW; using namespace TW::Seele; using json = nlohmann::json; using uint128_t = boost::multiprecision::uint128_t; Signer::Signer(Proto::SigningInput&& input) { this->input = input; } std::vector<uint8_t> Signer::sign() const { auto key = PrivateKey(input.private_key()); auto hash = this->hash(input.sign_transaction()); auto signature = key.sign(hash, TWCurveSECP256k1); return std::vector<uint8_t>(signature.begin(), signature.end()); } std::string Signer::signaturePreimage() const { return signaturePreimageJSON(input).dump(); } json Signer::buildTransactionJSON(const Data& signature) const { auto sig = Seele::Proto::Signature(); sig.set_sig(signature.data(), signature.size()); auto privateKey = PrivateKey(input.private_key()); auto transaction = Seele::Proto::Transaction(); auto hash = this->hash(input.sign_transaction()); *transaction.mutable_data() = input.sign_transaction(); *transaction.mutable_signature() = sig; transaction.set_hash("0x"+hex(hash)); return transactionJSON(transaction); } std::string Signer::buildTransaction() const { auto signature = sign(); return buildTransactionJSON(signature).dump(); } Proto::SigningOutput Signer::build() const { auto output = Proto::SigningOutput(); auto signature = sign(); auto txJson = buildTransactionJSON(signature); output.set_json(txJson.dump()); output.set_signature(signature.data(), signature.size()); return output; } Data Signer::hash(const Proto::SignTransaction& transaction) const noexcept { auto encoded = Data(); append(encoded, RLP::encodeLong(transaction.type())); append(encoded, RLP::encode(parse_hex(transaction.from()))); append(encoded, RLP::encode(parse_hex(transaction.to()))); append(encoded, RLP::encode(transaction.amount())); append(encoded, RLP::encode(transaction.account_nonce())); append(encoded, RLP::encodeLong(transaction.gas_price())); append(encoded, RLP::encodeLong(transaction.gas_limit())); append(encoded, RLP::encodeLong(transaction.timestamp())); append(encoded, RLP::encode(transaction.payload())); return Hash::keccak256(RLP::encodeList(encoded)); }
school-engagements/pikater-vaadin
src/net/edzard/kinetic/Kinetic.java
package net.edzard.kinetic; import java.util.List; import java.util.Map; import net.edzard.kinetic.Line.LineCap; import net.edzard.kinetic.Shape.LineJoin; import com.google.gwt.dom.client.Element; import com.google.gwt.resources.client.ImageResource; /** * Factory class for creating Kinetic objects. * Use methods from this class to create Kinetic objects. This class has some default settings that can be overridden. * Once overriden, all subsequently created objects will use the new defaults. * @author Ed */ public class Kinetic { /** Default stroke width (1 pixel) */ public static double defaultStrokeWidth = 1.0; /** Default fill colour (white) */ public static String defaultFillColour = Colour.white.toString(); /** Default stroke colour (black) */ public static String defaultStrokeColour = Colour.black.toString(); /** Default fill colour for text (black) */ public static String defaultTextFillColour = Colour.black.toString(); /** Default line cap style (ROUND) */ public static String defaultLineCap = LineCap.ROUND.toString(); /** Default line join style (ROUND) */ public static String defaultLineJoin = LineJoin.ROUND.toString(); /** Default font family (Arial) */ public static String defaultFontFamily = "Arial"; /** Default font size in pixels */ public static int defaultFontSize = 15; /** Default font style (normal) */ public static String defaultFontStyle = Text.FontStyle.NORMAL.toString(); /** Default dragability == Is a node dragable? (true) */ public static boolean defaultDragability = true; public static native String getVersion() /*-{ return $wnd.Kinetic.version; }-*/; /** * Create a node with JSON string. De-serialization does not generate custom shape drawing functions, * images, or event handlers (this would make the serialized object huge). If your app uses custom shapes, * images, and event handlers (it probably does), then you need to select the appropriate shapes after * loading the stage and set these properties via on(), setDrawFunc(), and setImage() methods */ public static native final Node createNode(String json) /*-{ return $wnd.Kinetic.Node.create(json); }-*/; /** * Create a new stage object. * @param stageContainer The DOM element that Kinetic should use * @return A stage object. * @see Stage */ public static native Stage createStage(Element stageContainer) /*-{ return new $wnd.Kinetic.Stage({ container: stageContainer, }); }-*/; /** * Create a stage with JSON string. De-serialization does not generate custom shape drawing functions, * images, or event handlers (this would make the serialized object huge). If your app uses custom shapes, * images, and event handlers (it probably does), then you need to select the appropriate shapes after * loading the stage and set these properties via on(), setDrawFunc(), and setImage() methods */ public static native final Node createStage(String json, Element stageContainer) /*-{ return $wnd.Kinetic.Node.create(json, stageContainer); }-*/; /** * Create a new stage object. * @param stageContainer The DOM element that Kinetic should use * @param stageWidth The stage's horizontal extent * @param stageHeight The stage's vertical extent * @return A stage object. * @see Stage */ public static native Stage createStage(Element stageContainer, int stageWidth, int stageHeight) /*-{ return new $wnd.Kinetic.Stage({ container: stageContainer, width: stageWidth, height: stageHeight }); }-*/; /** * Create a layer object. * The layer will be independent and needs to be added to a stage. * @return A new layer object * @see Layer */ public static native Layer createLayer() /*-{ return new $wnd.Kinetic.Layer(); }-*/; /** * Create a layer object. * This method also adds the layer to a given stage. * @param stage The stage to add the layer to * @return A new layer object * @see Layer */ public static Layer createLayer(Stage stage) { final Layer layer = Kinetic.createLayer(); stage.add(layer); return layer; } /** * Create a circle shape. * @param position The initial position * @param r The radius of the circle * @return The circle shape * @see Circle */ public static native Circle createCircle(Vector2d position, double r) /*-{ return new $wnd.Kinetic.Circle({ x: position.@net.edzard.kinetic.Vector2d::x, y: position.@net.edzard.kinetic.Vector2d::y, radius: r, fill: @net.edzard.kinetic.Kinetic::defaultFillColour, stroke: @net.edzard.kinetic.Kinetic::defaultStrokeColour, strokeWidth: @net.edzard.kinetic.Kinetic::defaultStrokeWidth, lineJoin: @net.edzard.kinetic.Kinetic::defaultLineJoin, draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create an ellipse shape. * @param position The initial position * @param radius The radius of the elipse (x and y component) * @return The ellipse shape * @see Ellipse */ public static native Ellipse createEllipse(Vector2d position, Vector2d radius) /*-{ return new $wnd.Kinetic.Ellipse({ x: position.@net.edzard.kinetic.Vector2d::x, y: position.@net.edzard.kinetic.Vector2d::y, radius: {x: radius.@net.edzard.kinetic.Vector2d::x, y: radius.@net.edzard.kinetic.Vector2d::y}, fill: @net.edzard.kinetic.Kinetic::defaultFillColour, stroke: @net.edzard.kinetic.Kinetic::defaultStrokeColour, strokeWidth: @net.edzard.kinetic.Kinetic::defaultStrokeWidth, lineJoin: @net.edzard.kinetic.Kinetic::defaultLineJoin, draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create a rectangle shape. * @param position The initial position and extent. * @return The rectangle shape * @see Rectangle */ public static native Rectangle createRectangle(Box2d position) /*-{ return new $wnd.Kinetic.Rect({ x: position.@net.edzard.kinetic.Box2d::left, y: position.@net.edzard.kinetic.Box2d::top, width: position.@net.edzard.kinetic.Box2d::right - position.@net.edzard.kinetic.Box2d::left, height: position.@net.edzard.kinetic.Box2d::bottom - position.@net.edzard.kinetic.Box2d::top, fill: @net.edzard.kinetic.Kinetic::defaultFillColour, stroke: @net.edzard.kinetic.Kinetic::defaultStrokeColour, strokeWidth: @net.edzard.kinetic.Kinetic::defaultStrokeWidth, lineJoin: @net.edzard.kinetic.Kinetic::defaultLineJoin, draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create an image shape. * @param position The initial position * @param img The image to use (no inlined image urls) * @return An image shape * @see Image */ public static native Image createImage(Vector2d position, com.google.gwt.user.client.ui.Image img) /*-{ return new $wnd.Kinetic.Image({ x: position.@net.edzard.kinetic.Vector2d::x, y: position.@net.edzard.kinetic.Vector2d::y, width: img.@com.google.gwt.user.client.ui.Image::getWidth()(), height: img.@com.google.gwt.user.client.ui.Image::getHeight()(), image: img.@com.google.gwt.user.client.ui.Image::getElement()(), draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create an image shape. * @param position The initial position * @param img The image resource to use * @return An image shape */ public static native Image createImage(Vector2d position, ImageResource res) /*-{ img = @com.google.gwt.user.client.ui.Image::new(Lcom/google/gwt/safehtml/shared/SafeUri;)(res.@com.google.gwt.resources.client.ImageResource::getSafeUri()()); return new $wnd.Kinetic.Image({ x: position.@net.edzard.kinetic.Vector2d::x, y: position.@net.edzard.kinetic.Vector2d::y, width: img.@com.google.gwt.user.client.ui.Image::getWidth()(), height: img.@com.google.gwt.user.client.ui.Image::getHeight()(), image: img.@com.google.gwt.user.client.ui.Image::getElement()(), draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create a sprite shape. * @param position The initial position * @param img The image to use for the sprite frames * @param animationKey The initial animation key * @param frames Definition of the animation sequences using croping boxes on the given image * @return A sprite object * @see Sprite */ public static Sprite createSprite(Vector2d position, com.google.gwt.user.client.ui.Image img, String animationKey, Map<String, List<Box2d>> frames) { Sprite s = createSprite(position, img, animationKey); s.setFrames(frames); return s; } /** * Create a sprite shape without the animation sequence definition. * @param position The initial position * @param img The image to use for the sprite frames * @param animationKey The initial animation key * @return A sprite object * @see Sprite */ private static native Sprite createSprite(Vector2d position, com.google.gwt.user.client.ui.Image img, String animationKey) /*-{ return new $wnd.Kinetic.Sprite({ x: position.@net.edzard.kinetic.Vector2d::x, y: position.@net.edzard.kinetic.Vector2d::y, width: img.@com.google.gwt.user.client.ui.Image::getWidth()(), height: img.@com.google.gwt.user.client.ui.Image::getHeight()(), image: img.@com.google.gwt.user.client.ui.Image::getElement()(), animation: animationKey, draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create a sprite shape. * @param position The initial position * @param res The image resource to use for the sprite frames * @param animationKey The initial animation key * @param frames Definition of the animation sequences using croping boxes on the given image * @return A sprite object * @see Sprite */ public static Sprite createSprite(Vector2d position, ImageResource res, String animationKey, Map<String, List<Box2d>> frames) { Sprite s = createSprite(position, res, animationKey); s.setFrames(frames); return s; } /** * Create a sprite shape without the animation sequence definition. * @param position The initial position * @param res The image resource to use for the sprite frames * @param animationKey The initial animation key * @param frames Definition of the animation sequences using croping boxes on the given image * @return A sprite object * @see Sprite */ private static native Sprite createSprite(Vector2d position, ImageResource res, String animationKey) /*-{ img = @com.google.gwt.user.client.ui.Image::new(Lcom/google/gwt/safehtml/shared/SafeUri;)(res.@com.google.gwt.resources.client.ImageResource::getSafeUri()()); return new $wnd.Kinetic.Sprite({ x: position.@net.edzard.kinetic.Vector2d::x, y: position.@net.edzard.kinetic.Vector2d::y, width: img.@com.google.gwt.user.client.ui.Image::getWidth()(), height: img.@com.google.gwt.user.client.ui.Image::getHeight()(), image: img.@com.google.gwt.user.client.ui.Image::getElement()(), animation: animationKey, draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create a text shape. * @param position The initial position * @param aText The text * @return A text shape * @see Text */ public static native Text createText(Vector2d position, String aText) /*-{ return new $wnd.Kinetic.Text({ x: position.@net.edzard.kinetic.Vector2d::x, y: position.@net.edzard.kinetic.Vector2d::y, text: aText, fill: @net.edzard.kinetic.Kinetic::defaultTextFillColour, fontStyle: @net.edzard.kinetic.Kinetic::defaultFontStyle, fontSize: @net.edzard.kinetic.Kinetic::defaultFontSize, fontFamily: @net.edzard.kinetic.Kinetic::defaultFontFamily, draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create a text shape that follows a SVG path. * A SVG path string is made up from path commands (see <a href="http://www.w3.org/TR/SVG/paths.html">W3C SVG 1.1 TR</a>). * @param position The initial position * @param aText The text * @param d The SVG path string * @return A text path shape * @see PathSVG */ public static native TextPath createTextPath(Vector2d position, String aText, String d) /*-{ return new $wnd.Kinetic.TextPath({ x: position.@net.edzard.kinetic.Vector2d::x, y: position.@net.edzard.kinetic.Vector2d::y, text: aText, textFill: @net.edzard.kinetic.Kinetic::defaultTextFillColour, fontStyle: @net.edzard.kinetic.Kinetic::defaultFontStyle, fontSize: @net.edzard.kinetic.Kinetic::defaultFontSize, fontFamily: @net.edzard.kinetic.Kinetic::defaultFontFamily, data: d, draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create a line shape. * The line will consist of only two points. * Use {@link Line#setPoints(List)} to set more than two. * @param start The start point * @param end The end point * @return A line object * @see Line */ public static native Line createLine(Vector2d start, Vector2d end) /*-{ return new $wnd.Kinetic.Line({ points: [start.@net.edzard.kinetic.Vector2d::x, start.@net.edzard.kinetic.Vector2d::y, end.@net.edzard.kinetic.Vector2d::x, end.@net.edzard.kinetic.Vector2d::y], stroke: @net.edzard.kinetic.Kinetic::defaultStrokeColour, strokeWidth: @net.edzard.kinetic.Kinetic::defaultStrokeWidth, lineCap: @net.edzard.kinetic.Kinetic::defaultLineCap, lineJoin: @net.edzard.kinetic.Kinetic::defaultLineJoin, draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create a line shape. * The line will consist of a number of points. * @param points * @return A line object * @see Line */ public static native Line createLine(List<Vector2d> lineDefinition) /*-{ // Create line var line = new $wnd.Kinetic.Line({ stroke: @net.edzard.kinetic.Kinetic::defaultStrokeColour, strokeWidth: @net.edzard.kinetic.Kinetic::defaultStrokeWidth, lineCap: @net.edzard.kinetic.Kinetic::defaultLineCap, lineJoin: @net.edzard.kinetic.Kinetic::defaultLineJoin, draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); // Set points var points = []; var it = lineDefinition.@java.util.List::iterator()(); while (it.@java.util.Iterator::hasNext()()) { var vec = it.@java.util.Iterator::next()(); points.push({ x: vec.@net.edzard.kinetic.Vector2d::x, y: vec.@net.edzard.kinetic.Vector2d::y }); } line.setPoints(points); return line; }-*/; /** * Create a polygonal shape. * The created polygon will be a triangle. * Use {@link Polygon#setPoints(List)} to set different shape points. * @param a First point * @param b Second point * @param c Third point * @return A triangular polagon shape * @see Polygon */ public static native Line createPolygon(Vector2d a, Vector2d b, Vector2d c) /*-{ return new $wnd.Kinetic.Polygon({ points: [{x: a.@net.edzard.kinetic.Vector2d::x, y: a.@net.edzard.kinetic.Vector2d::y}, {x: b.@net.edzard.kinetic.Vector2d::x, y: b.@net.edzard.kinetic.Vector2d::y}, {x: c.@net.edzard.kinetic.Vector2d::x, y: c.@<EMAIL>ard.kinetic.Vector2d::y}], fill: @net.edzard.kinetic.Kinetic::defaultFillColour, stroke: @net.edzard.kinetic.Kinetic::defaultStrokeColour, strokeWidth: @net.edzard.kinetic.Kinetic::defaultStrokeWidth, lineJoin: @net.edzard.kinetic.Kinetic::defaultLineJoin, draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create a regular polygon shape. * @param position The initial position * @param r The radius * @param s The number of sides * @return A regular polygon shape * @see RegularPolygon */ public static native RegularPolygon createRegularPolygon(Vector2d position, double r, int s) /*-{ return new $wnd.Kinetic.RegularPolygon({ x: position.@net.edzard.kinetic.Vector2d::x, y: position.@net.edzard.kinetic.Vector2d::y, radius: r, sides: s, fill: @net.edzard.kinetic.Kinetic::defaultFillColour, stroke: @net.edzard.kinetic.Kinetic::defaultStrokeColour, strokeWidth: @net.edzard.kinetic.Kinetic::defaultStrokeWidth, lineJoin: @net.edzard.kinetic.Kinetic::defaultLineJoin, draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create a shape that is defined by a SVG path string. * A SVG path string is made up from path commands (see <a href="http://www.w3.org/TR/SVG/paths.html">W3C SVG 1.1 TR</a>). * @param position The initial position * @param d The SVG path string * @return A SVG path shape * @see PathSVG */ public static native PathSVG createPathSVG(Vector2d position, String d) /*-{ return new $wnd.Kinetic.Path({ x: position.@net.edzard.kinetic.Vector2d::x, y: position.@net.edzard.kinetic.Vector2d::y, data: d, fill: @net.edzard.kinetic.Kinetic::defaultFillColour, stroke: @net.edzard.kinetic.Kinetic::defaultStrokeColour, strokeWidth: @net.edzard.kinetic.Kinetic::defaultStrokeWidth, lineJoin: @net.edzard.kinetic.Kinetic::defaultLineJoin, draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create a star shape. * @param position The initial position * @param innerR The inner radius of the star * @param outerR The outer radius of the star * @param num The number of points * @return A star shape * @see Star */ public static native Star createStar(Vector2d position, double innerR, double outerR, int num) /*-{ return new $wnd.Kinetic.Star({ x: position.@net.edzard.kinetic.Vector2d::x, y: position.@net.edzard.kinetic.Vector2d::y, innerRadius: innerR, outerRadius: outerR, numPoints: num, fill: @net.edzard.kinetic.Kinetic::defaultFillColour, stroke: @net.edzard.kinetic.Kinetic::defaultStrokeColour, strokeWidth: @net.edzard.kinetic.Kinetic::defaultStrokeWidth, lineJoin: @net.edzard.kinetic.Kinetic::defaultLineJoin, draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create a custom shape. * Custom shapes are defined using {@link Path} objects. * @param position The initial position * @return An undefined custom shape. A path still has to be set. * @see CustomShape */ public static native CustomShape createCustomShape(Vector2d position) /*-{ return new $wnd.Kinetic.Shape({ x: position.@net.edzard.kinetic.Vector2d::x, y: position.@net.edzard.kinetic.Vector2d::y, fill: @net.edzard.kinetic.Kinetic::defaultFillColour, stroke: @net.edzard.kinetic.Kinetic::defaultStrokeColour, strokeWidth: @net.edzard.kinetic.Kinetic::defaultStrokeWidth, lineJoin: @net.edzard.kinetic.Kinetic::defaultLineJoin, drawFunc: function(context) { if (this.path != null) { // Prepare context //var context = this.getContext(); // Iterate over commands var it = this.path.@net.edzard.kinetic.Path::getCommands()().@java.util.List::iterator()(); while (it.@java.util.Iterator::hasNext()()) { var cmd = it.@java.util.Iterator::next()(); // Process command by type switch (cmd.@net.edzard.kinetic.Path.Command::type) { // BEGIN PATH case @net.edzard.kinetic.Path.CommandType::BEGIN: context.beginPath(); break; // MOVE TO case @net.edzard.kinetic.Path.CommandType::MOVE: var vec = cmd.@net.edzard.kinetic.Path.MoveToCommand::getPosition()(); context.moveTo(vec.@net.edzard.kinetic.Vector2d::x, vec.@net.edzard.kinetic.Vector2d::y); break; // CLOSE PATH case @net.edzard.kinetic.Path.CommandType::CLOSE: context.closePath(); break; // LINE TO case @net.edzard.kinetic.Path.CommandType::LINE: var vec = cmd.@net.edzard.kinetic.Path.LineToCommand::getPosition()(); context.lineTo(vec.@net.edzard.kinetic.Vector2d::x, vec.@net.edzard.kinetic.Vector2d::y); break; // QUADRATIC CURVE case @net.edzard.kinetic.Path.CommandType::QUADRATIC: var pos = cmd.@net.edzard.kinetic.Path.QuadraticCurveCommand::getPosition()(); var cp = cmd.@net.edzard.kinetic.Path.QuadraticCurveCommand::getControlPoint()(); context.quadraticCurveTo( cp.@net.edzard.kinetic.Vector2d::x, cp.@net.edzard.kinetic.Vector2d::y, pos.@net.edzard.kinetic.Vector2d::x, pos.@net.edzard.kinetic.Vector2d::y ); break; // BEZIER CURVE case @net.edzard.kinetic.Path.CommandType::BEZIER: var pos = cmd.@net.edzard.kinetic.Path.BezierCurveCommand::getPosition()(); var cp1 = cmd.@net.edzard.kinetic.Path.BezierCurveCommand::getControlPoint1()(); var cp2 = cmd.@net.edzard.kinetic.Path.BezierCurveCommand::getControlPoint2()(); context.bezierCurveTo( cp1.@net.edzard.kinetic.Vector2d::x, cp1.@net.edzard.kinetic.Vector2d::y, cp2.@net.edzard.kinetic.Vector2d::x, cp2.@net.edzard.kinetic.Vector2d::y, pos.@net.edzard.kinetic.Vector2d::x, pos.@net.edzard.kinetic.Vector2d::y ); break; // ARCTO case @net.edzard.kinetic.Path.CommandType::ARCTO: var pos1 = cmd.@net.edzard.kinetic.Path.ArcToCommand::getPosition1()(); var pos2 = cmd.@net.edzard.kinetic.Path.ArcToCommand::getPosition2()(); var radius = cmd.@net.edzard.kinetic.Path.ArcToCommand::getRadius()(); context.arcTo( pos1.@net.edzard.kinetic.Vector2d::x, pos1.@net.edzard.kinetic.Vector2d::y, pos2.@net.edzard.kinetic.Vector2d::x, pos2.@net.edzard.kinetic.Vector2d::y, radius ); break; // ARC case @net.edzard.kinetic.Path.CommandType::ARC: var pos = cmd.@net.edzard.kinetic.Path.ArcCommand::getPosition()(); var radius = cmd.@net.edzard.kinetic.Path.ArcCommand::getRadius()(); var startAngle = cmd.@net.edzard.kinetic.Path.ArcCommand::getStartAngle()(); var endAngle = cmd.@net.edzard.kinetic.Path.ArcCommand::getEndAngle()(); var clockwise = cmd.@net.edzard.kinetic.Path.ArcCommand::isClockwise()(); context.arc( pos.@net.edzard.kinetic.Vector2d::x, pos.@net.edzard.kinetic.Vector2d::y, radius, startAngle, endAngle, !clockwise ); break; // RECT case @net.edzard.kinetic.Path.CommandType::RECT: var box = cmd.@net.edzard.kinetic.Path.RectCommand::getBox(); context.rect( box.@net.edzard.kinetic.Box2d::left, box.@net.edzard.kinetic.Box2d::top, box.@net.edzard.kinetic.Box2d::right - box.@net.edzard.kinetic.Box2d::left, box.@net.edzard.kinetic.Box2d::bottom - box.@net.edzard.kinetic.Box2d::top ); break; // TODO: ELLIPSE? }; } // Stroke and fill if (this.getFill() != null) this.fill(context); if (this.getStroke() != null) this.stroke(context); } }, draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create a shape group. * @return An empty group * @see Group */ public static native Group createGroup() /*-{ return new $wnd.Kinetic.Group({ draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create a shape group. * @param position The initial position * @param rot The initial rotation * @return A shape group with the given transformation assigned * @see Group */ public static native Group createGroup(Vector2d position, double rot) /*-{ return new $wnd.Kinetic.Group({ x: position.@net.edzard.kinetic.Vector2d::x, y: position.@net.edzard.kinetic.Vector2d::y, rotation: rot, draggable: @net.edzard.kinetic.Kinetic::defaultDragability }); }-*/; /** * Create an Animation. * @param context The context layer (animation takes place on this layer) * @param fct A custom drawing function * @return An object that can be used to control the animation */ public static native Animation createAnimation(Layer context, Drawable fct) /*-{ return new $wnd.Kinetic.Animation({ func: function(frame) { fct.@net.edzard.kinetic.Drawable::draw(Lnet/edzard/kinetic/Frame;)(@net.edzard.kinetic.Frame::new(DDD)(frame.lastTime, frame.time, frame.timeDiff)); }, node: context }); }-*/; }
maoa3/scalpel
psx/_dump_/41/_dump_c_src_/diabpsx/psxsrc/pads.h
// C:\diabpsx\PSXSRC\PADS.H #include "types.h" // address: 0x80138694 // line start: 97 // line end: 99 unsigned char CheckActive__4CPad(struct CPad *this) { } // address: 0x801571B4 // line start: 127 // line end: 131 unsigned short GetTick__C4CPad(struct CPad *this) { } // address: 0x801571DC // line start: 120 // line end: 124 unsigned short GetDown__C4CPad(struct CPad *this) { } // address: 0x80157204 // line start: 92 // line end: 92 void SetPadTickMask__4CPadUs(struct CPad *this, unsigned short mask) { } // address: 0x8015720C // line start: 91 // line end: 91 void SetPadTick__4CPadUs(struct CPad *this, unsigned short tick) { } // address: 0x80151ADC // line start: 120 // line end: 124 unsigned short GetDown__C4CPad_addr_80151ADC(struct CPad *this) { } // address: 0x80154358 // line start: 120 // line end: 124 unsigned short GetDown__C4CPad_addr_80154358(struct CPad *this) { } // address: 0x80085460 // line start: 106 // line end: 110 unsigned short GetCur__C4CPad(struct CPad *this) { } // address: 0x80085488 // line start: 97 // line end: 99 unsigned char CheckActive__4CPad_addr_80085488(struct CPad *this) { } // address: 0x800890F4 // line start: 120 // line end: 124 unsigned short GetDown__C4CPad_addr_800890F4(struct CPad *this) { } // address: 0x8008911C // line start: 97 // line end: 99 unsigned char CheckActive__4CPad_addr_8008911C(struct CPad *this) { } // address: 0x80089850 // line start: 102 // line end: 102 void SetPadType__4CPadUc(struct CPad *this, unsigned char val) { } // address: 0x80089858 // line start: 97 // line end: 99 unsigned char CheckActive__4CPad_addr_80089858(struct CPad *this) { } // address: 0x80089864 // line start: 94 // line end: 94 void SetActive__4CPadUc(struct CPad *this, unsigned char a) { } // address: 0x8008986C // line start: 87 // line end: 87 void SetBothFlag__4CPadUc(struct CPad *this, unsigned char fl) { } // address: 0x80089874 // size: 0xEC // line start: 85 // line end: 85 struct CPad *__4CPadi(struct CPad *this, int PhysStick) { } // address: 0x8009D774 // line start: 127 // line end: 131 unsigned short GetTick__C4CPad_addr_8009D774(struct CPad *this) { } // address: 0x8009D79C // line start: 120 // line end: 124 unsigned short GetDown__C4CPad_addr_8009D79C(struct CPad *this) { } // address: 0x8009D7C4 // line start: 113 // line end: 117 unsigned short GetUp__C4CPad(struct CPad *this) { } // address: 0x8009D7EC // line start: 106 // line end: 110 unsigned short GetCur__C4CPad_addr_8009D7EC(struct CPad *this) { } // address: 0x8009D814 // line start: 92 // line end: 92 void SetPadTickMask__4CPadUs_addr_8009D814(struct CPad *this, unsigned short mask) { } // address: 0x8009D81C // line start: 91 // line end: 91 void SetPadTick__4CPadUs_addr_8009D81C(struct CPad *this, unsigned short tick) { } // address: 0x800A3F34 // line start: 120 // line end: 124 unsigned short GetDown__C4CPad_addr_800A3F34(struct CPad *this) { } // address: 0x800A3F5C // line start: 106 // line end: 110 unsigned short GetCur__C4CPad_addr_800A3F5C(struct CPad *this) { } // address: 0x800AB13C // line start: 127 // line end: 131 unsigned short GetTick__C4CPad_addr_800AB13C(struct CPad *this) { } // address: 0x800AB164 // line start: 120 // line end: 124 unsigned short GetDown__C4CPad_addr_800AB164(struct CPad *this) { } // address: 0x800AB18C // line start: 113 // line end: 117 unsigned short GetUp__C4CPad_addr_800AB18C(struct CPad *this) { } // address: 0x800AB1B4 // line start: 92 // line end: 92 void SetPadTickMask__4CPadUs_addr_800AB1B4(struct CPad *this, unsigned short mask) { } // address: 0x800AB1BC // line start: 91 // line end: 91 void SetPadTick__4CPadUs_addr_800AB1BC(struct CPad *this, unsigned short tick) { } // address: 0x800AEE38 // line start: 127 // line end: 131 unsigned short GetTick__C4CPad_addr_800AEE38(struct CPad *this) { } // address: 0x800AEE60 // line start: 120 // line end: 124 unsigned short GetDown__C4CPad_addr_800AEE60(struct CPad *this) { } // address: 0x800AEE88 // line start: 92 // line end: 92 void SetPadTickMask__4CPadUs_addr_800AEE88(struct CPad *this, unsigned short mask) { } // address: 0x800AEE90 // line start: 91 // line end: 91 void SetPadTick__4CPadUs_addr_800AEE90(struct CPad *this, unsigned short tick) { } // address: 0x800B00A0 // line start: 106 // line end: 110 unsigned short GetCur__C4CPad_addr_800B00A0(struct CPad *this) { } // address: 0x8003753C // line start: 127 // line end: 131 unsigned short GetTick__C4CPad_addr_8003753C(struct CPad *this) { } // address: 0x80037564 // line start: 120 // line end: 124 unsigned short GetDown__C4CPad_addr_80037564(struct CPad *this) { } // address: 0x8003758C // line start: 92 // line end: 92 void SetPadTickMask__4CPadUs_addr_8003758C(struct CPad *this, unsigned short mask) { } // address: 0x80037594 // line start: 91 // line end: 91 void SetPadTick__4CPadUs_addr_80037594(struct CPad *this, unsigned short tick) { } // address: 0x8004E6E8 // line start: 120 // line end: 124 unsigned short GetDown__C4CPad_addr_8004E6E8(struct CPad *this) { } // address: 0x80073E10 // line start: 120 // line end: 124 unsigned short GetDown__C4CPad_addr_80073E10(struct CPad *this) { } // address: 0x8007ACC8 // line start: 120 // line end: 124 unsigned short GetDown__C4CPad_addr_8007ACC8(struct CPad *this) { } // address: 0x8007ACF0 // line start: 113 // line end: 117 unsigned short GetUp__C4CPad_addr_8007ACF0(struct CPad *this) { } // address: 0x8007AD18 // line start: 106 // line end: 110 unsigned short GetCur__C4CPad_addr_8007AD18(struct CPad *this) { } // address: 0x80082180 // line start: 120 // line end: 124 unsigned short GetDown__C4CPad_addr_80082180(struct CPad *this) { }
jonas-lj/MOSEF
test/TestModules.java
<reponame>jonas-lj/MOSEF import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import dk.jonaslindstrom.mosef.MOSEFSettings; import dk.jonaslindstrom.mosef.modules.Module; import dk.jonaslindstrom.mosef.modules.amplifier.Amplifier; import dk.jonaslindstrom.mosef.modules.delay.Delay; import dk.jonaslindstrom.mosef.modules.feedback.Feedback; import dk.jonaslindstrom.mosef.modules.misc.Constant; import dk.jonaslindstrom.mosef.modules.mixer.Mixer; import dk.jonaslindstrom.mosef.modules.oscillator.LFO; import dk.jonaslindstrom.mosef.modules.oscillator.waves.SampledWave; import dk.jonaslindstrom.mosef.modules.oscillator.waves.SquareWave; import java.util.Arrays; import java.util.stream.DoubleStream; import org.apache.commons.math3.util.FastMath; import org.junit.Assert; import org.junit.Test; public class TestModules { @Test public void testAmplifier() { int samples = 8; MOSEFSettings settings = mock(MOSEFSettings.class); when(settings.getBufferSize()).thenReturn(samples); double input = 5.0; double level = 0.5; Constant constant = new Constant(settings, 5.0); Amplifier amplifier = new Amplifier(settings, constant, 0.5); double[] actual = amplifier.getNextSamples(); double[] expected = new double[samples]; Arrays.fill(expected, input * level); Assert.assertArrayEquals(expected, actual, Double.MIN_NORMAL); } @Test public void testConstant() { int samples = 8; MOSEFSettings settings = mock(MOSEFSettings.class); when(settings.getBufferSize()).thenReturn(samples); double input = 5.0; Constant constant = new Constant(settings, 5.0); double[] actual = constant.getNextSamples(); double[] expected = new double[samples]; Arrays.fill(expected, input); Assert.assertArrayEquals(expected, actual, Double.MIN_NORMAL); } @Test public void testSquare() { int samples = 8; int sampleRate = 8; MOSEFSettings settings = mock(MOSEFSettings.class); when(settings.getBufferSize()).thenReturn(samples); when(settings.getSampleRate()).thenReturn(sampleRate); LFO square = new LFO(settings, 2, new SquareWave()); double[] actual = square.getNextSamples(); // On first iteration, we take a step before we sample, so the phase is 1 / sampleRate double[] expected = new double[]{1, -1, -1, 1, 1, -1, -1, 1}; Assert.assertArrayEquals(expected, actual, Double.MIN_NORMAL); } @Test public void testSine() { int samples = 512; int sampleRate = 512; double frequency = 3.2; MOSEFSettings settings = mock(MOSEFSettings.class); when(settings.getBufferSize()).thenReturn(samples); when(settings.getSampleRate()).thenReturn(sampleRate); LFO sine = new LFO(settings, frequency, new SampledWave(t -> FastMath .sin(2.0 * Math.PI * t), 32)); double[] actual = sine.getNextSamples(); double[] expected = DoubleStream.iterate(0.0, t -> t + 2.0 * Math.PI * frequency / sampleRate).limit(samples).map(Math::sin).toArray(); Assert.assertArrayEquals(expected, actual, 0.01); } @Test public void testMixer() { int samples = 4; MOSEFSettings settings = mock(MOSEFSettings.class); when(settings.getBufferSize()).thenReturn(samples); Module a = mock(Module.class); when(a.getNextSamples()).thenReturn(new double[] {1,2,3,4}); Module b = mock(Module.class); when(b.getNextSamples()).thenReturn(new double[] {4,5,6,7}); Mixer mixer = new Mixer(settings, a, b); double[] actual = mixer.getNextSamples(); double[] expected = new double[] {5, 7, 9, 11}; Assert.assertArrayEquals(expected, actual, Double.MIN_VALUE); } @Test public void testDelay() { int samples = 8; int sampleRate = 8; MOSEFSettings settings = mock(MOSEFSettings.class); when(settings.getBufferSize()).thenReturn(samples); when(settings.getSampleRate()).thenReturn(sampleRate); Module a = mock(Module.class); when(a.getNextSamples()).thenReturn(new double[] {1, 2, 3, 4, 5, 0, 0, 0}); Delay delay = new Delay(settings, a, new Constant(settings,0.5), 1.0); double[] actual = delay.getNextSamples(); double[] expected = new double[] {0, 0, 0, 0, 1, 2, 3, 4}; Assert.assertArrayEquals(expected, actual, Double.MIN_VALUE); actual = delay.getNextSamples(); expected = new double[] {5, 0, 0, 0, 1, 2, 3, 4}; Assert.assertArrayEquals(expected, actual, Double.MIN_VALUE); } @Test public void testFeedback() { int samples = 4; MOSEFSettings settings = mock(MOSEFSettings.class); when(settings.getBufferSize()).thenReturn(samples); Module a = mock(Module.class); when(a.getNextSamples()).thenReturn(new double[] {1, 2, 3, 4}); Feedback feedback = new Feedback(settings, a, new Constant(settings, 0.5)); Module b = mock(Module.class); when(b.getNextSamples()).thenReturn(new double[] {0, 0, 1, 1}); Module mixer = new Mixer(settings, feedback, b); Module withFeedback = feedback.attachFeedback(mixer); double[] actual = withFeedback.getNextSamples(); double[] expected = new double[] {1.5, 3.0, 5.5, 7.0}; Assert.assertArrayEquals(expected, actual, Double.MIN_VALUE); } }
moutainhigh/Huskie
my-plaform/engine/src/main/scala/com/kkb/engine/adaptor/DML/SaveAdaptor.scala
<filename>my-plaform/engine/src/main/scala/com/kkb/engine/adaptor/DML/SaveAdaptor.scala package com.kkb.engine.adaptor.DML import com.cartravel.engine.antlr.EngineParser import com.cartravel.engine.antlr.EngineParser.{AppendContext, BooleanExpressionContext, ColContext, ErrorIfExistsContext, ExpressionContext, FormatContext, IgnoreContext, NumPartitionContext, OverwriteContext, PathContext, TableNameContext, UpdateContext} import com.kkb.engine.EngineSQLExecListener import com.kkb.engine.`trait`.{ParseLogicalPlan, ParseLogicalTools} import com.kkb.engine.adaptor.BatchJobSaveAdaptor import org.apache.spark.sql.{DataFrame, SaveMode} class SaveAdaptor(engineSQLExecListener: EngineSQLExecListener) extends ParseLogicalPlan with ParseLogicalTools { var data: DataFrame = null var mode = SaveMode.ErrorIfExists //文件系统路径 var save_path = "" //存储数据的引擎:hdfs,hbase,redis var format = "" var option = Map[String, String]() var tableName: String = "" var partitionByCol = Array[String]() var numPartition: Int = 1 override def parse(ctx: EngineParser.SqlContext): Unit = { (0 until ctx.getChildCount).foreach(tokenIndex => { ctx.getChild(tokenIndex) match { case tag: OverwriteContext => mode = SaveMode.Overwrite case tag: AppendContext => mode = SaveMode.Append case tag: ErrorIfExistsContext => mode = SaveMode.ErrorIfExists case tag: IgnoreContext => mode = SaveMode.Ignore //spark里面目前不支持update操作,后续我们将要实现让spark支持update case tag: UpdateContext => option += ("savemode" -> "update") case tag: TableNameContext => { tableName = tag.getText //DataFrame注册到sparkSession临时试图中,才可以这样获取 data = engineSQLExecListener.sparkSession.table(tableName) } case tag: FormatContext => format = tag.getText case tag: PathContext => save_path = cleanStr(tag.getText) //where关键字后面的条件获取方式 case tag: ExpressionContext => option += (cleanStr(tag.identifier().getText) -> cleanStr(tag.STRING().getText)) //select * from where name=? and age=? case tag: BooleanExpressionContext => option += (cleanStr(tag.expression().identifier().getText) -> cleanStr(tag.expression().STRING().getText)) case tag: ColContext => partitionByCol = cleanStr(tag.getText).split(",") case tag:NumPartitionContext=> numPartition = tag.getText.toInt case _=> } }) //流处理和批处理的判断 if(engineSQLExecListener.env().contains("stream")){ //流处理的save操作 }else{ //批处理的save操作 new BatchJobSaveAdaptor( engineSQLExecListener, data, save_path, tableName, format, mode, partitionByCol, numPartition, option ).parse } } }
youzhengjie9/cloud-mall
cloud-mall-user/cloud-mall-user1901/src/main/java/com/boot/controller/UserDetailController.java
<filename>cloud-mall-user/cloud-mall-user1901/src/main/java/com/boot/controller/UserDetailController.java package com.boot.controller; import com.boot.enums.ResultConstant; import com.boot.pojo.UserDetail; import com.boot.service.UserDetailService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping(path = "/feign/userDetail") public class UserDetailController { @Autowired private UserDetailService userDetailService; @ResponseBody @PostMapping(path = "/updateSex") public String updateSex(@RequestBody UserDetail userDetail){ userDetailService.updateSex(userDetail.getUserid(), userDetail.getSex()); return ResultConstant.SUCCESS.getCodeStat(); } @ResponseBody @PostMapping(path = "/updateSignature") public String updateSignature(@RequestBody UserDetail userDetail){ userDetailService.updateSignature(userDetail.getUserid(),userDetail.getSignature()); return ResultConstant.SUCCESS.getCodeStat(); } //修改头像 @ResponseBody @PostMapping(path = "/updateIcon") public String updateIcon(@RequestBody UserDetail userDetail){ userDetailService.updateIcon(userDetail.getUserid(),userDetail.getIcon()); return ResultConstant.SUCCESS.getCodeStat(); } @ResponseBody @GetMapping(path = "/selectUserDetail/{userid}") public UserDetail selectUserDetail(@PathVariable("userid") long userid){ UserDetail userDetail = userDetailService.selectUserDetail(userid); return userDetail; } }
codeosseum/miles
src/main/java/com/codeosseum/miles/faultseeding/task/current/DefaultCurrentTaskServiceImpl.java
<filename>src/main/java/com/codeosseum/miles/faultseeding/task/current/DefaultCurrentTaskServiceImpl.java package com.codeosseum.miles.faultseeding.task.current; import java.util.List; import java.util.Optional; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; import com.codeosseum.miles.eventbus.dispatch.EventDispatcher; import com.codeosseum.miles.faultseeding.match.flow.setup.commencing.MatchCommencingSignal; import com.codeosseum.miles.faultseeding.task.Task; import com.codeosseum.miles.faultseeding.task.repository.TaskRepository; import com.codeosseum.miles.util.math.Span; import com.google.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.util.Objects.requireNonNull; public class DefaultCurrentTaskServiceImpl implements CurrentTaskService { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultCurrentTaskServiceImpl.class); private static final int STEP_TASK_ATTEMPTS = 10; private final TaskRepository taskRepository; private final List<Task> previousTaskList; private Span difficultySpan; private Task currentTask; private AtomicBoolean beingStepped; @Inject public DefaultCurrentTaskServiceImpl(final TaskRepository taskRepository, final EventDispatcher eventDispatcher) { this.taskRepository = taskRepository; this.currentTask = null; this.beingStepped = new AtomicBoolean(); this.difficultySpan = new Span(0, 0); this.previousTaskList = new CopyOnWriteArrayList<>(); eventDispatcher.registerConsumer(MatchCommencingSignal.class, this::reset); } @Override public void setDifficultySpan(final Span difficultySpan) { this.difficultySpan = requireNonNull(difficultySpan); } @Override public void stepCurrentTask() { guardBeingStepped(); final Task nextTask = findNextTask(); currentTask = nextTask; previousTaskList.add(nextTask); beingStepped.set(false); } @Override public Task getCurrentTask() { return currentTask; } private void reset() { this.previousTaskList.clear(); } private void guardBeingStepped() { if (!beingStepped.compareAndSet(false, true)) { throw new IllegalStateException("Already being stepped!"); } } private Task findNextTask() { for (int attempts = 0; attempts < STEP_TASK_ATTEMPTS; ++attempts) { final Optional<Task> taskOptional = taskRepository.getTaskWithDifficulty(difficultySpan); if (!taskOptional.isPresent()) { break; } else if (!previousTaskList.contains(taskOptional.get())) { return taskOptional.get(); } } throw new IllegalStateException("Could not find the next task"); } }
stalgiag/dispute-tools
src/javascripts/_entries/admin/disputes/show.js
<filename>src/javascripts/_entries/admin/disputes/show.js import NodeSupport from '../../../lib/widget/NodeSupport'; import Common from '../../../components/Common'; import * as informationForm from '../../../components/disputes/InformationForm'; const { mountDebtAmounts, default: DisputesInformationForm } = informationForm; class ViewAdminDisputesShow extends NodeSupport { constructor(config) { super(config); this.appendChild( new Common({ name: 'Common', currentUser: config.currentUser, currentURL: config.currentURL, isAdmin: true, }), ); this.appendChild( new DisputesInformationForm({ name: 'DisputesInformationForm', dispute: config.dispute, element: document.querySelector('[data-component-form="dispute-personal-information"]'), }), ); this.debtAmounts = mountDebtAmounts(config); } } window.ViewAdminDisputesShow = ViewAdminDisputesShow;
tomhosking/torchseq
torchseq/models/samplers/teacher_force.py
<filename>torchseq/models/samplers/teacher_force.py<gh_stars>10-100 import torch import torch.nn as nn from torchseq.utils.tokenizer import Tokenizer class TeacherForcedSampler(nn.Module): def __init__(self, config, device): super(TeacherForcedSampler, self).__init__() self.config = config self.device = device def forward(self, model, batch, tgt_field): curr_batch_size = batch[[k for k in batch.keys() if k[-5:] != "_text"][0]].size()[0] max_output_len = batch[tgt_field].size()[1] BART_HACK = self.config.eval.data.get("prepend_eos", False) MBART_HACK = self.config.eval.data.get("prepend_langcode", False) # Create vector of SOS + placeholder for first prediction logits = ( torch.FloatTensor(curr_batch_size, 1, self.config.prepro.vocab_size).fill_(float("-1e18")).to(self.device) ) if MBART_HACK: logits.scatter_(-1, batch["tgt_lang"].unsqueeze(1).unsqueeze(2), float("1e18")) else: logits[:, :, Tokenizer().bos_id] = float("1e18") # With a transformer decoder, we can lean on the internal mask to ensure that the model can't see ahead # ..and then just do a single pass through the whole model using the gold output as input output = batch[tgt_field][:, : max_output_len - 1].to(self.device) if self.config.training.data.get("token_dropout", 0) > 0 and self.training: rand = torch.rand_like(output, dtype=torch.float) masked = torch.full_like(output, Tokenizer().mask_id) output = torch.where( torch.bitwise_and( rand < self.config.training.data.get("token_dropout", 0), output != Tokenizer().pad_id ), masked, output, ) if BART_HACK: dummy_token = torch.LongTensor(curr_batch_size, 1).fill_(Tokenizer().eos_id).to(self.device) output = torch.cat([dummy_token, output], dim=1) if MBART_HACK: eos_token = torch.LongTensor(curr_batch_size, 1).fill_(Tokenizer().eos_id).to(self.device) # lang_token = batch["tgt_lang"].unsqueeze(-1) output = torch.cat([eos_token, output], dim=1) # print(output[0]) # exit() memory = {} pred_logits, memory = model(batch, output, tgt_field=tgt_field, memory=memory) if BART_HACK or MBART_HACK: output = output[:, 1:] pred_logits = pred_logits[:, 1:, :] # if MBART_HACK: # output = output[:, 2:] # pred_logits = pred_logits[:, 2:, :] logits = torch.cat([logits, pred_logits], dim=1) # print(BART_HACK, MBART_HACK) # print(output) # print(batch['q']) # print(torch.argmax(logits, dim=-1)) # exit() return output, logits, None, memory
Gambit-Play/inventory
src/redux/categories/categories.actions.js
import CategoriesActionTypes from './categories.types'; /* ================================================================ */ /* Process Start */ /* ================================================================ */ export const fetchCategoriesCollectionStart = () => ({ type: CategoriesActionTypes.FETCH_CATEGORIES_COLLECTIONS_START, }); /* ================================================================ */ /* Process Update */ /* ================================================================ */ export const fetchCategoriesCollectionUpdate = () => ({ type: CategoriesActionTypes.FETCH_CATEGORIES_COLLECTIONS_UPDATE, }); /* ================================================================ */ /* Process Success */ /* ================================================================ */ export const fetchCategoriesCollectionSuccess = categories => ({ type: CategoriesActionTypes.FETCH_CATEGORIES_COLLECTIONS_SUCCESS, payload: categories, }); /* ================================================================ */ /* Process Failure */ /* ================================================================ */ export const fetchCategoriesCollectionFailure = errorMessage => ({ type: CategoriesActionTypes.FETCH_CATEGORIES_COLLECTIONS_FAILURE, payload: errorMessage, }); /* ================================================================ */ /* Process Remove */ /* ================================================================ */ export const removeCategoriesCollectionListener = () => ({ type: CategoriesActionTypes.REMOVE_CATEGORIES_COLLECTION_LISTENER, }); export const clearCategoriesStart = () => ({ type: CategoriesActionTypes.CLEAR_CATEGORIES_COLLECTIONS, });
abraha2d/mirador
storage/admin.py
<reponame>abraha2d/mirador<filename>storage/admin.py<gh_stars>0 from django.contrib import admin from .models import ( Event, Picture, Video, ) @admin.register(Event) class EventAdmin(admin.ModelAdmin): pass @admin.register(Picture) class PictureAdmin(admin.ModelAdmin): pass @admin.register(Video) class VideoAdmin(admin.ModelAdmin): list_display = ("camera", "start_date", "end_date", "file") list_filter = ("camera",) ordering = ("-start_date",)
Udbhavbisarya23/MOTION2NX
src/motioncore/compute_server/compute_server.cpp
#include <iostream> #include <boost/asio.hpp> #include "compute_server.h" using namespace boost::asio; using ip::tcp; using std::string; using std::cout; using std::endl; namespace COMPUTE_SERVER { string read_(tcp::socket & socket) { boost::asio::streambuf buf; boost::asio::read_until( socket, buf, "\n" ); string data = boost::asio::buffer_cast<const char*>(buf.data()); return data; } void send_(tcp::socket & socket, const string& message) { const string msg = message + "\n"; boost::asio::write( socket, boost::asio::buffer(msg) ); } std::vector<std::pair<uint64_t,uint64_t>> get_provider_data(int port_number) { int count = 0; std::vector<std::pair<uint64_t,uint64_t> > ret; while(count < 2){ boost::asio::io_service io_service; //listen for new connection tcp::acceptor acceptor_(io_service, tcp::endpoint(tcp::v4(), port_number )); //socket creation tcp::socket socket_(io_service); //waiting for the connection acceptor_.accept(socket_); //read operation boost::system::error_code ec; Shares data; read(socket_ , buffer(&data, sizeof(data)), ec); // string message = read_(socket_); cout << data.Delta << endl; //write operation send_(socket_, "Hello From Server!"); socket_.close(); ret.push_back(std::make_pair(data.Delta,data.delta)); count += 1; cout << count << endl; } return ret; } std::vector<Shares> read_struct(tcp::socket & socket,int num_elements) { cout << "Before reading of data\n"; std::vector<Shares> data; for(int i=0;i<num_elements;i++) { boost::system::error_code ec; uint64_t arr[2]; read(socket , boost::asio::buffer(&arr,sizeof(arr)), ec); Shares temp; temp.Delta = arr[0]; temp.delta = arr[1]; data.push_back(temp); } return data; } std::pair <std::vector<Shares>,int > get_provider_dot_product_data(int port_number) { boost::asio::io_service io_service; //listen for new connection tcp::acceptor acceptor_(io_service, tcp::endpoint(tcp::v4(), port_number )); //socket creation tcp::socket socket_(io_service); //waiting for the connection acceptor_.accept(socket_); //read operation boost::system::error_code ec; int num_elements; read(socket_ , boost::asio::buffer(&num_elements, sizeof(num_elements)), ec); if(ec) { cout << ec << "\n"; } else { cout << "No Error\n"; } // string message = read_(socket_); cout << "The number of elements are :- " << num_elements << endl; //write operation const string msg = "Server has received the number of elements \n"; boost::asio::write( socket_, boost::asio::buffer(msg) ); cout << "Servent sent message to Client!" << endl; //Read the data in the reuired format std::vector<Shares> data = read_struct(socket_, num_elements); socket_.close(); for(int i=0;i<num_elements;i++) { std::cout << data[i].Delta << " " << data[i].delta << " "; std::cout << "\n\n"; } std::cout << "Finished reading input \n\n"; return std::make_pair(data,num_elements); } std::pair<std::size_t ,std::pair<std::vector<Shares>,std::vector<int> > >get_provider_mat_mul_data(int port_number) { boost::asio::io_service io_service; //listen for new connection tcp::acceptor acceptor_(io_service, tcp::endpoint(tcp::v4(), port_number )); //socket creation tcp::socket socket_(io_service); //waiting for the connection acceptor_.accept(socket_); // Read and write the number of fractional bits boost::system::error_code ec; size_t fractional_bits; read(socket_ , boost::asio::buffer(&fractional_bits, sizeof(fractional_bits)), ec); if(ec) { cout << ec << "\n"; } else { cout << "No Error\n"; } const string msg_init = "Server has received the number of fractional bits \n"; boost::asio::write( socket_, boost::asio::buffer(msg_init) ); cout << "Servent sent message to Client!" << endl; //read operation int arr[2]; read(socket_ , boost::asio::buffer(&arr, sizeof(arr)), ec); if(ec) { cout << ec << "\n"; } else { cout << "No Error\n"; } std::vector<int> dims; dims.push_back(arr[0]); dims.push_back(arr[1]); int num_elements = arr[0]*arr[1]; cout << "The number of elements are :- " << num_elements << endl; //write operation const string msg = "Server has received the number of elements \n"; boost::asio::write( socket_, boost::asio::buffer(msg) ); cout << "Servent sent message to Client!" << endl; //Read the data in the reuired format std::vector<Shares> data = read_struct(socket_, num_elements); socket_.close(); std::cout << "Finished reading input \n\n"; return std::make_pair(fractional_bits,std::make_pair(data,dims)); } }
yusufshakeel/pizza-microservice-backend
services/cart/src/repositories/index.js
'use strict'; const CartRepository = require('./cart-repository'); const SchemaRepository = require('./schema-repository'); const { CartModel } = require('../models/cart-model'); const RepositoryError = require('../errors/repository-error'); module.exports = function Repositories({ parser, errorable = RepositoryError() }) { this.cartRepository = new CartRepository({ CartModel, errorable }); this.schemaRepository = new SchemaRepository(parser); };
niulinlnc/rsbi-pom
src/main/java/com/ruisitech/bi/entity/bireport/QueryMonthDto.java
package com.ruisitech.bi.entity.bireport; import java.text.ParseException; import com.ruisitech.bi.entity.common.BaseEntity; public class QueryMonthDto extends BaseEntity { private String startMonth; private String endMonth; public String getStartMonth() { return startMonth; } public void setStartMonth(String startMonth) { this.startMonth = startMonth; } public String getEndMonth() { return endMonth; } public void setEndMonth(String endMonth) { this.endMonth = endMonth; } public int getBetweenMonth() throws ParseException{ int year1 = Integer.parseInt(this.startMonth.substring(0,4)); int year2 = Integer.parseInt(this.endMonth.substring(0,4)); int month1 = Integer.parseInt(this.startMonth.substring(4,6)); int month2 = Integer.parseInt(this.endMonth.substring(4,6)); int betweenMonth = month2 - month1; int betweenYear = year2 - year1; return betweenYear * 12 + betweenMonth; } @Override public void validate() { } }
kuryaki/cs-fpp
lab3/src/prob4/Main.java
<reponame>kuryaki/cs-fpp package prob4; public class Main { public static void main(String[] args) { Circle circle = new Circle(20); System.out.println("Area of circle is " + circle.area()); Rectangle rectangle = new Rectangle(20, 15); System.out.println("Area of rectangle is " + rectangle.area()); Triangle triangle = new Triangle(20, 10); System.out.println("Area of triangle is " + triangle.area()); } }
Addision/EventServer
LoginServer/NodeNet/LoginNodeClient.cpp
<filename>LoginServer/NodeNet/LoginNodeClient.cpp #include "LoginNodeClient.h" #include "JsonConfig.h" #include "SeFNetClient.h" #include "packet/PacketMgr.h" #include "MsgHandle/LoginPlayer.h" #include "LogUtil.h" void LoginNodeClient::InitHelper() { mNetCliModule->AddReceiveCallBack(ServerType::SERVER_TYPE_GATE, GATE_ROUTE_TO_LOGIN, this, &LoginNodeClient::OnGateRouteLogin); mNetCliModule->AddReceiveCallBack(ServerType::SERVER_TYPE_WORLD, WORLD_ROUTE_TO_LOGIN, this, &LoginNodeClient::OnWorldRouteLogin); SetReportInfo(); AddConnectServer(); } void LoginNodeClient::SetReportInfo() { mServerInfo.set_server_id(g_pConfig->m_ServerConf["NodeId"].asInt()); mServerInfo.set_server_name(g_pConfig->m_ServerConf["NodeName"].asString()); mServerInfo.set_server_cur_count(0); mServerInfo.set_server_ip(g_pConfig->m_ServerConf["NodeIp"].asString()); mServerInfo.set_server_port(g_pConfig->m_ServerConf["NodePort"].asInt()); mServerInfo.set_server_max_online(2000); mServerInfo.set_server_state(EServerState::EST_NORMAL); mServerInfo.set_server_type(ServerType::SERVER_TYPE_LOGIN); } void LoginNodeClient::AddConnectServer() { AddConnectMaster(); mConnectType.push_back(ServerType::SERVER_TYPE_WORLD); mConnectType.push_back(ServerType::SERVER_TYPE_GATE); } void LoginNodeClient::OnGateRouteLogin(const socket_t sock_fd, const int msg_id, const char* msg, const size_t msg_len) { GateToLoginPacket gate_packet; if (msg==nullptr || !gate_packet.ParseFromArray(msg, msg_len)) return; ConnectDataPtr pServerData = GetServerNetInfo(sock_fd); if (!pServerData) return; Packet* pRecvPacket = g_pPacketMgr->CreatePakcet(gate_packet.msg_id(), gate_packet.msg_body().c_str(), gate_packet.msg_body().length()); MsgHandle pHandle = g_pPacketMgr->GetMsgHandle(gate_packet.msg_id()); if (pHandle == nullptr || pRecvPacket == nullptr) return; LoginPlayer* loginPlayer = g_pLoginPlayerPool->NewLoginPlayer(); loginPlayer->m_playerid = gate_packet.player_id(); loginPlayer->m_servid = pServerData->serv_id; if (pHandle(loginPlayer, pRecvPacket) != 0) { CLOG_INFO << "OnGateRouteLogin: msg handle error" << CLOG_END; } } void LoginNodeClient::OnWorldRouteLogin(const socket_t sock_fd, const int msg_id, const char* msg, const size_t msg_len) { GateToWorldPacket gate_packet; if (msg == nullptr || !gate_packet.ParseFromArray(msg, msg_len)) return; ConnectDataPtr pServerData = GetServerNetInfo(sock_fd); if (!pServerData) return; Packet* pRecvPacket = g_pPacketMgr->CreatePakcet(gate_packet.msg_id(), gate_packet.msg_body().c_str(), gate_packet.msg_body().length()); MsgHandle pHandle = g_pPacketMgr->GetMsgHandle(gate_packet.msg_id()); if (pHandle == nullptr || pRecvPacket == nullptr) return; LoginPlayer* loginPlayer = g_pLoginPlayerPool->NewLoginPlayer(); loginPlayer->m_playerid = gate_packet.player_id(); loginPlayer->m_servid = pServerData->serv_id; if (pHandle(loginPlayer, pRecvPacket) != 0) { CLOG_INFO << "OnGateRouteWorld: msg handle error" << CLOG_END; } } void LoginNodeClient::SendToGate(const int& serverid, uint64_t playerId, const int msg_id, ::google::protobuf::Message* pb_msg) { LoginToGatePacket login_packet; std::string send_msg = pb_msg->SerializeAsString(); login_packet.set_msg_id(msg_id); login_packet.set_msg_body(send_msg); login_packet.set_player_id(playerId); mNetCliModule->SendPbByServId(serverid, LOGIN_ROUTE_TO_GATE, &login_packet); } void LoginNodeClient::SendToWorld(const int& serverid, uint64_t playerId, const int msg_id, ::google::protobuf::Message* pb_msg) { LoginToWorldPacket login_packet; std::string send_msg = pb_msg->SerializeAsString(); login_packet.set_msg_id(msg_id); login_packet.set_msg_body(send_msg); login_packet.set_player_id(playerId); mNetCliModule->SendPbByServId(serverid, LOGIN_ROUTE_TO_WORLD, &login_packet); }
ffteja/cgal
Straight_skeleton_2/doc/Straight_skeleton_2/Concepts/StraightSkeletonBuilder_2_Visitor.h
<reponame>ffteja/cgal<filename>Straight_skeleton_2/doc/Straight_skeleton_2/Concepts/StraightSkeletonBuilder_2_Visitor.h /*! \ingroup PkgStraightSkeleton2Concepts \cgalConcept The concept `StraightSkeletonBuilder_2_Visitor` describes the requirements of the visitor class required by the algorithm class `CGAL::Straight_skeleton_builder_2` in its third template parameter. \cgalHasModel `CGAL::Dummy_straight_skeleton_builder_2_visitor` \sa `CGAL::Straight_skeleton_builder_2<Traits,Ss,Visitor>` */ class StraightSkeletonBuilder_2_Visitor { public: /// \name Types /// @{ /*! A constant handle to a straight skeleton halfedge. */ typedef unspecified_type Halfedge_const_handle; /*! A constant handle to a straight skeleton vertex. */ typedef unspecified_type Vertex_const_handle; /// @} /// \name Operations /// @{ /*! Called for each contour halfedge added to the skeleton). */ void on_contour_edge_entered( const Halfedge_const_handle& ) const; /*! Called before the initialization stage (when initial events are discovered) is started. */ void on_initialization_started( std::size_t number_of_vertices ) const; /*! Called after the initial events involving the contour vertex `v` have been discovered. */ void on_initial_events_collected ( const Vertex_const_handle& v, bool is_reflex, bool is_degenerate) const; /*! Called after an edge event for nodes `node0` and `node1` has been discovered and put on the queue for later processing. */ void on_edge_event_created( const Vertex_const_handle& node0, const Vertex_const_handle& node1 ) const ; /*! Called after a slipt event for node `node` has been discovered and put on the queue for later processing. */ void on_split_event_created( const Vertex_const_handle& node ) const ; /*! Called after a pseudo slipt event for nodes `node0` and `node1` has been discovered and put on the queue for later processing. */ void on_pseudo_split_event_created( const Vertex_const_handle& node0, const Vertex_const_handle& node1 ) const ; /*! Called after all initial events have been discovered. */ void on_initialization_finished() const; /*! Called before the propagation stage (when events are poped off the queue and processed) is started. */ void on_propagation_started() const; /*! Called after an annihilation event for nodes `node0` and `node1` has been processed. A new skeleton edge between these nodes has been added. */ void on_anihiliation_event_processed ( const Vertex_const_handle& node0, const Vertex_const_handle& node1 ) const; /*! Called after an edge for nodes `seed0` and `seed1` has been processed. Skeleton vertex `newnode` and edges from `node0` to `newnode` and `node1` to `newnode` has been added. */ void on_edge_event_processed( const Vertex_const_handle& seed0, const Vertex_const_handle& seed1, const Vertex_const_handle& newnode ) const; /*! Called after a split event for node `seed` has been processed. Skeleton vertices `newnode0` and `newnode1` have been added. An skeleton edge from `seed` to `newnode0` has been added. In the final skeleton, `newnode1` is removed and only `newnode0` remains. */ void on_split_event_processed( const Vertex_const_handle& seed, const Vertex_const_handle& newnode0, const Vertex_const_handle& newnode1 ) const; /*! Called after a pseudo split event for nodes `seed0` and `seed1` has been processed. Skeleton vertices `newnode0` and `newnode1` have been added. Skeleton edges from `seed0` to `newnode0` and `seed1` to `newnode1` has been added. */ void on_pseudo_split_event_processed( const Vertex_const_handle& seed0, const Vertex_const_handle& seed1, const Vertex_const_handle& newnode0, const Vertex_const_handle& newnode1) const; /*! Called after vertex `v` has been marked as already processed. */ void on_vertex_processed( const Vertex_const_handle& v ) const; /*! Called after all events have been processed. */ void on_propagation_finished() const; /*! Called when the skeleton clean up (when multiple nodes are merged) is started. */ void on_cleanup_started() const; /*! Called when clean up finished. */ void on_cleanup_finished() const; /*! Called when the algorithm terminated. `finished_ok` is false if it terminated before completion or the resulting skeleton was found to be invalid. */ void on_algorithm_finished ( bool finished_ok ) const; /*! Called whenever an error was detected. `msg` is whatever error message accompanies the error. This pointer can be `null`. */ void on_error( char const* msg ) const; /// @} }; /* end StraightSkeletonBuilder_2_Visitor */
pymma/drools47jdk8
drools-jbrms/src/test/java/org/drools/brms/server/contenthandler/DRLFileContentHandlerTest.java
<reponame>pymma/drools47jdk8<filename>drools-jbrms/src/test/java/org/drools/brms/server/contenthandler/DRLFileContentHandlerTest.java package org.drools.brms.server.contenthandler; /* * Copyright 2005 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import junit.framework.TestCase; import org.drools.brms.server.contenthandler.DRLFileContentHandler; public class DRLFileContentHandlerTest extends TestCase { public void testSniffDRLType() throws Exception { DRLFileContentHandler h = new DRLFileContentHandler(); // in this case we have package, and N rules String classic = "package foobar \n rule boo \n when \n then\n end \n rule boo2 \n when \n then\n end"; // in this case we just have rules String moreRuleClassic = "\nrule bar \n when \n then \n end\nrule x \n when \n then \n end "; // in this case we just have a single rule String newRule = "agenda-group 'x' \n when \n then \n"; String moreSingle = "rule foo when then end"; String moreNewRule = "agenda-group 'x' \n when end.bar \n then rule.end.bar"; String emptyRule = ""; assertTrue(h.isStandAloneRule(newRule)); assertFalse(h.isStandAloneRule(moreRuleClassic)); assertFalse(h.isStandAloneRule(classic)); assertFalse(h.isStandAloneRule(moreSingle)); assertFalse(h.isStandAloneRule(null)); assertFalse(h.isStandAloneRule(emptyRule)); assertTrue(h.isStandAloneRule(moreNewRule)); } public void testRuleWithDialect() { String rule = "rule \"DemoRule\" \n "+ " salience 10 \n" + " dialect \"mvel\" \n " + " when \n" + " Driver( age > 65 ) \n" + " then \n" + " insert(new Rejection(\" too old \"));" + "end "; DRLFileContentHandler h = new DRLFileContentHandler(); assertFalse(h.isStandAloneRule( rule )); assertFalse(h.isStandAloneRule( "" )); } }
incodehq/ecpcrm
application/src/main/java/org/incode/eurocommercial/ecpcrm/module/api/service/vm/websiteuserdetail/WebsiteUserDetailResponseViewModel.java
package org.incode.eurocommercial.ecpcrm.module.api.service.vm.websiteuserdetail; import lombok.Getter; import lombok.Setter; import org.incode.eurocommercial.ecpcrm.module.api.service.vm.AbstractBaseViewModel; import org.incode.eurocommercial.ecpcrm.module.loyaltycards.dom.user.User; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class WebsiteUserDetailResponseViewModel extends AbstractBaseViewModel { @Getter @Setter String id; @Getter @Setter String name; @Getter @Setter String email; @Getter @Setter String title; @Getter @Setter String first_name; @Getter @Setter String last_name; @Getter @Setter String birthdate; @Getter @Setter String optin; @Getter @Setter String car; @Getter @Setter List<String> boutiques; @Getter @Setter String address; @Getter @Setter String zipcode; @Getter @Setter String city; @Getter @Setter String full_address; @Getter @Setter String phone; @Getter @Setter String haschildren; @Getter @Setter String nb_children; @Getter @Setter List<ChildViewModel> children; @Getter @Setter List<CardViewModel> cards; @Getter @Setter String open_card_request; @Getter @Setter String request; public WebsiteUserDetailResponseViewModel(User user){ setId(user.getReference()); setEmail(user.getEmail()); setName(user.getEmail()); setTitle(user.getTitle().toString().toLowerCase()); setFirst_name(user.getFirstName()); setLast_name(user.getLastName()); setBirthdate(asString(user.getBirthDate())); setOptin(asString(user.isPromotionalEmails())); setCar(asString(user.getHasCar())); setAddress(user.getAddress()); setZipcode(user.getZipcode()); setCity(user.getCity()); setFull_address(user.getAddress() + " - " + user.getZipcode() + " - " + user.getCity()); setPhone(user.getPhoneNumber()); setChildren(user.getChildren() .stream() .map(child -> {ChildViewModel cvm = new ChildViewModel(child); return cvm;}) .collect(Collectors.toList())); setCards(user.getCards() .stream() .map(card -> {CardViewModel vm = new CardViewModel(card); return vm;}) .collect(Collectors.toList())); setBoutiques(new ArrayList<>()); setOpen_card_request(user.getOpenCardRequest() == null ? "false" : "true"); } }
tickCoder/TICKCategory
TICKCategory/TICKCategory/TICKBlockButton/UIButton+TICKBlock.h
// // UIButton+TICKBlock.h // TICKBlockButton // // Created by iVan on 2015.07.15.Wednesday. // Copyright (c) 2015 tickCoder. All rights reserved. // #import <UIKit/UIKit.h> typedef void(^TICKButtonActionBlock)(void); @interface UIButton (TICKBlock) /*! * @brief add UIControlEvents action block for UIButton * * @param aBlock action block * @param aEvent UIControlEvents */ - (void)tick_addActionBlock:(TICKButtonActionBlock)aBlock forEvent:(UIControlEvents)aEvent; @end
hwx405562/master
test/integration/variable.test.js
<gh_stars>0 var expect = require('expect.js'), Variable = require('../../lib/index.js').Variable; /* global describe, it */ describe('Variable', function () { it('constructor must be exported', function () { expect(Variable).to.be.a('function'); }); it('should create a new instance', function () { var v = new Variable(); expect(v instanceof Variable).to.be.ok(); }); });
cjac/libffi-platypus-perl
xs/record_opaque.c
#include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "ppport.h" #include "ffi_platypus.h" #include "ffi_platypus_guts.h" XS(ffi_pl_record_accessor_opaque) { ffi_pl_record_member *member; SV *self; SV *arg; char *ptr1; void **ptr2; dVAR; dXSARGS; if(items == 0) croak("This is a method, you must provide at least the object"); member = (ffi_pl_record_member*) CvXSUBANY(cv).any_ptr; self = ST(0); if(SvROK(self)) self = SvRV(self); if(!SvOK(self)) croak("Null record error"); ptr1 = (char*) SvPV_nolen(self); ptr2 = (void**) &ptr1[member->offset]; if(items > 1) { arg = ST(1); *ptr2 = SvOK(arg) ? INT2PTR(void*, SvIV(arg)) : NULL; } if(GIMME_V == G_VOID) XSRETURN_EMPTY; if(*ptr2 != NULL) XSRETURN_IV( PTR2IV( *ptr2 )); else XSRETURN_EMPTY; } XS(ffi_pl_record_accessor_opaque_array) { ffi_pl_record_member *member; SV *self; SV *arg; SV **item; AV *av; char *ptr1; void **ptr2; int i; dVAR; dXSARGS; if(items == 0) croak("This is a method, you must provide at least the object"); member = (ffi_pl_record_member*) CvXSUBANY(cv).any_ptr; self = ST(0); if(SvROK(self)) self = SvRV(self); if(!SvOK(self)) croak("Null record error"); ptr1 = (char*) SvPV_nolen(self); ptr2 = (void**) &ptr1[member->offset]; if(items > 2) { i = SvIV(ST(1)); if(i >= 0 && i < member->count) { arg = ST(2); ptr2[i] = SvOK(arg) ? INT2PTR(void*, SvIV(arg)) : NULL; } else { warn("illegal index %d", i); } } else if(items > 1) { arg = ST(1); if(SvROK(arg) && SvTYPE(SvRV(arg)) == SVt_PVAV) { av = (AV*) SvRV(arg); for(i=0; i < member->count; i++) { item = av_fetch(av, i, 0); if(item != NULL && SvOK(*item)) { ptr2[i] = INT2PTR(void*, SvIV(*item)); } else { ptr2[i] = NULL; } } } else { i = SvIV(ST(1)); if(i < 0 && i >= member->count) { warn("illegal index %d", i); XSRETURN_EMPTY; } else if(ptr2[i] == NULL) { XSRETURN_EMPTY; } else { XSRETURN_IV(PTR2IV(ptr2[i])); } warn("passing non array reference into ffi/platypus array argument type"); } } if(GIMME_V == G_VOID) XSRETURN_EMPTY; av = newAV(); av_fill(av, member->count-1); for(i=0; i < member->count; i++) { if(ptr2[i] != NULL) sv_setiv(*av_fetch(av, i, 1), PTR2IV(ptr2[i])); } ST(0) = newRV_inc((SV*)av); XSRETURN(1); }
socialsensor/topic-detection
src/main/java/eu/socialsensor/documentpivot/utils/LSHListener.java
<reponame>socialsensor/topic-detection package eu.socialsensor.documentpivot.utils; import eu.socialsensor.documentpivot.LSH.HashTables; import eu.socialsensor.documentpivot.model.VectorSpace; import eu.socialsensor.documentpivot.model.Vocabulary; import twitter4j.Status; import twitter4j.StatusDeletionNotice; import twitter4j.StatusListener; import twitter4j.StallWarning; public class LSHListener implements StatusListener { int c = 0; private Vocabulary vocabulary; private HashTables hashTables; public LSHListener(Vocabulary vocabulary, HashTables hashTable) { this.vocabulary = vocabulary; this.hashTables = hashTables; } @Override public void onStatus(Status status) { c++; VectorSpace vsm = new VectorSpace(Long.toString(status.getId()), status.getText()); vocabulary.update(vsm.tokens()); hashTables.add(vsm); if(c>10000) { VectorSpace[] nn = hashTables.get(vsm); System.out.println(nn.length); } } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {} @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) {} @Override public void onScrubGeo(long arg0, long arg1) { } @Override public void onException(Exception ex) { ex.printStackTrace(); } @Override public void onStallWarning(StallWarning sw) { throw new UnsupportedOperationException("Not supported yet."); } }
unratito/ceylon.language
runtime-js/jsint/AppliedUnionType/string.js
<reponame>unratito/ceylon.language var qn=""; var first=true; for (var i=0;i<this.caseTypes.size;i++) { if (first)first=false;else qn+="|"; qn+=this.caseTypes.$_get(i).string; } return qn;
vonatzigenc/quarkus
extensions/amazon-services/common/runtime/src/main/java/io/quarkus/amazon/common/runtime/AbstractAmazonClientTransportRecorder.java
<reponame>vonatzigenc/quarkus package io.quarkus.amazon.common.runtime; import java.net.URI; import java.util.Optional; import io.quarkus.runtime.RuntimeValue; import software.amazon.awssdk.http.SdkHttpClient; import software.amazon.awssdk.http.TlsKeyManagersProvider; import software.amazon.awssdk.http.TlsTrustManagersProvider; import software.amazon.awssdk.http.async.SdkAsyncHttpClient; import software.amazon.awssdk.utils.StringUtils; public abstract class AbstractAmazonClientTransportRecorder { @SuppressWarnings("rawtypes") public RuntimeValue<SdkHttpClient.Builder> configureSync(String clientName, RuntimeValue<SyncHttpClientConfig> syncConfigRuntime) { throw new IllegalStateException("Configuring a sync client is not supported by " + this.getClass().getName()); } @SuppressWarnings("rawtypes") public RuntimeValue<SdkAsyncHttpClient.Builder> configureAsync(String clientName, RuntimeValue<NettyHttpClientConfig> asyncConfigRuntime) { throw new IllegalStateException("Configuring an async client is not supported by " + this.getClass().getName()); } protected Optional<TlsKeyManagersProvider> getTlsKeyManagersProvider(TlsKeyManagersProviderConfig config) { if (config.fileStore != null && config.fileStore.path.isPresent() && config.fileStore.type.isPresent()) { return Optional.of(config.type.create(config)); } return Optional.empty(); } protected Optional<TlsTrustManagersProvider> getTlsTrustManagersProvider(TlsTrustManagersProviderConfig config) { if (config.fileStore != null && config.fileStore.path.isPresent() && config.fileStore.type.isPresent()) { return Optional.of(config.type.create(config)); } return Optional.empty(); } protected void validateProxyEndpoint(String extension, URI endpoint, String clientType) { if (StringUtils.isBlank(endpoint.getScheme())) { throw new RuntimeConfigurationError( String.format("quarkus.%s.%s-client.proxy.endpoint (%s) - scheme must be specified", extension, clientType, endpoint.toString())); } if (StringUtils.isBlank(endpoint.getHost())) { throw new RuntimeConfigurationError( String.format("quarkus.%s.%s-client.proxy.endpoint (%s) - host must be specified", extension, clientType, endpoint.toString())); } if (StringUtils.isNotBlank(endpoint.getUserInfo())) { throw new RuntimeConfigurationError( String.format("quarkus.%s.%s-client.proxy.endpoint (%s) - user info is not supported.", extension, clientType, endpoint.toString())); } if (StringUtils.isNotBlank(endpoint.getPath())) { throw new RuntimeConfigurationError( String.format("quarkus.%s.%s-client.proxy.endpoint (%s) - path is not supported.", extension, clientType, endpoint.toString())); } if (StringUtils.isNotBlank(endpoint.getQuery())) { throw new RuntimeConfigurationError( String.format("quarkus.%s.%s-client.proxy.endpoint (%s) - query is not supported.", extension, clientType, endpoint.toString())); } if (StringUtils.isNotBlank(endpoint.getFragment())) { throw new RuntimeConfigurationError( String.format("quarkus.%s.%s-client.proxy.endpoint (%s) - fragment is not supported.", extension, clientType, endpoint.toString())); } } protected void validateTlsKeyManagersProvider(String extension, TlsKeyManagersProviderConfig config, String clientType) { if (config != null && config.type == TlsKeyManagersProviderType.FILE_STORE) { validateFileStore(extension, clientType, "key", config.fileStore); } } protected void validateTlsTrustManagersProvider(String extension, TlsTrustManagersProviderConfig config, String clientType) { if (config != null && config.type == TlsTrustManagersProviderType.FILE_STORE) { validateFileStore(extension, clientType, "trust", config.fileStore); } } protected void validateFileStore(String extension, String clientType, String storeType, FileStoreTlsManagersProviderConfig fileStore) { if (fileStore == null) { throw new RuntimeConfigurationError( String.format( "quarkus.%s.%s-client.tls-%s-managers-provider.file-store must be specified if 'FILE_STORE' provider type is used", extension, clientType, storeType)); } else { if (!fileStore.password.isPresent()) { throw new RuntimeConfigurationError( String.format( "quarkus.%s.%s-client.tls-%s-managers-provider.file-store.path should not be empty if 'FILE_STORE' provider is used.", extension, clientType, storeType)); } if (!fileStore.type.isPresent()) { throw new RuntimeConfigurationError( String.format( "quarkus.%s.%s-client.tls-%s-managers-provider.file-store.type should not be empty if 'FILE_STORE' provider is used.", extension, clientType, storeType)); } if (!fileStore.password.isPresent()) { throw new RuntimeConfigurationError( String.format( "quarkus.%s.%s-client.tls-%s-managers-provider.file-store.password should not be empty if 'FILE_STORE' provider is used.", extension, clientType, storeType)); } } } }
black-vision-engine/bv-engine
BlackVision/LibBlackVision/Source/Engine/Graphics/Effects/Logic/OutputRendering/Impl/FrameDataHandlers/Preview/PreviewHandler.cpp
#include "stdafx.h" #include "PreviewHandler.h" #include "Engine/Graphics/Effects/Logic/Components/RenderChannel.h" #include "Engine/Graphics/Effects/Logic/Components/RenderContext.h" #include "Engine/Graphics/Effects/Logic/FullscreenRendering/FullscreenEffectFactory.h" namespace bv { // ************************** // PreviewHandler::PreviewHandler () : m_mixChannelsEffect( nullptr ) , m_activeRenderOutput( 1 ) { m_mixChannelsEffect = CreateFullscreenEffect( FullscreenEffectType::NFET_MIX_CHANNELS ); } // ************************** // PreviewHandler::~PreviewHandler () { delete m_mixChannelsEffect; } // ************************** // void PreviewHandler::HandleFrameData ( const OutputState &, RenderContext * ctx, const RenderChannel * channel ) { m_activeRenderOutput.SetEntry( 0, channel->GetActiveRenderTarget() ); // FIXME: nrl - DefaultShow is only a very siple way of showing rendered result on preview - ask Pawelek about other possibilities m_mixChannelsEffect->Render( ctx, m_activeRenderOutput ); // Make sure that local preview is displayed properly renderer( ctx )->DisplayColorBuffer(); } // ************************** // FullscreenEffectComponentStatePtr PreviewHandler::GetInternalFSEState () { return m_mixChannelsEffect->GetState(); } } //bv
padogrid/padogrid
geode-addon-core/src/main/java/org/apache/geode/addon/cluster/DbUtil.java
<filename>geode-addon-core/src/main/java/org/apache/geode/addon/cluster/DbUtil.java package org.apache.geode.addon.cluster; import java.util.Set; import org.apache.geode.cache.Cache; import org.apache.geode.cache.CacheFactory; import org.apache.geode.cache.CacheLoader; import org.apache.geode.cache.Region; import org.apache.geode.cache.RegionAttributes; public class DbUtil { /** * Recursively loads database tables to all the regions that are registered with * {@linkplain CacheWriterLoaderPkDbImpl}. If the cache is not available or * closed then it silently returns without taking any actions. */ public final static void loadAll() { Cache cache; try { cache = CacheFactory.getAnyInstance(); if (cache.isClosed()) { return; } } catch (Exception ex) { // ignore return; } Set<Region<?, ?>> set = cache.rootRegions(); for (Region<?, ?> region : set) { loadAll(region); } } /** * Recursively loads database tables to the specified region and its sub-regions * that are registered with {@linkplain CacheWriterLoaderPkDbImpl}. * * @param region parent region */ @SuppressWarnings({ "rawtypes", "unchecked" }) public final static void loadAll(Region region) { RegionAttributes attr = region.getAttributes(); if (attr != null) { CacheLoader loader = attr.getCacheLoader(); if (loader != null && loader instanceof CacheWriterLoaderPkDbImpl) { CacheWriterLoaderPkDbImpl pkDbLoader = (CacheWriterLoaderPkDbImpl) loader; pkDbLoader.loadAllFromDb(); } } Set<Region> subRegionSet = region.subregions(false); for (Region<?, ?> subRegion : subRegionSet) { loadAll(subRegion); } } }
TheSledgeHammer/2.11BSD
contrib/pcc/dist/pcc/arch/hppa/macdefs.h
<gh_stars>1-10 /* Id: macdefs.h,v 1.21 2015/11/24 17:35:11 ragge Exp */ /* $NetBSD: macdefs.h,v 1.1.1.6 2016/02/09 20:28:15 plunky Exp $ */ /* * Copyright (c) 2007 <NAME> * Copyright (c) 2003 <NAME> (<EMAIL>). * 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */ /* * Convert (multi-)character constant to integer. */ #define makecc(val,i) (lastcon = (lastcon<<8)|((val<<24)>>24)) #define ARGINIT (32*8) /* bits below fp where args start */ #define AUTOINIT (4*8) /* bits above fp where locals start */ /* * storage sizes */ #define SZCHAR 8 #define SZBOOL 8 #define SZINT 32 #define SZFLOAT 32 #define SZDOUBLE 64 #define SZLDOUBLE 64 /* or later 128 */ #define SZLONG 32 #define SZSHORT 16 #define SZLONGLONG 64 #define SZPOINT(t) 32 /* * alignment requirements */ #define ALCHAR 8 #define ALBOOL 8 #define ALINT 32 #define ALFLOAT 32 #define ALDOUBLE 64 #define ALLDOUBLE 64 /* 128 later */ #define ALLONG 32 #define ALLONGLONG 32 #define ALSHORT 16 #define ALPOINT 32 #define ALSTRUCT 32 #define ALSTACK 64 /* * type value limits */ #define MIN_CHAR -128 #define MAX_CHAR 127 #define MAX_UCHAR 255 #define MIN_SHORT -32768 #define MAX_SHORT 32767 #define MAX_USHORT 65535 #define MIN_INT (-0x7fffffff-1) #define MAX_INT 0x7fffffff #define MAX_UNSIGNED 0xffffffff #define MIN_LONG MIN_INT #define MAX_LONG MAX_INT #define MAX_ULONG MAX_UNSIGNED #define MIN_LONGLONG (-0x7fffffffffffffffLL-1) #define MAX_LONGLONG 0x7fffffffffffffffLL #define MAX_ULONGLONG 0xffffffffffffffffULL #undef CHAR_UNSIGNED #define BOOL_TYPE CHAR typedef long long CONSZ; typedef unsigned long long U_CONSZ; typedef long long OFFSZ; #define CONFMT "%lld" /* format for printing constants */ #define LABFMT ".L%d" /* format for printing labels */ #define STABLBL ".LL%d" /* format for stab (debugging) labels */ #undef BACKAUTO /* stack grows upwards */ #undef BACKTEMP /* stack grows upwards */ #define FIELDOPS /* have bit field ops */ #define TARGET_ENDIAN TARGET_BE #define TARGET_FLT_EVAL_METHOD 0 /* all as their type */ #define BYTEOFF(x) ((x)&03) #define wdal(k) (BYTEOFF(k)==0) #define STOARG(p) #define STOFARG(p) #define STOSTARG(p) #define szty(t) (((t) == DOUBLE || (t) == LONGLONG || (t) == ULONGLONG) ? 2 : \ (t) == LDOUBLE ? 2 : 1) #define R0 0 #define R1 1 #define RP 2 #define FP 3 #define R4 4 #define R5 5 #define R6 6 #define R7 7 #define R8 8 #define R9 9 #define R10 10 #define R11 11 #define R12 12 #define R13 13 #define R14 14 #define R15 15 #define R16 16 #define R17 17 #define R18 18 #define T4 19 #define T3 20 #define T2 21 #define T1 22 #define ARG3 23 #define ARG2 24 #define ARG1 25 #define ARG0 26 #define DP 27 #define RET0 28 #define RET1 29 #define SP 30 #define R31 31 /* double regs overlay */ #define RD0 32 /* r0:r0 */ #define RD1 33 /* r1:r31 */ #define RD2 34 /* r1:t4 */ #define RD3 35 /* r1:t3 */ #define RD4 36 /* r1:t2 */ #define RD5 37 /* r1:t1 */ #define RD6 38 /* r31:t4 */ #define RD7 39 /* r31:t3 */ #define RD8 40 /* r31:t2 */ #define RD9 41 /* r31:t1 */ #define RD10 42 /* r4:r18 */ #define RD11 43 /* r5:r4 */ #define RD12 44 /* r6:r5 */ #define RD13 45 /* r7:r6 */ #define RD14 46 /* r8:r7 */ #define RD15 47 /* r9:r8 */ #define RD16 48 /* r10:r9 */ #define RD17 49 /* r11:r10 */ #define RD18 50 /* r12:r11 */ #define RD19 51 /* r13:r12 */ #define RD20 52 /* r14:r13 */ #define RD21 53 /* r15:r14 */ #define RD22 54 /* r16:r15 */ #define RD23 55 /* r17:r16 */ #define RD24 56 /* r18:r17 */ #define TD4 57 /* t1:t4 */ #define TD3 58 /* t4:t3 */ #define TD2 59 /* t3:t2 */ #define TD1 60 /* t2:t1 */ #define AD2 61 /* arg3:arg2 */ #define AD1 62 /* arg1:arg0 */ #define RETD0 63 /* ret1:ret0 */ /* FPU regs */ #define FR0 64 #define FR4 65 #define FR5 66 #define FR6 67 #define FR7 68 #define FR8 69 #define FR9 70 #define FR10 71 #define FR11 72 #define FR12 73 #define FR13 74 #define FR14 75 #define FR15 76 #define FR16 77 #define FR17 78 #define FR18 79 #define FR19 80 #define FR20 81 #define FR21 82 #define FR22 83 #define FR23 84 #define FR24 85 #define FR25 86 #define FR26 87 #define FR27 88 #define FR28 89 #define FR29 90 #define FR30 91 #define FR31 92 #define FR0L 93 #define FR0R 94 #define FR4L 95 #define FR4R 96 #define FR5L 97 #define FR5R 98 #define FR6L 99 #define FR6R 100 #define FR7L 101 #define FR7R 102 #define FR8L 103 #define FR8R 104 #define FR9L 105 #define FR9R 106 #define FR10L 107 #define FR10R 108 #define FR11L 109 #define FR11R 110 #define FR12L 111 #define FR12R 112 #define FR13L 113 #define FR13R 114 #define FR14L 115 #define FR14R 116 #define FR15L 117 #define FR15R 118 #define FR16L 119 #define FR16R 120 #define FR17L 121 #define FR17R 122 #define FR18L 123 #define FR18R 124 #ifdef __hppa64__ #define FR19L 125 #define FR19R 126 #define FR20L 127 #define FR20R 128 #define FR21L 129 #define FR21R 130 #define FR22L 131 #define FR22R 132 #define FR23L 133 #define FR23R 134 #define FR24L 135 #define FR24R 136 #define FR25L 137 #define FR25R 138 #define FR26L 139 #define FR26R 140 #define FR27L 141 #define FR27R 142 #define FR28L 143 #define FR28R 144 #define FR29L 145 #define FR29R 146 #define FR30L 147 #define FR30R 148 #define FR31L 149 #define FR31R 150 #define MAXREGS 151 #else #define MAXREGS 125 #endif #define RSTATUS \ 0, SAREG|TEMPREG, 0, 0, SAREG|PERMREG, SAREG|PERMREG, \ SAREG|PERMREG, SAREG|PERMREG, SAREG|PERMREG, SAREG|PERMREG, \ SAREG|PERMREG, SAREG|PERMREG, SAREG|PERMREG, SAREG|PERMREG, \ SAREG|PERMREG, SAREG|PERMREG, SAREG|PERMREG, SAREG|PERMREG, \ SAREG|PERMREG, \ SAREG|TEMPREG, SAREG|TEMPREG, SAREG|TEMPREG, SAREG|TEMPREG, \ SAREG|TEMPREG, SAREG|TEMPREG, SAREG|TEMPREG, SAREG|TEMPREG, \ 0, SAREG|TEMPREG, SAREG|TEMPREG, 0, SAREG|TEMPREG, \ /* double overlays */ \ 0, \ SBREG, SBREG, SBREG, SBREG, SBREG, SBREG, SBREG, SBREG, \ SBREG, SBREG, SBREG, SBREG, SBREG, SBREG, SBREG, SBREG, \ SBREG, SBREG, SBREG, SBREG, SBREG, SBREG, SBREG, SBREG, \ SBREG, SBREG, SBREG, SBREG, SBREG, SBREG, SBREG, \ /* double-precision floats */ \ 0, \ SDREG|TEMPREG, SDREG|TEMPREG, SDREG|TEMPREG, SDREG|TEMPREG, \ SDREG|TEMPREG, SDREG|TEMPREG, SDREG|TEMPREG, SDREG|TEMPREG, \ SDREG|PERMREG, SDREG|PERMREG, SDREG|PERMREG, SDREG|PERMREG, \ SDREG|PERMREG, SDREG|PERMREG, SDREG|PERMREG, SDREG|PERMREG, \ SDREG|PERMREG, SDREG|PERMREG, \ SDREG|TEMPREG, SDREG|TEMPREG, SDREG|TEMPREG, SDREG|TEMPREG, \ SDREG|TEMPREG, SDREG|TEMPREG, SDREG|TEMPREG, SDREG|TEMPREG, \ SDREG|TEMPREG, SDREG|TEMPREG, \ /* single-precision floats */ \ 0, 0, \ SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, \ SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, \ SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, \ SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, #ifdef __hppa64__ SCREG, SCREG, \ SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, \ SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, \ SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, SCREG, #endif #define ROVERLAP \ { -1 }, \ { RD1, RD2, RD3, RD4, RD5, -1 },\ { -1 }, { -1 }, \ { RD10, RD11, -1 }, \ { RD11, RD12, -1 }, \ { RD12, RD13, -1 }, \ { RD13, RD14, -1 }, \ { RD14, RD15, -1 }, \ { RD15, RD16, -1 }, \ { RD16, RD17, -1 }, \ { RD17, RD18, -1 }, \ { RD18, RD19, -1 }, \ { RD19, RD20, -1 }, \ { RD20, RD21, -1 }, \ { RD21, RD22, -1 }, \ { RD22, RD23, -1 }, \ { RD23, RD24, -1 }, \ { RD24, RD10, -1 }, \ { TD1, TD4, -1 }, \ { TD3, TD2, -1 }, \ { TD1, TD2, -1 }, \ { TD1, TD4, -1 }, \ { AD2, -1 }, { AD2, -1 }, \ { AD1, -1 }, { AD1, -1 }, \ { -1 }, \ { RETD0, -1 }, { RETD0, -1 }, \ { -1 }, \ { RD1, RD5, RD6, RD7, RD8, -1 },\ { -1 }, \ { R1, R31, -1 }, \ { R1, T4, -1 }, \ { R1, T3, -1 }, \ { R1, T2, -1 }, \ { R1, T1, -1 }, \ { R31, T4, -1 }, \ { R31, T3, -1 }, \ { R31, T2, -1 }, \ { R31, T1, -1 }, \ { R4, R18, -1 }, \ { R5, R4, -1 }, \ { R6, R5, -1 }, \ { R7, R6, -1 }, \ { R8, R7, -1 }, \ { R9, R8, -1 }, \ { R10, R9, -1 }, \ { R11, R10, -1 }, \ { R12, R11, -1 }, \ { R13, R12, -1 }, \ { R14, R15, -1 }, \ { R15, R14, -1 }, \ { R16, R15, -1 }, \ { R17, R16, -1 }, \ { R18, R17, -1 }, \ { T1, T4, -1 }, \ { T4, T3, -1 }, \ { T3, T2, -1 }, \ { T2, T1, -1 }, \ { ARG3, ARG2, -1 }, \ { ARG1, ARG0, -1 }, \ { RET1, RET0, -1 }, \ { -1 }, \ { FR4L, FR4R, -1 }, \ { FR5L, FR5R, -1 }, \ { FR6L, FR6R, -1 }, \ { FR7L, FR7R, -1 }, \ { FR8L, FR8R, -1 }, \ { FR9L, FR9R, -1 }, \ { FR10L, FR10R, -1 }, \ { FR11L, FR11R, -1 }, \ { FR12L, FR12R, -1 }, \ { FR13L, FR13R, -1 }, \ { FR14L, FR14R, -1 }, \ { FR15L, FR15R, -1 }, \ { FR16L, FR16R, -1 }, \ { FR17L, FR17R, -1 }, \ { FR18L, FR18R, -1 }, \ { -1 }, \ { -1 }, \ { -1 }, \ { -1 }, \ { -1 }, \ { -1 }, \ { -1 }, \ { -1 }, \ { -1 }, \ { -1 }, \ { -1 }, \ { -1 }, \ { -1 }, \ { -1 }, { -1 }, \ { FR4, -1 }, { FR4, -1 }, \ { FR5, -1 }, { FR5, -1 }, \ { FR6, -1 }, { FR6, -1 }, \ { FR7, -1 }, { FR7, -1 }, \ { FR8, -1 }, { FR8, -1 }, \ { FR9, -1 }, { FR9, -1 }, \ { FR10, -1 }, { FR10, -1 }, \ { FR11, -1 }, { FR11, -1 }, \ { FR12, -1 }, { FR12, -1 }, \ { FR13, -1 }, { FR13, -1 }, \ { FR14, -1 }, { FR14, -1 }, \ { FR15, -1 }, { FR15, -1 }, \ { FR16, -1 }, { FR16, -1 }, \ { FR17, -1 }, { FR17, -1 }, \ { FR18, -1 }, { FR18, -1 }, #ifdef __hppa64__ { FR19, -1 }, { FR19, -1 }, \ { FR20, -1 }, { FR20, -1 }, \ { FR21, -1 }, { FR21, -1 }, \ { FR22, -1 }, { FR22, -1 }, \ { FR23, -1 }, { FR23, -1 }, \ { FR24, -1 }, { FR24, -1 }, \ { FR25, -1 }, { FR25, -1 }, \ { FR26, -1 }, { FR26, -1 }, \ { FR27, -1 }, { FR27, -1 }, \ { FR28, -1 }, { FR28, -1 }, \ { FR29, -1 }, { FR29, -1 }, \ { FR30, -1 }, { FR30, -1 }, \ { FR31, -1 }, { FR31, -1 }, #endif #define PCLASS(p) \ (p->n_type == LONGLONG || p->n_type == ULONGLONG ? SBREG : \ (p->n_type == FLOAT ? SCREG : \ (p->n_type == DOUBLE || p->n_type == LDOUBLE ? SDREG : SAREG))) #define NUMCLASS 4 /* highest number of reg classes used */ int COLORMAP(int c, int *r); #define PERMTYPE(x) ((x) < 32? INT : ((x) < 64? LONGLONG : ((x) < 93? LDOUBLE : FLOAT))) #define GCLASS(x) ((x) < 32? CLASSA : ((x) < 64? CLASSB : ((x) < 93? CLASSD : CLASSC))) #define DECRA(x,y) (((x) >> (y*8)) & 255) /* decode encoded regs */ #define ENCRD(x) (x) /* Encode dest reg in n_reg */ #define ENCRA1(x) ((x) << 8) /* A1 */ #define ENCRA2(x) ((x) << 16) /* A2 */ #define ENCRA(x,y) ((x) << (8+y*8)) /* encode regs in int */ #define RETREG(x) (x == LONGLONG || x == ULONGLONG ? RETD0 : \ x == FLOAT? FR4L : \ x == DOUBLE || x == LDOUBLE ? FR4 : RET0) #define FPREG FP /* frame pointer */ #define STKREG SP /* stack pointer */ #define MYREADER(p) myreader(p) #define MYCANON(p) mycanon(p) #define MYOPTIM #define SFUNCALL (MAXSPECIAL+1) /* struct assign after function call */ #define SPCNHI (MAXSPECIAL+2) /* high 21bits constant */ #define SPCON (MAXSPECIAL+3) /* smaller constant */ #define SPICON (MAXSPECIAL+4) /* even smaller constant */ #define SPCNHW (MAXSPECIAL+5) /* LL const w/ 0 in low word */ #define SPCNLW (MAXSPECIAL+6) /* LL const w/ 0 in high word */ #define SPIMM (MAXSPECIAL+7) /* immidiate const for depi/comib */ #define SPNAME (MAXSPECIAL+8) /* ext symbol reference load/store */ #define NATIVE_FLOATING_POINT
TeamLifecycle/redundant-messaging
lib/models/providers/push/zeropush.js
<filename>lib/models/providers/push/zeropush.js var debug = require('debug')('venn'); MessagingServiceProvider = require("../../messaging_service_provider"); MessagingServiceStatus = require('../../messaging_service_status'); MessagingUserStatus = require('../../messaging_user_status'); var zeroPush = require("nzero-push") /*============================================================================= Define ZeroPush Service Provider =============================================================================*/ function ZeroPush(keys){ if (!keys) return this.name = "zeropush" this.keys = keys this.initialize = function() { this.client = new zeroPush(this.keys.server_token); } this.send = function(data, callback) { var context = this; context.client.register([data.deviceToken], [], function(err, response) { if (err) console.error(err); context.client.notify("ios_macos", [data.deviceToken], {alert: data.message}, function (err, result) { if (err) { zeropushStat = new ZeroPushServiceStatus(err, false); debug("-_-_ FAILED with zeropush _-_-"); debug(zeropushStat); return callback(zeropushStat); } else { zeropushStat = new ZeroPushServiceStatus(result, true); debug("-_-_ sent with zeropush _-_-"); result.service = context; result.status = zeropushStat; debug(result); return callback(null, result); } }); }); } debug("zeropush initing") this.initialize() } ZeroPush.prototype = new MessagingServiceProvider() /*============================================================================= Define ZeroPush Service Status Handler =============================================================================*/ function ZeroPushServiceStatus(response, success) { MessagingServiceStatus.call(this, 'zeropush'); // Put logic here for handling any possible service errors } ZeroPushServiceStatus.prototype = Object.create(MessagingServiceStatus.prototype); ZeroPushServiceStatus.prototype.constructor = ZeroPushServiceStatus; /*============================================================================= Define ZeroPush User Status Handler =============================================================================*/ function ZeroPushUserStatus(message, code) { MessagingUserStatus.call(this, 'zeropush'); // Put logic here for handling any possible user errors } ZeroPushUserStatus.prototype = Object.create(MessagingUserStatus.prototype); ZeroPushUserStatus.prototype.constructor = ZeroPushUserStatus; /*============================================================================= Define ZeroPush Helper Functions =============================================================================*/ module.exports = ZeroPush
prasanna2001t/geo
src/reducers/layout.js
<gh_stars>10-100 import { LAYOUT_DEFAULT, LAYOUT_HIDE_MENU } from 'constants/actions'; const layout = (state = 'default', action) => { switch (action.type) { case LAYOUT_DEFAULT: return 'default'; case LAYOUT_HIDE_MENU: return 'hide-menu'; default: return state; } } export default layout;
herrgrossmann/jo-widgets
modules/examples/org.jowidgets.examples.common/src/main/java/org/jowidgets/examples/common/demo/DemoProgressBar.java
/* * Copyright (c) 2010, grossmann * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the jo-widgets.org nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL jo-widgets.org BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.jowidgets.examples.common.demo; import java.util.concurrent.atomic.AtomicBoolean; import org.jowidgets.api.image.IconsSmall; import org.jowidgets.api.threads.IUiThreadAccess; import org.jowidgets.api.toolkit.Toolkit; import org.jowidgets.api.widgets.IButton; import org.jowidgets.api.widgets.IContainer; import org.jowidgets.api.widgets.IProgressBar; import org.jowidgets.api.widgets.IWindow; import org.jowidgets.api.widgets.blueprint.IProgressBarBluePrint; import org.jowidgets.api.widgets.blueprint.factory.IBluePrintFactory; import org.jowidgets.common.widgets.controller.IActionListener; import org.jowidgets.common.widgets.layout.MigLayoutDescriptor; import org.jowidgets.tools.controller.WindowAdapter; public class DemoProgressBar { public DemoProgressBar(final IContainer parentContainer, final IWindow parentWindow) { final AtomicBoolean windowActive = new AtomicBoolean(); final AtomicBoolean progressBarFinished = new AtomicBoolean(); final IProgressBar progressBar; final int max = (int) (Math.random() * 200) + 100; final boolean indetermined = Math.random() > 0.7; final IBluePrintFactory bpF = Toolkit.getBluePrintFactory(); parentContainer.setLayout(new MigLayoutDescriptor("0[grow][]0", "0[]0")); final IProgressBarBluePrint progressBarPb = bpF.progressBar().setIndeterminate(indetermined).setMaximum(max); progressBar = parentContainer.add(progressBarPb, "growx,w 300::, h 22:22:22"); final IButton buttonWidget = parentContainer.add(bpF.button().setIcon(IconsSmall.ERROR), " h 25:25:25, w 25:25:25, wrap"); buttonWidget.addActionListener(new IActionListener() { @Override public void actionPerformed() { progressBarFinished.set(true); progressBar.setProgress(0); } }); if (!indetermined) { parentWindow.addWindowListener(new WindowAdapter() { @Override public void windowActivated() { if (windowActive.getAndSet(true) || progressBarFinished.get()) { return; } progressBarFinished.set(false); final IUiThreadAccess uiThreadAccess = Toolkit.getUiThreadAccess(); new Thread(new Runnable() { private int i = 0; @Override public void run() { for (i = 0; i <= max && windowActive.get() && !progressBarFinished.get(); i++) { uiThreadAccess.invokeLater(new Runnable() { @Override public void run() { if (windowActive.get() && !progressBarFinished.get()) { progressBar.setProgress(i); } } }); try { Thread.sleep(200); } catch (final InterruptedException e) { throw new RuntimeException(e); } } } }).start(); } @Override public void windowClosed() { windowActive.set(false); } }); } } }
rifraf/IronRuby_Framework_4.7.2
Languages/Ruby/Tests/mspec/rubyspec/library/set/plus_spec.rb
<reponame>rifraf/IronRuby_Framework_4.7.2 require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/shared/union' require 'set' describe "Set#+" do it_behaves_like :set_union, :+ end
TranslatorIIPrototypes/robo-commons
greent/conftest.py
import pytest import json import os from greent.rosetta import Rosetta @pytest.fixture def rosetta (conf): """ Rosetta fixture """ config = conf.get ("config", "greent.conf") print (f"CONFIG: *** > {config}") return Rosetta(debug=True, greentConf=config) @pytest.fixture def conf(): conf = {} if os.path.exists ("pytest.conf"): with open ('pytest.conf', 'r') as stream: conf = json.loads (stream.read ()) return conf
dev-go/hello-world
c/64 c11 cond/main.c
<gh_stars>0 // Copyright (c) 2020, devgo.club // All rights reserved. #include <errno.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <threads.h> #include <time.h> /* (1) cnd_t 条件变量标识符 (2) int cnd_init(cnd_t* cond) 初始化新的条件变量。设置 cond 所指的对象为标识该条件变量的值。 参数: cond: 指针,指向要存储条件变量标识符到的对象 返回值: 若成功创建条件变量则为 thrd_success 。否则若内存量不足则返回 thrd_nomem ,若出现其他错误则返回 thrd_error 。 (3) int cnd_signal(cnd_t *cond) 除阻当前在 cond 所指向的条件变量上等待的一个线程。若无线程被阻塞,则不做任何事并返回 thrd_success 。 参数: cond: 指向条件变量的指针 返回值: 若成功则为 thrd_success ,否则为 thrd_error 。 (4) int cnd_broadcast(cnd_t *cond) 除阻所有当前在 cond 所指向的条件变量上等待的线程。若无被阻塞的线程,则不做任何事并返回 thrd_success 。 参数: cond: 指向条件变量的指针 返回值: 若成功则为 thrd_success ,否则为 thrd_error 。 (5) int cnd_wait(cnd_t* cond, mtx_t* mutex) 原子地解锁 mutex 所指向的互斥,并在 cond 所指向的条件变量上阻塞,直至线程被 cnd_signal 或 cnd_broadcast 发信号,或直至虚假唤醒出现。在此函数返回前,重新锁定该互斥。 若调用方线程未锁定该互斥,则行为未定义。 参数: cond: 指向要在上面阻塞的条件变量的指针 mutex: 指向要在阻塞期解锁的互斥的指针 返回值: 若成功则为 thrd_success ,否则为 thrd_error 。 (6) int cnd_timedwait(cnd_t* restrict cond, mtx_t* restrict mutex, const struct timespec* restrict time_point) 原子地解锁 mutex 所指向的互斥,并在 cond 所指向的条件变量上阻塞,直到线程被 cnd_signal 或 cnd_broadcast 发信号,或直至抵达 time_point 所指向的基于 TIME_UTC 的时间点,或直至虚假唤醒出现。在函数返回前重新锁定该互斥。 若调用方线程未锁定该互斥,则行为未定义。 参数: cond: 指向要在上面阻塞的条件变量的指针 mutex: 指向要在阻塞期间解锁的互斥的指针 time_point: 指向指定等待时限时间的对象的指针 返回值: 若成功则为 thrd_success ,若在锁定互斥前抵达时限则为 thrd_timedout ,若出现错误则为 thrd_error 。 (7) void cnd_destroy(cnd_t* cond) 销毁 cond 所指向的条件变量。 若有线程在 cond 上等待,则行为未定义。 参数: cond: 指向要销毁的条件变量的指针 返回值: (无) */ typedef struct { void *value; mtx_t locker; cnd_t read; cnd_t write; } channel_t; channel_t *create_channel() { channel_t *ch = (channel_t *)malloc(sizeof(channel_t)); ch->value = NULL; mtx_init(&(ch->locker), mtx_plain); cnd_init(&(ch->read)); cnd_init(&(ch->write)); return ch; } void delete_channel(channel_t *ch) { mtx_destroy(&(ch->locker)); cnd_destroy(&(ch->read)); cnd_destroy(&(ch->write)); return; } void *read(channel_t *ch) { void *ret; mtx_lock(&(ch->locker)); for (;;) { if (ch->value == NULL) { printf("[%ld] wait to read ...\n", thrd_current()); cnd_wait(&(ch->read), &(ch->locker)); printf("[%ld] can read now: \n", thrd_current()); } else { break; } } ret = ch->value; ch->value = NULL; mtx_unlock(&(ch->locker)); cnd_signal(&(ch->write)); return ret; } void write(channel_t *ch, void *value) { mtx_lock(&(ch->locker)); for (;;) { if (ch->value != NULL) { printf("[%ld] wait to write ...\n", thrd_current()); cnd_wait(&(ch->write), &(ch->locker)); printf("[%ld] can write now: \n", thrd_current()); } else { break; } } ch->value = value; mtx_unlock(&(ch->locker)); cnd_signal(&(ch->read)); return; } int th_read(void *p) { channel_t *ch = (channel_t *)p; int64_t *n = (int64_t *)read(ch); printf("[%ld] read: n=%ld\n", thrd_current(), *n); return thrd_success; } int th_write(void *p) { void **args = (void **)p; channel_t *ch = (channel_t *)args[0]; int64_t *n = (int64_t *)args[1]; write(ch, (void *)n); printf("[%ld] write: n=%ld\n", thrd_current(), *n); return thrd_success; } int main(int argc, char const *argv[]) { channel_t *ch = create_channel(); thrd_t r_th1; thrd_create(&r_th1, th_read, ch); thrd_t r_th2; thrd_create(&r_th2, th_read, ch); thrd_t w_th1; int64_t w_n1 = 100; void *w_args1[] = {ch, &w_n1}; thrd_create(&w_th1, th_write, (void *)w_args1); thrd_t w_th2; int64_t w_n2 = 200; void *w_args2[] = {ch, &w_n2}; thrd_create(&w_th2, th_write, (void *)w_args2); thrd_join(r_th1, NULL); thrd_join(r_th2, NULL); thrd_join(w_th1, NULL); thrd_join(w_th2, NULL); delete_channel(ch); return EXIT_SUCCESS; }
raoyitao/testplan
examples/JUnit/gradle_mock.py
#!/usr/bin/env python import sys import pathlib current_path = pathlib.Path(__file__).parent.absolute() def output(): sys.stdout.write( r"""> Configure project : > Task :compileJava UP-TO-DATE > Task :processResources UP-TO-DATE > Task :classes UP-TO-DATE > Task :compileTestJava UP-TO-DATE > Task :processTestResources NO-SOURCE > Task :testClasses UP-TO-DATE > Task :test MessageServiceTest > testGet() FAILED org.opentest4j.AssertionFailedError at MessageServiceTest.java:11 2021-03-19 11:11:50.150 INFO 39460 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor' > Task :test FAILED Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0. Use '--warning-mode all' to show the individual deprecation warnings. See https://docs.gradle.org/6.8.2/userguide/command_line_interface.html#sec:command_line_warnings 4 actionable tasks: 1 executed, 3 up-to-date """ ) def xml_output(report_dir): with open( report_dir / "TEST-com.gradle.example.application.ApplicationTests.xml", "w", ) as application_test: application_test.write( r"""<?xml version="1.0" encoding="UTF-8"?> <testsuite name="com.gradle.example.application.ApplicationTests" tests="1" skipped="0" failures="0" errors="0" timestamp="2021-03-19T03:11:49" hostname="example.com" time="0.228"> <properties/> <testcase name="contextLoads()" classname="com.gradle.example.application.ApplicationTests" time="0.228"/> <system-out><![CDATA[11:11:48.002 [Test worker] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate 11:48.283 [Test worker] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners 2021-03-19 11:11:48.665 INFO 39460 --- [ Test worker] c.m.g.e.application.ApplicationTests : Starting ApplicationTests using Java 1.8.0_242 on localhost with PID 39460 (started by user in gradle/samples/application) 2021-03-19 11:11:48.669 INFO 39460 --- [ Test worker] c.m.g.e.application.ApplicationTests : No active profile set, falling back to default profiles: default 2021-03-19 11:11:49.634 INFO 39460 --- [ Test worker] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2021-03-19 11:11:49.895 INFO 39460 --- [ Test worker] c.m.g.e.application.ApplicationTests : Started ApplicationTests in 1.579 seconds (JVM running for 2.668) ]]></system-out> <system-err><![CDATA[]]></system-err> </testsuite>""" ) def main(): test_report_path = current_path / "build/test-results/test" test_report_path.mkdir(parents=True, exist_ok=True) xml_output(test_report_path) output() if __name__ == "__main__": if len(sys.argv) == 2 and sys.argv[1] == "test": main() else: raise RuntimeError("Invalid argument!")
bmjames/intellij-haskforce
src/com/haskforce/parsing/srcExtsDatatypes/FieldUpdateTopType.java
<filename>src/com/haskforce/parsing/srcExtsDatatypes/FieldUpdateTopType.java package com.haskforce.parsing.srcExtsDatatypes; /** * data FieldUpdate l * = FieldUpdate l (QName l) (Exp l) -- ^ ordinary label-expression pair * | FieldPun l (Name l) -- ^ record field pun * | FieldWildcard l -- ^ record field wildcard */ public class FieldUpdateTopType { }
xtecuan/sgipd-main-final
sgipd-web/src/main/java/sv/gob/mined/projects/sgipd/resources/MunicipioResource.java
<reponame>xtecuan/sgipd-main-final package sv.gob.mined.projects.sgipd.resources; import sv.gob.mined.projects.sgipd.entities.Municipio; import sv.gob.mined.projects.sgipd.repositories.MunicipioRepository; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.util.List; @ApplicationScoped @Path("municipio") @Produces(MediaType.APPLICATION_JSON) public class MunicipioResource { @Inject private MunicipioRepository municipioRepository; @GET@Path("/departamento/{idDepartamento}") public List<Municipio> findAllMunicipiosByDepartamento(@PathParam("idDepartamento")long idDepartamento){ return municipioRepository.findAllMunicipiosByDepartamento(idDepartamento); } }
aleks-pro/resolve
packages/core/resolve-local-event-broker/src/server/anycast-events.js
<gh_stars>0 const anycastEvents = async (pool, listenerId, events, properties) => { const clientId = pool.clientMap .get(listenerId) [Symbol.iterator]() // eslint-disable-line no-unexpected-multiline .next().value const encodedTopic = pool.encodeXpubTopic({ listenerId, clientId }) const messageGuid = pool.cuid() const promise = new Promise(resolve => pool.waitMessagePromises.set(messageGuid, resolve) ) const encodedContent = pool.encodePubContent( JSON.stringify({ messageGuid, properties, events }) ) await pool.xpubSocket.send(`${encodedTopic} ${encodedContent}`) let isDone = false const result = await Promise.race([ (async () => { let promiseResult try { promiseResult = await promise } catch (err) {} isDone = true return promiseResult })(), (async () => { while (!isDone) { await new Promise(resolve => setTimeout(resolve, 100)) const listenerSet = pool.clientMap.get(listenerId) if (listenerSet == null || !listenerSet.has(clientId)) { pool.waitMessagePromises.delete(messageGuid) return null } } throw new Error('Abnormal termination') })() ]) return result } export default anycastEvents