repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
paul-nameless/beanie
beanie/odm/utils/projection.py
from typing import Dict, Type from pydantic import BaseModel def get_projection(model: Type[BaseModel]) -> Dict[str, int]: if getattr(model, "Settings", None) and getattr( model.Settings, "projection", None ): return model.Settings.projection document_projection: Dict[str, int] = {} for name, field in model.__fields__.items(): document_projection[field.alias] = 1 return document_projection
csyonghe/spire-engine
GameEngineCore/OutlinePassParameters.h
#ifndef GAME_ENGINE_OUTLINE_PARAMS_H #define GAME_ENGINE_OUTLINE_PARAMS_H #include "CoreLib/VectorMath.h" #include "CoreLib/Basic.h" namespace GameEngine { struct OutlinePassParameters { VectorMath::Vec4 color = VectorMath::Vec4::Create(0xFF/255.0f, 0xC1 / 255.0f, 0x07 / 255.0f, 1.0f); VectorMath::Vec2 pixelSize = VectorMath::Vec2::Create(0.0f, 0.0f); float Width = 5.0f; OutlinePassParameters() { } bool operator == (const OutlinePassParameters & other) const { return Width == other.Width && pixelSize.x == other.pixelSize.x && pixelSize.y == other.pixelSize.y; } }; } #endif
HildoBijl/stepwise
frontend/src/ui/edu/exercises/exercises/poissonsLawCompressor.js
<reponame>HildoBijl/stepwise import React from 'react' import { M, BM } from 'ui/components/equations' import { Par } from 'ui/components/containers' import { InputSpace } from 'ui/form/Status' import FloatUnitInput, { validNumberAndUnit } from 'ui/form/inputs/FloatUnitInput' import MultipleChoice from 'ui/form/inputs/MultipleChoice' import { Dutch } from 'ui/lang/gases' import StepExercise from '../types/StepExercise' import Substep from '../types/StepExercise/Substep' import { useSolution } from '../ExerciseContainer' import { getInputFieldFeedback, getMCFeedback } from '../util/feedback' export default function Exercise() { return <StepExercise Problem={Problem} steps={steps} getFeedback={getFeedback} /> } const Problem = ({ gas, V2, p1, p2 }) => <> <Par>Een compressor vult een drukvat met {Dutch[gas]}gas. Het drukvat heeft een volume van <M>{V2}.</M> De compressor comprimeert het {Dutch[gas]} van <M>{p1}</M> naar <M>{p2}.</M> Deze compressie is bij benadering isentroop, waardoor geldt <M>n = k.</M> Hoeveel volume aan {Dutch[gas]}gas is de compressor ingestroomd?</Par> <InputSpace> <Par> <FloatUnitInput id="V1" prelabel={<M>V_(\rm in)=</M>} label="Volume" size="s" /> </Par> </InputSpace> </> const steps = [ { Problem: () => <> <Par>Noem het ingestroomde gas "punt 1" en het uitgestroomde gas dat nu in het drukvat zit "punt 2". Zet alle gegeven waarden in eenheden waarmee we mogen rekenen.</Par> <InputSpace> <Par> <Substep ss={1}><FloatUnitInput id="p1" prelabel={<M>p_1=</M>} label="Begindruk" size="s" /></Substep> <Substep ss={2}><FloatUnitInput id="p2" prelabel={<M>p_2=</M>} label="Einddruk" size="s" /></Substep> <Substep ss={3}><FloatUnitInput id="V2" prelabel={<M>V_2=</M>} label="Eindvolume" size="s" /></Substep> </Par> </InputSpace> </>, Solution: ({ p1, p2, V2 }) => { return <> <Par>Wat druk betreft mogen we bij Poisson's wet rekenen met zowel bar als Pascal. Natuurlijk is het altijd veiliger om standaard eenheden (Pascal) te gebruiken, maar in dit geval mogen we dus ook met bar rekenen. We houden hier voor het gemak <M>p_1 = {p1}</M> en <M>p_2 = {p2}.</M></Par> <Par>Ook bij het volume mogen we rekenen met liters, in plaats van de standaard eenheid kubieke meters. We moeten dan wel onthouden dat de uitkomst van onze berekeningen ook in liters is. Dus rekenen we met <M>V_2 = {V2}.</M></Par> </> }, }, { Problem: () => <> <Par>Zoek de <M>k</M>-waarde (verhouding van soortelijke warmten) op van het betreffende gas.</Par> <InputSpace> <Par><FloatUnitInput id="k" prelabel={<M>k =</M>} label={<span><M>k</M>-waarde</span>} size="s" validate={validNumberAndUnit} /></Par> </InputSpace> </>, Solution: () => { const { gas, k } = useSolution() return <Par>De verhouding van soortelijke warmten van {Dutch[gas]} is <M>k = {k}.</M></Par> }, }, { Problem: () => <> <Par>Kies de juiste wet van Poisson. Welke is hier het handigst om te gebruiken?</Par> <InputSpace> <MultipleChoice id="eq" choices={[ <M>pV^n=(\rm constant)</M>, <M>TV^(n-1)=(\rm constant)</M>, <M>\frac(T^n)(p^(n-1))=(\rm constant)</M>, ]} /> </InputSpace> </>, Solution: () => { return <Par>Bij dit probleem weten we de druk <M>p</M> en het volume <M>V</M>, maar niet de temperatuur <M>T.</M> We pakken dus de vergelijking zonder temperatuur: <BM>pV^n=(\rm constant).</BM></Par> }, }, { Problem: () => <> <Par>Bereken via de gekozen wet van Poisson het volume voor de compressie.</Par> <InputSpace> <Par> <FloatUnitInput id="V1" prelabel={<M>V_1=</M>} label="Volume" size="s" /> </Par> </InputSpace> </>, Solution: () => { const { k, V1, V2, p1, p2 } = useSolution() return <Par>Poisson's wet zegt dat <M>pV^n=(\rm constant)</M> waardoor we mogen schrijven, <BM>p_1V_1^n = p_2V_2^n.</BM> We willen dit oplossen voor <M>V_1.</M> Delen door <M>p_1</M> geeft <BM>V_1^n = \frac(p_2)(p_1) \cdot V_2^n.</BM> Om de macht weg te krijgen doen we beide kanten van de vergelijking tot de macht <M>\frac(1)(n)</M> waarmee we uitkomen op <BM>V_1 = \left(\frac(p_2)(p_1) \cdot V_2^n\right)^(\frac(1)(n)) = \left(\frac(p_2)(p_1)\right)^(\frac(1)(n)) V_2 = \left(\frac{p2.float}{p1.float}\right)^(\frac(1)({k.float})) \cdot {V2.float} = {V1}.</BM> Omdat we het volume <M>V_2</M> in liters hebben ingevuld, is de uitkomst <M>V_1</M> ook in liters. We kunnen dit eventueel nog omrekenen naar <M>{V1.setUnit('m^3')}</M> maar dat is niet per se nodig.</Par> }, }, ] const getFeedback = (exerciseData) => { const { input, shared } = exerciseData const { data } = shared const feedback = { ...getInputFieldFeedback(['p1', 'p2', 'V1', 'V2', 'k'], exerciseData), ...getMCFeedback('eq', exerciseData, { correct: 0, step: 3, correctText: <span>Inderdaad! We weten <M>p</M> en <M>V</M>, wat dit de optimale vergelijking maakt om te gebruiken.</span>, incorrectText: <span>Dat lijkt me niet handig. We weten niets over de temperatuur <M>T</M>, en we hoeven hem ook niet te weten. Dus waarom wil je die in een vergelijking hebben?</span>, }), } // If p1 and p2 have different units, then note this. if (input.p1 && input.p2 && !input.p1.unit.equals(input.p2.unit, data.equalityOptions.pUnit)) { const addedFeedback = { correct: false, text: <span>De eenheden van <M>p_1</M> en <M>p_2</M> moeten gelijk zijn.</span> } feedback.p1 = addedFeedback feedback.p2 = addedFeedback } return feedback }
Nice9166/iotdb
server/src/main/java/org/apache/iotdb/db/mpp/common/filter/InFilter.java
<filename>server/src/main/java/org/apache/iotdb/db/mpp/common/filter/InFilter.java<gh_stars>1-10 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iotdb.db.mpp.common.filter; import org.apache.iotdb.db.exception.metadata.MetadataException; import org.apache.iotdb.db.exception.sql.StatementAnalyzeException; import org.apache.iotdb.db.metadata.path.PartialPath; import org.apache.iotdb.db.mpp.sql.constant.FilterConstant.FilterType; import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType; import org.apache.iotdb.tsfile.read.common.Path; import org.apache.iotdb.tsfile.read.expression.IUnaryExpression; import org.apache.iotdb.tsfile.read.expression.impl.GlobalTimeExpression; import org.apache.iotdb.tsfile.read.expression.impl.SingleSeriesExpression; import org.apache.iotdb.tsfile.read.filter.TimeFilter; import org.apache.iotdb.tsfile.read.filter.ValueFilter; import org.apache.iotdb.tsfile.read.filter.basic.Filter; import org.apache.iotdb.tsfile.utils.Binary; import org.apache.iotdb.tsfile.utils.Pair; import org.apache.iotdb.tsfile.utils.ReadWriteIOUtils; import org.apache.iotdb.tsfile.utils.StringContainer; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; /** operator 'in' & 'not in' */ public class InFilter extends FunctionFilter { private boolean not; protected Set<String> values; /** * In Filter Constructor. * * @param filterType filter Type * @param path path * @param values values */ public InFilter(FilterType filterType, PartialPath path, boolean not, Set<String> values) { super(filterType); this.singlePath = path; this.values = values; this.not = not; isLeaf = true; isSingle = true; } public Set<String> getValues() { return values; } public boolean getNot() { return not; } @Override public void reverseFunc() { not = !not; } @Override @SuppressWarnings("squid:S3776") // Suppress high Cognitive Complexity warning protected Pair<IUnaryExpression, String> transformToSingleQueryFilter( Map<PartialPath, TSDataType> pathTSDataTypeHashMap) throws StatementAnalyzeException, MetadataException { TSDataType type = pathTSDataTypeHashMap.get(singlePath); if (type == null) { throw new MetadataException( "given seriesPath:{" + singlePath.getFullPath() + "} don't exist in metadata"); } IUnaryExpression ret; switch (type) { case INT32: Set<Integer> integerValues = new HashSet<>(); for (String val : values) { integerValues.add(Integer.valueOf(val)); } ret = In.getUnaryExpression(singlePath, integerValues, not); break; case INT64: Set<Long> longValues = new HashSet<>(); for (String val : values) { longValues.add(Long.valueOf(val)); } ret = In.getUnaryExpression(singlePath, longValues, not); break; case BOOLEAN: Set<Boolean> booleanValues = new HashSet<>(); for (String val : values) { booleanValues.add(Boolean.valueOf(val)); } ret = In.getUnaryExpression(singlePath, booleanValues, not); break; case FLOAT: Set<Float> floatValues = new HashSet<>(); for (String val : values) { floatValues.add(Float.parseFloat(val)); } ret = In.getUnaryExpression(singlePath, floatValues, not); break; case DOUBLE: Set<Double> doubleValues = new HashSet<>(); for (String val : values) { doubleValues.add(Double.parseDouble(val)); } ret = In.getUnaryExpression(singlePath, doubleValues, not); break; case TEXT: Set<Binary> binaryValues = new HashSet<>(); for (String val : values) { binaryValues.add( (val.startsWith("'") && val.endsWith("'")) || (val.startsWith("\"") && val.endsWith("\"")) ? new Binary(val.substring(1, val.length() - 1)) : new Binary(val)); } ret = In.getUnaryExpression(singlePath, binaryValues, not); break; default: throw new StatementAnalyzeException(type.toString(), ""); } return new Pair<>(ret, singlePath.getFullPath()); } @Override public String showTree(int spaceNum) { StringContainer sc = new StringContainer(); for (int i = 0; i < spaceNum; i++) { sc.addTail(" "); } sc.addTail(singlePath.getFullPath(), getFilterSymbol(), not, values, ", single\n"); return sc.toString(); } @Override public InFilter copy() { InFilter ret = new InFilter(this.filterType, singlePath.clone(), not, new HashSet<>(values)); ret.isLeaf = isLeaf; ret.isSingle = isSingle; ret.pathSet = pathSet; return ret; } @Override public String toString() { List<String> valuesList = new ArrayList<>(values); Collections.sort(valuesList); return "[" + singlePath.getFullPath() + getFilterSymbol() + not + valuesList + "]"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InFilter that = (InFilter) o; return Objects.equals(singlePath, that.singlePath) && values.containsAll(that.values) && values.size() == that.values.size() && not == that.not; } @Override public int hashCode() { return Objects.hash(super.hashCode(), singlePath, not, values); } private static class In { public static <T extends Comparable<T>> IUnaryExpression getUnaryExpression( Path path, Set<T> values, boolean not) { if (path != null && path.toString().equals("time")) { return new GlobalTimeExpression(TimeFilter.in((Set<Long>) values, not)); } else { return new SingleSeriesExpression(path, ValueFilter.in(values, not)); } } public <T extends Comparable<T>> Filter getValueFilter(T value) { return ValueFilter.notEq(value); } } public void serialize(ByteBuffer byteBuffer) { FilterTypes.In.serialize(byteBuffer); super.serializeWithoutType(byteBuffer); ReadWriteIOUtils.write(not, byteBuffer); ReadWriteIOUtils.write(values.size(), byteBuffer); for (String value : values) { ReadWriteIOUtils.write(value, byteBuffer); } } public static InFilter deserialize(ByteBuffer byteBuffer) { QueryFilter queryFilter = QueryFilter.deserialize(byteBuffer); boolean not = ReadWriteIOUtils.readBool(byteBuffer); int size = ReadWriteIOUtils.readInt(byteBuffer); Set<String> values = new HashSet<>(); for (int i = 0; i < size; i++) { values.add(ReadWriteIOUtils.readString(byteBuffer)); } return new InFilter(queryFilter.filterType, queryFilter.singlePath, not, values); } }
daybreak/daybreak
vendor/extensions/record_tags/record_tags_extension.rb
<gh_stars>1-10 class RecordTagsExtension < Radiant::Extension version "0.5" description "Adds tags for displaying database records. A natural front end for custom, back-end models." url "" def activate Page.send :include, RecordTags end end
adamruzicka/dynflow
lib/dynflow/director/sequential_manager.rb
module Dynflow class Director class SequentialManager attr_reader :execution_plan, :world def initialize(world, execution_plan) @world = world @execution_plan = execution_plan @done = false end def run with_state_updates do dispatch(execution_plan.run_flow) finalize end return execution_plan end def finalize reset_finalize_steps unless execution_plan.error? step_id = execution_plan.finalize_flow.all_step_ids.first action_class = execution_plan.steps[step_id].action_class world.middleware.execute(:finalize_phase, action_class, execution_plan) do dispatch(execution_plan.finalize_flow) end end @done = true end def reset_finalize_steps execution_plan.finalize_flow.all_step_ids.each do |step_id| step = execution_plan.steps[step_id] step.state = :pending if [:success, :error].include? step.state end end def done? @done end private def dispatch(flow) case flow when Flows::Sequence run_in_sequence(flow.flows) when Flows::Concurrence run_in_concurrence(flow.flows) when Flows::Atom run_step(execution_plan.steps[flow.step_id]) else raise ArgumentError, "Don't know how to run #{flow}" end end def run_in_sequence(steps) steps.all? { |s| dispatch(s) } end def run_in_concurrence(steps) run_in_sequence(steps) end def run_step(step) step.execute return step.state != :error end def with_state_updates(&block) execution_plan.update_state(:running) block.call execution_plan.update_state(execution_plan.error? ? :paused : :stopped) end end end end
librairy/modeler-lda
src/main/java/org/librairy/modeler/lda/dao/LDAKeyspaceDao.java
<filename>src/main/java/org/librairy/modeler/lda/dao/LDAKeyspaceDao.java<gh_stars>1-10 /* * Copyright (c) 2016. Universidad Politecnica de Madrid * * @author <NAME>, Carlos <<EMAIL>> * */ package org.librairy.modeler.lda.dao; import com.datastax.driver.core.exceptions.InvalidQueryException; import org.librairy.boot.storage.dao.DBSessionManager; import org.librairy.boot.storage.generator.URIGenerator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @author <NAME>, Carlos <<EMAIL>> */ @Component public class LDAKeyspaceDao { private static final Logger LOG = LoggerFactory.getLogger(LDAKeyspaceDao.class); @Autowired DBSessionManager sessionManager; public void initialize(String domainUri){ LOG.info("creating a new LDA workspace for domain: " + domainUri); try{ sessionManager.getSession().execute("create keyspace if not exists "+DBSessionManager.getSpecificKeyspaceId("lda", URIGenerator.retrieveId(domainUri))+ " with replication = {'class' : 'SimpleStrategy', 'replication_factor' : 1} and DURABLE_WRITES = true;"); }catch (InvalidQueryException e){ LOG.warn(e.getMessage()); } } public void destroy(String domainUri){ LOG.info("dropping existing LDA workspace for domain: " + domainUri); try{ sessionManager.getSession().execute("drop keyspace if exists " + DBSessionManager.getSpecificKeyspaceId("lda", URIGenerator.retrieveId(domainUri))+ ";"); }catch (InvalidQueryException e){ LOG.warn(e.getMessage()); } } }
rajrs/reactWorkspace
todo/src/components/HomePage.js
<filename>todo/src/components/HomePage.js import React, { Component } from 'react' import TaskForm from './TaskForm'; import Todos from './Todo'; import {connect} from'react-redux'; class HomePage extends Component { render(){ return (<><TaskForm /><Todos todos={this.props.todos} /></>) } } const mapStatetoProp=(state)=>{ return {todos:state.todos,isAuth:state.isAuth} } export default connect(mapStatetoProp,null)(HomePage);
Kaupenjoe/Forge-Course-118
src/main/java/net/kaupenjoe/mccourse/entity/custom/ModBoatEntity.java
<reponame>Kaupenjoe/Forge-Course-118 package net.kaupenjoe.mccourse.entity.custom; import net.kaupenjoe.mccourse.entity.ModEntityTypes; import net.kaupenjoe.mccourse.item.ModItems; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.vehicle.Boat; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; import net.minecraft.world.level.Level; public class ModBoatEntity extends Boat { private static final EntityDataAccessor<Integer> DATA_ID_TYPE = SynchedEntityData.defineId(ModBoatEntity.class, EntityDataSerializers.INT); public ModBoatEntity(EntityType<? extends ModBoatEntity> entityType, Level level) { super(entityType, level); this.blocksBuilding = true; } public ModBoatEntity(Level worldIn, double x, double y, double z) { this(ModEntityTypes.BOAT_ENTITY.get(), worldIn); this.setPos(x, y, z); this.xo = x; this.yo = y; this.zo = z; } protected void addAdditionalSaveData(CompoundTag compound) { compound.putString("Type", this.getModBoatType().getName()); } protected void readAdditionalSaveData(CompoundTag compound) { if (compound.contains("Type", 8)) { this.setBoatType(ModBoatEntity.Type.byName(compound.getString("Type"))); } } @Override protected void defineSynchedData() { super.defineSynchedData(); this.entityData.define(DATA_ID_TYPE, Type.CHERRY_BLOSSOM.ordinal()); } @Override public Item getDropItem() { switch (this.getModBoatType()) { case CHERRY_BLOSSOM: return ModItems.CHERRY_BLOSSOM_BOAT.get(); default: return Items.OAK_BOAT; } } public void setBoatType(ModBoatEntity.Type boatType) { this.entityData.set(DATA_ID_TYPE, boatType.ordinal()); } public ModBoatEntity.Type getModBoatType() { return ModBoatEntity.Type.byId(this.entityData.get(DATA_ID_TYPE)); } public enum Type { CHERRY_BLOSSOM("cherry_blossom"); private final String name; Type(String name) { this.name = name; } public String getName() { return this.name; } public static ModBoatEntity.Type byId(int id) { ModBoatEntity.Type[] types = values(); if (id < 0 || id >= types.length) { id = 0; } return types[id]; } public static ModBoatEntity.Type byName(String nameIn) { ModBoatEntity.Type[] types = values(); for (int i = 0; i < types.length; ++i) { if (types[i].getName().equals(nameIn)) { return types[i]; } } return types[0]; } } }
Intel-EPID-SDK/epid-sdk
ext/ipp-crypto/sources/ippcp/gsmod_packctx.c
<filename>ext/ipp-crypto/sources/ippcp/gsmod_packctx.c<gh_stars>10-100 /******************************************************************************* * Copyright 2017-2020 Intel Corporation * * 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. *******************************************************************************/ /* // // Purpose: // Cryptography Primitive. Modular Arithmetic Engine. General Functionality // // Contents: // gsPackModEngineCtx() // */ #include "owndefs.h" #include "owncp.h" #include "pcpbnumisc.h" #include "pcpbnuarith.h" #include "gsmodstuff.h" #include "pcptool.h" /* // Pack/Unpack methods */ IPP_OWN_DEFN (void, gsPackModEngineCtx, (const gsModEngine* pCtx, Ipp8u* pBuffer)) { gsModEngine* pB = (gsModEngine*)pBuffer; /* max modulus length */ int modSize = MOD_LEN(pCtx); /* size of context (bytes) without cube and pool buffers */ int ctxSize = (Ipp32s)sizeof(gsModEngine) +(Ipp32s)sizeof(BNU_CHUNK_T)*(modSize*3); CopyBlock(pCtx, pB, ctxSize); MOD_MODULUS(pB) = (BNU_CHUNK_T*)((Ipp8u*)NULL + IPP_UINT_PTR(MOD_MODULUS(pCtx))-IPP_UINT_PTR(pCtx)); MOD_MNT_R(pB) = (BNU_CHUNK_T*)((Ipp8u*)NULL + IPP_UINT_PTR(MOD_MNT_R(pCtx))-IPP_UINT_PTR(pCtx)); MOD_MNT_R2(pB) = (BNU_CHUNK_T*)((Ipp8u*)NULL + IPP_UINT_PTR(MOD_MNT_R2(pCtx))-IPP_UINT_PTR(pCtx)); }
trevorsaunders/studentinsights
app/importers/tools/analyze_student_attendance_table.rb
require 'csv' class AnalyzeStudentAttendanceTable < Struct.new(:path) def contents encoding_options = { invalid: :replace, undef: :replace, replace: '' } @file ||= File.read(path).encode('UTF-8', 'binary', encoding_options) .gsub(/\\\\/, '') .gsub(/\\"/, '') end def data csv_options = { headers: true, header_converters: :symbol, converters: ->(h) { nil_converter(h) } } @parsed_csv ||= CSV.parse(contents, csv_options) end def nil_converter(value) value unless value == '\N' end def select_by_column(column, value) data.select { |row| row[column] == value } end def count_for_column(column, value) select_by_column(column, value).size end def total @total ||= data.length end def count_versus_total(column, value) count = count_for_column(column, value) percentage = 100 * count.to_f / total.to_f "#{column} => #{count} out of #{total} (#{percentage}%)" end end
LittleTear/zim
src/main/scala/org/bitlap/zim/configuration/ApplicationConfiguration.scala
<reponame>LittleTear/zim package org.bitlap.zim.configuration import org.bitlap.zim.application.{ UserApplication, UserService } import org.bitlap.zim.configuration.InfrastructureConfiguration.ZInfrastructureConfiguration import zio._ /** * 应用程序配置 * * @author 梦境迷离 * @since 2021/12/25 * @version 1.0 */ final class ApplicationConfiguration(infrastructureConfiguration: InfrastructureConfiguration) { // 应用程序管理多个application,这里只有一个(模块化) val userApplication: UserApplication = UserService(infrastructureConfiguration.userRepository) } /** * 应用程序依赖管理 */ object ApplicationConfiguration { def apply(infrastructureConfiguration: InfrastructureConfiguration): ApplicationConfiguration = new ApplicationConfiguration(infrastructureConfiguration) type ZApplicationConfiguration = Has[ApplicationConfiguration] val userApplication: URIO[ZApplicationConfiguration, UserApplication] = ZIO.access(_.get.userApplication) val live: ZLayer[ZInfrastructureConfiguration, Nothing, ZApplicationConfiguration] = ZLayer.fromService[InfrastructureConfiguration, ApplicationConfiguration](ApplicationConfiguration(_)) def make(infrastructureConfiguration: InfrastructureConfiguration): ULayer[ZApplicationConfiguration] = ZLayer.succeed(infrastructureConfiguration) >>> live }
ahmedsalihh/gitter-test
public/js/vue/thread-message-feed/store/index.js
<gh_stars>0 import Vue from 'vue'; import appEvents from '../../../utils/appevents'; import apiClient from '../../../components/api-client'; import log from '../../../utils/log'; import moment from 'moment'; import composeQueryString from 'gitter-web-qs/compose'; import * as rootTypes from '../../store/mutation-types'; import VuexApiRequest from '../../store/vuex-api-request'; import { generateChildMessageTmpId } from '../../store/mutations'; import ChatItemPolicy from '../../../views/chat/chat-item-policy'; import VuexMessageRequest from '../../store/vuex-message-request'; const FETCH_MESSAGES_LIMIT = 50; // Exported for testing export const childMessagesVuexRequest = new VuexApiRequest( 'CHILD_MESSAGES', 'childMessagesRequest' ); const canStartFetchingMessages = state => !state.childMessagesRequest.loading && !state.childMessagesRequest.error; /** * sets a prop on a message and after 5s sets * the same attribute to `undefined` * Used for notifying a chat-item component that it should react on an event */ const setTemporaryMessageProp = (commit, id, propName, propValue = true) => { commit(rootTypes.UPDATE_MESSAGE, { id, [propName]: propValue }, { root: true }); setTimeout( () => commit(rootTypes.UPDATE_MESSAGE, { id, [propName]: undefined }, { root: true }), 5000 ); }; const isMessageEditable = (message, rootState) => { const policy = new ChatItemPolicy(message, { currentUserId: rootState.user.id }); return policy.canEdit(); }; /* we only use `loading` attribute from the request state */ const getDefaultMessageEditState = () => ({ id: null, text: null }); // Exported for testing export const types = { TOGGLE_THREAD_MESSAGE_FEED: 'TOGGLE_THREAD_MESSAGE_FEED', SET_PARENT_MESSAGE_ID: 'SET_PARENT_MESSAGE_ID', UPDATE_DRAFT_MESSAGE: 'UPDATE_DRAFT_MESSAGE', SET_AT_TOP_IF_SAME_PARENT: 'SET_AT_TOP_IF_SAME_PARENT', SET_AT_BOTTOM_IF_SAME_PARENT: 'SET_AT_BOTTOM_IF_SAME_PARENT', RESET_THREAD_STATE: 'RESET_THREAD_STATE', UPDATE_MESSAGE_EDIT_STATE: 'UPDATE_MESSAGE_EDIT_STATE', // just for completeness, the types are referenced using the request class e.g. `childMessagesVuexRequest.successType` ...childMessagesVuexRequest.types }; export default { namespaced: true, state: () => ({ isVisible: false, draftMessage: '', messageEditState: getDefaultMessageEditState(), atTop: false, atBottom: false, parentId: null, ...childMessagesVuexRequest.initialState }), mutations: { [types.TOGGLE_THREAD_MESSAGE_FEED](state, isVisible) { state.isVisible = isVisible; }, [types.SET_PARENT_MESSAGE_ID](state, parentId) { state.parentId = parentId; }, [types.UPDATE_DRAFT_MESSAGE](state, draftMessage) { state.draftMessage = draftMessage; }, [types.SET_AT_TOP_IF_SAME_PARENT](state, parentId) { // TMF parent changed during fetching, don't add a mark if (state.parentId !== parentId) return; state.atTop = true; }, [types.SET_AT_BOTTOM_IF_SAME_PARENT](state, parentId) { // TMF parent changed during fetching, don't add a mark if (state.parentId !== parentId) return; state.atBottom = true; }, [types.RESET_THREAD_STATE](state) { state.parentId = null; state.draftMessage = ''; state.atTop = false; state.atBottom = false; state.messageEditState = getDefaultMessageEditState(); }, [types.UPDATE_MESSAGE_EDIT_STATE](state, newProperties) { Vue.set(state, 'messageEditState', { ...state.messageEditState, ...newProperties }); }, ...childMessagesVuexRequest.mutations }, getters: { parentMessage: (state, getters, rootState) => { return rootState.messageMap[state.parentId]; }, childMessages: (state, getters, rootState) => { const { parentId } = state; const childMessages = Object.values(rootState.messageMap).filter( m => m.parentId === parentId ); // we use moment because the messages combine messages from bayeux and ordinary json messages (fetch during TMF open) return childMessages.sort((m1, m2) => moment(m1.sent).diff(m2.sent)); // sort from oldest to latest } }, actions: { open: ({ commit, dispatch, state }, parentId) => { if (state.isVisible && state.parentId === parentId) return; commit(types.RESET_THREAD_STATE); commit(types.TOGGLE_THREAD_MESSAGE_FEED, true); commit(types.SET_PARENT_MESSAGE_ID, parentId); appEvents.trigger('vue:right-toolbar:toggle', false); return dispatch('fetchInitialMessages'); }, close: ({ commit }) => { commit(types.TOGGLE_THREAD_MESSAGE_FEED, false); appEvents.trigger('vue:right-toolbar:toggle', true); }, updateDraftMessage: ({ commit }, newDraftMessage) => { commit(types.UPDATE_DRAFT_MESSAGE, newDraftMessage); }, sendMessage: ({ state, commit, dispatch, rootState }) => { if (!state.draftMessage) return; const messagePayload = { text: state.draftMessage, parentId: state.parentId }; const fromUser = rootState.user; const tmpMessage = { ...messagePayload, id: generateChildMessageTmpId(state.parentId, fromUser.id, state.draftMessage), fromUser, sent: new Date(Date.now()) }; commit(rootTypes.ADD_TO_MESSAGE_MAP, [{ ...tmpMessage, loading: true }], { root: true }); apiClient.room .post('/chatMessages', messagePayload) .then(message => { // the message from the API response fully replaces the `tmpMessage` and because it // doesn't contain the `loading` attribute, UI will hide the loading indicator commit(rootTypes.ADD_TO_MESSAGE_MAP, [message], { root: true }); dispatch('focusOnMessage', { id: message.id, block: 'end' }); }) .catch(err => { log.error(err); commit(rootTypes.ADD_TO_MESSAGE_MAP, [{ ...tmpMessage, error: true, loading: false }], { root: true }); }); commit(types.UPDATE_DRAFT_MESSAGE, ''); }, deleteMessage: async ({ commit }, message) => { const messageRequest = new VuexMessageRequest(message.id); commit(...messageRequest.loadingMutation()); apiClient.room .delete(`/chatMessages/${message.id}`) .then(() => commit(rootTypes.REMOVE_MESSAGE, message, { root: true })) .catch(err => { log.error(err); commit(...messageRequest.errorMutation()); }); }, reportMessage: async ({ commit }, message) => { const messageRequest = new VuexMessageRequest(message.id); commit(...messageRequest.loadingMutation()); apiClient.room .post(`/chatMessages/${message.id}/report`) .then(() => commit(...messageRequest.successMutation())) .catch(err => { log.error(err); commit(...messageRequest.errorMutation()); }); }, quoteMessage: ({ commit, state }, message) => { const formattedText = message.text .split(/\r?\n/) .map(line => `> ${line}`) .join('\n'); const { draftMessage } = state; if (draftMessage) { commit(types.UPDATE_DRAFT_MESSAGE, `${draftMessage}\n${formattedText}\n\n`); } else { commit(types.UPDATE_DRAFT_MESSAGE, `${formattedText}\n\n`); } }, updateMessage: ({ commit, state, dispatch }) => { const { messageEditState } = state; const messageRequest = new VuexMessageRequest(messageEditState.id); commit(...messageRequest.loadingMutation()); return apiClient.room .put(`/chatMessages/${messageEditState.id}`, { text: messageEditState.text }) .then(updatedMessage => commit(...messageRequest.successMutation(updatedMessage))) .catch(err => { log.error(err); commit(...messageRequest.errorMutation({ text: messageEditState.text, html: undefined })); }) .finally(() => dispatch('cancelEdit')); }, editMessage: ({ commit, rootState }, message) => { if (isMessageEditable(message, rootState)) { commit(types.UPDATE_MESSAGE_EDIT_STATE, { id: message.id, text: message.text }); } }, cancelEdit: ({ commit }) => commit(types.UPDATE_MESSAGE_EDIT_STATE, getDefaultMessageEditState()), updateEditedText: ({ commit }, text) => { commit(types.UPDATE_MESSAGE_EDIT_STATE, { text }); }, editLastMessage: ({ dispatch, getters, rootState }) => { const lastEditableMessage = [...getters.childMessages] .reverse() .find(m => isMessageEditable(m, rootState)); if (!lastEditableMessage) return; dispatch('editMessage', lastEditableMessage); }, fetchChildMessages: ( { state, commit }, { beforeId, afterId, limit = FETCH_MESSAGES_LIMIT } = {} ) => { commit(childMessagesVuexRequest.requestType); const options = { beforeId, afterId, limit }; return apiClient.room .get(`/chatMessages/${state.parentId}/thread${composeQueryString(options)}`) .then(childMessages => { commit(childMessagesVuexRequest.successType); commit(rootTypes.ADD_TO_MESSAGE_MAP, childMessages, { root: true }); return childMessages; }) .catch(err => { log.error(err); commit(childMessagesVuexRequest.errorType, err); }); }, /* opens TMF and highlights the permalinked child message */ highlightChildMessage: ({ dispatch, commit }, { parentId, id }) => { dispatch('open', parentId).then(() => { setTemporaryMessageProp(commit, id, 'highlighted'); }); }, /* used to scroll TMF down to the newest message, or to reposition TMF during infinite scroll * `block` is scrollIntoView block argument ('start', 'end', 'center', 'nearest') * https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView */ focusOnMessage: async ({ dispatch, commit, rootState }, { id, block }) => { const message = rootState.messageMap[id]; if (!message) return; // this might be later conditional. If this is not child message, don't call open. await dispatch('open', message.parentId); commit( rootTypes.UPDATE_MESSAGE, { id, focusedAt: { block, timestamp: Date.now() } }, { root: true } ); }, fetchOlderMessages: async ({ dispatch, state, getters, commit }) => { if (state.atTop || !canStartFetchingMessages(state)) return; if (!getters.childMessages.length) return; const parentIdBeforeFetch = state.parentId; const childMessages = await dispatch('fetchChildMessages', { beforeId: getters.childMessages[0].id }); if (childMessages.length < FETCH_MESSAGES_LIMIT) commit(types.SET_AT_TOP_IF_SAME_PARENT, parentIdBeforeFetch); if (childMessages.length) { // align last message to the top (pushes the new messages just above the TMF viewport) dispatch('focusOnMessage', { id: childMessages[childMessages.length - 1].id, block: 'start' }); } }, fetchNewerMessages: async ({ dispatch, state, getters, commit }) => { if (state.atBottom || !canStartFetchingMessages(state)) return; const localChildMessages = getters.childMessages; if (!localChildMessages.length) return; const parentIdBeforeFetch = state.parentId; const childMessages = await dispatch('fetchChildMessages', { afterId: localChildMessages[localChildMessages.length - 1].id }); if (childMessages.length < FETCH_MESSAGES_LIMIT) commit(types.SET_AT_BOTTOM_IF_SAME_PARENT, parentIdBeforeFetch); if (childMessages.length) { // align last message to the bottom (pushes the new messages just below the TMF viewport) dispatch('focusOnMessage', { id: childMessages[0].id, block: 'end' }); } }, fetchInitialMessages: async ({ dispatch, state, commit }) => { const parentIdBeforeFetch = state.parentId; const childMessages = await dispatch('fetchChildMessages'); const lastMessage = childMessages[childMessages.length - 1]; if (lastMessage) dispatch('focusOnMessage', { id: lastMessage.id, block: 'end' }); commit(types.SET_AT_BOTTOM_IF_SAME_PARENT, parentIdBeforeFetch); if (childMessages.length < FETCH_MESSAGES_LIMIT) { commit(types.SET_AT_TOP_IF_SAME_PARENT, parentIdBeforeFetch); } } } };
fwcd/Sketch
src/main/java/fwcd/sketch/view/tools/EditingTool.java
<reponame>fwcd/Sketch<filename>src/main/java/fwcd/sketch/view/tools/EditingTool.java package fwcd.sketch.view.tools; import javax.swing.ImageIcon; import fwcd.sketch.view.canvas.SketchBoardView; import fwcd.fructose.geometry.Vector2D; import fwcd.sketch.model.items.SketchItem; public abstract class EditingTool<T extends SketchItem> implements SketchTool { public abstract void edit(T item); public abstract T getItem(SketchBoardView board); @SuppressWarnings("unchecked") public void tryEditing(SketchItem item) { edit((T) item); } @Override public final ImageIcon getIcon() { throw new UnsupportedOperationException("Icons are not (yet) supported by EditingTool"); } @Override public final void onMouseDoubleClick(Vector2D pos, SketchBoardView board) { throw new UnsupportedOperationException("Double click is not (yet) supported by EditingTool"); } }
forex24/ib_api_dart
TWS API/samples/DdeSocketBridge/src/main/java/com/ib/api/dde/socket2dde/datamap/MarketDataMap.java
/* Copyright (C) 2019 Interactive Brokers LLC. All rights reserved. This code is subject to the terms * and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */ package com.ib.api.dde.socket2dde.datamap; import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.ib.api.dde.dde2socket.requests.DdeRequest; /** Class represents market data map received from TWS */ public class MarketDataMap extends BaseDataMap { private Map<String, Object> m_dataMap = Collections.synchronizedMap(new HashMap<String, Object>()); // Map field->value public MarketDataMap(DdeRequest ddeRequest) { super(ddeRequest); } @Override public Object getValue(String field){ Object value = null; if(m_dataMap.containsKey(field)){ value = m_dataMap.get(field); if (value instanceof Double){ if ((Double)value == Double.MAX_VALUE) { return " "; } } if (value instanceof Integer){ if ((Integer)value == Integer.MAX_VALUE) { return " "; } } return value; } return -1; } public void setValue(String field, Object value) { m_dataMap.put(field, value); } }
Thewbi/knx_meister
core/src/main/java/core/pipeline/IpFilterPipelineStep.java
<filename>core/src/main/java/core/pipeline/IpFilterPipelineStep.java<gh_stars>0 package core.pipeline; import java.net.InetAddress; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import api.pipeline.PipelineStep; import core.packets.HPAIStructure; import core.packets.KNXPacket; import core.packets.StructureType; public class IpFilterPipelineStep implements PipelineStep<Object, Object> { private static final String BLACKLISTED_IP = "192.168.56.1"; private static final Logger LOG = LogManager.getLogger(IpFilterPipelineStep.class); @Override public Object execute(final Object dataAsObject) throws Exception { if (dataAsObject == null) { return null; } final Object[] data = (Object[]) dataAsObject; final KNXPacket knxPacket = (KNXPacket) data[1]; final HPAIStructure hpaiStructure = (HPAIStructure) knxPacket.getStructureMap() .get(StructureType.HPAI_CONTROL_ENDPOINT_UDP); if (hpaiStructure != null && hpaiStructure.getIpAddressAsObject() != null && hpaiStructure.getIpAddressAsObject().equals(InetAddress.getByName(BLACKLISTED_IP))) { LOG.warn("Ignoring packet from IP {}", BLACKLISTED_IP); return null; } return dataAsObject; } }
multipleton/spring-labs
src/main/java/com/multipleton/spring/dto/book/BookSearchDto.java
package com.multipleton.spring.dto.book; import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiParam; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; public class BookSearchDto { private String title; private String author; @ApiParam(value = "values should be separated by comma") private String tags; public BookSearchDto(String title, String author, String tags) { this.title = title; this.author = author; this.tags = tags; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getTags() { return tags; } @ApiModelProperty(hidden = true) public Set<String> getTagsSet() { if (tags == null || tags.isEmpty()) { return new HashSet<>(); } return Arrays.stream(tags.split(",")) .map(String::trim) .collect(Collectors.toSet()); } public void setTags(String tags) { this.tags = tags; } public boolean isEmpty() { return (title == null || title.isEmpty()) && (author == null || author.isEmpty()) && (tags == null || tags.isEmpty()); } }
stefanhans/programming-reactive-systems-in-go
thesis-code-snippets/3.4.1/info-gRPC/cmd/server/main.go
package main import ( "bytes" "encoding/binary" "fmt" "io/ioutil" "log" "net" "os" "github.com/golang/protobuf/proto" "github.com/stefanhans/programming-reactive-systems-in-go/thesis-code-snippets/3.4.1/info-gRPC/info" "golang.org/x/net/context" "google.golang.org/grpc" ) func main() { // Create and register server var infos infoServer srv := grpc.NewServer() info.RegisterInfosServer(srv, infos) // Create listener l, err := net.Listen("tcp", ":8888") if err != nil { log.Fatal("could not listen to :8888: \v", err) } // Serve messages via listener log.Fatal(srv.Serve(l)) } // Receiver for implementing the server service interface type infoServer struct{} // Server's Write implementation func (s infoServer) Write(ctx context.Context, info *info.Info) (*info.Info, error) { // Marshall message b, err := proto.Marshal(info) if err != nil { return nil, fmt.Errorf("could not encode info: %v", err) } // Open file f, err := os.OpenFile("storage", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666) if err != nil { return nil, fmt.Errorf("could not open storage: %v", err) } // Encode message and write to file if err := binary.Write(f, binary.LittleEndian, int64(len(b))); err != nil { return nil, fmt.Errorf("could not encode length of message: %v", err) } _, err = f.Write(b) if err != nil { return nil, fmt.Errorf("could not write info to file: %v", err) } // Close file if err := f.Close(); err != nil { return nil, fmt.Errorf("could not close file storage: %v", err) } return info, nil } // Server's Read implementation func (s infoServer) Read(ctx context.Context, void *info.Void) (*info.InfoList, error) { // Read file b, err := ioutil.ReadFile("storage") if err != nil { return nil, fmt.Errorf("could not read storage: %v", err) } // Iterate over read bytes var infos info.InfoList for { if len(b) == 0 { // Return result return &infos, nil } else if len(b) < 8 { return nil, fmt.Errorf("remaining odd %d bytes", len(b)) } // Decode message var length int64 if err := binary.Read(bytes.NewReader(b[:8]), binary.LittleEndian, &length); err != nil { return nil, fmt.Errorf("could not decode message length: %v", err) } b = b[8:] // Unmarshall message and append it var info info.Info if err := proto.Unmarshal(b[:length], &info); err != nil { return nil, fmt.Errorf("could not read info: %v", err) } b = b[length:] infos.Infos = append(infos.Infos, &info) } }
LiuTed/gym-TD
train/DQN/Model.py
<reponame>LiuTed/gym-TD<filename>train/DQN/Model.py<gh_stars>0 from os import setpgid from DQN.Memory import Memory import random import torch import numpy as np class DQN(object): def __init__(self, eps_sche, num_act, policy_network, config, target_network=None): self.memory = Memory(config.memory_size) self.eps_scheduler = eps_sche self.num_act = num_act self.policy = policy_network self.target = target_network if target_network is not None: self.target.load_state_dict(self.policy.state_dict()) self.target.train(False) self.optimizer = torch.optim.Adam( self.policy.parameters(), lr=config.learning_rate, weight_decay=0.001, amsgrad=True ) self.config = config self.step = 0 def get_action(self, state, training=True): r = random.random() if r < self.eps_scheduler.eps and training: return torch.tensor(np.random.randint(0, self.num_act, [1, ])) else: with torch.no_grad(): return self.policy(state.to(self.config.device)).max(1)[1].to('cpu') def push(self, val): ''' val should be [state, action, next_state, reward] map: [1, channels, height, width] action: [1,] net_output: [1, 4] rewards: 1 ''' self.memory.push(val) def learn(self): if(len(self.memory) < self.config.batch_size): return batch = self.memory.sample(self.config.batch_size) states = torch.cat([v[0] for v in batch], 0).to(device=self.config.device) next_states = torch.cat([v[2] for v in batch if v[2] is not None], 0).to(device=Param.device) if next_states.shape[0] == 0: print('!') return actions = torch.cat([v[1] for v in batch], 0).to(device=self.config.device) actions.unsqueeze_(1) # [?, 1] # if_nonterm_mask = [] # for i, v in enumerate(batch): # if v[2] is not None: # if_nonterm_mask.append(i) # if_nonterm_mask = torch.tensor(if_nonterm_mask, dtype=torch.long, device=Param.device) if_nonterm_mask = [[v[2] is not None] for v in batch] # [?, 1] if_nonterm_mask = torch.tensor(if_nonterm_mask, dtype=torch.bool, device=self.config.device) rewards = torch.tensor([[v[3]] for v in batch], dtype=torch.float32, device=self.config.device) # [?, 1] next_action_values = torch.zeros_like(rewards).to(self.config.device) if self.target is not None: result = self.target(next_states) else: result = self.policy(next_states) # next_action_values.index_copy_(0, if_nonterm_mask, result.max(2)[0]) # [?, 3] next_action_values[if_nonterm_mask] = result.max(1)[0] y = rewards + next_action_values * self.config.gamma y = y.detach() # [?, 1] self.optimizer.zero_grad() Q_sa = self.policy(states).gather(1, actions) # [?, 1] # Q_sa.squeeze_(2) loss = torch.nn.functional.mse_loss(Q_sa, y) loss.backward() self.optimizer.step() self.step += 1 if(self.target is not None and self.step % self.config.update_interval == 0): self.target.load_state_dict(self.policy.state_dict()) self.eps_scheduler.update() return loss, self.step def save(self, ckpt): torch.save(self.policy.state_dict(), ckpt+'/policy.pkl') save_dict = { 'step': self.step, 'eps_step': self.eps_scheduler.step } torch.save(save_dict, ckpt+'/model.pkl') def restore(self, ckpt): self.policy.load_state_dict(torch.load(ckpt+'/policy.pkl')) save_dict = torch.load(ckpt+'/model.pkl') self.step = save_dict['step'] self.eps_scheduler.step = save_dict['eps_step']
dromelvan/dromelvan
app/models/concerns/d11_team_squad_stat.rb
<reponame>dromelvan/dromelvan module D11TeamSquadStat extend ActiveSupport::Concern include PlayerStatsSummary included do belongs_to :d11_team, touch: true after_initialize :init before_validation :update_team_goals validates :d11_team, presence: true validates :team_goals, numericality: { greater_than_or_equal_to: 0 } def reset reset_stats_summary self.team_goals = 0 end private def init self.team_goals ||= 0 end def update_team_goals self.points ||= 0 if self.points > 0 then self.team_goals = (points / 5) + 1 else self.team_goals = 0 end end end end
benthie/wearables-praktikum
docs/search/properties_12.js
<reponame>benthie/wearables-praktikum<filename>docs/search/properties_12.js var searchData= [ ['xmlfile',['xmlFile',['../interface_preferences_window_controller.html#acc2c06ee9d9a1845b2e691ccc12b2e39',1,'PreferencesWindowController::xmlFile()'],['../interface_settings.html#a6726d1a3f9ffee94b858107937a9d356',1,'Settings::xmlFile()']]] ];
mbasnap/ps-server
routes/admin/report/index.js
<gh_stars>0 const express = require('express') const router = express.Router() const dirLevel = '/:p1?/:p2?/:p3?' const company = async (req, res, next) => { try { req.company = await req.db.get('company') next() } catch(e) { res.status(401).json(e) } } router.get('/', company, (req, res) => { res.json([ { key: 'report/balance', text: 'Баланс' }, { key: 'month', text: 'Месячный', children: [ { text: 'Касса ломбарда', key: 'report/month/kassa' }, { text: 'Ведомость остатков', key: 'report/month/ostatki' }, { text: '0203 Задолжность по кредитам', key: 'report/month/penalty' } ] }, { key: 'quarter', text: 'Квартальный', children: [ { text: '0201 Отчёт о деятельности', key: 'report/quarter/main' }, { text: '0202. Финансовый результат', key: 'report/quarter/fin-results' } ] } ]) }) router.get(dirLevel, (req, res) => { const path = Object.values(req.params).filter((v) => v).join('/') return require(`./${path}`).get(req, res) }) router.post(dirLevel, (req, res) => { const path = Object.values(req.params).filter((v) => v).join('/') return require(`./${path}`).post(req, res) }) router.delete(dirLevel, (req, res) => { const path = Object.values(req.params).filter((v) => v).join('/') return require(`./${path}`).remove(req, res) }) module.exports = router
Serik0/Partner-Center-Java
src/main/java/com/microsoft/store/partnercenter/models/products/BillingCycleType.java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See the LICENSE file in the project root for full license information. package com.microsoft.store.partnercenter.models.products; import com.fasterxml.jackson.annotation.JsonValue; /** * Types of Participants */ public enum BillingCycleType { /** * Default value if not known */ UNKNOWN("unknown"), /** * Indicates that the partner will be charged monthly. */ MONTHLY("monthly"), /** * Indicates that the partner will be charged annual. */ ANNUAL("annual"), /** * Indicates that the partner will not be charged. This value is used for trial offers. */ NONE("none"), /** * Indicates that the partner will be charged one time. This value is used for modern product SKUs. */ ONE_TIME("one_time"); private final String value; BillingCycleType(String value) { this.value = value; } /** * Converts the object to a string. * * @return A string that represents this object. */ @JsonValue @Override public String toString() { return value; } }
ipattarapong/dbnd
modules/dbnd-airflow/src/dbnd_airflow/airflow_override/dbnd_airflow_windows/getuser.py
<reponame>ipattarapong/dbnd import os def _default_getuser(): return "unknown" def find_runnable_getuser_function(): try: if hasattr(os, "getlogin"): os.getlogin() return os.getlogin # check before we return it import getpass if not hasattr(getpass, "getuser"): return _default_getuser() getpass.getuser() # check before we return it return getpass.getuser except Exception: return _default_getuser
rohanbharadwaj/sbrocks
w2/sys/process/process_manager.c
#include <sys/process/process_manager.h> extern void irq0(); struct task_struct* current_task = NULL; void start_process(struct task_struct* task, uint64_t ustack, uint64_t binary_entry); void save_registers(struct task_struct *p, struct task_struct *task); //void start_process(struct task_struct* task); /* web reference: http://www.jamesmolloy.co.uk/tutorial_html/10.-User%20Mode.html */ static struct task_struct* idle_task = NULL; static void idle_process(){ while(1); } void init_idle_process(){ idle_task = create_new_task("idle"); idle_task->state = TASK_IDLE; idle_task->e_entry = (uint64_t)idle_process; schedule_process(); } struct task_struct* get_current_task() { return current_task; } void set_current_task(struct task_struct* task) { current_task = task; } void load_process(struct task_struct* task, uint64_t binary_entry, uint64_t ustack) { current_task = task; task->state = TASK_RUNNING; /* setting up kernel stack for user process */ //task->rip = binary_entry; /*web reference: http://wiki.osdev.org/Getting_to_Ring_3*/ //task->rsp = (uint64_t)&task->kstack[KSTACK_SIZE-6]; //rsp //task->rsp = (uint64_t)&task->kstack[KSTACK_SIZE-6]; //if(task->ppid == -1) //no child process //{ // task->rsp = ustack; //rsp // task->rip = binary_entry; //} start_process(task, ustack, binary_entry); //kprintf("yeye process is loaded successfully \n"); } void schedule_process() { //TODO in case there is no task to run schedule kernel //if there is any new non kernel task scheduled and if current task is kernel remove kernel to IDLE state and // schedule new task kprintf("scheduling process stared.........\n"); struct task_struct *task = NULL; if(current_task == NULL) { task = get_next_task(current_task); if(task == NULL) return; else { //schedule new task //task->rsp = task->mm->stack_vm; //rsp //task->rip = task->e_entry; current_task = task; current_task->state = TASK_RUNNING; start_process(task, task->mm->stack_vm, task->e_entry); //load_process(task, task->e_entry, task->mm->stack_vm); } } else { //task switching is required task = get_next_task(current_task); if(task == NULL) return; else { //switch new task and save previous task state //__asm__ __volatile__("movq %%rsp, %[next_rsp]" :[next_rsp] "=m" (current_task->rsp): ); //current_task->rsp = current_task->kstack[KSTACK_SIZE-3]; //current_task->rip = current_task->kstack[KSTACK_SIZE-6]; //save_registers(current_task, task); current_task->state = TASK_RUNNABLE; kprintf("schedule called...%d \n", current_task->pid); current_task = task; current_task->state = TASK_RUNNING; start_process(task, task->mm->stack_vm, task->e_entry); //load_process(task, task->e_entry, task->mm->stack_vm); } } } void save_registers(struct task_struct *p, struct task_struct *task) { int i = 1; while(p->kstack[KSTACK_SIZE - i] == 0) i++; //p->rsp = p->kstack[KSTACK_SIZE - i - 1]; //p->rip = p->kstack[KSTACK_SIZE - i - 4]; /*if(task->ppid == current_task->pid) { task->rsp = p->rsp; task->rip = p->rip; }*/ } void start_process(struct task_struct* task, uint64_t ustack, uint64_t binary_entry) { //kprintf2("Running process %s \n",task->name); //1. load cr3 write_cr3(virt_to_phy(task->pml4e,0)); //task->r.rsp = ustack; //task->r.rip = task->e_entry; //task->r.rsp = ustack; //task->r.rip = task->e_entry; task->r.ss = 0x23; task->r.cs = 0x1b; task->r.rflag = 0x200; //2. swtich process stack to process stack //TODO change to assemblyutil function //write_rsp(task->rsp); //__asm__ __volatile__("sti" : :); //__asm__ __volatile__("movq %[next_rsp], %%rsp" : : [next_rsp] "m" (task->rsp)); //TODO //task->kstack[KSTACK_SIZE-21] = (uint64_t)irq0 + 0x20; //uint64_t rsp = (uint64_t)&task->kstack[KSTACK_SIZE-22]; //__asm__ __volatile__("movq %[next_rsp], %%rsp" : : [next_rsp] "m" (rsp)); //3. set rsp //set_tss_rsp0(task->rsp); //use set_tss_rsp0((uint64_t)&task->kstack[KSTACK_SIZE-1]); //set_tss_rsp0((uint64_t)&task->kstack); //"int $0x80;" //__asm__ __volatile__("int $0x20;" : :); //switch to ring 3 or user mode //switch_to_usermode(task->rsp, task->rip, task); }
shachindrasingh/apiman
gateway/engine/policies/src/test/java/io/apiman/gateway/engine/policies/util/LdapTestMixin.java
package io.apiman.gateway.engine.policies.util; import io.apiman.gateway.engine.beans.ApiRequest; import io.apiman.gateway.engine.beans.PolicyFailure; import io.apiman.gateway.engine.beans.PolicyFailureType; import io.apiman.gateway.engine.components.ILdapComponent; import io.apiman.gateway.engine.components.IPolicyFailureFactoryComponent; import io.apiman.gateway.engine.policies.AuthorizationPolicy; import io.apiman.gateway.engine.policies.BasicAuthLDAPTest; import io.apiman.gateway.engine.policies.BasicAuthenticationPolicy; import io.apiman.gateway.engine.policies.config.BasicAuthenticationConfig; import io.apiman.gateway.engine.policy.IPolicyChain; import io.apiman.gateway.engine.policy.IPolicyContext; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.util.Set; import javax.naming.NamingException; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.directory.api.ldap.model.entry.DefaultEntry; import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.exception.LdapException; import org.apache.directory.api.ldap.model.ldif.LdifEntry; import org.apache.directory.api.ldap.model.ldif.LdifReader; import org.apache.directory.api.ldap.model.name.Dn; import org.apache.directory.api.ldap.model.schema.SchemaManager; import org.apache.directory.api.ldap.schema.manager.impl.DefaultSchemaManager; import org.apache.directory.server.core.api.DirectoryService; import org.apache.directory.server.core.api.DnFactory; import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmPartition; import org.apache.directory.server.core.shared.DefaultDnFactory; import org.apache.directory.server.i18n.I18n; import org.junit.Assert; import org.mockito.Mockito; /** * Some common initialisation code for LDAP testing that can be mixed in without requiring inheritance * * @author <NAME> @{literal<<EMAIL>>} */ public interface LdapTestMixin { /** * Initialise the LDAP server with basic test setup. */ default JdbmPartition initLdapTestSetup( String partitionName, File targetDir, CacheManager ehCacheManager, DirectoryService service ) throws IOException, LdapException { JdbmPartition partition; if (!targetDir.isDirectory()) { throw new UncheckedIOException( new IOException("Couldn't find maven target directory: " + targetDir)); } File partitionDir = new File(targetDir, partitionName); if (partitionDir.exists()) { FileUtils.deleteDirectory(partitionDir); } partitionDir.mkdirs(); // Requires EHCache! String ehCacheName = "apiman-" + partitionName + "-ehcache-testing"; ehCacheManager.addCache(ehCacheName); Cache cache = ehCacheManager.getCache(ehCacheName); final SchemaManager schemaManager = new DefaultSchemaManager(); final DnFactory defaultDnFactory = new DefaultDnFactory(schemaManager, cache); partition = new JdbmPartition(schemaManager, defaultDnFactory); partition.setId("apiman"); partition.setPartitionPath(partitionDir.toURI()); partition.setSchemaManager(service.getSchemaManager()); partition.setSuffixDn(new Dn("o=apiman")); service.addPartition(partition); // Inject the foo root entry if it does not already exist try { service.getAdminSession().lookup(partition.getSuffixDn()); } catch (Exception lnnfe) { Dn dn = new Dn("o=apiman"); Entry entry = service.newEntry(dn); entry.add("objectClass", "top", "domain", "extensibleObject"); entry.add("dc", "apiman"); entry.add("cn", "o=apiman"); service.getAdminSession().add(entry); } return partition; } default void injectLdifFiles(DirectoryService service, String... ldifFiles) throws Exception { if (ldifFiles != null && ldifFiles.length > 0) { for (String ldifFile : ldifFiles) { InputStream is = null; try { is = BasicAuthLDAPTest.class.getClassLoader().getResourceAsStream(ldifFile); if (is == null) { throw new FileNotFoundException("LDIF file '" + ldifFile + "' not found."); } else { try { LdifReader ldifReader = new LdifReader(is); for (LdifEntry entry : ldifReader) { injectEntry(entry, service); } ldifReader.close(); } catch (Exception e) { throw new RuntimeException(e); } } } finally { IOUtils.closeQuietly(is); } } } } default void injectEntry(LdifEntry entry, DirectoryService service) throws Exception { if (entry.isChangeAdd()) { service.getAdminSession().add( new DefaultEntry(service.getSchemaManager(), entry.getEntry())); } else if (entry.isChangeModify()) { service.getAdminSession().modify(entry.getDn(), entry.getModifications()); } else { String message = I18n.err(I18n.ERR_117, entry.getChangeType()); throw new NamingException(message); } } /** * Creates the http Authorization string for the given credentials. * * @param username * @param password */ default String createBasicAuthorization(String username, String password) { String creds = username + ":" + password; StringBuilder builder = new StringBuilder(); builder.append("Basic "); builder.append(Base64.encodeBase64String(creds.getBytes())); return builder.toString(); } default void doTest(String json, String username, String password, Integer expectedFailureCode, ILdapComponent ldapComponentUnderTest) throws Exception { doTest(json, username, password, expectedFailureCode, null, ldapComponentUnderTest); } // pass null if you expect success default void doTest(String json, String username, String password, Integer expectedFailureCode, Set<String> expectedRoles, ILdapComponent ldapComponentUnderTest ) { BasicAuthenticationPolicy policy = new BasicAuthenticationPolicy(); BasicAuthenticationConfig config = policy.parseConfiguration(json); ApiRequest request = new ApiRequest(); request.setType("GET"); request.setApiKey("12345"); request.setRemoteAddr("1.2.3.4"); request.setDestination("/"); IPolicyContext context = Mockito.mock(IPolicyContext.class); final PolicyFailure failure = new PolicyFailure(); Mockito.when(context.getComponent(IPolicyFailureFactoryComponent.class)) .thenReturn((PolicyFailureType type, int failureCode, String message) -> { failure.setType(type); failure.setFailureCode(failureCode); failure.setMessage(message); return failure; }); // The LDAP stuff we're testing! Mockito.when(context.getComponent(ILdapComponent.class)).thenReturn(ldapComponentUnderTest); IPolicyChain<ApiRequest> chain = Mockito.mock(IPolicyChain.class); if (username != null) { request.getHeaders().put("Authorization", createBasicAuthorization(username, password)); } if (expectedFailureCode == null) { policy.apply(request, context, config, chain); Mockito.verify(chain).doApply(request); } else { policy.apply(request, context, config, chain); Mockito.verify(chain).doFailure(failure); Assert.assertEquals(expectedFailureCode.intValue(), failure.getFailureCode()); } if (expectedRoles != null && expectedFailureCode == null) { Mockito.verify(context).setAttribute(AuthorizationPolicy.AUTHENTICATED_USER_ROLES, expectedRoles); } } }
lionelgo/openair-mme
src/s6a/s6a_notify.c
<reponame>lionelgo/openair-mme<filename>src/s6a/s6a_notify.c /* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the terms found in the LICENSE file in the root of this source tree. * * 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 more information about the OpenAirInterface (OAI) Software Alliance: * <EMAIL> */ #include <stdint.h> #include <stdio.h> #include "bstrlib.h" #include "dynamic_memory_check.h" #include "log.h" #include "mme_config.h" #include "msc.h" #include "assertions.h" #include "conversions.h" #include "common_defs.h" #include "common_types.h" #include "intertask_interface.h" #include "msc.h" #include "s6a_defs.h" #include "s6a_messages.h" int s6a_na_cb(struct msg **msg, struct avp *paramavp, struct session *sess, void *opaque, enum disp_action *act) { struct msg *ans = NULL; struct msg *qry = NULL; struct avp *avp = NULL; struct avp_hdr *hdr = NULL; MessageDef *message_p = NULL; s6a_notify_ans_t *s6a_notify_ans_p = NULL; DevAssert(msg); ans = *msg; /* * Retrieve the original query associated with the asnwer */ CHECK_FCT(fd_msg_answ_getq(ans, &qry)); DevAssert(qry); message_p = itti_alloc_new_message(TASK_S6A, S6A_NOTIFY_ANS); s6a_notify_ans_p = &message_p->ittiMsg.s6a_notify_ans; OAILOG_DEBUG(LOG_S6A, "Received S6A Notify Answer (NA)\n"); // CHECK_FCT (fd_msg_search_avp (qry, s6a_fd_cnf.dataobj_s6a_user_name, // &avp)); // // if (avp) { // CHECK_FCT (fd_msg_avp_hdr (avp, &hdr)); // snprintf (s6a_auth_info_ans_p->imsi, (int)hdr->avp_value->os.len + 1, // "%*s", (int)hdr->avp_value->os.len, hdr->avp_value->os.data); // } else { // DevMessage ("Query has been freed before we received the answer\n"); // } /* * Retrieve the result-code */ CHECK_FCT(fd_msg_search_avp(ans, s6a_fd_cnf.dataobj_s6a_result_code, &avp)); if (avp) { CHECK_FCT(fd_msg_avp_hdr(avp, &hdr)); s6a_notify_ans_p->result.present = S6A_RESULT_BASE; s6a_notify_ans_p->result.choice.base = hdr->avp_value->u32; MSC_LOG_TX_MESSAGE(MSC_S6A_MME, MSC_NAS_MME, NULL, 0, "0 S6A_NOTIFY_ANS %s", retcode_2_string(s6a_notif_ans_p->result.choice.base)); if (hdr->avp_value->u32 != ER_DIAMETER_SUCCESS) { OAILOG_ERROR(LOG_S6A, "Got error %u:%s\n", hdr->avp_value->u32, retcode_2_string(hdr->avp_value->u32)); } else { OAILOG_DEBUG(LOG_S6A, "Received S6A Result code %u:%s\n", s6a_notify_ans_p->result.choice.base, retcode_2_string(s6a_notify_ans_p->result.choice.base)); } } else { /* * The result-code is not present, may be it is an experimental result * * * * avp indicating a 3GPP specific failure. */ CHECK_FCT(fd_msg_search_avp(ans, s6a_fd_cnf.dataobj_s6a_experimental_result, &avp)); if (avp) { /* * The procedure has failed within the HSS. * * * * NOTE: contrary to result-code, the experimental-result is a * grouped * * * * AVP and requires parsing its childs to get the code back. */ s6a_notify_ans_p->result.present = S6A_RESULT_EXPERIMENTAL; s6a_parse_experimental_result( avp, &s6a_notify_ans_p->result.choice.experimental); MSC_LOG_TX_MESSAGE(MSC_S6A_MME, MSC_NAS_MME, NULL, 0, "0 S6A_NOTIFY_ANS %s", s6a_notify_ans_p->imsi, experimental_retcode_2_string( s6a_notify_ans_p->result.choice.experimental)); } else { /* * Neither result-code nor experimental-result is present -> * * * * totally incorrect behaviour here. */ MSC_LOG_TX_MESSAGE_FAILED(MSC_S6A_MME, MSC_NAS_MME, NULL, 0, "0 S6A_NOTIFY_ANS", s6a_notify_ans_p->imsi); OAILOG_ERROR(LOG_S6A, "Experimental-Result and Result-Code are absent: " "This is not a correct behaviour\n"); goto err; } } OAILOG_INFO(LOG_S6A, "Successfully parsed Notify Answer from HSS. \n"); fd_msg_free(*msg); *msg = NULL; err: return RETURNok; } int s6a_generate_notify_req(s6a_notify_req_t *nr_p) { struct avp *avp; struct msg *msg; struct session *sess; union avp_value value; DevAssert(nr_p); /* * Create the new notify request */ CHECK_FCT(fd_msg_new(s6a_fd_cnf.dataobj_s6a_nr, 0, &msg)); /* * Create a new session */ CHECK_FCT(fd_sess_new(&sess, fd_g_config->cnf_diamid, fd_g_config->cnf_diamid_len, (os0_t) "apps6a", 6)); { os0_t sid; size_t sidlen; CHECK_FCT(fd_sess_getsid(sess, &sid, &sidlen)); CHECK_FCT(fd_msg_avp_new(s6a_fd_cnf.dataobj_s6a_session_id, 0, &avp)); value.os.data = sid; value.os.len = sidlen; CHECK_FCT(fd_msg_avp_setvalue(avp, &value)); CHECK_FCT(fd_msg_avp_add(msg, MSG_BRW_FIRST_CHILD, avp)); } CHECK_FCT(fd_msg_avp_new(s6a_fd_cnf.dataobj_s6a_auth_session_state, 0, &avp)); /* * No State maintained */ value.i32 = 1; CHECK_FCT(fd_msg_avp_setvalue(avp, &value)); CHECK_FCT(fd_msg_avp_add(msg, MSG_BRW_LAST_CHILD, avp)); /* * Add Origin_Host & Origin_Realm */ CHECK_FCT(fd_msg_add_origin(msg, 0)); mme_config_read_lock(&mme_config); /* * Destination Host */ { bstring host = bstrcpy(mme_config.s6a_config.hss_host_name); bconchar(host, '.'); bconcat(host, mme_config.realm); CHECK_FCT(fd_msg_avp_new(s6a_fd_cnf.dataobj_s6a_destination_host, 0, &avp)); value.os.data = (unsigned char *)bdata(host); value.os.len = blength(host); CHECK_FCT(fd_msg_avp_setvalue(avp, &value)); CHECK_FCT(fd_msg_avp_add(msg, MSG_BRW_LAST_CHILD, avp)); bdestroy_wrapper(&host); } /* * Destination_Realm */ { CHECK_FCT( fd_msg_avp_new(s6a_fd_cnf.dataobj_s6a_destination_realm, 0, &avp)); value.os.data = (unsigned char *)bdata(mme_config.realm); value.os.len = blength(mme_config.realm); CHECK_FCT(fd_msg_avp_setvalue(avp, &value)); CHECK_FCT(fd_msg_avp_add(msg, MSG_BRW_LAST_CHILD, avp)); } mme_config_unlock(&mme_config); /* * Adding the User-Name (IMSI) */ CHECK_FCT(fd_msg_avp_new(s6a_fd_cnf.dataobj_s6a_user_name, 0, &avp)); value.os.data = (unsigned char *)nr_p->imsi; value.os.len = strlen(nr_p->imsi); CHECK_FCT(fd_msg_avp_setvalue(avp, &value)); CHECK_FCT(fd_msg_avp_add(msg, MSG_BRW_LAST_CHILD, avp)); /* * Adding the visited plmn id */ { uint8_t plmn[3] = {0x00, 0x00, 0x00}; //{ 0x02, 0xF8, 0x29 }; plmn_t plmn_mme; plmn_mme = mme_config.gummei.gummei[0].plmn; CHECK_FCT(fd_msg_avp_new(s6a_fd_cnf.dataobj_s6a_visited_plmn_id, 0, &avp)); PLMN_T_TO_TBCD( plmn_mme, plmn, mme_config_find_mnc_length( nr_p->visited_plmn.mcc_digit1, nr_p->visited_plmn.mcc_digit2, nr_p->visited_plmn.mcc_digit3, nr_p->visited_plmn.mnc_digit1, nr_p->visited_plmn.mnc_digit2, nr_p->visited_plmn.mnc_digit3)); value.os.data = plmn; value.os.len = 3; CHECK_FCT(fd_msg_avp_setvalue(avp, &value)); CHECK_FCT(fd_msg_avp_add(msg, MSG_BRW_LAST_CHILD, avp)); OAILOG_DEBUG(LOG_S6A, "%s NR- new plmn: %02X%02X%02X\n", __FUNCTION__, plmn[0], plmn[1], plmn[2]); OAILOG_DEBUG(LOG_S6A, "%s NR- new visited_plmn: %02X%02X%02X\n", __FUNCTION__, value.os.data[0], value.os.data[1], value.os.data[2]); } /* * NOR Flags */ CHECK_FCT(fd_msg_avp_new(s6a_fd_cnf.dataobj_s6a_nr_flags, 0, &avp)); value.u32 = 0; /* * Set the nr-flags as indicated by upper layer */ if (nr_p->single_registration_indiction) { FLAGS_SET(value.u32, NR_SINGLE_REGISTRATION_IND); } CHECK_FCT(fd_msg_avp_setvalue(avp, &value)); CHECK_FCT(fd_msg_avp_add(msg, MSG_BRW_LAST_CHILD, avp)); CHECK_FCT(fd_msg_send(&msg, NULL, NULL)); return RETURNok; }
Kair0z/StikBoldt-PC
OverlordEngine/GeneralStructs.h
#pragma once #include "GameTime.h" #include "CameraComponent.h" #include "InputManager.h" #include "MaterialManager.h" #include "ShadowMapRenderer.h" class CameraComponent; struct GameSettings { GameSettings(): Window(WindowSettings()), DirectX(DirectXSettings()) {} #pragma region struct WindowSettings { WindowSettings(): Width(1280), Height(720), AspectRatio(Width/static_cast<float>(Height)), Title(L"Overlord Engine (DX11)"), WindowHandle(nullptr) { } int Width; int Height; float AspectRatio; std::wstring Title; HWND WindowHandle; }Window; #pragma endregion WINDOW_SETTINGS #pragma region struct DirectXSettings { DirectXSettings() : pAdapter(nullptr), pOutput(nullptr) {} IDXGIAdapter* pAdapter; IDXGIOutput* pOutput; }DirectX; #pragma endregion DIRECTX_SETTINGS }; class PhysxProxy; struct GameContext { GameTime* pGameTime; CameraComponent* pCamera; ID3D11Device* pDevice; ID3D11DeviceContext* pDeviceContext; InputManager* pInput; MaterialManager* pMaterialManager; PhysxProxy* pPhysxProxy; ShadowMapRenderer* pShadowMapper; };
hackoregon/website
src/components/Post.js
<reponame>hackoregon/website /* eslint-disable react/prop-types */ /** @jsx jsx */ import { jsx, css } from "@emotion/core"; import { documentToReactComponents } from "@contentful/rich-text-react-renderer"; import { Link } from "gatsby"; import { Location } from "@reach/router"; import { xsBreak } from "../_Theme/UpdatedBrandTheme"; import GridSingle from "./GridSingle"; import options from "../_Common/contentfulOptions"; const Post = ({ title, authors, content, featured, slug, updated, created, buttonText, buttonLocalLink, buttonExternalLink }) => ( <GridSingle containerStyle={css` padding: 0 40px; ${xsBreak} { padding: 0 20px; } `} > {featured && ( <div css={css` width: 100%; display: flex; `} > <h3>Featured Post</h3> </div> )} <h2> <Location> {({ location }) => { if (location.pathname === `/posts/${slug}`) { return title; } return <Link to={`/posts/${slug}`}>{title}</Link>; }} </Location> </h2> {authors.map(author => ( <p className="data-sm" css={css` margin-top: -1.5rem; `} > Posted {created} {updated && updated !== created && `, updated ${updated}`} by{" "} <a href={`mailto:${author.email}`}>{author.name}</a> </p> ))} <div>{documentToReactComponents(content.json, options)}</div> {/* Temporary condition to handle contentful update (removing buttonLocalLink when this is merged) */} {buttonLocalLink && !buttonExternalLink && ( <Link to={buttonLocalLink} className="btn-yellow" css={css` margin-top: 1.5rem; `} > <p>{buttonText}</p> </Link> )} {buttonExternalLink && ( <a href={buttonExternalLink} className="btn-yellow" css={css` margin-top: 1.5rem; `} target="_blank" rel="noopener noreferrer" > <p>{buttonText}</p> </a> )} </GridSingle> ); export default Post;
hawkwang/BeyondMDM
SymmetricDS/symmetric-client-clib/src/model/TriggerHistory.c
<reponame>hawkwang/BeyondMDM<filename>SymmetricDS/symmetric-client-clib/src/model/TriggerHistory.c<gh_stars>0 /** * Licensed to JumpMind Inc under one or more contributor * license agreements. See the NOTICE file distributed * with this work for additional information regarding * copyright ownership. JumpMind Inc licenses this file * to you under the GNU General Public License, version 3.0 (GPLv3) * (the "License"); you may not use this file except in compliance * with the License. * * You should have received a copy of the GNU General Public License, * version 3.0 (GPLv3) along with this library; if not, see * <http://www.gnu.org/licenses/>. * * 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 "model/TriggerHistory.h" SymStringArray * SymTiggerHistory_getParsedColumnNames(SymTriggerHistory *this) { return SymStringArray_split(this->columnNames, ","); } SymStringArray * SymTiggerHistory_getParsedPkColumnNames(SymTriggerHistory *this) { return SymStringArray_split(this->pkColumnNames, ","); } SymList * SymTiggerHistory_getParsedColumns(SymTriggerHistory *this) { SymList *columns = SymList_new(NULL); SymStringArray *columnNames = this->getParsedColumnNames(this); SymStringArray *pkNames = this->getParsedPkColumnNames(this); int i; unsigned short isPrimaryKey; for (i = 0; i < columnNames->size; i++) { char *columnName = columnNames->get(columnNames, i); isPrimaryKey = pkNames->contains(pkNames, columnName); columns->add(columns, SymColumn_new(NULL, columnName, isPrimaryKey)); } columnNames->destroy(columnNames); pkNames->destroy(pkNames); return columns; } char * SymTriggerHistory_getTriggerNameForDmlType(SymTriggerHistory *this, SymDataEventType type) { switch (type) { case SYM_DATA_EVENT_INSERT: return this->nameForInsertTrigger; case SYM_DATA_EVENT_UPDATE: return this->nameForUpdateTrigger; case SYM_DATA_EVENT_DELETE: return this->nameForDeleteTrigger; default: break; } SymLog_error("Unknown SymDataEventType %d", type); return NULL; } void SymTriggerHistory_destroy(SymTriggerHistory *this) { if (this->nameForInsertTrigger) { free(this->nameForInsertTrigger); } if (this->nameForUpdateTrigger) { free(this->nameForUpdateTrigger); } if (this->nameForDeleteTrigger) { free(this->nameForDeleteTrigger); } if (this->columnNames) { free(this->columnNames); this->columnNames = NULL; } if (this->pkColumnNames) { free(this->pkColumnNames); this->pkColumnNames = NULL; } if (this->createTime) { this->createTime->destroy(this->createTime); } if (this->inactiveTime) { this->inactiveTime->destroy(this->inactiveTime); } free(this); } SymTriggerHistory * SymTriggerHistory_new(SymTriggerHistory *this) { if (this == NULL) { this = (SymTriggerHistory *) calloc(1, sizeof(SymTriggerHistory)); } this->getParsedColumns = (void *) SymTiggerHistory_getParsedColumns; this->getParsedColumnNames = (void *) SymTiggerHistory_getParsedColumnNames; this->getParsedPkColumnNames = (void *) SymTiggerHistory_getParsedPkColumnNames; this->getTriggerNameForDmlType = SymTriggerHistory_getTriggerNameForDmlType; this->destroy = (void *) &SymTriggerHistory_destroy; return this; } SymTriggerHistory * SymTriggerHistory_newWithId(SymTriggerHistory *this, int triggerHistoryId) { this = SymTriggerHistory_new(this); this->triggerHistoryId = triggerHistoryId; return this; }
ogerardin/back2back
updater/src/main/java/Updater.java
<gh_stars>1-10 import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.ogerardin.update.UpdatePerformer; import org.ogerardin.update.action.ReplaceFileAction; import org.ogerardin.update.action.StartServiceAction; import org.ogerardin.update.action.StopServiceAction; import org.ogerardin.update.UpdateContext; @Slf4j @Data public class Updater { public static void main(String[] args) { UpdateContext context = new UpdateContext(args); UpdatePerformer updatePerformer = UpdatePerformer.builder() .context(context) .step(new StopServiceAction("back2back")) .step(new ReplaceFileAction("back2back-bundle-standalone.jar")) .step(new StartServiceAction("back2back")) .build(); updatePerformer.run(); } }
lauram15a/Programacion
Laboratorio/NetBeansProjects/sols/LabSesion7_Sol/LabSesion7_Sol/src/ejemplos_labsesion6/Fechas.java
<filename>Laboratorio/NetBeansProjects/sols/LabSesion7_Sol/LabSesion7_Sol/src/ejemplos_labsesion6/Fechas.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 ejemplos_labsesion6; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; /** * * @author Salva */ public class Fechas extends javax.swing.JFrame { /** * Creates new form Fechas */ public Fechas() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jFormattedTextField1 = new javax.swing.JFormattedTextField(); jButton1 = new javax.swing.JButton(); jTextField1 = new javax.swing.JTextField(); jSpinner1 = new javax.swing.JSpinner(); jLabel2 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Fechas"); jLabel1.setText("Fecha1:"); try { jFormattedTextField1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } jButton1.setText("Procesar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jSpinner1.setModel(new javax.swing.SpinnerDateModel()); jLabel2.setText("Fecha2:"); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel3.setText("TRATAMIENTO DE FECHAS"); jLabel4.setText("Fecha1:"); jLabel5.setText("Fecha2:"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(148, 148, 148) .addComponent(jButton1)) .addGroup(layout.createSequentialGroup() .addGap(69, 69, 69) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jFormattedTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE) .addComponent(jSpinner1)))) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel4) .addComponent(jLabel5)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE) .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.TRAILING)))) .addContainerGap(55, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel3) .addGap(66, 66, 66)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(jLabel3) .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(16, 16, 16) .addComponent(jButton1) .addGap(37, 37, 37) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addContainerGap(41, Short.MAX_VALUE)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents public static boolean esBisiesto(int y) { return (y % 4 == 0) && ((y % 100 != 0) || (y % 400 == 0)); } public static boolean buenaFecha(int d, int m, int a) { int[] diasMes = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (esBisiesto(a)) { diasMes[1] = 29; //Febrero es el segundo mes (índice 1) } return (a > 0 && a < 3000 && m >= 1 && m <= 12 && d >= 1 && d <= diasMes[m - 1]); } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // Tratamiento fecha jFormattedTextField String fecha1txt = (String) jFormattedTextField1.getValue(); String[] partes = fecha1txt.split("/"); int d1 = Integer.parseInt(partes[0]); int m1 = Integer.parseInt(partes[1]); int a1 = Integer.parseInt(partes[2]); if (!buenaFecha(d1, m1, a1)) { fecha1txt = "Fecha incorrecta"; } jTextField1.setText(fecha1txt); // Tratamiento fecha jSpinner // De Date a LocalTime Date fecha2 = (Date) jSpinner1.getValue(); Instant instant = Instant.ofEpochMilli(fecha2.getTime()); LocalDate localDate = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate(); DateTimeFormatter formatoCorto = DateTimeFormatter.ofPattern("dd/MM/yyyy"); jTextField2.setText(localDate.format(formatoCorto)); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Fechas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Fechas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Fechas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Fechas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Fechas().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JFormattedTextField jFormattedTextField1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JSpinner jSpinner1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; // End of variables declaration//GEN-END:variables }
kkcookies99/UAST
Dataset/Leetcode/train/3/128.java
<filename>Dataset/Leetcode/train/3/128.java class Solution { public int XXX(String s) { if(s==null||s.length()==0) return 0; int begin=0,end=0,max=0; HashSet<Character> set=new HashSet(); while(end<s.length()){ if(!set.add(s.charAt(end))){ max=Math.max(max,end-begin); begin=end; } end++; } return max; } }
wangrzneu/ucloud-sdk-go
ucloud/utest/driver/specification.go
<gh_stars>10-100 package driver import ( "testing" ) type SpecificationReport struct { Status string `json:"status"` Execution SpecificationExecution `json:"execution"` Scenarios []ScenarioReport `json:"scenarios"` PassedCount int `json:"passed_count"` FailedCount int `json:"failed_count"` SkippedCount int `json:"skipped_count"` } type SpecificationExecution struct { Duration float64 `json:"duration"` StartTime float64 `json:"start_time"` EndTime float64 `json:"end_time"` } type Specification struct { Scenarios []*Scenario fixtures map[string]FixtureFunc } type FixtureFunc func(step *Step) (interface{}, error) // AddFixture is a help function for dependency injection func (spec *Specification) AddFixture(name string, fixture FixtureFunc) { if spec.fixtures == nil { spec.fixtures = make(map[string]FixtureFunc) } spec.fixtures[name] = fixture } // ParallelTest is a help function for parallel testing func (spec *Specification) ParallelTest(t *testing.T, sce *Scenario) { t.Parallel() spec.AddScenario(sce) sce.Run(t) } func (spec *Specification) AddScenario(scenario *Scenario) { scenario.Spec = spec spec.Scenarios = append(spec.Scenarios, scenario) } func (spec *Specification) Report() SpecificationReport { var scenarios []ScenarioReport var passedCount, failedCount, skippedCount int for _, v := range spec.Scenarios { scenarios = append(scenarios, v.Report()) switch v.status() { case "passed": passedCount++ case "failed": failedCount++ case "skipped": skippedCount++ } } return SpecificationReport{ Status: spec.status(), Execution: SpecificationExecution{ Duration: spec.endTime() - spec.startTime(), StartTime: spec.startTime(), EndTime: spec.endTime(), }, PassedCount: passedCount, FailedCount: failedCount, SkippedCount: skippedCount, Scenarios: scenarios, } } func (spec *Specification) status() string { var status []string for _, v := range spec.Scenarios { switch v.status() { case "failed": return "failed" case "skipped": continue case "passed": status = append(status, "passed") } } if len(status) == 0 { return "skipped" } return "passed" } func (spec *Specification) startTime() float64 { var t float64 for _, v := range spec.Scenarios { if v.status() != "skipped" && v.startTime() != 0 { if t == 0 { t = v.startTime() } else if v.startTime() < t { t = v.startTime() } } } return t } func (spec *Specification) endTime() float64 { var t float64 for _, v := range spec.Scenarios { if v.status() != "skipped" && v.endTime() > t { t = v.endTime() } } return t }
dlxswangli/gaia
apps/email/js/ext/oauth.js
define(function(require, exports) { var errorutils = require('./errorutils'); var syncbase = require('./syncbase'); var slog = require('./slog'); var date = require('./date'); /** * A window in which a renew request can be sent as a last ditch effort to * get a valid access_token. This value is consulted when a connection fails * due to an expired access_token, but the code did not realize it needed to * try for a renew due to problems with an incorrect system clock. Most access * tokens only last about an hour. So pick a renew window time that is shorter * than that but would only result in one or two tries for a last ditch * effort. If the token is really bad or the user really needs to just * reauthorize the app, then do not want to keep hammering away at the renew * API. */ var RENEW_WINDOW_MS = 30 * 60 * 1000; // Extra timeout padding for oauth tokens. var TIMEOUT_MS = 30 * 1000; /** * Decides if a renew may be feasible to do. Does not allow renew within a * time window. This kind of renew is only used as a last ditch effort to get * oauth to work, where the cached oauth2 data indicates the access token is * still good, but it is being fooled by things like an incorrect clock. * * This can be reset between restarts of the app, since performance.now can * be reset or changed. So it is possible it could try for more than * RENEW_WINDOW_MS if the app has been closed but restarted within that * window. */ exports.isRenewPossible = function(credentials) { var oauth2 = credentials.oauth2, lastRenew = oauth2 && (oauth2._transientLastRenew || 0), now = date.PERFNOW(); if (!oauth2) { return false; } if (!oauth2 || (lastRenew && (now - lastRenew) < RENEW_WINDOW_MS)) { return false; } else { return true; } }; /** * Ensure that the credentials given are still valid, and refresh * them if not. For an OAUTH account, this may entail obtaining a * new access token from the server; for non-OAUTH accounts, this * function always succeeds. * * @param {object} credentials * An object with (at a minimum) 'refreshToken' (and 'accessToken', * if one had already been obtained). * @param {Function} [credsUpdatedCallback] a callback to be called if the * credentials have been updated via a renew. * @param {Boolean} [forceRenew] forces the renewAccessToken step. * @return {Promise} * success: {boolean} True if the credentials were modified. * failure: {String} A normalized error string. */ exports.ensureUpdatedCredentials = function(credentials, credsUpdatedCallback, forceRenew) { if (forceRenew) { console.log('ensureUpdatedCredentials: force renewing token'); } var oauth2 = credentials.oauth2; // If this is an OAUTH account, see if we need to refresh the // accessToken. If not, just continue on our way. if (oauth2 && (!oauth2.accessToken || oauth2.expireTimeMS < date.NOW()) || forceRenew) { return renewAccessToken(oauth2) .then(function(newTokenData) { oauth2.accessToken = newTokenData.accessToken; oauth2.expireTimeMS = newTokenData.expireTimeMS; slog.log('oauth:credentials-changed', { _accessToken: oauth2.accessToken, expireTimeMS: oauth2.expireTimeMS }); if (credsUpdatedCallback) { credsUpdatedCallback(credentials); } }); } else { slog.log('oauth:credentials-ok'); // Not OAUTH; everything is fine. return Promise.resolve(false); } }; /** * Given an OAUTH refreshToken, ask the server for a new * accessToken. If this request fails with the 'needs-oauth-reauth' * error, you should invalidate the refreshToken and have the user * go through the OAUTH flow again. * * @param {String} refreshToken * The long-lived refresh token we've stored in long-term storage. * @return {Promise} * success: {String} { accessToken, expireTimeMS } * failure: {String} normalized errorString */ function renewAccessToken(oauthInfo) { slog.log('oauth:renewing-access-token'); return new Promise(function(resolve, reject) { oauthInfo._transientLastRenew = date.PERFNOW(); var xhr = slog.interceptable('oauth:renew-xhr', function() { return new XMLHttpRequest({ mozSystem: true }); }); xhr.open('POST', oauthInfo.tokenEndpoint, true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.timeout = syncbase.CONNECT_TIMEOUT_MS; xhr.send([ 'client_id=', encodeURIComponent(oauthInfo.clientId), '&client_secret=', encodeURIComponent(oauthInfo.clientSecret), '&refresh_token=', encodeURIComponent(oauthInfo.refreshToken), '&grant_type=refresh_token' ].join('')); xhr.onload = function() { // If we couldn't retrieve the access token, either the user // revoked the access we granted (per Google's OAUTH docs) or // something has gone horribly wrong. The best we can assume // is that the problem will be resolved, or clarified by // instructing the user to reauthenticate. if (xhr.status < 200 || xhr.status >= 300) { // We do still get a JSON response if that goes bad, so let's include // it. try { var errResp = JSON.parse(xhr.responseText); } catch (ex) { } slog.error('oauth:xhr-fail', { tokenEndpoint: oauthInfo.tokenEndpoint, status: xhr.status, errResp: errResp }); reject('needs-oauth-reauth'); } else { try { var data = JSON.parse(xhr.responseText); if (data && data.access_token) { slog.log('oauth:got-access-token', { _accessToken: data.access_token }); // OAUTH returns an expire time as "seconds from now"; // convert that to an absolute DateMS, then subtract a bit of time // to give a buffer from a the token expiring before a renewal is // attempted. var expiresInMS = data.expires_in * 1000; var expireTimeMS = date.NOW() + Math.max(0, expiresInMS - TIMEOUT_MS); resolve({ accessToken: data.access_token, expireTimeMS: expireTimeMS }); } else { slog.error('oauth:no-access-token', { data: xhr.responseText }); reject('needs-oauth-reauth'); } } catch(e) { slog.error('oauth:bad-json', { error: e, data: xhr.responseText }); reject('needs-oauth-reauth'); } } }; xhr.onerror = function(err) { reject(errorutils.analyzeException(err)); }; xhr.ontimeout = function() { reject('unresponsive-server'); }; }); } });
finnhaedicke/metaSMT
toolbox/metaSMT-server/SolverProcess.cpp
#include "SolverProcess.hpp" #include <unistd.h> #include <fcntl.h> #include <cassert> const std::string SolverBase::success = "success"; const std::string SolverBase::unsupported = "unsupported"; const std::string SolverBase::error = "error"; const std::string SolverBase::sat = "sat"; const std::string SolverBase::unsat = "unsat"; const std::string SolverBase::unknown = "unknown"; bool fd_block(int fd, bool block) { int flags = fcntl(fd, F_GETFL, 0); if (flags == -1) return 0; if (block) flags &= ~O_NONBLOCK; else flags |= O_NONBLOCK; return fcntl(fd, F_SETFL, flags) != -1; } SolverProcess::SolverProcess(std::string const &solver_type) : solver_type(solver_type) , sb(0) , num_answers(0) {} SolverProcess::~SolverProcess() { for (int n = 0; n < 2; ++n) { close(fd_c2p[n]); close(fd_p2c[n]); } if ( sb ) { delete sb; } } int SolverProcess::initPipes() { return pipe(fd_c2p) != -1 && pipe(fd_p2c) != -1; } std::string SolverProcess::child_read_command() { return read_command(fd_p2c[0]); } void SolverProcess::child_write_command(std::string s) { write_command(fd_c2p[1], s); } void SolverProcess::parent_write_command(std::string s) { write_command(fd_p2c[1], s); } std::string SolverProcess::parent_read_command() { std::string r; if (*p2c_read_command.rbegin() == '\n') { p2c_read_command.erase(p2c_read_command.find_last_not_of(" \n\r\t") + 1); r = p2c_read_command; } else { r = p2c_read_command + read_command(fd_c2p[0]); } p2c_read_command.clear(); ++num_answers; return r; } bool SolverProcess::parent_read_command_available() { fd_block(fd_c2p[0], false); char buf[1]; int len = read(fd_c2p[0], buf, 1); if (len > 0) p2c_read_command += buf[0]; bool r = len > 0 || !p2c_read_command.empty(); fd_block(fd_c2p[0], true); return r; } std::string SolverProcess::read_command(int fd) { std::string s; char buf[1]; do { int res = read(fd, buf, 1); assert( res > 0 ); s += buf[0]; } while (buf[0] != '\n'); s.erase(s.find_last_not_of("\n\r\t") + 1); return s; } void SolverProcess::write_command(int fd, std::string s) { s += '\n'; write(fd, s.c_str(), s.length()); }
l33tdaima/l33tdaima
p290e/word_pattern.py
class Solution: def wordPatternV1(self, pattern: str, str: str) -> bool: p2s, s2p, words = {}, {}, str.split() if len(pattern) != len(words): return False for p, s in zip(pattern, words): if p in p2s and p2s[p] != s: return False else: p2s[p] = s if s in s2p and s2p[s] != p: return False else: s2p[s] = p return True def wordPatternV2(self, pattern: str, str: str) -> bool: # map the element of iterable xs to the index of first appearance f = lambda xs: map({}.setdefault, xs, range(len(xs))) return list(f(pattern)) == list(f(str.split())) # TESTS tests = [ ("aaa", "aa aa aa aa", False), ("abba", "dog cat cat dog", True), ("abba", "dog cat cat fish", False), ("aaaa", "dog cat cat dog", False), ("abba", "dog dog dog dog", False), ] for pattern, string, expected in tests: sol = Solution() actual = sol.wordPatternV1(pattern, string) print("String", string, "follows the same pattern", pattern, "->", actual) assert actual == expected assert expected == sol.wordPatternV2(pattern, string)
dev7355608/perfect-vision
scripts/core/lighting.js
<reponame>dev7355608/perfect-vision<filename>scripts/core/lighting.js export class Lighting { static findArea(point) { let result = canvas.lighting; const areas = canvas.lighting._pv_areas; if (areas?.length > 0) { for (const area of areas) { if (area._pv_los && !area._pv_los.containsPoint(point)) { continue; } if (area._pv_fov.containsPoint(point)) { result = area; } } } return result; } }
vahidmoeinifar/ndlib
ndlib/models/epidemics/GeneralisedThresholdModel.py
<reponame>vahidmoeinifar/ndlib from ..DiffusionModel import DiffusionModel import networkx as nx import future.utils import random import queue from collections import defaultdict __author__ = "<NAME>" __license__ = "BSD-2-Clause" __email__ = "<EMAIL>" class GeneralisedThresholdModel(DiffusionModel): """ Node Parameters to be specified via ModelConfig :param threshold: The node threshold. If not specified otherwise a value of 0.1 is assumed for all nodes. """ def __init__(self, graph): """ Model Constructor :param graph: A networkx graph object """ super(self.__class__, self).__init__(graph) self.available_statuses = { "Susceptible": 0, "Infected": 1 } self.parameters = { "model": { "tau": { "descr": "Adoption threshold rate", "range": [0, float("inf")], "optional": False}, "mu": { "descr": "Exogenous timescale", "range": [0, float("inf")], "optional": False}, }, "nodes": { "threshold": { "descr": "Node threshold", "range": [0, 1], "optional": True, "default": 0.1 } }, "edges": {}, } self.queue = queue.PriorityQueue() self.inqueue = defaultdict(int) self.name = "GeneralisedThresholdModel" def iteration(self, node_status=True): """ Execute a single model iteration :return: Iteration_id, Incremental node status (dictionary node->status) """ self.clean_initial_status(self.available_statuses.values()) actual_status = {node: nstatus for node, nstatus in future.utils.iteritems(self.status)} if self.actual_iteration == 0: self.actual_iteration += 1 self.params['model']['queue'] = dict() return 0, actual_status gamma = float(self.params['model']['mu']) * float(self.actual_iteration) / float(self.params['model']['tau']) list_node = self.graph.nodes() start = min(list_node) stop = max(list_node) number_node_susceptible = len(self.graph.nodes()) - sum(self.status.values()) while gamma >= 1 and number_node_susceptible >= 1: random_index = random.randrange(start, stop+1, 1) if random_index in list_node and actual_status[random_index] == 0: actual_status[random_index] = 1 gamma -= 1 number_node_susceptible -= 1 for u in self.graph.nodes(): if actual_status[u] == 1: continue neighbors = list(self.graph.neighbors(u)) if isinstance(self.graph, nx.DiGraph): neighbors = list(self.graph.predecessors(u)) infected = 0 for v in neighbors: infected += self.status[v] if len(neighbors) > 0: infected_ratio = float(infected)/len(neighbors) if infected_ratio >= self.params['nodes']['threshold'][u]: if u not in self.inqueue: self.queue.put((self.actual_iteration, u)) self.inqueue[u] = None while not self.queue.empty(): next = self.queue.queue[0] if self.actual_iteration - next[0] >= self.params['model']['tau']: self.queue.get() else: break delta = self.status_delta(actual_status) self.status = actual_status self.actual_iteration += 1 return self.actual_iteration - 1, delta
AndrzejWoronko/WebPassWare
src/Gui/Dialogs/CsvExportDialogController.cpp
<filename>src/Gui/Dialogs/CsvExportDialogController.cpp<gh_stars>0 #include "CsvExportDialogController.h" #include "MessageBox.h" #include "ExportCsv.h" #include "Application.h" CCsvExportDialogController::CCsvExportDialogController(CSqlModel *model, QWidget *parent) : QWidget(parent), m_model(model) { m_dialog = new CCsvExportDialog(); APPI->setAppInformation(); m_settings = new QSettings(); m_settings->beginGroup("ExportCsvData"); restoreLastState(); restoreDialogState(); connect(m_dialog->getButtonBox(), SIGNAL(accepted()), this, SLOT(onAccept())); connect(m_dialog->getButtonBox(), SIGNAL(rejected()), this, SLOT(onReject())); connect(m_dialog->getButtonChoiceFileCsv(), SIGNAL(clicked()), this, SLOT(onButtonChoiceFileCsv())); } CCsvExportDialogController::~CCsvExportDialogController() { saveLastState(); saveDialogState(); m_settings->endGroup(); safe_delete(m_settings) safe_delete(m_dialog) } void CCsvExportDialogController::saveLastState() { m_settings->setValue(m_dialog->getFileNameCsv()->getVariableName(), m_dialog->getFileNameCsv()->getValue().toString()); m_settings->setValue(m_dialog->getFieldsSeparator()->getVariableName(), m_dialog->getFieldsSeparator()->getValue().toString()); m_settings->setValue(m_dialog->getDigitSign()->getVariableName(), m_dialog->getDigitSign()->getValue().toString()); m_settings->setValue(m_dialog->getFileCodec()->getVariableName(), m_dialog->getFileCodec()->getValue().toString()); } void CCsvExportDialogController::restoreLastState() { m_dialog->getFileNameCsv()->setValue(m_settings->value(m_dialog->getFileNameCsv()->getVariableName())); m_dialog->getFileNameCsv()->setStartValue(m_settings->value(m_dialog->getFileNameCsv()->getVariableName())); m_dialog->getFieldsSeparator()->setValue(m_settings->value(m_dialog->getFieldsSeparator()->getVariableName())); m_dialog->getFieldsSeparator()->setStartValue(m_settings->value(m_dialog->getFieldsSeparator()->getVariableName())); m_dialog->getDigitSign()->setValue(m_settings->value(m_dialog->getDigitSign()->getVariableName())); m_dialog->getDigitSign()->setStartValue(m_settings->value(m_dialog->getDigitSign()->getVariableName())); m_dialog->getFileCodec()->setValue(m_settings->value(m_dialog->getFileCodec()->getVariableName())); m_dialog->getFileCodec()->setStartValue(m_settings->value(m_dialog->getFileCodec()->getVariableName())); } //Zapisanie i odtworzenie układu graficznego dialogu void CCsvExportDialogController::restoreDialogState() { QByteArray state = m_dialogState->getState(QString("EXPORT_DIALOG")); m_dialog->restoreGeometry(state); } void CCsvExportDialogController::saveDialogState() { QByteArray state = m_dialog->saveGeometry(); QByteArray oldState = m_dialogState->getState(QString("EXPORT_DIALOG")); if(state != oldState) m_dialogState->saveState(QString("EXPORT_DIALOG"), state); } bool CCsvExportDialogController::wrtite2Csv(const QString &fileName, const QChar &delimeter, const QString &codecName, const QChar &digitSign) { CExportCsv *eCsv = new CExportCsv(fileName, delimeter, codecName, digitSign); if (!eCsv->getFile()->isWritable()) { delete eCsv; return false; } if (m_model) { QVector<QVariant> header = m_model->toVariantRowHeader(); QList< QVector<QVariant> > data = m_model->toVariantRowListData(); eCsv->writeLine(header); Q_FOREACH(auto row, data) { eCsv->writeLine(row); } } delete eCsv; return true; } void CCsvExportDialogController::onButtonChoiceFileCsv() { QString fileName(""); QString fileType(tr("Plik CSV (*.csv)")); fileName = CFileDialog::getSaveFileName(m_dialog, tr("Wybierz plik"), QDir::currentPath(), fileType, QFileDialog::DontConfirmOverwrite, true, m_dialog->getFileNameCsv()->getValue().toString()); if (!fileName.isEmpty()) { if (!fileName.contains(".csv") && !fileName.contains(".CSV")) fileName.append(".csv"); m_dialog->getFileNameCsv()->setValue(fileName); } } void CCsvExportDialogController::onAccept() { QString filename = m_dialog->getFileNameCsv()->getValue().toString(); if (filename.length() > 0) { if (!filename.contains(".csv") && !filename.contains(".CSV")) filename.append(".csv"); m_dialog->getFileNameCsv()->setValue(filename); QChar delimeter; if (m_dialog->getFieldsSeparator()->getValue().toString().length() > 0) delimeter = m_dialog->getFieldsSeparator()->getValue().toString().at(0).toLatin1(); QChar digitSign; if (m_dialog->getDigitSign()->getValue().toString().length() >0) digitSign = m_dialog->getDigitSign()->getValue().toString().at(0).toLatin1(); QString codecName = m_dialog->getFileCodec()->getValue().toString(); if (codecName.length() > 0 && !delimeter.isNull() && !digitSign.isNull()) { if (m_dialog->getFieldsSeparator()->getValue().toString() == QString("TAB")) delimeter = QChar('\t'); if (wrtite2Csv(filename, delimeter, codecName, digitSign)) CMessageBox::OkDialogInformation(tr("Dane zostały pomyślnie zapisane."), m_dialog); else CMessageBox::OkDialogCritical(tr("Dane nie zostały pomyślnie zapisane !!!"), m_dialog); m_dialog->accept(); } } } void CCsvExportDialogController::onReject() { m_dialog->reject(); }
labra/Voting_2a
VoteSystemCountingFinal_2a/src/main/java/es/uniovi/asw/persistence/impl/VotacionJdbcDao.java
<gh_stars>1-10 package es.uniovi.asw.persistence.impl; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import es.uniovi.asw.model.Votacion; import es.uniovi.asw.persistence.Jdbc; import es.uniovi.asw.persistence.VotacionDao; public class VotacionJdbcDao implements VotacionDao { private Properties QUERIES = Jdbc.getQueries(); public boolean save(Votacion votacion) { Connection con = null; PreparedStatement ps = null; try { con=Jdbc.getConnection(); ps=con.prepareStatement(QUERIES.getProperty("SAVE_VOTACION")); ps.setString(1, votacion.getDefinicion()); ps.setDate(2,(Date) votacion.getFechaInicio()); ps.setDate(3,(Date) votacion.getFechaFin()); int num=ps.executeUpdate(); return (num>0); } catch (SQLException e) { e.printStackTrace(); }finally { Jdbc.close(con, ps); } return false; } public Votacion findById(Long id) { Connection con = null; PreparedStatement ps = null; ResultSet rs = null; Votacion vot=null; try { con=Jdbc.getConnection(); ps=con.prepareStatement(QUERIES.getProperty("FIND_VOTACION")); ps.setLong(1, id); rs=ps.executeQuery(); if(rs.next()){ vot=new Votacion(id, rs.getString("DEFINICION")); } } catch (SQLException e) { e.printStackTrace(); }finally { Jdbc.close(rs, ps, con); } return vot; } public List<Votacion> findAll() { Connection con = null; PreparedStatement ps = null; ResultSet rs = null; List<Votacion> vot=new ArrayList<Votacion>(); try { con=Jdbc.getConnection(); ps=con.prepareStatement(QUERIES.getProperty("FIND_TODAS_VOTACIONES")); rs=ps.executeQuery(); while(rs.next()){ vot.add(new Votacion(rs.getLong("id"), rs.getString("DEFINICION"),rs.getDate(3),rs.getDate(4))); } } catch (SQLException e) { e.printStackTrace(); }finally { Jdbc.close(rs, ps, con); } return vot; } }
lechium/iOS1351Headers
System/Library/PrivateFrameworks/SetupAssistantUI.framework/BFFFinishSetupPaymentController.h
<gh_stars>1-10 /* * This header is generated by classdump-dyld 1.5 * on Friday, April 30, 2021 at 11:37:09 AM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/SetupAssistantUI.framework/SetupAssistantUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. Updated by <NAME>. */ #import <libobjc.A.dylib/PKPaymentSetupViewControllerDelegate.h> #import <libobjc.A.dylib/BFFFinishSetupFlowControlling.h> @protocol BFFFinishSetupFlowHosting; @class NSObject, PKPaymentSetupAssistantRegistrationViewController, NSString; @interface BFFFinishSetupPaymentController : NSObject <PKPaymentSetupViewControllerDelegate, BFFFinishSetupFlowControlling> { NSObject*<BFFFinishSetupFlowHosting> _host; PKPaymentSetupAssistantRegistrationViewController* _registrationController; /*^block*/id _completion; } @property (nonatomic,copy) id completion; //@synthesize completion=_completion - In the implementation block @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; +(unsigned long long)registrationViewControllerOutstandingRequirements; +(BOOL)hasPrimaryiCloudAccount; +(id)finishSetupPaymentControllerWithHost:(id)arg1 ; -(void)setCompletion:(id)arg1 ; -(id)completion; -(void)_completeWithResult:(unsigned long long)arg1 ; -(id)initWithHost:(id)arg1 ; -(BOOL)controllerNeedsToRun; -(void)_userDidTapCancelButton:(id)arg1 ; -(void)viewControllerDidTerminateSetupFlow:(id)arg1 ; -(id)viewControllerWithCompletion:(/*^block*/id)arg1 ; -(id)prerequisiteFlowIdentifier; -(void)performExtendedInitializationWithCompletion:(/*^block*/id)arg1 ; -(BOOL)canCompleteExtendedInitializationQuickly; @end
bytemechanics/test-drive
test-drive/src/main/java/org/bytemechanics/testdrive/runners/beans/EvaluationBean.java
/* * Copyright 2018 Byte Mechanics. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.bytemechanics.testdrive.runners.beans; import java.util.Objects; import java.util.Optional; import org.bytemechanics.testdrive.adapter.EvaluationId; import org.bytemechanics.testdrive.annotations.Evaluation; import org.bytemechanics.testdrive.exceptions.TestParametersNotMatch; import org.bytemechanics.testdrive.exceptions.UnparseableParameter; import org.bytemechanics.testdrive.internal.commons.string.GenericTextParser; import org.bytemechanics.testdrive.internal.commons.string.SimpleFormat; /** * * @author afarre */ public class EvaluationBean extends TestBean implements EvaluationId{ private final Evaluation evaluation; private final int evaluationCounter; private final String evaluationName; private final String[] evaluationArguments; private ResultBean evaluationResult; public EvaluationBean(final TestBean _test,final int _counter,final Evaluation _evaluation) { super(_test); this.evaluation=_evaluation; this.evaluationCounter = _counter; this.evaluationName = Optional.of(_evaluation.name()) .filter(val -> !val.isEmpty()) .map(val -> SimpleFormat.format("{}(\"{}\")",_counter,val)) .orElseGet(() -> String.valueOf(_counter)); this.evaluationArguments = _evaluation.args(); this.evaluationResult=null; } public EvaluationBean(final TestBean _test) { super(_test); this.evaluationCounter = 1; this.evaluationName = _test.getTestName(); this.evaluationArguments = new String[0]; this.evaluationResult=null; this.evaluation=null; } @Override public int getEvaluationCounter() { return evaluationCounter; } @Override public String getEvaluationName() { return evaluationName; } @Override public String[] getEvaluationArguments() { return evaluationArguments; } public Evaluation getEvaluation() { return evaluation; } public ResultBean getEvaluationResult() { return evaluationResult; } public void setEvaluationResult(ResultBean result) { this.evaluationResult = result; } protected Object[] parseArguments(final Class[] _classes,final String[] _values){ final Object[] reply=new Object[_classes.length]; for(int ic1=0;ic1<_classes.length;ic1++){ try { final int position=ic1; reply[position]=GenericTextParser.toValue(_classes[position], _values[position]) .orElseThrow(() -> new UnparseableParameter(position, _classes[position], _values[position])); } catch (Throwable ex) { throw (UnparseableParameter)ex; } } return reply; } public Object[] getParsedArguments(){ return Optional.ofNullable(getTestMethodParameters()) .filter(parameters -> parameters.length<=getEvaluationArguments().length) .map(parameters -> parseArguments(parameters, getEvaluationArguments())) .orElseThrow(() -> new TestParametersNotMatch(getSpecificationClass(),getTestMethod(),getEvaluationArguments())); } @Override public int hashCode() { int hash = super.hashCode(); hash = 97 * hash + Objects.hashCode(this.evaluationResult); return hash; } @Override @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") public boolean equals(Object obj) { if (!super.equals(obj)) { return false; } final EvaluationBean other = (EvaluationBean) obj; return Objects.equals(this.evaluationResult, other.evaluationResult); } }
entbit/tortilla-website
src/utils/routes.js
// @ts-check exports.stepRoute = ({ owner, repo, branch, version, step }) => { let route = `/${owner}/${repo}` if (branch) { route += `/${branch}` } if (version) { route += `/${version}/step/${step}` } return route } exports.diffRoute = ({ owner, repo, branch, srcVersion, destVersion }) => `/${owner}/${repo}/${branch}/${destVersion}/diff/${srcVersion}`
SpiNNakerManchester/nengo_spinnaker
regression-tests/test_node_output.py
import logging logging.basicConfig(level=logging.DEBUG) import nengo import nengo_spinnaker import numpy as np def test_node_output_transmitted_to_board(): with nengo.Network("Test Network") as network: a = nengo.Node(lambda t: 0.5) b = nengo.Ensemble(100, 2) nengo.Connection(a, b, transform=[[-1.0], [1.0]]) p = nengo.Probe(b, synapse=0.05) # Create the simulate and simulate sim = nengo_spinnaker.Simulator(network) # Run the simulation for long enough to ensure that the decoded value is # with +/-20% of the input value. with sim: sim.run(2.0) # Check that the value was decoded as expected index = int(p.synapse.tau * 2.5 / sim.dt) data = sim.data[p] assert(np.all(+0.40 <= data[index:, 1]) and np.all(+0.60 >= data[index:, 1]) and np.all(-0.60 <= data[index:, 0]) and np.all(-0.40 >= data[index:, 0])) if __name__ == "__main__": test_node_output_transmitted_to_board()
gtorvald/gauge3panel
node_modules/@iconscout/react-unicons/icons/uil-pentagon.js
import React from 'react'; import PropTypes from 'prop-types'; const UilPentagon = (props) => { const { color, size, ...otherProps } = props return React.createElement('svg', { xmlns: 'http://www.w3.org/2000/svg', width: size, height: size, viewBox: '0 0 24 24', fill: color, ...otherProps }, React.createElement('path', { d: 'M21.59,9.17l-9-6.54a1,1,0,0,0-1.18,0l-9,6.54a1,1,0,0,0-.36,1.12L5.49,20.87a1,1,0,0,0,1,.69H17.56a1,1,0,0,0,1-.69L22,10.29A1,1,0,0,0,21.59,9.17ZM16.84,19.56H7.16l-3-9.2L12,4.68l7.82,5.68Z' })); }; UilPentagon.propTypes = { color: PropTypes.string, size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; UilPentagon.defaultProps = { color: 'currentColor', size: '24', }; export default UilPentagon;
npocmaka/Windows-Server-2003
ds/security/passport/passportmanager/manager.cpp
<reponame>npocmaka/Windows-Server-2003<filename>ds/security/passport/passportmanager/manager.cpp<gh_stars>10-100 /**********************************************************************/ /** Microsoft Passport **/ /** Copyright(c) Microsoft Corporation, 1999 - 2001 **/ /**********************************************************************/ /* manager.cpp COM object for manager interface FILE HISTORY: */ // Manager.cpp : Implementation of CManager #include "stdafx.h" #include <httpext.h> #include "Manager.h" #include <httpfilt.h> #include <time.h> #include <malloc.h> #include <wininet.h> #include <nsconst.h> #include "VariantUtils.h" #include "HelperFuncs.h" #include "RegistryConfig.h" #include "PassportService_i.c" #include "atlbase.h" PWSTR GetVersionString(); //using namespace ATL; // gmarks #include "Monitoring.h" ///////////////////////////////////////////////////////////////////////////// // CManager #include "passporttypes.h" // static utility func static VOID GetTicketAndProfileFromHeader(PWSTR pszAuthHeader, PWSTR& pszTicket, PWSTR& pszProfile, PWSTR& pszF); // Used for cookie expiration. const DATE g_dtExpire = 365*137; const DATE g_dtExpired = 365*81; //=========================================================================== // // CManager // CManager::CManager() : m_fromQueryString(false), m_ticketValid(VARIANT_FALSE), m_profileValid(VARIANT_FALSE), m_lNetworkError(0), m_pRegistryConfig(NULL), m_pECB(NULL), m_pFC(NULL), m_bIsTweenerCapable(FALSE), m_bSecureTransported(false) { PPTraceFuncV func(PPTRACE_FUNC, "CManager"); // ticket object m_pUnkMarshaler = NULL; try { m_piTicket = new CComObject<CTicket>(); } catch(...) { m_piTicket = NULL; } if(m_piTicket) m_piTicket->AddRef(); // profile object try { m_piProfile = new CComObject<CProfile>(); } catch(...) { m_piProfile = NULL; } if(m_piProfile) m_piProfile->AddRef(); m_bOnStartPageCalled = false; } //=========================================================================== // // ~CManager // CManager::~CManager() { PPTraceFuncV func(PPTRACE_FUNC, "~CManager"); if(m_pRegistryConfig) m_pRegistryConfig->Release(); if (m_piTicket) m_piTicket->Release(); if (m_piProfile) m_piProfile->Release(); } //=========================================================================== // // IfConsentCookie -- if a consent cookie should be sent back // return value: S_OK -- has consent cookie; S_FALSE -- no consent cookie // output param: The consent cookie // HRESULT CManager::IfConsentCookie(BSTR* pMSPConsent) { BSTR bstrRawConsent = NULL; HRESULT hr = S_FALSE; PPTraceFunc<HRESULT> func( PPTRACE_FUNC, hr, "IfConsentCookie"," <<<< %lx", pMSPConsent ); if (!m_piTicket || !m_piProfile || !m_pRegistryConfig) { hr = E_OUTOFMEMORY; goto Cleanup; } LPCSTR domain = m_pRegistryConfig->getTicketDomain(); LPCSTR path = m_pRegistryConfig->getTicketPath(); LPCSTR tertiaryDomain = m_pRegistryConfig->getProfileDomain(); LPCSTR tertiaryPath = m_pRegistryConfig->getProfilePath(); if (!tertiaryPath) tertiaryPath = "/"; if(!domain) domain = ""; if(!path) path = ""; if(!tertiaryDomain) tertiaryDomain = ""; if(!tertiaryPath) tertiaryPath = ""; // // if a separate consent cookie is necessary if((lstrcmpiA(domain, tertiaryDomain) || lstrcmpiA(path, tertiaryPath)) && (m_piTicket->GetPassportFlags() & k_ulFlagsConsentCookieNeeded) && !m_pRegistryConfig->bInDA() ) { if (pMSPConsent == NULL) // no output param hr = S_OK; else { *pMSPConsent = NULL; CCoCrypt* crypt = m_pRegistryConfig->getCurrentCrypt(); if (!crypt) { hr = E_FAIL; goto Cleanup; } // get the consent cookie from ticket hr = m_piTicket->get_unencryptedCookie(CTicket::MSPConsent, 0, &bstrRawConsent); if (FAILED(hr)) goto Cleanup; // encrypt it with partner's key if (!crypt->Encrypt(m_pRegistryConfig->getCurrentCryptVersion(), (LPSTR)bstrRawConsent, SysStringByteLen(bstrRawConsent), pMSPConsent)) { hr = E_FAIL; goto Cleanup; } } } Cleanup: if (bstrRawConsent) { SysFreeString(bstrRawConsent); } if(pMSPConsent) PPTracePrint(PPTRACE_RAW, ">>> pMSPConsent:%ws", PPF_WCHAR(*pMSPConsent)); return hr; } //=========================================================================== // // IfAlterAuthCookie // // return S_OK -- when auth cookie is different from t (altered), should use // the cookie and secAuth cookie returned // S_FALSE -- not altered -- can use the t as auth cookie // if MSPSecAuth != NULL, write the secure cookie HRESULT CManager::IfAlterAuthCookie(BSTR* pMSPAuth, BSTR* pMSPSecAuth) { _ASSERT(pMSPAuth && pMSPSecAuth); *pMSPAuth = NULL; *pMSPSecAuth = NULL; HRESULT hr = S_FALSE; PPTraceFunc<HRESULT> func(PPTRACE_FUNC, hr, "IfAlterAuthCookie", "<<< %lx, %lx", pMSPAuth, pMSPSecAuth); if (!m_piTicket || !m_piProfile || !m_pRegistryConfig) { return E_OUTOFMEMORY; } if (!(m_piTicket->GetPassportFlags() & k_ulFlagsSecuredTransportedTicket) || !m_bSecureTransported) { return hr; } BSTR bstrRawAuth = NULL; BSTR bstrRawSecAuth = NULL; CCoCrypt* crypt = m_pRegistryConfig->getCurrentCrypt(); if (!crypt) { hr = PM_CANT_DECRYPT_CONFIG; goto Cleanup; } hr = m_piTicket->get_unencryptedCookie(CTicket::MSPAuth, 0, &bstrRawAuth); if (FAILED(hr)) goto Cleanup; if (!crypt->Encrypt(m_pRegistryConfig->getCurrentCryptVersion(), (LPSTR)bstrRawAuth, SysStringByteLen(bstrRawAuth), pMSPAuth)) { hr = PM_CANT_DECRYPT_CONFIG; goto Cleanup; } hr = m_piTicket->get_unencryptedCookie(CTicket::MSPSecAuth, 0, &bstrRawSecAuth); if (FAILED(hr)) goto Cleanup; if (!crypt->Encrypt(m_pRegistryConfig->getCurrentCryptVersion(), (LPSTR)bstrRawSecAuth, SysStringByteLen(bstrRawSecAuth), pMSPSecAuth)) { hr = PM_CANT_DECRYPT_CONFIG; goto Cleanup; } Cleanup: if (bstrRawAuth) { SysFreeString(bstrRawAuth); } if (bstrRawSecAuth) { SysFreeString(bstrRawSecAuth); } PPTracePrint(PPTRACE_RAW, ">>> pMSPAuth:%ws, pMSPSecAuth:%ws", PPF_WCHAR(*pMSPAuth), PPF_WCHAR(*pMSPSecAuth)); return hr; } //=========================================================================== // // wipeState -- cleanup teh state of manager object // void CManager::wipeState() { PPTraceFuncV func(PPTRACE_FUNC, "wipeState"); m_pECB = NULL; m_pFC = NULL; m_bIsTweenerCapable = FALSE; m_bOnStartPageCalled = false; m_fromQueryString = false; m_lNetworkError = 0; m_ticketValid = VARIANT_FALSE; m_profileValid = VARIANT_FALSE; m_piRequest = NULL; m_piResponse = NULL; // cleanup ticket content if(m_piTicket) m_piTicket->put_unencryptedTicket(NULL); // cleanup profile content if(m_piProfile) m_piProfile->put_unencryptedProfile(NULL); // cleanup buffered registry config if(m_pRegistryConfig) { m_pRegistryConfig->Release(); m_pRegistryConfig = NULL; } } //=========================================================================== // // InterfaceSupportsErrorInfo // STDMETHODIMP CManager::InterfaceSupportsErrorInfo(REFIID riid) { PPTraceFuncV func(PPTRACE_FUNC, "InterfaceSupportsErrorInfo"); static const IID* arr[] = { &IID_IPassportManager, &IID_IPassportManager2, &IID_IPassportManager3, &IID_IDomainMap, }; for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++) { if (InlineIsEqualGUID(*arr[i],riid)) return S_OK; } return S_FALSE; } //=========================================================================== // // OnStartPage -- called by ASP pages automatically by IIS when declared on the page // STDMETHODIMP CManager::OnStartPage (IUnknown* pUnk) { HRESULT hr = S_OK; PPTraceFunc<HRESULT> func(PPTRACE_FUNC, hr, "OnStartPage"," <<< %lx", pUnk); if(!pUnk) { return hr = E_POINTER; } IScriptingContextPtr spContext; spContext = pUnk; // Get Request Object Pointer hr = OnStartPageASP(spContext->Request, spContext->Response); return hr; } BSTR MyA2W( char *src ) { if (src == NULL) { return NULL; } BSTR str = NULL; int nConvertedLen = MultiByteToWideChar(GetACP(), 0, src, -1, NULL, NULL); str = ::SysAllocStringLen(NULL, nConvertedLen - 1); if (str != NULL) { if (!MultiByteToWideChar(GetACP(), 0, src, -1, str, nConvertedLen)) { SysFreeString(str); str = NULL; } } return str; } //=========================================================================== // // OnStartPageASP -- called by asp pages when created by using factory object // FUTURE --- should change the OnStartPage function to use this function // STDMETHODIMP CManager::OnStartPageASP( IDispatch* piRequest, IDispatch* piResponse ) { HRESULT hr = S_OK; char* spBuf = NULL; BSTR bstrName=NULL; BSTR bstrValue=NULL; PPTraceFunc<HRESULT> func(PPTRACE_FUNC, hr, "OnStartPageASP", " <<< %lx, %lx", piRequest, piResponse); PassportLog("CManager::OnStartPageASP Enter:\r\n"); if(!piRequest || !piResponse) return hr = E_INVALIDARG; USES_CONVERSION; try { IRequestDictionaryPtr piServerVariables; _variant_t vtItemName; _variant_t vtHTTPS; _variant_t vtMethod; _variant_t vtPath; _variant_t vtQs; _variant_t vtServerPort; _variant_t vtHeaders; CComQIPtr<IResponse> spResponse; CComQIPtr<IRequest> spRequest; // Get Request Object Pointer spRequest = piRequest; spResponse = piResponse; // // Get the server variables collection. // spRequest->get_ServerVariables(&piServerVariables); // // now see if that's a special redirect // requiring challenge generation // if so processing stops here .... // if (checkForPassportChallenge(piServerVariables)) { PPTracePrint(PPTRACE_RAW, "special redirect for Challenge"); return S_OK; } // // Might need this for multi-site, or secure ticket/profile // vtItemName = L"HTTPS"; piServerVariables->get_Item(vtItemName, &vtHTTPS); if(vtHTTPS.vt != VT_BSTR) vtHTTPS.ChangeType(VT_BSTR); DWORD flags = 0; if(vtHTTPS.bstrVal && lstrcmpiW(L"on", vtHTTPS.bstrVal) == 0) flags |= PASSPORT_HEADER_FLAGS_HTTPS; // headers vtItemName.Clear(); vtItemName = L"ALL_RAW"; piServerVariables->get_Item(vtItemName, &vtHeaders); if(vtHeaders.vt != VT_BSTR){ vtHeaders.ChangeType(VT_BSTR); } // path vtItemName.Clear(); vtItemName = L"PATH_INFO"; piServerVariables->get_Item(vtItemName, &vtPath); if(vtPath.vt != VT_BSTR) vtPath.ChangeType(VT_BSTR); // vtMethod vtItemName.Clear(); vtItemName = L"REQUEST_METHOD"; piServerVariables->get_Item(vtItemName, &vtMethod); if(vtMethod.vt != VT_BSTR) vtMethod.ChangeType(VT_BSTR); // QUERY_STRING vtItemName.Clear(); vtItemName = L"QUERY_STRING"; piServerVariables->get_Item(vtItemName, &vtQs); if(vtQs.vt != VT_BSTR) vtQs.ChangeType(VT_BSTR); DWORD bufSize = 0; DWORD requiredBufSize = MAX_URL_LENGTH; // make sure the size if sufficient while(bufSize < requiredBufSize) { if (spBuf) { free(spBuf); } if(NULL == (spBuf = (char *)malloc(requiredBufSize))) { hr = E_OUTOFMEMORY; goto exit; } bufSize = requiredBufSize; hr = OnStartPageHTTPRawEx(W2A(vtMethod.bstrVal), W2A(vtPath.bstrVal), W2A(vtQs.bstrVal), NULL, // version W2A(vtHeaders.bstrVal), flags, &requiredBufSize, spBuf); } // write the cookies if(hr == S_OK && requiredBufSize && *spBuf) { char* pNext = spBuf; while(pNext != NULL) { char* pName = pNext; char* pValue = strchr(pName, ':'); if(pValue) { // make temp sub string TempSubStr tsN(pName, pValue - pName); bstrName = MyA2W(pName); if (bstrName) { ++pValue; pNext = strstr(pValue, "\r\n"); // new line if(pNext) { // make temp sub string TempSubStr tsV(pValue, pNext - pValue); pNext += 2; bstrValue = MyA2W(pValue); } else { bstrValue = MyA2W(pValue); } if (bstrValue) { spResponse->raw_AddHeader(bstrName, bstrValue); } } } else { pNext = pValue; } if (bstrName) { SysFreeString(bstrName); bstrName = NULL; } if (bstrValue) { SysFreeString(bstrValue); bstrValue = NULL; } } } if (spBuf) { free(spBuf); spBuf = NULL; } // Get Request Object Pointer m_piRequest = piRequest; // Get Response Object Pointer m_piResponse = piResponse; } catch (...) { if (m_piRequest.GetInterfacePtr() != NULL) m_piRequest.Release(); if (m_piResponse.GetInterfacePtr() != NULL) m_piResponse.Release(); m_bOnStartPageCalled = false; if (spBuf) { free(spBuf); } if (bstrName) { SysFreeString(bstrName); } if (bstrValue) { SysFreeString(bstrValue); } } exit: return hr = S_OK; } //=========================================================================== // // OnStartPageManual -- authenticate with t, and p, MSPAuth, MSPProf, MSPConsent, MSPsecAuth // not recommended to use, will be depracated // STDMETHODIMP CManager::OnStartPageManual( BSTR qsT, BSTR qsP, BSTR mspauth, BSTR mspprof, BSTR mspconsent, VARIANT mspsec, VARIANT* pCookies ) { int hasSec; BSTR bstrSec; BSTR bstrConsent = NULL; BSTR bstrNewAuth = NULL; BSTR bstrNewSecAuth = NULL; HRESULT hr = S_OK; PPTraceFunc<HRESULT> func(PPTRACE_FUNC, hr, "OnStartPageManual", " <<< %ws, %ws, %ws, %ws, %ws", qsT, qsP, mspauth, mspprof, mspconsent); PassportLog("CManager::OnStartPageManual Enter: T = %ws, P = %ws, A = %ws, PR = %ws\r\n", qsT, qsP, mspauth, mspprof); if (!g_config->isValid()) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); return PP_E_NOT_CONFIGURED; } if (!m_piTicket || !m_piProfile) { return E_OUTOFMEMORY; } wipeState(); if(m_pRegistryConfig) m_pRegistryConfig->Release(); m_pRegistryConfig = g_config->checkoutRegistryConfig(); // Auth with Query String T & P first if (handleQueryStringData(qsT, qsP)) { VARIANT_BOOL persist; _bstr_t domain; _bstr_t path; _bstr_t bstrAuth; _bstr_t bstrProf; bstrAuth.Assign(qsT); bstrProf.Assign(qsP); if (pCookies) { VariantInit(pCookies); if (m_pRegistryConfig->getTicketPath()) path = m_pRegistryConfig->getTicketPath(); else path = L"/"; m_piTicket->get_HasSavedPassword(&persist); BOOL bSetConsent = (S_OK == IfConsentCookie(&bstrConsent)); SAFEARRAYBOUND rgsabound; rgsabound.lLbound = 0; rgsabound.cElements = 2; // secure cookie if (m_bSecureTransported) rgsabound.cElements++; if(bSetConsent) rgsabound.cElements++; SAFEARRAY *sa = SafeArrayCreate(VT_VARIANT, 1, &rgsabound); if (!sa) { hr = E_OUTOFMEMORY; goto Cleanup; } pCookies->vt = VT_ARRAY | VT_VARIANT; pCookies->parray = sa; WCHAR buf[4096]; DWORD bufSize; long spot = 0; VARIANT *vArray; SafeArrayAccessData(sa, (void**)&vArray); // write Auth cookies BSTR auth, secAuth; // do not call SysFreeString on them, they are skin level copy if (S_OK == IfAlterAuthCookie(&bstrNewAuth, &bstrNewSecAuth)) { auth = bstrNewAuth; secAuth = bstrNewSecAuth; } else { auth = bstrAuth; secAuth = NULL; } domain = m_pRegistryConfig->getTicketDomain(); // add MSPAuth if (domain.length()) { bufSize = _snwprintf(buf, 4096, L"Set-Cookie: MSPAuth=%s; path=%s; domain=%s; %s\r\n", (LPWSTR)auth, (LPWSTR)path, (LPWSTR)domain, persist ? W_COOKIE_EXPIRES(EXPIRE_FUTURE) : L""); } else { bufSize = _snwprintf(buf, 4096, L"Set-Cookie: MSPAuth=%s; path=%s; %s\r\n", (LPWSTR)auth, (LPWSTR)path, persist ? W_COOKIE_EXPIRES(EXPIRE_FUTURE) : L""); } buf[4095] = L'\0'; vArray[spot].vt = VT_BSTR; vArray[spot].bstrVal = ALLOC_AND_GIVEAWAY_BSTR_LEN(buf, bufSize); spot++; // add MSPSecAuth if (m_bSecureTransported) { _bstr_t secDomain = m_pRegistryConfig->getSecureDomain(); _bstr_t secPath; if (m_pRegistryConfig->getSecurePath()) secPath = m_pRegistryConfig->getSecurePath(); else secPath = L"/"; if (secDomain.length()) { bufSize = _snwprintf(buf, 4096, L"Set-Cookie: MSPSecAuth=%s; path=%s; domain=%s; %s; secure\r\n", ((secAuth && *secAuth) ? (LPWSTR)secAuth : L""), (LPWSTR)secPath, (LPWSTR)secDomain, ((!secAuth || *secAuth == 0) ? W_COOKIE_EXPIRES(EXPIRE_PAST) : L"")); } else { bufSize = _snwprintf(buf, 4096, L"Set-Cookie: MSPSecAuth=%s; path=%s; %s; secure\r\n", ((secAuth && *secAuth) ? (LPWSTR)secAuth : L""), (LPWSTR)secPath, ((!secAuth || *secAuth == 0) ? W_COOKIE_EXPIRES(EXPIRE_PAST) : L"")); } buf[4095] = L'\0'; vArray[spot].vt = VT_BSTR; vArray[spot].bstrVal = ALLOC_AND_GIVEAWAY_BSTR_LEN(buf, bufSize); spot++; } if (domain.length()) { bufSize = _snwprintf(buf, 4096, L"Set-Cookie: MSPProf=%s; path=%s; domain=%s; %s\r\n", (LPWSTR)bstrProf, (LPWSTR)path, (LPWSTR)domain, persist ? W_COOKIE_EXPIRES(EXPIRE_FUTURE) : L""); } else { bufSize = _snwprintf(buf, 4096, L"Set-Cookie: MSPProf=%s; path=%s; %s\r\n", (LPWSTR)bstrProf, (LPWSTR)path, persist ? W_COOKIE_EXPIRES(EXPIRE_FUTURE) : L""); } buf[4095] = L'\0'; vArray[spot].vt = VT_BSTR; vArray[spot].bstrVal = ALLOC_AND_GIVEAWAY_BSTR_LEN(buf, bufSize); spot++; if(bSetConsent) { if (m_pRegistryConfig->getProfilePath()) path = m_pRegistryConfig->getProfilePath(); else path = L"/"; domain = m_pRegistryConfig->getProfileDomain(); if (domain.length()) { bufSize = _snwprintf(buf, 4096, L"Set-Cookie: MSPConsent=%s; path=%s; domain=%s; %s\r\n", bSetConsent ? (LPWSTR)bstrConsent : L"", (LPWSTR)path, (LPWSTR)domain, bSetConsent ? (persist ? W_COOKIE_EXPIRES(EXPIRE_FUTURE) : L"") : W_COOKIE_EXPIRES(EXPIRE_PAST)); } else { bufSize = _snwprintf(buf, 4096, L"Set-Cookie: MSPConsent=%s; path=%s; %s\r\n", bSetConsent ? (LPWSTR)bstrConsent : L"", (LPWSTR)path, bSetConsent ? (persist ? W_COOKIE_EXPIRES(EXPIRE_FUTURE) : L"") : W_COOKIE_EXPIRES(EXPIRE_PAST)); } buf[4095] = L'\0'; vArray[spot].vt = VT_BSTR; vArray[spot].bstrVal = ALLOC_AND_GIVEAWAY_BSTR_LEN(buf, bufSize); spot++; } SafeArrayUnaccessData(sa); } } // Now, check the cookies if (!m_fromQueryString) { hasSec = GetBstrArg(mspsec, &bstrSec); if(hasSec == CV_DEFAULT || hasSec == CV_BAD) bstrSec = NULL; handleCookieData(mspauth, mspprof, mspconsent, bstrSec); if(hasSec == CV_FREE) SysFreeString(bstrSec); } hr = S_OK; Cleanup: if (bstrNewAuth) { SysFreeString(bstrNewAuth); } if (bstrNewSecAuth) { SysFreeString(bstrNewSecAuth); } if (bstrConsent) { SysFreeString(bstrConsent); } PassportLog("CManager::OnStartPageManual Exit:\r\n"); return hr; } //=========================================================================== // // OnStartPageECB -- Authenticate with ECB -- for ISAPI extensions // STDMETHODIMP CManager::OnStartPageECB( LPBYTE pvECB, DWORD* bufSize, LPSTR pCookieHeader ) { if (!pvECB) return E_INVALIDARG; EXTENSION_CONTROL_BLOCK* pECB = (EXTENSION_CONTROL_BLOCK*) pvECB; HRESULT hr = S_OK; PPTraceFunc<HRESULT> func(PPTRACE_FUNC, hr, "OnStartPageECB", " <<< %lx, %lx, %d, %lx", pvECB, bufSize, *bufSize, pCookieHeader); ATL::CAutoVectorPtr<CHAR> spHTTPS; ATL::CAutoVectorPtr<CHAR> spheaders; spheaders.Attach(GetServerVariableECB(pECB, "ALL_RAW")); spHTTPS.Attach(GetServerVariableECB(pECB, "HTTPS")); DWORD flags = 0; if((CHAR*)spHTTPS && lstrcmpiA("on", (CHAR*)spHTTPS) == 0) flags |= PASSPORT_HEADER_FLAGS_HTTPS; hr = OnStartPageHTTPRawEx(pECB->lpszMethod, pECB->lpszPathInfo, pECB->lpszQueryString, NULL, // version (CHAR*)spheaders, flags, bufSize, pCookieHeader); m_pECB = pECB; return hr; } //=========================================================================== // // OnStartPageHTTPRaw -- Authenticate with HTTP request-line and headers // returns response headers as output parameters // STDMETHODIMP CManager::OnStartPageHTTPRaw( /* [string][in] */ LPCSTR request_line, /* [string][in] */ LPCSTR headers, /* [in] */ DWORD flags, /* [out][in] */ DWORD *bufSize, /* [size_is][out] */ LPSTR pCookieHeader) { // an old client, let's try the QS DWORD dwSize; HRESULT hr = S_OK; PPTraceFunc<HRESULT> func(PPTRACE_FUNC, hr, "OnStartPageHTTPRaw", " <<< %s, %s, %lx, %lx, %d, %lx", request_line, headers, flags, bufSize, *bufSize, pCookieHeader); LPCSTR pBuffer = GetRawQueryString(request_line, &dwSize); if (pBuffer) { TempSubStr tss(pBuffer, dwSize); hr = OnStartPageHTTPRawEx(NULL, NULL, pBuffer, NULL, headers, flags, bufSize, pCookieHeader); } else hr = OnStartPageHTTPRawEx(NULL, NULL, NULL, NULL, headers, flags, bufSize, pCookieHeader); return hr; } //=========================================================================== // // @func OnStartPageHTTPRawEx -- Authenticate with HTTP request-line and headers // returns response headers as output parameters. If *bufsize is not smaller // the required length or pCookieHeader is NULL, the required length is returned // in bufsize. In this case, an empty string is written into pCookieHeader if // it is not NULL. // method, path, HTTPVer are not being used in this version of the API // // @rdesc returns one of these values // @flag E_POINTER | NULL bufSize // @flag E_POINTER | not writable buffer given by pCookieHeader // @flag PP_E_NOT_CONFIGURED | not valid state to call this method // @flag S_OK // STDMETHODIMP CManager::OnStartPageHTTPRawEx( /* [string][in] */ LPCSTR method, /* [string][in] */ LPCSTR path, /* [string][in] */ LPCSTR QS, /* [string][in] */ LPCSTR HTTPVer, /* [string][in] */ LPCSTR headers, /* [in] */ DWORD flags, /* [out][in] */ DWORD *bufSize, //@parm retuns the length of the headers. Could be 0 to ask for the req. len. /* [size_is][out]*/ LPSTR pCookieHeader) //@parm buffer to hold the headers. Could be NULL to ask for the req. len { USES_CONVERSION; if(bufSize == NULL) return E_POINTER; HRESULT hr = S_OK; PPTraceFunc<HRESULT> func(PPTRACE_FUNC, hr, "OnStartPageHTTPRawEx", " <<< %s, %s, %s, %s, %s, %lx, %lx, %d, %lx", method, path, QS, HTTPVer, headers, flags, bufSize, *bufSize, pCookieHeader); PassportLog("CManager::OnStartPageHTTPRawEx Enter:\r\n"); // // 12002: if *bufSize is 0, we will not be writing into pCookieHeader // if(*bufSize == 0) pCookieHeader = NULL; if(pCookieHeader && IsBadWritePtr(pCookieHeader, *bufSize)) return E_POINTER; if (!g_config || !g_config->isValid()) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); return PP_E_NOT_CONFIGURED; } if (!m_piTicket || !m_piProfile) { return E_OUTOFMEMORY; } wipeState(); DWORD dwSize; LPCSTR pBuffer; // used to convert to wide ... WCHAR *pwszBuf = NULL; enum { header_Host, header_Accept_Auth, header_Authorization, header_Cookie, header_total }; LPCSTR headerNames[header_total] = { "Host", "Accept-Auth", "Authorization", "Cookie"}; DWORD headerSizes[header_total]; LPCSTR headerValues[header_total] = {0}; GetRawHeaders(headers, headerNames, headerValues, headerSizes, header_total); // // Use the header to get the server name being requested // so we can get the correct registry config. But only do this // if we have some configured sites. // if(m_pRegistryConfig) m_pRegistryConfig->Release(); pBuffer = headerValues[header_Host]; if(g_config->HasSites() && pBuffer) { TempSubStr tss(pBuffer, headerSizes[header_Host]); TempSubStr tssRemovePort; LPSTR pPort = strstr(pBuffer, ":"); if(pPort) { ++pPort; DWORD dwPort = atoi(pPort); if(dwPort == 80 || dwPort == 443) { tssRemovePort.Set(pBuffer, pPort - pBuffer - 1); } } // for port 80 and 443, this should be removed PPTracePrint(PPTRACE_RAW, "SiteName %s", PPF_CHAR(pBuffer)); m_pRegistryConfig = g_config->checkoutRegistryConfig((LPSTR)pBuffer); } else { PPTracePrint(PPTRACE_RAW, "Default Site"); m_pRegistryConfig = g_config->checkoutRegistryConfig(NULL); } if (pCookieHeader) *pCookieHeader = '\0'; // // If we have a secure ticket/profile and the url is SSL, // then tack on the MSPPuid cookie. // if(PASSPORT_HEADER_FLAGS_HTTPS & flags) m_bSecureTransported = true; else m_bSecureTransported = false; PPTracePrint(PPTRACE_RAW, "HTTPS:%d", m_bSecureTransported); // see if client understands passport pBuffer = headerValues[header_Accept_Auth]; if (pBuffer) { TempSubStr tss(pBuffer, headerSizes[header_Accept_Auth]); if (strstr(pBuffer, PASSPORT_PROT14_A)) { m_bIsTweenerCapable = TRUE; PPTracePrint(PPTRACE_RAW, "PASSPORT_PROT14 capable"); } } BSTR ret = NULL; CCoCrypt* crypt = NULL; BOOL fParseSuccess = FALSE; pBuffer = headerValues[header_Authorization]; PWSTR pwszTicket = NULL, pwszProfile = NULL, pwszF = NULL; // use these when t&p come from qs BSTR QSAuth = NULL, QSProf = NULL, QSErrflag = NULL; BSTR bstrConsent = NULL; BSTR bstrNewAuth = NULL; BSTR bstrNewSecAuth = NULL; if (pBuffer) { TempSubStr tss(pBuffer, headerSizes[header_Authorization]); // has passport auth header if(strstr(pBuffer, PASSPORT_PROT14_A)) { // convert to wide ... int cch = MultiByteToWideChar(GetACP(), 0, pBuffer, -1, NULL, NULL); pwszBuf = (WCHAR*)LocalAlloc(LMEM_FIXED, (cch + 1) * sizeof (WCHAR)); if (NULL != pwszBuf) { if (0 != MultiByteToWideChar(GetACP(), 0, pBuffer, -1, pwszBuf, cch)) { BSTR bstrT = NULL; BSTR bstrP = NULL; GetTicketAndProfileFromHeader(pwszBuf, pwszTicket, pwszProfile, pwszF); // due to the fact that handleQueryStringData wants BSTRs we can't use // the direct pointers we just got, so we have to make copies. if( pwszTicket == NULL ) { bstrT = NULL; } else { bstrT = SysAllocString(pwszTicket); if (NULL == bstrT) { hr = E_OUTOFMEMORY; goto Cleanup; } } if( pwszProfile == NULL ) { bstrP = NULL; } else { bstrP = SysAllocString(pwszProfile); if (NULL == bstrP) { SysFreeString(bstrT); hr = E_OUTOFMEMORY; goto Cleanup; } } // make ticket and profile BSTRs PPTracePrint(PPTRACE_RAW, "PASSPORT_PROT14 Authorization <<< header:%ws, t:%ws, p:%ws, f:%ws", pwszBuf, pwszTicket, pwszProfile, pwszF); fParseSuccess = handleQueryStringData(bstrT, bstrP); if (pwszF) m_lNetworkError = _wtol(pwszF); SysFreeString(bstrT); SysFreeString(bstrP); } } } else { // not our header. BUGBUG could there be multiple headers ??? pBuffer = NULL; } } if (!pBuffer) { // an old client, let's try the QS if (QS) { // get ticket and profile ... // BUGBUG This could be optimized to avoid wide/short conversions, but later... GetQueryData(QS, &QSAuth, &QSProf, &QSErrflag); fParseSuccess = handleQueryStringData(QSAuth,QSProf); if(QSErrflag != NULL) m_lNetworkError = _wtol(QSErrflag); PPTracePrint(PPTRACE_RAW, "QueryString <<< t:%ws, p:%ws, f:%ws", QSAuth, QSProf, QSErrflag); } } if (fParseSuccess) { // // If we got secure ticket or profile, then // we need to re-encrypt the insecure version // before setting the cookie headers. // PPTracePrint(PPTRACE_RAW, "Authenticated"); // Set the cookies LPSTR ticketDomain = m_pRegistryConfig->getTicketDomain(); LPSTR profileDomain = m_pRegistryConfig->getProfileDomain(); LPSTR secureDomain = m_pRegistryConfig->getSecureDomain(); LPSTR ticketPath = m_pRegistryConfig->getTicketPath(); LPSTR profilePath = m_pRegistryConfig->getProfilePath(); LPSTR securePath = m_pRegistryConfig->getSecurePath(); VARIANT_BOOL persist; m_piTicket->get_HasSavedPassword(&persist); // MSPConsent cookie BOOL bSetConsent = (S_OK == IfConsentCookie(&bstrConsent)); // Build the cookie headers. // the authentication cookies BSTR auth, secAuth; // do not call SysFreeString on them, they are skin level copy if (S_OK == IfAlterAuthCookie(&bstrNewAuth, &bstrNewSecAuth)) { auth = bstrNewAuth; secAuth = bstrNewSecAuth; } else { if (pwszTicket) { auth = pwszTicket; } else { auth = QSAuth; } secAuth = NULL; } // build cookies for output BuildCookieHeaders(W2A(auth), (pwszProfile ? W2A(pwszProfile) : (QSProf ? W2A(QSProf) : NULL)), (bSetConsent ? W2A(bstrConsent) : NULL), (secAuth ? W2A(secAuth) : NULL), ticketDomain, ticketPath, profileDomain, profilePath, secureDomain, securePath, persist, pCookieHeader, bufSize, !m_pRegistryConfig->getNotUseHTTPOnly()); PPTracePrint(PPTRACE_RAW, "Cookie headers >>> %s",PPF_CHAR(pCookieHeader)); } if (QSAuth) FREE_BSTR(QSAuth); if (QSProf) FREE_BSTR(QSProf); if (QSErrflag) FREE_BSTR(QSErrflag); if (bstrNewAuth) { SysFreeString(bstrNewAuth); } if (bstrNewSecAuth) { SysFreeString(bstrNewSecAuth); } if (bstrConsent) { SysFreeString(bstrConsent); } // Now, check the cookies if (!m_fromQueryString) { BSTR CookieAuth = NULL, CookieProf = NULL, CookieConsent = NULL, CookieSecure = NULL; pBuffer = headerValues[header_Cookie]; if(pBuffer) { TempSubStr tss(pBuffer, headerSizes[header_Cookie]); GetCookie(pBuffer, "MSPAuth", &CookieAuth); // GetCookie has URLDecode in it GetCookie(pBuffer, "MSPProf", &CookieProf); GetCookie(pBuffer, "MSPConsent", &CookieConsent); GetCookie(pBuffer, "MSPSecAuth", &CookieSecure); handleCookieData(CookieAuth,CookieProf,CookieConsent,CookieSecure); PPTracePrint(PPTRACE_RAW, "Cookies <<< t:%ws, p:%ws, c:%ws, s:%ws", CookieAuth, CookieProf, CookieConsent, CookieSecure); if (CookieAuth) FREE_BSTR(CookieAuth); if (CookieProf) FREE_BSTR(CookieProf); if (CookieConsent) FREE_BSTR(CookieConsent); if (CookieSecure) FREE_BSTR(CookieSecure); } // we are not returning cookie info back if (pCookieHeader) *pCookieHeader = 0; *bufSize = 0; } PassportLog("CManager::OnStartPageHTTPRawEx Exit:\r\n"); hr = S_OK; Cleanup: if (NULL != pwszBuf) { // free the memory since we no longer need it LocalFree(pwszBuf); } return hr; } //=========================================================================== // // ContinueStartPageBody // -- when OnStartPageHTTPRaw returns PP_E_HTTP_BODY_REQUIRED, this func is expected to call // not doing anything for 2.0 release STDMETHODIMP CManager::ContinueStartPageHTTPRaw( /* [in] */ DWORD bodyLen, /* [size_is][in] */ byte *body, /* [out][in] */ DWORD *pBufSize, /* [size_is][out] */ LPSTR pRespHeaders, /* [out][in] */ DWORD *pRespBodyLen, /* [size_is][out] */ byte *pRespBody) { return E_NOTIMPL; } //=========================================================================== // // OnStartPageFilter -- for ISAPI filters // STDMETHODIMP CManager::OnStartPageFilter( LPBYTE pvPFC, DWORD* bufSize, LPSTR pCookieHeader ) { if (!pvPFC) return E_INVALIDARG; PHTTP_FILTER_CONTEXT pfc = (PHTTP_FILTER_CONTEXT) pvPFC; HRESULT hr = S_OK; PPTraceFunc<HRESULT> func(PPTRACE_FUNC, hr, "OnStartPageFilter", " <<< %lx, %lx, %d, %lx", pvPFC, bufSize, *bufSize, pCookieHeader); ATL::CAutoVectorPtr<CHAR> spheaders; ATL::CAutoVectorPtr<CHAR> spHTTPS; ATL::CAutoVectorPtr<CHAR> spQS; spheaders.Attach(GetServerVariablePFC(pfc, "ALL_RAW")); spHTTPS.Attach(GetServerVariablePFC(pfc, "HTTPS")); spQS.Attach(GetServerVariablePFC(pfc, "QUERY_STRING")); DWORD flags = 0; if((CHAR*)spHTTPS && lstrcmpiA("on", (CHAR*)spHTTPS) == 0) flags |= PASSPORT_HEADER_FLAGS_HTTPS; hr = OnStartPageHTTPRawEx(NULL, NULL, (CHAR*)spQS, NULL, (CHAR*)spheaders, flags, bufSize, pCookieHeader); m_pFC = pfc; return hr; } //=========================================================================== // // OnEndPage // STDMETHODIMP CManager::OnEndPage () { PassportLog("CManager::OnEndPage Enter:\r\n"); if (m_bOnStartPageCalled) { m_bOnStartPageCalled = false; // Release all interfaces m_piRequest.Release(); m_piResponse.Release(); } if (!m_piTicket || !m_piProfile) { return E_OUTOFMEMORY; } // Just in case... m_piTicket->put_unencryptedTicket(NULL); m_piProfile->put_unencryptedProfile(NULL); m_profileValid = m_ticketValid = VARIANT_FALSE; m_fromQueryString = false; if(m_pRegistryConfig) { m_pRegistryConfig->Release(); m_pRegistryConfig = NULL; } PassportLog("CManager::OnEndPage Exit:\r\n"); return S_OK; } //=========================================================================== // // AuthURL // // // Old API. Auth URL is pointing to the login server // STDMETHODIMP CManager::AuthURL( VARIANT vRU, VARIANT vTimeWindow, VARIANT vForceLogin, VARIANT vCoBrand, VARIANT vLCID, VARIANT vNameSpace, VARIANT vKPP, VARIANT vSecureLevel, BSTR *pAuthUrl) { CComVariant vEmpty(_T("")); return CommonAuthURL(vRU, vTimeWindow, vForceLogin, vCoBrand, vLCID, vNameSpace, vKPP, vSecureLevel, FALSE, vEmpty, pAuthUrl); } //=========================================================================== // // AuthURL2 // // // new API. return URL is to the login server // STDMETHODIMP CManager::AuthURL2( VARIANT vRU, VARIANT vTimeWindow, VARIANT vForceLogin, VARIANT vCoBrand, VARIANT vLCID, VARIANT vNameSpace, VARIANT vKPP, VARIANT vSecureLevel, BSTR *pAuthUrl) { CComVariant vEmpty(_T("")); return CommonAuthURL(vRU, vTimeWindow, vForceLogin, vCoBrand, vLCID, vNameSpace, vKPP, vSecureLevel, TRUE, vEmpty, pAuthUrl); } //=========================================================================== // // CommonAuthURL // // // AuthURL implementation // STDMETHODIMP CManager::CommonAuthURL( VARIANT vRU, VARIANT vTimeWindow, VARIANT vForceLogin, VARIANT vCoBrand, VARIANT vLCID, VARIANT vNameSpace, VARIANT vKPP, VARIANT vSecureLevel, BOOL fRedirToSelf, VARIANT vFunctionArea, // BSTR: e.g. Wireless BSTR *pAuthUrl) { USES_CONVERSION; time_t ct; WCHAR url[MAX_URL_LENGTH] = L""; VARIANT freeMe; UINT TimeWindow; int nKPP; VARIANT_BOOL ForceLogin = VARIANT_FALSE; ULONG ulSecureLevel = 0; BSTR CBT = NULL, returnUrl = NULL, bstrNameSpace = NULL; int hasCB, hasRU, hasLCID, hasTW, hasFL, hasNameSpace, hasKPP, hasUseSec; USHORT Lang; HRESULT hr = S_OK; BSTR bstrFunctionArea = NULL; int hasFunctionArea; CNexusConfig* cnc = NULL; PassportLog("CManager::CommonAuthURL Enter:\r\n"); if (!g_config) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); return PP_E_NOT_CONFIGURED; } if (!m_pRegistryConfig) m_pRegistryConfig = g_config->checkoutRegistryConfig(); if (!g_config->isValid() || !m_pRegistryConfig) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); return PP_E_NOT_CONFIGURED; } // Make sure args are of the right type if ((hasTW = GetIntArg(vTimeWindow, (int*) &TimeWindow)) == CV_BAD) return E_INVALIDARG; if ((hasFL = GetBoolArg(vForceLogin, &ForceLogin)) == CV_BAD) return E_INVALIDARG; if ((hasUseSec = GetIntArg(vSecureLevel, (int*)&ulSecureLevel)) == CV_BAD) return E_INVALIDARG; if ((hasLCID = GetShortArg(vLCID,&Lang)) == CV_BAD) return E_INVALIDARG; if ((hasKPP = GetIntArg(vKPP, &nKPP)) == CV_BAD) return E_INVALIDARG; hasCB = GetBstrArg(vCoBrand, &CBT); if (hasCB == CV_BAD) return E_INVALIDARG; if (hasCB == CV_FREE) { TAKEOVER_BSTR(CBT); } hasRU = GetBstrArg(vRU, &returnUrl); if (hasRU == CV_BAD) { if (hasCB == CV_FREE && CBT) FREE_BSTR(CBT); return E_INVALIDARG; } if (hasRU == CV_FREE) { TAKEOVER_BSTR(returnUrl); } hasNameSpace = GetBstrArg(vNameSpace, &bstrNameSpace); if (hasNameSpace == CV_BAD) { if (hasCB == CV_FREE && CBT) SysFreeString(CBT); if (hasRU == CV_FREE && returnUrl) SysFreeString(returnUrl); return E_INVALIDARG; } if (hasNameSpace == CV_FREE) { TAKEOVER_BSTR(bstrNameSpace); } if (hasNameSpace == CV_DEFAULT) { bstrNameSpace = m_pRegistryConfig->getNameSpace(); } // ************************************************** // Logging if (NULL != returnUrl) { PassportLog(" RU = %ws\n", returnUrl); } PassportLog(" TW = %X, SL = %X, L = %d, KPP = %X\r\n", TimeWindow, ulSecureLevel, Lang, nKPP); if (NULL != bstrNameSpace) { PassportLog(" NS = %ws\r\n", bstrNameSpace); } if (NULL != CBT) { PassportLog(" CBT = %ws\r\n", CBT); } // ************************************************** hasFunctionArea = GetBstrArg(vFunctionArea, &bstrFunctionArea); if (hasFunctionArea == CV_FREE) { TAKEOVER_BSTR(bstrFunctionArea); } if(hasUseSec == CV_DEFAULT) ulSecureLevel = m_pRegistryConfig->getSecureLevel(); WCHAR *szAUAttrName; if (SECURELEVEL_USE_HTTPS(ulSecureLevel)) szAUAttrName = L"AuthSecure"; else szAUAttrName = L"Auth"; BSTR szAttrName_FuncArea = NULL; if (bstrFunctionArea != NULL) { szAttrName_FuncArea = SysAllocStringLen(NULL, wcslen(bstrFunctionArea) + wcslen(szAUAttrName)); if (NULL == szAttrName_FuncArea) { hr = E_OUTOFMEMORY; goto Cleanup; } wcscpy(szAttrName_FuncArea, bstrFunctionArea); wcscat(szAttrName_FuncArea, szAUAttrName); } cnc = g_config->checkoutNexusConfig(); if (hasLCID == CV_DEFAULT) Lang = m_pRegistryConfig->getDefaultLCID(); if (hasKPP == CV_DEFAULT) nKPP = m_pRegistryConfig->getKPP(); VariantInit(&freeMe); if (!m_pRegistryConfig->DisasterModeP()) { // If I'm authenticated, get my domain specific url if (m_ticketValid && m_profileValid) { HRESULT hr = m_piProfile->get_ByIndex(MEMBERNAME_INDEX, &freeMe); if (hr != S_OK || freeMe.vt != VT_BSTR) { if (bstrFunctionArea) { cnc->getDomainAttribute(L"Default", szAttrName_FuncArea, sizeof(url) / sizeof(WCHAR), url, Lang); } if (*url == 0) // nothing is in URL string { cnc->getDomainAttribute(L"Default", szAUAttrName, sizeof(url) / sizeof(WCHAR), url, Lang); } } else { LPCWSTR psz = wcsrchr(freeMe.bstrVal, L'@'); if (bstrFunctionArea) { cnc->getDomainAttribute(psz ? psz+1 : L"Default", szAttrName_FuncArea, sizeof(url) / sizeof(WCHAR), url, Lang); } if (*url == 0) // nothing is in URL string { cnc->getDomainAttribute(psz ? psz+1 : L"Default", szAUAttrName, sizeof(url) / sizeof(WCHAR), url, Lang); } } } else { if (bstrFunctionArea) { cnc->getDomainAttribute(L"Default", szAttrName_FuncArea, sizeof(url) / sizeof(WCHAR), url, Lang); } } if(*url == 0) // nothing in URL string { cnc->getDomainAttribute(L"Default", szAUAttrName, sizeof(url) / sizeof(WCHAR), url, Lang); } } else lstrcpynW(url, m_pRegistryConfig->getDisasterUrl(), sizeof(url) / sizeof(WCHAR)); time(&ct); if (*url == L'\0') { hr = S_OK; goto Cleanup; } if (hasTW == CV_DEFAULT) TimeWindow = m_pRegistryConfig->getDefaultTicketAge(); if (hasFL == CV_DEFAULT) ForceLogin = m_pRegistryConfig->forceLoginP() ? VARIANT_TRUE : VARIANT_FALSE; if (hasCB == CV_DEFAULT) CBT = m_pRegistryConfig->getDefaultCoBrand(); if (hasRU == CV_DEFAULT) returnUrl = m_pRegistryConfig->getDefaultRU(); if (returnUrl == NULL) returnUrl = L""; if(ulSecureLevel == VARIANT_TRUE) // special case for backward compatible ulSecureLevel = k_iSeclevelSecureChannel; if ((TimeWindow != 0 && TimeWindow < PPM_TIMEWINDOW_MIN) || TimeWindow > PPM_TIMEWINDOW_MAX) { WCHAR buf[20]; _itow(TimeWindow,buf,10); AtlReportError(CLSID_Manager, (LPCOLESTR) PP_E_INVALID_TIMEWINDOWSTR, IID_IPassportManager, PP_E_INVALID_TIMEWINDOW); hr = PP_E_INVALID_TIMEWINDOW; goto Cleanup; } if (NULL == pAuthUrl) { hr = E_INVALIDARG; goto Cleanup; } *pAuthUrl = FormatAuthURL( url, m_pRegistryConfig->getSiteId(), returnUrl, TimeWindow, ForceLogin, m_pRegistryConfig->getCurrentCryptVersion(), ct, CBT, bstrNameSpace, nKPP, Lang, ulSecureLevel, m_pRegistryConfig, fRedirToSelf, IfCreateTPF() ); if (NULL == *pAuthUrl) { hr = E_OUTOFMEMORY; goto Cleanup; } hr = S_OK; Cleanup: if (szAttrName_FuncArea) { SysFreeString(szAttrName_FuncArea); } if (NULL != cnc) { cnc->Release(); } if (hasFunctionArea== CV_FREE && bstrFunctionArea) FREE_BSTR(bstrFunctionArea); if (hasRU == CV_FREE && returnUrl) FREE_BSTR(returnUrl); if (hasCB == CV_FREE && CBT) FREE_BSTR(CBT); // !!! need to confirmation if (hasNameSpace == CV_FREE && bstrNameSpace) FREE_BSTR(bstrNameSpace); VariantClear(&freeMe); PassportLog("CManager::CommonAuthURL Exit: %X\r\n", hr); return hr; } //=========================================================================== // // GetLoginChallenge // return AuthURL, // output parameter: tweener authHeader // // get AuthURL and AuthHeaders // STDMETHODIMP CManager::GetLoginChallenge(VARIANT vReturnUrl, VARIANT vTimeWindow, VARIANT vForceLogin, VARIANT vCoBrandTemplate, VARIANT vLCID, VARIANT vNameSpace, VARIANT vKPP, VARIANT vSecureLevel, VARIANT vExtraParams, BSTR* pAuthHeader ) { if (!pAuthHeader) return E_INVALIDARG; VARIANT vHeader; VariantInit(&vHeader); HRESULT hr = GetLoginChallengeInternal( vReturnUrl, vTimeWindow, vForceLogin, vCoBrandTemplate, vLCID, vNameSpace, vKPP, vSecureLevel, vExtraParams, &vHeader, NULL); if(S_OK == hr && V_VT(&vHeader) == VT_BSTR && V_BSTR(&vHeader)) { *pAuthHeader = V_BSTR(&vHeader); VariantInit(&vHeader); } else VariantClear(&vHeader); return hr; } //=========================================================================== // // GetLoginChallengeInternal // return AuthURL, // output parameter: tweener authHeader // // get AuthURL and AuthHeaders // STDMETHODIMP CManager::GetLoginChallengeInternal(VARIANT vReturnUrl, VARIANT vTimeWindow, VARIANT vForceLogin, VARIANT vCoBrandTemplate, VARIANT vLCID, VARIANT vNameSpace, VARIANT vKPP, VARIANT vSecureLevel, VARIANT vExtraParams, VARIANT *pAuthHeader, BSTR* pAuthVal ) { HRESULT hr = S_OK; if (pAuthVal) { *pAuthVal = NULL; } if (pAuthHeader) { V_BSTR(pAuthHeader) = NULL; } _bstr_t strAuthHeader; try { // format qs and WWW-Authenticate header .... _bstr_t strUrl, strRetUrl, strCBT, strNameSpace; UINT TimeWindow; int nKPP; time_t ct; VARIANT_BOOL ForceLogin; ULONG ulSecureLevel; WCHAR rgLCID[10]; hr = GetLoginParams(vReturnUrl, vTimeWindow, vForceLogin, vCoBrandTemplate, vLCID, vNameSpace, vKPP, vSecureLevel, strUrl, strRetUrl, TimeWindow, ForceLogin, ct, strCBT, strNameSpace, nKPP, ulSecureLevel, rgLCID); if (S_OK == hr && strUrl.length() != 0) { WCHAR szBuf[MAX_QS_LENGTH] = L""; // prepare redirect URL to the login server for // downlevel clients if (NULL == FormatAuthURLParameters(strUrl, m_pRegistryConfig->getSiteId(), strRetUrl, TimeWindow, ForceLogin, m_pRegistryConfig->getCurrentCryptVersion(), ct, strCBT, strNameSpace, nKPP, szBuf, sizeof(szBuf)/sizeof(WCHAR), 0, // lang does not matter .... ulSecureLevel, m_pRegistryConfig, FALSE, IfCreateTPF() )) // do not redirect to self! { hr = E_OUTOFMEMORY; goto Cleanup; } // insert the WWW-Authenticate header ... hr = FormatAuthHeaderFromParams(strUrl, strRetUrl, TimeWindow, ForceLogin, ct, strCBT, strNameSpace, nKPP, rgLCID, ulSecureLevel, strAuthHeader); if (S_OK != hr) { goto Cleanup; } // and add the extra .... BSTR strExtra = NULL; int res = GetBstrArg(vExtraParams, &strExtra); if (res != CV_BAD) { if (res == CV_DEFAULT) { strExtra = m_pRegistryConfig->getExtraParams(); } if (NULL != strExtra) { strAuthHeader += _bstr_t(L",") + strExtra; } } if (res == CV_FREE) ::SysFreeString(strExtra); // set return values if (pAuthHeader && (WCHAR*)strAuthHeader != NULL) { V_VT(pAuthHeader) = VT_BSTR; // TODO: should avoid this SysAllocString V_BSTR(pAuthHeader) = ::SysAllocString((WCHAR*)strAuthHeader); if (NULL == V_BSTR(pAuthHeader)) { hr = E_OUTOFMEMORY; goto Cleanup; } } if (pAuthVal) { *pAuthVal = ::SysAllocString(szBuf); if (NULL == *pAuthVal) { hr = E_OUTOFMEMORY; goto Cleanup; } } } } catch(...) { hr = E_OUTOFMEMORY; } Cleanup: return hr; } //=========================================================================== // // LoginUser // // // client logon method // vExtraParams: coBranding text is passed as cbtxt=cobrandingtext // the content of the input parameter should be UTF8 encoded, and // properly URL escapted before passing into this function // STDMETHODIMP CManager::LoginUser(VARIANT vReturnUrl, VARIANT vTimeWindow, VARIANT vForceLogin, VARIANT vCoBrandTemplate, VARIANT vLCID, VARIANT vNameSpace, VARIANT vKPP, VARIANT vSecureLevel, VARIANT vExtraParams) { // format qs and WWW-Authenticate header .... BSTR authURL = NULL; CComVariant authHeader; PassportLog("CManager::LoginUser Enter:\r\n"); HRESULT hr = GetLoginChallengeInternal( vReturnUrl, vTimeWindow, vForceLogin, vCoBrandTemplate, vLCID, vNameSpace, vKPP, vSecureLevel, vExtraParams, &authHeader, &authURL); if (S_OK == hr) { _ASSERT(V_VT(&authHeader) == VT_BSTR); _ASSERT(authURL); _ASSERT(V_BSTR(&authHeader)); // TODO: _bstr_t should be removed globaly in ppm if (m_piResponse) { m_piResponse->AddHeader(L"WWW-Authenticate", V_BSTR(&authHeader)); _bstr_t authURL1 = authURL; // and redirect! if (!m_bIsTweenerCapable) m_piResponse->Redirect(authURL1); else { // send a 401 m_piResponse->put_Status(L"401 Unauthorized"); m_piResponse->End(); } } else if (m_pECB || m_pFC) { // use ECB of Filter interfaces // 4k whould be enough .... char buffer[4096], status[25] = "302 Object moved", *psz=buffer, rgszTemplate[] = "Content-Type: text/html\r\nLocation: %ws\r\n" "Content-Length: 0\r\n" "WWW-Authenticate: %ws\r\n\r\n"; DWORD cbTotalLength = strlen(rgszTemplate); // // This is a hack fix, unfortunately we can succeed the call to GetChallengeInternal but // have a NULL authHeader, it seemed a bit risky to try and fix GetLoginParams which // seems to be the function which returns success when allocations are failing. // if ((NULL == V_BSTR(&authHeader)) || (NULL == (BSTR)authURL)) { hr = E_OUTOFMEMORY; goto Cleanup; } cbTotalLength += wcslen(V_BSTR(&authHeader)) + wcslen(authURL); if (m_bIsTweenerCapable) strcpy(status, "401 Unauthorized"); if (cbTotalLength >= sizeof(buffer)) { // if not ... // need to alloc psz = new CHAR[cbTotalLength]; _ASSERT(psz); } if (psz) { sprintf(psz, rgszTemplate, authURL, V_BSTR(&authHeader)); if (m_pECB) { // extension HSE_SEND_HEADER_EX_INFO Headers = { status, psz, strlen(status), strlen(psz), TRUE }; if (!m_pECB->ServerSupportFunction(m_pECB->ConnID, HSE_REQ_SEND_RESPONSE_HEADER_EX, &Headers, NULL, NULL)) { hr = HRESULT_FROM_WIN32(GetLastError()); } } else { // filter if (!m_pFC->ServerSupportFunction(m_pFC, SF_REQ_SEND_RESPONSE_HEADER, status, (ULONG_PTR) psz, NULL)) { hr = HRESULT_FROM_WIN32(GetLastError()); } } if (psz != buffer) // if we had to allocate delete[] psz; } else { hr = E_OUTOFMEMORY; } } } Cleanup: if (authURL) { SysFreeString(authURL); } PassportLog("CManager::LoginUser Exit: %X\r\n", hr); return hr; } //=========================================================================== // // IsAuthenticated -- determine if authenticated with specified SecureLevel // STDMETHODIMP CManager::IsAuthenticated( VARIANT vTimeWindow, VARIANT vForceLogin, VARIANT SecureLevel, VARIANT_BOOL *pVal) { HRESULT hr; ULONG TimeWindow; VARIANT_BOOL ForceLogin; ATL::CComVariant vSecureLevel; ULONG ulSecureLevel; int hasTW, hasFL, hasSecureLevel; PassportLog("CManager::IsAuthenticated Enter:\r\n"); PPTraceFunc<HRESULT> func(PPTRACE_FUNC, hr, "IsAuthenticated", "<<< %lx, %lx, %1x, %1x", V_I4(&vTimeWindow), V_I4(&vForceLogin), V_I4(&SecureLevel), pVal); if (!m_piTicket || !m_piProfile) { hr = E_OUTOFMEMORY; goto Cleanup; } if (!g_config) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); hr = PP_E_NOT_CONFIGURED; goto Cleanup; } if (!m_pRegistryConfig) m_pRegistryConfig = g_config->checkoutRegistryConfig(); if (!g_config->isValid() || !m_pRegistryConfig) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); hr = PP_E_NOT_CONFIGURED; goto Cleanup; } if ((hasTW = GetIntArg(vTimeWindow,(int*)&TimeWindow)) == CV_BAD) { hr = E_INVALIDARG; goto Cleanup; } if (hasTW == CV_DEFAULT) TimeWindow = m_pRegistryConfig->getDefaultTicketAge(); if ((hasFL = GetBoolArg(vForceLogin, &ForceLogin)) == CV_BAD) { hr = E_INVALIDARG; goto Cleanup; } if (hasFL == CV_DEFAULT) ForceLogin = m_pRegistryConfig->forceLoginP() ? VARIANT_TRUE : VARIANT_FALSE; hasSecureLevel = GetIntArg(SecureLevel, (int*)&ulSecureLevel); if(hasSecureLevel == CV_BAD) // try the legacy type VT_BOOL, map VARIANT_TRUE to SecureChannel { hr = E_INVALIDARG; goto Cleanup; } else if (hasSecureLevel == CV_DEFAULT) { ulSecureLevel = m_pRegistryConfig->getSecureLevel(); } if(ulSecureLevel == VARIANT_TRUE)// backward compatible with 1.3X { ulSecureLevel = k_iSeclevelSecureChannel; } vSecureLevel = ulSecureLevel; // Logging PassportLog(" TW = %X, SL = %X\r\n", TimeWindow, ulSecureLevel); hr = m_piTicket->get_IsAuthenticated(TimeWindow, ForceLogin, vSecureLevel, pVal); PPTracePrint(PPTRACE_RAW, "IsAuthenticated Params: %d, %d, %d, %lx", TimeWindow, ForceLogin, ulSecureLevel, *pVal); Cleanup: if(g_pPerf) { if (*pVal) { g_pPerf->incrementCounter(PM_AUTHSUCCESS_TOTAL); g_pPerf->incrementCounter(PM_AUTHSUCCESS_SEC); } else { g_pPerf->incrementCounter(PM_AUTHFAILURE_TOTAL); g_pPerf->incrementCounter(PM_AUTHFAILURE_SEC); } } else { _ASSERT(g_pPerf); } PassportLog("CManager::IsAuthenticated Exit: %X\r\n", hr); return hr; } //=========================================================================== // // LogoTag // // // old PM API. The URL is pointing to login server // STDMETHODIMP CManager::LogoTag( VARIANT vRU, VARIANT vTimeWindow, VARIANT vForceLogin, VARIANT vCoBrand, VARIANT vLCID, VARIANT vSecure, VARIANT vNameSpace, VARIANT vKPP, VARIANT vSecureLevel, BSTR *pVal) { return CommonLogoTag(vRU, vTimeWindow, vForceLogin, vCoBrand, vLCID, vSecure, vNameSpace, vKPP, vSecureLevel, FALSE, pVal); } //=========================================================================== // // LogoTag2 // // // new PM API. The URL is pointing to the partner site // STDMETHODIMP CManager::LogoTag2( VARIANT vRU, VARIANT vTimeWindow, VARIANT vForceLogin, VARIANT vCoBrand, VARIANT vLCID, VARIANT vSecure, VARIANT vNameSpace, VARIANT vKPP, VARIANT vSecureLevel, BSTR *pVal) { return CommonLogoTag(vRU, vTimeWindow, vForceLogin, vCoBrand, vLCID, vSecure, vNameSpace, vKPP, vSecureLevel, TRUE, pVal); } //=========================================================================== // // CommonLogoTag // STDMETHODIMP CManager::CommonLogoTag( VARIANT vRU, VARIANT vTimeWindow, VARIANT vForceLogin, VARIANT vCoBrand, VARIANT vLCID, VARIANT vSecure, VARIANT vNameSpace, VARIANT vKPP, VARIANT vSecureLevel, BOOL fRedirToSelf, BSTR *pVal) { time_t ct; ULONG TimeWindow; int nKPP; VARIANT_BOOL ForceLogin, bSecure = VARIANT_FALSE; ULONG ulSecureLevel = 0; BSTR CBT = NULL, returnUrl = NULL, NameSpace = NULL; int hasCB = -1, hasRU = -1, hasLCID, hasTW, hasFL, hasSec, hasUseSec, hasNameSpace = -1, hasKPP; USHORT Lang; LPWSTR pszNewURL = NULL; BSTR upd = NULL; CNexusConfig* cnc = NULL; HRESULT hr = S_OK; USES_CONVERSION; PassportLog("CManager::CommonLogoTag Enter:\r\n"); time(&ct); if (NULL == pVal) { hr = E_INVALIDARG; goto Cleanup; } *pVal = NULL; if (!g_config) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); hr = PP_E_NOT_CONFIGURED; goto Cleanup; } if (!m_pRegistryConfig) m_pRegistryConfig = g_config->checkoutRegistryConfig(); if (!g_config->isValid() || !m_pRegistryConfig) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); hr = PP_E_NOT_CONFIGURED; goto Cleanup; } // // parameters parsing ... // Make sure args are of the right type if ( ((hasTW = GetIntArg(vTimeWindow, (int*) &TimeWindow)) == CV_BAD) || ((hasFL = GetBoolArg(vForceLogin, &ForceLogin)) == CV_BAD) || ((hasSec = GetBoolArg(vSecure,&bSecure)) == CV_BAD) || // FUTURE: should introduce a new func: GetLongArg ... ((hasUseSec = GetIntArg(vSecureLevel,(int*)&ulSecureLevel)) == CV_BAD) || ((hasLCID = GetShortArg(vLCID,&Lang)) == CV_BAD) || ((hasKPP = GetIntArg(vKPP, &nKPP)) == CV_BAD) ) { hr = E_INVALIDARG; goto Cleanup; } hasCB = GetBstrArg(vCoBrand, &CBT); if (hasCB == CV_BAD) { hr = E_INVALIDARG; goto Cleanup; } if (hasCB == CV_FREE) { TAKEOVER_BSTR(CBT); } hasRU = GetBstrArg(vRU, &returnUrl); if (hasRU == CV_BAD) { hr = E_INVALIDARG; goto Cleanup; } if (hasRU == CV_FREE) { TAKEOVER_BSTR(returnUrl); } hasNameSpace = GetBstrArg(vNameSpace, &NameSpace); if (hasNameSpace == CV_BAD) { hr = E_INVALIDARG; goto Cleanup; } if (hasNameSpace == CV_FREE) { TAKEOVER_BSTR(NameSpace); } if (hasNameSpace == CV_DEFAULT) { NameSpace = m_pRegistryConfig->getNameSpace(); } WCHAR *szSIAttrName, *szSOAttrName; if (hasSec == CV_OK && bSecure == VARIANT_TRUE) { szSIAttrName = L"SecureSigninLogo"; szSOAttrName = L"SecureSignoutLogo"; } else { szSIAttrName = L"SigninLogo"; szSOAttrName = L"SignoutLogo"; } if(hasUseSec == CV_DEFAULT) ulSecureLevel = m_pRegistryConfig->getSecureLevel(); if(ulSecureLevel == VARIANT_TRUE) // special case for backward compatible ulSecureLevel = k_iSeclevelSecureChannel; WCHAR *szAUAttrName; if (SECURELEVEL_USE_HTTPS(ulSecureLevel)) szAUAttrName = L"AuthSecure"; else szAUAttrName = L"Auth"; cnc = g_config->checkoutNexusConfig(); if (NULL == cnc) { hr = PP_E_NOT_CONFIGURED; goto Cleanup; } if (hasLCID == CV_DEFAULT) Lang = m_pRegistryConfig->getDefaultLCID(); if (hasTW == CV_DEFAULT) TimeWindow = m_pRegistryConfig->getDefaultTicketAge(); if (hasFL == CV_DEFAULT) ForceLogin = m_pRegistryConfig->forceLoginP() ? VARIANT_TRUE : VARIANT_FALSE; if (hasCB == CV_DEFAULT) CBT = m_pRegistryConfig->getDefaultCoBrand(); if (hasRU == CV_DEFAULT) returnUrl = m_pRegistryConfig->getDefaultRU(); if (hasKPP == CV_DEFAULT) nKPP = m_pRegistryConfig->getKPP(); if (returnUrl == NULL) returnUrl = L""; // ************************************************** // Logging PassportLog(" RU = %ws\r\n", returnUrl); PassportLog(" TW = %X, SL = %X, L = %d, KPP = %X\r\n", TimeWindow, ulSecureLevel, Lang, nKPP); if (NULL != NameSpace) { PassportLog(" NS = %ws\r\n", NameSpace); } if (NULL != CBT) { PassportLog(" CBT = %ws\r\n", CBT); } // ************************************************** if ((TimeWindow != 0 && TimeWindow < PPM_TIMEWINDOW_MIN) || TimeWindow > PPM_TIMEWINDOW_MAX) { WCHAR buf[20]; _itow(TimeWindow,buf,10); AtlReportError(CLSID_Manager, (LPCOLESTR) PP_E_INVALID_TIMEWINDOWSTR, IID_IPassportManager, PP_E_INVALID_TIMEWINDOW); hr = PP_E_INVALID_TIMEWINDOW; goto Cleanup; } if (m_ticketValid) { LPCWSTR domain = NULL; WCHAR url[MAX_URL_LENGTH]; VARIANT freeMe; VariantInit(&freeMe); if (m_pRegistryConfig->DisasterModeP()) lstrcpynW(url, m_pRegistryConfig->getDisasterUrl(), sizeof(url)/sizeof(WCHAR)); else { if (m_profileValid && m_piProfile->get_ByIndex(MEMBERNAME_INDEX, &freeMe) == S_OK && freeMe.vt == VT_BSTR) { domain = wcsrchr(freeMe.bstrVal, L'@'); } cnc->getDomainAttribute(L"Default", L"Logout", sizeof(url)/sizeof(WCHAR), url, Lang); } // find out if there are any updates m_piProfile->get_updateString(&upd); if (upd) { TAKEOVER_BSTR(upd); // form the appropriate URL CCoCrypt* crypt = NULL; BSTR newCH = NULL; crypt = m_pRegistryConfig->getCurrentCrypt(); // IsValid ensures this is non-null if (!crypt->Encrypt(m_pRegistryConfig->getCurrentCryptVersion(), (LPSTR)upd, SysStringByteLen(upd), &newCH)) { AtlReportError(CLSID_Manager, (LPCOLESTR) PP_E_UNABLE_TO_ENCRYPTSTR, IID_IPassportManager, PP_E_UNABLE_TO_ENCRYPT); hr = PP_E_UNABLE_TO_ENCRYPT; goto Cleanup; } TAKEOVER_BSTR(newCH); WCHAR iurlbuf[1024] = L""; LPCWSTR iurl; cnc->getDomainAttribute(domain ? domain+1 : L"Default", L"Update", sizeof(iurlbuf) >> 1, iurlbuf, Lang); if(*iurlbuf == 0) { cnc->getDomainAttribute(L"Default", L"Update", sizeof(iurlbuf) >> 1, iurlbuf, Lang); } // convert this url to https as appropriate if(!bSecure) iurl = iurlbuf; else { LPWSTR psz; pszNewURL = SysAllocStringByteLen(NULL, (lstrlenW(iurlbuf) + 2) * sizeof(WCHAR)); if(pszNewURL) { psz = wcsstr(iurlbuf, L"http:"); if(psz != NULL) { psz += 4; lstrcpynW(pszNewURL, iurlbuf, (psz - iurlbuf + 1)); lstrcatW(pszNewURL, L"s"); lstrcatW(pszNewURL, psz); iurl = pszNewURL; } } } // This is a bit gross... we need to find the $1 in the update url... LPCWSTR ins = iurl ? (wcsstr(iurl, L"$1")) : NULL; // We'll break if null, but won't crash... if (ins && *url != L'\0') { *pVal = FormatUpdateLogoTag( url, m_pRegistryConfig->getSiteId(), returnUrl, TimeWindow, ForceLogin, m_pRegistryConfig->getCurrentCryptVersion(), ct, CBT, nKPP, iurl, bSecure, newCH, PM_LOGOTYPE_SIGNOUT, ulSecureLevel, m_pRegistryConfig, IfCreateTPF() ); } FREE_BSTR(newCH); } else { WCHAR iurl[MAX_URL_LENGTH] = L""; cnc->getDomainAttribute(L"Default", szSOAttrName, sizeof(iurl)/sizeof(WCHAR), iurl, Lang); if (*iurl != L'\0') { *pVal = FormatNormalLogoTag( url, m_pRegistryConfig->getSiteId(), returnUrl, TimeWindow, ForceLogin, m_pRegistryConfig->getCurrentCryptVersion(), ct, CBT, iurl, NULL, nKPP, PM_LOGOTYPE_SIGNOUT, Lang, ulSecureLevel, m_pRegistryConfig, fRedirToSelf, IfCreateTPF() ); } } VariantClear(&freeMe); if (NULL == *pVal) { hr = E_OUTOFMEMORY; goto Cleanup; } } else { WCHAR url[MAX_URL_LENGTH]; if (!(m_pRegistryConfig->DisasterModeP())) cnc->getDomainAttribute(L"Default", szAUAttrName, sizeof(url)/sizeof(WCHAR), url, Lang); else lstrcpynW(url, m_pRegistryConfig->getDisasterUrl(), sizeof(url)/sizeof(WCHAR)); WCHAR iurl[MAX_URL_LENGTH]; cnc->getDomainAttribute(L"Default", szSIAttrName, sizeof(iurl)/sizeof(WCHAR), iurl, Lang); if (*iurl != L'\0') { *pVal = FormatNormalLogoTag( url, m_pRegistryConfig->getSiteId(), returnUrl, TimeWindow, ForceLogin, m_pRegistryConfig->getCurrentCryptVersion(), ct, CBT, iurl, NameSpace, nKPP, PM_LOGOTYPE_SIGNIN, Lang, ulSecureLevel, m_pRegistryConfig, fRedirToSelf, IfCreateTPF() ); if (NULL == *pVal) { hr = E_OUTOFMEMORY; goto Cleanup; } } } Cleanup: if (NULL != cnc) { cnc->Release(); } if (NULL != upd) FREE_BSTR(upd); if (pszNewURL) SysFreeString(pszNewURL); if (hasRU == CV_FREE && returnUrl) FREE_BSTR(returnUrl); if (hasCB == CV_FREE && CBT) FREE_BSTR(CBT); if (hasNameSpace == CV_FREE && NameSpace) FREE_BSTR(NameSpace); PassportLog("CManager::CommonLogoTag Exit: %X\r\n", hr); return hr; } //=========================================================================== // // HasProfile -- if valid profile is present // STDMETHODIMP CManager::HasProfile(VARIANT var, VARIANT_BOOL *pVal) { LPWSTR profileName; PassportLog("CManager::HasProfile Enter:\r\n"); if (var.vt == (VT_BSTR | VT_BYREF)) profileName = *var.pbstrVal; else if (var.vt == VT_BSTR) profileName = var.bstrVal; else if (var.vt == (VT_VARIANT | VT_BYREF)) { return HasProfile(*(var.pvarVal), pVal); } else profileName = NULL; if ((!profileName) || (!_wcsicmp(profileName, L"core"))) { HRESULT ok = m_piProfile->get_IsValid(pVal); if (ok != S_OK) *pVal = VARIANT_FALSE; } else { VARIANT vAtt; VariantInit(&vAtt); PassportLog(" %ws\r\n", profileName); HRESULT ok = m_piProfile->get_Attribute(profileName, &vAtt); if (ok != S_OK) { if (g_pAlert) g_pAlert->report(PassportAlertInterface::ERROR_TYPE, PM_INVALID_PROFILETYPE); *pVal = VARIANT_FALSE; } else { if (vAtt.vt == VT_I4) *pVal = vAtt.lVal > 0 ? VARIANT_TRUE : VARIANT_FALSE; else if (vAtt.vt == VT_I2) *pVal = vAtt.iVal > 0 ? VARIANT_TRUE : VARIANT_FALSE; else { if (g_pAlert) g_pAlert->report(PassportAlertInterface::ERROR_TYPE, PM_INVALID_PROFILETYPE); } VariantClear(&vAtt); } } PassportLog("CManager::HasProfile Exit: %X\r\n", *pVal); return(S_OK); } //=========================================================================== // // get_HasTicket // STDMETHODIMP CManager::get_HasTicket(VARIANT_BOOL *pVal) { PassportLog("CManager::get_HasTicket:\r\n"); if(!pVal) return E_POINTER; *pVal = m_ticketValid ? VARIANT_TRUE : VARIANT_FALSE; return S_OK; } //=========================================================================== // // get_FromNetworkServer -- if it's authenticated by QueryString // STDMETHODIMP CManager::get_FromNetworkServer(VARIANT_BOOL *pVal) { PassportLog("CManager::get_FromNetworkServer:\r\n"); *pVal = (m_fromQueryString && m_ticketValid) ? VARIANT_TRUE : VARIANT_FALSE; return S_OK; } //=========================================================================== // // HasFlag -- obsolete function // STDMETHODIMP CManager::HasFlag(VARIANT var, VARIANT_BOOL *pVal) { PassportLog("CManager::HasFlag:\r\n"); AtlReportError(CLSID_Manager, PP_E_GETFLAGS_OBSOLETESTR, IID_IPassportManager, E_NOTIMPL); return E_NOTIMPL; } //=========================================================================== // // get_TicketAge -- get how long has passed since ticket was created // STDMETHODIMP CManager::get_TicketAge(int *pVal) { PassportLog("CManager::get_TicketAge:\r\n"); if (!m_piTicket) { return E_OUTOFMEMORY; } return m_piTicket->get_TicketAge(pVal); } //=========================================================================== // // get_TicketTime -- get when the ticket was created // STDMETHODIMP CManager::get_TicketTime(long *pVal) { PassportLog("CManager::get_TicketTime:\r\n"); if (!m_piTicket) { return E_OUTOFMEMORY; } return m_piTicket->get_TicketTime(pVal); } //=========================================================================== // // get_SignInTime -- get last signin time // STDMETHODIMP CManager::get_SignInTime(long *pVal) { PassportLog("CManager::get_SignInTime:\r\n"); if (!m_piTicket) { return E_OUTOFMEMORY; } return m_piTicket->get_SignInTime(pVal); } //=========================================================================== // // get_TimeSinceSignIn -- time passed since last signin // STDMETHODIMP CManager::get_TimeSinceSignIn(int *pVal) { PassportLog("CManager::get_TimeSinceSignIn:\r\n"); if (!m_piTicket) { return E_OUTOFMEMORY; } return m_piTicket->get_TimeSinceSignIn(pVal); } //=========================================================================== // // GetDomainAttribute -- return information defined in partner.xml file // STDMETHODIMP CManager::GetDomainAttribute(BSTR attributeName, VARIANT lcid, VARIANT domain, BSTR *pAttrVal) { HRESULT hr = S_OK; PassportLog("CManager::GetDomainAttribute Enter:\r\n"); if(attributeName == NULL || *attributeName == 0) return E_INVALIDARG; PassportLog(" %ws\r\n", attributeName); if (!g_config || !g_config->isValid()) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); return PP_E_NOT_CONFIGURED; } if (!m_pRegistryConfig) m_pRegistryConfig = g_config->checkoutRegistryConfig(); if (!m_pRegistryConfig) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); return PP_E_NOT_CONFIGURED; } LPWSTR d; BSTR dn = NULL; if (domain.vt == (VT_BSTR | VT_BYREF)) d = *domain.pbstrVal; else if (domain.vt == VT_BSTR) d = domain.bstrVal; else if (domain.vt == (VT_VARIANT | VT_BYREF)) { return GetDomainAttribute(attributeName, lcid, *(domain.pvarVal), pAttrVal); } else { // domain best be not filled in this case, that's why we reuse it here // if not, let dfmn generate the error HRESULT hr = DomainFromMemberName(domain, &dn); if (hr != S_OK) return hr; TAKEOVER_BSTR(dn); d = dn; } if (NULL != d) { PassportLog(" %ws\r\n", d); } CNexusConfig* cnc = g_config->checkoutNexusConfig(); USHORT sLcid = 0; VARIANT innerLC; VariantInit(&innerLC); if (lcid.vt != VT_ERROR && VariantChangeType(&innerLC, &lcid, 0, VT_UI2) == S_OK) sLcid = innerLC.iVal; else { sLcid = m_pRegistryConfig->getDefaultLCID(); // Check user profile if (!sLcid && m_profileValid) { m_piProfile->get_ByIndex(LANGPREF_INDEX, &innerLC); if (innerLC.vt == VT_I2 || innerLC.vt == VT_UI2) sLcid = innerLC.iVal; VariantClear(&innerLC); } } WCHAR data[PP_MAX_ATTRIBUTE_LENGTH] = L""; cnc->getDomainAttribute(d, attributeName, sizeof(data)/sizeof(WCHAR), data, sLcid); // try default domain if (!(*data) && (!d || !(*d) || lstrcmpiW(d, L"Default"))) { cnc->getDomainAttribute(L"Default", attributeName, sizeof(data)/sizeof(WCHAR), data, sLcid); } if (*data) { *pAttrVal = ALLOC_AND_GIVEAWAY_BSTR(data); } else { /* fix bug: 12102 -- for backward compitible, not to return error hr = E_INVALIDARG; */ *pAttrVal = NULL; } cnc->Release(); if (dn) FREE_BSTR(dn); PassportLog("CManager::GetDomainAttribute Exit: %X, %ws\r\n", hr, pAttrVal); return hr; } //=========================================================================== // // DomainFromMemberName -- returns domain name with given user id // STDMETHODIMP CManager::DomainFromMemberName(VARIANT var, BSTR *pDomainName) { HRESULT hr; LPWSTR psz, memberName; VARIANT intoVar; PassportLog("CManager::DomainFromMemberName Enter:\r\n"); VariantInit(&intoVar); if (var.vt == (VT_BSTR | VT_BYREF)) memberName = *var.pbstrVal; else if (var.vt == VT_BSTR) memberName = var.bstrVal; else if (var.vt == (VT_VARIANT | VT_BYREF)) { return DomainFromMemberName(*(var.pvarVal), pDomainName); } else { // Try to get it from the profile if (!m_profileValid) { *pDomainName = ALLOC_AND_GIVEAWAY_BSTR(L"Default"); return S_OK; } HRESULT hr = m_piProfile->get_Attribute(L"internalmembername", &intoVar); if (hr != S_OK) { *pDomainName = NULL; return hr; } if (VariantChangeType(&intoVar,&intoVar, 0, VT_BSTR) != S_OK) { AtlReportError(CLSID_Manager, L"PassportManager: Couldn't convert memberName to string. Call partner support.", IID_IPassportManager, E_FAIL); return E_FAIL; } memberName = intoVar.bstrVal; } if(memberName == NULL) { hr = E_POINTER; goto Cleanup; } PassportLog(" %ws\r\n", memberName); psz = wcsrchr(memberName, L'@'); if(psz == NULL) { // fix bug: 13380 // hr = E_INVALIDARG; // goto Cleanup; psz = L"@Default"; } psz++; *pDomainName = ALLOC_AND_GIVEAWAY_BSTR(psz); hr = S_OK; Cleanup: VariantClear(&intoVar); PassportLog("CManager::DomainFromMemberName Exit: %X\r\n", hr); if (S_OK == hr) { PassportLog(" %ws\r\n", *pDomainName); } return hr; } //=========================================================================== // // get_Profile -- get property from profile property bag // STDMETHODIMP CManager::get_Profile(BSTR attributeName, VARIANT *pVal) { HRESULT hr = m_piProfile->get_Attribute(attributeName,pVal); PassportLog("CManager::get_Profile: %ws\r\n", attributeName); if(hr == S_OK && pVal->vt != VT_EMPTY) { if(g_pPerf) { g_pPerf->incrementCounter(PM_VALIDPROFILEREQ_SEC); g_pPerf->incrementCounter(PM_VALIDPROFILEREQ_TOTAL); } else { _ASSERT(g_pPerf); } } return hr; } //=========================================================================== // // put_Profile -- put property in profile property bag -- obselete // STDMETHODIMP CManager::put_Profile(BSTR attributeName, VARIANT newVal) { if (!m_piProfile) { return E_OUTOFMEMORY; } PassportLog("CManager::put_Profile: %ws\r\n", attributeName); return m_piProfile->put_Attribute(attributeName,newVal); } //=========================================================================== // // get_HexPUID // STDMETHODIMP CManager::get_HexPUID(BSTR *pVal) { PassportLog("CManager::get_HexPUID:\r\n"); if(!pVal) return E_INVALIDARG; if (!m_piTicket) { return E_OUTOFMEMORY; } if(m_piTicket) return m_piTicket->get_MemberId(pVal); else { AtlReportError(CLSID_Manager, PP_E_INVALID_TICKETSTR, IID_IPassportManager, PP_E_INVALID_TICKET); return PP_E_INVALID_TICKET; } } //=========================================================================== // // get_PUID // STDMETHODIMP CManager::get_PUID(BSTR *pVal) { PassportLog("CManager::get_HexPUID:\r\n"); if(!pVal) return E_INVALIDARG; if(m_piTicket) { HRESULT hr = S_OK; WCHAR id[64] = L"0"; int l = 0; int h = 0; LARGE_INTEGER ui64; hr = m_piTicket->get_MemberIdLow(&l); if (S_OK != hr) return hr; hr = m_piTicket->get_MemberIdHigh(&h); if (S_OK != hr) return hr; ui64.HighPart = h; ui64.LowPart = l; _ui64tow(ui64.QuadPart, id, 10); *pVal = SysAllocString(id); if(*pVal == NULL) { hr = E_OUTOFMEMORY; } return hr; } else { AtlReportError(CLSID_Manager, PP_E_INVALID_TICKETSTR, IID_IPassportManager, PP_E_INVALID_TICKET); return PP_E_INVALID_TICKET; } } STDMETHODIMP CManager::get_Option( /* [in] */ BSTR name, /* [retval][out] */ VARIANT *pVal) { if (!name || _wcsicmp(name, L"iMode") != 0 || !pVal) return E_INVALIDARG; VariantCopy(pVal, (VARIANT*)&m_iModeOption); return S_OK; } STDMETHODIMP CManager::put_Option( /* [in] */ BSTR name, /* [in] */ VARIANT newVal) { // support only this option for now. if (!name || _wcsicmp(name, L"iMode") != 0) return E_INVALIDARG; m_iModeOption = newVal; return S_OK; } //=========================================================================== // // get_Ticket -- get new introduced ticket property from the bag. // STDMETHODIMP CManager::get_Ticket(BSTR attributeName, VARIANT *pVal) { if (!m_piTicket) { return E_OUTOFMEMORY; } return m_piTicket->GetProperty(attributeName,pVal); } //=========================================================================== // // LogoutURL -- returns LogoutURL with given parameters // STDMETHODIMP CManager::LogoutURL( /* [optional][in] */ VARIANT vRU, /* [optional][in] */ VARIANT vCoBrand, /* [optional][in] */ VARIANT lang_id, /* [optional][in] */ VARIANT Namespace, /* [optional][in] */ VARIANT bSecure, /* [retval][out] */ BSTR __RPC_FAR *pVal) { HRESULT hr = S_OK; VARIANT_BOOL bUseSecure = VARIANT_FALSE; BSTR CBT = NULL, returnUrl = NULL, bstrNameSpace = NULL; int hasCB, hasRU, hasLCID, hasNameSpace, hasUseSec; USHORT Lang; WCHAR nameSpace[MAX_PATH] = L""; bool bUrlFromSecureKey = false; WCHAR UrlBuf[MAX_URL_LENGTH] = L""; WCHAR retUrlBuf[MAX_URL_LENGTH] = L""; DWORD bufLen = MAX_URL_LENGTH; WCHAR qsLeadCh = L'?'; CNexusConfig* cnc = NULL; int iRet = 0; if (!pVal) return E_INVALIDARG; if (!g_config) { return PP_E_NOT_CONFIGURED; } cnc = g_config->checkoutNexusConfig(); if (!m_pRegistryConfig) m_pRegistryConfig = g_config->checkoutRegistryConfig(); if ((hasUseSec = GetBoolArg(bSecure, &bUseSecure)) == CV_BAD) { hr = E_INVALIDARG; goto Cleanup; } if ((hasLCID = GetShortArg(lang_id,&Lang)) == CV_BAD) { hr = E_INVALIDARG; goto Cleanup; } if (hasLCID == CV_DEFAULT) Lang = m_pRegistryConfig->getDefaultLCID(); hasCB = GetBstrArg(vCoBrand, &CBT); if (hasCB == CV_BAD) { hr = E_INVALIDARG; goto Cleanup; } hasRU = GetBstrArg(vRU, &returnUrl); if (hasRU == CV_BAD) { hr = E_INVALIDARG; goto Cleanup; } hasNameSpace = GetBstrArg(Namespace, &bstrNameSpace); if (hasNameSpace == CV_BAD) { hr = E_INVALIDARG; goto Cleanup; } // get the right URL -- namespace, secure // namespace if (!IsEmptyString(bstrNameSpace)) { if(0 == _snwprintf(nameSpace, sizeof(nameSpace) / sizeof(WCHAR), L"%s", bstrNameSpace)) { hr = HRESULT_FROM_WIN32(GetLastError()); if FAILED(hr) goto Cleanup; } } if (hasCB == CV_DEFAULT) CBT = m_pRegistryConfig->getDefaultCoBrand(); if (hasRU == CV_DEFAULT) returnUrl = m_pRegistryConfig->getDefaultRU(); if (returnUrl == NULL) returnUrl = L""; if (*nameSpace == 0) // 0 length string wcscpy(nameSpace, L"Default"); if(hasUseSec == CV_DEFAULT) { ULONG ulSecureLevel = m_pRegistryConfig->getSecureLevel(); bUseSecure = (SECURELEVEL_USE_HTTPS(ulSecureLevel)) ? VARIANT_TRUE : VARIANT_FALSE; } // secure if(bUseSecure == VARIANT_TRUE) { cnc->getDomainAttribute(nameSpace, L"LogoutSecure", sizeof(UrlBuf)/sizeof(WCHAR), UrlBuf, Lang); if (*UrlBuf != 0) { bUrlFromSecureKey = true; } } // insecure if (*UrlBuf == 0) { cnc->getDomainAttribute(nameSpace, L"Logout", sizeof(UrlBuf)/sizeof(WCHAR), UrlBuf, Lang); } // error case if(*UrlBuf == 0) { AtlReportError(CLSID_Profile, PP_E_LOGOUTURL_NOTDEFINEDSTR, IID_IPassportProfile, PP_E_LOGOUTURL_NOTDEFINED); hr = PP_E_LOGOUTURL_NOTDEFINED; goto Cleanup; } if(bUseSecure == VARIANT_TRUE && !bUrlFromSecureKey) // translate from http to https { if (_wcsnicmp(UrlBuf, L"http:", 5) == 0) // replace with HTTPS { memmove(UrlBuf + 5, UrlBuf + 4, sizeof(UrlBuf) - 5 * sizeof(WCHAR)); memcpy(UrlBuf, L"https", 5 * sizeof(WCHAR)); } } // us common function to append the thing one by one ... if (wcsstr(UrlBuf, L"?")) // ? already exists in the URL, use & to start qsLeadCh = L'&'; if (CBT) _snwprintf(retUrlBuf, sizeof(retUrlBuf) / sizeof(WCHAR), L"%s%cid=%-d&ru=%s&lcid=%-d&cb=%s", UrlBuf, qsLeadCh, m_pRegistryConfig->getSiteId(), returnUrl, Lang, CBT); else _snwprintf(retUrlBuf, sizeof(retUrlBuf) / sizeof(WCHAR), L"%s%cid=%-d&ru=%s&lcid=%-d", UrlBuf, qsLeadCh, m_pRegistryConfig->getSiteId(), returnUrl, Lang); *pVal = ALLOC_AND_GIVEAWAY_BSTR(retUrlBuf); Cleanup: if (NULL != cnc) { cnc->Release(); } return hr; } //=========================================================================== // // get_ProfileByIndex -- get property value by index of the property // STDMETHODIMP CManager::get_ProfileByIndex(int index, VARIANT *pVal) { HRESULT hr = m_piProfile->get_ByIndex(index,pVal); if(hr == S_OK && pVal->vt != VT_EMPTY) { if(g_pPerf) { g_pPerf->incrementCounter(PM_VALIDPROFILEREQ_SEC); g_pPerf->incrementCounter(PM_VALIDPROFILEREQ_TOTAL); } else { _ASSERT(g_pPerf); } } return hr; } //=========================================================================== // // put_ProfileByIndex -- put property value by index // STDMETHODIMP CManager::put_ProfileByIndex(int index, VARIANT newVal) { return m_piProfile->put_ByIndex(index,newVal); } //=========================================================================== // // handleQueryStringData -- authenticate with T & P from Query String // BOOL CManager::handleQueryStringData(BSTR a, BSTR p) { BOOL retVal; //whither to set cookies HRESULT hr; VARIANT vFalse; _variant_t vFlags; // // check for empty ticket // if (!a || !*a) return FALSE; if (!m_piTicket || !m_piProfile) { return FALSE; } hr = DecryptTicketAndProfile(a, p, FALSE, NULL, m_pRegistryConfig, m_piTicket, m_piProfile); if(hr != S_OK) { m_ticketValid = VARIANT_FALSE; m_profileValid = VARIANT_FALSE; retVal = FALSE; goto Cleanup; } VariantInit(&vFalse); vFalse.vt = VT_BOOL; vFalse.boolVal = VARIANT_FALSE; m_piTicket->get_IsAuthenticated(0, VARIANT_FALSE, vFalse, &m_ticketValid); if(!m_bSecureTransported) // secure bit should NOI set { if (S_OK == m_piTicket->GetProperty(ATTR_PASSPORTFLAGS, &vFlags)) { // the bit should NOT set if ( vFlags.vt == VT_I4 && (vFlags.lVal & k_ulFlagsSecuredTransportedTicket) != 0) m_ticketValid = VARIANT_FALSE; } } // let the ticket to valid if secure signin if(m_ticketValid) m_piTicket->DoSecureCheckInTicket(m_bSecureTransported); // profile stuff m_piProfile->get_IsValid(&m_profileValid); if (m_ticketValid) { m_fromQueryString = true; // Set the cookies if (!m_pRegistryConfig->setCookiesP()) { retVal = FALSE; goto Cleanup; } } else { retVal = FALSE; goto Cleanup; } retVal = TRUE; Cleanup: return retVal; } //=========================================================================== // // handleCookieData -- authenticate with cookies // BOOL CManager::handleCookieData( BSTR auth, BSTR prof, BSTR consent, BSTR secAuth ) { BOOL retVal; HRESULT hr; VARIANT vDoSecureCheck; VARIANT_BOOL bValid; _variant_t vFlags; // bail out on empty cookie if (!auth || !*auth) return FALSE; if (!m_piTicket || !m_piProfile) { return FALSE; } // the consent cookie if(consent != NULL && SysStringLen(consent) != 0) { hr = DecryptTicketAndProfile( auth, prof, !(m_pRegistryConfig->bInDA()), consent, m_pRegistryConfig, m_piTicket, m_piProfile); } else { // // If regular cookie domain/path is identical to consent cookie domain/path, then // MSPProf cookie is equivalent to consent cookie, and we should set m_bUsingConsentCookie // to true // BOOL bCheckConsentCookie = ( lstrcmpA(m_pRegistryConfig->getTicketDomain(), m_pRegistryConfig->getProfileDomain()) || lstrcmpA(m_pRegistryConfig->getTicketPath(), m_pRegistryConfig->getProfilePath()) ); hr = DecryptTicketAndProfile( auth, prof, !(m_pRegistryConfig->bInDA()) && bCheckConsentCookie, NULL, m_pRegistryConfig, m_piTicket, m_piProfile); } if(hr != S_OK) { m_ticketValid = VARIANT_FALSE; m_profileValid = VARIANT_FALSE; retVal = FALSE; goto Cleanup; } VariantInit(&vDoSecureCheck); vDoSecureCheck.vt = VT_BOOL; if(secAuth && secAuth[0] && m_bSecureTransported) { if(DoSecureCheck(secAuth, m_pRegistryConfig, m_piTicket) == S_OK) vDoSecureCheck.boolVal = VARIANT_TRUE; else vDoSecureCheck.boolVal = VARIANT_FALSE; } else vDoSecureCheck.boolVal = VARIANT_FALSE; m_piTicket->get_IsAuthenticated(0, VARIANT_FALSE, vDoSecureCheck, &m_ticketValid); // a partner cookie should not include the secure bit if (!m_pRegistryConfig->bInDA() && S_OK == m_piTicket->GetProperty(ATTR_PASSPORTFLAGS, &vFlags)) { // the bit should NOT set if ( vFlags.vt == VT_I4 && (vFlags.lVal & k_ulFlagsSecuredTransportedTicket) != 0) m_ticketValid = VARIANT_FALSE; } // for insecure case, the secure cookie should not come if(!m_bSecureTransported && (secAuth && secAuth[0])) // this should not come { m_ticketValid = VARIANT_FALSE; } // profile stuff m_piProfile->get_IsValid(&m_profileValid); if(!m_ticketValid) { retVal = FALSE; goto Cleanup; } retVal = TRUE; Cleanup: return retVal; } //=========================================================================== // // get_HasSavedPassword -- if users chooses to persiste cookies // STDMETHODIMP CManager::get_HasSavedPassword(VARIANT_BOOL *pVal) { if (!m_piTicket) { return E_OUTOFMEMORY; } PassportLog("CManager::get_HasSavedPassword:\r\n"); // TODO: using flags for this return m_piTicket->get_HasSavedPassword(pVal); } //=========================================================================== // // Commit -- post changes of profile back to the cookie // STDMETHODIMP CManager::Commit(BSTR *pNewProfileCookie) { PassportLog("CManager::Commit:\r\n"); if (!g_config) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); return PP_E_NOT_CONFIGURED; } if (!m_pRegistryConfig) m_pRegistryConfig = g_config->checkoutRegistryConfig(); if (!g_config->isValid() || !m_pRegistryConfig) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); return PP_E_NOT_CONFIGURED; } if (!m_piTicket || !m_piProfile) { return E_OUTOFMEMORY; } if (!m_ticketValid || !m_profileValid) { AtlReportError(CLSID_Manager, PP_E_IT_FOR_COMMITSTR, IID_IPassportManager, PP_E_INVALID_TICKET); return PP_E_INVALID_TICKET; } // Write new passport profile cookie... // return a safearray if we aren't used from ASP BSTR newP = NULL; HRESULT hr = m_piProfile->incrementVersion(); hr = m_piProfile->get_unencryptedProfile(&newP); TAKEOVER_BSTR(newP); if (hr != S_OK || newP == NULL) { AtlReportError(CLSID_Manager, L"PassportManager.Commit: unknown failure.", IID_IPassportManager, E_FAIL); return E_FAIL; } CCoCrypt* crypt = NULL; BSTR newCH = NULL; crypt = m_pRegistryConfig->getCurrentCrypt(); // IsValid ensures this is non-null if ((!crypt->Encrypt(m_pRegistryConfig->getCurrentCryptVersion(), (LPSTR)newP, SysStringByteLen(newP), &newCH)) || !newCH) { AtlReportError(CLSID_Manager, L"PassportManager.Commit: encryption failure.", IID_IPassportManager, E_FAIL); FREE_BSTR(newP); return E_FAIL; } FREE_BSTR(newP); TAKEOVER_BSTR(newCH); if (m_bOnStartPageCalled) { if (m_pRegistryConfig->setCookiesP()) { try { VARIANT_BOOL persist; _bstr_t domain; _bstr_t path; if (m_pRegistryConfig->getTicketPath()) path = m_pRegistryConfig->getTicketPath(); else path = L"/"; m_piTicket->get_HasSavedPassword(&persist); IRequestDictionaryPtr piCookies = m_piResponse->Cookies; VARIANT vtNoParam; VariantInit(&vtNoParam); vtNoParam.vt = VT_ERROR; vtNoParam.scode = DISP_E_PARAMNOTFOUND; IWriteCookiePtr piCookie = piCookies->Item[L"MSPProf"]; piCookie->Item[vtNoParam] = newCH; domain = m_pRegistryConfig->getTicketDomain(); if (domain.length()) piCookie->put_Domain(domain); if (persist) piCookie->put_Expires(g_dtExpire); piCookie->put_Path(path); } catch (...) { FREE_BSTR(newCH); return E_FAIL; } } } GIVEAWAY_BSTR(newCH); *pNewProfileCookie = newCH; if(g_pPerf) { g_pPerf->incrementCounter(PM_PROFILECOMMITS_SEC); g_pPerf->incrementCounter(PM_PROFILECOMMITS_TOTAL); } else { _ASSERT(g_pPerf); } return S_OK; } //=========================================================================== // // _Ticket -- ticket object property // STDMETHODIMP CManager::_Ticket(IPassportTicket** piTicket) { if (!m_piTicket) { return E_OUTOFMEMORY; } return m_piTicket->QueryInterface(IID_IPassportTicket,(void**)piTicket); } //=========================================================================== // // _Profile // STDMETHODIMP CManager::_Profile(IPassportProfile** piProfile) { return m_piProfile->QueryInterface(IID_IPassportProfile,(void**)piProfile); } //=========================================================================== // // DomainExists -- if a domain exists // STDMETHODIMP CManager::DomainExists( BSTR bstrDomainName, VARIANT_BOOL* pbExists ) { PassportLog("CManager::DomainExists Enter:\r\n"); if(!pbExists) return E_INVALIDARG; if(!bstrDomainName || (bstrDomainName[0] == L'\0')) return E_INVALIDARG; if(!g_config || !g_config->isValid()) { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); return PP_E_NOT_CONFIGURED; } CNexusConfig* cnc = g_config->checkoutNexusConfig(); *pbExists = cnc->DomainExists(bstrDomainName) ? VARIANT_TRUE : VARIANT_FALSE; cnc->Release(); PassportLog("CManager::DomainExists Exit:\r\n"); return S_OK; } //=========================================================================== // // get_Domains -- get a list of domains // STDMETHODIMP CManager::get_Domains(VARIANT *pArrayVal) { CNexusConfig* cnc = NULL; LPCWSTR* arr = NULL; int iArr = 0; HRESULT hr; PassportLog("CManager::get_Domains Enter:\r\n"); if (!pArrayVal) return E_INVALIDARG; if (!g_config || !g_config->isValid()) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); return PP_E_NOT_CONFIGURED; } cnc = g_config->checkoutNexusConfig(); arr = cnc->getDomains(&iArr); if (!arr || iArr == 0) { VariantClear(pArrayVal); hr = S_OK; goto Cleanup; } // Make a safearray with all the goods SAFEARRAYBOUND rgsabound; rgsabound.lLbound = 0; rgsabound.cElements = iArr; SAFEARRAY *sa = SafeArrayCreate(VT_VARIANT, 1, &rgsabound); if (!sa) { hr = E_OUTOFMEMORY; goto Cleanup; } VariantInit(pArrayVal); pArrayVal->vt = VT_ARRAY | VT_VARIANT; pArrayVal->parray = sa; VARIANT *vArray; SafeArrayAccessData(sa, (void**)&vArray); for (long i = 0; i < iArr; i++) { vArray[i].vt = VT_BSTR; vArray[i].bstrVal = ALLOC_AND_GIVEAWAY_BSTR(arr[i]); } SafeArrayUnaccessData(sa); hr = S_OK; Cleanup: if (arr) { delete[] arr; } if (NULL != cnc) { cnc->Release(); } PassportLog("CManager::DomainExists Exit:\r\n"); return hr; } //=========================================================================== // // get_Error -- get the error returned with &f query parameter // STDMETHODIMP CManager::get_Error(long* plError) { if(plError == NULL) return E_INVALIDARG; if(m_ticketValid) { if (!m_piTicket) { return E_OUTOFMEMORY; } m_piTicket->get_Error(plError); if(*plError == 0) *plError = m_lNetworkError; } else { *plError = m_lNetworkError; } PassportLog("CManager::get_Error: %X\r\n", *plError); return S_OK; } //=========================================================================== // // GetServerInfo // STDMETHODIMP CManager::GetServerInfo(BSTR *pbstrOut) { if (!g_config || !g_config->isValid()) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); return PP_E_NOT_CONFIGURED; } if(!m_pRegistryConfig) // This only happens when OnStartPage was not called first. m_pRegistryConfig = g_config->checkoutRegistryConfig(); if (!m_pRegistryConfig) { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); return PP_E_NOT_CONFIGURED; } CNexusConfig* cnc = g_config->checkoutNexusConfig(); BSTR bstrVersion = cnc->GetXMLInfo(); cnc->Release(); WCHAR wszName[MAX_COMPUTERNAME_LENGTH+1]; DWORD dwSize = MAX_COMPUTERNAME_LENGTH+1; GetComputerName(wszName, &dwSize); *pbstrOut = ALLOC_AND_GIVEAWAY_BSTR_LEN(NULL, wcslen(wszName) + ::SysStringLen(bstrVersion) + 2); if (NULL == *pbstrOut) { return E_OUTOFMEMORY; } wcscpy(*pbstrOut, wszName); BSTR p = *pbstrOut + wcslen(wszName); *p = L' '; wcsncpy(p+1, bstrVersion, ::SysStringLen(bstrVersion) + 1); return S_OK; } //=========================================================================== // // HaveConsent -- if the user has the specified consent // STDMETHODIMP CManager::HaveConsent( VARIANT_BOOL bNeedFullConsent, VARIANT_BOOL bNeedBirthdate, VARIANT_BOOL* pbHaveConsent) { HRESULT hr; ULONG flags = 0; VARIANT vBdayPrecision; BOOL bKid; BOOL bConsentSatisfied; ConsentStatusEnum ConsentCode = ConsentStatus_Unknown; VARIANT_BOOL bRequireConsentCookie; if(pbHaveConsent == NULL) { hr = E_POINTER; goto Cleanup; } *pbHaveConsent = VARIANT_FALSE; VariantInit(&vBdayPrecision); if (!m_piTicket || !m_piProfile || !m_pRegistryConfig) { hr = E_OUTOFMEMORY; goto Cleanup; } // If the cookies came in on the query string then there is no consent cookie yet so don't // require one. Otherwise check to see if the consent cookie domain or path is set // differently than the cookie domain or path. If so (and we aren't in the DA domain) then // the consent cookie is required. bRequireConsentCookie = !m_fromQueryString && ((lstrcmpA(m_pRegistryConfig->getTicketDomain(), m_pRegistryConfig->getProfileDomain()) || lstrcmpA(m_pRegistryConfig->getTicketPath(), m_pRegistryConfig->getProfilePath())) && !(m_pRegistryConfig->bInDA())) ? VARIANT_TRUE : VARIANT_FALSE; // // Get flags. // hr = m_piTicket->ConsentStatus(bRequireConsentCookie, &flags, &ConsentCode); // ignore return value if (hr != S_OK) { hr = S_OK; goto Cleanup; } // if old ticket, we get the consent info from the profile if(ConsentCode == ConsentStatus_NotDefinedInTicket) { // then we get from profile VARIANT_BOOL bValid; CComVariant vFlags; m_piProfile->get_IsValid(&bValid); if(bValid == VARIANT_FALSE) { hr = S_OK; goto Cleanup; } hr = m_piProfile->get_Attribute(L"flags", &vFlags); if(hr != S_OK) goto Cleanup; bKid = ((V_I4(&vFlags) & k_ulFlagsAccountType) == k_ulFlagsAccountTypeKid); } else bKid = ((flags & k_ulFlagsAccountType) == k_ulFlagsAccountTypeKid); // we should have the flags by now // // Do we have the requested level of consent? // bConsentSatisfied = bNeedFullConsent ? (flags & 0x60) == 0x40 : (flags & 0x60) != 0; if(bKid) { *pbHaveConsent = (bConsentSatisfied) ? VARIANT_TRUE : VARIANT_FALSE; } else { // // Make sure we have birthday if it was requested. // // no return value check need here, always returns S_OK. VARIANT_BOOL bValid; m_piProfile->get_IsValid(&bValid); // if profile is not valid, then we don't have consent. // return. if(bValid == VARIANT_FALSE) { hr = S_OK; goto Cleanup; } if(bNeedBirthdate) { hr = m_piProfile->get_Attribute(L"bday_precision", &vBdayPrecision); if(hr != S_OK) goto Cleanup; *pbHaveConsent = (vBdayPrecision.iVal != 0 && vBdayPrecision.iVal != 3) ? VARIANT_TRUE : VARIANT_FALSE; } else *pbHaveConsent = VARIANT_TRUE; } hr = S_OK; Cleanup: VariantClear(&vBdayPrecision); return hr; } //=========================================================================== // // checkForPassportChallenge // // // check the qs parameter. if challenge is requested, // build the auth header and redirect with a modified qs // BOOL CManager::checkForPassportChallenge(IRequestDictionaryPtr piServerVariables) { BOOL fReturn = FALSE; BSTR bstrBuf = NULL; // just need the request string _variant_t vtItemName, vtQueryString; vtItemName = L"QUERY_STRING"; piServerVariables->get_Item(vtItemName, &vtQueryString); if(vtQueryString.vt != VT_BSTR) vtQueryString.ChangeType(VT_BSTR); if (vtQueryString.bstrVal && *vtQueryString.bstrVal) { // check if pchg=1 is there. It is the first parameter .... PWSTR psz = wcsstr(vtQueryString.bstrVal, L"pchg=1"); if (psz) { // we are in business. reformat the URL, insert the headers and // redirect psz = wcsstr(psz, PPLOGIN_PARAM); _ASSERT(psz); if (psz) { psz += wcslen(PPLOGIN_PARAM); PWSTR pszEndLoginUrl = wcsstr(psz, L"&"); _ASSERT(pszEndLoginUrl); if (pszEndLoginUrl) { *pszEndLoginUrl = L'\0'; // unescape the URL // use temp buffer ... DWORD cch = wcslen(psz) + 1; bstrBuf = SysAllocStringLen(NULL, cch); if (NULL == bstrBuf) { goto Cleanup; } if(!InternetCanonicalizeUrl(psz, bstrBuf, &cch, ICU_DECODE | ICU_NO_ENCODE)) { // what else can be done ??? _ASSERT(FALSE); } else { // copy the unescaped URL to the orig buffer wcscpy(psz, (BSTR)bstrBuf); // set headers first ... // just use the qs param with some reformatting _bstr_t bstrHeader; if (HeaderFromQS(wcsstr(psz, L"?"), bstrHeader)) { m_piResponse->AddHeader(L"WWW-Authenticate", bstrHeader); // Url is ready, redirect ... m_piResponse->Redirect(psz); fReturn = TRUE; } } } } } } Cleanup: if (bstrBuf) { SysFreeString(bstrBuf); } return fReturn; } //=========================================================================== // // HeaderFromQS // // // given a queryString, format the www-authenticate header // BOOL CManager::HeaderFromQS(PWSTR pszQS, _bstr_t& bstrHeader) { // common header start ... bstrHeader = PASSPORT_PROT14; BOOL fSuccess = TRUE; BSTR signature = NULL; // advance thru any leading junk ... while(!iswalnum(*pszQS) && *pszQS) pszQS++; if (!*pszQS) { fSuccess = FALSE; goto Cleanup; } WCHAR rgszValue[1000]; // buffer large enough for most values ... PCWSTR psz = pszQS, pszNext = pszQS; while(TRUE) { // no param name is more than 10 .... WCHAR rgszName[10]; LONG cch = sizeof(rgszName)/sizeof(WCHAR); PCWSTR pszName = psz; while(*pszNext && *pszNext != L'&') pszNext++; // grab the next qsparam // name first while(*pszName != L'=' && pszName < pszNext) pszName++; _ASSERT(pszName != pszNext); // this should never happen if (pszName == pszNext) { // and if it does, skip this parameter and return FALSE ... fSuccess = FALSE; goto Cleanup; } else { PWSTR pszVal = rgszValue; ULONG cchVal; _ASSERT((pszName - psz) <= cch); wcsncpy(rgszName, psz, cch - 1); rgszName[cch - 1] = L'\0'; // next comes the value pszName++; cchVal = (pszNext - pszName); // note these are PWSTR pointers so the result is length in characters if (cchVal >= (sizeof(rgszValue) / sizeof(rgszValue[0])) ) { // have to allocate ... pszVal = new WCHAR[cchVal + 1]; if (!pszVal) { fSuccess = FALSE; goto Cleanup; } } // copy the value ... wcsncpy(pszVal, pszName, cchVal ); pszVal[cchVal] = L'\0'; // and insert in the header ... if (psz != pszQS) // this is not the first param bstrHeader += L","; else // first separator is a space ... bstrHeader += L" "; bstrHeader += _bstr_t(rgszName) + L"=" + pszVal; if (pszVal != rgszValue) // it was alloc'd delete[] pszVal; } // else '=' found // leave loop if (!*pszNext) break; psz = ++pszNext; } // while // sign the header // actually the signature is on the qs HRESULT hr = PartnerHash(m_pRegistryConfig, m_pRegistryConfig->getCurrentCryptVersion(), pszQS, wcslen(pszQS), &signature); if (S_OK == hr) { bstrHeader += _bstr_t(L",tpf=") + (BSTR)signature; } else { fSuccess = FALSE; } Cleanup: if (signature) { SysFreeString(signature); } return fSuccess; } //=========================================================================== // // FormatAuthHeaderFromParams // // // format WWW-Auth from parameters // STDMETHODIMP CManager::FormatAuthHeaderFromParams(PCWSTR pszLoginUrl, // unused for now PCWSTR pszRetUrl, ULONG ulTimeWindow, BOOL fForceLogin, time_t ct, PCWSTR pszCBT, // unused for now PCWSTR pszNamespace, int nKpp, PWSTR pszLCID, // tweener needs the LCID ULONG ulSecureLevel, _bstr_t& strHeader // return result ) { WCHAR temp[40]; // based on the spec ... // lcid is not really needed, however it is present when // header is created from qs and it's used strHeader = _bstr_t(PASSPORT_PROT14) + L" lc=" + pszLCID; // site= strHeader += "&id="; _ultow(m_pRegistryConfig->getSiteId(), temp, 10); strHeader += temp; // rtw= strHeader += "&tw="; _ultow(ulTimeWindow, temp, 10); strHeader += temp; if (fForceLogin) { strHeader += _bstr_t("&fs=1"); } if (pszNamespace && *pszNamespace) { strHeader += _bstr_t("&ns=") + pszNamespace; } // ru= strHeader += _bstr_t("&ru=") + pszRetUrl; // ct= _ultow(ct, temp, 10); strHeader += _bstr_t(L"&ct=") + temp; // kpp if (nKpp != -1) { _ultow(nKpp, temp, 10); strHeader += _bstr_t(L"&kpp=") + temp; } // key version and version _ultow(m_pRegistryConfig->getCurrentCryptVersion(), temp, 10); strHeader += _bstr_t(L"&kv=") + temp; strHeader += _bstr_t(L"&ver=") + GetVersionString(); // secure level if (ulSecureLevel) { strHeader += _bstr_t(L"&seclog=") + _ultow(ulSecureLevel, temp, 10); } // sign the header BSTR signature = NULL; PWSTR szStart = wcsstr(strHeader, L"lc="); HRESULT hr = PartnerHash(m_pRegistryConfig, m_pRegistryConfig->getCurrentCryptVersion(), szStart, strHeader.length() - (szStart - strHeader), &signature); // replace '&' with ',' BSTR psz = (BSTR)strHeader; while (*psz) { if (*psz == L'&') *psz = L','; psz++; } if (S_OK == hr) { strHeader += _bstr_t(L",tpf=") + (BSTR)signature; } if (signature) { SysFreeString(signature); } return hr; } //=========================================================================== // // GetLoginParams // // // common code to parse user's parameters // and get defaults from registry config // STDMETHODIMP CManager::GetLoginParams(VARIANT vRU, VARIANT vTimeWindow, VARIANT vForceLogin, VARIANT vCoBrand, VARIANT vLCID, VARIANT vNameSpace, VARIANT vKPP, VARIANT vSecureLevel, // these are the processed values _bstr_t& strUrl, _bstr_t& strReturnUrl, UINT& TimeWindow, VARIANT_BOOL& ForceLogin, time_t& ct, _bstr_t& strCBT, _bstr_t& strNameSpace, int& nKpp, ULONG& ulSecureLevel, PWSTR pszLCID) { USES_CONVERSION; LPCWSTR url; VARIANT freeMe; BSTR CBT = NULL, returnUrl = NULL, bstrNameSpace = NULL; int hasCB, hasRU, hasLCID, hasTW, hasFL, hasNameSpace, hasKPP, hasUseSec; USHORT Lang; CNexusConfig* cnc = NULL; HRESULT hr = S_OK; PassportLog("CManager::GetLoginParams Enter:\r\n"); if (!g_config) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); return PP_E_NOT_CONFIGURED; } if (!m_pRegistryConfig) m_pRegistryConfig = g_config->checkoutRegistryConfig(); if (!g_config->isValid() || !m_pRegistryConfig) // Guarantees config is non-null { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportManager, PP_E_NOT_CONFIGURED); return PP_E_NOT_CONFIGURED; } // Make sure args are of the right type if ((hasTW = GetIntArg(vTimeWindow, (int*) &TimeWindow)) == CV_BAD) return E_INVALIDARG; if ((hasFL = GetBoolArg(vForceLogin, &ForceLogin)) == CV_BAD) return E_INVALIDARG; if ((hasUseSec = GetIntArg(vSecureLevel, (int*)&ulSecureLevel)) == CV_BAD) return E_INVALIDARG; if ((hasLCID = GetShortArg(vLCID, &Lang)) == CV_BAD) return E_INVALIDARG; if ((hasKPP = GetIntArg(vKPP, &nKpp)) == CV_BAD) return E_INVALIDARG; hasCB = GetBstrArg(vCoBrand, &CBT); if (hasCB == CV_BAD) return E_INVALIDARG; strCBT = CBT; if (hasCB == CV_FREE) { TAKEOVER_BSTR(CBT); } hasRU = GetBstrArg(vRU, &returnUrl); if (hasRU == CV_BAD) { if (hasCB == CV_FREE && CBT) FREE_BSTR(CBT); return E_INVALIDARG; } strReturnUrl = returnUrl; if (hasRU == CV_FREE) { FREE_BSTR(returnUrl); } hasNameSpace = GetBstrArg(vNameSpace, &bstrNameSpace); if (hasNameSpace == CV_BAD) { if (hasCB == CV_FREE && CBT) FREE_BSTR(CBT); return E_INVALIDARG; } if (hasNameSpace == CV_OK) strNameSpace = bstrNameSpace; if (hasNameSpace == CV_FREE) { FREE_BSTR(bstrNameSpace); } if (hasNameSpace == CV_DEFAULT) { if (NULL == m_pRegistryConfig->getNameSpace()) { strNameSpace = L""; } else { strNameSpace = m_pRegistryConfig->getNameSpace(); } } if(hasUseSec == CV_DEFAULT) ulSecureLevel = m_pRegistryConfig->getSecureLevel(); if(ulSecureLevel == VARIANT_TRUE) // special case for backward compatible ulSecureLevel = k_iSeclevelSecureChannel; WCHAR *szAUAttrName; if (SECURELEVEL_USE_HTTPS(ulSecureLevel)) szAUAttrName = L"AuthSecure"; else szAUAttrName = L"Auth"; cnc = g_config->checkoutNexusConfig(); if (hasLCID == CV_DEFAULT) Lang = m_pRegistryConfig->getDefaultLCID(); if (hasKPP == CV_DEFAULT) nKpp = m_pRegistryConfig->getKPP(); // convert the LCID to str for tweener ... _itow((int)Lang, pszLCID, 10); VariantInit(&freeMe); // ************************************************** // Logging if (NULL != returnUrl) { PassportLog(" RU = %ws\r\n", returnUrl); } PassportLog(" TW = %X, SL = %X, L = %d, KPP = %X\r\n", TimeWindow, ulSecureLevel, Lang, nKpp); if (NULL != CBT) { PassportLog(" CBT = %ws\r\n", CBT); } // ************************************************** if (!m_pRegistryConfig->DisasterModeP()) { // If I'm authenticated, get my domain specific url WCHAR UrlBuf[MAX_URL_LENGTH]; if (m_ticketValid && m_profileValid) { HRESULT hr = m_piProfile->get_ByIndex(MEMBERNAME_INDEX, &freeMe); if (hr != S_OK || freeMe.vt != VT_BSTR) { cnc->getDomainAttribute(L"Default", szAUAttrName, sizeof(UrlBuf)/sizeof(WCHAR), UrlBuf, Lang); strUrl = UrlBuf; } else { LPCWSTR psz = wcsrchr(freeMe.bstrVal, L'@'); cnc->getDomainAttribute(psz ? psz+1 : L"Default", szAUAttrName, sizeof(UrlBuf)/sizeof(WCHAR), UrlBuf, Lang); strUrl = UrlBuf; } } if (strUrl.length() == 0) { cnc->getDomainAttribute(L"Default", szAUAttrName, sizeof(UrlBuf)/sizeof(WCHAR), UrlBuf, Lang); strUrl = UrlBuf; } } else strUrl = m_pRegistryConfig->getDisasterUrl(); _ASSERT(strUrl.length() != 0); time(&ct); if (hasTW == CV_DEFAULT) TimeWindow = m_pRegistryConfig->getDefaultTicketAge(); if (hasFL == CV_DEFAULT) ForceLogin = m_pRegistryConfig->forceLoginP() ? VARIANT_TRUE : VARIANT_FALSE; if (hasCB == CV_DEFAULT) strCBT = m_pRegistryConfig->getDefaultCoBrand(); if (hasRU == CV_DEFAULT) strReturnUrl = m_pRegistryConfig->getDefaultRU() ? m_pRegistryConfig->getDefaultRU() : L""; if ((TimeWindow != 0 && TimeWindow < PPM_TIMEWINDOW_MIN) || TimeWindow > PPM_TIMEWINDOW_MAX) { AtlReportError(CLSID_Manager, (LPCOLESTR) PP_E_INVALID_TIMEWINDOWSTR, IID_IPassportManager, PP_E_INVALID_TIMEWINDOW); hr = PP_E_INVALID_TIMEWINDOW; goto Cleanup; } Cleanup: if (NULL != cnc) { cnc->Release(); } VariantClear(&freeMe); PassportLog("CManager::GetLoginParams Exit: %X\r\n", hr); return hr; } //=========================================================================== // // GetTicketAndProfileFromHeader // // // get ticket & profile from auth header // params: // AuthHeader - [in/out] contents of HTTP_Authorization header // pszTicket - [out] ptr to the ticket part in the header // pszProfile -[out] ptr to the profile // pwszF - [out] ptr to error coming in the header // Auth header contents is changed as a side effect of the function // static VOID GetTicketAndProfileFromHeader(PWSTR pszAuthHeader, PWSTR& pszTicket, PWSTR& pszProfile, PWSTR& pszF) { // check for t=, p=, and f= if (pszAuthHeader && *pszAuthHeader) { // format is 'Authorization: from-PP='t=xxx&p=xxx' PWSTR pwsz = wcsstr(pszAuthHeader, L"from-PP"); if (pwsz) { // ticket and profile are enclosed in ''. Not very strict parsing indeed .... while(*pwsz != L'\'' && *pwsz) pwsz++; if (*pwsz++) { if (*pwsz == L'f') { pwsz++; if (*pwsz == L'=') { pwsz++; // error case pszF = pwsz; } } else { // ticket and profile ... _ASSERT(*pwsz == L't'); if (*pwsz == L't') { pwsz++; if (*pwsz == L'=') { pwsz++; pszTicket = pwsz; } } while(*pwsz != L'&' && *pwsz) pwsz++; if (*pwsz) *pwsz++ = L'\0'; if (*pwsz == L'p') { pwsz++; if (*pwsz == L'=') { pwsz++; pszProfile = pwsz; } } // finally remove the last ' } // set \0 terminator while(*pwsz != L'\'' && *pwsz) pwsz++; if (*pwsz) *pwsz = L'\0'; } } } } ///////////////////////////////////////////////////////////////////////////// // IPassportService implementation //=========================================================================== // // Initialize // STDMETHODIMP CManager::Initialize(BSTR configfile, IServiceProvider* p) { HRESULT hr; // Initialized? if (!g_config || !g_config->isValid()) // This calls UpdateNow if not yet initialized. { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportService, PP_E_NOT_CONFIGURED); hr = PP_E_NOT_CONFIGURED; goto Cleanup; } hr = S_OK; Cleanup: return hr; } //=========================================================================== // // Shutdown // STDMETHODIMP CManager::Shutdown() { return S_OK; } //=========================================================================== // // ReloadState // STDMETHODIMP CManager::ReloadState(IServiceProvider*) { HRESULT hr; // Initialize. if(!g_config || !g_config->PrepareUpdate(TRUE)) { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportService, PP_E_NOT_CONFIGURED); hr = PP_E_NOT_CONFIGURED; goto Cleanup; } hr = S_OK; Cleanup: return hr; } //=========================================================================== // // CommitState // STDMETHODIMP CManager::CommitState(IServiceProvider*) { HRESULT hr; // Finish the two phase update. if(!g_config || !g_config->CommitUpdate()) { AtlReportError(CLSID_Manager, PP_E_NOT_CONFIGUREDSTR, IID_IPassportService, PP_E_NOT_CONFIGURED); hr = PP_E_NOT_CONFIGURED; goto Cleanup; } hr = S_OK; Cleanup: return hr; } //=========================================================================== // // DumpState // STDMETHODIMP CManager::DumpState(BSTR* pbstrState) { ATLASSERT( *pbstrState != NULL && "CManager:DumpState - " "Are you sure you want to hand me a non-null BSTR?" ); if(!g_config) { return PP_E_NOT_CONFIGURED; } g_config->Dump(pbstrState); return S_OK; }
chocobearz/faisal-OHIF-Viewer-XNAT
platform/viewer/src/components/OHIFLogo/OHIFLogo.js
import './OHIFLogo.css'; import { Icon } from '@ohif/ui'; import React from 'react'; import { useIdleTimer } from 'react-idle-timer'; import { userManagement } from '@xnat-ohif/extension-xnat'; const timeout = 1000 * 60 * 10; let timeSinceLastApi = 0; function OHIFLogo() { const handleOnAction = () => { if (timeSinceLastApi >= timeout) { // invoke api call userManagement.getSessionID() .then(data => { console.log('Keeping the XNAT session alive...'); }) .catch(error => { console.warn(error); }); timeSinceLastApi = 0; reset(); } else { timeSinceLastApi = getElapsedTime(); } } const { getElapsedTime, reset } = useIdleTimer({ timeout: timeout, events: [ 'keydown', 'wheel', 'mousewheel', 'mousedown', 'touchstart', 'touchmove' ], onAction: handleOnAction, startOnMount: false, debounce: 500 }); let versionStr = ''; const version = window.config.version; if (version) { versionStr = `v${version.major}.${version.minor}.${version.patch}`; if (version.dev) { versionStr += `-${version.dev}` } if (version.build) { versionStr += ` build-${version.build}` } if (version.dev) { versionStr += t(' | INVESTIGATIONAL USE ONLY'); } } return ( <a target="_blank" // rel="noopener noreferrer" className="header-brand" // href="http://ohif.org" > <Icon name="xnat-ohif-logo" className="header-logo-image" /> <Icon name="xnat-icr-logo" className="header-logo-image-icr" /> <div className="header-logo-text"> OHIF-XNAT Viewer <span style={{ color: '#91b9cd', fontSize: 13 }}>|{` ${versionStr}`}</span> </div> {/*<Icon name="ohif-logo" className="header-logo-image" />*/} {/* Logo text would fit smaller displays at two lines: * * Open Health * Imaging Foundation * * Or as `OHIF` on really small displays */} {/*<Icon name="ohif-text-logo" className="header-logo-text" />*/} </a> ); } export default OHIFLogo;
Liooo/mobx-little-router
packages/mobx-little-router/src/util/delay.js
// @flow export default function delay(ms: number): Promise<void> { return new Promise(res => { setTimeout(() => res(), ms) }) }
Uniandes-isis2603/s1_puntosfidelidad
puntosfidelidad-web/src/main/java/co/edu/uniandes/csw/puntosfidelidad/dtos/FotoDTO.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 co.edu.uniandes.csw.puntosfidelidad.dtos; import co.edu.uniandes.csw.puntosfidelidad.entities.FotoEntity; import java.io.Serializable; /** * * @author cass_ */ public class FotoDTO implements Serializable{ private String url; /** * Constructor vaacío obligatorio para la inicialuzacón con Jax RS */ public FotoDTO(){ //Método vacio obligatorio. } /** * Constructor de un FotoDTO a paritir de un FotoEntity * @param entity */ public FotoDTO(FotoEntity entity){ this.url = entity.getURL(); } /** * Método wue convierte un entity en un DTO */ public FotoEntity toEntity(){ FotoEntity entity = new FotoEntity(); entity.setURL(this.url);; return entity; } /** * @return the url */ public String getUrl() { return url; } /** * @param url the url to set */ public void setUrl(String url) { this.url = url; } }
MarginC/kame
netbsd/sys/arch/sgimips/include/kcore.h
<filename>netbsd/sys/arch/sgimips/include/kcore.h /* $NetBSD: kcore.h,v 1.1 2000/06/14 15:39:58 soren Exp $ */ #include <mips/kcore.h>
pedwards95/Springboard_Class
Exercises/41.2-ReactRouterPatterns/DogFinder/src/DogDetails.js
<gh_stars>0 import React from "react"; import { Link, Redirect } from "react-router-dom"; import "./DogDetails.css"; function DogDetails({dog}) { if (!dog) return <Redirect to="/dogs"/> return ( <div className="DogDetails"> <div> <img src={dog.src} alt={dog.name} /> <h2>{dog.name}</h2> <h3>{dog.age} years old</h3> <ul> {dog.facts.map((fact, i) => ( <li key={i}>{fact}</li> ))} </ul> <Link to="/dogs">Go Back</Link> </div> </div> ); } export default DogDetails;
sfanous/IPTVProxy
iptv_proxy/logging.py
<gh_stars>1-10 import copy import hashlib import json import logging import logging.config import os import sys import traceback from watchdog.observers import Observer from iptv_proxy.constants import DEFAULT_LOGGING_CONFIGURATION from iptv_proxy.constants import LOGGING_CONFIGURATION_FILE_PATH from iptv_proxy.constants import TRACE from iptv_proxy.utilities import Utility from iptv_proxy.watchdog_events import FileSystemEventHandler logger = logging.getLogger(__name__) def trace(self, msg, *args, **kwargs): if self.isEnabledFor(TRACE): self._log(TRACE, msg, args, **kwargs) class Logging(object): __slots__ = [] _logging_configuration_file_watchdog_observer = None _log_file_path = None @classmethod def get_log_file_path(cls): return cls._log_file_path @classmethod def initialize_logging(cls, log_file_path): logging.addLevelName(TRACE, 'TRACE') logging.TRACE = TRACE logging.trace = trace logging.Logger.trace = trace try: cls.set_logging_configuration() except Exception: logging_configuration = copy.copy(DEFAULT_LOGGING_CONFIGURATION) logging_configuration['handlers']['rotating_file'][ 'filename' ] = log_file_path cls.set_logging_configuration(logging_configuration) @classmethod def join_logging_configuration_file_watchdog_observer(cls): cls._logging_configuration_file_watchdog_observer.join() @classmethod def set_logging_configuration(cls, configuration=None): if configuration is None: try: with open( LOGGING_CONFIGURATION_FILE_PATH, 'r' ) as logging_configuration_file: logging.config.dictConfig(json.load(logging_configuration_file)) except FileNotFoundError: raise except Exception: (type_, value_, traceback_) = sys.exc_info() logger.error( '\n'.join(traceback.format_exception(type_, value_, traceback_)) ) raise else: logging.config.dictConfig(configuration) @classmethod def set_log_file_path(cls, log_file_path): cls._log_file_path = log_file_path @classmethod def set_logging_level(cls, log_level): iptv_proxy_logger = logging.getLogger('iptv_proxy') iptv_proxy_logger.setLevel(log_level) for handler in iptv_proxy_logger.handlers: handler.setLevel(log_level) @classmethod def start_logging_configuration_file_watchdog_observer(cls): logging_configuration_event_handler = LoggingConfigurationEventHandler( LOGGING_CONFIGURATION_FILE_PATH ) cls._logging_configuration_file_watchdog_observer = Observer() cls._logging_configuration_file_watchdog_observer.schedule( logging_configuration_event_handler, os.path.dirname(LOGGING_CONFIGURATION_FILE_PATH), recursive=False, ) cls._logging_configuration_file_watchdog_observer.start() @classmethod def stop_logging_configuration_file_watchdog_observer(cls): cls._logging_configuration_file_watchdog_observer.stop() class LoggingConfigurationEventHandler(FileSystemEventHandler): def __init__(self, logging_configuration_file_path): FileSystemEventHandler.__init__(self, logging_configuration_file_path) def on_created(self, event): with self._lock: if os.path.normpath(event.src_path) == os.path.normpath(self._file_path): self._last_file_version_md5_checksum = hashlib.md5( Utility.read_file(self._file_path, in_binary=True) ).hexdigest() logger.debug( 'Detected creation of logging configuration file\n' 'Logging configuration file path => %s', self._file_path, ) Logging.set_logging_configuration() def on_deleted(self, event): with self._lock: if os.path.normpath(event.src_path) == os.path.normpath(self._file_path): self._last_file_version_md5_checksum = None logger.debug( 'Detected deletion of logging configuration file\n' 'Logging configuration file path => %s', self._file_path, ) logging_configuration = copy.copy(DEFAULT_LOGGING_CONFIGURATION) logging_configuration['handlers']['rotating_file'][ 'filename' ] = Logging.get_log_file_path() Logging.set_logging_configuration(logging_configuration) def on_modified(self, event): with self._lock: if self._do_process_on_modified_event(event): logger.debug( 'Detected changes in logging configuration file\n' 'Logging configuration file path => %s', self._file_path, ) Logging.set_logging_configuration()
bng11cal/DAF
node_modules/react-native/Libraries/CustomComponents/Navigator/NavigatorNavigationBar.js
/** * Copyright (c) 2015, Facebook, Inc. All rights reserved. * * Facebook, Inc. ("Facebook") owns all right, title and interest, including * all intellectual property and other proprietary rights, in and to the React * Native CustomComponents software (the "Software"). Subject to your * compliance with these terms, you are hereby granted a non-exclusive, * worldwide, royalty-free copyright license to (1) use and copy the Software; * and (2) reproduce and distribute the Software as part of your own software * ("Your Software"). Facebook reserves all rights not expressly granted to * you in this license agreement. * * THE SOFTWARE AND DOCUMENTATION, IF ANY, ARE PROVIDED "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 FACEBOOK OR ITS AFFILIATES, OFFICERS, DIRECTORS OR * EMPLOYEES 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 THE SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @providesModule NavigatorNavigationBar */ 'use strict'; var React = require('React'); var NavigatorNavigationBarStyles = require('NavigatorNavigationBarStyles'); var StaticContainer = require('StaticContainer.react'); var StyleSheet = require('StyleSheet'); var View = require('View'); var { Map } = require('immutable'); var COMPONENT_NAMES = ['Title', 'LeftButton', 'RightButton']; var navStatePresentedIndex = function(navState) { if (navState.presentedIndex !== undefined) { return navState.presentedIndex; } // TODO: rename `observedTopOfStack` to `presentedIndex` in `NavigatorIOS` return navState.observedTopOfStack; }; var NavigatorNavigationBar = React.createClass({ propTypes: { navigator: React.PropTypes.object, routeMapper: React.PropTypes.shape({ Title: React.PropTypes.func.isRequired, LeftButton: React.PropTypes.func.isRequired, RightButton: React.PropTypes.func.isRequired, }), navState: React.PropTypes.shape({ routeStack: React.PropTypes.arrayOf(React.PropTypes.object), presentedIndex: React.PropTypes.number, }), style: View.propTypes.style, }, statics: { Styles: NavigatorNavigationBarStyles, }, componentWillMount: function() { this._components = {}; this._descriptors = {}; COMPONENT_NAMES.forEach(componentName => { this._components[componentName] = new Map(); this._descriptors[componentName] = new Map(); }); }, _getReusableProps: function( /*string*/componentName, /*number*/index ) /*object*/ { if (!this._reusableProps) { this._reusableProps = {}; } var propStack = this._reusableProps[componentName]; if (!propStack) { propStack = this._reusableProps[componentName] = []; } var props = propStack[index]; if (!props) { props = propStack[index] = {style:{}}; } return props; }, _updateIndexProgress: function( /*number*/progress, /*number*/index, /*number*/fromIndex, /*number*/toIndex ) { var amount = toIndex > fromIndex ? progress : (1 - progress); var oldDistToCenter = index - fromIndex; var newDistToCenter = index - toIndex; var interpolate; if (oldDistToCenter > 0 && newDistToCenter === 0 || newDistToCenter > 0 && oldDistToCenter === 0) { interpolate = NavigatorNavigationBarStyles.Interpolators.RightToCenter; } else if (oldDistToCenter < 0 && newDistToCenter === 0 || newDistToCenter < 0 && oldDistToCenter === 0) { interpolate = NavigatorNavigationBarStyles.Interpolators.CenterToLeft; } else if (oldDistToCenter === newDistToCenter) { interpolate = NavigatorNavigationBarStyles.Interpolators.RightToCenter; } else { interpolate = NavigatorNavigationBarStyles.Interpolators.RightToLeft; } COMPONENT_NAMES.forEach(function (componentName) { var component = this._components[componentName].get(this.props.navState.routeStack[index]); var props = this._getReusableProps(componentName, index); if (component && interpolate[componentName](props.style, amount)) { component.setNativeProps(props); } }, this); }, updateProgress: function( /*number*/progress, /*number*/fromIndex, /*number*/toIndex ) { var max = Math.max(fromIndex, toIndex); var min = Math.min(fromIndex, toIndex); for (var index = min; index <= max; index++) { this._updateIndexProgress(progress, index, fromIndex, toIndex); } }, render: function() { var navState = this.props.navState; var components = COMPONENT_NAMES.map(function (componentName) { return navState.routeStack.map( this._getComponent.bind(this, componentName) ); }, this); return ( <View style={[styles.navBarContainer, this.props.style]}> {components} </View> ); }, _getComponent: function( /*string*/componentName, /*object*/route, /*number*/index ) /*?Object*/ { if (this._descriptors[componentName].includes(route)) { return this._descriptors[componentName].get(route); } var rendered = null; var content = this.props.routeMapper[componentName]( this.props.navState.routeStack[index], this.props.navigator, index, this.props.navState ); if (!content) { return null; } var initialStage = index === navStatePresentedIndex(this.props.navState) ? NavigatorNavigationBarStyles.Stages.Center : NavigatorNavigationBarStyles.Stages.Left; rendered = ( <View ref={(ref) => { this._components[componentName] = this._components[componentName].set(route, ref); }} style={initialStage[componentName]}> {content} </View> ); this._descriptors[componentName] = this._descriptors[componentName].set(route, rendered); return rendered; }, }); var styles = StyleSheet.create({ navBarContainer: { position: 'absolute', height: NavigatorNavigationBarStyles.General.TotalNavHeight, top: 0, left: 0, right: 0, backgroundColor: 'transparent', }, }); module.exports = NavigatorNavigationBar;
dmgerman/gerrit
javatests/com/google/gerrit/gpg/PublicKeyStoreTest.java
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|// Copyright (C) 2015 The Android Open Source Project end_comment begin_comment comment|// end_comment begin_comment comment|// Licensed under the Apache License, Version 2.0 (the "License"); end_comment begin_comment comment|// you may not use this file except in compliance with the License. end_comment begin_comment comment|// You may obtain a copy of the License at end_comment begin_comment comment|// end_comment begin_comment comment|// http://www.apache.org/licenses/LICENSE-2.0 end_comment begin_comment comment|// end_comment begin_comment comment|// Unless required by applicable law or agreed to in writing, software end_comment begin_comment comment|// distributed under the License is distributed on an "AS IS" BASIS, end_comment begin_comment comment|// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. end_comment begin_comment comment|// See the License for the specific language governing permissions and end_comment begin_comment comment|// limitations under the License. end_comment begin_package DECL|package|com.google.gerrit.gpg package|package name|com operator|. name|google operator|. name|gerrit operator|. name|gpg package|; end_package begin_import import|import static name|com operator|. name|google operator|. name|gerrit operator|. name|gpg operator|. name|PublicKeyStore operator|. name|REFS_GPG_KEYS import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|gerrit operator|. name|gpg operator|. name|PublicKeyStore operator|. name|keyIdToString import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|gerrit operator|. name|gpg operator|. name|PublicKeyStore operator|. name|keyObjectId import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|gerrit operator|. name|gpg operator|. name|PublicKeyStore operator|. name|keyToString import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|gerrit operator|. name|gpg operator|. name|testing operator|. name|TestKeys operator|. name|validKeyWithExpiration import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|gerrit operator|. name|gpg operator|. name|testing operator|. name|TestKeys operator|. name|validKeyWithSecondUserId import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|gerrit operator|. name|gpg operator|. name|testing operator|. name|TestKeys operator|. name|validKeyWithoutExpiration import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|gerrit operator|. name|gpg operator|. name|testing operator|. name|TestKeys operator|. name|validKeyWithoutExpirationWithSubkeyWithExpiration import|; end_import begin_import import|import static name|java operator|. name|nio operator|. name|charset operator|. name|StandardCharsets operator|. name|UTF_8 import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertEquals import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertFalse import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertTrue import|; end_import begin_import import|import name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|Iterators import|; end_import begin_import import|import name|com operator|. name|google operator|. name|gerrit operator|. name|gpg operator|. name|testing operator|. name|TestKey import|; end_import begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Arrays import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Iterator import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Set import|; end_import begin_import import|import name|java operator|. name|util operator|. name|TreeSet import|; end_import begin_import import|import name|org operator|. name|bouncycastle operator|. name|openpgp operator|. name|PGPPublicKey import|; end_import begin_import import|import name|org operator|. name|bouncycastle operator|. name|openpgp operator|. name|PGPPublicKeyRing import|; end_import begin_import import|import name|org operator|. name|bouncycastle operator|. name|openpgp operator|. name|PGPPublicKeyRingCollection import|; end_import begin_import import|import name|org operator|. name|eclipse operator|. name|jgit operator|. name|internal operator|. name|storage operator|. name|dfs operator|. name|DfsRepositoryDescription import|; end_import begin_import import|import name|org operator|. name|eclipse operator|. name|jgit operator|. name|internal operator|. name|storage operator|. name|dfs operator|. name|InMemoryRepository import|; end_import begin_import import|import name|org operator|. name|eclipse operator|. name|jgit operator|. name|junit operator|. name|TestRepository import|; end_import begin_import import|import name|org operator|. name|eclipse operator|. name|jgit operator|. name|lib operator|. name|CommitBuilder import|; end_import begin_import import|import name|org operator|. name|eclipse operator|. name|jgit operator|. name|lib operator|. name|ObjectReader import|; end_import begin_import import|import name|org operator|. name|eclipse operator|. name|jgit operator|. name|lib operator|. name|PersonIdent import|; end_import begin_import import|import name|org operator|. name|eclipse operator|. name|jgit operator|. name|lib operator|. name|RefUpdate import|; end_import begin_import import|import name|org operator|. name|eclipse operator|. name|jgit operator|. name|notes operator|. name|NoteMap import|; end_import begin_import import|import name|org operator|. name|eclipse operator|. name|jgit operator|. name|revwalk operator|. name|RevWalk import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Before import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_class DECL|class|PublicKeyStoreTest specifier|public class|class name|PublicKeyStoreTest block|{ DECL|field|tr specifier|private name|TestRepository argument_list|< name|? argument_list|> name|tr decl_stmt|; DECL|field|store specifier|private name|PublicKeyStore name|store decl_stmt|; annotation|@ name|Before DECL|method|setUp () specifier|public name|void name|setUp parameter_list|() throws|throws name|Exception block|{ name|tr operator|= operator|new name|TestRepository argument_list|<> argument_list|( operator|new name|InMemoryRepository argument_list|( operator|new name|DfsRepositoryDescription argument_list|( literal|"pubkeys" argument_list|) argument_list|) argument_list|) expr_stmt|; name|store operator|= operator|new name|PublicKeyStore argument_list|( name|tr operator|. name|getRepository argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|testKeyIdToString () specifier|public name|void name|testKeyIdToString parameter_list|() throws|throws name|Exception block|{ name|PGPPublicKey name|key init|= name|validKeyWithoutExpiration argument_list|() operator|. name|getPublicKey argument_list|() decl_stmt|; name|assertEquals argument_list|( literal|"46328A8C" argument_list|, name|keyIdToString argument_list|( name|key operator|. name|getKeyID argument_list|() argument_list|) argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|testKeyToString () specifier|public name|void name|testKeyToString parameter_list|() throws|throws name|Exception block|{ name|PGPPublicKey name|key init|= name|validKeyWithoutExpiration argument_list|() operator|. name|getPublicKey argument_list|() decl_stmt|; name|assertEquals argument_list|( literal|"46328A8C Testuser One<<EMAIL>>" operator|+ literal|" (04AE A7ED 2F82 1133 E5B1 28D1 ED06 25DC 4632 8A8C)" argument_list|, name|keyToString argument_list|( name|key argument_list|) argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|testKeyObjectId () specifier|public name|void name|testKeyObjectId parameter_list|() throws|throws name|Exception block|{ name|PGPPublicKey name|key init|= name|validKeyWithoutExpiration argument_list|() operator|. name|getPublicKey argument_list|() decl_stmt|; name|String name|objId init|= name|keyObjectId argument_list|( name|key operator|. name|getKeyID argument_list|() argument_list|) operator|. name|name argument_list|() decl_stmt|; name|assertEquals argument_list|( literal|"ed0625dc46328a8c000000000000000000000000" argument_list|, name|objId argument_list|) expr_stmt|; name|assertEquals argument_list|( name|keyIdToString argument_list|( name|key operator|. name|getKeyID argument_list|() argument_list|) operator|. name|toLowerCase argument_list|() argument_list|, name|objId operator|. name|substring argument_list|( literal|8 argument_list|, literal|16 argument_list|) argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|get () specifier|public name|void name|get parameter_list|() throws|throws name|Exception block|{ name|TestKey name|key1 init|= name|validKeyWithoutExpiration argument_list|() decl_stmt|; name|tr operator|. name|branch argument_list|( name|REFS_GPG_KEYS argument_list|) operator|. name|commit argument_list|() operator|. name|add argument_list|( name|keyObjectId argument_list|( name|key1 operator|. name|getKeyId argument_list|() argument_list|) operator|. name|name argument_list|() argument_list|, name|key1 operator|. name|getPublicKeyArmored argument_list|() argument_list|) operator|. name|create argument_list|() expr_stmt|; name|TestKey name|key2 init|= name|validKeyWithExpiration argument_list|() decl_stmt|; name|tr operator|. name|branch argument_list|( name|REFS_GPG_KEYS argument_list|) operator|. name|commit argument_list|() operator|. name|add argument_list|( name|keyObjectId argument_list|( name|key2 operator|. name|getKeyId argument_list|() argument_list|) operator|. name|name argument_list|() argument_list|, name|key2 operator|. name|getPublicKeyArmored argument_list|() argument_list|) operator|. name|create argument_list|() expr_stmt|; name|assertKeys argument_list|( name|key1 operator|. name|getKeyId argument_list|() argument_list|, name|key1 argument_list|) expr_stmt|; name|assertKeys argument_list|( name|key2 operator|. name|getKeyId argument_list|() argument_list|, name|key2 argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|getSubkeyReturnsMasterKey () specifier|public name|void name|getSubkeyReturnsMasterKey parameter_list|() throws|throws name|Exception block|{ name|TestKey name|key1 init|= name|validKeyWithoutExpirationWithSubkeyWithExpiration argument_list|() decl_stmt|; name|PGPPublicKeyRing name|keyRing init|= name|key1 operator|. name|getPublicKeyRing argument_list|() decl_stmt|; name|store operator|. name|add argument_list|( name|keyRing argument_list|) expr_stmt|; name|assertEquals argument_list|( name|RefUpdate operator|. name|Result operator|. name|NEW argument_list|, name|store operator|. name|save argument_list|( name|newCommitBuilder argument_list|() argument_list|) argument_list|) expr_stmt|; name|long name|masterKeyId init|= name|key1 operator|. name|getKeyId argument_list|() decl_stmt|; name|long name|subKeyId init|= literal|0 decl_stmt|; for|for control|( name|PGPPublicKey name|key range|: name|keyRing control|) block|{ if|if condition|( name|masterKeyId operator|!= name|subKeyId condition|) block|{ name|subKeyId operator|= name|key operator|. name|getKeyID argument_list|() expr_stmt|; block|} block|} name|assertKeys argument_list|( name|subKeyId argument_list|, name|key1 argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|getMultiple () specifier|public name|void name|getMultiple parameter_list|() throws|throws name|Exception block|{ name|TestKey name|key1 init|= name|validKeyWithoutExpiration argument_list|() decl_stmt|; name|TestKey name|key2 init|= name|validKeyWithExpiration argument_list|() decl_stmt|; name|tr operator|. name|branch argument_list|( name|REFS_GPG_KEYS argument_list|) operator|. name|commit argument_list|() operator|. name|add argument_list|( name|keyObjectId argument_list|( name|key1 operator|. name|getKeyId argument_list|() argument_list|) operator|. name|name argument_list|() argument_list|, name|key1 operator|. name|getPublicKeyArmored argument_list|() comment|// Mismatched for this key ID, but we can still read it out. operator|+ name|key2 operator|. name|getPublicKeyArmored argument_list|() argument_list|) operator|. name|create argument_list|() expr_stmt|; name|assertKeys argument_list|( name|key1 operator|. name|getKeyId argument_list|() argument_list|, name|key1 argument_list|, name|key2 argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|save () specifier|public name|void name|save parameter_list|() throws|throws name|Exception block|{ name|TestKey name|key1 init|= name|validKeyWithoutExpiration argument_list|() decl_stmt|; name|TestKey name|key2 init|= name|validKeyWithExpiration argument_list|() decl_stmt|; name|store operator|. name|add argument_list|( name|key1 operator|. name|getPublicKeyRing argument_list|() argument_list|) expr_stmt|; name|store operator|. name|add argument_list|( name|key2 operator|. name|getPublicKeyRing argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|RefUpdate operator|. name|Result operator|. name|NEW argument_list|, name|store operator|. name|save argument_list|( name|newCommitBuilder argument_list|() argument_list|) argument_list|) expr_stmt|; name|assertKeys argument_list|( name|key1 operator|. name|getKeyId argument_list|() argument_list|, name|key1 argument_list|) expr_stmt|; name|assertKeys argument_list|( name|key2 operator|. name|getKeyId argument_list|() argument_list|, name|key2 argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|saveAppendsToExistingList () specifier|public name|void name|saveAppendsToExistingList parameter_list|() throws|throws name|Exception block|{ name|TestKey name|key1 init|= name|validKeyWithoutExpiration argument_list|() decl_stmt|; name|TestKey name|key2 init|= name|validKeyWithExpiration argument_list|() decl_stmt|; name|tr operator|. name|branch argument_list|( name|REFS_GPG_KEYS argument_list|) operator|. name|commit argument_list|() comment|// Mismatched for this key ID, but we can still read it out. operator|. name|add argument_list|( name|keyObjectId argument_list|( name|key1 operator|. name|getKeyId argument_list|() argument_list|) operator|. name|name argument_list|() argument_list|, name|key2 operator|. name|getPublicKeyArmored argument_list|() argument_list|) operator|. name|create argument_list|() expr_stmt|; name|store operator|. name|add argument_list|( name|key1 operator|. name|getPublicKeyRing argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|RefUpdate operator|. name|Result operator|. name|FAST_FORWARD argument_list|, name|store operator|. name|save argument_list|( name|newCommitBuilder argument_list|() argument_list|) argument_list|) expr_stmt|; name|assertKeys argument_list|( name|key1 operator|. name|getKeyId argument_list|() argument_list|, name|key1 argument_list|, name|key2 argument_list|) expr_stmt|; try|try init|( name|ObjectReader name|reader init|= name|tr operator|. name|getRepository argument_list|() operator|. name|newObjectReader argument_list|() init|; name|RevWalk name|rw operator|= operator|new name|RevWalk argument_list|( name|reader argument_list|) init|) block|{ name|NoteMap name|notes init|= name|NoteMap operator|. name|read argument_list|( name|reader argument_list|, name|tr operator|. name|getRevWalk argument_list|() operator|. name|parseCommit argument_list|( name|tr operator|. name|getRepository argument_list|() operator|. name|exactRef argument_list|( name|REFS_GPG_KEYS argument_list|) operator|. name|getObjectId argument_list|() argument_list|) argument_list|) decl_stmt|; name|String name|contents init|= operator|new name|String argument_list|( name|reader operator|. name|open argument_list|( name|notes operator|. name|get argument_list|( name|keyObjectId argument_list|( name|key1 operator|. name|getKeyId argument_list|() argument_list|) argument_list|) argument_list|) operator|. name|getBytes argument_list|() argument_list|, name|UTF_8 argument_list|) decl_stmt|; name|String name|header init|= literal|"-----BEGIN PGP PUBLIC KEY BLOCK-----" decl_stmt|; name|int name|i1 init|= name|contents operator|. name|indexOf argument_list|( name|header argument_list|) decl_stmt|; name|assertTrue argument_list|( name|i1 operator|>= literal|0 argument_list|) expr_stmt|; name|int name|i2 init|= name|contents operator|. name|indexOf argument_list|( name|header argument_list|, name|i1 operator|+ name|header operator|. name|length argument_list|() argument_list|) decl_stmt|; name|assertTrue argument_list|( name|i2 operator|>= literal|0 argument_list|) expr_stmt|; block|} block|} annotation|@ name|Test DECL|method|updateExisting () specifier|public name|void name|updateExisting parameter_list|() throws|throws name|Exception block|{ name|TestKey name|key5 init|= name|validKeyWithSecondUserId argument_list|() decl_stmt|; name|PGPPublicKeyRing name|keyRing init|= name|key5 operator|. name|getPublicKeyRing argument_list|() decl_stmt|; name|PGPPublicKey name|key init|= name|keyRing operator|. name|getPublicKey argument_list|() decl_stmt|; name|PGPPublicKey name|subKey init|= name|keyRing operator|. name|getPublicKey argument_list|( name|Iterators operator|. name|get argument_list|( name|keyRing operator|. name|getPublicKeys argument_list|() argument_list|, literal|1 argument_list|) operator|. name|getKeyID argument_list|() argument_list|) decl_stmt|; name|store operator|. name|add argument_list|( name|keyRing argument_list|) expr_stmt|; name|assertEquals argument_list|( name|RefUpdate operator|. name|Result operator|. name|NEW argument_list|, name|store operator|. name|save argument_list|( name|newCommitBuilder argument_list|() argument_list|) argument_list|) expr_stmt|; name|assertUserIds argument_list|( name|store operator|. name|get argument_list|( name|key5 operator|. name|getKeyId argument_list|() argument_list|) operator|. name|iterator argument_list|() operator|. name|next argument_list|() argument_list|, literal|"<NAME><<EMAIL>>" argument_list|, literal|"foo:myId" argument_list|) expr_stmt|; name|keyRing operator|= name|PGPPublicKeyRing operator|. name|removePublicKey argument_list|( name|keyRing argument_list|, name|subKey argument_list|) expr_stmt|; name|keyRing operator|= name|PGPPublicKeyRing operator|. name|removePublicKey argument_list|( name|keyRing argument_list|, name|key argument_list|) expr_stmt|; name|key operator|= name|PGPPublicKey operator|. name|removeCertification argument_list|( name|key argument_list|, literal|"foo:myId" argument_list|) expr_stmt|; name|keyRing operator|= name|PGPPublicKeyRing operator|. name|insertPublicKey argument_list|( name|keyRing argument_list|, name|key argument_list|) expr_stmt|; name|keyRing operator|= name|PGPPublicKeyRing operator|. name|insertPublicKey argument_list|( name|keyRing argument_list|, name|subKey argument_list|) expr_stmt|; name|store operator|. name|add argument_list|( name|keyRing argument_list|) expr_stmt|; name|assertEquals argument_list|( name|RefUpdate operator|. name|Result operator|. name|FAST_FORWARD argument_list|, name|store operator|. name|save argument_list|( name|newCommitBuilder argument_list|() argument_list|) argument_list|) expr_stmt|; name|Iterator argument_list|< name|PGPPublicKeyRing argument_list|> name|keyRings init|= name|store operator|. name|get argument_list|( name|key operator|. name|getKeyID argument_list|() argument_list|) operator|. name|iterator argument_list|() decl_stmt|; name|keyRing operator|= name|keyRings operator|. name|next argument_list|() expr_stmt|; name|assertFalse argument_list|( name|keyRings operator|. name|hasNext argument_list|() argument_list|) expr_stmt|; name|assertUserIds argument_list|( name|keyRing argument_list|, literal|"<NAME><<EMAIL>>" argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|remove () specifier|public name|void name|remove parameter_list|() throws|throws name|Exception block|{ name|TestKey name|key1 init|= name|validKeyWithoutExpiration argument_list|() decl_stmt|; name|store operator|. name|add argument_list|( name|key1 operator|. name|getPublicKeyRing argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|RefUpdate operator|. name|Result operator|. name|NEW argument_list|, name|store operator|. name|save argument_list|( name|newCommitBuilder argument_list|() argument_list|) argument_list|) expr_stmt|; name|assertKeys argument_list|( name|key1 operator|. name|getKeyId argument_list|() argument_list|, name|key1 argument_list|) expr_stmt|; name|store operator|. name|remove argument_list|( name|key1 operator|. name|getPublicKey argument_list|() operator|. name|getFingerprint argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|RefUpdate operator|. name|Result operator|. name|FAST_FORWARD argument_list|, name|store operator|. name|save argument_list|( name|newCommitBuilder argument_list|() argument_list|) argument_list|) expr_stmt|; name|assertKeys argument_list|( name|key1 operator|. name|getKeyId argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|removeMasterKeyRemovesSubkey () specifier|public name|void name|removeMasterKeyRemovesSubkey parameter_list|() throws|throws name|Exception block|{ name|TestKey name|key1 init|= name|validKeyWithoutExpirationWithSubkeyWithExpiration argument_list|() decl_stmt|; name|PGPPublicKeyRing name|keyRing init|= name|key1 operator|. name|getPublicKeyRing argument_list|() decl_stmt|; name|store operator|. name|add argument_list|( name|keyRing argument_list|) expr_stmt|; name|assertEquals argument_list|( name|RefUpdate operator|. name|Result operator|. name|NEW argument_list|, name|store operator|. name|save argument_list|( name|newCommitBuilder argument_list|() argument_list|) argument_list|) expr_stmt|; name|long name|masterKeyId init|= name|key1 operator|. name|getKeyId argument_list|() decl_stmt|; name|long name|subKeyId init|= literal|0 decl_stmt|; for|for control|( name|PGPPublicKey name|key range|: name|keyRing control|) block|{ if|if condition|( name|masterKeyId operator|!= name|subKeyId condition|) block|{ name|subKeyId operator|= name|key operator|. name|getKeyID argument_list|() expr_stmt|; block|} block|} name|store operator|. name|remove argument_list|( name|key1 operator|. name|getPublicKey argument_list|() operator|. name|getFingerprint argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|RefUpdate operator|. name|Result operator|. name|FAST_FORWARD argument_list|, name|store operator|. name|save argument_list|( name|newCommitBuilder argument_list|() argument_list|) argument_list|) expr_stmt|; name|assertKeys argument_list|( name|masterKeyId argument_list|) expr_stmt|; name|assertKeys argument_list|( name|subKeyId argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|removeNonexisting () specifier|public name|void name|removeNonexisting parameter_list|() throws|throws name|Exception block|{ name|TestKey name|key1 init|= name|validKeyWithoutExpiration argument_list|() decl_stmt|; name|store operator|. name|add argument_list|( name|key1 operator|. name|getPublicKeyRing argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|RefUpdate operator|. name|Result operator|. name|NEW argument_list|, name|store operator|. name|save argument_list|( name|newCommitBuilder argument_list|() argument_list|) argument_list|) expr_stmt|; name|TestKey name|key2 init|= name|validKeyWithExpiration argument_list|() decl_stmt|; name|store operator|. name|remove argument_list|( name|key2 operator|. name|getPublicKey argument_list|() operator|. name|getFingerprint argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|RefUpdate operator|. name|Result operator|. name|NO_CHANGE argument_list|, name|store operator|. name|save argument_list|( name|newCommitBuilder argument_list|() argument_list|) argument_list|) expr_stmt|; name|assertKeys argument_list|( name|key1 operator|. name|getKeyId argument_list|() argument_list|, name|key1 argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|addThenRemove () specifier|public name|void name|addThenRemove parameter_list|() throws|throws name|Exception block|{ name|TestKey name|key1 init|= name|validKeyWithoutExpiration argument_list|() decl_stmt|; name|store operator|. name|add argument_list|( name|key1 operator|. name|getPublicKeyRing argument_list|() argument_list|) expr_stmt|; name|store operator|. name|remove argument_list|( name|key1 operator|. name|getPublicKey argument_list|() operator|. name|getFingerprint argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|RefUpdate operator|. name|Result operator|. name|NO_CHANGE argument_list|, name|store operator|. name|save argument_list|( name|newCommitBuilder argument_list|() argument_list|) argument_list|) expr_stmt|; name|assertKeys argument_list|( name|key1 operator|. name|getKeyId argument_list|() argument_list|) expr_stmt|; block|} DECL|method|assertKeys (long keyId, TestKey... expected) specifier|private name|void name|assertKeys parameter_list|( name|long name|keyId parameter_list|, name|TestKey modifier|... name|expected parameter_list|) throws|throws name|Exception block|{ name|Set argument_list|< name|String argument_list|> name|expectedStrings init|= operator|new name|TreeSet argument_list|<> argument_list|() decl_stmt|; for|for control|( name|TestKey name|k range|: name|expected control|) block|{ name|expectedStrings operator|. name|add argument_list|( name|keyToString argument_list|( name|k operator|. name|getPublicKey argument_list|() argument_list|) argument_list|) expr_stmt|; block|} name|PGPPublicKeyRingCollection name|actual init|= name|store operator|. name|get argument_list|( name|keyId argument_list|) decl_stmt|; name|Set argument_list|< name|String argument_list|> name|actualStrings init|= operator|new name|TreeSet argument_list|<> argument_list|() decl_stmt|; for|for control|( name|PGPPublicKeyRing name|k range|: name|actual control|) block|{ name|actualStrings operator|. name|add argument_list|( name|keyToString argument_list|( name|k operator|. name|getPublicKey argument_list|() argument_list|) argument_list|) expr_stmt|; block|} name|assertEquals argument_list|( name|expectedStrings argument_list|, name|actualStrings argument_list|) expr_stmt|; block|} DECL|method|assertUserIds (PGPPublicKeyRing keyRing, String... expected) specifier|private name|void name|assertUserIds parameter_list|( name|PGPPublicKeyRing name|keyRing parameter_list|, name|String modifier|... name|expected parameter_list|) throws|throws name|Exception block|{ name|List argument_list|< name|String argument_list|> name|actual init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; name|Iterator argument_list|< name|String argument_list|> name|userIds init|= name|store operator|. name|get argument_list|( name|keyRing operator|. name|getPublicKey argument_list|() operator|. name|getKeyID argument_list|() argument_list|) operator|. name|iterator argument_list|() operator|. name|next argument_list|() operator|. name|getPublicKey argument_list|() operator|. name|getUserIDs argument_list|() decl_stmt|; while|while condition|( name|userIds operator|. name|hasNext argument_list|() condition|) block|{ name|actual operator|. name|add argument_list|( name|userIds operator|. name|next argument_list|() argument_list|) expr_stmt|; block|} name|assertEquals argument_list|( name|Arrays operator|. name|asList argument_list|( name|expected argument_list|) argument_list|, name|actual argument_list|) expr_stmt|; block|} DECL|method|newCommitBuilder () specifier|private name|CommitBuilder name|newCommitBuilder parameter_list|() block|{ name|CommitBuilder name|cb init|= operator|new name|CommitBuilder argument_list|() decl_stmt|; name|PersonIdent name|ident init|= operator|new name|PersonIdent argument_list|( literal|"<NAME>" argument_list|, literal|"<EMAIL>" argument_list|) decl_stmt|; name|cb operator|. name|setAuthor argument_list|( name|ident argument_list|) expr_stmt|; name|cb operator|. name|setCommitter argument_list|( name|ident argument_list|) expr_stmt|; return|return name|cb return|; block|} block|} end_class end_unit
Vyraax/PXL
PXL/src/ui/shapes/rect.cpp
#include "rect.h" Rect::Rect(const glm::vec2& position, const glm::vec2& size) : m_position(position), m_size(size) { } bool Rect::intersects(const glm::vec2& point) { return point.x > m_position.x && point.x < m_position.x + m_size.x && point.y > m_position.y && point.y < m_position.y + m_size.y; } Rect::~Rect() { }
deepcrawler/TVStreamerLib
core/src/com/TVCastLib/discovery/DiscoveryProviderListener.java
<gh_stars>1-10 /* * DiscoveryProviderListener * TVCastLib * * Copyright (c) 2014 <NAME>. * Created by <NAME> on 19 Jan 2014 * */ package com.TVCastLib.discovery; import com.TVCastLib.service.command.ServiceCommandError; import com.TVCastLib.service.config.ServiceDescription; /** * The DiscoveryProviderListener is mechanism for passing service information to the DiscoveryManager. You likely will not be using the DiscoveryProviderListener class directly, as DiscoveryManager acts as a listener to all of the DiscoveryProviders. */ public interface DiscoveryProviderListener { /** * This method is called when the DiscoveryProvider discovers a service that matches one of its DeviceService filters. The ServiceDescription is created and passed to the listener (which should be the DiscoveryManager). The ServiceDescription is used to create a DeviceService, which is then attached to a ConnectableDevice object. * * @param provider DiscoveryProvider that found the service * @param description ServiceDescription of the service that was found */ public void onServiceAdded(DiscoveryProvider provider, ServiceDescription serviceDescription); /** * This method is called when the DiscoveryProvider's internal mechanism loses reference to a service that matches one of its DeviceService filters. * * @param provider DiscoveryProvider that lost the service * @param description ServiceDescription of the service that was lost */ public void onServiceRemoved(DiscoveryProvider provider, ServiceDescription serviceDescription); /** * This method is called on any error/failure within the DiscoveryProvider. * * @param provider DiscoveryProvider that failed * @param error ServiceCommandError providing a information about the failure */ public void onServiceDiscoveryFailed(DiscoveryProvider provider, ServiceCommandError error); }
licit-lab/ensemble
tests/stream/test_vehiclelist.py
<filename>tests/stream/test_vehiclelist.py<gh_stars>0 """ Unit testing for vehicle list """ # ============================================================================ # STANDARD IMPORTS # ============================================================================ from jinja2 import Environment, PackageLoader, select_autoescape from collections import namedtuple import pytest # ============================================================================ # INTERNAL IMPORTS # ============================================================================ from ensemble.component.vehiclelist import VehicleList from ensemble.handler.symuvia.stream import SimulatorRequest from ensemble.logic.platoon_states import StandAlone # ============================================================================ # TESTS AND DEFINITIONS # ============================================================================ KEYS = ( "abscissa", "acceleration", "distance", "driven", "elevation", "lane", "link", "ordinate", "speed", "vehid", "vehtype", "status", "platoon", "comv2x", ) trkdata = namedtuple("Truckdata", KEYS) # ============================================================================ # GENERIC FUNCTIONS # ============================================================================ env = Environment( loader=PackageLoader("ensemble", "templates"), autoescape=select_autoescape( [ "xml", ] ), ) def transform_data(TEST): VEHICLES = [dict(zip(KEYS, v)) for v in TEST] template = env.get_template("instant.xml") return str.encode(template.render(vehicles=VEHICLES), encoding="UTF8") # ============================================================================ # TESTS # ============================================================================ @pytest.fixture def symuviarequest(): return SimulatorRequest() @pytest.fixture def TEST01(): return [ trkdata( 0, 0, 350 - 150 * i, False, 0, 1, "LinkA", 350 - 150 * i, 40 - i * 10, i, "PLT", StandAlone(), False, False, ) for i in range(1, 3) ] def test_get_leader(symuviarequest, TEST01): symuviarequest.query = transform_data(TEST01) vehlist = VehicleList(symuviarequest) assert vehlist.get_leader(vehlist[0]) is vehlist[0] assert vehlist.get_leader(vehlist[1]) is vehlist[1] def test_get_leader_inrange(symuviarequest, TEST01): symuviarequest.query = transform_data(TEST01) vehlist = VehicleList(symuviarequest) assert vehlist.get_leader(vehlist[0], 200) is vehlist[0] assert vehlist.get_leader(vehlist[1], 200) is vehlist[0] def test_get_follower(symuviarequest, TEST01): symuviarequest.query = transform_data(TEST01) vehlist = VehicleList(symuviarequest) assert vehlist.get_follower(vehlist[0]) is vehlist[0] assert vehlist.get_follower(vehlist[1]) is vehlist[1] def test_get_follower_inrange(symuviarequest, TEST01): symuviarequest.query = transform_data(TEST01) vehlist = VehicleList(symuviarequest) assert vehlist.get_follower(vehlist[0], 200) is vehlist[1] assert vehlist.get_follower(vehlist[1], 200) is vehlist[1]
Antot-12/PicoJobs
slimjar/slimjar/src/test/java/io/github/slimjar/resolver/strategy/PathResolutionStrategyTest.java
// // MIT License // // Copyright (c) 2021 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // package io.github.slimjar.resolver.strategy; import io.github.slimjar.resolver.data.Dependency; import io.github.slimjar.resolver.data.Repository; import junit.framework.TestCase; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.HashSet; public class PathResolutionStrategyTest extends TestCase { public void testPathResolutionStrategyMaven() throws MalformedURLException { final String repoString = "https://repo.tld/"; final Repository repository = new Repository(new URL(repoString)); final Dependency dependency = new Dependency("a.b.c", "d", "1.0", null, Collections.emptySet()); final PathResolutionStrategy pathResolutionStrategy = new MavenPathResolutionStrategy(); final Collection<String> resolvedPath = pathResolutionStrategy.pathTo(repository, dependency); assertEquals("Maven Path Resolution (LOCAL)", new HashSet<>(resolvedPath), new HashSet<>(Collections.singleton("https://repo.tld/a/b/c/d/1.0/d-1.0.jar"))); } }
NULLCT/LOMC
src/data/1146.py
<reponame>NULLCT/LOMC<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- import sys sys.setrecursionlimit(10**7) from pprint import pprint as pp from pprint import pformat as pf # @pysnooper.snoop() #import pysnooper # debug def ternary_op(flg, a, b): if flg: return a else: return b import math #from sortedcontainers import SortedList, SortedDict, SortedSet # no in atcoder import bisect # Queue is very slow from collections import defaultdict class Graph: def __init__(self, size): # id starts from 0 self.size = size self.vertices = [0] * size # store depth self.edges = [None] * size for i in range(size): self.edges[i] = [] def __repr__(self): out = [] out.append("vertices {}".format(self.vertices)) for i, e in enumerate(self.edges): out.append("{}{}".format(i, pf(e))) return "\n".join(out) def add_edge(self, frm, to): self.edges[frm].append(to) self.edges[to].append(frm) def prepare(graph): visited = [False] * graph.size dfs(graph, 0, visited, 0) def dfs(graph, v, visited, depth): visited[v] = True graph.vertices[v] = depth depth += 1 for to in graph.edges[v]: if visited[to]: continue dfs(graph, to, visited, depth) def solve(graph, c, d): depth_c = graph.vertices[c] depth_d = graph.vertices[d] dist_like = depth_c + depth_d if dist_like % 2 == 0: return "Town" else: return "Road" if __name__ == '__main__': n, q = list(map(int, input().split())) graph = Graph(n) for _ in range(n - 1): a, b = list(map(int, input().split())) a -= 1 b -= 1 graph.add_edge(a, b) prepare(graph) #print('graph') # debug #pp(graph) # debug for _ in range(q): c, d = list(map(int, input().split())) c -= 1 d -= 1 ans = solve(graph, c, d) print(ans) #print('\33[32m' + 'end' + '\033[0m') # debug
shenkevin/FlameDragon
Classes/FDMoveCreatureActivity.h
// // FDMoveCreatureActivity.h // FlameDragon // // Created by <NAME> on 11-11-6. // Copyright 2011 ms. All rights reserved. // #import "FDActivity.h" #import "FDCreature.h" @interface FDMoveCreatureActivity : FDActivity { FDCreature *creature; float speed; int dx; int dy; int direction; // 0:left 1:up 2:right 3:down CGPoint targetLocation; } -(id) initWithObject:(FDCreature *)obj ToLocation:(CGPoint)loc Speed:(float)s; @end
pavel-alay/drebedengi-api
src/main/java/com/alay/drebedengi/api/DrebedengiApi.java
package com.alay.drebedengi.api; import com.alay.drebedengi.api.data.Account; import com.alay.drebedengi.api.data.Balance; import com.alay.drebedengi.api.data.Category; import com.alay.drebedengi.api.data.Currency; import com.alay.drebedengi.api.data.Tag; import com.alay.drebedengi.api.operations.Credit; import com.alay.drebedengi.api.operations.Debit; import com.alay.drebedengi.api.operations.Exchange; import com.alay.drebedengi.api.operations.GenericRecord; import com.alay.drebedengi.api.operations.OperationType; import com.alay.drebedengi.api.operations.Transfer; import com.alay.drebedengi.soap.functions.GetBalance; import com.alay.drebedengi.soap.functions.GetCategoryList; import com.alay.drebedengi.soap.functions.GetCurrencyList; import com.alay.drebedengi.soap.functions.GetCurrentRevision; import com.alay.drebedengi.soap.functions.GetPlaceList; import com.alay.drebedengi.soap.functions.GetRecordList; import com.alay.drebedengi.soap.functions.GetSourceList; import com.alay.drebedengi.soap.functions.GetTagList; import com.alay.drebedengi.soap.functions.SetRecordList; import com.alay.drebedengi.soap.functions.base.BaseFunction; import com.alay.drebedengi.soap.responses.GetBalanceReturn; import com.alay.drebedengi.soap.responses.GetCategoryListReturn; import com.alay.drebedengi.soap.responses.GetCurrencyListReturn; import com.alay.drebedengi.soap.responses.GetCurrentRevisionReturn; import com.alay.drebedengi.soap.responses.GetPlaceListReturn; import com.alay.drebedengi.soap.responses.GetRecordListReturn; import com.alay.drebedengi.soap.responses.GetSourceListReturn; import com.alay.drebedengi.soap.responses.GetTagListReturn; import com.alay.drebedengi.soap.responses.SetRecordListReturn; import com.alay.drebedengi.soap.responses.base.BaseResponse; import java.io.IOException; import java.math.BigDecimal; import java.rmi.RemoteException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import static java.util.Map.entry; @SuppressWarnings("rawtypes") public class DrebedengiApi { private final WebClient webClient; private static final AtomicInteger clientIdCounter = new AtomicInteger(getTimeBasedId()); public DrebedengiApi(DrebedengiConf conf) { this.webClient = new WebClient(conf); } public int getCurrentRevision() throws IOException { GetCurrentRevisionReturn response = request(new GetCurrentRevision()); return Integer.parseInt(response.getValue()); } public List<Balance> getBalances() throws IOException { return getBalances(LocalDate.now(), false, false); } public List<Category> getDebitCategories() throws IOException { GetCategoryListReturn response = request(new GetCategoryList()); return response.getList() .stream() .map(Category::new) .collect(Collectors.toList()); } public List<Category> getIncomeSources() throws IOException { GetSourceListReturn response = request(new GetSourceList()); return response.getList() .stream() .map(Category::new) .collect(Collectors.toList()); } public List<Balance> getBalances(LocalDate date, boolean withAccum, boolean withDuty) throws IOException { GetBalanceReturn response = request(new GetBalance() .withParam("restDate", DateTimeUtils.dateToString(date)) .withParam("is_with_accum", withAccum) .withParam("is_with_duty", withDuty)); return response.getList() .stream() .map(Balance::new) .collect(Collectors.toList()); } /** * Retrievs place list (array of arrays): * [id] => Internal place ID; * [budget_family_id] => User family ID (for multiuser mode); * [type] => Type of object, 4 - places; [name] => Place name given by user; * [is_hidden] => is place hidden in user interface; * [is_autohide] => debts will auto hide on null balance; * [is_for_duty] => Internal place for duty logic, Auto created while user adds "Waste or income duty"; * [sort] => User sort of place list; * [purse_of_nuid] => Not empty if place is purse of user # The value is internal user ID; * [icon_id] => Place icon ID from http://www.drebedengi.ru/img/pl[icon_id].gif; * If parameter [idList] is given, it will be treat as ID list of objects to retrieve # this is used for synchronization; * There is may be empty response, if user access level is limited; * * @return list of account * @throws RemoteException on any network error */ public List<Account> getAccounts() throws IOException { GetPlaceListReturn response = request(new GetPlaceList()); return response.getList() .stream() .map(Account::new) .collect(Collectors.toList()); } public List<Currency> getCurrencies() throws IOException { GetCurrencyListReturn response = request( new GetCurrencyList()); return response.getList() .stream() .map(Currency::new) .collect(Collectors.toList()); } public List<Tag> getTags() throws IOException { GetTagListReturn response = request(new GetTagList()); return response.getList() .stream() .map(Tag::new) .collect(Collectors.toList()); } public List<Map<String, String>> createExchange(Exchange exchange) throws IOException { int clientIdSold = clientIdCounter.incrementAndGet(); int clientIdBought = clientIdCounter.incrementAndGet(); SetRecordListReturn response = request(new SetRecordList() .add(Map.ofEntries( entry("client_id", clientIdSold), entry("client_change_id", clientIdBought), entry("place_id", exchange.getAccountId()), entry("budget_object_id", exchange.getAccountId()), entry("sum", -1 * convertAmountToInt(exchange.getSoldSum())), entry("currency_id", exchange.getSoldCurrencyId()), entry("operation_type", OperationType.EXCHANGE.getValue()), entry("operation_date", DateTimeUtils.dateToString(exchange.getDate())), entry("comment", "[Автоввод] " + exchange.getComment()), entry("is_duty", false) )) .add(Map.ofEntries( entry("client_id", clientIdBought), entry("client_change_id", clientIdSold), entry("place_id", exchange.getAccountId()), entry("budget_object_id", exchange.getAccountId()), entry("sum", convertAmountToInt(exchange.getBoughtSum())), entry("currency_id", exchange.getBoughtCurrencyId()), entry("operation_type", OperationType.EXCHANGE.getValue()), entry("operation_date", DateTimeUtils.dateToString(exchange.getDate())), entry("comment", "[Автоввод] " + exchange.getComment()), entry("is_duty", false) ))); return response.getList(); } public List<Map<String, String>> createTransfer(Transfer transfer) throws IOException { int clientIdFrom = clientIdCounter.incrementAndGet(); int clientIdTo = clientIdCounter.incrementAndGet(); SetRecordListReturn response = request(new SetRecordList() .add(Map.ofEntries( entry("client_id", clientIdFrom), entry("client_move_id", clientIdTo), entry("place_id", transfer.getFromAccountId()), entry("budget_object_id", transfer.getToAccountId()), entry("sum", -1 * convertAmountToInt(transfer.getSum())), entry("currency_id", transfer.getCurrencyId()), entry("operation_type", OperationType.TRANSFER.getValue()), entry("operation_date", DateTimeUtils.dateToString(transfer.getDate())), entry("comment", "[Автоввод] " + transfer.getComment()), entry("is_duty", false) )) .add(Map.ofEntries( entry("client_id", clientIdTo), entry("client_move_id", clientIdFrom), entry("place_id", transfer.getToAccountId()), entry("budget_object_id", transfer.getFromAccountId()), entry("sum", convertAmountToInt(transfer.getSum())), entry("currency_id", transfer.getCurrencyId()), entry("operation_type", OperationType.TRANSFER.getValue()), entry("operation_date", DateTimeUtils.dateToString(transfer.getDate())), entry("comment", "[Автоввод] " + transfer.getComment()), entry("is_duty", false) ))); return response.getList(); } public List<Map<String, String>> createDebit(Debit debit) throws IOException { int clientId = clientIdCounter.incrementAndGet(); SetRecordListReturn response = request(new SetRecordList() .add(Map.ofEntries( entry("client_id", clientId), entry("sum", convertAmountToInt(debit.getSum())), entry("place_id", debit.getAccountId()), entry("budget_object_id", debit.getCategoryId()), entry("currency_id", debit.getCurrencyId()), entry("operation_type", OperationType.DEBIT.getValue()), entry("operation_date", DateTimeUtils.dateToString(debit.getDate())), entry("comment", "[Автоввод] " + debit.getComment()), entry("is_duty", false) ))); return response.getList(); } public List<Map<String, String>> createCredit(Credit debit) throws IOException { int clientId = clientIdCounter.incrementAndGet(); SetRecordListReturn response = request(new SetRecordList() .add(Map.ofEntries( entry("client_id", clientId), entry("sum", convertAmountToInt(debit.getSum())), entry("place_id", debit.getAccountId()), entry("budget_object_id", debit.getCategoryId()), entry("currency_id", debit.getCurrencyId()), entry("operation_type", OperationType.CREDIT.getValue()), entry("operation_date", DateTimeUtils.dateToString(debit.getDate())), entry("comment", "[Автоввод] " + debit.getComment()), entry("is_duty", false) ))); return response.getList(); } public List<Map<String, String>> updateRecords(GenericRecord ... records) throws IOException { SetRecordList recordList = new SetRecordList(); for (GenericRecord record : records) { recordList.add(record.convertToMap()); } SetRecordListReturn response = request(recordList); return response.getList(); } public List<GenericRecord> fetchDebits(LocalDate from) throws IOException { GetRecordListReturn response = request(new GetRecordList() .withParam("is_report", false) // Data not for report, but for export .withParam("r_period", 0)// Show last 20 record (for each operation type, if not one, see 'r_what') .withParam("period_from", DateTimeUtils.dateToString(from))// 'period_from' [YYYY-MM-DD] - custom period, if 'r_period' = 0; .withParam("period_to", DateTimeUtils.dateToString(LocalDate.now()))// 'period_to' [YYYY-MM-DD] - custom period, if 'r_period' = 0; .withParam("r_what", OperationType.DEBIT.getValue()) .withParam("r_how", 1)// Show in original currency ); return response.getMap().values() .stream() .map(GenericRecord::new) .collect(Collectors.toList()); } public List<GenericRecord> fetchCredits(LocalDate from) throws IOException { GetRecordListReturn response = request(new GetRecordList() .withParam("is_report", false) // Data not for report, but for export .withParam("r_period", 0)// Show last 20 record (for each operation type, if not one, see 'r_what') .withParam("period_from", DateTimeUtils.dateToString(from))// 'period_from' [YYYY-MM-DD] - custom period, if 'r_period' = 0; .withParam("period_to", DateTimeUtils.dateToString(LocalDate.now()))// 'period_to' [YYYY-MM-DD] - custom period, if 'r_period' = 0; .withParam("r_what", OperationType.CREDIT.getValue()) .withParam("r_how", 1)// Show in original currency ); return response.getMap().values() .stream() .map(GenericRecord::new) .collect(Collectors.toList()); } public List<GenericRecord> fetchExchanges(LocalDate from) throws IOException { GetRecordListReturn response = request(new GetRecordList() .withParam("is_report", false) // Data not for report, but for export .withParam("r_period", 0)// Show last 20 record (for each operation type, if not one, see 'r_what') .withParam("period_from", DateTimeUtils.dateToString(from))// 'period_from' [YYYY-MM-DD] - custom period, if 'r_period' = 0; .withParam("period_to", DateTimeUtils.dateToString(LocalDate.now()))// 'period_to' [YYYY-MM-DD] - custom period, if 'r_period' = 0; .withParam("r_what", OperationType.EXCHANGE.getValue()) .withParam("r_how", 1)// Show in original currency ); return response.getMap().values() .stream() .map(GenericRecord::new) .collect(Collectors.toList()); } public List<GenericRecord> fetchTransfers(LocalDate from) throws IOException { GetRecordListReturn response = request( new GetRecordList() .withParam("is_report", false) // Data not for report, but for export .withParam("r_period", 0)// Show last 20 record (for each operation type, if not one, see 'r_what') .withParam("period_from", DateTimeUtils.dateToString(from))// 'period_from' [YYYY-MM-DD] - custom period, if 'r_period' = 0; .withParam("period_to", DateTimeUtils.dateToString(LocalDate.now()))// 'period_to' [YYYY-MM-DD] - custom period, if 'r_period' = 0; .withParam("r_what", OperationType.TRANSFER.getValue()) .withParam("r_how", 1)// Show in original currency ); return response.getMap().values() .stream() .map(GenericRecord::new) .collect(Collectors.toList()); } <R extends BaseResponse> R request(BaseFunction<R> function) throws IOException { return function.request(webClient); } private static int convertAmountToInt(BigDecimal amount) { return amount.multiply(BigDecimal.valueOf(100)).intValue(); } /** * Return 100th part of the second unit. * So, it's guarantee a unique id within a month and int32 will be enough. * * @return 100th part of the second unit since the beginning of the current month. */ private static int getTimeBasedId() { LocalDateTime startOfMonth = LocalDate.now().withDayOfMonth(1).atStartOfDay(); return (int) ChronoUnit.MILLIS.between(startOfMonth, LocalDateTime.now()) / 10; } }
0katekate0/WxJava
weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/marketing/FavorCouponsQueryRequest.java
<filename>weixin-java-pay/src/main/java/com/github/binarywang/wxpay/bean/marketing/FavorCouponsQueryRequest.java<gh_stars>1000+ package com.github.binarywang.wxpay.bean.marketing; import com.google.gson.annotations.SerializedName; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; /** * 根据商户号查用户的券 * <pre> * 文档地址:https://pay.weixin.qq.com/wiki/doc/apiv3/wxpay/marketing/convention/chapter3_9.shtml * </pre> * * @author thinsstar */ @Data @Builder @NoArgsConstructor @AllArgsConstructor public class FavorCouponsQueryRequest implements Serializable { private static final long serialVersionUID = 1L; /** * <pre> * 字段名:用户标识 * 变量名:openid * 是否必填:是 * 类型:string[1,128] * 描述: * 用户在商户appid 下的唯一标识。 * 示例值:2323dfsdf342342 * </pre> */ @SerializedName(value = "openid") private String openid; /** * <pre> * 字段名:公众账号ID * 变量名:appid * 是否必填:是 * 类型:string[1,128] * 描述: * 微信为发券方商户分配的公众账号ID,接口传入的所有appid应该为公众号的appid(在mp.weixin.qq.com申请的),不能为APP的appid(在open.weixin.qq.com申请的)。 * 示例值:wx233544546545989 * </pre> */ @SerializedName(value = "appid") private String appid; /** * <pre> * 字段名:批次号 * 变量名:stock_id * 是否必填:否 * 类型:string[1,20] * 描述: * 批次号,是否指定批次号查询,填写available_mchid,该字段不生效。 * 示例值:9865000 * </pre> */ @SerializedName(value = "stock_id") private String stockId; /** * <pre> * 字段名:券状态 * 变量名:status * 是否必填:否 * 类型:string[1,6] * 描述: * 代金券状态: * SENDED:可用 * USED:已实扣 * 填写available_mchid,该字段不生效。 * 示例值:USED * </pre> */ @SerializedName(value = "status") private String status; /** * <pre> * 字段名:创建批次的商户号 * 变量名:creator_mchid * 是否必填:否 * 类型:string[1,20] * 描述: * 批次创建方商户号。 * 示例值:9865002 * </pre> */ @SerializedName(value = "creator_mchid") private String creatorMchid; /** * <pre> * 字段名:批次发放商户号 * 变量名:sender_mchid * 是否必填:否 * 类型:string[1,20] * 描述: * 批次创建方商户号。 * 示例值:9865002 * </pre> */ @SerializedName(value = "sender_mchid") private String senderMchid; /** * <pre> * 字段名:可用商户号 * 变量名:available_mchid * 是否必填:否 * 类型:string[1,20] * 描述: * 批次创建方商户号。 * 示例值:9865002 * </pre> */ @SerializedName(value = "available_mchid") private String availableMchid; /** * <pre> * 字段名:分页页码 * 变量名:offset * 是否必填:是 * 类型:uint32 * 描述: * 页码从0开始,默认第0页。 * 示例值:1 * </pre> */ @SerializedName(value = "offset") private Integer offset; /** * <pre> * 字段名:分页大小 * 变量名:limit * 是否必填:是 * 类型:uint32 * 描述: * 分页大小,最大10。 * 示例值:8 * </pre> */ @SerializedName(value = "limit") private Integer limit; }
meruemsoftware/vaadin-app-layout
app-layout-addon/src/main/java/com/github/appreciated/app/layout/builder/elements/AbstractNavigationElement.java
package com.github.appreciated.app.layout.builder.elements; import com.github.appreciated.app.layout.builder.ComponentProvider; import com.vaadin.ui.Component; public abstract class AbstractNavigationElement<T> { ComponentProvider<T> provider; private Component component; abstract T getInfo(); public ComponentProvider<T> getProvider() { return provider; } public void setProvider(ComponentProvider<T> provider) { this.provider = provider; } public Component getComponent() { if (component == null) { component = provider.get(getInfo()); } return component; } public void setComponent(Component component) { this.component = component; } }
lemonJun/ESHunt
src/test/java/org/elasticsearch/action/admin/indices/stats/IndicesStatsTests.java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.admin.indices.stats; import org.elasticsearch.index.engine.CommitStats; import org.elasticsearch.index.translog.Translog; import org.elasticsearch.test.ElasticsearchSingleNodeTest; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasKey; public class IndicesStatsTests extends ElasticsearchSingleNodeTest { public void testCommitStats() throws Exception { createIndex("test"); ensureGreen("test"); IndicesStatsResponse rsp = client().admin().indices().prepareStats("test").get(); for (ShardStats shardStats : rsp.getIndex("test").getShards()) { final CommitStats commitStats = shardStats.getCommitStats(); assertNotNull(commitStats); assertThat(commitStats.getGeneration(), greaterThan(0l)); assertThat(commitStats.getUserData(), hasKey(Translog.TRANSLOG_ID_KEY)); } } }
qkmango/tms
src/main/java/cn/qkmango/tms/insertQuery/controller/InsertController.java
package cn.qkmango.tms.insertQuery.controller; import cn.qkmango.tms.domain.bind.PermissionType; import cn.qkmango.tms.domain.orm.*; import cn.qkmango.tms.domain.vo.InsertElectiveVO; import cn.qkmango.tms.common.exception.InsertException; import cn.qkmango.tms.common.exception.ParamVerifyException; import cn.qkmango.tms.insertQuery.service.InsertService; import cn.qkmango.tms.common.annotation.Permission; import cn.qkmango.tms.common.map.ResponseMap; import cn.qkmango.tms.domain.model.CourseInfoModel; import cn.qkmango.tms.common.validate.group.Insert.InsertRoom; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.Locale; import java.util.Map; /** * 插入数据控制器 * * 所有需要校验的字段都需要在字段后面跟 BindingResult result, * 类切面会自动拦截方法, * ControllerAspect 判断 result 对象中是否保存的有字段校验错误信息,如果有则直接响应给前端 * @see cn.qkmango.tms.common.aspect.ControllerAspect */ @RestController @RequestMapping(value = "/insert",method = RequestMethod.POST) public class InsertController { @Resource private InsertService service; @Resource private ReloadableResourceBundleMessageSource messageSource; /** * 插入课程 * @validated true * @param course 课程 * @param courseResult * @param courseInfoModel 课程信息(每次上课的信息) * @param courseInfoModelResult * @return * @throws InsertException */ @Permission(PermissionType.admin) @RequestMapping("/insertCourse.do") public Map<String, Object> insertCourse(@Validated Course course, BindingResult courseResult, @Validated CourseInfoModel courseInfoModel, BindingResult courseInfoModelResult, Locale locale) throws InsertException { if (courseResult.hasErrors()|| courseInfoModelResult.hasErrors()) { throw new ParamVerifyException(courseResult, courseInfoModelResult); } service.insertCourse(course,courseInfoModel,locale); ResponseMap map = new ResponseMap(); map.setSuccess(true); map.setMessage(messageSource.getMessage("db.insertCourse.success",null,locale)); return map; } /** * 添加楼宇 * @validated true * @param building 楼宇对象(楼号,楼名称) * @param result * @return * @throws InsertException */ @Permission(PermissionType.admin) @RequestMapping("/insertBuilding.do") public Map<String, Object> insertBuilding(@Validated Building building, BindingResult result, Locale locale) throws InsertException { service.insertBuilding(building,locale); ResponseMap map = new ResponseMap(); map.setSuccess(true); map.setMessage(messageSource.getMessage("db.insertBuilding.success",null,locale)); return map; } /** * 添加教室 * @validated true * @param room * @return * @throws InsertException */ @Permission(PermissionType.admin) @RequestMapping("/insertRoom.do") public Map<String, Object> insertRoom(@Validated(InsertRoom.class) Room room, BindingResult result, Locale locale) throws InsertException { service.insertRoom(room,locale); ResponseMap map = new ResponseMap(); map.setSuccess(true); map.setMessage(messageSource.getMessage("db.insertRoom.success",null,locale)); return map; } /** * 添加年度 * @validated true * @param year 年度 * @param result * @param locale * @return * @throws InsertException */ @Permission(PermissionType.admin) @RequestMapping("/insertYear.do") public Map<String, Object> insertYear(@Validated Year year, BindingResult result, Locale locale) throws InsertException { service.insertYear(year,locale); ResponseMap map = new ResponseMap(); map.setSuccess(true); map.setMessage(messageSource.getMessage("db.insertYear.success",null,locale)); return map; } /** * 批量插入选课,学生进行选课 * @validated true * @param electiveVO * @param session * @param locale * @return * @throws InsertException */ @Permission(PermissionType.student) @RequestMapping("/insertElective.do") public Map<String, Object> insertElective(@Validated InsertElectiveVO electiveVO, BindingResult result, HttpSession session, Locale locale) throws InsertException { User user = (User) session.getAttribute("user"); Integer id = user.getId(); HashMap<String, Object> param = new HashMap<>(2); param.put("studentId",id); param.put("courseIds",electiveVO.getCourseIds()); service.insertElective(param,locale); ResponseMap map = new ResponseMap(); map.setSuccess(true); map.setMessage(messageSource.getMessage("db.insertElective.success",null,locale)); return map; } /** * 添加教学评价 */ @Permission(PermissionType.student) @RequestMapping("/insertTeachEvaluate.do") public Map insertTeachEvaluate(@Validated TeachEvaluate teachEvaluate,BindingResult result,HttpSession session, Locale locale) throws InsertException { User user = (User) session.getAttribute("user"); Integer id = user.getId(); teachEvaluate.setStudent(id); service.insertTeachEvaluate(teachEvaluate,locale); ResponseMap map = new ResponseMap(); map.setSuccess(true); map.setMessage(messageSource.getMessage("db.insertTeachEvaluate.success",null,locale)); return map; } }
roberterdin/thatsapp
src/back-end/src/main/java/com/whatistics/backend/mail/MailUtilities.java
<reponame>roberterdin/thatsapp<filename>src/back-end/src/main/java/com/whatistics/backend/mail/MailUtilities.java package com.whatistics.backend.mail; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.mail.BodyPart; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Part; import java.io.*; import java.util.Map; import java.util.TreeMap; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * @author robert */ public class MailUtilities { private static final Logger logger = LoggerFactory.getLogger(MailUtilities.class); private static Pattern txtPattern = Pattern.compile("(.+?)(\\.txt)$"); private static Pattern zipPattern = Pattern.compile("(.+?)(\\.zip)$"); public static TreeMap<String, InputStream> getCleanAttachments(Message message) { TreeMap<String, InputStream> attachments = MailUtilities.getAttachments(message); // unzip potential .zip files for (Map.Entry<String, InputStream> entry : attachments.entrySet()) { if (zipPattern.matcher(entry.getKey()).matches()) { ZipInputStream zis = new ZipInputStream(entry.getValue()); ZipEntry zipEntry; try { while ((zipEntry = zis.getNextEntry()) != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // consume all the data from this entry while (zis.available() > 0) outputStream.write(zis.read()); // add file to attachments // todo: don't do in memory attachments.put(zipEntry.getName(), new ByteArrayInputStream(outputStream.toByteArray())); } } catch (IOException e) { logger.error("Failed reading .zip file", e); } finally { try { zis.close(); } catch (IOException e) { logger.error("Failed closing ZIP Stream", e); } } } } // remove all non .txt or .zip messages attachments.entrySet().removeIf(entry -> !txtPattern.matcher(entry.getKey()).matches()); return attachments; } public static TreeMap<String, InputStream> getAttachments(Message message) { Object content; try { content = message.getContent(); if (content instanceof String) { return new TreeMap<String, InputStream>(); } if (content instanceof Multipart) { Multipart multipart = (Multipart) content; TreeMap<String, InputStream> result = new TreeMap<>(); for (int i = 0; i < multipart.getCount(); i++) { result.putAll(getAttachments(multipart.getBodyPart(i))); } return result; } return null; } catch (Exception e) { e.printStackTrace(); return null; } } private static TreeMap<String, InputStream> getAttachments(BodyPart part) throws Exception { TreeMap<String, InputStream> result = new TreeMap<>(); Object content = part.getContent(); if (content instanceof InputStream || content instanceof String) { if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()) || StringUtils.isNotBlank(part.getFileName())) { result.put(part.getFileName(), part.getInputStream()); return result; } else { return new TreeMap<String, InputStream>(); } } if (content instanceof Multipart) { Multipart multipart = (Multipart) content; for (int i = 0; i < multipart.getCount(); i++) { BodyPart bodyPart = multipart.getBodyPart(i); result.putAll(getAttachments(bodyPart)); } } return result; } static boolean isValid(Message message) { Map attachments = getCleanAttachments(message); if (attachments.size() == 1) { return true; } else if (attachments.size() == 0) { logger.info("Number of attachments is 0"); } return false; } }
TU-Berlin-DIMA/resense
data-reader/src/main/java/de/tuberlin/dima/datareader/SensorReader.java
package de.tuberlin.dima.datareader; import io.undertow.websockets.core.WebSocketChannel; import io.undertow.websockets.core.WebSockets; import java.io.IOException; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; public class SensorReader implements Runnable { private Sensor sensor; private WebSocketChannel channel; public SensorReader(Sensor sensor, WebSocketChannel channel) { this.sensor = sensor; this.channel = channel; } @Override public void run() { Object[] data; try { data = sensor.read(); WebSockets.sendText(Arrays.toString(data), channel, null); } catch (IOException | InterruptedException ex) { Logger.getLogger(SensorReader.class.getName()).log(Level.SEVERE, null, ex); } } }
tedrong/topics
forms/dashboard.go
package forms type SystemInfo struct { CPU string `json:"cpu"` Memory string `json:"memory"` Disk string `json:"disk"` BootTime int64 `json:"bootTime"` } type SystemLog struct { Level string `json:"level"` Time int64 `json:"time"` Msg string `json:"message"` Type string `json:"type"` Server string `json:"server"` CronJob string `json:"cronjob"` }
dantin/cub
module/ultrasound/ultrasound_test.go
<filename>module/ultrasound/ultrasound_test.go package ultrasound import ( "context" "crypto/tls" "testing" c2srouter "github.com/dantin/cubit/c2s/router" "github.com/dantin/cubit/router" "github.com/dantin/cubit/router/host" memorystorage "github.com/dantin/cubit/storage/memory" "github.com/dantin/cubit/stream" "github.com/dantin/cubit/xmpp" "github.com/dantin/cubit/xmpp/jid" "github.com/google/uuid" "github.com/stretchr/testify/require" ) func TestModule_Ultrasound_MatchesIQ(t *testing.T) { r := setupTest() srvJID, _ := jid.New("", "example.org", "", true) j, _ := jid.New("user", "example.org", "desktop", true) stm := stream.NewMockC2S(uuid.New().String(), j) stm.SetPresence(xmpp.NewPresence(j, j, xmpp.AvailableType)) r.Bind(context.Background(), stm) cfg := Config{} x := New(&cfg, nil, r, nil, nil) defer func() { _ = x.Shutdown() }() // test MatchesIQ iq := xmpp.NewIQType(uuid.New().String(), xmpp.GetType) iq.SetFromJID(j) iq.SetToJID(srvJID) query := xmpp.NewElementNamespace("query", ultrasoundNamespace) iq.AppendElement(query) require.False(t, x.MatchesIQ(iq)) iq.ClearElements() query = xmpp.NewElementNamespace("profile", ultrasoundNamespace) iq.AppendElement(query) require.True(t, x.MatchesIQ(iq)) iq.ClearElements() query = xmpp.NewElementNamespace("rooms", ultrasoundNamespace) iq.AppendElement(query) require.True(t, x.MatchesIQ(iq)) } func setupTest() router.Router { hosts, _ := host.New([]host.Config{{Name: "example.org", Certificate: tls.Certificate{}}}) r, _ := router.New( hosts, c2srouter.New(memorystorage.NewUser(), memorystorage.NewBlockList()), nil, ) return r }
kzhioki/U8g2_Arduino
src/clib/u8g2_font_logisoso26_tr.c
<gh_stars>0 #include "u8g2.h" /* Fontname: -FreeType-Logisoso-Medium-R-Normal--38-380-72-72-P-46-ISO10646-1 Copyright: Created by <NAME> with FontForge 2.0 (http://fontforge.sf.net) - Brussels - 2009 Glyphs: 96/527 BBX Build Mode: 0 */ const uint8_t u8g2_font_logisoso26_tr[2645] U8G2_FONT_SECTION("u8g2_font_logisoso26_tr") = "`\0\4\4\5\6\4\6\6\31'\0\371\32\371\32\0\3[\6\304\12\70 \6\0@\60\6!\12C" "[P\205\77\30\226\0\42\17\207h;\206\21&F\10\21\21&\4\0#;MS\60&\42\203H\20" "\32Bh\10\31\42\203\210\14\42\62\210\4\211\7\17\222\20\31Dd\20\221A$\210<x\220\202\310 " "\42\203H\20\32Bh\10\241!d\210\14\42\62\10\0$$-T.\256\241\63<\225f\11\231T\347" "\214\222$Z\262Ni:\324\334)\22\204H\254Iup\350\254\0%\60NSP\226Q\212F\34!" "\61\311\20\63c(\35Jt\354P\242C\211\216\35Jt(\321\261C\211\224\31r\202\310\210iFL" "T\202\324\20\0&,mS\60\246r\247\322\224(\62j\310\250!CI\22\35J\260\334\261c#H" "\215 b\204\204\21\22f\64R\243\306D%k\26%'\12\203X[\5\23\42B\0(\36Gk\60" "\246Pd\306\220\31Cf\320\64d\6\315#\62\204&\42\64\210\14!BA\0)\32Gk\60\26\61" "\204\10\15\42\64\21\31B\363\67\324\214\241f\14\231Qb\0*\31\213Y\71\246\201\203\204\14\11\61\342" "\301\220CG\36$\31\22j\340 \0+\16J\331\22\246q\263y\360h\334\64\0,\10\203\330O\205" "$\1-\7jX\24\206\17.\7cXP\205\4/\35MS\60N\222#\251\34I\345H*GR" "\71\222\344H*GR\71\222\312\221$\1\60\31MS\60\246bi\226\24I\205\314\234\375\177w\212D" "\221\22k\222\25\2\61\16Fs\60\236IH<@\63\377\377\3\62!MS\60\246bi\226\224P\205" "\314\234\271S$\302\21\244\222 \225\4\251$H%A\222\17\36$\63\34M\323/\206\17RRH%" "A*I\232;X\224\350|\22\14Q\211%\252\316\0\64$MS\60\256\221$\207\216\244r\350H*" "\207\216\244d\320\230Ac\306\220\31Cf\314\203\7\351\206\316\15\0\65\37MS\60\206\17\230\316\213B" "KX\30I\205\314\334\320\231\232\63w\212D\221\22k\222\25\2\66!MS\60\246bi\226\24I\205" "\314\350L\325,aQ&\325\71\273;v\212D\221\22k\222\25\2\67\36NS\60\206\337\215\30Fb" "\30\211a$\211\322\222(\225DiI\224\322\241\264$\7\0\70&MS\60\246bi\226\24Iu\316" "v\307F\220)\261&\315\222\22\252\220\231\263\356\330)\22EJ\254IV\10\0\71%MS\60\246b" "i\226\24I\205\314\234\335\235\42Q\244\4\223E%\206Nj\316\334)\22EJ\254IV\10\0:\11" "\343\331Q\205\364\200\23;\12\3ZQ\205\364\200\223\4<\25\350iR\276P\203\310PRf\224\260Q" "\205JQ\65.\0=\15,YR\206\17\314C\366\340\201\1>\26\350iR\206p\243hUj\230\250" "AD\212\220!\64*\34\0\77\35mS\60\246bi\226\224(A\12\231\271\241#)\244K\222C\347" "{\310\206N\5\0@L\367\323l\277\304-\337\31+U\262La\42\244\216L\224\4\215\32C$\312" "\30\232\306\320\64\206\246\61\64\215\241i\14Mch\32C\323\30\232\306\320\64\206H\230@\363\240\220\223" "aD\312\220\7E\36Py@\347\201<\10\351\226\15\0A(MS\60\256\241\4\353\335\261c#\206" "\215\30\66b\24\11BD\6\215\31\64f\320\230Ac\210\354d\324\220Q\230\231\33B%MS\60\6" "Tj\226\14*\61l\304\260\273\42\301b\311\222\61&F\221\30v\316\316N\241\61\261D\15*\0C" "\33MS\60\246bi\226\224P\205\314\234\321\371\277;v\212D\221\22k\222\25\2D\26MS\60\206" "DKX\214Bv\316\376\377\354\320\203\21K\22\1E\22NS\60\206\337\316o\25i\64v\376\366\301" "\3\6F\20NS\60\206\337\316o\25i\64v\376\267\0G\34MS\60\246bi\226\224P\205\314\350" "|\224;\273;v\212D\221\22L\26\225\30H\17MS\60\206q\366\337=\370\316\376w\3I\11C" "[P\205\177\60\0J\24MS\60\326\371\377O\315\231;E\242H\211\65\311\12\1K\64MS\60\206" "a\247H\214\42\61\210\310 \42c\310\14!\64\204\320\10R\307\216\231\263\335\261c#H\15!\64\204" "\320\30\62\203\210\14\42\62\212\304\260\21\303\10L\16NS\60\206\261\363\377\377\355\203\7\14M(MS" "\60\206q\247P%J\243f\311\12\26\17\36\224(a\242\204\211\22F\206\30\31bF\210\231\60f\302" "\230\263\357\6N\42MS\60\6b\227\241B\225(#\65jL\20\61A\304\310\20#$\214\220\60\243" "Q\256\60\273\335\0O\32MS\60\246bi\226\24I\205\314\234\375\277;v\212D\221\22k\222\25\2" "P\32MS\60\6Tj\226\214\61\61\12\331\71;;T\202\305\222DC\347\77\5Q\32MS\60\246" "bi\226\24I\205\314\234\375\277;v\212D\221\22L\26\225\30R*MS\60\6Tj\226\214\61\61" "\354:;;Tb\211\232Dc\310\14\32\63h\314 \42\243\206\214\42\61\212\304\260\21\303\256\33S " "MS\60\246bi\226\224P\205\314\234Q*+-Y\227D\315\231;E\242H\211\65\311\12\1T\16" "MS\60\206\17R\15\235\377\377\257\0U\24MS\60\206q\366\377\277;v\212D\221\22k\222\25\2" "V.MS\60\206q\307N\221\30Eb\324\220QC\10\15!\64f\14\231\211\306\14\42\62\210\310\250" "\21\244F\220\32\61\354:\333\25,I#\0W\63MS\60\6RxEb\24\211Q$F\221\30E" "bH\20\22C\202\220\30\42\202\304\24$F\34\31qd\337\250!Q\206D\31\42d\210\220\31C\2" "\0X\65MS\60\6b\247H\214\32\62j\10\31\62c\310LD\202\20\11R#\206]W\260\334\261" "c#F\221 D\202\320\230Ac\210\220!\62j\310\250\21\244\220\15Y'MS\60\206a\250H\214" "\32\62\210\10\31\42d\6\15!\64d\24f\346,$Ir$\225#\251\34Ir$\225\0Z!M" "S\60\206\17R\222\34Ir$\311\221\24\222$H\222 I\202$I\216$\71\222\344\203\7\11[\16" "Hk\60\206\7\254\346\377\177\365 \1\134\42MS\60\6\242C\211NJt(I\242CI\22\35J" "\222\350P\242CI\22\35J\222\350P\222\4]\16Gk\60\206\7\206\346\377\177\364 \1^\15\253\330" "=\246q\245\316\220\240\206\0_\10Q@/\206\17\10`\12\246\360<\206\61d\6Ma(\217Rp" "&\203\310\24\25)Cj\314\260\61\303\6\217%\245h\15\23bC\210\15\31\67\204\330\220\62'\234\264" "\71#\0b\35mS\60\206\241\363\213BKX\230P\205\314\234\375\356\330)\25\17F,\31Q\10\0" "c\33\215R\60\246bi\226\224P\205\314\234\321\371\356\330)\22EJ\254IV\10\0d\35mS\60" "\326\371Q\211!+X\224P\205\314\234\375\356\330)\22EJ\60YTb\0e\34\215R\60\246bi" "\226\24I\205\314\234\271\7\237NJ\222\324\220*\326$+\4\0f\30mS\60\266r\247\22\221 \64" "f\320\320y\306\202\253\241\363\177\6\0g(m\323,\246\64JV\224P\205\314\234\271c\247HT\262" "&\321\261\241CI\246Y\361@\324\71s\247H\260Xt\6\0h\24mS\60\206\241\363\213BKX" "\230P\205\314\234\375\277\33i\21eS\60\205!\323\203\33\62\377\77)A\215\0j\24J\344,\276\331" "\303d\334\374\377\337\31j\201\4\21\31\0k*mS\60\206\241\363\263\253H\14\42\62\210\310\30\62c" "\310\14!\64d\324\10RX%RS\202\14%\204\206\214\42\61\354\30\1l\17gSP\205A\363\377" "\377\21!\23f\10m\64\227Rp\207\21\245\12\255H\362\340\204\211\24\252J!#fn\234\271q\346" "\306\231\33gn\234\271q\346\306\231\33gn\234\271q\346\306\231\33gn\234\271\11n\23\215R\60\206" "\21\205\226\260\60\241\12\231\71\373\177\67\0o\32\215R\60\246bi\226\224P\205\314\234\375\356\330)\22" "EJ\254IV\10\0p\36m\323,\206\21\205\226\260\60\241\12\231\71\373\335\261SJ\36\210X\62\242" "\320\320\371\24\0q\35m\323,\246\22CV\260(\241\12\231\71\373\335\261S$\212\224`\262\250\304\320" "\371\1r\21\212R\320\205\21\17\36\210\70sl\334\374\277\3s\37\214R\20\236bhT\24It\354" " \311c\250\20\222<f\354\20\11\42D\324 #\4\0t\23hKP\225Q\363\315\203$\243\346\377" "\212\220\231B\4u\24\215R\60\206q\366\377\356\330)\22EJ\60YTb\0v+\215R\60\206q" "\346N\221\30Eb\324\220QC\10\15!Cf\14\231\211\306\14\42\62\210\4\251\21\244F\14\33\61\354" ":s\205\0wG\227Rp\207q\343\314\215;U\12U)\22\243J\15\31Uj\310(CC\310\234" "!B\346\14\231)\306\14\32\63b\314\240\61#\210\14\42A#\22DF\220\32\61f\304\260\21cF" "\14;s\354\314\61S\346J\25\2x*\215R\60\206q#F\221\30\65f\14\231\251F\220\32\61\316" "\134\311\241#\13\226\33\61l\304\250\61\203\306\20\31\65d\324\271\1y/m\323,\16R#\10\21\31" "Dd\20\221Ac\310\214!\63h\10\241!\204\206\214\42\61\212\304\260\313\314YX!IZ\211(\204" "\352 \71\0z\27\215R\60\206\17R\22$X\220\302\202\24\26\244\260 \225\17\36${\33\311\343." "\266Q\204\12Q\65l\276\42D\25\251b\304\346g\244\210\225\42\66\0|\11#|.\206\377 \1}" "\33\311\343.\206a\244\252\42\66\77\243\331\240B\243H\15\233\257\310\24*\64\14\0~\15\217\310\64\6" "\42g\232\270)C\0\177\6\0@\60\6\0\0\0\4\377\377\0";
kittywhisker/libdispatch
src/introspection_internal.h
<filename>src/introspection_internal.h /* Copyright (c) 2010-2013 Apple Inc. All rights reserved. @APPLE_APACHE_LICENSE_HEADER_START@ 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. @APPLE_APACHE_LICENSE_HEADER_END@ */ /* IMPORTANT: This header file describes INTERNAL interfaces to libdispatch which are subject to change in future releases of Mac OS X. Any applications relying on these interfaces WILL break. */ #ifndef __DISPATCH_INTROSPECTION_INTERNAL__ #define __DISPATCH_INTROSPECTION_INTERNAL__ /* keep in sync with introspection_private.h */ enum dispatch_introspection_runtime_event { dispatch_introspection_runtime_event_worker_event_delivery = 1, dispatch_introspection_runtime_event_worker_unpark = 2, dispatch_introspection_runtime_event_worker_request = 3, dispatch_introspection_runtime_event_worker_park = 4, dispatch_introspection_runtime_event_sync_wait = 10, dispatch_introspection_runtime_event_async_sync_handoff = 11, dispatch_introspection_runtime_event_sync_sync_handoff = 12, dispatch_introspection_runtime_event_sync_async_handoff = 13, }; #if DISPATCH_INTROSPECTION #define DC_BARRIER 0x1 #define DC_SYNC 0x2 #define DC_APPLY 0x4 typedef struct dispatch_queue_introspection_context_s { dispatch_queue_class_t dqic_queue; dispatch_function_t dqic_finalizer; LIST_ENTRY(dispatch_queue_introspection_context_s) dqic_list; char __dqic_no_queue_inversion[0]; // used for queue inversion debugging only dispatch_unfair_lock_s dqic_order_top_head_lock; dispatch_unfair_lock_s dqic_order_bottom_head_lock; LIST_HEAD(, dispatch_queue_order_entry_s) dqic_order_top_head; LIST_HEAD(, dispatch_queue_order_entry_s) dqic_order_bottom_head; } *dispatch_queue_introspection_context_t; struct dispatch_introspection_state_s { LIST_HEAD(, dispatch_introspection_thread_s) threads; LIST_HEAD(, dispatch_queue_introspection_context_s) queues; dispatch_unfair_lock_s threads_lock; dispatch_unfair_lock_s queues_lock; ptrdiff_t thread_queue_offset; // dispatch introspection features bool debug_queue_inversions; // DISPATCH_DEBUG_QUEUE_INVERSIONS }; extern struct dispatch_introspection_state_s _dispatch_introspection; void _dispatch_introspection_init(void); void _dispatch_introspection_thread_add(void); dispatch_function_t _dispatch_object_finalizer(dispatch_object_t dou); void _dispatch_object_set_finalizer(dispatch_object_t dou, dispatch_function_t finalizer); dispatch_queue_class_t _dispatch_introspection_queue_create( dispatch_queue_class_t dqu); void _dispatch_introspection_queue_dispose(dispatch_queue_class_t dqu); void _dispatch_introspection_queue_item_enqueue(dispatch_queue_class_t dqu, dispatch_object_t dou); void _dispatch_introspection_queue_item_dequeue(dispatch_queue_class_t dqu, dispatch_object_t dou); void _dispatch_introspection_queue_item_complete(dispatch_object_t dou); void _dispatch_introspection_callout_entry(void *ctxt, dispatch_function_t f); void _dispatch_introspection_callout_return(void *ctxt, dispatch_function_t f); struct dispatch_object_s *_dispatch_introspection_queue_fake_sync_push_pop( dispatch_queue_t dq, void *ctxt, dispatch_function_t func, uintptr_t dc_flags); void _dispatch_introspection_runtime_event( enum dispatch_introspection_runtime_event event, void *ptr, uint64_t value); #if DISPATCH_PURE_C DISPATCH_ALWAYS_INLINE static inline void _dispatch_introspection_queue_push_list(dispatch_queue_class_t dqu, dispatch_object_t head, dispatch_object_t tail) { struct dispatch_object_s *dou = head._do; do { _dispatch_introspection_queue_item_enqueue(dqu, dou); } while (dou != tail._do && (dou = dou->do_next)); }; DISPATCH_ALWAYS_INLINE static inline void _dispatch_introspection_queue_push(dispatch_queue_class_t dqu, dispatch_object_t dou) { _dispatch_introspection_queue_item_enqueue(dqu, dou); } DISPATCH_ALWAYS_INLINE static inline void _dispatch_introspection_queue_pop(dispatch_queue_class_t dqu, dispatch_object_t dou) { _dispatch_introspection_queue_item_dequeue(dqu, dou); } void _dispatch_introspection_order_record(dispatch_queue_t top_q); void _dispatch_introspection_target_queue_changed(dispatch_queue_t dq); DISPATCH_ALWAYS_INLINE static inline void _dispatch_introspection_sync_begin(dispatch_queue_class_t dq) { if (!_dispatch_introspection.debug_queue_inversions) { return; } _dispatch_introspection_order_record(dq._dq); } #endif // DISPATCH_PURE_C #else // DISPATCH_INTROSPECTION #define _dispatch_introspection_init() #define _dispatch_introspection_thread_add() DISPATCH_ALWAYS_INLINE static inline dispatch_queue_class_t _dispatch_introspection_queue_create(dispatch_queue_class_t dqu) { return dqu; } #if DISPATCH_PURE_C DISPATCH_ALWAYS_INLINE static inline dispatch_function_t _dispatch_object_finalizer(dispatch_object_t dou) { return dou._do->do_finalizer; } DISPATCH_ALWAYS_INLINE static inline void _dispatch_object_set_finalizer(dispatch_object_t dou, dispatch_function_t finalizer) { dou._do->do_finalizer = finalizer; } #endif // DISPATCH_PURE_C DISPATCH_ALWAYS_INLINE static inline void _dispatch_introspection_queue_dispose( dispatch_queue_class_t dqu DISPATCH_UNUSED) {} DISPATCH_ALWAYS_INLINE static inline void _dispatch_introspection_queue_push_list( dispatch_queue_class_t dqu DISPATCH_UNUSED, dispatch_object_t head DISPATCH_UNUSED, dispatch_object_t tail DISPATCH_UNUSED) {} DISPATCH_ALWAYS_INLINE static inline void _dispatch_introspection_queue_push(dispatch_queue_class_t dqu DISPATCH_UNUSED, dispatch_object_t dou DISPATCH_UNUSED) {} DISPATCH_ALWAYS_INLINE static inline void _dispatch_introspection_queue_pop(dispatch_queue_class_t dqu DISPATCH_UNUSED, dispatch_object_t dou DISPATCH_UNUSED) {} DISPATCH_ALWAYS_INLINE static inline void _dispatch_introspection_queue_item_complete( dispatch_object_t dou DISPATCH_UNUSED) {} DISPATCH_ALWAYS_INLINE static inline void _dispatch_introspection_callout_entry(void *ctxt DISPATCH_UNUSED, dispatch_function_t f DISPATCH_UNUSED) {} DISPATCH_ALWAYS_INLINE static inline void _dispatch_introspection_callout_return(void *ctxt DISPATCH_UNUSED, dispatch_function_t f DISPATCH_UNUSED) {} DISPATCH_ALWAYS_INLINE static inline void _dispatch_introspection_target_queue_changed( dispatch_queue_t dq DISPATCH_UNUSED) {} DISPATCH_ALWAYS_INLINE static inline void _dispatch_introspection_sync_begin( dispatch_queue_class_t dq DISPATCH_UNUSED) {} DISPATCH_ALWAYS_INLINE static inline struct dispatch_object_s * _dispatch_introspection_queue_fake_sync_push_pop( dispatch_queue_t dq DISPATCH_UNUSED, void *ctxt DISPATCH_UNUSED, dispatch_function_t func DISPATCH_UNUSED, uintptr_t dc_flags DISPATCH_UNUSED) { return NULL; } DISPATCH_ALWAYS_INLINE static inline void _dispatch_introspection_runtime_event( enum dispatch_introspection_runtime_event event DISPATCH_UNUSED, void *ptr DISPATCH_UNUSED, uint64_t value DISPATCH_UNUSED) {} #endif // DISPATCH_INTROSPECTION #endif // __DISPATCH_INTROSPECTION_INTERNAL__
zourzouvillys/graphql
graphql-schema/src/main/java/io/zrz/zulu/schema/SchemaType.java
package io.zrz.zulu.schema; import io.zrz.graphql.core.types.GQLTypeDeclKind; public interface SchemaType { String typeName(); GQLTypeDeclKind typeKind(); void apply(VoidVisitor visitor); <R> R apply(SupplierVisitor<R> visitor); <T, R> R apply(FunctionVisitor<T, R> visitor, T value); <T1, T2, R> R apply(BiFunctionVisitor<T1, T2, R> visitor, T1 arg1, T2 arg2); interface VoidVisitor { void visit(ResolvedEnumType type); void visit(ResolvedInputType type); void visit(ResolvedInterfaceType type); void visit(ResolvedObjectType type); void visit(ResolvedScalarType type); void visit(ResolvedUnionType type); } interface SupplierVisitor<R> { R visit(ResolvedEnumType type); R visit(ResolvedInputType type); R visit(ResolvedInterfaceType type); R visit(ResolvedObjectType type); R visit(ResolvedScalarType type); R visit(ResolvedUnionType type); } interface FunctionVisitor<T, R> { R visit(ResolvedEnumType type, T value); R visit(ResolvedInputType type, T value); R visit(ResolvedInterfaceType type, T value); R visit(ResolvedObjectType type, T value); R visit(ResolvedScalarType type, T value); R visit(ResolvedUnionType type, T value); } interface BiFunctionVisitor<T1, T2, R> { R visit(ResolvedEnumType type, T1 arg1, T2 arg2); R visit(ResolvedInputType type, T1 arg1, T2 arg2); R visit(ResolvedInterfaceType type, T1 arg1, T2 arg2); R visit(ResolvedObjectType type, T1 arg1, T2 arg2); R visit(ResolvedScalarType type, T1 arg1, T2 arg2); R visit(ResolvedUnionType type, T1 arg1, T2 arg2); } }
SnirkImmington/sr-server
routes/httpSession.go
package routes import ( "errors" "github.com/gomodule/redigo/redis" redisUtil "sr/redis" "sr/session" "strings" ) var errNoAuthBearer = errors.New("httpSession: no auth: bearer header") var errNoSessionParam = errors.New("httpSession: no session query param") func sessionFromHeader(request *Request) (string, error) { auth := request.Header.Get("Authentication") if !strings.HasPrefix(auth, "Bearer") { return "", errNoAuthBearer } return auth[7:], nil } func sessionFromParams(request *Request) (string, error) { session := request.URL.Query().Get("session") if session == "" || session == "null" || session == "undefined" { return "", errNoSessionParam } return session, nil } // requestSession retrieves the authenticated session for the request. // It does not open redis if an invalid session is supplied. func requestSession(request *Request) (*session.Session, redis.Conn, error) { sessionID, err := sessionFromHeader(request) if err != nil { logf(request, "Didn't have a session ID") return nil, nil, err } conn := contextRedisConn(request.Context()) session, err := session.GetByID(sessionID, conn) if err != nil { logf(request, "Didn't get %s by id", sessionID) redisUtil.Close(conn) return nil, nil, err } return session, conn, nil } func requestParamSession(request *Request) (*session.Session, redis.Conn, error) { sessionID, err := sessionFromParams(request) if err != nil { return nil, nil, err } conn := contextRedisConn(request.Context()) session, err := session.GetByID(sessionID, conn) if err != nil { redisUtil.Close(conn) return nil, nil, err } return session, conn, nil }
dougli1sqrd/SGDBackend-Nex2
scripts/loading/reference/reference_pubtype_update.py
<reponame>dougli1sqrd/SGDBackend-Nex2<gh_stars>1-10 from datetime import datetime import time from io import StringIO from Bio import Entrez, Medline import sys import importlib importlib.reload(sys) # Reload does the trick! sys.setdefaultencoding('UTF8') sys.path.insert(0, '../../../src/') from models import Referencedbentity, Referencetype, Source sys.path.insert(0, '../') from config import CREATED_BY from database_session import get_nex_session as get_session from .pubmed import get_pubmed_record __author__ = 'sweng66' MAX = 200 SLEEP_TIME = 2 SOURCE = 'NCBI' SRC = 'NCBI' def update_all_pubtypes(log_file): nex_session = get_session() fw = open(log_file,"w") fw.write(str(datetime.now()) + "\n") fw.write("Getting PMID list...\n") print(datetime.now()) print("Getting PMID list...") pmid_to_reference = dict([(x.pmid, x) for x in nex_session.query(Referencedbentity).all()]) source_to_id = dict([(x.display_name, x.source_id) for x in nex_session.query(Source).all()]) reference_id_to_pubtypes = {} for x in nex_session.query(Referencetype).all(): pubtypes = [] if x.reference_id in reference_id_to_pubtypes: pubtypes = reference_id_to_pubtypes[x.reference_id] pubtypes.append(x.display_name) reference_id_to_pubtypes[x.reference_id] = pubtypes fw.write(str(datetime.now()) + "\n") fw.write("Getting Pubmed records...\n") print(datetime.now()) print("Getting Pubmed records...") source_id = source_to_id[SRC] pmids = [] for pmid in pmid_to_reference: fw.write("Getting data for PMID="+ str(pmid) + "\n") if pmid is None or pmid in [26842620, 27823544]: continue if len(pmids) >= MAX: records = get_pubmed_record(','.join(pmids)) update_database_batch(nex_session, fw, records, pmid_to_reference, reference_id_to_pubtypes, source_id) pmids = [] time.sleep(SLEEP_TIME) pmids.append(str(pmid)) if len(pmids) > 0: records = get_pubmed_record(','.join(pmids)) update_database_batch(nex_session, fw, records, pmid_to_reference, reference_id_to_pubtypes, source_id) print("Done") fw.close() nex_session.commit() def update_database_batch(nex_session, fw, records, pmid_to_reference, reference_id_to_pubtypes, source_id): for rec in records: rec_file = StringIO(rec) record = Medline.read(rec_file) pmid = record.get('PMID') if pmid is None: continue x = pmid_to_reference.get(int(pmid)) if x is None: continue pubtypes = record.get('PT', []) ## a list of types update_reftypes(nex_session, fw, pmid, x.dbentity_id, pubtypes, reference_id_to_pubtypes.get(x.dbentity_id), source_id) def update_reftypes(nex_session, fw, pmid, reference_id, pubtypes, pubtypes_in_db, source_id): if pubtypes_in_db is None: pubtypes_in_db = [] if sorted(pubtypes) == sorted(pubtypes_in_db): return updated = 0 for type in pubtypes_in_db: if type not in pubtypes: rt = nex_session.query(Referencetype).filter_by(reference_id=reference_id, display_name=type).all() nex_session.delete(rt[0]) updated = 1 # add new ones for type in pubtypes: if type not in pubtypes_in_db: rt = Referencetype(display_name = type, source_id = source_id, obj_url = '/referencetype/' + type.replace(' ', '_'), reference_id = reference_id, created_by = CREATED_BY) nex_session.add(rt) updated = 1 if updated == 1: nex_session.commit() fw.write("PMID=" + str(pmid) + ": the reference type list is updated.\nNew types: " + str(pubtypes) + "\nOld types: " + str(pubtypes_in_db) + "\n\n") print("PMID=", pmid, ": the reference type list is updated.") print("New types:", pubtypes) print("Old types:", pubtypes_in_db) if __name__ == '__main__': log_file = "logs/reference_pubtype_update.log" update_all_pubtypes(log_file)
Neomades/NeoMAD-Samples
PlatformSpecificCode/specific-def/com/neomades/specific/Compass.java
<filename>PlatformSpecificCode/specific-def/com/neomades/specific/Compass.java package com.neomades.specific; public class Compass { /** * We set the visibility to protected, because this attribute will be * accessed by the class extending the generated abstract class */ protected CompassListener listener; /** * This method is used to know if the compass is supported on the target * platform. * * @return true if the compass is supported (for the moment only on iOS, * Android, Windows Phone and Windows) and false if not supported */ public boolean isSupported() { return false; } /** * Sets a listener, that will be called every time the compass orientation * changes. * * @param listener */ public void setCompassListener(CompassListener listener) { this.listener = listener; } }
jharting/undertow
core/src/main/java/io/undertow/websockets/api/PingFrameSender.java
<filename>core/src/main/java/io/undertow/websockets/api/PingFrameSender.java /* * Copyright 2013 JBoss, by Red Hat, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.undertow.websockets.api; import java.io.IOException; import java.nio.ByteBuffer; /** * Allows to send a PING message to the remote peer. The remote peer will then respond with a PONG message which contains * the same payload as the one that was contained in the PING message. This is useful to check if the remote peer * is still alive and can so be used to implement a heartbeat. * * @author <a href="mailto:<EMAIL>"><NAME></a> */ public interface PingFrameSender { /** * Send the a PING websocket frame and notify the {@link SendCallback} once done. * It is possible to send multiple frames at the same time even if the {@link SendCallback} is not triggered yet. * The implementation is responsible to queue them up and send them in the correct order. * * @param payload * The payload * @param callback * The callback that is called when sending is done or {@code null} if no notification * should be done. */ void sendPing(ByteBuffer payload, SendCallback callback); /** * Send the a PING websocket frame and notify the {@link SendCallback} once done. * It is possible to send multiple frames at the same time even if the {@link SendCallback} is not triggered yet. * The implementation is responsible to queue them up and send them in the correct order. * * @param payload * The payload * @param callback * The callback that is called when sending is done or {@code null} if no notification * should be done. */ void sendPing(ByteBuffer[] payload, SendCallback callback); /** * Send the a PING websocket frame and blocks until complete. * <p/> * The implementation is responsible to queue them up and send them in the correct order. * * @param payload * The payload * @throws IOException * If sending failed */ void sendPing(ByteBuffer payload) throws IOException; /** * Send the a PING websocket frame and blocks until complete. * <p/> * The implementation is responsible to queue them up and send them in the correct order. * * @param payload * The payload * @throws IOException * If sending failed */ void sendPing(ByteBuffer[] payload) throws IOException; }
gcnyin/vproxy
base/src/main/java/io/vproxy/base/dns/dnsserverlistgetter/GetDnsServerListFromDhcp.java
<reponame>gcnyin/vproxy<filename>base/src/main/java/io/vproxy/base/dns/dnsserverlistgetter/GetDnsServerListFromDhcp.java package io.vproxy.base.dns.dnsserverlistgetter; import io.vproxy.base.Config; import io.vproxy.base.dhcp.DHCPClientHelper; import io.vproxy.base.dns.AbstractResolver; import io.vproxy.base.dns.DnsServerListGetter; import io.vproxy.base.dns.Resolver; import io.vproxy.base.util.LogType; import io.vproxy.base.util.Logger; import io.vproxy.base.util.callback.Callback; import io.vproxy.vfd.IP; import io.vproxy.vfd.IPPort; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public class GetDnsServerListFromDhcp implements DnsServerListGetter { @Override public void get(boolean firstRun, Callback<List<IPPort>, Throwable> cb) { DHCPClientHelper.getDomainNameServers(((AbstractResolver) Resolver.getDefault()).getLoop().getSelectorEventLoop(), Config.dhcpGetDnsListNics, 1, new Callback<>() { @Override protected void onSucceeded(Set<IP> nameServerIPs) { cb.succeeded(nameServerIPs.stream().map(ip -> new IPPort(ip, 53)).collect(Collectors.toList())); } @Override protected void onFailed(IOException err) { if (firstRun) { Logger.error(LogType.ALERT, "failed retrieving dns servers from dhcp", err); } cb.failed(err); } }); } }
vishnudevk/MiBandDecompiled
Original Files/source/src/com/nostra13/universalimageloader/core/assist/QueueProcessingType.java
<gh_stars>10-100 // Decompiled by Jad v1.5.8e. Copyright 2001 <NAME>. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.nostra13.universalimageloader.core.assist; public final class QueueProcessingType extends Enum { public static final QueueProcessingType FIFO; public static final QueueProcessingType LIFO; private static final QueueProcessingType a[]; private QueueProcessingType(String s, int i) { super(s, i); } public static QueueProcessingType valueOf(String s) { return (QueueProcessingType)Enum.valueOf(com/nostra13/universalimageloader/core/assist/QueueProcessingType, s); } public static QueueProcessingType[] values() { return (QueueProcessingType[])a.clone(); } static { FIFO = new QueueProcessingType("FIFO", 0); LIFO = new QueueProcessingType("LIFO", 1); QueueProcessingType aqueueprocessingtype[] = new QueueProcessingType[2]; aqueueprocessingtype[0] = FIFO; aqueueprocessingtype[1] = LIFO; a = aqueueprocessingtype; } }
rtobar/askapsoft
Code/Components/CP/pipelinetasks/current/casdaupload/ScanElement.cc
<filename>Code/Components/CP/pipelinetasks/current/casdaupload/ScanElement.cc<gh_stars>1-10 /// @file ScanElement.cc /// /// @copyright (c) 2015 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// <EMAIL> /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution is free software: you can redistribute it /// and/or modify it under the terms of the GNU General Public License as /// published by the Free Software Foundation; either version 2 of the License, /// or (at your option) any later version. /// /// This program is distributed in the hope that it will be useful, /// but WITHOUT ANY WARRANTY; without even the implied warranty of /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /// GNU General Public License for more details. /// /// You should have received a copy of the GNU General Public License /// along with this program; if not, write to the Free Software /// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA /// /// @author <NAME> <<EMAIL>> // Include own header file first #include "casdaupload/ScanElement.h" // Include package level header file #include "askap_pipelinetasks.h" // System includes #include <string> #include <sstream> #include <cmath> #include <stdint.h> // ASKAPsoft includes #include "askap/AskapUtil.h" #include "xercesc/dom/DOM.hpp" // Includes all DOM #include "votable/XercescUtils.h" #include "votable/XercescString.h" // Using using namespace std; using namespace askap::cp::pipelinetasks; using namespace casa; using namespace xercesc; using askap::utility::toString; using askap::accessors::XercescUtils; using askap::accessors::XercescString; ScanElement::ScanElement(const int id, const casa::MEpoch& scanstart, const casa::MEpoch& scanend, const casa::MDirection& fieldcentre, const std::string& fieldname, const casa::Vector<casa::Int> polarisations, const int numchan, const casa::Quantity& centrefreq, const casa::Quantity& channelwidth) : itsId(id), itsScanStart(scanstart), itsScanEnd(scanend), itsFieldCentre(fieldcentre), itsFieldName(fieldname), itsPolarisations(polarisations), itsNumChan(numchan), itsCentreFreq(centrefreq), itsChannelWidth(channelwidth) { } xercesc::DOMElement* ScanElement::toXmlElement(xercesc::DOMDocument& doc) const { DOMElement* e = doc.createElement(XercescString("scan")); XercescUtils::addTextElement(*e, "id", toString(itsId)); XercescUtils::addTextElement(*e, "scanstart", MVTime(itsScanStart.get("s")).string(MVTime::FITS)); XercescUtils::addTextElement(*e, "scanend", MVTime(itsScanEnd.get("s")).string(MVTime::FITS)); // Format the field direction like so: "1.13701, -1.112" stringstream ss; ss << "["; ss << itsFieldCentre.getAngle().getValue("rad")(0); ss << ", "; ss << itsFieldCentre.getAngle().getValue("rad")(1); ss << "]"; DOMElement* child = XercescUtils::addTextElement(*e, "fieldcentre", ss.str()); child->setAttribute(XercescString("units"), XercescString("rad")); XercescUtils::addTextElement(*e, "coordsystem", itsFieldCentre.getRefString()); XercescUtils::addTextElement(*e, "fieldname", itsFieldName); // Format the polarisaztions like so: "XX, XY, YX, YY" ss.str(""); ss << "["; for (size_t i = 0; i < itsPolarisations.size(); ++i) { if (i != 0) ss << ", "; ss << Stokes::name(Stokes::type(itsPolarisations(i))); } ss << "]"; XercescUtils::addTextElement(*e, "polarisations", ss.str()); XercescUtils::addTextElement(*e, "numchan", toString(itsNumChan)); const string FREQ_UNITS = "Hz"; child = XercescUtils::addTextElement(*e, "centrefreq", toString(static_cast<uint64_t>(round(fabs(itsCentreFreq.getValue(FREQ_UNITS.c_str())))))); child->setAttribute(XercescString("units"), XercescString(FREQ_UNITS)); child = XercescUtils::addTextElement(*e, "chanwidth", toString(static_cast<uint64_t>(round(fabs(itsChannelWidth.getValue(FREQ_UNITS.c_str())))))); child->setAttribute(XercescString("units"), XercescString(FREQ_UNITS)); return e; }
krka/Ardor3D
ardor3d-core/src/main/java/com/ardor3d/util/export/xml/DOMInputCapsule.java
/** * Copyright (c) 2008-2010 Ardor Labs, Inc. * * This file is part of Ardor3D. * * Ardor3D is free software: you can redistribute it and/or modify it * under the terms of its license which may be found in the accompanying * LICENSE file or at <http://www.ardor3d.com/LICENSE>. */ package com.ardor3d.util.export.xml; import java.io.IOException; import java.lang.reflect.Array; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.ardor3d.annotation.SavableFactory; import com.ardor3d.image.Texture; import com.ardor3d.renderer.state.RenderState; import com.ardor3d.renderer.state.TextureState; import com.ardor3d.util.Ardor3dException; import com.ardor3d.util.TextureKey; import com.ardor3d.util.TextureManager; import com.ardor3d.util.export.InputCapsule; import com.ardor3d.util.export.Savable; import com.ardor3d.util.geom.BufferUtils; /** * Part of the ardor3d XML IO system */ public class DOMInputCapsule implements InputCapsule { private final Document _doc; private Element _currentElem; private boolean _isAtRoot = true; private final Map<String, Savable> _referencedSavables = new HashMap<String, Savable>(); public DOMInputCapsule(final Document doc) { _doc = doc; _currentElem = doc.getDocumentElement(); } private static String decodeString(String s) { if (s == null) { return null; } s = s.replaceAll("\\&quot;", "\"").replaceAll("\\&lt;", "<").replaceAll("\\&amp;", "&"); return s; } private Element findFirstChildElement(final Element parent) { Node ret = parent.getFirstChild(); while (ret != null && (!(ret instanceof Element))) { ret = ret.getNextSibling(); } return (Element) ret; } private Element findChildElement(final Element parent, final String name) { if (parent == null) { return null; } Node ret = parent.getFirstChild(); while (ret != null && (!(ret instanceof Element) || !ret.getNodeName().equals(name))) { ret = ret.getNextSibling(); } return (Element) ret; } private Element findNextSiblingElement(final Element current) { Node ret = current.getNextSibling(); while (ret != null) { if (ret instanceof Element) { return (Element) ret; } ret = ret.getNextSibling(); } return null; } public byte readByte(final String name, final byte defVal) throws IOException { byte ret = defVal; try { ret = Byte.parseByte(_currentElem.getAttribute(name)); } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public byte[] readByteArray(final String name, final byte[] defVal) throws IOException { byte[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final byte[] tmp = new byte[size]; final String[] strings = tmpEl.getAttribute("data").split("\\s+"); for (int i = 0; i < size; i++) { tmp[i] = Byte.parseByte(strings[i]); } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public byte[][] readByteArray2D(final String name, final byte[][] defVal) throws IOException { byte[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final byte[][] tmp = new byte[size][]; final NodeList nodes = _currentElem.getChildNodes(); int strIndex = 0; for (int i = 0; i < nodes.getLength(); i++) { final Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("array")) { if (strIndex < size) { tmp[strIndex++] = readByteArray(n.getNodeName(), null); } else { throw new IOException("String array contains more elements than specified!"); } } } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } _currentElem = (Element) _currentElem.getParentNode(); return ret; } public int readInt(final String name, final int defVal) throws IOException { int ret = defVal; try { final String s = _currentElem.getAttribute(name); if (s.length() > 0) { ret = Integer.parseInt(s); } } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public int[] readIntArray(final String name, final int[] defVal) throws IOException { int[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final int[] tmp = new int[size]; final String[] strings = tmpEl.getAttribute("data").split("\\s+"); for (int i = 0; i < size; i++) { tmp[i] = Integer.parseInt(strings[i]); } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public int[][] readIntArray2D(final String name, final int[][] defVal) throws IOException { int[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final int[][] tmp = new int[size][]; final NodeList nodes = _currentElem.getChildNodes(); int strIndex = 0; for (int i = 0; i < nodes.getLength(); i++) { final Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("array")) { if (strIndex < size) { tmp[strIndex++] = readIntArray(n.getNodeName(), null); } else { throw new IOException("String array contains more elements than specified!"); } } } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } _currentElem = (Element) _currentElem.getParentNode(); return ret; } public float readFloat(final String name, final float defVal) throws IOException { float ret = defVal; try { final String s = _currentElem.getAttribute(name); if (s.length() > 0) { ret = Float.parseFloat(s); } } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public float[] readFloatArray(final String name, final float[] defVal) throws IOException { float[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final float[] tmp = new float[size]; final String[] strings = tmpEl.getAttribute("data").split("\\s+"); for (int i = 0; i < size; i++) { tmp[i] = Float.parseFloat(strings[i]); } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public float[][] readFloatArray2D(final String name, final float[][] defVal) throws IOException { float[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size_outer = Integer.parseInt(tmpEl.getAttribute("size_outer")); final int size_inner = Integer.parseInt(tmpEl.getAttribute("size_outer")); final float[][] tmp = new float[size_outer][size_inner]; final String[] strings = tmpEl.getAttribute("data").split("\\s+"); for (int i = 0; i < size_outer; i++) { tmp[i] = new float[size_inner]; for (int k = 0; k < size_inner; k++) { tmp[i][k] = Float.parseFloat(strings[i]); } } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public double readDouble(final String name, final double defVal) throws IOException { double ret = defVal; try { final String s = _currentElem.getAttribute(name); if (s.length() > 0) { ret = Double.parseDouble(s); } } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public double[] readDoubleArray(final String name, final double[] defVal) throws IOException { double[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final double[] tmp = new double[size]; final String[] strings = tmpEl.getAttribute("data").split("\\s+"); for (int i = 0; i < size; i++) { tmp[i] = Double.parseDouble(strings[i]); } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public double[][] readDoubleArray2D(final String name, final double[][] defVal) throws IOException { double[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final double[][] tmp = new double[size][]; final NodeList nodes = _currentElem.getChildNodes(); int strIndex = 0; for (int i = 0; i < nodes.getLength(); i++) { final Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("array")) { if (strIndex < size) { tmp[strIndex++] = readDoubleArray(n.getNodeName(), null); } else { throw new IOException("String array contains more elements than specified!"); } } } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } _currentElem = (Element) _currentElem.getParentNode(); return ret; } public long readLong(final String name, final long defVal) throws IOException { long ret = defVal; try { final String s = _currentElem.getAttribute(name); if (s.length() > 0) { ret = Long.parseLong(s); } } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public long[] readLongArray(final String name, final long[] defVal) throws IOException { long[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final long[] tmp = new long[size]; final String[] strings = tmpEl.getAttribute("data").split("\\s+"); for (int i = 0; i < size; i++) { tmp[i] = Long.parseLong(strings[i]); } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public long[][] readLongArray2D(final String name, final long[][] defVal) throws IOException { long[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final long[][] tmp = new long[size][]; final NodeList nodes = _currentElem.getChildNodes(); int strIndex = 0; for (int i = 0; i < nodes.getLength(); i++) { final Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("array")) { if (strIndex < size) { tmp[strIndex++] = readLongArray(n.getNodeName(), null); } else { throw new IOException("String array contains more elements than specified!"); } } } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } _currentElem = (Element) _currentElem.getParentNode(); return ret; } public short readShort(final String name, final short defVal) throws IOException { short ret = defVal; try { final String s = _currentElem.getAttribute(name); if (s.length() > 0) { ret = Short.parseShort(s); } } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public short[] readShortArray(final String name, final short[] defVal) throws IOException { short[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final short[] tmp = new short[size]; final String[] strings = tmpEl.getAttribute("data").split("\\s+"); for (int i = 0; i < size; i++) { tmp[i] = Short.parseShort(strings[i]); } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public short[][] readShortArray2D(final String name, final short[][] defVal) throws IOException { short[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final short[][] tmp = new short[size][]; final NodeList nodes = _currentElem.getChildNodes(); int strIndex = 0; for (int i = 0; i < nodes.getLength(); i++) { final Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("array")) { if (strIndex < size) { tmp[strIndex++] = readShortArray(n.getNodeName(), null); } else { throw new IOException("String array contains more elements than specified!"); } } } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } _currentElem = (Element) _currentElem.getParentNode(); return ret; } public boolean readBoolean(final String name, final boolean defVal) throws IOException { boolean ret = defVal; try { final String s = _currentElem.getAttribute(name); if (s.length() > 0) { ret = Boolean.parseBoolean(s); } } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public boolean[] readBooleanArray(final String name, final boolean[] defVal) throws IOException { boolean[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final boolean[] tmp = new boolean[size]; final String[] strings = tmpEl.getAttribute("data").split("\\s+"); for (int i = 0; i < size; i++) { tmp[i] = Boolean.parseBoolean(strings[i]); } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public boolean[][] readBooleanArray2D(final String name, final boolean[][] defVal) throws IOException { boolean[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final boolean[][] tmp = new boolean[size][]; final NodeList nodes = _currentElem.getChildNodes(); int strIndex = 0; for (int i = 0; i < nodes.getLength(); i++) { final Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("array")) { if (strIndex < size) { tmp[strIndex++] = readBooleanArray(n.getNodeName(), null); } else { throw new IOException("String array contains more elements than specified!"); } } } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } _currentElem = (Element) _currentElem.getParentNode(); return ret; } public String readString(final String name, final String defVal) throws IOException { String ret = defVal; try { ret = decodeString(_currentElem.getAttribute(name)); } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public String[] readStringArray(final String name, final String[] defVal) throws IOException { String[] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final String[] tmp = new String[size]; final NodeList nodes = tmpEl.getChildNodes(); int strIndex = 0; for (int i = 0; i < nodes.getLength(); i++) { final Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("String")) { if (strIndex < size) { tmp[strIndex++] = ((Element) n).getAttributeNode("value").getValue(); } else { throw new IOException("String array contains more elements than specified!"); } } } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } // _currentElem = (Element) _currentElem.getParentNode(); return ret; } public String[][] readStringArray2D(final String name, final String[][] defVal) throws IOException { String[][] ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final String[][] tmp = new String[size][]; final NodeList nodes = _currentElem.getChildNodes(); int strIndex = 0; for (int i = 0; i < nodes.getLength(); i++) { final Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().contains("array")) { if (strIndex < size) { tmp[strIndex++] = readStringArray(n.getNodeName(), null); } else { throw new IOException("String array contains more elements than specified!"); } } } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } _currentElem = (Element) _currentElem.getParentNode(); return ret; } public BitSet readBitSet(final String name, final BitSet defVal) throws IOException { BitSet ret = defVal; try { final BitSet set = new BitSet(); final String bitString = _currentElem.getAttribute(name); final String[] strings = bitString.split("\\s+"); for (int i = 0; i < strings.length; i++) { final int isSet = Integer.parseInt(strings[i]); if (isSet == 1) { set.set(i); } } ret = set; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public Savable readSavable(final String name, final Savable defVal) throws IOException { Savable ret = defVal; try { Element tmpEl = null; if (name != null) { tmpEl = findChildElement(_currentElem, name); if (tmpEl == null) { return defVal; } } else if (_isAtRoot) { tmpEl = _doc.getDocumentElement(); _isAtRoot = false; } else { tmpEl = findFirstChildElement(_currentElem); } _currentElem = tmpEl; ret = readSavableFromCurrentElem(defVal); if (_currentElem.getParentNode() instanceof Element) { _currentElem = (Element) _currentElem.getParentNode(); } else { _currentElem = null; } } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } private Savable readSavableFromCurrentElem(final Savable defVal) throws InstantiationException, ClassNotFoundException, IOException, IllegalAccessException { Savable ret = defVal; Savable tmp = null; if (_currentElem == null || _currentElem.getNodeName().equals("null")) { return null; } final String reference = _currentElem.getAttribute("ref"); if (reference.length() > 0) { ret = _referencedSavables.get(reference); } else { String className = _currentElem.getNodeName(); if (defVal != null) { className = defVal.getClass().getName(); } else if (_currentElem.hasAttribute("class")) { className = _currentElem.getAttribute("class"); } try { @SuppressWarnings("unchecked") final Class<? extends Savable> clazz = (Class<? extends Savable>) Class.forName(className); final SavableFactory ann = clazz.getAnnotation(SavableFactory.class); if (ann == null) { tmp = clazz.newInstance(); } else { tmp = (Savable) clazz.getMethod(ann.factoryMethod(), (Class<?>[]) null).invoke(null, (Object[]) null); } } catch (final InstantiationException e) { Logger.getLogger(getClass().getName()).logp( Level.SEVERE, this.getClass().toString(), "readSavableFromCurrentElem(Savable)", "Could not access constructor of class '" + className + "'! \n" + "Some types may require the annotation SavableFactory. Please double check."); throw new Ardor3dException(e); } catch (final NoSuchMethodException e) { Logger .getLogger(getClass().getName()) .logp( Level.SEVERE, this.getClass().toString(), "readSavableFromCurrentElem(Savable)", e.getMessage() + " \n" + "Method specified in annotation does not appear to exist or has an invalid method signature."); throw new Ardor3dException(e); } catch (final Exception e) { Logger.getLogger(getClass().getName()).logp(Level.SEVERE, this.getClass().toString(), "readSavableFromCurrentElem(Savable)", "Exception", e); return null; } final String refID = _currentElem.getAttribute("reference_ID"); if (refID.length() > 0) { _referencedSavables.put(refID, tmp); } if (tmp != null) { tmp.read(this); ret = tmp; } } return ret; } private TextureState readTextureStateFromCurrent() { final Element el = _currentElem; TextureState ret = null; try { ret = (TextureState) readSavableFromCurrentElem(null); final Savable[] savs = readSavableArray("texture", new Texture[0]); for (int i = 0; i < savs.length; i++) { Texture t = (Texture) savs[i]; final TextureKey tKey = t.getTextureKey(); t = TextureManager.loadFromKey(tKey, null, t); ret.setTexture(t, i); } } catch (final Exception e) { Logger.getLogger(DOMInputCapsule.class.getName()).log(Level.SEVERE, null, e); } _currentElem = el; return ret; } private Savable[] readRenderStateList(final Element fromElement, final Savable[] defVal) { Savable[] ret = defVal; try { final List<RenderState> tmp = new ArrayList<RenderState>(); _currentElem = findFirstChildElement(fromElement); while (_currentElem != null) { final Element el = _currentElem; RenderState rs = null; if (el.getNodeName().equals("com.ardor3d.scene.state.TextureState")) { rs = readTextureStateFromCurrent(); } else { rs = (RenderState) (readSavableFromCurrentElem(null)); } if (rs != null) { tmp.add(rs); } _currentElem = findNextSiblingElement(el); } ret = tmp.toArray(new RenderState[0]); } catch (final Exception e) { Logger.getLogger(DOMInputCapsule.class.getName()).log(Level.SEVERE, null, e); } return ret; } public Savable[] readSavableArray(final String name, final Savable[] defVal) throws IOException { Savable[] ret = defVal; try { final Element tmpEl = findChildElement(_currentElem, name); if (tmpEl == null) { return defVal; } if (name.equals("renderStateList")) { ret = readRenderStateList(tmpEl, defVal); } else { final int size = Integer.parseInt(tmpEl.getAttribute("size")); final Savable[] tmp = new Savable[size]; _currentElem = findFirstChildElement(tmpEl); for (int i = 0; i < size; i++) { tmp[i] = (readSavableFromCurrentElem(null)); if (i == size - 1) { break; } _currentElem = findNextSiblingElement(_currentElem); } ret = tmp; } _currentElem = (Element) tmpEl.getParentNode(); } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public Savable[][] readSavableArray2D(final String name, final Savable[][] defVal) throws IOException { Savable[][] ret = defVal; try { final Element tmpEl = findChildElement(_currentElem, name); if (tmpEl == null) { return defVal; } final int size_outer = Integer.parseInt(tmpEl.getAttribute("size_outer")); final int size_inner = Integer.parseInt(tmpEl.getAttribute("size_outer")); final Savable[][] tmp = new Savable[size_outer][size_inner]; _currentElem = findFirstChildElement(tmpEl); for (int i = 0; i < size_outer; i++) { for (int j = 0; j < size_inner; j++) { tmp[i][j] = (readSavableFromCurrentElem(null)); if (i == size_outer - 1 && j == size_inner - 1) { break; } _currentElem = findNextSiblingElement(_currentElem); } } ret = tmp; _currentElem = (Element) tmpEl.getParentNode(); } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } @SuppressWarnings("unchecked") public <E extends Savable> List<E> readSavableList(final String name, final List<E> defVal) throws IOException { List<E> ret = defVal; try { final Element tmpEl = findChildElement(_currentElem, name); if (tmpEl == null) { return defVal; } final String s = tmpEl.getAttribute("size"); final int size = Integer.parseInt(s); final List tmp = new ArrayList(); _currentElem = findFirstChildElement(tmpEl); for (int i = 0; i < size; i++) { tmp.add(readSavableFromCurrentElem(null)); if (i == size - 1) { break; } _currentElem = findNextSiblingElement(_currentElem); } ret = tmp; _currentElem = (Element) tmpEl.getParentNode(); } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } @SuppressWarnings("unchecked") public <E extends Savable> List<E>[] readSavableListArray(final String name, final List<E>[] defVal) throws IOException { List<E>[] ret = defVal; try { final Element tmpEl = findChildElement(_currentElem, name); if (tmpEl == null) { return defVal; } _currentElem = tmpEl; final int size = Integer.parseInt(tmpEl.getAttribute("size")); final List<E>[] tmp = new ArrayList[size]; for (int i = 0; i < size; i++) { final StringBuilder buf = new StringBuilder("SavableArrayList_"); buf.append(i); final List<E> al = readSavableList(buf.toString(), null); tmp[i] = al; if (i == size - 1) { break; } } ret = tmp; _currentElem = (Element) tmpEl.getParentNode(); } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } @SuppressWarnings("unchecked") public <E extends Savable> List<E>[][] readSavableListArray2D(final String name, final List<E>[][] defVal) throws IOException { List<E>[][] ret = defVal; try { final Element tmpEl = findChildElement(_currentElem, name); if (tmpEl == null) { return defVal; } _currentElem = tmpEl; final int size = Integer.parseInt(tmpEl.getAttribute("size")); final List[][] tmp = new ArrayList[size][]; for (int i = 0; i < size; i++) { final List[] arr = readSavableListArray("SavableArrayListArray_" + i, null); tmp[i] = arr; } ret = tmp; _currentElem = (Element) tmpEl.getParentNode(); } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public List<FloatBuffer> readFloatBufferList(final String name, final List<FloatBuffer> defVal) throws IOException { List<FloatBuffer> ret = defVal; try { final Element tmpEl = findChildElement(_currentElem, name); if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final List<FloatBuffer> tmp = new ArrayList<FloatBuffer>(size); _currentElem = findFirstChildElement(tmpEl); for (int i = 0; i < size; i++) { tmp.add(readFloatBuffer(null, null)); if (i == size - 1) { break; } _currentElem = findNextSiblingElement(_currentElem); } ret = tmp; _currentElem = (Element) tmpEl.getParentNode(); } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } @SuppressWarnings("unchecked") public <K extends Savable, V extends Savable> Map<K, V> readSavableMap(final String name, final Map<K, V> defVal) throws IOException { Map<K, V> ret; Element tempEl; if (name != null) { tempEl = findChildElement(_currentElem, name); } else { tempEl = _currentElem; } ret = new HashMap<K, V>(); final NodeList nodes = tempEl.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { final Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().equals("MapEntry")) { final Element elem = (Element) n; _currentElem = elem; final K key = (K) readSavable(XMLExporter.ELEMENT_KEY, null); final V val = (V) readSavable(XMLExporter.ELEMENT_VALUE, null); ret.put(key, val); } } _currentElem = (Element) tempEl.getParentNode(); return ret; } @SuppressWarnings("unchecked") public <V extends Savable> Map<String, V> readStringSavableMap(final String name, final Map<String, V> defVal) throws IOException { Map<String, V> ret = null; Element tempEl; if (name != null) { tempEl = findChildElement(_currentElem, name); } else { tempEl = _currentElem; } if (tempEl != null) { ret = new HashMap<String, V>(); final NodeList nodes = tempEl.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { final Node n = nodes.item(i); if (n instanceof Element && n.getNodeName().equals("MapEntry")) { final Element elem = (Element) n; _currentElem = elem; final String key = _currentElem.getAttribute("key"); final V val = (V) readSavable("Savable", null); ret.put(key, val); } } } else { return defVal; } _currentElem = (Element) tempEl.getParentNode(); return ret; } /** * reads from currentElem if name is null */ public FloatBuffer readFloatBuffer(final String name, final FloatBuffer defVal) throws IOException { FloatBuffer ret = defVal; try { Element tmpEl; if (name != null) { tmpEl = findChildElement(_currentElem, name); } else { tmpEl = _currentElem; } if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final FloatBuffer tmp = BufferUtils.createFloatBuffer(size); if (size > 0) { final String[] strings = tmpEl.getAttribute("data").split("\\s+"); for (final String s : strings) { tmp.put(Float.parseFloat(s)); } tmp.flip(); } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public IntBuffer readIntBuffer(final String name, final IntBuffer defVal) throws IOException { IntBuffer ret = defVal; try { final Element tmpEl = findChildElement(_currentElem, name); if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final IntBuffer tmp = BufferUtils.createIntBuffer(size); if (size > 0) { final String[] strings = tmpEl.getAttribute("data").split("\\s+"); for (final String s : strings) { tmp.put(Integer.parseInt(s)); } tmp.flip(); } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public ByteBuffer readByteBuffer(final String name, final ByteBuffer defVal) throws IOException { ByteBuffer ret = defVal; try { final Element tmpEl = findChildElement(_currentElem, name); if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final ByteBuffer tmp = BufferUtils.createByteBuffer(size); if (size > 0) { final String[] strings = tmpEl.getAttribute("data").split("\\s+"); for (final String s : strings) { tmp.put(Byte.valueOf(s)); } tmp.flip(); } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public ShortBuffer readShortBuffer(final String name, final ShortBuffer defVal) throws IOException { ShortBuffer ret = defVal; try { final Element tmpEl = findChildElement(_currentElem, name); if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final ShortBuffer tmp = BufferUtils.createShortBuffer(size); if (size > 0) { final String[] strings = tmpEl.getAttribute("data").split("\\s+"); for (final String s : strings) { tmp.put(Short.valueOf(s)); } tmp.flip(); } ret = tmp; } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public List<ByteBuffer> readByteBufferList(final String name, final List<ByteBuffer> defVal) throws IOException { List<ByteBuffer> ret = defVal; try { final Element tmpEl = findChildElement(_currentElem, name); if (tmpEl == null) { return defVal; } final int size = Integer.parseInt(tmpEl.getAttribute("size")); final List<ByteBuffer> tmp = new ArrayList<ByteBuffer>(size); _currentElem = findFirstChildElement(tmpEl); for (int i = 0; i < size; i++) { tmp.add(readByteBuffer(null, null)); if (i == size - 1) { break; } _currentElem = findNextSiblingElement(_currentElem); } ret = tmp; _currentElem = (Element) tmpEl.getParentNode(); } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } public <T extends Enum<T>> T readEnum(final String name, final Class<T> enumType, final T defVal) throws IOException { T ret = defVal; try { final String eVal = _currentElem.getAttribute(name); if (eVal != null && eVal.length() > 0) { ret = Enum.valueOf(enumType, eVal); } } catch (final Exception e) { final IOException ex = new IOException(); ex.initCause(e); throw ex; } return ret; } @SuppressWarnings("unchecked") public <T extends Enum<T>> T[] readEnumArray(final String name, final Class<T> enumType, final T[] defVal) throws IOException { final String[] eVals = readStringArray(name, null); if (eVals != null) { final T[] rVal = (T[]) Array.newInstance(enumType, eVals.length); int i = 0; for (final String eVal : eVals) { rVal[i++] = Enum.valueOf(enumType, eVal); } return rVal; } else { return defVal; } } }
kaituo/sedge
trunk/test/org/apache/pig/test/TestPhyOp.java
<gh_stars>1-10 /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pig.test; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.data.Tuple; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.PhysicalOperator; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.POStatus; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.Result; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators.ConstantExpression; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators.GreaterThanExpr; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhyPlanVisitor; import org.apache.pig.test.utils.GenPhyOp; import org.apache.pig.test.utils.GenRandomData; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestPhyOp extends junit.framework.TestCase { PhysicalOperator op; PhysicalOperator inpOp; Tuple t; @Before public void setUp() throws Exception { op = GenPhyOp.topFilterOp(); inpOp = GenPhyOp.topFilterOpWithExPlan(25, 10); t = GenRandomData.genRandSmallBagTuple(new Random(), 10, 100); } @After public void tearDown() throws Exception { } @Test public void testProcessInput() throws ExecException { // Stand-alone tests Result res = op.processInput(); assertEquals(POStatus.STATUS_EOP, res.returnStatus); op.attachInput(t); res = op.processInput(); assertEquals(POStatus.STATUS_OK, res.returnStatus); assertEquals(t, res.result); op.detachInput(); res = op.processInput(); assertEquals(POStatus.STATUS_EOP, res.returnStatus); // With input operator List<PhysicalOperator> inp = new ArrayList<PhysicalOperator>(); inp.add(inpOp); op.setInputs(inp); op.processInput(); assertEquals(POStatus.STATUS_EOP, res.returnStatus); inpOp.attachInput(t); res = op.processInput(); assertEquals(POStatus.STATUS_OK, res.returnStatus); assertEquals(t, res.result); inpOp.detachInput(); res = op.processInput(); assertEquals(POStatus.STATUS_EOP, res.returnStatus); } }
emilyemorehouse/ast-and-me
code/tmp_rtrip/threading.py
<reponame>emilyemorehouse/ast-and-me """Thread module emulating a subset of Java's threading model.""" import sys as _sys import _thread from time import monotonic as _time from traceback import format_exc as _format_exc from _weakrefset import WeakSet from itertools import islice as _islice, count as _count try: from _collections import deque as _deque except ImportError: from collections import deque as _deque __all__ = ['get_ident', 'active_count', 'Condition', 'current_thread', 'enumerate', 'main_thread', 'TIMEOUT_MAX', 'Event', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Barrier', 'BrokenBarrierError', 'Timer', 'ThreadError', 'setprofile', 'settrace', 'local', 'stack_size'] _start_new_thread = _thread.start_new_thread _allocate_lock = _thread.allocate_lock _set_sentinel = _thread._set_sentinel get_ident = _thread.get_ident ThreadError = _thread.error try: _CRLock = _thread.RLock except AttributeError: _CRLock = None TIMEOUT_MAX = _thread.TIMEOUT_MAX del _thread _profile_hook = None _trace_hook = None def setprofile(func): """Set a profile function for all threads started from the threading module. The func will be passed to sys.setprofile() for each thread, before its run() method is called. """ global _profile_hook _profile_hook = func def settrace(func): """Set a trace function for all threads started from the threading module. The func will be passed to sys.settrace() for each thread, before its run() method is called. """ global _trace_hook _trace_hook = func Lock = _allocate_lock def RLock(*args, **kwargs): """Factory function that returns a new reentrant lock. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it. """ if _CRLock is None: return _PyRLock(*args, **kwargs) return _CRLock(*args, **kwargs) class _RLock: """This class implements reentrant lock objects. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it. """ def __init__(self): self._block = _allocate_lock() self._owner = None self._count = 0 def __repr__(self): owner = self._owner try: owner = _active[owner].name except KeyError: pass return '<%s %s.%s object owner=%r count=%d at %s>' % ('locked' if self._block.locked() else 'unlocked', self.__class__.__module__, self.__class__.__qualname__, owner, self._count, hex(id(self))) def acquire(self, blocking=True, timeout=-1): """Acquire a lock, blocking or non-blocking. When invoked without arguments: if this thread already owns the lock, increment the recursion level by one, and return immediately. Otherwise, if another thread owns the lock, block until the lock is unlocked. Once the lock is unlocked (not owned by any thread), then grab ownership, set the recursion level to one, and return. If more than one thread is blocked waiting until the lock is unlocked, only one at a time will be able to grab ownership of the lock. There is no return value in this case. When invoked with the blocking argument set to true, do the same thing as when called without arguments, and return true. When invoked with the blocking argument set to false, do not block. If a call without an argument would block, return false immediately; otherwise, do the same thing as when called without arguments, and return true. When invoked with the floating-point timeout argument set to a positive value, block for at most the number of seconds specified by timeout and as long as the lock cannot be acquired. Return true if the lock has been acquired, false if the timeout has elapsed. """ me = get_ident() if self._owner == me: self._count += 1 return 1 rc = self._block.acquire(blocking, timeout) if rc: self._owner = me self._count = 1 return rc __enter__ = acquire def release(self): """Release a lock, decrementing the recursion level. If after the decrement it is zero, reset the lock to unlocked (not owned by any thread), and if any other threads are blocked waiting for the lock to become unlocked, allow exactly one of them to proceed. If after the decrement the recursion level is still nonzero, the lock remains locked and owned by the calling thread. Only call this method when the calling thread owns the lock. A RuntimeError is raised if this method is called when the lock is unlocked. There is no return value. """ if self._owner != get_ident(): raise RuntimeError('cannot release un-acquired lock') self._count = count = self._count - 1 if not count: self._owner = None self._block.release() def __exit__(self, t, v, tb): self.release() def _acquire_restore(self, state): self._block.acquire() self._count, self._owner = state def _release_save(self): if self._count == 0: raise RuntimeError('cannot release un-acquired lock') count = self._count self._count = 0 owner = self._owner self._owner = None self._block.release() return count, owner def _is_owned(self): return self._owner == get_ident() _PyRLock = _RLock class Condition: """Class that implements a condition variable. A condition variable allows one or more threads to wait until they are notified by another thread. If the lock argument is given and not None, it must be a Lock or RLock object, and it is used as the underlying lock. Otherwise, a new RLock object is created and used as the underlying lock. """ def __init__(self, lock=None): if lock is None: lock = RLock() self._lock = lock self.acquire = lock.acquire self.release = lock.release try: self._release_save = lock._release_save except AttributeError: pass try: self._acquire_restore = lock._acquire_restore except AttributeError: pass try: self._is_owned = lock._is_owned except AttributeError: pass self._waiters = _deque() def __enter__(self): return self._lock.__enter__() def __exit__(self, *args): return self._lock.__exit__(*args) def __repr__(self): return '<Condition(%s, %d)>' % (self._lock, len(self._waiters)) def _release_save(self): self._lock.release() def _acquire_restore(self, x): self._lock.acquire() def _is_owned(self): if self._lock.acquire(0): self._lock.release() return False else: return True def wait(self, timeout=None): """Wait until notified or until a timeout occurs. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method releases the underlying lock, and then blocks until it is awakened by a notify() or notify_all() call for the same condition variable in another thread, or until the optional timeout occurs. Once awakened or timed out, it re-acquires the lock and returns. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). When the underlying lock is an RLock, it is not released using its release() method, since this may not actually unlock the lock when it was acquired multiple times recursively. Instead, an internal interface of the RLock class is used, which really unlocks it even when it has been recursively acquired several times. Another internal interface is then used to restore the recursion level when the lock is reacquired. """ if not self._is_owned(): raise RuntimeError('cannot wait on un-acquired lock') waiter = _allocate_lock() waiter.acquire() self._waiters.append(waiter) saved_state = self._release_save() gotit = False try: if timeout is None: waiter.acquire() gotit = True elif timeout > 0: gotit = waiter.acquire(True, timeout) else: gotit = waiter.acquire(False) return gotit finally: self._acquire_restore(saved_state) if not gotit: try: self._waiters.remove(waiter) except ValueError: pass def wait_for(self, predicate, timeout=None): """Wait until a condition evaluates to True. predicate should be a callable which result will be interpreted as a boolean value. A timeout may be provided giving the maximum time to wait. """ endtime = None waittime = timeout result = predicate() while not result: if waittime is not None: if endtime is None: endtime = _time() + waittime else: waittime = endtime - _time() if waittime <= 0: break self.wait(waittime) result = predicate() return result def notify(self, n=1): """Wake up one or more threads waiting on this condition, if any. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. This method wakes up at most n of the threads waiting for the condition variable; it is a no-op if no threads are waiting. """ if not self._is_owned(): raise RuntimeError('cannot notify on un-acquired lock') all_waiters = self._waiters waiters_to_notify = _deque(_islice(all_waiters, n)) if not waiters_to_notify: return for waiter in waiters_to_notify: waiter.release() try: all_waiters.remove(waiter) except ValueError: pass def notify_all(self): """Wake up all threads waiting on this condition. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. """ self.notify(len(self._waiters)) notifyAll = notify_all class Semaphore: """This class implements semaphore objects. Semaphores manage a counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1. """ def __init__(self, value=1): if value < 0: raise ValueError('semaphore initial value must be >= 0') self._cond = Condition(Lock()) self._value = value def acquire(self, blocking=True, timeout=None): """Acquire a semaphore, decrementing the internal counter by one. When invoked without arguments: if the internal counter is larger than zero on entry, decrement it by one and return immediately. If it is zero on entry, block, waiting until some other thread has called release() to make it larger than zero. This is done with proper interlocking so that if multiple acquire() calls are blocked, release() will wake exactly one of them up. The implementation may pick one at random, so the order in which blocked threads are awakened should not be relied on. There is no return value in this case. When invoked with blocking set to true, do the same thing as when called without arguments, and return true. When invoked with blocking set to false, do not block. If a call without an argument would block, return false immediately; otherwise, do the same thing as when called without arguments, and return true. When invoked with a timeout other than None, it will block for at most timeout seconds. If acquire does not complete successfully in that interval, return false. Return true otherwise. """ if not blocking and timeout is not None: raise ValueError("can't specify timeout for non-blocking acquire") rc = False endtime = None with self._cond: while self._value == 0: if not blocking: break if timeout is not None: if endtime is None: endtime = _time() + timeout else: timeout = endtime - _time() if timeout <= 0: break self._cond.wait(timeout) else: self._value -= 1 rc = True return rc __enter__ = acquire def release(self): """Release a semaphore, incrementing the internal counter by one. When the counter is zero on entry and another thread is waiting for it to become larger than zero again, wake up that thread. """ with self._cond: self._value += 1 self._cond.notify() def __exit__(self, t, v, tb): self.release() class BoundedSemaphore(Semaphore): """Implements a bounded semaphore. A bounded semaphore checks to make sure its current value doesn't exceed its initial value. If it does, ValueError is raised. In most situations semaphores are used to guard resources with limited capacity. If the semaphore is released too many times it's a sign of a bug. If not given, value defaults to 1. Like regular semaphores, bounded semaphores manage a counter representing the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative. If not given, value defaults to 1. """ def __init__(self, value=1): Semaphore.__init__(self, value) self._initial_value = value def release(self): """Release a semaphore, incrementing the internal counter by one. When the counter is zero on entry and another thread is waiting for it to become larger than zero again, wake up that thread. If the number of releases exceeds the number of acquires, raise a ValueError. """ with self._cond: if self._value >= self._initial_value: raise ValueError('Semaphore released too many times') self._value += 1 self._cond.notify() class Event: """Class implementing event objects. Events manage a flag that can be set to true with the set() method and reset to false with the clear() method. The wait() method blocks until the flag is true. The flag is initially false. """ def __init__(self): self._cond = Condition(Lock()) self._flag = False def _reset_internal_locks(self): self._cond.__init__(Lock()) def is_set(self): """Return true if and only if the internal flag is true.""" return self._flag isSet = is_set def set(self): """Set the internal flag to true. All threads waiting for it to become true are awakened. Threads that call wait() once the flag is true will not block at all. """ with self._cond: self._flag = True self._cond.notify_all() def clear(self): """Reset the internal flag to false. Subsequently, threads calling wait() will block until set() is called to set the internal flag to true again. """ with self._cond: self._flag = False def wait(self, timeout=None): """Block until the internal flag is true. If the internal flag is true on entry, return immediately. Otherwise, block until another thread calls set() to set the flag to true, or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). This method returns the internal flag on exit, so it will always return True except if a timeout is given and the operation times out. """ with self._cond: signaled = self._flag if not signaled: signaled = self._cond.wait(timeout) return signaled class Barrier: """Implements a Barrier. Useful for synchronizing a fixed number of threads at known synchronization points. Threads block on 'wait()' and are simultaneously once they have all made that call. """ def __init__(self, parties, action=None, timeout=None): """Create a barrier, initialised to 'parties' threads. 'action' is a callable which, when supplied, will be called by one of the threads after they have all entered the barrier and just prior to releasing them all. If a 'timeout' is provided, it is uses as the default for all subsequent 'wait()' calls. """ self._cond = Condition(Lock()) self._action = action self._timeout = timeout self._parties = parties self._state = 0 self._count = 0 def wait(self, timeout=None): """Wait for the barrier. When the specified number of threads have started waiting, they are all simultaneously awoken. If an 'action' was provided for the barrier, one of the threads will have executed that callback prior to returning. Returns an individual index number from 0 to 'parties-1'. """ if timeout is None: timeout = self._timeout with self._cond: self._enter() index = self._count self._count += 1 try: if index + 1 == self._parties: self._release() else: self._wait(timeout) return index finally: self._count -= 1 self._exit() def _enter(self): while self._state in (-1, 1): self._cond.wait() if self._state < 0: raise BrokenBarrierError assert self._state == 0 def _release(self): try: if self._action: self._action() self._state = 1 self._cond.notify_all() except: self._break() raise def _wait(self, timeout): if not self._cond.wait_for(lambda : self._state != 0, timeout): self._break() raise BrokenBarrierError if self._state < 0: raise BrokenBarrierError assert self._state == 1 def _exit(self): if self._count == 0: if self._state in (-1, 1): self._state = 0 self._cond.notify_all() def reset(self): """Reset the barrier to the initial state. Any threads currently waiting will get the BrokenBarrier exception raised. """ with self._cond: if self._count > 0: if self._state == 0: self._state = -1 elif self._state == -2: self._state = -1 else: self._state = 0 self._cond.notify_all() def abort(self): """Place the barrier into a 'broken' state. Useful in case of error. Any currently waiting threads and threads attempting to 'wait()' will have BrokenBarrierError raised. """ with self._cond: self._break() def _break(self): self._state = -2 self._cond.notify_all() @property def parties(self): """Return the number of threads required to trip the barrier.""" return self._parties @property def n_waiting(self): """Return the number of threads currently waiting at the barrier.""" if self._state == 0: return self._count return 0 @property def broken(self): """Return True if the barrier is in a broken state.""" return self._state == -2 class BrokenBarrierError(RuntimeError): pass _counter = _count().__next__ _counter() def _newname(template='Thread-%d'): return template % _counter() _active_limbo_lock = _allocate_lock() _active = {} _limbo = {} _dangling = WeakSet() class Thread: """A class that represents a thread of control. This class can be safely subclassed in a limited fashion. There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass. """ _initialized = False _exc_info = _sys.exc_info def __init__(self, group=None, target=None, name=None, args=(), kwargs= None, *, daemon=None): """This constructor should always be called with keyword arguments. Arguments are: *group* should be None; reserved for future extension when a ThreadGroup class is implemented. *target* is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called. *name* is the thread name. By default, a unique name is constructed of the form "Thread-N" where N is a small decimal number. *args* is the argument tuple for the target invocation. Defaults to (). *kwargs* is a dictionary of keyword arguments for the target invocation. Defaults to {}. If a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread. """ assert group is None, 'group argument must be None for now' if kwargs is None: kwargs = {} self._target = target self._name = str(name or _newname()) self._args = args self._kwargs = kwargs if daemon is not None: self._daemonic = daemon else: self._daemonic = current_thread().daemon self._ident = None self._tstate_lock = None self._started = Event() self._is_stopped = False self._initialized = True self._stderr = _sys.stderr _dangling.add(self) def _reset_internal_locks(self, is_alive): self._started._reset_internal_locks() if is_alive: self._set_tstate_lock() else: self._is_stopped = True self._tstate_lock = None def __repr__(self): assert self._initialized, 'Thread.__init__() was not called' status = 'initial' if self._started.is_set(): status = 'started' self.is_alive() if self._is_stopped: status = 'stopped' if self._daemonic: status += ' daemon' if self._ident is not None: status += ' %s' % self._ident return '<%s(%s, %s)>' % (self.__class__.__name__, self._name, status) def start(self): """Start the thread's activity. It must be called at most once per thread object. It arranges for the object's run() method to be invoked in a separate thread of control. This method will raise a RuntimeError if called more than once on the same thread object. """ if not self._initialized: raise RuntimeError('thread.__init__() not called') if self._started.is_set(): raise RuntimeError('threads can only be started once') with _active_limbo_lock: _limbo[self] = self try: _start_new_thread(self._bootstrap, ()) except Exception: with _active_limbo_lock: del _limbo[self] raise self._started.wait() def run(self): """Method representing the thread's activity. You may override this method in a subclass. The standard run() method invokes the callable object passed to the object's constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively. """ try: if self._target: self._target(*self._args, **self._kwargs) finally: del self._target, self._args, self._kwargs def _bootstrap(self): try: self._bootstrap_inner() except: if self._daemonic and _sys is None: return raise def _set_ident(self): self._ident = get_ident() def _set_tstate_lock(self): """ Set a lock object which will be released by the interpreter when the underlying thread state (see pystate.h) gets deleted. """ self._tstate_lock = _set_sentinel() self._tstate_lock.acquire() def _bootstrap_inner(self): try: self._set_ident() self._set_tstate_lock() self._started.set() with _active_limbo_lock: _active[self._ident] = self del _limbo[self] if _trace_hook: _sys.settrace(_trace_hook) if _profile_hook: _sys.setprofile(_profile_hook) try: self.run() except SystemExit: pass except: if _sys and _sys.stderr is not None: print('Exception in thread %s:\n%s' % (self.name, _format_exc()), file=_sys.stderr) elif self._stderr is not None: exc_type, exc_value, exc_tb = self._exc_info() try: print('Exception in thread ' + self.name + ' (most likely raised during interpreter shutdown):' , file=self._stderr) print('Traceback (most recent call last):', file= self._stderr) while exc_tb: print(' File "%s", line %s, in %s' % (exc_tb. tb_frame.f_code.co_filename, exc_tb. tb_lineno, exc_tb.tb_frame.f_code.co_name), file=self._stderr) exc_tb = exc_tb.tb_next print('%s: %s' % (exc_type, exc_value), file=self. _stderr) finally: del exc_type, exc_value, exc_tb finally: pass finally: with _active_limbo_lock: try: del _active[get_ident()] except: pass def _stop(self): lock = self._tstate_lock if lock is not None: assert not lock.locked() self._is_stopped = True self._tstate_lock = None def _delete(self): """Remove current thread from the dict of currently running threads.""" try: with _active_limbo_lock: del _active[get_ident()] except KeyError: if 'dummy_threading' not in _sys.modules: raise def join(self, timeout=None): """Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates -- either normally or through an unhandled exception or until the optional timeout occurs. When the timeout argument is present and not None, it should be a floating point number specifying a timeout for the operation in seconds (or fractions thereof). As join() always returns None, you must call isAlive() after join() to decide whether a timeout happened -- if the thread is still alive, the join() call timed out. When the timeout argument is not present or None, the operation will block until the thread terminates. A thread can be join()ed many times. join() raises a RuntimeError if an attempt is made to join the current thread as that would cause a deadlock. It is also an error to join() a thread before it has been started and attempts to do so raises the same exception. """ if not self._initialized: raise RuntimeError('Thread.__init__() not called') if not self._started.is_set(): raise RuntimeError('cannot join thread before it is started') if self is current_thread(): raise RuntimeError('cannot join current thread') if timeout is None: self._wait_for_tstate_lock() else: self._wait_for_tstate_lock(timeout=max(timeout, 0)) def _wait_for_tstate_lock(self, block=True, timeout=-1): lock = self._tstate_lock if lock is None: assert self._is_stopped elif lock.acquire(block, timeout): lock.release() self._stop() @property def name(self): """A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor. """ assert self._initialized, 'Thread.__init__() not called' return self._name @name.setter def name(self, name): assert self._initialized, 'Thread.__init__() not called' self._name = str(name) @property def ident(self): """Thread identifier of this thread or None if it has not been started. This is a nonzero integer. See the thread.get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited. """ assert self._initialized, 'Thread.__init__() not called' return self._ident def is_alive(self): """Return whether the thread is alive. This method returns True just before the run() method starts until just after the run() method terminates. The module function enumerate() returns a list of all alive threads. """ assert self._initialized, 'Thread.__init__() not called' if self._is_stopped or not self._started.is_set(): return False self._wait_for_tstate_lock(False) return not self._is_stopped isAlive = is_alive @property def daemon(self): """A boolean value indicating whether this thread is a daemon thread. This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False. The entire Python program exits when no alive non-daemon threads are left. """ assert self._initialized, 'Thread.__init__() not called' return self._daemonic @daemon.setter def daemon(self, daemonic): if not self._initialized: raise RuntimeError('Thread.__init__() not called') if self._started.is_set(): raise RuntimeError('cannot set daemon status of active thread') self._daemonic = daemonic def isDaemon(self): return self.daemon def setDaemon(self, daemonic): self.daemon = daemonic def getName(self): return self.name def setName(self, name): self.name = name class Timer(Thread): """Call a function after a specified number of seconds: t = Timer(30.0, f, args=None, kwargs=None) t.start() t.cancel() # stop the timer's action if it's still waiting """ def __init__(self, interval, function, args=None, kwargs=None): Thread.__init__(self) self.interval = interval self.function = function self.args = args if args is not None else [] self.kwargs = kwargs if kwargs is not None else {} self.finished = Event() def cancel(self): """Stop the timer if it hasn't finished yet.""" self.finished.set() def run(self): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) self.finished.set() class _MainThread(Thread): def __init__(self): Thread.__init__(self, name='MainThread', daemon=False) self._set_tstate_lock() self._started.set() self._set_ident() with _active_limbo_lock: _active[self._ident] = self class _DummyThread(Thread): def __init__(self): Thread.__init__(self, name=_newname('Dummy-%d'), daemon=True) self._started.set() self._set_ident() with _active_limbo_lock: _active[self._ident] = self def _stop(self): pass def is_alive(self): assert not self._is_stopped and self._started.is_set() return True def join(self, timeout=None): assert False, 'cannot join a dummy thread' def current_thread(): """Return the current Thread object, corresponding to the caller's thread of control. If the caller's thread of control was not created through the threading module, a dummy thread object with limited functionality is returned. """ try: return _active[get_ident()] except KeyError: return _DummyThread() currentThread = current_thread def active_count(): """Return the number of Thread objects currently alive. The returned count is equal to the length of the list returned by enumerate(). """ with _active_limbo_lock: return len(_active) + len(_limbo) activeCount = active_count def _enumerate(): return list(_active.values()) + list(_limbo.values()) def enumerate(): """Return a list of all Thread objects currently alive. The list includes daemonic threads, dummy thread objects created by current_thread(), and the main thread. It excludes terminated threads and threads that have not yet been started. """ with _active_limbo_lock: return list(_active.values()) + list(_limbo.values()) from _thread import stack_size _main_thread = _MainThread() def _shutdown(): tlock = _main_thread._tstate_lock assert tlock is not None assert tlock.locked() tlock.release() _main_thread._stop() t = _pickSomeNonDaemonThread() while t: t.join() t = _pickSomeNonDaemonThread() _main_thread._delete() def _pickSomeNonDaemonThread(): for t in enumerate(): if not t.daemon and t.is_alive(): return t return None def main_thread(): """Return the main thread object. In normal conditions, the main thread is the thread from which the Python interpreter was started. """ return _main_thread try: from _thread import _local as local except ImportError: from _threading_local import local def _after_fork(): global _active_limbo_lock, _main_thread _active_limbo_lock = _allocate_lock() new_active = {} current = current_thread() _main_thread = current with _active_limbo_lock: threads = set(_enumerate()) threads.update(_dangling) for thread in threads: if thread is current: thread._reset_internal_locks(True) ident = get_ident() thread._ident = ident new_active[ident] = thread else: thread._reset_internal_locks(False) thread._stop() _limbo.clear() _active.clear() _active.update(new_active) assert len(_active) == 1
NidhishG/thegodhype
commands/moderation/ccmake.js
<filename>commands/moderation/ccmake.js<gh_stars>0 const Discord = require('discord.js') const db = require('quick.db') module.exports = { config:{ name: 'ccmake', description: 'Add a tag', usage: 'tag <command> <reply>', guildOnly: true, }, async execute(client, message, args) { if (!message.member.hasPermission("ADMINISTRATOR")) return message.channel.send('try again... when you have perms') let command = args[0] let reply = args.slice(1).join(" ") if (!command) return message.channel.send({ embed: { title: 'Error', description: 'Missing Command Name', fields: [{ name: 'Usage:', value: '`ccmake <command> <reply`' }] } }) if (!reply) return message.channel.send({ embed: { title: 'Error', description: 'Missing Command Reply', fields: [{ name: 'Usage:', value: '`addtag <command> <reply`' }] } }) if(db.get(`tag_${message.guild.id}_${command}`) !== null) return message.channel.send({ embed: { title: 'Error', description: 'This tag already exists', } }) db.set(`tag_${message.guild.id}_${command}`, reply) await message.channel.send({ embed: { title: 'Success!', color: 'GREEN', description: `I have added the tag \`${command}\` with a reply of \`${reply}\`` } }) } }
hsingh23/classwhole
test/unit/helpers/scheduler_helper_test.rb
require 'test_helper' class SchedulerHelperTest < ActionView::TestCase end
flowmemo/leetcode-in-js
test/solution/012.js
<gh_stars>1-10 const data = [ { input: [2568], ans: 'MMDLXVIII' }, { input: [125], ans: 'CXXV' }, { input: [501], ans: 'DI' } ] module.exports = { data, checker: require('../checkers.js').normalChecker }
lauriscx/DEngine
src/Application/Application.h
#pragma once #include "Core/Core.h" #include "AppContext.h" #include "AppConfig.h" #include "Core/EventSystem/EventHandler.h" #include "Core/InputSystem/InputHandler.h" #include "Core/ModuleSystem/Module.h" #include "Core/ModuleSystem/ModuleRegistry.h" #include "Core/Hardware/Device.h" #include "Core/Utils/Timer.h" #include <filesystem> #include "Core/FileSystem/VFS/VFS.h" #include "mono/metadata/assembly.h" //#define MT_SCHEDULER_PROFILER_TASK_SCOPE_CODE_INJECTION( TYPE, DEBUG_COLOR, SRC_FILE, SRC_LINE) OPTICK_CATEGORY( MT_TEXT( #TYPE ), OPTICK_MAKE_CATEGORY(0, DEBUG_COLOR) ); namespace AppFrame { class Application : public EventHandler, public InputHandler, public ModuleRegistry, public AppContext { public: Application(AppFrame::AppConfig* config); inline void SetConfig(AppConfig* config) { m_Config = config; } virtual void Run(); virtual void OnEarlyUpdate(); virtual void OnUpdate(); virtual void OnLateUpdate(); virtual bool OnEvent(BasicEvent& event) override; virtual bool OnInput(const InputData& input) override; template<typename T> static T* Module() { return s_Instance->GetModule<T>(); } static Application* GetInstance() { return s_Instance; } static void SetInstance(Application* instance) { s_Instance = instance; } virtual AppConfig * GetConfig(); virtual Device * GetDevice(); virtual void Stop(); virtual ~Application(); /* Application data */ private: AppConfig * m_Config; Device * m_Device; Timer m_Timer; static Application* s_Instance; }; }
arslantalib3/algo_ds_101
Maths_And_Stats/Geometry/Polar_Cartesian_Conversion/Polar_Cartesian_Conversion.java
import java.util.Scanner; public class PolarCartesian { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Input radius: "); double radius = sc.nextDouble(); System.out.print("Input theta in degrees: "); double theta = sc.nextDouble(); // converting theta from degrees to radians theta = theta * Math.PI / 180f; double x = radius * Math.cos(theta); double y = radius * Math.sin(theta); System.out.printf("Cartesian coordinates: (%5.3f, %5.3f)", x, y); } }
hoojaoh/git-for-beginners
src/components/ChapterProgress.js
<reponame>hoojaoh/git-for-beginners<filename>src/components/ChapterProgress.js import React from 'react'; import styled from 'styled-components'; import Title from './Title'; function ChapterProgress({ className, tutorial }) { return ( <div className={className}> <Title minor>{tutorial.currentChapterIndex + 1} / {tutorial.chapters.length}</Title> </div> ) } export default styled(ChapterProgress)` position: absolute; bottom: 50%; left: 0; transform: translateX(-50%) rotate(-90deg) translateY(${props => props.theme.spacing(-1)}); transform-origin: 50% 100%; `;
DeaLoic/bmstu-TaSD
lab_06/source/avl.h
<reponame>DeaLoic/bmstu-TaSD #ifndef __AVL_H__ #define __AVL_H__ #include "bst.h" int height(bst_node_t *p); int b_factor(bst_node_t *p); void fix_height(bst_node_t *p); void balance_full(bst_node_t *p); bst_node_t *rotate_right(bst_node_t *p); // правый поворот вокруг p bst_node_t *rotate_left(bst_node_t *q); // левый поворот вокруг q bst_node_t *balance(bst_node_t *p); // балансировка узла p bst_node_t *insert(bst_node_t *p, int data, int *cmp); // вставка ключа k в дерево с корнем p bst_node_t *find_min(bst_node_t *p); // поиск узла с минимальным ключом в дереве p bst_node_t *remove_min(bst_node_t *p); // удаление узла с минимальным ключом из дерева p bst_node_t *remove_avl(bst_node_t *p, int data); // удаление ключа k из дерева p void balance_bst_to_avl(bst_node_t *root, bst_t *avl); void fill_tree_avl(bst_t *tree, FILE *source); #endif
PraneshASP/Leetcode
src/main/java/com/fishercoder/solutions/_836.java
package com.fishercoder.solutions; public class _836 { public static class Solution1 { /** * credit: https://leetcode.com/problems/rectangle-overlap/discuss/132340/C%2B%2BJavaPython-1-line-Solution-1D-to-2D */ public boolean isRectangleOverlap(int[] rec1, int[] rec2) { return rec1[0] < rec2[2] && rec2[0] < rec1[2] && rec1[1] < rec2[3] && rec2[1] < rec1[3]; } } }
martheveldhuis/DivisionEngine
DivisionEngine/DivisionEngine/Logger.h
#ifndef DIVISION_LOGGER_H #define DIVISION_LOGGER_H #define logError(msg) error(msg, __FILE__, __LINE__) #define logWarning(msg) warning(msg, __FILE__, __LINE__) #define logInfo(msg) info(msg, __FILE__, __LINE__) #include <fstream> #include <string> namespace Division { /** File logger which can write log data to a file. */ class Logger { public: /** Create a logger by name, the name will be used to determine the file name to output to. The extension will be appended. @param name The clean filename to log to. ".log" will be appended */ Logger(std::string); ~Logger(); /** Log info with error level. @param msg The info message. @param file The file name the info originated from. @param line The line the log was called from. */ void error(const std::string& msg, const char *file, const int& line); /** Log info with warning level. @param msg The info message. @param file The file name the info originated from. @param line The line the log was called from. */ void warning(const std::string& msg, const char *file, const int& line); /** Log info with info level. @param msg The info message. @param file The file name the info originated from. @param line The line the log was called from. */ void info(const std::string& msg, const char *file, const int& line); /** Log info with info level. @param msg The info integer. @param file The file name the info originated from. @param line The line the log was called from. */ void info(const int msg, const char *file, const int& line); private: char drive_[_MAX_DRIVE]; char dir_[_MAX_DIR]; char fname_[_MAX_FNAME]; char ext_[_MAX_EXT]; std::ofstream logFile_; std::string filePath_; }; } #endif // !DIVISION_LOGGER_H
cmartinaf/open-gto
lib/WFObj/Reader.cpp
<filename>lib/WFObj/Reader.cpp // // Copyright (c) 2009, Tweak Software // 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 Tweak Software 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 Tweak Software ''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 Tweak Software 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. // #include "Reader.h" #include <fstream> extern void WFObjParse(std::istream&,WFObj::Reader*); namespace WFObj { using namespace std; Reader::Reader() {} Reader::~Reader() {} void Reader::finished() {} void Reader::v(float x,float y,float z) {} void Reader::v(float x,float y,float z,float w) { v(x,y,z); } void Reader::vt(float) {} void Reader::vt(float,float) {} void Reader::vt(float,float,float) {} void Reader::vn(float,float,float) {} void Reader::vp(float,float) {} void Reader::vp(float) {} void Reader::f(const Reader::VertexIndices&, const Reader::NormalIndices&, const Reader::TextureIndices&) {} void Reader::l(const Reader::VertexIndices&, const Reader::NormalIndices&, const Reader::TextureIndices&) {} void Reader::p(const Reader::VertexIndices&, const Reader::NormalIndices&, const Reader::TextureIndices&) {} void Reader::newGroup(const std::string&) {} void Reader::activeGroups(const Reader::Strings&) {} void Reader::smoothingGroup(Reader::Id) {} void Reader::activeObject(const std::string&) {} void Reader::usemtl(const std::string&) {} void Reader::usemap(const std::string&) {} void Reader::mtllib(const std::string&) {} void Reader::maplib(const std::string&) {} void Reader::shadow_obj(const std::string&) {} void Reader::trace_obj(const std::string&) {} void Reader::lod(int) {} void Reader::bevel(bool) {} void Reader::cinterp(bool) {} void Reader::dinterp(bool) {} void Reader::parse(istream &i) { WFObjParse(i,this); finished(); } bool Reader::parseFile(const char *filename) { ifstream file(filename); if (file) { parse(file); return true; } else { cerr << "Couldn't open the file " << filename << endl << flush; return false; } } } // WFObj
Corpus-2021/nakedobjects-4.0.0
core/runtime/src/main/java/org/nakedobjects/runtime/persistence/oidgenerator/timebased/TimeBasedOidGenerator.java
<reponame>Corpus-2021/nakedobjects-4.0.0 package org.nakedobjects.runtime.persistence.oidgenerator.timebased; import java.util.Date; import org.nakedobjects.metamodel.adapter.oid.Oid; import org.nakedobjects.runtime.persistence.oidgenerator.simple.SimpleOidGenerator; /** * Generates {@link Oid}s based on the system clock. * * <p> * The same algorithm and {@link Oid} implementation as * {@link SimpleOidGenerator} is used; it just seeds with a different value. */ public class TimeBasedOidGenerator extends SimpleOidGenerator { @Override public String name() { return "Time Initialised OID Generator"; } public TimeBasedOidGenerator() { super(new Date().getTime()); } } // Copyright (c) Naked Objects Group Ltd.
dominik-lueke/ttr-mannschafts-planer-2.0
src/editor/js/view/editor/spielklasseView.js
class SpielklasseView { constructor(spielklasseContainer, spielklasse, model) { this.model = model this.planung = model.planung this.spielklasse = spielklasse this.id = spielklasse.replace(" ","") this.html = $(` <div id="${this.id}" class="card card-spielklasse card-collapseable mb-4 p-0" spielklasse="${spielklasse}"> <div class="card-header collapsed link d-flex justify-content-between" data-toggle="collapse" data-target="#${this.id}-card-body" aria-expanded="false" aria-controls="#${this.id}-card-body"> <h5><small><i class="fa fa-caret-down ml-1"></i></small> ${spielklasse}</h5><small class="spielklasse-infos pl-4 mt-1 text-muted">Mannschaften (Spieler)</small> </div> <div id="${this.id}-card-body" class="card-body p-0 collapse" data-parent="#${this.id}"> <div id="${this.id}-mannschafts-container" class="container connected-sortable-mannschaft" spielklasse="${spielklasse}"> </div> <div id="${this.id}-add-mannschaft-button-container" class="container add-mannschaft-button-container"> <div class="row mannschafts-row"> <div class="${this.id}-empty-planung-message empty-planung-message text-center mannschaft mb-3 display-none"> <h6 class="mb-3">Es existieren noch keine Mannschaften oder Spieler</h6> <h6 class="mb-3">Lege manuell welche an</h6> </div> <div class="card mannschaft"> <button id="${this.id}-add-mannschaft-button" class="btn btn-light text-muted"> <i class="fa fa-plus"></i> Mannschaft hinzufügen </button> </div> <div class="${this.id}-empty-planung-message empty-planung-message text-center mannschaft mt-3 display-none"> <h6 class="mb-3">oder</h6> <h6 class="link text-success" id="${this.id}-lade-aufstellung-link" data-toggle="modal" data-target="#planung-reload-data-modal">lade eine Aufstellung von myTischtennis.de</h6> </div> </div> </div> </div> </div> `) spielklasseContainer.append(this.html) this.card_header = $(`#${this.id} .card-header`) this.card_body = $(`#${this.id}-card-body`) this.mannschaftsContainer = $(`#${this.id}-mannschafts-container`) this.add_mannschaft_button = $(`#${this.id}-add-mannschaft-button`) this.empty_planung_message = $(`.${this.id}-empty-planung-message`) this.lade_aufstellung_link = $(`#${this.id}-lade-aufstellung-link`) this.spielklasse_infos = this.card_header.find('.spielklasse-infos') this.mannschaftViews = [] this.add_mannschaft_handler = {} this.displayMannschaften(this.planung) } displayMannschaften(planung) { const mannschaften = planung.mannschaften.liste.filter(mannschaft => mannschaft.spielklasse == this.spielklasse) const spieler = planung.spieler.liste.filter(spieler => spieler.spielklasse == this.spielklasse) // Display empty message if (mannschaften.length === 0){ this.empty_planung_message.removeClass("display-none") } else { this.empty_planung_message.addClass("display-none") } // Delete all nodes execpt the "Mannschaft hinzufügen" button this.mannschaftViews.forEach( mannschaft => { mannschaft.delete() }) this.mannschaftViews = [] this.mannschaften = mannschaften // Create Mannschafts rows for each Mannschaft in state mannschaften.forEach(mannschaft => { const mannschaftsspieler = spieler.filter(spieler => spieler.mannschaft === mannschaft.nummer).sort((a,b) => { return a.position - b.position }) this.mannschaftViews.push( new MannschaftView(this.mannschaftsContainer, mannschaft, mannschaftsspieler, mannschaften.length, planung) ) }) // Fill spielklasse infos in header const spielklasse_infos = `${mannschaften.length} Mannschaften (${spieler.length} Spieler)`.replace('0', 'Keine').replace('(0 Spieler)', '') this.spielklasse_infos.text(spielklasse_infos) } delete(){ this.html.remove() } /* COLLAPSE */ expand(){ this.card_body.collapse('show') } bindSpielklasseExpanded(handler) { this.card_body.on('show.bs.collapse', (event) => { handler(this.model, this.id, true) }) this.card_body.on('hide.bs.collapse', (event) => { handler(this.model, this.id, false) } ) } /* LADE AUFSTELLUNG LINK */ bindClickOnLadeAufstellungLink(handler) { this.lade_aufstellung_link.click( (event) => { handler() } ) } /* MANNSCHAFT BINDINGS */ bindClickOnMannschaft(handler) { this.mannschaftViews.forEach(mannschaft => { mannschaft.bindClickOnMannschaft(handler)}) } bindAddMannschaft(handler) { if (this.add_mannschaft_handler != handler) { this.add_mannschaft_handler = handler this.add_mannschaft_button.click( (event) => { handler(this.spielklasse, this.mannschaften.length + 1)}) } } /* SPIELER BINDINGS */ bindAddSpieler(handler) { this.mannschaftViews.forEach(mannschaft => { mannschaft.bindAddSpieler(handler)}) } bindClickOnSpieler(handler) { this.mannschaftViews.forEach(mannschaft => { mannschaft.bindClickOnSpieler(handler)}) } bindToggleSpvOnSpieler(handler) { this.mannschaftViews.forEach(mannschaft => { mannschaft.bindToggleSpvOnSpieler(handler)}) } }
lemanhdung/learnstorybook
src/node_modules/@storybook/store/dist/modern/ArgsStore.js
import { combineArgs, mapArgsToTypes, validateOptions, deepDiff, DEEPLY_EQUAL } from './args'; function deleteUndefined(obj) { // eslint-disable-next-line no-param-reassign Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key]); return obj; } export class ArgsStore { constructor() { this.initialArgsByStoryId = {}; this.argsByStoryId = {}; } get(storyId) { if (!(storyId in this.argsByStoryId)) { throw new Error(`No args known for ${storyId} -- has it been rendered yet?`); } return this.argsByStoryId[storyId]; } setInitial(story) { if (!this.initialArgsByStoryId[story.id]) { this.initialArgsByStoryId[story.id] = story.initialArgs; this.argsByStoryId[story.id] = story.initialArgs; } else if (this.initialArgsByStoryId[story.id] !== story.initialArgs) { // When we get a new version of a story (with new initialArgs), we re-apply the same diff // that we had previously applied to the old version of the story const delta = deepDiff(this.initialArgsByStoryId[story.id], this.argsByStoryId[story.id]); this.initialArgsByStoryId[story.id] = story.initialArgs; this.argsByStoryId[story.id] = story.initialArgs; if (delta !== DEEPLY_EQUAL) { this.updateFromDelta(story, delta); } } } updateFromDelta(story, delta) { // Use the argType to ensure we setting a type with defined options to something outside of that const validatedDelta = validateOptions(delta, story.argTypes); // NOTE: we use `combineArgs` here rather than `combineParameters` because changes to arg // array values are persisted in the URL as sparse arrays, and we have to take that into // account when overriding the initialArgs (e.g. we patch [,'changed'] over ['initial', 'val']) this.argsByStoryId[story.id] = combineArgs(this.argsByStoryId[story.id], validatedDelta); } updateFromPersisted(story, persisted) { // Use the argType to ensure we aren't persisting the wrong type of value to the type. // For instance you could try and set a string-valued arg to a number by changing the URL const mappedPersisted = mapArgsToTypes(persisted, story.argTypes); return this.updateFromDelta(story, mappedPersisted); } update(storyId, argsUpdate) { if (!(storyId in this.argsByStoryId)) { throw new Error(`No args known for ${storyId} -- has it been rendered yet?`); } this.argsByStoryId[storyId] = deleteUndefined(Object.assign({}, this.argsByStoryId[storyId], argsUpdate)); } }
MrNinso/ProjetoUnivesp2021Frontend
app/src/main/java/com/developer/projetounivesp2021_frontrnd/adapters/holders/EstadoCidadeHolder.java
package com.developer.projetounivesp2021_frontrnd.adapters.holders; import android.view.View; import android.widget.TextView; import androidx.annotation.NonNull; import com.developer.projetounivesp2021_frontrnd.R; import com.developer.projetounivesp2021_frontrnd.adapters.BaseAdapter; import org.jetbrains.annotations.NotNull; public class EstadoCidadeHolder extends BaseAdapter.BaseHolder<String> { private final TextView mItemNome; public EstadoCidadeHolder(@NonNull @NotNull View itemView) { super(itemView); this.mItemNome = itemView.findViewById(R.id.list_tvw_string); } @Override protected void bindUnselectViewHolder(String s) { this.mItemNome.setText(s); this.mItemNome.setTextColor(mItemNome.getResources().getColor(android.R.color.black)); } @Override protected void bindSelectViewHolder(String s) { this.mItemNome.setText(s); this.mItemNome.setTextColor(mItemNome.getResources().getColor(android.R.color.white)); } }
HeavyMetalPirate/DiscordFantasyUnlimited
Core/src/main/java/com/fantasyunlimited/openapi/OpenApiConfiguration.java
package com.fantasyunlimited.openapi; import io.swagger.v3.oas.models.ExternalDocumentation; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; import org.springdoc.core.GroupedOpenApi; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class OpenApiConfiguration { @Bean public GroupedOpenApi contentListings() { return GroupedOpenApi.builder() .group("Content") .pathsToMatch("/api/content/**") .packagesToScan("com.fantasyunlimited.rest") .build(); } @Bean public GroupedOpenApi userOperations() { return GroupedOpenApi.builder() .group("User Operations") .pathsToMatch("/api/user/**") .packagesToScan("com.fantasyunlimited.rest") .build(); } @Bean public GroupedOpenApi gameOperations() { return GroupedOpenApi.builder() .group("Game Operations") .pathsToMatch("/api/game/**") .packagesToScan("com.fantasyunlimited.rest") .build(); } @Bean public OpenAPI springShopOpenAPI() { return new OpenAPI() .info(new Info().title("FantasyUnlimited API") .description("Fantasy Unlimited - REST API Description") .version("v0.0.1") .license(new License().name("Apache 2.0") .url("https://fantasyunlimited.com") ) ); } }
hyunjiLeeTech/BookEat
frontend/src/component/Profile/Manager/ManagerProfile.js
<reponame>hyunjiLeeTech/BookEat import React, {Component} from "react"; import MainContainer from "../../Style/MainContainer"; import Parser from "html-react-parser"; import $ from "jquery"; import ChangePassword from "../../Forms/Customer/ChangePassword"; import RestaurantReservation from "../../Reservation/Restaurant/RestaurantReservation"; import Menu from "../../Menu/Menu"; import ds from "../../../Services/dataService"; import FullscreenError from "../../Style/FullscreenError"; import ViewReview from "../../Review/Restaurant/ViewReview"; //Validation const regExpEmail = RegExp(/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]+$/); const regExpPhone = RegExp( /^\(?([0-9]{3})\)?[-.●]?([0-9]{3})[-.●]?([0-9]{4})$/, ); const formValid = ({isError, ...rest}) => { let isValid = false; Object.values(isError).forEach((val) => { if (val.length !== "&#160;") { isValid = false; } else { isValid = true; } }); Object.values(rest).forEach((val) => { if (val === null) { isValid = false; } else { isValid = true; } }); return isValid; }; class ManagerProfile extends Component { constructor(props) { super(props); this.state = { phonenumber: "", email: "", firstName: "", lastName: "", isError: { phonenumber: "&#160;", email: "&#160;", firstName: "&#160;", lastName: "&#160;", }, resultsErr: false, }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(e) { e.preventDefault(); const {name, value} = e.target; let isError = this.state.isError; switch (name) { case "email": isError.email = regExpEmail.test(value) ? "&#160;" : "Invalid email address"; break; case "phonenumber": isError.phonenumber = regExpPhone.test(value) ? "&#160;" : "Phone Number is invalid"; break; case "firstName": isError.firstName = value.length >= 2 && value.length <= 32 ? "&#160;" : "Atleast 2 character required"; break; case "lastName": isError.lastName = value.length >= 2 && value.length <= 32 ? "&#160;" : "Atleast 2 character required"; break; default: break; } this.setState({ [e.target.id]: e.target.value, }); } handleSubmit = (e) => { e.preventDefault(); if (formValid(this.state)) { ds.editManagerProfile(this.state); } else { console.log("Form is invalid!"); } try { $("#manProfileResultText") .text("Profiled is edited") .removeClass("alert-warning") .removeClass("alert-danger") .removeClass("alert-success") .addClass("alert-success"); } catch (err) { $("#manProfileResultText") .text("Sorry, " + err) .removeClass("alert-warning") .removeClass("alert-danger") .removeClass("alert-success") .addClass("alert-danger"); } }; async componentDidMount() { //for displaying customer profile const manager = await ds.getManagerInformation(); if (manager) { this.setState((state, props) => { return { firstName: typeof manager.firstname != "undefined" ? manager.firstname : "", lastName: typeof manager.lastname != "undefined" ? manager.lastname : "", phonenumber: typeof manager.phonenumber != "undefined" ? manager.phonenumber : "", email: typeof manager.accountId != "undefined" ? manager.accountId.email : "", }; }); } //Avoid spacing on the form var t2 = document.getElementById("email"); t2.onkeypress = function (e) { if (e.keyCode === 32) return false; }; var t6 = document.getElementById("phonenumber"); t6.onkeypress = function (e) { if (e.keyCode === 32) return false; }; var t1 = document.getElementById("firstName"); t1.onkeypress = function (e) { if (e.keyCode === 32) return false; }; //Disable Button $(document).ready(function () { //Form Disable if ($("#manForm :input").prop("disabled", true)) { $("#editButton").click(function () { $("#manForm :input").prop("disabled", false); //Disable Email $("#email").prop("disabled", true); }); } }); } // Edit profile disable button handleEdit() { this.setState({ disabled: !this.state.disabled, }); this.changeText(); } //Edit profile - button changeText() { this.setState( (state) => { return { edit: !state.edit, }; }, () => { if (this.state.edit) { $("#save_edit_btn") .attr("data-toggle", "modal") .attr("data-target", "#manProfileResultModal") .attr("type", "button"); } else { $("#save_edit_btn") .attr("data-toggle", "") .attr("data-target", "") .attr("type", ""); } }, ); } render() { const {isError} = this.state; return ( <MainContainer> {this.state.resultsErr ? FullscreenError("An error occured, please try again later") : null} <div className="card"> <div className="card-header"> <ul className="nav nav-tabs card-header-tabs"> <li className="nav-item"> <a className="nav-link active" data-toggle="tab" role="tab" href="#managerProfile" aria-controls="managerProfile" aria-selected="true" > My Profile </a> </li> <li className="nav-item"> <a className="nav-link" data-toggle="tab" role="tab" href="#menu" aria-controls="menu" aria-selected="false" > Menu </a> </li> <li className="nav-item"> <a className="nav-link" data-toggle="tab" role="tab" href="#reservation" aria-controls="reservation" aria-selected="false" > Reservation </a> </li> <li className="nav-item"> <a className="nav-link" data-toggle="tab" role="tab" href="#manReview" aria-controls="manReview" aria-selected="false" > Review </a> </li> <li className="nav-item"> <a className="nav-link" data-toggle="tab" role="tab" href="#changePassword" aria-controls="changePassword" aria-selected="false" > Password </a> </li> </ul> </div> <div className="card-body"> <div className="tab-content"> {/* Start Manager profile */} <div id="managerProfile" className="tab-pane fade show active" role="tabpanel" aria-labelledby="managerProfile" > <form onSubmit={this.handleSubmit} noValidate> <div id="manForm"> <div className="form-group row"> <label htmlFor="streetnumber" className="col-sm-2 col-form-label" > {" "} First Name </label> <div className="col-sm-4"> <input type="text" id="firstName" name="firstName" value={this.state.firstName} placeholder="<NAME>" className={ isError.firstName.length > 6 ? "is-invalid form-control" : "form-control" } onChange={this.handleChange} disabled={!this.state.disabled} required /> <span className="invalid-feedback"> {Parser(isError.firstName)} </span> </div> <label htmlFor="streetname" className="col-sm-2 col-form-label" > {" "} Last Name </label> <div className="col-sm-4"> <input type="text" id="lastName" name="lastName" value={this.state.lastName} placeholder="<NAME>" className={ isError.lastName.length > 6 ? "is-invalid form-control" : "form-control" } onChange={this.handleChange} disabled={!this.state.disabled} required /> <span className="invalid-feedback"> {Parser(isError.lastName)} </span> </div> </div> <div className="form-group row"> <label htmlFor="phonenumber" className="col-sm-2 col-form-label" > {" "} Phone Number </label> <div className="col-md-4"> <input type="text" id="phonenumber" name="phonenumber" value={this.state.phonenumber} placeholder="Phone Number" className={ isError.phonenumber.length > 6 ? "is-invalid form-control" : "form-control" } onChange={this.handleChange} disabled={!this.state.disabled} required /> <span className="invalid-feedback"> {Parser(isError.phonenumber)} </span> </div> </div> <div className="form-group row"> <label htmlFor="email" className="col-sm-2 col-form-label" > {" "} Email </label> <div className="col-md-10"> <input type="email" id="email" name="email" value={this.state.email} placeholder="Email" className={ isError.email.length > 6 ? "is-invalid form-control" : "form-control" } onChange={this.handleChange} disabled={true} required /> <span className="invalid-feedback"> {Parser(isError.email)} </span> </div> </div> </div> <div className="form-inline"> <div className="form-group text-center "> <button id="save_edit_btn" onClick={this.handleEdit.bind(this)} type="button" className="btn btn-primary mr-sm-4 " > {this.state.edit ? "Save Change" : "Edit"} </button> </div> </div> {/* Restaurant profile result Modal */} <div className="modal fade" id="manProfileResultModal" tabIndex="-1" role="dialog" aria-labelledby="manProfileResultModalLabel" aria-hidden="true" > <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <h5 className="modal-title" id="manProfileResultModalLabel" > Manager Profile </h5> <button type="button" className="close" data-dismiss="modal" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> <div className="modal-body"> <p className="alert alert-warning" id="manProfileResultText" > Please Wait... </p> </div> <div className="modal-footer"> <button type="button" className="btn btn-primary" data-dismiss="modal" > Close </button> </div> </div> </div> </div> </form> </div> {/* End Manager Profile */} {/* Start Password */} <div id="changePassword" className="tab-pane fade" role="tabpanel" aria-labelledby="changePassword" > <ChangePassword /> </div> {/* End Password */} {/* Start Reservation */} <div id="reservation" className="tab-pane fade" role="tabpanel" aria-labelledby="reservation" > <RestaurantReservation /> </div> {/* End Reservation */} {/* Start menu */} <div id="menu" className="tab-pane fade" role="tabpanel" aria-labelledby="menu" > <Menu /> </div> {/* End mENU */} {/* Start of Review*/} <div id="manReview" className="tab-pane fade" role="tabpanel" aria-labelledby="manReview" > <ViewReview /> </div> {/* End of Review Account */} </div> </div> </div> </MainContainer> ); } } export default ManagerProfile;
JulienBreux/triggy
internal/adapter/rabbitmq/rabbitmq.go
package rabbitmq import ( "errors" "fmt" "github.com/streadway/amqp" "github.com/julienbreux/triggy/internal/adapter" "github.com/julienbreux/triggy/internal/adapter/rabbitmq/parameter" "github.com/julienbreux/triggy/internal/provider/action" "github.com/julienbreux/triggy/internal/provider/trigger" ) const ( name = "rabbitmq" version = "0.0.1" ) type instance struct { configured bool param *parameter.Parameter conn *amqp.Connection channel *amqp.Channel } // New creates a new RabbitMQ adapter func New() adapter.Adapter { return &instance{} } // Name returns the adapter name func (a *instance) Name() string { return name } // Version returns the adapter version func (a *instance) Version() string { return version } // Configure configures the adapter func (a *instance) Configure(params map[string]interface{}) error { p, err := parameter.New(params) if err != nil { return err } a.param = p return nil } // Connect connects the adapter to server func (a *instance) Connect() error { if !a.configured { return errors.New("adapter: adapter not configured") } var err error a.conn, err = amqp.Dial(a.param.URL().String()) if err != nil { return fmt.Errorf("adapter: %s: %s", name, err) } // go func() { // fmt.Printf("closing: %s", <-a.conn.NotifyClose(make(chan *amqp.Error))) // }() a.channel, err = a.conn.Channel() if err != nil { return fmt.Errorf("adapter: %s: channel: %s", name, err) } return nil } // Disconnect disconnects the adapter from server func (a *instance) Disconnect() error { if a.conn != nil { return a.conn.Close() } return nil } // HealthCheck checks the health of the adapter func (a *instance) HealthCheck() error { return nil } // Actions func (a *instance) Actions() map[string]action.Action { return nil } // Trigger func (a *instance) Trigger() map[string]trigger.Trigger { return nil }